π 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(intelligence): deterministic Tier-1 codemods replacing Agent Booster (ADR-143)
ruv0988d92ce81b
diff --git a/CLAUDE.md b/CLAUDE.mdindex 6c219809b2..475079fbb5 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -70,16 +70,18 @@- MUST call MCP tools AND Task tool in ONE message for complex work- Always call MCP first, then IMMEDIATELY call Task tool to spawn agents-### 3-Tier Model Routing (ADR-026)+### 3-Tier Model Routing (ADR-026, ADR-143)| Tier | Handler | Latency | Cost | Use Cases ||------|---------|---------|------|-----------|-| **1** | Agent Booster (WASM) | <1ms | $0 | Simple transforms (varβconst, add types, etc.) β **Skip LLM entirely** |+| **1** | Deterministic codemod | ~1ms | $0 | Structural transforms with **no LLM**: `var-to-const`, `remove-console`, `add-logging` || **2** | Haiku | ~500ms | $0.0002 | Simple tasks, low complexity (<30%) || **3** | Sonnet/Opus | 2-5s | $0.003-0.015 | Complex reasoning, architecture, security (>30%) |-- Always check for `[AGENT_BOOSTER_AVAILABLE]` or `[TASK_MODEL_RECOMMENDATION]` before spawning agents-- Use Edit tool directly when `[AGENT_BOOSTER_AVAILABLE]` β intent types: `var-to-const`, `add-types`, `add-error-handling`, `async-await`, `add-logging`, `remove-console`+- Always check for `[CODEMOD_AVAILABLE]` or `[TASK_MODEL_RECOMMENDATION]` before spawning agents+- When you see `[CODEMOD_AVAILABLE]`, call the `hooks_codemod` MCP tool (intent + file) β it applies the transform deterministically via the TypeScript compiler at $0, no LLM. Deterministic intents only: `var-to-const`, `remove-console`, `add-logging`+- `add-types`, `add-error-handling`, `async-await` need judgement and route to a model (Tier 2/3) β they are **not** $0 codemods (see ADR-143)+- Agent Booster (`agent-booster`) is a fast-apply merge engine for arbitrary LLM-produced edit snippets, not an intent-transform engine β it is **not** the Tier-1 path## Swarm Configuration & Anti-Driftdiff --git a/docs/benchmarks/runs/codemod-2026-05-29T19-31-22-484Z.json b/docs/benchmarks/runs/codemod-2026-05-29T19-31-22-484Z.jsonnew file mode 100644index 0000000000..3605f1a3a3--- /dev/null+++ b/docs/benchmarks/runs/codemod-2026-05-29T19-31-22-484Z.json@@ -0,0 +1,120 @@+{+ "summary": {+ "runAt": "2026-05-29T19:31:22.484Z",+ "benchmark": "codemod-tier1",+ "corpusVersion": 1,+ "corpusSize": 12,+ "winRate": 1,+ "winRatePct": "100.0%",+ "successCount": 12,+ "avgLatencyMs": 0.5533,+ "p50LatencyMs": 0.296,+ "p99LatencyMs": 3.1452,+ "maxLatencyMs": 3.1452,+ "structuralCostUsd": 0,+ "llmBaseline": "estimated",+ "estimatedSavingsUsd": {+ "vsHaiku": 0.0024,+ "vsSonnet": 0.036,+ "vsOpus": 0.18+ }+ },+ "results": [+ {+ "id": "v2c-simple",+ "intent": "var-to-const",+ "correct": true,+ "changed": true,+ "edits": 2,+ "latencyMs": 3.1452+ },+ {+ "id": "v2c-reassigned",+ "intent": "var-to-const",+ "correct": true,+ "changed": true,+ "edits": 1,+ "latencyMs": 0.4904+ },+ {+ "id": "v2c-for-loop",+ "intent": "var-to-const",+ "correct": true,+ "changed": true,+ "edits": 1,+ "latencyMs": 0.6178+ },+ {+ "id": "v2c-destructure",+ "intent": "var-to-const",+ "correct": true,+ "changed": true,+ "edits": 1,+ "latencyMs": 0.296+ },+ {+ "id": "v2c-scope-aware",+ "intent": "var-to-const",+ "correct": true,+ "changed": true,+ "edits": 2,+ "latencyMs": 0.619+ },+ {+ "id": "v2c-comments-preserved",+ "intent": "var-to-const",+ "correct": true,+ "changed": true,+ "edits": 1,+ "latencyMs": 0.2776+ },+ {+ "id": "rmc-midblock",+ "intent": "remove-console",+ "correct": true,+ "changed": true,+ "edits": 1,+ "latencyMs": 0.2854+ },+ {+ "id": "rmc-multiple",+ "intent": "remove-console",+ "correct": true,+ "changed": true,+ "edits": 2,+ "latencyMs": 0.1528+ },+ {+ "id": "rmc-indented",+ "intent": "remove-console",+ "correct": true,+ "changed": true,+ "edits": 1,+ "latencyMs": 0.1218+ },+ {+ "id": "rmc-keep-logger",+ "intent": "remove-console",+ "correct": true,+ "changed": false,+ "edits": 0,+ "latencyMs": 0.0757+ },+ {+ "id": "log-named-fn",+ "intent": "add-logging",+ "correct": true,+ "changed": true,+ "edits": 1,+ "latencyMs": 0.1759+ },+ {+ "id": "log-arrow-var",+ "intent": "add-logging",+ "correct": true,+ "changed": true,+ "edits": 1,+ "latencyMs": 0.3822+ }+ ]+}\ No newline at end of filediff --git a/docs/benchmarks/runs/codemod-latest.json b/docs/benchmarks/runs/codemod-latest.jsonnew file mode 100644index 0000000000..3605f1a3a3--- /dev/null+++ b/docs/benchmarks/runs/codemod-latest.json@@ -0,0 +1,120 @@+{+ "summary": {+ "runAt": "2026-05-29T19:31:22.484Z",+ "benchmark": "codemod-tier1",+ "corpusVersion": 1,+ "corpusSize": 12,+ "winRate": 1,+ "winRatePct": "100.0%",+ "successCount": 12,+ "avgLatencyMs": 0.5533,+ "p50LatencyMs": 0.296,+ "p99LatencyMs": 3.1452,+ "maxLatencyMs": 3.1452,+ "structuralCostUsd": 0,+ "llmBaseline": "estimated",+ "estimatedSavingsUsd": {+ "vsHaiku": 0.0024,+ "vsSonnet": 0.036,+ "vsOpus": 0.18+ }+ },+ "results": [+ {+ "id": "v2c-simple",+ "intent": "var-to-const",+ "correct": true,+ "changed": true,+ "edits": 2,+ "latencyMs": 3.1452+ },+ {+ "id": "v2c-reassigned",+ "intent": "var-to-const",+ "correct": true,+ "changed": true,+ "edits": 1,+ "latencyMs": 0.4904+ },+ {+ "id": "v2c-for-loop",+ "intent": "var-to-const",+ "correct": true,+ "changed": true,+ "edits": 1,+ "latencyMs": 0.6178+ },+ {+ "id": "v2c-destructure",+ "intent": "var-to-const",+ "correct": true,+ "changed": true,+ "edits": 1,+ "latencyMs": 0.296+ },+ {+ "id": "v2c-scope-aware",+ "intent": "var-to-const",+ "correct": true,+ "changed": true,+ "edits": 2,+ "latencyMs": 0.619+ },+ {+ "id": "v2c-comments-preserved",+ "intent": "var-to-const",+ "correct": true,+ "changed": true,+ "edits": 1,+ "latencyMs": 0.2776+ },+ {+ "id": "rmc-midblock",+ "intent": "remove-console",+ "correct": true,+ "changed": true,+ "edits": 1,+ "latencyMs": 0.2854+ },+ {+ "id": "rmc-multiple",+ "intent": "remove-console",+ "correct": true,+ "changed": true,+ "edits": 2,+ "latencyMs": 0.1528+ },+ {+ "id": "rmc-indented",+ "intent": "remove-console",+ "correct": true,+ "changed": true,+ "edits": 1,+ "latencyMs": 0.1218+ },+ {+ "id": "rmc-keep-logger",+ "intent": "remove-console",+ "correct": true,+ "changed": false,+ "edits": 0,+ "latencyMs": 0.0757+ },+ {+ "id": "log-named-fn",+ "intent": "add-logging",+ "correct": true,+ "changed": true,+ "edits": 1,+ "latencyMs": 0.1759+ },+ {+ "id": "log-arrow-var",+ "intent": "add-logging",+ "correct": true,+ "changed": true,+ "edits": 1,+ "latencyMs": 0.3822+ }+ ]+}\ No newline at end of filediff --git a/v3/@claude-flow/cli/CLAUDE.md b/v3/@claude-flow/cli/CLAUDE.mdindex f617cc31a4..9011347d7c 100644--- a/v3/@claude-flow/cli/CLAUDE.md+++ b/v3/@claude-flow/cli/CLAUDE.md@@ -17,13 +17,13 @@**CLI coordinates, Task tool agents do the actual work!**-### π€ INTELLIGENT 3-TIER MODEL ROUTING (ADR-026)+### π€ INTELLIGENT 3-TIER MODEL ROUTING (ADR-026, ADR-143)**The routing system has 3 tiers for optimal cost/performance:**| Tier | Handler | Latency | Cost | Use Cases ||------|---------|---------|------|-----------|-| **1** | Agent Booster | <1ms | $0 | Simple transforms (varβconst, add-types, remove-console) |+| **1** | Deterministic codemod | ~1ms | $0 | Structural transforms, **no LLM**: varβconst, remove-console, add-logging || **2** | Haiku | ~500ms | $0.0002 | Simple tasks, bug fixes, low complexity || **3** | Sonnet/Opus | 2-5s | $0.003-$0.015 | Architecture, security, complex reasoning |@@ -34,8 +34,9 @@ npx @claude-flow/cli@latest hooks pre-task --description "[task description]"**When you see these recommendations:**-1. `[AGENT_BOOSTER_AVAILABLE]` β Skip LLM entirely, use Edit tool directly- - Intent types: `var-to-const`, `add-types`, `add-error-handling`, `async-await`, `add-logging`, `remove-console`+1. `[CODEMOD_AVAILABLE]` β call the `hooks_codemod` MCP tool (intent + file). It applies the transform deterministically via the TypeScript compiler at $0, no LLM.+ - Deterministic intents (Tier 1): `var-to-const`, `remove-console`, `add-logging`+ - `add-types`, `add-error-handling`, `async-await` need judgement β they route to a model (Tier 2/3), NOT a $0 codemod2. `[TASK_MODEL_RECOMMENDATION] Use model="X"` β Use that model in Task tool:```javascript@@ -46,7 +47,7 @@ Task({})```-**Benefits:** 75% cost reduction, 352x faster for Tier 1 tasks+**Benefits:** Tier-1 codemods are $0 and ~1ms (no model call); routing keeps simple edits off Sonnet/Opus.---diff --git a/v3/@claude-flow/cli/__tests__/codemod-corpus.test.ts b/v3/@claude-flow/cli/__tests__/codemod-corpus.test.tsnew file mode 100644index 0000000000..1153732f17--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/codemod-corpus.test.ts@@ -0,0 +1,23 @@+import { describe, it, expect } from 'vitest';+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, join } from 'node:path';+import { applyCodemod } from '../src/ruvector/codemods/engine.js';++const here = dirname(fileURLToPath(import.meta.url));+const corpus = JSON.parse(readFileSync(join(here, '..', 'bench', 'codemod-corpus.json'), 'utf-8'));++describe('codemod golden corpus (ADR-143 #4)', () => {+ it('has a non-empty versioned corpus', () => {+ expect(corpus.version).toBeGreaterThanOrEqual(1);+ expect(corpus.cases.length).toBeGreaterThan(0);+ });++ for (const c of corpus.cases) {+ it(`${c.id} (${c.intent}) matches golden output`, () => {+ const r = applyCodemod(c.intent, c.code, { language: c.language });+ expect(r.success).toBe(true);+ expect(r.output).toBe(c.expected);+ });+ }+});diff --git a/v3/@claude-flow/cli/__tests__/codemod-engine.test.ts b/v3/@claude-flow/cli/__tests__/codemod-engine.test.tsnew file mode 100644index 0000000000..3481ec8cc9--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/codemod-engine.test.ts@@ -0,0 +1,190 @@+import { describe, it, expect } from 'vitest';+import {+ applyCodemod,+ isDeterministicCodemod,+ DETERMINISTIC_CODEMOD_INTENTS,+ MODEL_ROUTED_INTENTS,+} from '../src/ruvector/codemods/engine.js';++describe('codemod engine β registry', () => {+ it('classifies deterministic vs model-routed intents', () => {+ expect(isDeterministicCodemod('var-to-const')).toBe(true);+ expect(isDeterministicCodemod('remove-console')).toBe(true);+ expect(isDeterministicCodemod('add-logging')).toBe(true);+ for (const i of MODEL_ROUTED_INTENTS) {+ expect(isDeterministicCodemod(i)).toBe(false);+ }+ });++ it('refuses non-deterministic intents with a reason', () => {+ const r = applyCodemod('add-types', 'const x = 1;', { language: 'typescript' });+ expect(r.success).toBe(false);+ expect(r.changed).toBe(false);+ expect(r.reason).toMatch(/not a deterministic codemod/i);+ });++ it('never throws on malformed input', () => {+ const r = applyCodemod('var-to-const', 'var x = = = ;;;{{{', { language: 'javascript' });+ expect(r).toBeDefined();+ // Either no-op or aborted; must not crash and must not worsen parse errors.+ expect(typeof r.output).toBe('string');+ });+});++describe('var-to-const', () => {+ it('uses const when never reassigned', () => {+ const r = applyCodemod('var-to-const', 'var x = 1;\nvar y = 2;', { language: 'javascript' });+ expect(r.success).toBe(true);+ expect(r.changed).toBe(true);+ expect(r.output).toBe('const x = 1;\nconst y = 2;');+ expect(r.edits).toBe(2);+ });++ it('uses let when reassigned via =', () => {+ const r = applyCodemod('var-to-const', 'var x = 1;\nx = 2;', { language: 'javascript' });+ expect(r.output).toBe('let x = 1;\nx = 2;');+ });++ it('uses let for a for-loop counter mutated with ++', () => {+ const src = 'for (var i = 0; i < 3; i++) {\n doThing(i);\n}';+ const r = applyCodemod('var-to-const', src, { language: 'javascript' });+ expect(r.output).toContain('for (let i = 0;');+ });++ it('preserves comments and indentation', () => {+ const src = '// counter\nfunction f() {\n var n = 0; // local\n return n;\n}';+ const r = applyCodemod('var-to-const', src, { language: 'javascript' });+ expect(r.output).toBe('// counter\nfunction f() {\n const n = 0; // local\n return n;\n}');+ });++ it('handles destructuring declarations', () => {+ const r = applyCodemod('var-to-const', 'var { a, b } = obj;', { language: 'javascript' });+ expect(r.output).toBe('const { a, b } = obj;');+ });++ it('is idempotent (second run is a no-op)', () => {+ const first = applyCodemod('var-to-const', 'var x = 1;', { language: 'javascript' });+ const second = applyCodemod('var-to-const', first.output, { language: 'javascript' });+ expect(second.changed).toBe(false);+ expect(second.output).toBe(first.output);+ });++ it('does not touch existing let/const', () => {+ const r = applyCodemod('var-to-const', 'const a = 1;\nlet b = 2;', { language: 'javascript' });+ expect(r.changed).toBe(false);+ });++ // Scope-aware analysis (ADR-143 #2): a reassignment in an unrelated scope+ // must not force an unrelated var to `let`.+ it('uses const when the only reassignment is in a different function', () => {+ const src = [+ 'function a() {',+ ' var x = 1;', // never reassigned in a()+ ' return x;',+ '}',+ 'function b() {',+ ' var x = 1;', // reassigned only here+ ' x = 2;',+ ' return x;',+ '}',+ ].join('\n');+ const r = applyCodemod('var-to-const', src, { language: 'javascript' });+ // a()'s x β const; b()'s x β let+ expect(r.output).toContain('function a() {\n const x = 1;');+ expect(r.output).toContain('function b() {\n let x = 1;');+ });++ it('uses let when an inner closure reassigns the outer var', () => {+ const src = [+ 'function outer() {',+ ' var x = 1;',+ ' function inner() { x = 2; }',+ ' inner();',+ ' return x;',+ '}',+ ].join('\n');+ const r = applyCodemod('var-to-const', src, { language: 'javascript' });+ expect(r.output).toContain(' let x = 1;');+ });++ it('shadowing inner var reassignment does not force outer var to let', () => {+ const src = [+ 'function outer() {',+ ' var x = 1;', // not reassigned in outer+ ' function inner() { var x = 9; x = 2; }', // own x reassigned+ ' return x;',+ '}',+ ].join('\n');+ const r = applyCodemod('var-to-const', src, { language: 'javascript' });+ expect(r.output).toContain(' const x = 1;'); // outer x stays const+ expect(r.output).toContain('var x = 9; x = 2;'.replace('var', 'let')); // inner x β let+ });+});++describe('remove-console', () => {+ it('removes an own-line console statement and its line', () => {+ const src = 'const a = 1;\nconsole.log(a);\nconst b = 2;';+ const r = applyCodemod('remove-console', src, { language: 'javascript' });+ expect(r.output).toBe('const a = 1;\nconst b = 2;');+ });++ it('removes console.error/warn/debug too', () => {+ const src = 'console.error("x");\nconsole.warn("y");\nfoo();';+ const r = applyCodemod('remove-console', src, { language: 'javascript' });+ expect(r.output).toBe('foo();');+ });++ it('preserves indentation of surrounding code', () => {+ const src = 'function f() {\n console.log("hi");\n return 1;\n}';+ const r = applyCodemod('remove-console', src, { language: 'javascript' });+ expect(r.output).toBe('function f() {\n return 1;\n}');+ });++ it('no-ops when there is no console call', () => {+ const r = applyCodemod('remove-console', 'const x = 1;', { language: 'javascript' });+ expect(r.changed).toBe(false);+ });++ it('does not remove non-console calls', () => {+ const src = 'logger.log("keep me");';+ const r = applyCodemod('remove-console', src, { language: 'javascript' });+ expect(r.changed).toBe(false);+ });+});++describe('add-logging', () => {+ it('inserts an entry log into a named function', () => {+ const src = 'function greet() {\n return 1;\n}';+ const r = applyCodemod('add-logging', src, { language: 'javascript' });+ expect(r.output).toBe("function greet() {\n console.log(\"greet called\");\n return 1;\n}");+ });++ it('names arrow functions from their variable', () => {+ const src = 'const add = (a, b) => {\n return a + b;\n};';+ const r = applyCodemod('add-logging', src, { language: 'javascript' });+ expect(r.output).toContain('console.log("add called");');+ });++ it('is idempotent (does not double-insert)', () => {+ const src = 'function f() {\n return 1;\n}';+ const first = applyCodemod('add-logging', src, { language: 'javascript' });+ const second = applyCodemod('add-logging', first.output, { language: 'javascript' });+ expect(second.changed).toBe(false);+ expect(second.output).toBe(first.output);+ });++ it('produces output that still parses', () => {+ const src = 'class C {\n method() {\n return 2;\n }\n}';+ const r = applyCodemod('add-logging', src, { language: 'typescript' });+ expect(r.success).toBe(true);+ expect(r.output).toContain('console.log("method called");');+ });+});++describe('exported constants', () => {+ it('exposes the deterministic intent list', () => {+ expect([...DETERMINISTIC_CODEMOD_INTENTS].sort()).toEqual(+ ['add-logging', 'remove-console', 'var-to-const'],+ );+ });+});diff --git a/v3/@claude-flow/cli/__tests__/codemod-routing.test.ts b/v3/@claude-flow/cli/__tests__/codemod-routing.test.tsnew file mode 100644index 0000000000..7c07ba07b9--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/codemod-routing.test.ts@@ -0,0 +1,44 @@+import { describe, it, expect, afterAll } from 'vitest';+import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { getEnhancedModelRouter } from '../src/ruvector/enhanced-model-router.js';++const dir = mkdtempSync(join(tmpdir(), 'codemod-routing-'));+afterAll(() => rmSync(dir, { recursive: true, force: true }));++const router = getEnhancedModelRouter();++describe('route-time dry-run (ADR-143 #3)', () => {+ it('keeps Tier-1 codemod when the file actually has work to do', async () => {+ const f = join(dir, 'has.js');+ writeFileSync(f, 'var a = 1;\nvar b = 2;\n');+ const r = await router.route('convert var to const', { filePath: f });+ expect(r.tier).toBe(1);+ expect(r.handler).toBe('codemod');+ expect(r.deterministic).toBe(true);+ expect(r.reasoning).toMatch(/\d+ edit/); // edit count from the dry-run+ });++ it('falls through to model routing when the codemod is a verified no-op', async () => {+ const f = join(dir, 'none.js');+ writeFileSync(f, 'const a = 1;\n'); // nothing to convert+ const r = await router.route('convert var to const', { filePath: f });+ expect(r.tier).not.toBe(1);+ expect(r.handler).not.toBe('codemod');+ });++ it('recommends best-effort Tier-1 when no file is available to dry-run', async () => {+ const r = await router.route('convert var to const');+ expect(r.tier).toBe(1);+ expect(r.handler).toBe('codemod');+ });++ it('never claims Tier-1 for a non-deterministic intent', async () => {+ const f = join(dir, 'typed.ts');+ writeFileSync(f, 'function f(a) { return a; }\n');+ const r = await router.route('add type annotations', { filePath: f });+ expect(r.tier).not.toBe(1);+ expect(r.handler).not.toBe('codemod');+ });+});diff --git a/v3/@claude-flow/cli/bench/codemod-corpus.json b/v3/@claude-flow/cli/bench/codemod-corpus.jsonnew file mode 100644index 0000000000..f1bbdb5c68--- /dev/null+++ b/v3/@claude-flow/cli/bench/codemod-corpus.json@@ -0,0 +1,90 @@+{+ "version": 1,+ "description": "Golden corpus for deterministic Tier-1 codemods (ADR-143). Each case: applyCodemod(intent, code) must equal expected exactly.",+ "cases": [+ {+ "id": "v2c-simple",+ "intent": "var-to-const",+ "language": "javascript",+ "code": "var x = 1;\nvar y = 2;",+ "expected": "const x = 1;\nconst y = 2;"+ },+ {+ "id": "v2c-reassigned",+ "intent": "var-to-const",+ "language": "javascript",+ "code": "var x = 1;\nx = 2;",+ "expected": "let x = 1;\nx = 2;"+ },+ {+ "id": "v2c-for-loop",+ "intent": "var-to-const",+ "language": "javascript",+ "code": "for (var i = 0; i < 3; i++) {\n f(i);\n}",+ "expected": "for (let i = 0; i < 3; i++) {\n f(i);\n}"+ },+ {+ "id": "v2c-destructure",+ "intent": "var-to-const",+ "language": "javascript",+ "code": "var { a, b } = obj;",+ "expected": "const { a, b } = obj;"+ },+ {+ "id": "v2c-scope-aware",+ "intent": "var-to-const",+ "language": "javascript",+ "code": "function a() {\n var x = 1;\n return x;\n}\nfunction b() {\n var x = 1;\n x = 2;\n return x;\n}",+ "expected": "function a() {\n const x = 1;\n return x;\n}\nfunction b() {\n let x = 1;\n x = 2;\n return x;\n}"+ },+ {+ "id": "v2c-comments-preserved",+ "intent": "var-to-const",+ "language": "javascript",+ "code": "// counter\nvar n = 0; // local",+ "expected": "// counter\nconst n = 0; // local"+ },+ {+ "id": "rmc-midblock",+ "intent": "remove-console",+ "language": "javascript",+ "code": "const a = 1;\nconsole.log(a);\nconst b = 2;",+ "expected": "const a = 1;\nconst b = 2;"+ },+ {+ "id": "rmc-multiple",+ "intent": "remove-console",+ "language": "javascript",+ "code": "console.error(\"x\");\nconsole.warn(\"y\");\nfoo();",+ "expected": "foo();"+ },+ {+ "id": "rmc-indented",+ "intent": "remove-console",+ "language": "javascript",+ "code": "function f() {\n console.log(\"hi\");\n return 1;\n}",+ "expected": "function f() {\n return 1;\n}"+ },+ {+ "id": "rmc-keep-logger",+ "intent": "remove-console",+ "language": "javascript",+ "code": "logger.log(\"keep\");\nbar();",+ "expected": "logger.log(\"keep\");\nbar();"+ },+ {+ "id": "log-named-fn",+ "intent": "add-logging",+ "language": "javascript",+ "code": "function greet() {\n return 1;\n}",+ "expected": "function greet() {\n console.log(\"greet called\");\n return 1;\n}"+ },+ {+ "id": "log-arrow-var",+ "intent": "add-logging",+ "language": "javascript",+ "code": "const add = (a, b) => {\n return a + b;\n};",+ "expected": "const add = (a, b) => {\n console.log(\"add called\");\n return a + b;\n};"+ }+ ]+}diff --git a/v3/@claude-flow/cli/scripts/benchmark-codemods.mjs b/v3/@claude-flow/cli/scripts/benchmark-codemods.mjsnew file mode 100644index 0000000000..a9be0e1a35--- /dev/null+++ b/v3/@claude-flow/cli/scripts/benchmark-codemods.mjs@@ -0,0 +1,125 @@+#!/usr/bin/env node+// benchmark-codemods.mjs β measured benchmark for deterministic Tier-1 codemods (ADR-143).+//+// Runs every case in bench/codemod-corpus.json through applyCodemod() and records:+// - correctness vs the golden `expected` output+// - latency (avg / p50 / p99 / max)+// - cost: $0 measured (no API call) + estimated savings vs an LLM edit+//+// Writes a run JSON in the cost-trend summary schema to+// <repo>/docs/benchmarks/runs/codemod-<timestamp>.json (+ codemod-latest.json)+// so the cost-tracker's trend tooling can ingest it.+//+// Usage:+// node scripts/benchmark-codemods.mjs # build dist first (npm run build)+// BENCH_JSON=1 node scripts/benchmark-codemods.mjs # machine-readable JSON to stdout+// BENCH_NO_WRITE=1 node scripts/benchmark-codemods.mjs # don't write a run file++import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, join, resolve } from 'node:path';+import { performance } from 'node:perf_hooks';++const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));+const CLI_ROOT = resolve(SCRIPT_DIR, '..');+const REPO_ROOT = resolve(SCRIPT_DIR, '../../../..');+const RUNS_DIR = join(REPO_ROOT, 'docs', 'benchmarks', 'runs');++// Estimated per-edit LLM cost (USD). Documented estimates, NOT a live call β+// used only to express the savings of a $0 deterministic codemod.+const LLM_EDIT_COST = { haiku: 0.0002, sonnet: 0.003, opus: 0.015 };++function percentile(sorted, p) {+ if (sorted.length === 0) return 0;+ const idx = Math.min(sorted.length - 1, Math.floor((p / 100) * sorted.length));+ return sorted[idx];+}++async function main() {+ const { applyCodemod } = await import('../dist/src/ruvector/codemods/engine.js');+ const corpus = JSON.parse(readFileSync(join(CLI_ROOT, 'bench', 'codemod-corpus.json'), 'utf-8'));+ const cases = corpus.cases;++ const results = [];+ const latencies = [];+ let correct = 0;++ for (const c of cases) {+ const t0 = performance.now();+ const r = applyCodemod(c.intent, c.code, { language: c.language });+ const latencyMs = performance.now() - t0;+ latencies.push(latencyMs);+ const ok = r.success && r.output === c.expected;+ if (ok) correct++;+ results.push({+ id: c.id, intent: c.intent, correct: ok, changed: r.changed,+ edits: r.edits, latencyMs: Number(latencyMs.toFixed(4)),+ ...(ok ? {} : { gotPrefix: (r.output ?? '').slice(0, 80), reason: r.reason }),+ });+ }++ const sorted = [...latencies].sort((a, b) => a - b);+ const avg = latencies.reduce((s, x) => s + x, 0) / latencies.length;+ const winRate = correct / cases.length;+ const estSavings = {+ vsHaiku: Number((LLM_EDIT_COST.haiku * cases.length).toFixed(6)),+ vsSonnet: Number((LLM_EDIT_COST.sonnet * cases.length).toFixed(6)),+ vsOpus: Number((LLM_EDIT_COST.opus * cases.length).toFixed(6)),+ };++ const summary = {+ runAt: new Date().toISOString(),+ benchmark: 'codemod-tier1',+ corpusVersion: corpus.version,+ corpusSize: cases.length,+ winRate,+ winRatePct: `${(winRate * 100).toFixed(1)}%`,+ successCount: correct,+ avgLatencyMs: Number(avg.toFixed(4)),+ p50LatencyMs: Number(percentile(sorted, 50).toFixed(4)),+ p99LatencyMs: Number(percentile(sorted, 99).toFixed(4)),+ maxLatencyMs: Number(Math.max(...latencies).toFixed(4)),+ structuralCostUsd: 0,+ llmBaseline: 'estimated',+ estimatedSavingsUsd: estSavings,+ };++ const run = { summary, results };++ if (process.env.BENCH_JSON) {+ console.log(JSON.stringify(run, null, 2));+ } else {+ console.log(`# Codemod Tier-1 benchmark (${cases.length} cases, corpus v${corpus.version})`);+ console.log('');+ console.log('| Metric | Value |');+ console.log('|---|---:|');+ console.log(`| Win rate (correct vs golden) | ${summary.winRatePct} (${correct}/${cases.length}) |`);+ console.log(`| Avg latency | ${summary.avgLatencyMs} ms |`);+ console.log(`| p50 / p99 / max latency | ${summary.p50LatencyMs} / ${summary.p99LatencyMs} / ${summary.maxLatencyMs} ms |`);+ console.log(`| Measured cost | $0 (no API call) |`);+ console.log(`| Est. savings vs Haiku/Sonnet/Opus | $${estSavings.vsHaiku} / $${estSavings.vsSonnet} / $${estSavings.vsOpus} |`);+ console.log('');+ const failed = results.filter((r) => !r.correct);+ if (failed.length) {+ console.log('## Failures');+ for (const f of failed) console.log(`- \`${f.id}\` (${f.intent}): ${f.reason ?? `got "${f.gotPrefix}"`}`);+ console.log('');+ }+ }++ if (!process.env.BENCH_NO_WRITE) {+ mkdirSync(RUNS_DIR, { recursive: true });+ const stamp = summary.runAt.replace(/[:.]/g, '-');+ writeFileSync(join(RUNS_DIR, `codemod-${stamp}.json`), JSON.stringify(run, null, 2));+ writeFileSync(join(RUNS_DIR, 'codemod-latest.json'), JSON.stringify(run, null, 2));+ if (!process.env.BENCH_JSON) console.log(`Wrote run to ${join(RUNS_DIR, `codemod-${stamp}.json`)}`);+ }++ // Non-zero exit if any case regressed β usable as a CI guardrail.+ if (correct !== cases.length) process.exit(1);+}++main().catch((err) => {+ console.error('benchmark failed:', err);+ process.exit(1);+});diff --git a/v3/@claude-flow/cli/src/commands/hooks.ts b/v3/@claude-flow/cli/src/commands/hooks.tsindex 68eb39db31..dc34951538 100644--- a/v3/@claude-flow/cli/src/commands/hooks.ts+++ b/v3/@claude-flow/cli/src/commands/hooks.ts@@ -1831,24 +1831,25 @@ const preTaskCommand: Command = {output.printList(result.recommendations);}- // Enhanced model routing with Agent Booster AST (ADR-026)+ // Enhanced model routing with deterministic codemod Tier-1 (ADR-026, ADR-143)try {const { getEnhancedModelRouter } = await import('../ruvector/enhanced-model-router.js');const router = getEnhancedModelRouter();const routeResult = await router.route(description, { filePath: ctx.flags.file as string });+ const intent = routeResult.codemodIntent ?? routeResult.agentBoosterIntent;output.writeln();output.writeln(output.bold('Intelligent Model Routing'));if (routeResult.tier === 1) {- // Agent Booster can handle this task - skip LLM entirely- output.writeln(output.success(` Tier 1: Agent Booster (WASM)`));- output.writeln(output.dim(` Intent: ${routeResult.agentBoosterIntent?.type}`));- output.writeln(output.dim(` Latency: <1ms | Cost: $0`));+ // Deterministic codemod can apply this edit - skip LLM entirely ($0)+ output.writeln(output.success(` Tier 1: Deterministic codemod`));+ output.writeln(output.dim(` Intent: ${intent?.type}`));+ output.writeln(output.dim(` Latency: ~1ms | Cost: $0 | No LLM`));output.writeln();output.writeln(output.dim('β'.repeat(60)));- output.writeln(output.bold(output.success(`[AGENT_BOOSTER_AVAILABLE] Skip LLM - use Agent Booster for "${routeResult.agentBoosterIntent?.type}"`)));- output.writeln(output.dim(`Confidence: ${(routeResult.confidence * 100).toFixed(0)}% | Intent: ${routeResult.agentBoosterIntent?.description}`));+ output.writeln(output.bold(output.success(`[CODEMOD_AVAILABLE] Skip LLM β call hooks_codemod with intent="${intent?.type}" (deterministic, $0)`)));+ output.writeln(output.dim(`Confidence: ${(routeResult.confidence * 100).toFixed(0)}% | Intent: ${intent?.description}`));output.writeln(output.dim('β'.repeat(60)));} else {// LLM required - show tier and model recommendation@@ -1875,7 +1876,8 @@ const preTaskCommand: Command = {complexity: routeResult.complexity,reasoning: routeResult.reasoning,canSkipLLM: routeResult.canSkipLLM,- agentBoosterIntent: routeResult.agentBoosterIntent+ deterministic: routeResult.deterministic,+ codemodIntent: routeResult.codemodIntent ?? routeResult.agentBoosterIntent,};} catch {// Enhanced router not available, skip recommendationdiff --git a/v3/@claude-flow/cli/src/mcp-tools/agent-execute-core.ts b/v3/@claude-flow/cli/src/mcp-tools/agent-execute-core.tsindex 1ef57d6e3d..d22c56df6f 100644--- a/v3/@claude-flow/cli/src/mcp-tools/agent-execute-core.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/agent-execute-core.ts@@ -28,7 +28,7 @@ export interface AgentRecord {createdAt: string;domain?: string;model?: ClaudeModel;- modelRoutedBy?: 'explicit' | 'router' | 'agent-booster' | 'default';+ modelRoutedBy?: 'explicit' | 'router' | 'codemod' | 'default';lastResult?: Record<string, unknown>;}diff --git a/v3/@claude-flow/cli/src/mcp-tools/agent-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/agent-tools.tsindex fc48564960..5239d6d6a8 100644--- a/v3/@claude-flow/cli/src/mcp-tools/agent-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/agent-tools.ts@@ -34,7 +34,7 @@ interface AgentRecord {createdAt: string;domain?: string;model?: ClaudeModel; // Model assigned to this agent- modelRoutedBy?: 'explicit' | 'router' | 'agent-booster' | 'default'; // How model was determined (ADR-026)+ modelRoutedBy?: 'explicit' | 'router' | 'codemod' | 'default'; // How model was determined (ADR-026, ADR-143)lastResult?: Record<string, unknown>; // Output from last completed task}@@ -143,7 +143,7 @@ async function getModelRouter() {/*** Determine model for agent based on (ADR-026 3-tier routing):* 1. Explicit model in config- * 2. Enhanced task-based routing with Agent Booster AST (if task provided)+ * 2. Enhanced task-based routing with deterministic Tier-1 codemods (if task provided)* 3. Agent type defaults* 4. Fallback to sonnet*/@@ -153,9 +153,9 @@ async function determineAgentModel(task?: string): Promise<{model: ClaudeModel;- routedBy: 'explicit' | 'router' | 'agent-booster' | 'default';+ routedBy: 'explicit' | 'router' | 'codemod' | 'default';canSkipLLM?: boolean;- agentBoosterIntent?: string;+ codemodIntent?: string;tier?: 1 | 2 | 3;}> {// 1. Explicit model in config@@ -163,21 +163,21 @@ async function determineAgentModel(return { model: config.model as ClaudeModel, routedBy: 'explicit' };}- // 2. Enhanced task-based routing with Agent Booster AST+ // 2. Enhanced task-based routing with deterministic Tier-1 codemodsif (task) {try {- // Try enhanced router first (includes Agent Booster detection)+ // Try enhanced router first (includes codemod-intent detection)const { getEnhancedModelRouter } = await import('../ruvector/enhanced-model-router.js');const enhancedRouter = getEnhancedModelRouter();const routeResult = await enhancedRouter.route(task, { filePath: config.filePath as string });if (routeResult.tier === 1 && routeResult.canSkipLLM) {- // Agent Booster can handle this task+ // Deterministic codemod can apply this edit ($0, no LLM)return {- model: 'haiku', // Use haiku as fallback if AB fails- routedBy: 'agent-booster',+ model: 'haiku', // fallback model if the codemod can't apply+ routedBy: 'codemod',canSkipLLM: true,- agentBoosterIntent: routeResult.agentBoosterIntent?.type,+ codemodIntent: (routeResult.codemodIntent ?? routeResult.agentBoosterIntent)?.type,tier: 1,};}@@ -314,7 +314,7 @@ export const agentTools: MCPTool[] = [await addNode({ id: agentId, type: 'agent', name: agentType });} catch { /* graph-node not available */ }- // Include Agent Booster routing info if applicable+ // Include deterministic codemod routing info if applicableconst response: Record<string, unknown> = {success: true,agentId,@@ -329,12 +329,12 @@ export const agentTools: MCPTool[] = ['(3) claude -p β headless background instance.',};- // Add Agent Booster info if task can skip LLM+ // Add codemod info if task can skip LLM (deterministic Tier-1, ADR-143)if (routingResult.canSkipLLM) {response.canSkipLLM = true;- response.agentBoosterIntent = routingResult.agentBoosterIntent;+ response.codemodIntent = routingResult.codemodIntent;response.tier = routingResult.tier;- response.note = `Agent Booster can handle "${routingResult.agentBoosterIntent}" - use agent_booster_edit_file MCP tool`;+ response.note = `Deterministic codemod can apply "${routingResult.codemodIntent}" β call the hooks_codemod MCP tool (intent="${routingResult.codemodIntent}"), $0, no LLM`;} else if (routingResult.tier) {response.tier = routingResult.tier;}diff --git a/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.tsindex 7db8ca53bf..fa4cc22bf7 100644--- a/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts@@ -4,6 +4,7 @@*/import { mkdirSync, writeFileSync, existsSync, readFileSync, statSync, unlinkSync, readdirSync, rmSync } from 'fs';+import * as nodeFs from 'fs';import { dirname, join, resolve } from 'path';import { type MCPTool, getProjectCwd } from './types.js';import { validateIdentifier, validateText, validatePath } from './validate-input.js';@@ -917,7 +918,7 @@ export const hooksPostCommand: MCPTool = {export const hooksRoute: MCPTool = {name: 'hooks_route',- description: 'Get a 3-tier routing recommendation for a task: Tier 1 (Agent Booster, 0ms / $0 β for var-to-const, add-types, etc.), Tier 2 (Haiku β simple), Tier 3 (Sonnet/Opus β complex). Use this BEFORE spawning an agent to avoid sending simple transforms to Sonnet. Native tools have no equivalent β Claude Code does not introspect its own model-selection cost. Returns the recommended model + a `[AGENT_BOOSTER_AVAILABLE]` literal when the WASM bypass applies. Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state β pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',+ description: 'Get a 3-tier routing recommendation for a task: Tier 1 (deterministic codemod, ~0ms / $0 β for var-to-const, remove-console, add-logging), Tier 2 (Haiku β simple), Tier 3 (Sonnet/Opus β complex). Use this BEFORE spawning an agent to avoid sending simple transforms to Sonnet. Native tools have no equivalent β Claude Code does not introspect its own model-selection cost. Returns the recommended model + a `[CODEMOD_AVAILABLE]` literal when a deterministic codemod can fully apply the edit (then call hooks_codemod). Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state β pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',inputSchema: {type: 'object',properties: {@@ -1242,7 +1243,7 @@ export const hooksPreTask: MCPTool = {? 'low': 'medium';- // Enhanced model routing with Agent Booster AST (ADR-026)+ // Enhanced model routing with deterministic Tier-1 codemods (ADR-026, ADR-143)let modelRouting: Record<string, unknown> | undefined;try {const { getEnhancedModelRouter } = await import('../ruvector/enhanced-model-router.js');@@ -1250,17 +1251,19 @@ export const hooksPreTask: MCPTool = {const routeResult = await router.route(description, { filePath });if (routeResult.tier === 1) {- // Agent Booster can handle this task+ // Deterministic codemod can apply this edit with $0 / no LLM (ADR-143)+ const intentType = routeResult.codemodIntent?.type ?? routeResult.agentBoosterIntent?.type;modelRouting = {tier: 1,- handler: 'agent-booster',+ handler: 'codemod',canSkipLLM: true,- agentBoosterIntent: routeResult.agentBoosterIntent?.type,- intentDescription: routeResult.agentBoosterIntent?.description,+ deterministic: true,+ codemodIntent: intentType,+ intentDescription: routeResult.codemodIntent?.description ?? routeResult.agentBoosterIntent?.description,confidence: routeResult.confidence,estimatedLatencyMs: routeResult.estimatedLatencyMs,estimatedCost: routeResult.estimatedCost,- recommendation: `[AGENT_BOOSTER_AVAILABLE] Skip LLM - use Agent Booster for "${routeResult.agentBoosterIntent?.type}"`,+ recommendation: `[CODEMOD_AVAILABLE] Skip LLM β call hooks_codemod with intent="${intentType}" (deterministic, $0)`,};} else {// LLM required@@ -4094,6 +4097,152 @@ export const hooksModelStats: MCPTool = {},};+// Supported source extensions for codemods.+const CODEMOD_EXTENSIONS = new Set(['.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs', '.mts', '.cts']);+const CODEMOD_MAX_FILES = 2000;++function codemodLangForExt(abs: string): 'javascript' | 'typescript' | 'jsx' | 'tsx' {+ const ext = abs.slice(abs.lastIndexOf('.')).toLowerCase();+ if (ext === '.tsx') return 'tsx';+ if (ext === '.jsx') return 'jsx';+ if (ext === '.js' || ext === '.mjs' || ext === '.cjs') return 'javascript';+ return 'typescript';+}++// Deterministic codemod execution β the real Tier-1 path (ADR-143)+export const hooksCodemod: MCPTool = {+ name: 'hooks_codemod',+ description: 'Apply a deterministic, $0 (no-LLM) code transform β the real Tier-1 execution path (ADR-143). Supported intents: var-to-const, remove-console, add-logging. Uses the TypeScript compiler with formatting-preserving edits (comments/whitespace survive). Targets: raw `code` (returns transformed text, writes nothing) | a single `file` | a `files` array | a `glob` pattern (batch β applies the intent across every match in one $0 call). Files are rewritten in place unless `dryRun`. Intents that need reasoning β add-types, add-error-handling, async-await β are NOT supported here; route those to a model via hooks_model-route. Use when hooks_pre-task / hooks_route returned [CODEMOD_AVAILABLE].',+ inputSchema: {+ type: 'object',+ properties: {+ intent: { type: 'string', enum: ['var-to-const', 'remove-console', 'add-logging'], description: 'Deterministic codemod to apply' },+ file: { type: 'string', description: 'Path to a single existing source file to transform in place' },+ files: { type: 'array', items: { type: 'string' }, description: 'Multiple file paths to transform in one batch call' },+ glob: { type: 'string', description: 'Glob pattern (relative to project root, e.g. "src/**/*.ts") β applies the intent to every matching source file' },+ code: { type: 'string', description: 'Raw source to transform instead of files (returns transformed code, writes nothing)' },+ language: { type: 'string', enum: ['javascript', 'typescript', 'jsx', 'tsx'], description: 'Language hint for raw code (default typescript; inferred from extension for files)' },+ dryRun: { type: 'boolean', description: 'Report what would change without writing files' },+ },+ required: ['intent'],+ },+ handler: async (params: Record<string, unknown>) => {+ const intent = params.intent as string;+ const file = params.file as string | undefined;+ const files = Array.isArray(params.files) ? (params.files as string[]) : undefined;+ const glob = params.glob as string | undefined;+ const rawCode = params.code as string | undefined;+ const dryRun = params.dryRun === true;+ const langParam = params.language as string | undefined;++ const { applyCodemod, isDeterministicCodemod } = await import('../ruvector/codemods/engine.js');+ if (!isDeterministicCodemod(intent)) {+ return {+ success: false,+ error: `"${intent}" is not a deterministic codemod. Route it to a model via hooks_model-route (Tier 2/3).`,+ };+ }++ // Mode A: transform raw code (never touches disk)+ if (typeof rawCode === 'string') {+ const language = (langParam as 'javascript' | 'typescript' | 'jsx' | 'tsx') ?? 'typescript';+ const r = applyCodemod(intent, rawCode, { language });+ return {+ success: r.success, intent, mode: 'code', changed: r.changed, edits: r.edits,+ output: r.output, language: r.language, reason: r.reason, cost: 0, tier: 1,+ };+ }++ const cwd = getProjectCwd();++ // Resolve the target file set (single / array / glob), with path containment.+ const resolveTargets = (): { abs: string[]; truncated: boolean; error?: string } => {+ const out = new Set<string>();+ const addRaw = (p: string): string | undefined => {+ const v = validatePath(p, 'path');+ if (!v.valid) return v.error;+ const abs = resolve(cwd, v.sanitized);+ if (!abs.startsWith(cwd)) return `path escapes project root: ${p}`;+ out.add(abs);+ return undefined;+ };++ if (file) { const e = addRaw(file); if (e) return { abs: [], truncated: false, error: e }; }+ if (files) for (const p of files) { const e = addRaw(p); if (e) return { abs: [], truncated: false, error: e }; }+ if (glob) {+ if (glob.includes('..')) return { abs: [], truncated: false, error: 'glob must not contain ".."' };+ // fs.globSync is Node 22+; @types/node here predates it, so type it locally.+ const globSync = (nodeFs as { globSync?: (p: string, o?: { cwd?: string }) => string[] }).globSync;+ if (typeof globSync !== 'function') {+ return { abs: [], truncated: false, error: 'glob requires Node 22+ (fs.globSync unavailable); pass `files[]` instead' };+ }+ let matches: string[] = [];+ try {+ matches = globSync(glob, { cwd });+ } catch (err) {+ return { abs: [], truncated: false, error: `glob failed: ${(err as Error).message}` };+ }+ for (const m of matches) {+ const abs = resolve(cwd, m);+ if (abs.startsWith(cwd) && CODEMOD_EXTENSIONS.has(abs.slice(abs.lastIndexOf('.')).toLowerCase())) {+ out.add(abs);+ }+ }+ }++ const all = [...out];+ const truncated = all.length > CODEMOD_MAX_FILES;+ return { abs: truncated ? all.slice(0, CODEMOD_MAX_FILES) : all, truncated };+ };++ const targets = resolveTargets();+ if (targets.error) return { success: false, error: targets.error };+ if (targets.abs.length === 0) {+ return { success: false, error: 'No target files. Provide `code`, `file`, `files[]`, or a matching `glob`.' };+ }++ // Apply to each file.+ const results: Array<Record<string, unknown>> = [];+ let filesChanged = 0, totalEdits = 0, failures = 0, skipped = 0;++ for (const abs of targets.abs) {+ const rel = abs.startsWith(cwd) ? abs.slice(cwd.length).replace(/^[/\\]/, '') : abs;+ if (!existsSync(abs)) { results.push({ file: rel, success: false, reason: 'not found' }); failures++; continue; }+ if (!CODEMOD_EXTENSIONS.has(abs.slice(abs.lastIndexOf('.')).toLowerCase())) {+ results.push({ file: rel, success: false, reason: 'unsupported extension' }); skipped++; continue;+ }+ const before = readFileSync(abs, 'utf-8');+ const r = applyCodemod(intent, before, { language: codemodLangForExt(abs) });+ if (!r.success) { results.push({ file: rel, success: false, changed: false, reason: r.reason }); failures++; continue; }+ const written = r.changed && !dryRun;+ if (written) writeFileSync(abs, r.output, 'utf-8');+ if (r.changed) { filesChanged++; totalEdits += r.edits; }+ results.push({ file: rel, success: true, changed: r.changed, edits: r.edits, written });+ }++ const single = targets.abs.length === 1 && !files && !glob;+ return {+ success: failures === 0,+ intent,+ mode: single ? (dryRun ? 'dry-run' : 'file') : (dryRun ? 'batch-dry-run' : 'batch'),+ summary: {+ filesScanned: targets.abs.length,+ filesChanged,+ filesUnchanged: targets.abs.length - filesChanged - failures - skipped,+ totalEdits,+ failures,+ skipped,+ truncatedAt: targets.truncated ? CODEMOD_MAX_FILES : undefined,+ },+ results: results.slice(0, 500),+ resultsTruncated: results.length > 500,+ cost: 0,+ tier: 1,+ timestamp: new Date().toISOString(),+ };+ },+};+// Simple fallback complexity analyzerfunction analyzeComplexityFallback(task: string): number {const taskLower = task.toLowerCase();@@ -4261,6 +4410,8 @@ export const hooksTools: MCPTool[] = [hooksModelRoute,hooksModelOutcome,hooksModelStats,+ // Deterministic Tier-1 codemod execution (ADR-143)+ hooksCodemod,];export default hooksTools;diff --git a/v3/@claude-flow/cli/src/ruvector/codemods/engine.ts b/v3/@claude-flow/cli/src/ruvector/codemods/engine.tsnew file mode 100644index 0000000000..a99673c607--- /dev/null+++ b/v3/@claude-flow/cli/src/ruvector/codemods/engine.ts@@ -0,0 +1,371 @@+/**+ * Deterministic Codemod Engine (ADR-143)+ *+ * Truly $0, no-LLM Tier-1 code transforms. Uses the TypeScript compiler API to+ * locate exact AST nodes, then applies formatting-preserving text-range edits to+ * the original source string (we never re-print the whole file, so comments and+ * formatting survive).+ *+ * Only intents that can be transformed *deterministically and safely* live here.+ * Intents that need inference or judgement (add-types, add-error-handling,+ * async-await) are intentionally NOT codemods β they route to a model. See+ * ADR-143 for the rationale.+ *+ * @module ruvector/codemods/engine+ */++import ts from 'typescript';+import { buildReassignmentResolver } from './scope-analysis.js';++export type CodemodIntent = 'var-to-const' | 'remove-console' | 'add-logging';++/** Intents this engine can apply deterministically with $0 cost. */+export const DETERMINISTIC_CODEMOD_INTENTS: readonly CodemodIntent[] = [+ 'var-to-const',+ 'remove-console',+ 'add-logging',+] as const;++/** Intents recognised by the router but NOT safe as deterministic codemods. */+export const MODEL_ROUTED_INTENTS: readonly string[] = [+ 'add-types',+ 'add-error-handling',+ 'async-await',+] as const;++export type CodemodLanguage = 'javascript' | 'typescript' | 'jsx' | 'tsx';++export interface CodemodResult {+ intent: CodemodIntent;+ success: boolean;+ /** true if the output differs from the input. */+ changed: boolean;+ output: string;+ /** number of discrete edit sites applied. */+ edits: number;+ language: CodemodLanguage;+ reason?: string;+}++interface TextEdit {+ start: number;+ end: number;+ replacement: string;+}++export function isDeterministicCodemod(intent: string): intent is CodemodIntent {+ return (DETERMINISTIC_CODEMOD_INTENTS as readonly string[]).includes(intent);+}++// ============================================================================+// Parsing & edit application+// ============================================================================++function scriptKind(language: CodemodLanguage): ts.ScriptKind {+ switch (language) {+ case 'typescript':+ return ts.ScriptKind.TS;+ case 'tsx':+ return ts.ScriptKind.TSX;+ case 'jsx':+ return ts.ScriptKind.JSX;+ default:+ return ts.ScriptKind.JS;+ }+}++function parse(code: string, language: CodemodLanguage): ts.SourceFile {+ return ts.createSourceFile(+ `codemod-input.${language}`,+ code,+ ts.ScriptTarget.Latest,+ /* setParentNodes */ true,+ scriptKind(language),+ );+}++function parseDiagnosticCount(sf: ts.SourceFile): number {+ // parseDiagnostics is internal but stable; guard so a missing field never throws.+ return (sf as unknown as { parseDiagnostics?: unknown[] }).parseDiagnostics?.length ?? 0;+}++/** Apply edits to the original source, right-to-left so offsets stay valid. */+function applyEdits(code: string, edits: TextEdit[]): string {+ const sorted = [...edits].sort((a, b) => b.start - a.start);+ let out = code;+ for (const e of sorted) {+ out = out.slice(0, e.start) + e.replacement + out.slice(e.end);+ }+ return out;+}++function lineStartOffset(code: string, pos: number): number {+ let i = pos;+ while (i > 0 && code[i - 1] !== '\n') i--;+ return i;+}++function leadingIndent(code: string, lineStart: number): string {+ let i = lineStart;+ while (i < code.length && (code[i] === ' ' || code[i] === '\t')) i++;+ return code.slice(lineStart, i);+}++// ============================================================================+// var-to-const (scope-aware reassignment analysis β see scope-analysis.ts)+// ============================================================================++function isVarList(list: ts.VariableDeclarationList): boolean {+ return !(list.flags & (ts.NodeFlags.Let | ts.NodeFlags.Const));+}++function collectBindingNames(name: ts.BindingName, out: Set<string>): void {+ if (ts.isIdentifier(name)) {+ out.add(name.text);+ return;+ }+ for (const el of name.elements) {+ if (ts.isBindingElement(el)) collectBindingNames(el.name, out);+ }+}++function varToConstEdits(code: string, sf: ts.SourceFile): TextEdit[] {+ const resolver = buildReassignmentResolver(sf);+ const edits: TextEdit[] = [];++ const visit = (node: ts.Node): void => {+ if (ts.isVariableDeclarationList(node) && isVarList(node)) {+ const names = new Set<string>();+ for (const decl of node.declarations) collectBindingNames(decl.name, names);+ // `const` only when no declared binding is reassigned *within its own scope*.+ const anyReassigned = [...names].some((n) => resolver.isReassigned(n, node));+ const keyword = anyReassigned ? 'let' : 'const';++ // The `var` keyword is the first token of the declaration list.+ const start = node.getStart(sf);+ // Only rewrite when the literal text really is `var` (guards against odd trivia).+ if (code.slice(start, start + 3) === 'var') {+ edits.push({ start, end: start + 3, replacement: keyword });+ }+ }+ ts.forEachChild(node, visit);+ };++ visit(sf);+ return edits;+}++// ============================================================================+// remove-console+// ============================================================================++function rootIdentifier(expr: ts.Expression): ts.Identifier | undefined {+ let cur: ts.Expression = expr;+ while (ts.isPropertyAccessExpression(cur) || ts.isElementAccessExpression(cur)) {+ cur = cur.expression;+ }+ return ts.isIdentifier(cur) ? cur : undefined;+}++function isConsoleCallStatement(stmt: ts.Statement): boolean {+ if (!ts.isExpressionStatement(stmt)) return false;+ let expr: ts.Expression = stmt.expression;+ // unwrap `void console.log(x)` and awaited/comma forms defensively+ if (ts.isCallExpression(expr)) {+ const root = rootIdentifier(expr.expression);+ return !!root && root.text === 'console';+ }+ return false;+}++function removeConsoleEdits(code: string, sf: ts.SourceFile): TextEdit[] {+ const edits: TextEdit[] = [];++ const visit = (node: ts.Node): void => {+ if (isConsoleCallStatement(node as ts.Statement)) {+ const stmt = node as ts.Statement;+ const start = stmt.getStart(sf);+ const end = stmt.getEnd();+ const ls = lineStartOffset(code, start);+ const beforeIsBlank = code.slice(ls, start).trim() === '';++ // Is the rest of the line after the statement only whitespace?+ let lineEnd = end;+ while (lineEnd < code.length && code[lineEnd] !== '\n') lineEnd++;+ const afterIsBlank = code.slice(end, lineEnd).trim() === '';++ if (beforeIsBlank && afterIsBlank) {+ // Statement owns its line(s): drop the whole line incl. trailing newline.+ const dropEnd = lineEnd < code.length ? lineEnd + 1 : lineEnd;+ edits.push({ start: ls, end: dropEnd, replacement: '' });+ } else {+ // Inline with other code: remove just the statement, tidy one trailing space.+ let e = end;+ if (code[e] === ' ') e++;+ edits.push({ start, end: e, replacement: '' });+ }+ }+ ts.forEachChild(node, visit);+ };++ visit(sf);+ return edits;+}++// ============================================================================+// add-logging+// ============================================================================++type FunctionLike =+ | ts.FunctionDeclaration+ | ts.FunctionExpression+ | ts.ArrowFunction+ | ts.MethodDeclaration+ | ts.ConstructorDeclaration+ | ts.GetAccessorDeclaration+ | ts.SetAccessorDeclaration;++function isFunctionLikeWithBlock(node: ts.Node): node is FunctionLike {+ return (+ (ts.isFunctionDeclaration(node) ||+ ts.isFunctionExpression(node) ||+ ts.isArrowFunction(node) ||+ ts.isMethodDeclaration(node) ||+ ts.isConstructorDeclaration(node) ||+ ts.isGetAccessor(node) ||+ ts.isSetAccessor(node)) &&+ !!node.body &&+ ts.isBlock(node.body)+ );+}++function functionName(node: FunctionLike): string {+ if (ts.isConstructorDeclaration(node)) return 'constructor';+ if (+ (ts.isFunctionDeclaration(node) ||+ ts.isFunctionExpression(node) ||+ ts.isMethodDeclaration(node) ||+ ts.isGetAccessor(node) ||+ ts.isSetAccessor(node)) &&+ node.name &&+ (ts.isIdentifier(node.name) || ts.isStringLiteral(node.name))+ ) {+ return node.name.text;+ }+ // function expression / arrow assigned to a variable or property+ const parent = node.parent;+ if (parent && ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name)) return parent.name.text;+ if (parent && ts.isPropertyAssignment(parent) && ts.isIdentifier(parent.name)) return parent.name.text;+ return 'anonymous';+}++function alreadyLogsEntry(body: ts.Block, name: string): boolean {+ const first = body.statements[0];+ if (!first || !isConsoleCallStatement(first)) return false;+ const text = first.getText();+ return text.includes(`'${name} called'`) || text.includes(`"${name} called"`);+}++function addLoggingEdits(code: string, sf: ts.SourceFile): TextEdit[] {+ const edits: TextEdit[] = [];++ const visit = (node: ts.Node): void => {+ if (isFunctionLikeWithBlock(node)) {+ const body = node.body as ts.Block;+ const name = functionName(node);+ if (!alreadyLogsEntry(body, name)) {+ const braceOffset = body.getStart(sf); // position of '{'+ const headerLineStart = lineStartOffset(code, node.getStart(sf));+ const indent = leadingIndent(code, headerLineStart);+ const bodyIndent = indent + ' ';+ const insertion = `\n${bodyIndent}console.log(${JSON.stringify(`${name} called`)});`;+ edits.push({ start: braceOffset + 1, end: braceOffset + 1, replacement: insertion });+ }+ }+ ts.forEachChild(node, visit);+ };++ visit(sf);+ return edits;+}++// ============================================================================+// Public API+// ============================================================================++const TRANSFORMS: Record<CodemodIntent, (code: string, sf: ts.SourceFile) => TextEdit[]> = {+ 'var-to-const': varToConstEdits,+ 'remove-console': removeConsoleEdits,+ 'add-logging': addLoggingEdits,+};++export interface ApplyCodemodOptions {+ language?: CodemodLanguage;+}++/**+ * Apply a deterministic codemod to a source string.+ *+ * Returns the transformed source plus metadata. Never throws on malformed input+ * β it reports `success: false` with a reason instead. Guarantees the output+ * does not introduce new parse errors (otherwise it returns the input unchanged).+ */+export function applyCodemod(+ intent: string,+ code: string,+ opts: ApplyCodemodOptions = {},+): CodemodResult {+ const language: CodemodLanguage = opts.language ?? 'typescript';++ if (!isDeterministicCodemod(intent)) {+ return {+ intent: intent as CodemodIntent,+ success: false,+ changed: false,+ output: code,+ edits: 0,+ language,+ reason: `"${intent}" is not a deterministic codemod β route it to a model (Tier 2/3).`,+ };+ }++ let sf: ts.SourceFile;+ try {+ sf = parse(code, language);+ } catch (err) {+ return {+ intent,+ success: false,+ changed: false,+ output: code,+ edits: 0,+ language,+ reason: `parse failed: ${(err as Error).message}`,+ };+ }++ const beforeDiagnostics = parseDiagnosticCount(sf);+ const edits = TRANSFORMS[intent](code, sf);++ if (edits.length === 0) {+ return { intent, success: true, changed: false, output: code, edits: 0, language };+ }++ const output = applyEdits(code, edits);++ // Safety net: never hand back source that parses worse than the input.+ const afterDiagnostics = parseDiagnosticCount(parse(output, language));+ if (afterDiagnostics > beforeDiagnostics) {+ return {+ intent,+ success: false,+ changed: false,+ output: code,+ edits: 0,+ language,+ reason: 'transform would introduce parse errors β aborted (input returned unchanged).',+ };+ }++ return { intent, success: true, changed: true, output, edits: edits.length, language };+}diff --git a/v3/@claude-flow/cli/src/ruvector/codemods/scope-analysis.ts b/v3/@claude-flow/cli/src/ruvector/codemods/scope-analysis.tsnew file mode 100644index 0000000000..6c207a1fe7--- /dev/null+++ b/v3/@claude-flow/cli/src/ruvector/codemods/scope-analysis.ts@@ -0,0 +1,168 @@+/**+ * Scope-aware reassignment analysis for the `var-to-const` codemod (ADR-143).+ *+ * The naive version marks a `var` as reassigned if its name is assigned to+ * *anywhere* in the file. That is correct but over-conservative: a `var x` in+ * one function is forced to `let` just because an unrelated function also has+ * an `x = β¦`. This module resolves each assignment to the binding it actually+ * mutates (function-scope hoisting semantics), so a `var` becomes `const`+ * unless *its own* binding is reassigned.+ *+ * Soundness: resolution only ever attributes a reassignment to a scope that+ * actually hoists the name (i.e. genuinely declares that binding). It therefore+ * never marks a truly-reassigned binding as un-reassigned β so a `var` is only+ * promoted to `const` when it is provably never reassigned. Block-scoped+ * shadowing (let/const) is ignored for resolution, which can only make us *more*+ * conservative (fall back to `let`), never wrong.+ *+ * @module ruvector/codemods/scope-analysis+ */++import ts from 'typescript';++/** A scope is a function-like node or the SourceFile (the var-hoist boundaries). */+function isScopeNode(node: ts.Node): boolean {+ return (+ ts.isSourceFile(node) ||+ ts.isFunctionDeclaration(node) ||+ ts.isFunctionExpression(node) ||+ ts.isArrowFunction(node) ||+ ts.isMethodDeclaration(node) ||+ ts.isConstructorDeclaration(node) ||+ ts.isGetAccessorDeclaration(node) ||+ ts.isSetAccessorDeclaration(node)+ );+}++function enclosingScope(node: ts.Node): ts.Node {+ let cur: ts.Node | undefined = node.parent;+ while (cur && !isScopeNode(cur)) cur = cur.parent;+ return cur ?? node.getSourceFile();+}++function parentScope(scope: ts.Node): ts.Node | undefined {+ if (ts.isSourceFile(scope)) return undefined;+ return enclosingScope(scope);+}++function collectIdentifierNames(target: ts.Node, out: (name: string) => void): void {+ if (ts.isIdentifier(target)) {+ out(target.text);+ return;+ }+ // Destructuring assignment target (object/array literal on the LHS of `=`).+ ts.forEachChild(target, (child) => collectIdentifierNames(child, out));+}++const ASSIGNMENT_OPERATORS = new Set<ts.SyntaxKind>([+ ts.SyntaxKind.EqualsToken,+ ts.SyntaxKind.PlusEqualsToken,+ ts.SyntaxKind.MinusEqualsToken,+ ts.SyntaxKind.AsteriskEqualsToken,+ ts.SyntaxKind.AsteriskAsteriskEqualsToken,+ ts.SyntaxKind.SlashEqualsToken,+ ts.SyntaxKind.PercentEqualsToken,+ ts.SyntaxKind.LessThanLessThanEqualsToken,+ ts.SyntaxKind.GreaterThanGreaterThanEqualsToken,+ ts.SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken,+ ts.SyntaxKind.AmpersandEqualsToken,+ ts.SyntaxKind.BarEqualsToken,+ ts.SyntaxKind.CaretEqualsToken,+ ts.SyntaxKind.BarBarEqualsToken,+ ts.SyntaxKind.AmpersandAmpersandEqualsToken,+ ts.SyntaxKind.QuestionQuestionEqualsToken,+]);++export interface ReassignmentResolver {+ /** True if the `var` binding declared by `declarationList` (for `name`) is reassigned within its scope. */+ isReassigned(name: string, declarationList: ts.VariableDeclarationList): boolean;+}++/**+ * Build a scope-aware resolver: which `var` bindings are actually reassigned.+ */+export function buildReassignmentResolver(sf: ts.SourceFile): ReassignmentResolver {+ // Names hoisted into each scope: var-declared names, function declarations,+ // and parameters. (Collected per scope, not crossing nested function scopes.)+ const hoisted = new Map<ts.Node, Set<string>>();+ const ensure = (scope: ts.Node): Set<string> => {+ let s = hoisted.get(scope);+ if (!s) { s = new Set(); hoisted.set(scope, s); }+ return s;+ };+ ensure(sf);++ const addBinding = (name: ts.BindingName, scope: ts.Node): void => {+ if (ts.isIdentifier(name)) {+ ensure(scope).add(name.text);+ } else {+ for (const el of name.elements) {+ if (ts.isBindingElement(el)) addBinding(el.name, scope);+ }+ }+ };++ // Pass 1 β record hoisted names per scope.+ const collectHoisted = (node: ts.Node): void => {+ if (isScopeNode(node) && !ts.isSourceFile(node)) {+ ensure(node);+ // Parameters belong to the function's own scope.+ const params = (node as ts.FunctionLikeDeclarationBase).parameters;+ if (params) for (const p of params) addBinding(p.name, node);+ }+ if (ts.isVariableDeclarationList(node) && !(node.flags & (ts.NodeFlags.Let | ts.NodeFlags.Const))) {+ const scope = enclosingScope(node); // var hoists to the nearest function/source scope+ for (const decl of node.declarations) addBinding(decl.name, scope);+ }+ if (ts.isFunctionDeclaration(node) && node.name) {+ ensure(enclosingScope(node)).add(node.name.text);+ }+ ts.forEachChild(node, collectHoisted);+ };+ collectHoisted(sf);++ const resolveScope = (name: string, from: ts.Node): ts.Node | undefined => {+ let scope: ts.Node | undefined = from;+ while (scope) {+ if (hoisted.get(scope)?.has(name)) return scope;+ scope = parentScope(scope);+ }+ return undefined;+ };++ // Pass 2 β attribute each reassignment to the binding (scope) it mutates.+ const reassigned = new Set<string>(); // key: `${scopeId}::${name}`+ const scopeIds = new Map<ts.Node, number>();+ let nextId = 0;+ const scopeId = (scope: ts.Node): number => {+ let id = scopeIds.get(scope);+ if (id === undefined) { id = nextId++; scopeIds.set(scope, id); }+ return id;+ };++ const markReassigned = (name: string, at: ts.Node): void => {+ const declScope = resolveScope(name, enclosingScope(at));+ if (declScope) reassigned.add(`${scopeId(declScope)}::${name}`);+ };++ const collectReassignments = (node: ts.Node): void => {+ if (ts.isBinaryExpression(node) && ASSIGNMENT_OPERATORS.has(node.operatorToken.kind)) {+ collectIdentifierNames(node.left, (n) => markReassigned(n, node));+ } else if (+ (ts.isPostfixUnaryExpression(node) || ts.isPrefixUnaryExpression(node)) &&+ (node.operator === ts.SyntaxKind.PlusPlusToken || node.operator === ts.SyntaxKind.MinusMinusToken) &&+ ts.isIdentifier(node.operand)+ ) {+ markReassigned(node.operand.text, node);+ }+ ts.forEachChild(node, collectReassignments);+ };+ collectReassignments(sf);++ return {+ isReassigned(name: string, declarationList: ts.VariableDeclarationList): boolean {+ const declScope = enclosingScope(declarationList);+ return reassigned.has(`${scopeId(declScope)}::${name}`);+ },+ };+}diff --git a/v3/@claude-flow/cli/src/ruvector/enhanced-model-router.ts b/v3/@claude-flow/cli/src/ruvector/enhanced-model-router.tsindex 4a2f17f82d..d4320687ff 100644--- a/v3/@claude-flow/cli/src/ruvector/enhanced-model-router.ts+++ b/v3/@claude-flow/cli/src/ruvector/enhanced-model-router.ts@@ -9,9 +9,20 @@* @module enhanced-model-router*/-import { existsSync, readFileSync } from 'fs';-import { extname } from 'path';+import { existsSync, readFileSync, writeFileSync } from 'fs';+import { extname, isAbsolute, resolve as resolvePath } from 'path';import { ClaudeModel, getModelRouter, ModelRouter, ModelRoutingResult } from './model-router.js';+import { applyCodemod, isDeterministicCodemod, type CodemodLanguage } from './codemods/engine.js';++/** Map a file path to the codemod engine's language, falling back to a hint. */+function codemodLanguageFor(filePath: string, fallback?: string): CodemodLanguage {+ const ext = extname(filePath).toLowerCase();+ if (ext === '.tsx') return 'tsx';+ if (ext === '.jsx') return 'jsx';+ if (ext === '.ts' || ext === '.mts' || ext === '.cts') return 'typescript';+ if (ext === '.js' || ext === '.mjs' || ext === '.cjs') return 'javascript';+ return fallback === 'typescript' ? 'typescript' : 'javascript';+}// ============================================================================// Types@@ -44,12 +55,20 @@ export interface EditIntent {*/export interface EnhancedRouteResult {tier: 1 | 2 | 3;- handler: 'agent-booster' | 'haiku' | 'sonnet' | 'opus';+ handler: 'codemod' | 'agent-booster' | 'haiku' | 'sonnet' | 'opus';model?: ClaudeModel;confidence: number;complexity?: number;reasoning: string;+ /** The detected edit intent (Tier 1 only). */+ codemodIntent?: EditIntent;+ /**+ * Back-compat alias for {@link codemodIntent}. Older callers read this field.+ * @deprecated use {@link codemodIntent}+ */agentBoosterIntent?: EditIntent;+ /** true when a deterministic, $0 codemod can fully apply this edit (no LLM). */+ deterministic?: boolean;canSkipLLM?: boolean;estimatedLatencyMs: number;estimatedCost: number;@@ -347,21 +366,59 @@ export class EnhancedModelRouter {* Route a task to the optimal tier and handler*/async route(task: string, context?: { filePath?: string }): Promise<EnhancedRouteResult> {- // Step 1: Try Agent Booster intent detection+ // Step 1: Deterministic codemod detection (ADR-143).+ // Only intents that a codemod can apply *deterministically and safely* skip+ // the LLM. Intents that need inference (add-types, add-error-handling,+ // async-await) are detected but fall through to model routing below.if (this.config.agentBoosterEnabled) {const intent = this.detectIntent(task);- if (intent && intent.confidence >= this.config.agentBoosterConfidenceThreshold) {- return {- tier: 1,- handler: 'agent-booster',- confidence: intent.confidence,- reasoning: `Agent Booster can handle "${intent.type}" with ${(intent.confidence * 100).toFixed(0)}% confidence`,- agentBoosterIntent: intent,- canSkipLLM: true,- estimatedLatencyMs: 1,- estimatedCost: 0,- };+ if (+ intent &&+ intent.confidence >= this.config.agentBoosterConfidenceThreshold &&+ isDeterministicCodemod(intent.type)+ ) {+ // Route-time dry-run (ADR-143 #3): when a target file is known, only+ // claim Tier-1 if the codemod actually changes something. This avoids+ // recommending [CODEMOD_AVAILABLE] for no-ops (e.g. "remove console" on+ // a file with no console calls). With no file to check, recommend Tier-1+ // best-effort β the executor (hooks_codemod) verifies before writing.+ // Prefer the caller-provided path (authoritative, usually absolute) over+ // the path heuristically extracted from the task text; resolve relatives.+ const fpRaw = context?.filePath || intent.filePath;+ const fp = fpRaw ? (isAbsolute(fpRaw) ? fpRaw : resolvePath(process.cwd(), fpRaw)) : undefined;+ let tier1 = true;+ let edits: number | undefined;+ if (fp && existsSync(fp)) {+ try {+ const code = readFileSync(fp, 'utf-8');+ const res = applyCodemod(intent.type, code, { language: codemodLanguageFor(fp, intent.language) });+ if (res.success && res.changed) {+ edits = res.edits;+ } else {+ tier1 = false; // verified no-op / can't apply β fall through to model routing+ }+ } catch {+ // read error β leave best-effort Tier-1 (executor will verify)+ }+ }++ if (tier1) {+ const editsNote = edits !== undefined ? ` (${edits} edit${edits === 1 ? '' : 's'})` : '';+ return {+ tier: 1,+ handler: 'codemod',+ confidence: intent.confidence,+ reasoning: `Deterministic codemod can apply "${intent.type}" with ${(intent.confidence * 100).toFixed(0)}% confidence β $0, no LLM${editsNote}`,+ codemodIntent: intent,+ agentBoosterIntent: intent,+ deterministic: true,+ canSkipLLM: true,+ estimatedLatencyMs: 1,+ estimatedCost: 0,+ };+ }+ // verified no-op: fall through to model routing below}}@@ -489,35 +546,39 @@ export class EnhancedModelRouter {}/**- * Execute task using the appropriate tier- * Returns the result and routing information+ * Execute task using the appropriate tier.+ *+ * For Tier-1 deterministic intents this applies the codemod directly (writing+ * the file back when a path is given) β $0, no LLM. Otherwise it returns the+ * routing result and the caller invokes the recommended model.*/async execute(task: string,context?: { filePath?: string; originalCode?: string }): Promise<{- result: string | { applied: boolean; confidence: number };+ result: string | { applied: boolean; changed: boolean; edits: number };routeResult: EnhancedRouteResult;}> {const routeResult = await this.route(task, context);+ const intent = routeResult.codemodIntent ?? routeResult.agentBoosterIntent;- if (routeResult.tier === 1 && routeResult.agentBoosterIntent) {- // Try to execute with Agent Booster- const abResult = await this.tryAgentBooster(routeResult.agentBoosterIntent, context);+ if (routeResult.tier === 1 && routeResult.deterministic && intent) {+ const cm = this.tryCodemod(intent, context);- if (abResult.success) {+ if (cm.success) {return {- result: { applied: true, confidence: abResult.confidence },+ result: { applied: true, changed: cm.changed, edits: cm.edits },routeResult,};}- // Agent Booster failed, fall back to LLM+ // Codemod could not apply (no file / parse issue) β fall back to a model.routeResult.tier = 2;routeResult.handler = 'sonnet';routeResult.model = 'sonnet';+ routeResult.deterministic = false;routeResult.canSkipLLM = false;- routeResult.reasoning += ' (Agent Booster fallback to LLM)';+ routeResult.reasoning += ' (codemod fallback to LLM)';}// Return routing result - caller handles LLM invocation@@ -525,72 +586,32 @@ export class EnhancedModelRouter {}/**- * Try to apply edit using Agent Booster+ * Apply a deterministic codemod to the intent's target file.+ *+ * This is the real Tier-1 execution path (ADR-143). It uses the in-process+ * TypeScript-compiler codemod engine β no `agent-booster` import, no subprocess,+ * no LLM. Writes the transformed source back to disk when it changes.*/- private async tryAgentBooster(+ private tryCodemod(intent: EditIntent,context?: { filePath?: string; originalCode?: string }- ): Promise<{ success: boolean; confidence: number; output?: string }> {- try {- const filePath = intent.filePath || context?.filePath;- if (!filePath || !existsSync(filePath)) {- return { success: false, confidence: 0 };- }-- const originalCode = context?.originalCode || readFileSync(filePath, 'utf-8');-- const intentToInstruction: Record<EditIntentType, string> = {- 'var-to-const': 'Convert all var declarations to const',- 'add-types': 'Add TypeScript type annotations',- 'add-error-handling': 'Wrap in try/catch blocks',- 'async-await': 'Convert to async/await',- 'add-logging': 'Add console.log statements',- 'remove-console': 'Remove all console.* statements',- };+ ): { success: boolean; changed: boolean; edits: number } {+ const filePath = intent.filePath || context?.filePath;+ if (!filePath || !existsSync(filePath)) {+ return { success: false, changed: false, edits: 0 };+ }- const instruction = intentToInstruction[intent.type];- const language = intent.language || 'javascript';-- // Try local agentic-flow agent-booster (v3 β no npx needed)- // Note: agent-booster export declared but dist missing in alpha.1; use intelligence path as fallback- const boosterModule = await import('agentic-flow/agent-booster')- .catch(() => import(/* @vite-ignore */ 'agentic-flow/intelligence/agent-booster-enhanced'))- .catch(() => null);- if (boosterModule?.enhancedApply) {- const result = await boosterModule.enhancedApply({- code: originalCode,- edit: instruction,- language,- });- if (result && result.confidence >= this.config.agentBoosterConfidenceThreshold) {- return { success: true, confidence: result.confidence, output: result.output };- }- return { success: false, confidence: result?.confidence ?? 0 };- }+ const originalCode = context?.originalCode ?? readFileSync(filePath, 'utf-8');+ const language = codemodLanguageFor(filePath, intent.language);+ const result = applyCodemod(intent.type, originalCode, { language });- // Fallback: shell out to npx agent-booster- // Sanitize language to prevent command injection (whitelist only)- const SAFE_LANGUAGES = ['javascript', 'typescript', 'python', 'rust', 'go', 'java', 'c', 'cpp', 'ruby', 'swift', 'kotlin'];- const safeLang = SAFE_LANGUAGES.includes(language) ? language : 'javascript';- const { execSync } = await import('child_process');- const cmd = `npx --yes [email protected] apply --language ${safeLang}`;- const result = execSync(cmd, {- encoding: 'utf-8',- input: JSON.stringify({ code: originalCode, edit: instruction }),- maxBuffer: 10 * 1024 * 1024,- timeout: 5000,- stdio: ['pipe', 'pipe', 'pipe'],- });-- const parsed = JSON.parse(result);- if (parsed.confidence >= this.config.agentBoosterConfidenceThreshold) {- return { success: true, confidence: parsed.confidence, output: parsed.output };- }- return { success: false, confidence: parsed.confidence ?? 0 };- } catch {- // Agent Booster not available or failed- return { success: false, confidence: 0 };+ if (!result.success) {+ return { success: false, changed: false, edits: 0 };+ }+ if (result.changed && !context?.originalCode) {+ writeFileSync(filePath, result.output, 'utf-8');}+ return { success: true, changed: result.changed, edits: result.edits };}/**@@ -657,18 +678,24 @@ export async function enhancedRouteToModel(}/**- * Detect if a task can be handled by Agent Booster+ * Detect if a task can be applied by a deterministic, $0 codemod (ADR-143).+ * Only the deterministic intents qualify β others need a model.*/-export function canUseAgentBooster(task: string): {+export function canUseCodemod(task: string): {canUse: boolean;intent?: EditIntent;} {const router = getEnhancedModelRouter();const intent = router.detectIntent(task);- if (intent && intent.confidence >= 0.7) {+ if (intent && intent.confidence >= 0.7 && isDeterministicCodemod(intent.type)) {return { canUse: true, intent };}return { canUse: false };}++/**+ * @deprecated Agent Booster never performed these transforms. Use {@link canUseCodemod}.+ */+export const canUseAgentBooster = canUseCodemod;diff --git a/v3/docs/adr/ADR-143-deterministic-tier1-codemods.md b/v3/docs/adr/ADR-143-deterministic-tier1-codemods.mdnew file mode 100644index 0000000000..112ff56285--- /dev/null+++ b/v3/docs/adr/ADR-143-deterministic-tier1-codemods.md@@ -0,0 +1,134 @@+# ADR-143 β Deterministic Codemods for Tier-1 Routing (replacing "Agent Booster")++**Status**: Accepted β Implemented in v3.10.x (2026-05-29)+**Related**: ADR-026 (3-tier model routing), ADR-142 (per-task bandit priors), #2238, docs/reviews/intelligence-system-audit-2026-05-29.md++## Context++ADR-026 advertises **Tier 1 = Agent Booster (WASM), <1 ms, $0, no LLM** for simple+code transforms (`var-to-const`, `remove-console`, β¦). An audit of the live code+paths found the claim was not real:++1. **The execution path was dead code.** The only methods that invoke a booster β+ `EnhancedModelRouter.execute()` / `tryAgentBooster()` and+ `TokenOptimizer.optimizedEdit()` β are called by *nothing* in the CLI or MCP+ runtime. Every caller uses `route()`, which only emits a *recommendation*.+2. **It was also wired wrong.** `tryAgentBooster()` built the edit from a+ natural-language instruction (`"Convert all var declarations to const"`) and+ passed that as `edit` to `agent-booster`. But `agent-booster` is a *fast-apply+ merge engine* (Morph/Cursor-style): `apply({ code, edit })` expects `edit` to be+ the **target code snippet**, not an instruction. Fed an instruction it returns+ `success:false, confidence:0, strategy:"failed"`. Every Tier-1 call would have+ failed even if `execute()` were wired in.+3. **The module didn't resolve.** `import('agentic-flow/agent-booster')` β+ `ERR_MODULE_NOT_FOUND`; `agentic-flow` exports only `main` + `reasoningbank`.++So `[AGENT_BOOSTER_AVAILABLE]` only ever told Claude "do this edit yourself with+the Edit tool." No WASM, no $0 transform, no booster in the loop β the+recommendation borrowed the booster's *name* for something that never touched it.+A phantom MCP tool `agent_booster_edit_file` was referenced in `agent-tools.ts`+but never existed.++The key realisation: **Agent Booster cannot do zero-LLM intent transforms.** It is+an *applier* of a pre-computed edit, not a *generator* of one. To make the+"$0, no-LLM Tier 1" claim literally true, Tier 1 must be a transform that needs no+edit snippet at all.++## Decision++Replace the Tier-1 "Agent Booster" execution with **deterministic codemods** for+the intents that can be transformed safely without inference, using the+**TypeScript compiler API** with **formatting-preserving text-range edits** (locate+exact AST nodes, splice the original source β never re-print the file, so comments+and whitespace survive).++**Deterministic β Tier 1 (codemod, $0, no LLM):**++| intent | rule |+|------------------|------|+| `var-to-const` | `const` when the binding is never reassigned anywhere in the file, else `let` (conservative: `let` is always valid) |+| `remove-console` | drop `console.*(β¦)` expression statements; whole-line removal only when the statement owns its line |+| `add-logging` | insert one entry `console.log("<name> called")` per function body; idempotent (skips if already present) |++**Needs judgement β NOT a codemod, routes to a model (Tier 2/3):**++`add-types`, `add-error-handling`, `async-await`. These are still *detected* by the+intent classifier, but the router deliberately does **not** return Tier 1 for them β+they fall through to complexity-based model routing. Deterministic "codemods" for+these would either be trivial (`: any`) or unsafe, which is worse than routing to a+model.++`agent-booster` remains a dependency for general fast-apply (arbitrary+LLM-produced edit snippets), but it is **out of the Tier-1 path**.++## Implementation++- **`v3/@claude-flow/cli/src/ruvector/codemods/engine.ts`** β `applyCodemod(intent, code, {language})`+ + `isDeterministicCodemod()` + `DETERMINISTIC_CODEMOD_INTENTS` /+ `MODEL_ROUTED_INTENTS`. Never throws on malformed input; includes a+ **parse-diagnostic safety net** β if a transform would introduce new parse+ errors, it returns the input unchanged (`success:false`).+- **`enhanced-model-router.ts`** β Tier-1 branch gated on `isDeterministicCodemod`;+ handler renamed `agent-booster` β `codemod` with a `deterministic` flag.+ `agentBoosterIntent` kept as a deprecated alias of the new `codemodIntent`.+ `execute()`/`tryAgentBooster()` rewritten to `tryCodemod()` calling the engine+ (removed the broken NL-instruction `agentic-flow/agent-booster` import and the+ `npx agent-booster` subprocess fallback). `canUseAgentBooster` β deprecated alias+ of `canUseCodemod`.+- **`hooks_codemod` MCP tool** (`hooks-tools.ts`) β the real executable Tier-1+ surface. Transforms a `file` in place (path-validated, must exist; `dryRun`+ supported) or raw `code`. Reports `cost: 0`. Refuses non-deterministic intents.+- **Recommendation emitters** β `hooks_pre-task`, `hooks_route` (description), CLI+ `hooks pre-task`, and `agent-tools` now emit `[CODEMOD_AVAILABLE] β¦ call+ hooks_codemod` instead of `[AGENT_BOOSTER_AVAILABLE]`; the phantom+ `agent_booster_edit_file` note now points at `hooks_codemod`.++## Consequences++- **The Tier-1 "$0, no-LLM" claim is now literally true** for the 3 deterministic+ intents, and reachable end-to-end (router β `[CODEMOD_AVAILABLE]` β+ `hooks_codemod` β file rewritten at $0).+- **Three intents lost their (fake) Tier-1 status.** `add-types`,+ `add-error-handling`, `async-await` now honestly route to a model. This is a net+ correctness gain β they never actually worked as $0 transforms.+- Formatting/comments are preserved (text-range edits, not re-printing).+- `agent-booster` is no longer on any hot path; the `agentic-flow/agent-booster`+ import and `npx` fallback are gone, so a missing module can no longer silently+ fail a route.++## Follow-up optimizations++1. **Batch / glob mode** (`hooks_codemod`) β beyond a single `file`, the tool now+ accepts `files[]` or a `glob` pattern and applies the intent across every match+ in one $0 call, returning a per-file + summary report. Paths are validated and+ contained to the project root; globs reject `..`; capped at 2000 files. Uses+ Node 22 `fs.globSync` (typed locally β `@types/node` here predates it).+2. **Scope-aware `var-to-const`** (`codemods/scope-analysis.ts`) β replaces+ file-global reassignment detection with function-scope resolution: a `var`+ becomes `const` unless *its own* binding is reassigned. A reassignment in an+ unrelated function no longer forces an unrelated `var` to `let`. Sound: it only+ ever errs toward `let`, never toward an incorrect `const`.+3. **Route-time dry-run** β when a target file is known, `route()` dry-runs the+ codemod and only emits `[CODEMOD_AVAILABLE]` if it actually changes something;+ a verified no-op falls through to model routing. With no file, it recommends+ Tier-1 best-effort (the executor verifies before writing).+4. **Measured benchmark + corpus guardrail** β `bench/codemod-corpus.json` (12+ golden cases) + `scripts/benchmark-codemods.mjs` measure correctness/latency and+ write a run JSON (cost-trend schema) to `docs/benchmarks/runs/codemod-*.json`.+ `__tests__/codemod-corpus.test.ts` fails CI on any regression vs golden.++## Verification++- `__tests__/codemod-engine.test.ts` β 23/23 (incl. 3 scope-aware cases);+ `__tests__/codemod-routing.test.ts` β 4/4 (dry-run gating);+ `__tests__/codemod-corpus.test.ts` β 13/13 (golden guardrail).+- Build clean (`tsc -b`); `__tests__/mcp-tools-deep.test.ts` (107) and+ `__tests__/router-bandit.test.ts` (8) still green.+- **Measured benchmark (12-case corpus, this host):** 100% correct (12/12),+ avg **0.55 ms/edit**, p99 **3.1 ms**, **$0** measured cost (no API call);+ estimated savings vs an LLM edit β $0.0024 (Haiku) / $0.036 (Sonnet) / $0.18+ (Opus) across the corpus.+- Manual end-to-end: router returns Tier-1 codemod for `convert var to const` on a+ file with `var`s (with edit count), falls through to Haiku on a no-op file, and+ best-effort Tier-1 with no file; `hooks_codemod` glob mode transforms a whole+ tree in one $0 call; refuses `add-types`.