🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
feat(guidance): bind mod exports to Git blobs and explain review signals
rUv2207f8779a79
diff --git a/.github/workflows/mod-guidance.yml b/.github/workflows/mod-guidance.ymlnew file mode 100644index 0000000000..4133e79f41--- /dev/null+++ b/.github/workflows/mod-guidance.yml@@ -0,0 +1,53 @@+name: Native mod guidance source contracts++on:+ pull_request:+ paths:+ - 'plugins/ruflo-mods/**'+ - 'v3/@claude-flow/cli/src/commands/guidance.ts'+ - 'v3/@claude-flow/cli/src/guidance/mod-*.ts'+ - 'v3/@claude-flow/cli/__tests__/mods/**'+ - 'v3/@claude-flow/cli/vitest.config.ts'+ - 'v3/@claude-flow/cli/tsconfig.mod-guidance.json'+ - 'v3/@claude-flow/guidance/src/**'+ - 'v3/@claude-flow/security/src/safe-git.ts'+ - 'scripts/ci-test-ratchet.mjs'+ - '.github/workflows/mod-guidance.yml'+ - 'package-lock.json'+ push:+ branches: [main]+ paths:+ - 'plugins/ruflo-mods/**'+ - 'v3/@claude-flow/cli/src/guidance/mod-*.ts'+ - 'v3/@claude-flow/cli/src/commands/guidance.ts'+ - 'v3/@claude-flow/cli/__tests__/mods/**'+ - '.github/workflows/mod-guidance.yml'++permissions:+ contents: read++jobs:+ guidance-contracts:+ name: Guidance source, lifecycle and review contracts+ runs-on: ubuntu-latest+ timeout-minutes: 15+ steps:+ - uses: actions/checkout@v4+ with:+ persist-credentials: false+ - uses: actions/setup-node@v4+ with:+ node-version: '20'+ cache: npm+ - name: Install locked dependencies without lifecycle scripts+ run: npm ci --ignore-scripts --legacy-peer-deps+ - name: Check adapter types and static mod security+ run: |+ node_modules/.bin/tsc -p v3/@claude-flow/cli/tsconfig.mod-guidance.json+ bash plugins/ruflo-mods/scripts/smoke.sh+ - name: Run source mod contracts with the workspace compiler+ working-directory: v3/@claude-flow/cli+ run: ../../../node_modules/.bin/vitest run __tests__/mods/ --exclude '**/mods-cli-bin.test.ts'++# Claude Code native kit tests require the separately enabled host runtime.+# Built CLI tests still belong to the normal provisioned build gate.diff --git a/scripts/ci-test-ratchet.mjs b/scripts/ci-test-ratchet.mjsindex c2f8c7943c..9d229cb24c 100644--- a/scripts/ci-test-ratchet.mjs+++ b/scripts/ci-test-ratchet.mjs@@ -109,6 +109,12 @@ function main() {const run = spawnSync(process.execPath, [vitestBin,'run',+ // These files use Claude Code's native test kit, not Vitest. Their+ // enabled host gate is separate from the ordinary source runner.+ '--exclude=plugins/ruflo-mods/tests/*.test.ts',+ // ADR-447 needs the CLI workspace compiler/source aliases. The+ // mod-guidance workflow requires this suite with that configuration.+ '--exclude=v3/@claude-flow/cli/__tests__/mods/mods-guidance-e2e.test.ts','--reporter=json',`--outputFile=${reportPath}`,], {diff --git a/v3/@claude-flow/cli/__tests__/mods/harness.ts b/v3/@claude-flow/cli/__tests__/mods/harness.tsindex 406bb24f13..687b6c9e6b 100644--- a/v3/@claude-flow/cli/__tests__/mods/harness.ts+++ b/v3/@claude-flow/cli/__tests__/mods/harness.ts@@ -19,7 +19,7 @@* not run), budgets, streaming events, rendering.*/-import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';+import { existsSync, lstatSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';import { dirname } from 'node:path';type AnyHook = ($: any, e: any, next: any) => any;@@ -60,9 +60,8 @@ function engineOf(world: World) {if (!f) throw enoent(path);return { kind: 'file', size: Buffer.byteLength(f.text), mtimeMs: f.mtimeMs, isLink: false };}- if (!existsSync(path)) throw enoent(path);- const s = statSync(path);- return { kind: s.isFile() ? 'file' : s.isDirectory() ? 'dir' : 'other', size: s.size, mtimeMs: s.mtimeMs, isLink: false };+ const s = lstatSync(path);+ return { kind: s.isFile() ? 'file' : s.isDirectory() ? 'dir' : 'other', size: s.size, mtimeMs: s.mtimeMs, isLink: s.isSymbolicLink() };},async read(path: string) {const injected = world.failRead?.(path);diff --git a/v3/@claude-flow/cli/__tests__/mods/mods-guidance-e2e.test.ts b/v3/@claude-flow/cli/__tests__/mods/mods-guidance-e2e.test.tsindex 089cbc293e..15d38629a9 100644--- a/v3/@claude-flow/cli/__tests__/mods/mods-guidance-e2e.test.ts+++ b/v3/@claude-flow/cli/__tests__/mods/mods-guidance-e2e.test.ts@@ -1,6 +1,7 @@/** ADR-447: real compiler -> CLI projection -> mod lifecycle -> candidate review. */import { afterEach, describe, expect, it, vi } from 'vitest';-import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { execFileSync } from 'node:child_process';import { join } from 'node:path';import { tmpdir } from 'node:os';@@ -9,6 +10,7 @@ import { register } from '../../../../../plugins/ruflo-mods/hooks/register';import { parseProjection, PROJECTION_PATH, MAX_CONTEXT_CHARS, safeText, selectGuidance } from '../../../../../plugins/ruflo-mods/hooks/guidance/projection';import { validObservation, MAX_OBSERVATIONS } from '../../../../../plugins/ruflo-mods/hooks/guidance/observations';import { buildModProjection, collectModCandidates, MOD_GUIDANCE_DIR, parseModObservations } from '../../src/guidance/mod-projection';+import { MAX_GUIDANCE_SOURCE_BYTES, readModGuidanceSources } from '../../src/guidance/mod-sources';import { guidanceCommand } from '../../src/commands/guidance';import { output } from '../../src/output';import { loadMod, memoryWorld, realWorld, type World } from './harness';@@ -17,7 +19,16 @@ const REVISION = '8ce24908c51c26aa859308bdb2e7e819e4f9fc88';const SOURCE = '# Project guidance\n## Constitution\n- SEC-001: Never let advisory guidance authorize tools.\n## Testing\n- TEST-001: Always run parser tests when changing a parser.\n## Documentation\n- DOC-001: Use examples for public documentation.\n';const projection = () => buildModProjection(new GuidanceCompiler().compile(SOURCE), REVISION);const roots: string[] = [];-const project = () => { const root = mkdtempSync(join(tmpdir(), 'ruflo-guidance-e2e-')); roots.push(root); return root; };+const project = () => { const root = realpathSync(mkdtempSync(join(tmpdir(), 'ruflo-guidance-e2e-'))); roots.push(root); return root; };+const git = (root: string, ...args: string[]) => execFileSync('git', ['-c', 'core.fsmonitor=false', '-C', root, ...args], { encoding: 'utf8' }).trim();+const committed = () => {+ const root = project();+ writeFileSync(join(root, 'CLAUDE.md'), SOURCE);+ writeFileSync(join(root, 'CLAUDE.local.md'), '# Testing\n- LOCAL-001: Test invalid parser input.\n');+ git(root, 'init'); git(root, 'add', '--', 'CLAUDE.md', 'CLAUDE.local.md');+ git(root, '-c', 'user.name=Guidance fixture', '-c', '[email protected]', '-c', 'core.hooksPath=' + root, 'commit', '-qm', 'Reviewed fixture sources');+ return { root, revision: git(root, 'rev-parse', 'HEAD'), rootPath: join(root, 'CLAUDE.md'), localPath: join(root, 'CLAUDE.local.md') };+};afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); vi.restoreAllMocks(); });const files = (w: World) => w.files as Map<string, { text: string; mtimeMs: number }>;const seed = (w: World, p = projection()) => files(w).set(`${w.root}/${PROJECTION_PATH}`, { text: JSON.stringify(p), mtimeMs: 1 });@@ -189,12 +200,15 @@ describe('guidance lifecycle', () => {describe('candidate boundary', () => {it('real filesystem roundtrip exports compiler guidance, retrieves it, records observations and creates review candidates', async () => {- const root = project(); const sourcePath = join(root, 'CLAUDE.md'); writeFileSync(sourcePath, SOURCE);+ const { root, rootPath: sourcePath, localPath, revision } = committed();vi.spyOn(output, 'writeln').mockImplementation(() => undefined);const compile = guidanceCommand.subcommands!.find(c => c.name === 'compile')!;- const exported = await compile.action!({ flags: { root: sourcePath, 'mod-projection': true, revision: REVISION, output: join(root, MOD_GUIDANCE_DIR), json: true } } as never);+ const exported = await compile.action!({ flags: { root: sourcePath, local: localPath, 'mod-projection': true, revision, output: join(root, MOD_GUIDANCE_DIR), json: true } } as never);expect(exported.success).toBe(true);const p = (exported.data as { projection: ReturnType<typeof projection> }).projection;+ expect(p.sourceRevision).toBe(revision);+ expect(p.sourceDigests?.root).toMatch(/^[a-f0-9]{64}$/);+ expect(p.entries.some(e => e.id === 'LOCAL-001')).toBe(true);const mod = await start(realWorld(root));const submitted = await prompt(mod); expect(submitted.context.join('\n')).toContain(p.bundleId);await mod.dispatch('tool.check', { tool: 'Read', input: { file_path: sourcePath } }, () => ({ decision: 'deny', rule: 'host' }));@@ -205,7 +219,9 @@ describe('candidate boundary', () => {expect(reviewed.success).toBe(true);const report = reviewed.data as Awaited<ReturnType<typeof collectModCandidates>>;expect(report).toMatchObject({ observations: 1, status: 'pending-independent-verification', learningEligible: false });- expect(report.candidates.find(c => c.ruleId === 'TEST-001')).toMatchObject({ toolErrors: 1, deniedChecks: 1 });+ expect(report.summary).toMatchObject({ files: 1, withGuidance: 1, withoutGuidance: 0, completed: 1, checks: { deny: 1 }, tools: { error: 1 } });+ expect(report.candidates.find(c => c.ruleId === 'TEST-001')).toMatchObject({ toolErrors: 1, toolExecutions: 1, toolErrorRate: 1,+ deniedChecks: 1, permissionChecks: 1, deniedCheckRate: 1, reviewReasons: ['observed tool errors', 'denied checks'], verified: false, learningEligible: false });const empty = await collectModCandidates(join(root, MOD_GUIDANCE_DIR, 'observations'), 'f'.repeat(64));expect(empty).toMatchObject({ observations: 0, excluded: 1 });expect(readFileSync(sourcePath, 'utf8')).toBe(SOURCE);@@ -230,4 +246,113 @@ describe('candidate boundary', () => {expect(records(w)).toHaveLength(MAX_OBSERVATIONS);expect(records(w).every(r => r.verified === false)).toBe(true);});++ it('reports denominators, incomplete turns and unique global totals without causal claims', async () => {+ const root = project();+ const base = { version: 1, kind: 'guidance-observation', runId: 'mod-fixture-a-b', bundleId: 'a'.repeat(64), sourceRevision: REVISION,+ checks: { allow: 0, ask: 0, deny: 0 }, tools: { ok: 0, error: 0, denied: 0 }, completion: 'completed', verified: false, learningEligible: false };+ const rows = [+ { ...base, taskId: 1, ruleIds: ['TEST-001', 'SEC-001'], tools: { ok: 1, error: 1, denied: 0 }, checks: { allow: 3, ask: 0, deny: 1 } },+ { ...base, taskId: 2, ruleIds: ['TEST-002'], tools: { ok: 98, error: 2, denied: 0 } },+ { ...base, taskId: 3, ruleIds: ['TEST-003'], completion: 'interrupted' },+ { ...base, taskId: 4, ruleIds: ['TEST-003'], completion: 'aborted' },+ { ...base, taskId: 5, ruleIds: [] },+ ].map(r => ({ ...r, id: `${r.runId}:${r.taskId}` }));+ writeFileSync(join(root, `${base.runId}.json`), JSON.stringify(rows));+ const report = await collectModCandidates(root);+ expect(report.observations).toBe(5);+ expect(report.summary).toMatchObject({ withGuidance: 4, withoutGuidance: 1, completed: 3, aborted: 1, interrupted: 1, tools: { ok: 99, error: 3, denied: 0 } });+ expect(report.candidates.find(c => c.ruleId === 'TEST-001')).toMatchObject({ toolErrorRate: 0.5, deniedCheckRate: 0.25, affectedObservations: 1 });+ expect(report.candidates.find(c => c.ruleId === 'TEST-002')).toMatchObject({ toolErrorRate: 0.02, deniedCheckRate: null });+ expect(report.candidates.find(c => c.ruleId === 'TEST-003')).toMatchObject({ toolErrorRate: null, deniedCheckRate: null,+ affectedObservations: 2, aborted: 1, interrupted: 1, reviewReasons: ['aborted turns', 'interrupted turns'] });+ expect(report.candidates[0].ruleId).toBe('TEST-003');+ expect(report.interpretation).toContain('not proven causes');+ expect(report.candidates.every(c => c.verified === false && c.learningEligible === false)).toBe(true);+ expect(await collectModCandidates(root)).toEqual(report);+ });++ it('uses full version identity to order tied rule review groups deterministically', async () => {+ const w = memoryWorld(); seed(w); const mod = await start(w); await prompt(mod); await complete(mod);+ const base = records(w)[0]; const root = project();+ const rows = ['b', 'a'].map((hex, i) => ({ ...base, taskId: i + 1, id: `${base.runId}:${i + 1}`, bundleId: hex.repeat(64), ruleIds: ['TEST-001'] }));+ writeFileSync(join(root, `${base.runId}.json`), JSON.stringify(rows));+ const report = await collectModCandidates(root);+ expect(report.candidates.map(c => c.bundleId)).toEqual(['a'.repeat(64), 'b'.repeat(64)]);+ });++ it('refuses real symlinked projections and observation files', async () => {+ const root = project(); const outside = project();+ const target = join(outside, 'projection.json'); writeFileSync(target, JSON.stringify(projection()));+ mkdirSync(join(root, MOD_GUIDANCE_DIR), { recursive: true });+ symlinkSync(target, join(root, PROJECTION_PATH));+ const mod = await start(realWorld(root));+ expect((await prompt(mod)).context.join('\n')).not.toContain('advisory guidance DATA');+ await complete(mod); await end(mod);+ const path = join(outside, 'mod-fixture-a-b.json'); writeFileSync(path, '[]');+ symlinkSync(path, join(root, 'mod-fixture-a-b.json'));+ await expect(collectModCandidates(root)).rejects.toThrow(/Unsafe/);+ });+});++describe('immutable guidance source export', () => {+ it('verifies root and local raw bytes and ignores unrelated workspace changes', async () => {+ const fixture = committed();+ writeFileSync(join(fixture.root, 'unrelated.txt'), 'unrelated work');+ const checked = await readModGuidanceSources(fixture);+ expect(checked.rootContent).toBe(SOURCE);+ expect(checked.sources.root).toMatchObject({ path: 'CLAUDE.md', byteLength: Buffer.byteLength(SOURCE) });+ expect(checked.sources.local?.blobId).toBe(git(fixture.root, 'rev-parse', `${fixture.revision}:CLAUDE.local.md`));+ expect(checked.sources.root.sha256.slice(0, 16)).toBe(projection().sourceHashes.root);+ });++ for (const failure of ['dirty-root', 'dirty-local', 'missing-local', 'untracked-local', 'outside-local', 'fake-revision', 'blob-revision', 'short-revision', 'symlink-root', 'symlink-ancestor', 'oversized-local', 'byte-drift']) {+ it(`rejects ${failure} before replacing a valid projection`, async () => {+ const fixture = committed(); const dest = join(fixture.root, MOD_GUIDANCE_DIR);+ const compile = guidanceCommand.subcommands!.find(c => c.name === 'compile')!;+ vi.spyOn(output, 'writeln').mockImplementation(() => undefined);+ const flags = { root: fixture.rootPath, local: fixture.localPath, 'mod-projection': true, revision: fixture.revision, output: dest, json: true };+ expect((await compile.action!({ flags } as never)).success).toBe(true);+ const prior = readFileSync(join(dest, 'projection.json'));+ if (failure === 'dirty-root') writeFileSync(fixture.rootPath, SOURCE + '\n- TEST-002: Always test more.\n');+ if (failure === 'dirty-local') writeFileSync(fixture.localPath, '# Changed local guidance\n');+ if (failure === 'missing-local') flags.local = join(fixture.root, 'missing.md');+ if (failure === 'untracked-local') { flags.local = join(fixture.root, 'untracked.md'); writeFileSync(flags.local, SOURCE); }+ if (failure === 'outside-local') { flags.local = join(project(), 'outside.md'); writeFileSync(flags.local, SOURCE); }+ if (failure === 'fake-revision') flags.revision = 'f'.repeat(40);+ if (failure === 'blob-revision') flags.revision = git(fixture.root, 'rev-parse', `${fixture.revision}:CLAUDE.md`);+ if (failure === 'short-revision') flags.revision = fixture.revision.slice(0, 12);+ if (failure === 'symlink-root') { const path = join(fixture.root, 'alias.md'); symlinkSync(fixture.rootPath, path); flags.root = path; }+ if (failure === 'symlink-ancestor') { const path = join(project(), 'alias'); symlinkSync(fixture.root, path, 'dir'); flags.root = join(path, 'CLAUDE.md'); }+ if (failure === 'oversized-local') writeFileSync(fixture.localPath, 'x'.repeat(MAX_GUIDANCE_SOURCE_BYTES + 1));+ if (failure === 'byte-drift') writeFileSync(fixture.rootPath, SOURCE.replace(/\n/g, '\r\n'));+ expect((await compile.action!({ flags } as never)).success).toBe(false);+ expect(readFileSync(join(dest, 'projection.json'))).toEqual(prior);+ expect(readdirSync(dest)).toEqual(['projection.json']);+ });+ }++ it('ignores inherited Git repository/config overrides and disables replacement refs', async () => {+ const fixture = committed(); const other = committed();+ vi.stubEnv('GIT_DIR', join(other.root, '.git')); vi.stubEnv('GIT_WORK_TREE', other.root);+ vi.stubEnv('GIT_CONFIG_COUNT', '1'); vi.stubEnv('GIT_CONFIG_KEY_0', 'core.fsmonitor'); vi.stubEnv('GIT_CONFIG_VALUE_0', 'false');+ try { expect((await readModGuidanceSources(fixture)).sourceRevision).toBe(fixture.revision); }+ finally { vi.unstubAllEnvs(); }+ writeFileSync(fixture.rootPath, SOURCE + '\n- TEST-002: Always test replacements.\n');+ git(fixture.root, 'add', '--', 'CLAUDE.md');+ git(fixture.root, '-c', 'user.name=Guidance fixture', '-c', '[email protected]', '-c', 'core.hooksPath=' + fixture.root, 'commit', '-qm', 'Replacement source');+ git(fixture.root, 'replace', fixture.revision, git(fixture.root, 'rev-parse', 'HEAD'));+ await expect(readModGuidanceSources(fixture)).rejects.toThrow(/differ/);+ });++ it('treats option-like wildcard filenames literally and rejects invalid committed UTF-8', async () => {+ const fixture = committed(); const literal = join(fixture.root, '-policy[*].md');+ writeFileSync(literal, SOURCE); git(fixture.root, 'add', '--', '-policy[*].md');+ git(fixture.root, '-c', 'user.name=Guidance fixture', '-c', '[email protected]', '-c', 'core.hooksPath=' + fixture.root, 'commit', '-qm', 'Literal source path');+ const revision = git(fixture.root, 'rev-parse', 'HEAD');+ expect((await readModGuidanceSources({ rootPath: literal, revision })).sources.root.path).toBe('-policy[*].md');+ writeFileSync(fixture.rootPath, Buffer.from([0xc3, 0x28])); git(fixture.root, 'add', '--', 'CLAUDE.md');+ git(fixture.root, '-c', 'user.name=Guidance fixture', '-c', '[email protected]', '-c', 'core.hooksPath=' + fixture.root, 'commit', '-qm', 'Invalid UTF-8 source');+ await expect(readModGuidanceSources({ rootPath: fixture.rootPath, revision: git(fixture.root, 'rev-parse', 'HEAD') })).rejects.toThrow(/encoded data/);+ });});diff --git a/v3/@claude-flow/cli/src/commands/guidance.ts b/v3/@claude-flow/cli/src/commands/guidance.tsindex cc0f5456ce..dc96ff752c 100644--- a/v3/@claude-flow/cli/src/commands/guidance.ts+++ b/v3/@claude-flow/cli/src/commands/guidance.ts@@ -52,9 +52,14 @@ const compileCommand: Command = {return { success: false, message: `File not found: ${rootPath}` };}- const rootContent = await readFile(rootPath, 'utf-8');+ const modExport = ctx.flags['mod-projection'] === true;+ const checked = modExport ? await (await import('../guidance/mod-sources.js')).readModGuidanceSources({+ rootPath, localPath, revision: String(ctx.flags.revision || ''),+ }) : undefined;+ const rootContent = checked ? checked.rootContent : await readFile(rootPath, 'utf-8');let localContent: string | undefined;- if (localPath && existsSync(localPath)) {+ if (checked) localContent = checked.localContent;+ else if (localPath && existsSync(localPath)) {localContent = await readFile(localPath, 'utf-8');}@@ -62,12 +67,14 @@ const compileCommand: Command = {const compiler = new GuidanceCompiler();const bundle = compiler.compile(rootContent, localContent);- if (ctx.flags['mod-projection'] === true) {+ if (checked) {const { buildModProjection, writeModProjection, MOD_GUIDANCE_DIR } = await import('../guidance/mod-projection.js');- const projection = buildModProjection(bundle, String(ctx.flags.revision || ''));+ const sourceDigests = Object.fromEntries(Object.entries(checked.sources).map(([key, binding]) => [key, binding.sha256]));+ const projection = buildModProjection(bundle, checked.sourceRevision, sourceDigests);const path = await writeModProjection(String(ctx.flags.output || MOD_GUIDANCE_DIR), projection);- output.writeln(jsonOutput ? JSON.stringify({ path, projection }) : output.success(`Advisory mod projection exported: ${path}`));- return { success: true, data: { path, projection } };+ const data = { path, projection, sources: checked.sources };+ output.writeln(jsonOutput ? JSON.stringify(data) : output.success(`Git source matched; advisory mod projection exported: ${path}`));+ return { success: true, data };}if (jsonOutput) {diff --git a/v3/@claude-flow/cli/src/guidance/mod-projection.ts b/v3/@claude-flow/cli/src/guidance/mod-projection.tsindex a01b500395..72b7034bcc 100644--- a/v3/@claude-flow/cli/src/guidance/mod-projection.ts+++ b/v3/@claude-flow/cli/src/guidance/mod-projection.ts@@ -40,8 +40,8 @@ export interface ModObservation {}/** Stable digest of the exported rules; a provenance identifier, not a signature. */-export function buildModProjection(bundle: Bundle, sourceRevision: string) {- if (!/^[a-f0-9]{40,64}$/.test(sourceRevision)) throw new Error('--revision must be an immutable source commit SHA');+export function buildModProjection(bundle: Bundle, sourceRevision: string, sourceDigests?: Record<string, string>) {+ if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(sourceRevision)) throw new Error('--revision must be an immutable source commit SHA');const rules = [...bundle.constitution.rules, ...bundle.shards.map(s => s.rule)];if (rules.length > 256) throw new Error('Mod projection supports at most 256 rules; supply a reviewed scoped source');const ids = new Set<string>();@@ -55,7 +55,10 @@ export function buildModProjection(bundle: Bundle, sourceRevision: string) {if (!/^[a-f0-9]{16}$/.test(bundle.constitution.hash) || Object.entries(sourceHashes).some(([key, value]) => !['root', 'local'].includes(key) || !/^[a-f0-9]{16}$/.test(value))) {throw new Error('Unsupported compiler source hashes');}- const data = { version: 1 as const, sourceRevision, constitutionHash: bundle.constitution.hash, sourceHashes, entries };+ if (sourceDigests && (Object.keys(sourceDigests).length !== Object.keys(sourceHashes).length ||+ Object.entries(sourceDigests).some(([key, digest]) => !HEX.test(digest) || sourceHashes[key] !== digest.slice(0, 16)))) throw new Error('Source digests do not match compiler snapshots');+ const data = { version: 1 as const, sourceRevision, constitutionHash: bundle.constitution.hash, sourceHashes,+ ...(sourceDigests ? { sourceDigests: Object.fromEntries(Object.entries(sourceDigests).sort(([a], [b]) => a.localeCompare(b))) } : {}), entries };const bundleId = createHash('sha256').update(JSON.stringify(data)).digest('hex');const projection = { ...data, bundleId };if (Buffer.byteLength(JSON.stringify(projection)) > MAX_BYTES) throw new Error('Mod projection exceeds 256 KiB');@@ -104,9 +107,11 @@ export async function collectModCandidates(directory: string, bundleId?: string)catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') names = []; else throw error; }if (names.length > 128) throw new Error('At most 128 observation files may be reviewed per batch');const seen = new Set<string>();- const groups = new Map<string, { bundleId: string; sourceRevision: string; ruleId: string; observations: number; toolErrors: number; deniedChecks: number; aborted: number }>();+ const groups = new Map<string, { bundleId: string; sourceRevision: string; ruleId: string; observations: number; affectedObservations: number; toolErrors: number; toolExecutions: number; deniedTools: number; deniedChecks: number; permissionChecks: number; aborted: number; interrupted: number; completed: number }>();let observations = 0;let excluded = 0;+ const summary = { files: names.length, withGuidance: 0, withoutGuidance: 0, completed: 0, aborted: 0, interrupted: 0,+ checks: { allow: 0, ask: 0, deny: 0 }, tools: { ok: 0, error: 0, denied: 0 } };for (const name of names) {const path = join(directory, name);const stat = await lstat(path);@@ -117,20 +122,38 @@ export async function collectModCandidates(directory: string, bundleId?: string)seen.add(r.id);if (bundleId && r.bundleId !== bundleId) { excluded++; continue; }observations++;+ summary[r.ruleIds.length ? 'withGuidance' : 'withoutGuidance']++;+ summary[r.completion]++;+ for (const key of ['allow', 'ask', 'deny'] as const) summary.checks[key] += r.checks[key];+ for (const key of ['ok', 'error', 'denied'] as const) summary.tools[key] += r.tools[key];for (const ruleId of r.ruleIds) {const key = `${r.bundleId}:${r.sourceRevision}:${ruleId}`;- const group = groups.get(key) ?? { bundleId: r.bundleId, sourceRevision: r.sourceRevision, ruleId, observations: 0, toolErrors: 0, deniedChecks: 0, aborted: 0 };+ const group = groups.get(key) ?? { bundleId: r.bundleId, sourceRevision: r.sourceRevision, ruleId, observations: 0, affectedObservations: 0,+ toolErrors: 0, toolExecutions: 0, deniedTools: 0, deniedChecks: 0, permissionChecks: 0, aborted: 0, interrupted: 0, completed: 0 };group.observations++;+ group.affectedObservations += r.tools.error > 0 || r.tools.denied > 0 || r.checks.deny > 0 || r.completion !== 'completed' ? 1 : 0;group.toolErrors += r.tools.error;+ group.toolExecutions += r.tools.ok + r.tools.error;+ group.deniedTools += r.tools.denied;group.deniedChecks += r.checks.deny;- group.aborted += r.completion === 'aborted' ? 1 : 0;+ group.permissionChecks += r.checks.allow + r.checks.ask + r.checks.deny;+ group[r.completion]++;groups.set(key, group);}}}return {- version: 1, status: 'pending-independent-verification', learningEligible: false,- observations, excluded, candidates: [...groups.values()].sort((a, b) => b.toolErrors - a.toolErrors || a.ruleId.localeCompare(b.ruleId)),+ version: 1, status: 'pending-independent-verification', verified: false, learningEligible: false,+ observations, excluded, summary,+ candidates: [...groups.values()].sort((a, b) => b.affectedObservations - a.affectedObservations || b.toolErrors - a.toolErrors ||+ b.deniedChecks - a.deniedChecks || a.bundleId.localeCompare(b.bundleId) || a.sourceRevision.localeCompare(b.sourceRevision) || a.ruleId.localeCompare(b.ruleId))+ .map(group => ({ ...group, verified: false, learningEligible: false,+ toolErrorRate: group.toolExecutions ? group.toolErrors / group.toolExecutions : null,+ deniedCheckRate: group.permissionChecks ? group.deniedChecks / group.permissionChecks : null,+ reviewReasons: [group.toolErrors ? 'observed tool errors' : '', group.deniedTools ? 'denied tool calls' : '', group.deniedChecks ? 'denied checks' : '',+ group.aborted ? 'aborted turns' : '', group.interrupted ? 'interrupted turns' : ''].filter(Boolean),+ })),+ interpretation: 'Activity correlations only. Completed turns are not accepted successes; displayed rules are not proven causes.',requiredBeforeLearning: ['task-bound acceptance evidence', 'held-out baseline and candidate evaluation', 'authorized promotion'],};}diff --git a/v3/@claude-flow/cli/src/guidance/mod-sources.ts b/v3/@claude-flow/cli/src/guidance/mod-sources.tsnew file mode 100644index 0000000000..8d8611ea07--- /dev/null+++ b/v3/@claude-flow/cli/src/guidance/mod-sources.ts@@ -0,0 +1,92 @@+/** Explicit export only: bind the compiled snapshots to immutable Git blobs. */+import { execFile } from 'node:child_process';+import { constants } from 'node:fs';+import { lstat, open, realpath } from 'node:fs/promises';+import { devNull } from 'node:os';+import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';+import { createHash } from 'node:crypto';+import { promisify } from 'node:util';+import { safeGitArgv } from '@claude-flow/security/safe-git';++const run = promisify(execFile);+const OID = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/;+export const MAX_GUIDANCE_SOURCE_BYTES = 1024 * 1024;++export interface ModSourceBinding {+ path: string;+ blobId: string;+ sha256: string;+ byteLength: number;+}++/** Local reads only; no shell, Git hooks, filters, replacement refs or lazy fetch. */+async function git(repo: string, args: string[]): Promise<Buffer> {+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.toUpperCase().startsWith('GIT_')));+ Object.assign(env, { GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: devNull, GIT_NO_LAZY_FETCH: '1', GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0' });+ const { stdout } = await run('git', safeGitArgv(repo, ['--no-replace-objects', '--literal-pathspecs', '-c', `core.hooksPath=${devNull}`, ...args]), {+ encoding: 'buffer', env, maxBuffer: 2 * MAX_GUIDANCE_SOURCE_BYTES, timeout: 10_000, windowsHide: true,+ });+ return stdout;+}++async function sourcePath(path: string): Promise<string> {+ const absolute = resolve(path);+ if (/[\u0000-\u001f\u007f]/.test(absolute)) throw new Error('Unsupported guidance source path');+ const stat = await lstat(absolute);+ if (!stat.isFile() || stat.isSymbolicLink() || await realpath(absolute) !== absolute) throw new Error('Guidance source must be a regular file without symlink components');+ return absolute;+}++/** Descriptor based bounded read; never reread mutable bytes after verification. */+async function sourceBytes(path: string): Promise<Buffer> {+ const file = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));+ try {+ const stat = await file.stat();+ if (!stat.isFile() || stat.size > MAX_GUIDANCE_SOURCE_BYTES) throw new Error('Guidance source exceeds 1 MiB or is not a regular file');+ const bytes = Buffer.alloc(MAX_GUIDANCE_SOURCE_BYTES + 1);+ let size = 0;+ while (size < bytes.length) {+ const { bytesRead } = await file.read(bytes, size, bytes.length - size, null);+ if (!bytesRead) break;+ size += bytesRead;+ }+ if (size > MAX_GUIDANCE_SOURCE_BYTES) throw new Error('Guidance source exceeds 1 MiB');+ return bytes.subarray(0, size);+ } finally { await file.close(); }+}++/** A commit label alone is insufficient. Both supplied files must match its blobs. */+export async function readModGuidanceSources(input: { rootPath: string; localPath?: string; revision: string }) {+ if (!OID.test(input.revision)) throw new Error('--revision must be a full immutable source commit SHA');+ const rootPath = await sourcePath(input.rootPath);+ let repo: string;+ try {+ repo = (await git(dirname(rootPath), ['rev-parse', '--show-toplevel'])).toString('utf8').replace(/\r?\n$/, '');+ repo = await realpath(repo);+ if ((await git(repo, ['cat-file', '-t', input.revision])).toString('utf8').trim() !== 'commit') throw new Error('not a commit');+ } catch { throw new Error('Guidance source requires a local Git repository and an existing immutable commit'); }++ const read = async (path: string): Promise<{ content: string; binding: ModSourceBinding }> => {+ const absolute = await sourcePath(path);+ const rel = relative(repo, absolute);+ if (!rel || isAbsolute(rel) || rel === '..' || rel.startsWith(`..${sep}`)) throw new Error('Guidance sources must belong to the same Git repository');+ const sourceRepo = (await git(dirname(absolute), ['rev-parse', '--show-toplevel'])).toString('utf8').replace(/\r?\n$/, '');+ if (await realpath(sourceRepo) !== repo) throw new Error('Guidance sources must belong to the same Git repository');+ const gitPath = rel.split(sep).join('/');+ const tree = (await git(repo, ['ls-tree', '-z', '--full-tree', input.revision, '--', gitPath])).toString('utf8');+ const match = /^(100644|100755) blob ([a-f0-9]{40}|[a-f0-9]{64})\t([^\0]+)\0$/.exec(tree);+ if (!match || match[3] !== gitPath) throw new Error('Guidance source must be a regular tracked blob in the supplied commit');+ const blobId = match[2];+ const blobSize = Number((await git(repo, ['cat-file', '-s', blobId])).toString('utf8').trim());+ if (!Number.isSafeInteger(blobSize) || blobSize < 0 || blobSize > MAX_GUIDANCE_SOURCE_BYTES) throw new Error('Committed guidance source exceeds 1 MiB');+ const committed = await git(repo, ['cat-file', 'blob', blobId]);+ const bytes = await sourceBytes(absolute);+ if (!bytes.equals(committed)) throw new Error('Guidance source bytes differ from the supplied commit; commit the reviewed source before exporting');+ // Preserve a BOM in the compiler snapshot; reject invalid UTF-8 rather than replacing bytes.+ const content = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);+ return { content, binding: { path: gitPath, blobId, sha256: createHash('sha256').update(bytes).digest('hex'), byteLength: bytes.length } };+ };+ const root = await read(rootPath);+ const local = input.localPath === undefined ? undefined : await read(input.localPath);+ return { sourceRevision: input.revision, rootContent: root.content, localContent: local?.content, sources: { root: root.binding, ...(local ? { local: local.binding } : {}) } };+}diff --git a/v3/@claude-flow/cli/tsconfig.mod-guidance.json b/v3/@claude-flow/cli/tsconfig.mod-guidance.jsonnew file mode 100644index 0000000000..11b2d026de--- /dev/null+++ b/v3/@claude-flow/cli/tsconfig.mod-guidance.json@@ -0,0 +1,16 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "NodeNext",+ "moduleResolution": "NodeNext",+ "strict": true,+ "noEmit": true,+ "skipLibCheck": true,+ "types": ["node"],+ "baseUrl": ".",+ "paths": {+ "@claude-flow/security/safe-git": ["../security/src/safe-git.ts"]+ }+ },+ "include": ["src/guidance/mod-projection.ts", "src/guidance/mod-sources.ts"]+}