@yasaswy.nagavolu/agents 0.26.7 → 0.26.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1597,12 +1597,20 @@
1597
1597
  {
1598
1598
  "path": "proxy/routing_post_hook.py",
1599
1599
  "kind": "hook",
1600
- "wiring": {
1601
- "event": "PostToolUse",
1602
- "matcher": "Agent",
1603
- "type": "command",
1604
- "command": "python ~/.claude/proxy/routing_post_hook.py"
1605
- }
1600
+ "wiring": [
1601
+ {
1602
+ "event": "PostToolUse",
1603
+ "matcher": "Agent",
1604
+ "type": "command",
1605
+ "command": "python ~/.claude/proxy/routing_post_hook.py"
1606
+ },
1607
+ {
1608
+ "event": "PostToolUseFailure",
1609
+ "matcher": "Agent",
1610
+ "type": "command",
1611
+ "command": "python ~/.claude/proxy/routing_post_hook.py"
1612
+ }
1613
+ ]
1606
1614
  },
1607
1615
  {
1608
1616
  "path": "proxy/routing_escalation_hook.py",
@@ -20,7 +20,8 @@ The guard stays. It owns what the mod cannot do: name injection, `agent_dispatch
20
20
 
21
21
  | Spawn | Model set |
22
22
  |---|---|
23
- | Fork, or a workflow-script agent | unchanged (the engine ignores a model for these) |
23
+ | Fork whose parent model is a `mainChat` family | denied: `fork would run on a main-chat model; dispatch a typed subagent` (rule `fork-main-chat`) |
24
+ | Any other fork, or a workflow-script agent | unchanged (the engine ignores a model for these) |
24
25
  | Registered agent with `role:` in a worker role | that role's id (+ `agentSuffix`) |
25
26
  | Registered agent with frontmatter `model:` and no `role:` | unchanged, unless that model or the requested one is a `mainChat` family (then worker) |
26
27
  | Requested model is a `mainChat` family (alias, id, any version) | worker |
@@ -37,7 +38,7 @@ The guard stays. It owns what the mod cannot do: name injection, `agent_dispatch
37
38
  ## Fail-safe
38
39
 
39
40
  - Any error (missing or corrupt `models.json`, a read failure) leaves the spawn unchanged and logs one
40
- `model-routing: left spawn unchanged: ...` line per 5 minutes. The mod never returns `deny`.
41
+ `model-routing: left spawn unchanged: ...` line per 5 minutes. The mod returns `deny` only for a fork on a main-chat parent; nothing else is ever denied.
41
42
  - An engine-level failure of the hook is skipped by the engine and the guard's alias still applies.
42
43
  - `models.json` is read at every spawn. A role edit applies to the next spawn of a running session.
43
44
  The mod itself loads at session start, so a new install needs a restart.
@@ -51,6 +52,7 @@ The guard stays. It owns what the mod cannot do: name injection, `agent_dispatch
51
52
  | Routing logic and hook wiring (node, no network) | `node --test mods/model-routing/tests/*.test.mjs` (also runs in pytest: `proxy/tests/test_model_routing_mod.py`) |
52
53
  | Headless proof with a real subagent per case | `python mods/model-routing/tests/e2e/run_e2e.py [--guard]` |
53
54
  | Headless proof of effort, role brief, re-route, escalation, ledger and audit | `python mods/model-routing/tests/e2e/run_routing_e2e.py [--no-mod]` |
55
+ | Headless proof of the fork rule (`CLAUDE_CODE_FORK_SUBAGENT=1`; main-chat parent denied, assistant parent allowed) | `python mods/model-routing/tests/e2e/run_routing_e2e.py --fork` |
54
56
  | Guard-vs-mod role drift | `python -m pytest proxy/tests/test_routing_drift.py` |
55
57
  | Engine tests with stubbed Claude answers (needs claude 2.1.287+) | `claude plugin test mods/model-routing` (`tests/*.test.ts`; also run by `tools/tests/test_mod_plugin_tests.py`) |
56
58
  | Plugin validate | `claude plugin validate mods/model-routing --strict` |
@@ -61,8 +63,8 @@ PreToolUse guard first.
61
63
 
62
64
  ## Records and handover
63
65
 
64
- - Every spawn leaves `~/.claude/logs/routing/mod/<tool_use_id>.json` (`$CLAUDE_ROUTING_MOD_DIR`): the type, name, requested model, the model the mod set (null when unchanged), the role and the rule. A write failure never blocks the spawn.
65
- - At `session.start` the mod writes `session-<session id>.json` (same directory): proof that it loaded in that session. A record write is retried once.
66
+ - Every spawn leaves `~/.claude/logs/routing/mod/<tool_use_id>.json` (`$CLAUDE_ROUTING_MOD_DIR`): the type, name, requested model, the model the mod set (null when unchanged), the role, the rule, `resolved` (the model the engine reports from the spawn result, absent when the spawn failed or was denied) and `fork: true` for a fork. The record is written after the spawn started. A write failure never blocks the spawn.
67
+ - At `session.start`, and again at the first spawn of a session id the mod has not beaten yet, the mod writes `session-<session id>.json` (same directory): proof that it loaded in that session, also for resumed sessions and `/clear` successors in a running process. A write is retried once; a failed heartbeat is tried again at the next spawn.
66
68
  - `proxy/routing_post_hook.py` (PostToolUse on Agent) reads that record. No record means the mod did not handle the dispatch; the hook then warns loudly and `agents-cli doctor` goes red. See `docs/model-routing.md` sections 8 and 9.
67
69
  - A prompt that starts with the guard's `[routing:role=<role>]` header sets the role first, so a guard re-route (assistant -> worker for a security task) survives the mod as last writer. Without the header the mod applies its own rules, which the shared table in `proxy/tests/routing_role_table.json` keeps equal to the guard's.
68
70
  - `effort` is set by the guard. Headless proof: with the mod loaded, a dispatch with no effort ran at `high` and a caller's `low` stayed `low` (the SubagentStop payload reports the subagent's effort level).
@@ -64,13 +64,22 @@ async function writeJson($, file, value) {
64
64
  return false
65
65
  }
66
66
 
67
- async function writeHeartbeat($) {
67
+ async function writeHeartbeat($, beaten) {
68
68
  const id = safeRecordId(await $.session.id())
69
- if (!id) return
70
- await writeJson($, (await recordDir($)) + '/session-' + id + '.json', { v: RECORD_VERSION, session_id: id, ts: await $.clock.now(), loaded: true })
69
+ if (!id || beaten.has(id)) return
70
+ const ok = await writeJson($, (await recordDir($)) + '/session-' + id + '.json', { v: RECORD_VERSION, session_id: id, ts: await $.clock.now(), loaded: true })
71
+ if (ok) beaten.add(id)
72
+ }
73
+
74
+ async function tryHeartbeat($, beaten) {
75
+ try {
76
+ await writeHeartbeat($, beaten)
77
+ } catch (err) {
78
+ await failOpen($, err)
79
+ }
71
80
  }
72
81
 
73
- async function writeRecord($, e, chosen, rule) {
82
+ async function writeRecord($, e, chosen, rule, resolved) {
74
83
  const id = safeRecordId(e.tool_use_id)
75
84
  if (!id) return
76
85
  try {
@@ -82,10 +91,12 @@ async function writeRecord($, e, chosen, rule) {
82
91
  subagent_type: e.subagentType,
83
92
  name: e.name || null,
84
93
  requested: e.model || null,
85
- set: chosen ? chosen.model : null,
86
- role: chosen ? chosen.role : null,
94
+ set: chosen && chosen.model ? chosen.model : null,
95
+ role: chosen && chosen.role ? chosen.role : null,
87
96
  rule,
88
97
  }
98
+ if (resolved) record.resolved = resolved
99
+ if (e.fork) record.fork = true
89
100
  await writeJson($, dir + '/' + id + '.json', record)
90
101
  } catch (err) {
91
102
  await failOpen($, err)
@@ -93,16 +104,14 @@ async function writeRecord($, e, chosen, rule) {
93
104
  }
94
105
 
95
106
  export function register(on) {
107
+ const beaten = new Set()
96
108
  on('session.start', async ($, e, next) => {
97
- try {
98
- await writeHeartbeat($)
99
- } catch (err) {
100
- await failOpen($, err)
101
- }
109
+ await tryHeartbeat($, beaten)
102
110
  return next(e)
103
111
  })
104
112
 
105
113
  on('agent.spawn', async ($, e, next) => {
114
+ await tryHeartbeat($, beaten)
106
115
  let chosen = null
107
116
  let rule = 'unchanged'
108
117
  try {
@@ -117,9 +126,21 @@ export function register(on) {
117
126
  rule = 'config-error'
118
127
  await failOpen($, err)
119
128
  }
120
- await writeRecord($, e, chosen, rule)
121
- if (!chosen) return next(e)
122
- $.ui.log(`model-routing: ${e.subagentType} ${e.model || 'unset'} -> ${chosen.model} (${chosen.rule})`)
123
- return next({ ...e, model: chosen.model })
129
+ if (chosen && chosen.deny) {
130
+ await writeRecord($, e, chosen, rule)
131
+ $.ui.log(`model-routing: ${e.subagentType} fork on ${e.parentModel} denied (${rule})`)
132
+ return { deny: chosen.deny }
133
+ }
134
+ const spawned = chosen ? { ...e, model: chosen.model } : e
135
+ if (chosen) $.ui.log(`model-routing: ${e.subagentType} ${e.model || 'unset'} -> ${chosen.model} (${chosen.rule})`)
136
+ let result
137
+ try {
138
+ result = await next(spawned)
139
+ } catch (err) {
140
+ await writeRecord($, e, chosen, rule)
141
+ throw err
142
+ }
143
+ await writeRecord($, e, chosen, rule, result && typeof result.model === 'string' ? result.model : null)
144
+ return result
124
145
  })
125
146
  }
@@ -65,9 +65,12 @@ export function agentFileNames(name) {
65
65
  return [`.claude/agents/${name}.md`, `.claude/agents/${name}.agent.md`, `.github/agents/${name}.md`, `.github/agents/${name}.agent.md`]
66
66
  }
67
67
 
68
- // Returns { model, role, rule } for the model to set, or null to leave the spawn unchanged.
68
+ export const FORK_DENY_REASON = 'fork would run on a main-chat model; dispatch a typed subagent'
69
+
70
+ // Returns { model, role, rule } for the model to set, { deny, rule } to refuse the spawn, or null to leave it unchanged.
69
71
  export function decide(cfg, spawn, registered) {
70
- if (!validConfig(cfg) || !spawn || spawn.fork || spawn.workflow) return null
72
+ if (!validConfig(cfg) || !spawn || spawn.workflow) return null
73
+ if (spawn.fork) return isMainChat(cfg, spawn.parentModel) ? { deny: FORK_DENY_REASON, rule: 'fork-main-chat' } : null
71
74
  const reg = registered && registered.found ? registered : null
72
75
  const pick = (role, rule) => ({ model: roleModel(cfg, role), role, rule })
73
76
 
@@ -6,6 +6,7 @@ Every sink (dispatch log, mod records, pending files, ledger) is redirected into
6
6
 
7
7
  python mods/model-routing/tests/e2e/run_routing_e2e.py full scenario
8
8
  python mods/model-routing/tests/e2e/run_routing_e2e.py --no-mod the mod is not loaded: proves the loud flag
9
+ python mods/model-routing/tests/e2e/run_routing_e2e.py --fork a fork on a main-chat parent is denied, a fork on the assistant parent is not
9
10
  """
10
11
  import json
11
12
  import os
@@ -37,6 +38,10 @@ FULL_PROMPT = (
37
38
  "and prompt 'Reply DONE.' Then print one line per call: name and the first line of its reply."
38
39
  )
39
40
 
41
+ FORK_PROMPT = (
42
+ "Make one Agent tool call: name f1, subagent_type fork, prompt 'Reply DONE.'. Then print its reply, or the error if the call was refused."
43
+ )
44
+
40
45
  NO_MOD_PROMPT = (
41
46
  "Make one Agent tool call: name m1, subagent_type general-purpose, prompt 'Reply DONE.'. Then print its reply."
42
47
  )
@@ -49,6 +54,7 @@ def settings(sandbox: Path) -> Path:
49
54
  data = {"hooks": {
50
55
  "PreToolUse": [{"matcher": "Agent", "hooks": [cmd(str(PROXY / "agent_model_guard.py"))]}],
51
56
  "PostToolUse": [{"matcher": "Agent", "hooks": [cmd(str(PROXY / "routing_post_hook.py"))]}],
57
+ "PostToolUseFailure": [{"matcher": "Agent", "hooks": [cmd(str(PROXY / "routing_post_hook.py"))]}],
52
58
  "SubagentStop": [{"hooks": [cmd(str(PROXY / "routing_escalation_hook.py")), cmd(str(HERE / "payload_probe.py"))]}],
53
59
  "Stop": [{"hooks": [cmd(str(PROXY / "routing_escalation_hook.py"))]}],
54
60
  }}
@@ -57,8 +63,10 @@ def settings(sandbox: Path) -> Path:
57
63
  return path
58
64
 
59
65
 
60
- def env_for(sandbox: Path, with_mod: bool) -> dict:
66
+ def env_for(sandbox: Path, with_mod: bool, fork: bool = False) -> dict:
61
67
  env = dict(os.environ)
68
+ if fork:
69
+ env["CLAUDE_CODE_FORK_SUBAGENT"] = "1"
62
70
  env.update({
63
71
  "CLAUDE_CODE_PLUGIN_DIRS": str(MOD) if with_mod else "",
64
72
  "CLAUDE_MODELS_CONFIG": str(CONFIG),
@@ -75,14 +83,14 @@ def env_for(sandbox: Path, with_mod: bool) -> dict:
75
83
  return env
76
84
 
77
85
 
78
- def run_claude(sandbox: Path, prompt: str, with_mod: bool) -> dict:
86
+ def run_claude(sandbox: Path, prompt: str, with_mod: bool, model: str | None = None, fork: bool = False) -> dict:
79
87
  project = sandbox / "proj"
80
88
  project.mkdir(exist_ok=True)
81
89
  cfg = json.loads(CONFIG.read_text(encoding="utf-8"))
82
- argv = [shutil.which("claude") or "claude", "-p", "--model", cfg["roles"]["assistant"], "--setting-sources", "project,local",
90
+ argv = [shutil.which("claude") or "claude", "-p", "--model", model or cfg["roles"]["assistant"], "--setting-sources", "project,local",
83
91
  "--settings", str(settings(sandbox)), "--permission-mode", "bypassPermissions", "--no-session-persistence",
84
92
  "--output-format", "json", "--debug-file", str(sandbox / "debug.log"), prompt]
85
- done = subprocess.run(argv, cwd=project, env=env_for(sandbox, with_mod), capture_output=True, text=True, timeout=1200, creationflags=CREATE_NO_WINDOW)
93
+ done = subprocess.run(argv, cwd=project, env=env_for(sandbox, with_mod, fork), capture_output=True, text=True, timeout=1200, creationflags=CREATE_NO_WINDOW)
86
94
  (sandbox / "result.json").write_text(done.stdout, encoding="utf-8")
87
95
  return json.loads(done.stdout) if done.stdout.strip() else {"result": "", "session_id": None, "stderr": done.stderr[-400:]}
88
96
 
@@ -139,12 +147,39 @@ def check_full(sandbox: Path, result: dict) -> list:
139
147
  resolved = jsonl(sandbox / "resolved.jsonl")
140
148
  need(all(r.get("subagent_type") for r in log), "a dispatch-log row has no subagent_type")
141
149
  need(len(resolved) >= 5 and all(r.get("model_source") == "mod" for r in resolved), "resolved rows are missing or not sourced from the mod")
150
+ sid = result["session_id"]
151
+ need((sandbox / "mod" / f"session-{sid}.json").exists(), "no session heartbeat was written")
152
+ records = [json.loads(f.read_text(encoding="utf-8")) for f in (sandbox / "mod").glob("toolu_*.json")]
153
+ need(records and all(r.get("resolved") for r in records), f"a mod record lacks the engine-resolved model: {records}")
154
+ need(all(r.get("model_source") == "mod" and r.get("engine_model") for r in resolved), "a resolved row lacks the engine model")
142
155
  done = audit(sandbox, result["session_id"])
143
156
  kinds = sorted({line.split()[1] for line in done.stdout.splitlines() if line.startswith("DISCREPANCY")})
144
157
  need(done.returncode == 1 and kinds == ["escalated"], f"audit expected exactly the 'escalated' discrepancy, got exit {done.returncode} {kinds}\n{done.stdout}")
145
158
  return problems
146
159
 
147
160
 
161
+ def check_fork(sandbox: Path, result: dict, denied: bool) -> list:
162
+ problems = []
163
+ records = [json.loads(f.read_text(encoding="utf-8")) for f in (sandbox / "mod").glob("toolu_*.json")]
164
+ forks = [r for r in records if r.get("fork")]
165
+ if not forks:
166
+ return [f"no fork spawn reached the mod (records: {records}); the harness could not drive a fork"]
167
+ rule = "fork-main-chat" if denied else "unchanged"
168
+ if forks[0].get("rule") != rule:
169
+ problems.append(f"fork rule is {forks[0].get('rule')!r}, expected {rule!r}")
170
+ verdicts = [r["verdict"] for r in ledger(sandbox) if r.get("record_type") == "routing"]
171
+ if denied and "fork_main_chat" not in verdicts:
172
+ problems.append(f"no fork_main_chat ledger verdict: {verdicts}")
173
+ if not denied and verdicts != ["routed"]:
174
+ problems.append(f"fork on the assistant parent should be routed: {verdicts}")
175
+ done = audit(sandbox, result["session_id"])
176
+ if denied and "fork_main_chat" not in done.stdout:
177
+ problems.append(f"audit did not report fork_main_chat: {done.stdout}")
178
+ if not denied and done.returncode != 0:
179
+ problems.append(f"audit not clean for the allowed fork: {done.stdout}")
180
+ return problems
181
+
182
+
148
183
  def check_no_mod(sandbox: Path, result: dict) -> list:
149
184
  problems = []
150
185
  flag = sandbox / "mod_unhandled.json"
@@ -165,7 +200,27 @@ def check_no_mod(sandbox: Path, result: dict) -> list:
165
200
  return problems
166
201
 
167
202
 
203
+ def run_fork_scenarios() -> int:
204
+ cfg = json.loads(CONFIG.read_text(encoding="utf-8"))
205
+ failed = False
206
+ for label, model, denied in (("main-chat parent", cfg["mainChat"]["opus"], True), ("assistant parent", cfg["roles"]["assistant"], False)):
207
+ sandbox = Path(tempfile.mkdtemp(prefix="routing-e2e-fork-"))
208
+ result = run_claude(sandbox, FORK_PROMPT, True, model, True)
209
+ if not result.get("session_id"):
210
+ print("claude run failed:", result)
211
+ return 1
212
+ problems = check_fork(sandbox, result, denied)
213
+ print(json.dumps({"mode": f"fork/{label}", "sandbox": str(sandbox), "answer": result.get("result", "")[:300]}, indent=1))
214
+ for p in problems:
215
+ print("FAIL", p)
216
+ failed = failed or bool(problems)
217
+ print("FAILED" if failed else "PASS")
218
+ return 1 if failed else 0
219
+
220
+
168
221
  def main(argv: list) -> int:
222
+ if "--fork" in argv:
223
+ return run_fork_scenarios()
169
224
  with_mod = "--no-mod" not in argv
170
225
  sandbox = Path(tempfile.mkdtemp(prefix="routing-e2e-"))
171
226
  result = run_claude(sandbox, FULL_PROMPT if with_mod else NO_MOD_PROMPT, with_mod)
@@ -138,18 +138,34 @@ test('live read: a changed config applies on the next spawn', async () => {
138
138
  assert.equal((await spawn(e())).seen.model, 'w-model-2[1m]')
139
139
  })
140
140
 
141
- test('never denies, whatever the input', async () => {
141
+ test('never denies a non-fork, whatever the input', async () => {
142
142
  const { spawn } = harness({ files: FILES })
143
- for (const o of [{}, { model: 'opus' }, { subagentType: 'Explore' }, { fork: true }, { workflow: { runId: 'wf_1', agentIndex: 1 } }]) {
143
+ for (const o of [{}, { model: 'opus' }, { subagentType: 'Explore' }, { fork: true }, { fork: true, parentModel: 'w-model-1[1m]' }, { workflow: { runId: 'wf_1', agentIndex: 1 } }]) {
144
144
  const { res } = await spawn(e(o))
145
145
  assert.equal(res.deny, undefined)
146
146
  }
147
147
  })
148
148
 
149
- test('forks and workflow agents are passed through untouched', async () => {
150
- const { spawn } = harness({ files: FILES })
151
- const fork = e({ fork: true, model: 'opus' })
149
+ test('a fork on a main-chat parent is denied with a record, the fork flag and no downstream call', async () => {
150
+ const { spawn, writes, logs } = harness({ files: FILES })
151
+ const { seen, res } = await spawn(e({ tool_use_id: 'toolu_F1', fork: true, subagentType: 'fork', parentModel: 'big-opus-9-9[1m]' }))
152
+ assert.equal(seen, null)
153
+ assert.deepEqual(res, { deny: 'fork would run on a main-chat model; dispatch a typed subagent' })
154
+ const rec = JSON.parse(writes['C:/home/.claude/logs/routing/mod/toolu_F1.json'])
155
+ assert.deepEqual({ rule: rec.rule, set: rec.set, role: rec.role, fork: rec.fork, resolved: rec.resolved }, { rule: 'fork-main-chat', set: null, role: null, fork: true, resolved: undefined })
156
+ assert.equal(logs.length, 1)
157
+ })
158
+
159
+ test('a fork on a worker parent passes through untouched and is recorded as a fork', async () => {
160
+ const { spawn, writes } = harness({ files: FILES })
161
+ const fork = e({ tool_use_id: 'toolu_F2', fork: true, model: 'opus', parentModel: 'w-model-1[1m]' })
152
162
  assert.deepEqual((await spawn(fork)).seen, fork)
163
+ const rec = JSON.parse(writes['C:/home/.claude/logs/routing/mod/toolu_F2.json'])
164
+ assert.deepEqual({ rule: rec.rule, set: rec.set, fork: rec.fork }, { rule: 'unchanged', set: null, fork: true })
165
+ })
166
+
167
+ test('workflow agents are passed through untouched', async () => {
168
+ const { spawn } = harness({ files: FILES })
153
169
  const wf = e({ workflow: { runId: 'wf_1', agentIndex: 1 } })
154
170
  assert.deepEqual((await spawn(wf)).seen, wf)
155
171
  })
@@ -183,7 +199,7 @@ test('a bad config is recorded as config-error and the spawn still runs', async
183
199
  test('CLAUDE_ROUTING_MOD_DIR redirects the records', async () => {
184
200
  const { spawn, writes } = harness({ files: FILES, env: { CLAUDE_ROUTING_MOD_DIR: '/tmp/rec' } })
185
201
  await spawn(e({ tool_use_id: 'toolu_D1' }))
186
- assert.deepEqual(Object.keys(writes), ['/tmp/rec/toolu_D1.json'])
202
+ assert.deepEqual(Object.keys(writes).sort(), ['/tmp/rec/session-sess-9.json', '/tmp/rec/toolu_D1.json'])
187
203
  })
188
204
 
189
205
  test('a record write failure never blocks or changes the spawn', async () => {
@@ -197,7 +213,7 @@ test('a missing or unsafe tool_use_id writes no record', async () => {
197
213
  const { spawn, writes } = harness({ files: FILES })
198
214
  await spawn(e({ tool_use_id: undefined }))
199
215
  await spawn(e({ tool_use_id: '../escape' }))
200
- assert.deepEqual(writes, {})
216
+ assert.deepEqual(Object.keys(writes), ['C:/home/.claude/logs/routing/mod/session-sess-9.json'])
201
217
  })
202
218
 
203
219
  test('the guard header role wins over the mod rules (re-route survives the last writer)', async () => {
@@ -228,9 +244,50 @@ test('a failing heartbeat write never blocks session start', async () => {
228
244
  assert.deepEqual(out, { passed: event })
229
245
  })
230
246
 
247
+ test('the first spawn writes the heartbeat when session.start never ran, once per session', async () => {
248
+ const { spawn, writes } = harness({ files: FILES })
249
+ await spawn(e({ tool_use_id: 'toolu_H1' }))
250
+ const beat = 'C:/home/.claude/logs/routing/mod/session-sess-9.json'
251
+ assert.equal(JSON.parse(writes[beat]).loaded, true)
252
+ delete writes[beat]
253
+ await spawn(e({ tool_use_id: 'toolu_H2' }))
254
+ assert.equal(writes[beat], undefined)
255
+ })
256
+
257
+ test('session.start then a spawn writes the heartbeat once', async () => {
258
+ const { handlers, spawn, writes, $, h } = harness({ files: FILES })
259
+ await handlers['session.start']($, {}, async (x) => x)
260
+ const before = h.attempts
261
+ await spawn(e({ tool_use_id: 'toolu_H3' }))
262
+ assert.equal(h.attempts - before, 1)
263
+ assert.ok(writes['C:/home/.claude/logs/routing/mod/session-sess-9.json'])
264
+ })
265
+
266
+ test('a failed heartbeat is retried on the next spawn and never blocks the spawn', async () => {
267
+ const { spawn, h } = harness({ files: FILES, failFirstWrites: 2 })
268
+ const { seen } = await spawn(e({ tool_use_id: 'toolu_H4', model: 'opus' }))
269
+ assert.equal(seen.model, 'w-model-1[1m]')
270
+ await spawn(e({ tool_use_id: 'toolu_H5' }))
271
+ assert.ok(h.attempts >= 4)
272
+ })
273
+
274
+ test('the record carries the model the engine resolved from next()', async () => {
275
+ const { spawn, writes } = harness({ files: FILES })
276
+ await spawn(e({ tool_use_id: 'toolu_V1', model: 'opus' }))
277
+ assert.equal(JSON.parse(writes['C:/home/.claude/logs/routing/mod/toolu_V1.json']).resolved, 'w-model-1[1m]')
278
+ })
279
+
280
+ test('a downstream failure still leaves a record and is rethrown', async () => {
281
+ const { handlers, writes, $ } = harness({ files: FILES })
282
+ await assert.rejects(handlers['agent.spawn']($, e({ tool_use_id: 'toolu_X1' }), async () => { throw new Error('boom') }), /boom/)
283
+ const rec = JSON.parse(writes['C:/home/.claude/logs/routing/mod/toolu_X1.json'])
284
+ assert.equal(rec.resolved, undefined)
285
+ assert.equal(rec.rule, 'default')
286
+ })
287
+
231
288
  test('a record write that fails once is retried and lands', async () => {
232
289
  const { spawn, writes, h } = harness({ files: FILES, failFirstWrites: 1 })
233
290
  await spawn(e({ tool_use_id: 'toolu_R1', model: 'opus' }))
234
- assert.equal(h.attempts, 2)
291
+ assert.equal(h.attempts, 3)
235
292
  assert.ok(writes['C:/home/.claude/logs/routing/mod/toolu_R1.json'])
236
293
  })
@@ -1,7 +1,7 @@
1
1
  import test from 'node:test'
2
2
  import assert from 'node:assert/strict'
3
3
  import { readFileSync } from 'node:fs'
4
- import { decide, parseFrontmatter, isMainChat, agentFileNames, baseId } from '../lib/route.mjs'
4
+ import { decide, FORK_DENY_REASON, parseFrontmatter, isMainChat, agentFileNames, baseId } from '../lib/route.mjs'
5
5
 
6
6
  const CFG = {
7
7
  roles: { worker: 'w-model-1', assistant: 'a-model-1' },
@@ -64,8 +64,17 @@ test('registered agent with neither role nor model follows the unregistered rule
64
64
  assert.equal(decide(CFG, spawn({ subagentType: 'x' }), { found: true, role: '', model: '' }).role, 'worker')
65
65
  })
66
66
 
67
- test('forks, workflow agents and bad config leave the spawn unchanged', () => {
67
+ test('a fork whose parent is a main-chat model is denied, any other fork is left alone', () => {
68
+ assert.deepEqual(decide(CFG, spawn({ fork: true, parentModel: 'big-opus-9-9[1m]' }), none), { deny: FORK_DENY_REASON, rule: 'fork-main-chat' })
69
+ assert.equal(decide(CFG, spawn({ fork: true, parentModel: 'fable' }), none).rule, 'fork-main-chat')
70
+ assert.equal(decide(CFG, spawn({ fork: true, parentModel: 'w-model-1[1m]' }), none), null)
71
+ assert.equal(decide(CFG, spawn({ fork: true, parentModel: 'a-model-1' }), none), null)
68
72
  assert.equal(decide(CFG, spawn({ fork: true }), none), null)
73
+ assert.equal(decide(CFG, spawn({ fork: true, parentModel: 'opus', workflow: { runId: 'wf_1', agentIndex: 1 } }), none), null)
74
+ assert.equal(decide({ roles: {} }, spawn({ fork: true, parentModel: 'opus' }), none), null)
75
+ })
76
+
77
+ test('workflow agents and bad config leave the spawn unchanged', () => {
69
78
  assert.equal(decide(CFG, spawn({ workflow: { runId: 'wf_1', agentIndex: 1 } }), none), null)
70
79
  for (const bad of [null, undefined, {}, { roles: {} }, 'x', { roles: { assistant: 'a' } }]) assert.equal(decide(bad, spawn(), none), null)
71
80
  assert.equal(decide(CFG, null, none), null)
@@ -77,7 +86,7 @@ test('a role missing from workerRoles is never chosen by request or type', () =>
77
86
  assert.equal(decide(cfg, spawn({ model: 'haiku' }), none).role, 'worker')
78
87
  })
79
88
 
80
- test('never denies: result has only model, role, rule', () => {
89
+ test('a non-fork spawn is never denied: result has only model, role, rule', () => {
81
90
  assert.deepEqual(Object.keys(decide(CFG, spawn(), none)).sort(), ['model', 'role', 'rule'])
82
91
  })
83
92
 
@@ -506,8 +506,8 @@ def _safe_main() -> None:
506
506
  corrected["prompt"] = new_prompt
507
507
  defaults_applied = True
508
508
 
509
- # loud, repeated until a later dispatch is handled by the model-routing mod again
510
- unhandled = routing_log.read_unhandled_flag()
509
+ # this session's own unhandled count, until one of its dispatches is handled by the model-routing mod again
510
+ unhandled = routing_log.read_unhandled_flag(str(data.get("session_id") or ""))
511
511
  if unhandled and routing_log.mod_installed() and routing_log.warn_once(str(data.get("session_id") or "")):
512
512
  notes.append(routing_log.unhandled_warning(unhandled))
513
513
 
@@ -12,6 +12,8 @@ Discrepancy kinds:
12
12
  no_ledger_event dispatch in the log with no `routing` event in the ledger
13
13
  no_mod_record the mod did not handle the dispatch (not loaded, load error, old Claude Code)
14
14
  role_model_mismatch the model the mod set (else the guard's) is not the model of the dispatch's role
15
+ engine_model_mismatch the model the engine resolved is not the one the mod set (a main-chat model, or another role's)
16
+ fork_main_chat a fork on a main-chat parent model was attempted; the mod denied it
15
17
  role_mismatch the dispatch's role is not the role the shared role table gives its type and request
16
18
  no_header no role brief was applied where models.json defines one
17
19
  bad_effort effort missing or not one of the Agent enum
@@ -78,6 +80,13 @@ def audit_session(session_id: str, cfg: dict | None = None) -> tuple[int, list[d
78
80
  add(row, "role_model_mismatch", f"mod set {set_model}, role {role} is {role_id}")
79
81
  elif not set_model and row.get("model") and role_id and models_config.base_id(row["model"]) != models_config.base_id(role_id):
80
82
  add(row, "role_model_mismatch", f"guard logged {row['model']}, role {role} is {role_id}")
83
+ resolved = (mod or {}).get("resolved")
84
+ if set_model and resolved and not (mod or {}).get("fork"):
85
+ got = models_config.role_for_model(cfg, resolved)
86
+ if models_config.is_main_chat_model(cfg, resolved) or (got and got != models_config.role_for_model(cfg, set_model)):
87
+ add(row, "engine_model_mismatch", f"mod set {set_model}, the engine resolved {resolved}")
88
+ if (mod or {}).get("rule") == "fork-main-chat":
89
+ add(row, "fork_main_chat", "a fork on a main-chat model was denied; dispatch a typed subagent")
81
90
  if cfg and row.get("registered") is False:
82
91
  want = expected_role(cfg, row.get("subagent_type") or "", row.get("requested_model"), row.get("reroute"))
83
92
  if want and role and want != role:
@@ -13,6 +13,7 @@ import time
13
13
 
14
14
  RECORD_ID_RE = re.compile(r"^[A-Za-z0-9_-]+$")
15
15
  MOD_RECORD_MAX_AGE_S = 14 * 86400
16
+ FLAG_TTL_S = 86400
16
17
 
17
18
 
18
19
  def _ledger():
@@ -213,40 +214,102 @@ def unhandled_flag_path() -> str:
213
214
  return os.environ.get("CLAUDE_ROUTING_FLAG") or os.path.join(_claude_dir(), "logs", "routing", "mod_unhandled.json")
214
215
 
215
216
 
216
- def read_unhandled_flag() -> dict | None:
217
+ def _flag_sessions() -> dict:
218
+ """The flag file as {session_id: entry}; a pre-0.26.8 file (one global entry) reads as a single session."""
217
219
  try:
218
220
  with open(unhandled_flag_path(), "r", encoding="utf-8") as fh:
219
221
  flag = json.load(fh)
220
- return flag if isinstance(flag, dict) else None
221
222
  except (OSError, ValueError):
222
- return None
223
+ return {}
224
+ if not isinstance(flag, dict):
225
+ return {}
226
+ if isinstance(flag.get("sessions"), dict):
227
+ return {k: v for k, v in flag["sessions"].items() if isinstance(v, dict)}
228
+ return {str(flag.get("session_id") or "unknown"): flag} if flag.get("count") else {}
223
229
 
224
230
 
225
- def write_unhandled_flag(session_id: str, name: str, tool_use_id: str, state: str = "not_loaded") -> None:
231
+ def _store_flag_sessions(sessions: dict) -> None:
226
232
  path = unhandled_flag_path()
227
- prior = read_unhandled_flag() or {}
228
233
  try:
234
+ if not sessions:
235
+ os.remove(path)
236
+ return
229
237
  os.makedirs(os.path.dirname(path), exist_ok=True)
230
- with open(path, "w", encoding="utf-8") as fh:
231
- json.dump({"ts": time.time(), "session_id": session_id, "name": name, "tool_use_id": tool_use_id,
232
- "count": int(prior.get("count") or 0) + 1, "state": state}, fh)
238
+ tmp = f"{path}.{os.getpid()}.tmp"
239
+ with open(tmp, "w", encoding="utf-8") as fh:
240
+ json.dump({"sessions": sessions}, fh)
241
+ os.replace(tmp, path)
233
242
  except OSError:
234
243
  pass
235
244
 
236
245
 
237
- def clear_unhandled_flag() -> None:
246
+ def read_unhandled_flag(session_id: str) -> dict | None:
247
+ """This session's own unhandled-dispatch entry, or None."""
248
+ return _flag_sessions().get(session_id)
249
+
250
+
251
+ def write_unhandled_flag(session_id: str, name: str, tool_use_id: str, state: str = "not_loaded", predates_mod: bool | None = None) -> None:
252
+ sessions = _flag_sessions()
253
+ now = time.time()
254
+ sessions = {k: v for k, v in sessions.items() if now - float(v.get("ts") or 0) < FLAG_TTL_S}
255
+ prior = sessions.get(session_id) or {}
256
+ sessions[session_id] = {"ts": now, "name": name, "tool_use_id": tool_use_id, "state": state,
257
+ "count": int(prior.get("count") or 0) + 1, "predates_mod": predates_mod}
258
+ _store_flag_sessions(sessions)
259
+
260
+
261
+ def clear_unhandled_flag(session_id: str) -> None:
262
+ sessions = _flag_sessions()
263
+ if session_id in sessions:
264
+ del sessions[session_id]
265
+ _store_flag_sessions(sessions)
266
+
267
+
268
+ def claude_process_start() -> float | None:
269
+ """Start time (epoch s) of the Claude process hosting this hook: the nearest ancestor named claude or node."""
270
+ override = os.environ.get("CLAUDE_ROUTING_PROCESS_START")
271
+ if override:
272
+ try:
273
+ return float(override)
274
+ except ValueError:
275
+ return None
238
276
  try:
239
- os.remove(unhandled_flag_path())
277
+ import psutil
278
+
279
+ proc = psutil.Process(os.getppid())
280
+ for _ in range(8):
281
+ if proc.name().lower().removesuffix(".exe") in ("claude", "node"):
282
+ return proc.create_time()
283
+ proc = proc.parent()
284
+ if proc is None:
285
+ return None
286
+ except Exception:
287
+ return None
288
+ return None
289
+
290
+
291
+ def mod_install_time() -> float | None:
292
+ try:
293
+ return os.path.getmtime(os.path.join(mod_install_dir(), ".claude-plugin", "plugin.json"))
240
294
  except OSError:
241
- pass
295
+ return None
296
+
297
+
298
+ def process_predates_mod() -> bool | None:
299
+ """True when the hosting Claude process started before the mod files were last written (mods load only at process start); None when unknown."""
300
+ started, installed = claude_process_start(), mod_install_time()
301
+ return None if started is None or installed is None else started < installed - 1.0
242
302
 
243
303
 
244
- def unhandled_warning(flag: dict) -> str:
245
- if flag.get("state") == "loaded_no_record":
304
+ def unhandled_warning(entry: dict) -> str:
305
+ n = entry.get("count", 1)
306
+ head = f"ROUTING MOD NOT ACTIVE: {n} dispatch(es) in this session, last '{entry.get('name')}', were not handled by the model-routing mod: "
307
+ if entry.get("predates_mod"):
308
+ return (head + "this process started before the mod was installed. Restart it; /clear does not load mods. "
309
+ "Models fall back to the guard's alias only.")
310
+ if entry.get("state") == "loaded_no_record":
246
311
  cause = ("the mod IS loaded in this session but left no record for the spawn (its hook was skipped, e.g. a plugin reload, "
247
312
  "or the record write failed)")
248
313
  else:
249
314
  cause = "the mod is not loaded in this session (not loaded, load error, or Claude Code older than 2.1.289)"
250
- return (f"ROUTING MOD NOT ACTIVE: {flag.get('count', 1)} dispatch(es), last '{flag.get('name')}', were not handled by the "
251
- f"model-routing mod: {cause}. Models fall back to the guard's alias only. "
252
- "Run `agents-cli doctor` and restart the session after fixing it.")
315
+ return head + f"{cause}. Models fall back to the guard's alias only. Run `agents-cli doctor` and restart the session after fixing it."
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env python3
2
2
  """
3
- routing_post_hook.py — PostToolUse observer for Agent dispatches. After the guard (PreToolUse)
3
+ routing_post_hook.py — PostToolUse observer for Agent dispatches (plus PostToolUseFailure, read only for a fork the mod denied). After the guard (PreToolUse)
4
4
  and the model-routing mod (agent.spawn) ran, it reconciles the three records of one dispatch:
5
5
 
6
6
  guard row agent_dispatch.jsonl, keyed by tool_use_id (role, effort, header, re-route)
@@ -9,7 +9,8 @@ and the model-routing mod (agent.spawn) ran, it reconciles the three records of
9
9
 
10
10
  and appends a row to logs/routing/resolved.jsonl (never to agent_dispatch.jsonl; the model the mod actually set, else the
11
11
  requested one, plus the effort). When the mod did not handle the dispatch it answers with a loud
12
- additionalContext and leaves a flag the guard repeats until a handled dispatch clears it.
12
+ additionalContext and leaves a per-session flag entry that a handled dispatch of the same session clears.
13
+ A fork has no routable model: its row carries the engine-resolved one, and a fork the mod denied is a `fork_main_chat` verdict.
13
14
 
14
15
  Diagnostic, never blocking: any error is swallowed and the hook exits 0.
15
16
  """
@@ -27,26 +28,38 @@ import routing_log
27
28
 
28
29
 
29
30
  def reconcile(payload: dict) -> dict | None:
30
- """Do the bookkeeping for one Agent PostToolUse payload. Returns the hook output, or None."""
31
+ """Do the bookkeeping for one Agent PostToolUse (or, for a denied fork, PostToolUseFailure) payload. Returns the hook output, or None."""
31
32
  tool_use_id = payload.get("tool_use_id") or ""
32
33
  session_id = payload.get("session_id") or ""
33
34
  if not tool_use_id or not session_id:
34
35
  return None
36
+ failed = payload.get("hook_event_name") == "PostToolUseFailure"
35
37
  guard = routing_log.guard_row(tool_use_id) or {}
36
- mod = routing_log.wait_for_mod_record(tool_use_id)
38
+ mod = routing_log.read_mod_record(tool_use_id) if failed else routing_log.wait_for_mod_record(tool_use_id)
39
+ if failed and (mod or {}).get("rule") != "fork-main-chat":
40
+ return None
37
41
  state = "handled" if mod is not None else ("loaded_no_record" if routing_log.mod_loaded_in_session(session_id) else "not_loaded")
38
42
  response = payload.get("tool_response") if isinstance(payload.get("tool_response"), dict) else {}
39
43
  name = guard.get("name") or (payload.get("tool_input") or {}).get("name")
40
44
  handled = mod is not None
41
45
  mod_set = (mod or {}).get("set")
46
+ mod_resolved = (mod or {}).get("resolved")
47
+ fork = bool((mod or {}).get("fork"))
42
48
  requested = guard.get("requested_model")
43
- model, source = (mod_set, "mod") if mod_set else ((guard.get("model"), "guard") if guard.get("model") else (requested, "requested"))
49
+ if fork:
50
+ model, source = (mod_resolved, "engine") if mod_resolved else (None, "fork")
51
+ elif mod_set:
52
+ model, source = mod_set, "mod"
53
+ else:
54
+ model, source = (guard.get("model"), "guard") if guard.get("model") else (requested, "requested")
55
+ verdict = "fork_main_chat" if (mod or {}).get("rule") == "fork-main-chat" else ("routed" if handled else "mod_not_handled")
56
+ predates = None if handled else routing_log.process_predates_mod()
44
57
 
45
58
  routing_log.append_resolved_row({
46
59
  "kind": "resolved", "ts": time.time(), "session_id": session_id, "tool_use_id": tool_use_id, "name": name,
47
- "model": model, "model_source": source, "effort": guard.get("effort"), "mod_handled": handled,
60
+ "model": model, "model_source": source, "effort": guard.get("effort"), "mod_handled": handled, "engine_model": mod_resolved,
48
61
  })
49
- routing_log.append_ledger_event(session_id, "routing", "routed" if handled else "mod_not_handled", {
62
+ routing_log.append_ledger_event(session_id, "routing", verdict, {
50
63
  "project": payload.get("cwd"),
51
64
  "agent_id": response.get("agentId"),
52
65
  "agent_name": name,
@@ -58,8 +71,11 @@ def reconcile(payload: dict) -> dict | None:
58
71
  "guard_model": guard.get("model"),
59
72
  "mod_set": mod_set,
60
73
  "mod_rule": (mod or {}).get("rule"),
74
+ "mod_resolved": mod_resolved,
75
+ "fork": fork,
61
76
  "mod_handled": handled,
62
77
  "mod_state": state,
78
+ "mod_predates_install": predates,
63
79
  "effort": guard.get("effort"),
64
80
  "header": guard.get("header"),
65
81
  "reroute": guard.get("reroute"),
@@ -67,15 +83,15 @@ def reconcile(payload: dict) -> dict | None:
67
83
  routing_log.prune_mod_records()
68
84
 
69
85
  if handled:
70
- routing_log.clear_unhandled_flag()
86
+ routing_log.clear_unhandled_flag(session_id)
71
87
  return None
72
88
  if not routing_log.mod_installed():
73
89
  return None
74
- routing_log.write_unhandled_flag(session_id, str(name), tool_use_id, state)
90
+ routing_log.write_unhandled_flag(session_id, str(name), tool_use_id, state, predates)
75
91
  if not routing_log.warn_once(session_id):
76
92
  return None
77
- flag = routing_log.read_unhandled_flag() or {"count": 1, "name": name}
78
- return {"hookSpecificOutput": {"hookEventName": "PostToolUse", "additionalContext": routing_log.unhandled_warning(flag)}}
93
+ flag = routing_log.read_unhandled_flag(session_id) or {"count": 1, "name": name, "state": state, "predates_mod": predates}
94
+ return {"hookSpecificOutput": {"hookEventName": payload.get("hook_event_name"), "additionalContext": routing_log.unhandled_warning(flag)}}
79
95
 
80
96
 
81
97
  def _safe_main() -> None:
@@ -83,7 +99,7 @@ def _safe_main() -> None:
83
99
  payload = json.loads(sys.stdin.read() or "{}")
84
100
  except ValueError:
85
101
  return
86
- if not isinstance(payload, dict) or payload.get("hook_event_name") != "PostToolUse" or payload.get("tool_name") != "Agent":
102
+ if not isinstance(payload, dict) or payload.get("hook_event_name") not in ("PostToolUse", "PostToolUseFailure") or payload.get("tool_name") != "Agent":
87
103
  return
88
104
  out = reconcile(payload)
89
105
  if out:
@@ -29,6 +29,14 @@ function readJson(file) {
29
29
  }
30
30
  }
31
31
 
32
+ const FLAG_TTL_MS = 24 * 60 * 60 * 1000;
33
+
34
+ function unhandledEntries(flag, now) {
35
+ if (!flag || typeof flag !== 'object') return [];
36
+ const all = flag.sessions && typeof flag.sessions === 'object' ? Object.values(flag.sessions) : flag.count ? [flag] : [];
37
+ return all.filter((e) => e && typeof e === 'object' && (!e.ts || now - e.ts * 1000 < FLAG_TTL_MS));
38
+ }
39
+
32
40
  /**
33
41
  * Is the model-routing mod installed, byte-identical to the repo copy, wired into
34
42
  * settings.json, and free of the guard's "mod did not handle a dispatch" flag?
@@ -59,13 +67,18 @@ function checkRoutingMod({ manifest, repoRoot, targetBase, env = process.env })
59
67
  return { status: 'not-wired', line: `routing mod: installed but missing from env.${PLUGIN_DIRS_ENV} in settings.json; run \`agents-cli update\``, details: [] };
60
68
  }
61
69
  const flagFile = env.CLAUDE_ROUTING_FLAG || path.join(targetBase, 'logs', 'routing', 'mod_unhandled.json');
62
- const flag = readJson(flagFile);
63
- if (flag) {
70
+ const entries = unhandledEntries(readJson(flagFile), Date.now());
71
+ if (entries.length > 0) {
72
+ const count = entries.reduce((n, e) => n + (e.count || 1), 0);
73
+ const last = entries.reduce((a, b) => ((b.ts || 0) >= (a.ts || 0) ? b : a));
74
+ const cause = last.predates_mod
75
+ ? 'that process started before the mod was installed'
76
+ : last.state === 'loaded_no_record'
77
+ ? 'the mod was loaded but its spawn hook was skipped or its record write failed'
78
+ : 'the mod was not loaded in that session';
64
79
  return {
65
80
  status: 'unhandled',
66
- line: `routing mod: ${flag.count || 1} dispatch(es) were not handled by the mod (last: ${flag.name}; ${
67
- flag.state === 'loaded_no_record' ? 'the mod was loaded but its spawn hook was skipped or its record write failed' : 'the mod was not loaded in that session'
68
- }); restart the session after fixing the install`,
81
+ line: `routing mod: ${count} dispatch(es) in ${entries.length} session(s) were not handled by the mod (last: ${last.name}; ${cause}); restart the session after fixing the install`,
69
82
  details: [],
70
83
  };
71
84
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yasaswy.nagavolu/agents",
3
- "version": "0.26.7",
3
+ "version": "0.26.8",
4
4
  "description": "CLI for installing the yasaswy.nagavolu agent/skill/hook bundle. `install` opens an interactive bundle menu in a TTY (or `--bundle <key> --yes` for non-interactive installs), with hash-tracked idempotent deploys, automatic hook wiring into settings.json, and masked secret prompting. `update` reconciles installed bundles against the current source (hash-tracked: silent overwrite, conflict diff+prompt, or --theirs/--keep-mine). `uninstall` removes a bundle's files and wiring. `secrets` re-runs secret prompting for already-installed bundles.",
5
5
  "license": "MIT",
6
6
  "type": "commonjs",