@yasaswy.nagavolu/agents 0.26.3 → 0.26.4

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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "handoff",
3
- "version": "0.3.2",
3
+ "version": "0.3.3",
4
4
  "description": "One-click session handoff: prepares the work, writes a lean handoff file, verifies it, clears the session and submits the handoff as the first message",
5
5
  "author": { "name": "Yasaswy Nagavolu" },
6
6
  "metadata": { "minClaudeCodeVersion": "2.1.287" }
@@ -28,27 +28,27 @@ an unattended session's prompt cache warm. Needs Claude Code 2.1.287 or later (m
28
28
  chord shows the toast `handoff already running (<phase>)` and starts nothing.
29
29
  - Busy chat (a turn runs, a user prompt waits, or a nudge is in flight): the handoff queues. The band reads
30
30
  `Handoff queued: waiting for the current turn to finish...` with a `Cancel` button. The prep prompt is submitted
31
- when the turn ends (or at the next keep-warm tick), after the running-work gate runs again.
31
+ when the turn ends (or at the next keep-warm tick), and the running-work note shows then.
32
32
  - The prep prompt opens with `[Handoff prep - this is not the handoff itself]` and a one-line note, so the
33
33
  chat shows it is not the handoff. The label is added by code (`lib/prep.mjs`), not by the prompt file.
34
34
  - The prep reply is the turn whose start text carries that label and this session's handoff path; only its turn id
35
35
  is scored, so an earlier queued message or nudge cannot cause "no HANDOFF_READY line". A prep that never starts aborts after 30 min.
36
36
  - Phase A: `prompts/handoff-prep.md` syncs tasks and PRD, fixes docs, runs tests, commits and pushes,
37
37
  writes `~/.claude/handoffs/<session_id>.md`, then prints `HANDOFF_READY <path>` or `HANDOFF_ABORT <reason>`.
38
- - Phase B (turn complete): sentinel, `lib/validate.mjs`, git gate (`lib/gitgate.mjs`), running-work gate.
38
+ - Phase B (turn complete): sentinel, `lib/validate.mjs`, git gate (`lib/gitgate.mjs`).
39
39
  Only then: clipboard, `/clear`, submit the handoff. Any failed check keeps the session and the file.
40
40
  - Git gate: no dirty tracked files, and nothing unpushed. With an upstream it counts `@{upstream}..HEAD`.
41
41
  Without one (or on a detached HEAD) it counts commits not on the remote default branch (`origin/HEAD`,
42
42
  else `origin/main`, else `origin/master`). A repo with a remote but no resolvable default branch aborts;
43
43
  a repo with no remote, or no repo at all, passes.
44
- - Running-work gate: before Phase A and again before `/clear`, the mod counts running subagents (`$.agent.list()`, live) and background
45
- tasks (the `background_tasks` of the last `classic.Stop`, a snapshot: if stale, send any message and retry). Any running work aborts with a
46
- toast and log line; it never stops anything. Step 0 of `prompts/handoff-prep.md` also tells the model not to go on.
44
+ - Running work never blocks: when the handoff starts (or a queued one is released) the mod counts running subagents (`$.agent.list()`, live) and
45
+ background tasks (the `background_tasks` of the last `classic.Stop`, a snapshot) and shows one toast if any run. Nothing is stopped or waited for;
46
+ step 0 of `prompts/handoff-prep.md` lists them in the handoff's open risks.
47
47
 
48
48
  ## Auto-handoff
49
49
 
50
50
  - On by default. When context is at 65% or more and the chat is idle, the mod runs the same flow as `Alt+H`
51
- (same git gate, running-work gate and validator) and shows the toast `Auto-handoff: context is at N% ...`.
51
+ (same git gate and validator) and shows the toast `Auto-handoff: context is at N% ...`.
52
52
  - Idle means: no running turn, no user prompt waiting, no nudge in flight, no handoff running, and an
53
53
  empty prompt box. A busy chat defers to the next idle tick (15 s). Unknown context never fires.
54
54
  - After an auto run aborts, auto waits until context has grown 5 points past the level at the abort. A new
@@ -6,7 +6,7 @@ import { copyViaSystem } from '../lib/clipboard.mjs'
6
6
  import { TONES, busyBand, idleBand, textBand } from '../lib/band.mjs'
7
7
  import { renderPrep, isPrepTurn, prepStartExpired } from '../lib/prep.mjs'
8
8
  import { evaluateGitState, collectGitState } from '../lib/gitgate.mjs'
9
- import { summarizeActiveWork, activeWorkReason } from '../lib/activework.mjs'
9
+ import { summarizeActiveWork, activeWorkNote } from '../lib/activework.mjs'
10
10
  import { claudeSubdir, sessionFilePath, cacheInfoFromState, cacheRemainingMs } from '../lib/cache.mjs'
11
11
  import { AUTO_THRESHOLD_PERCENT, AUTO_STORE_KEY, HANDOFF_USAGE, newAuto, storedEnabled, onAutoAbort, settleAuto, decideAuto, autoLabel, autoStatusText, parseHandoffArgs } from '../lib/auto.mjs'
12
12
  import {
@@ -83,7 +83,6 @@ async function startHandoff($, autoLevel = null) {
83
83
  setPhase($, 'starting')
84
84
  try {
85
85
  const work = await activeWork($)
86
- if (work.total > 0) return fail($, activeWorkReason(work))
87
86
  const sessionId = await $.session.id()
88
87
  const home = (await $.env.get('USERPROFILE')) || (await $.env.get('HOME'))
89
88
  const dir = (await $.env.get('HANDOFF_DIR')) || defaultHandoffDir(home)
@@ -98,12 +97,17 @@ async function startHandoff($, autoLevel = null) {
98
97
  $.ui.toast('Handoff queued - waiting for the current turn to finish', { timeoutMs: TOAST_MS })
99
98
  return
100
99
  }
100
+ noteActiveWork($, work)
101
101
  await submitPrep($)
102
102
  } catch (err) {
103
103
  return fail($, 'could not start (' + err + ')')
104
104
  }
105
105
  }
106
106
 
107
+ function noteActiveWork($, work) {
108
+ if (work.total > 0) $.ui.toast(activeWorkNote(work), { timeoutMs: TOAST_MS })
109
+ }
110
+
107
111
  async function submitPrep($) {
108
112
  flow.turnId = null
109
113
  flow.submittedAt = await $.clock.now()
@@ -115,8 +119,7 @@ async function releaseQueued($) {
115
119
  if (flow.phase !== 'queued' || isBusy(state, await $.clock.now())) return
116
120
  flow.phase = 'prep'
117
121
  try {
118
- const work = await activeWork($)
119
- if (work.total > 0) return fail($, activeWorkReason(work))
122
+ noteActiveWork($, await activeWork($))
120
123
  await submitPrep($)
121
124
  } catch (err) {
122
125
  return fail($, 'could not start (' + err + ')')
@@ -146,9 +149,6 @@ async function finishHandoff($, reason) {
146
149
  const gate = evaluateGitState(await collectGitState((argv) => $.process.run(argv)))
147
150
  if (!gate.ok) return fail($, gate.reason)
148
151
 
149
- const work = await activeWork($)
150
- if (work.total > 0) return fail($, activeWorkReason(work))
151
-
152
152
  const submission = prepareSubmission(handoff)
153
153
  const copied = await copyToClipboard($, handoff, flow.path)
154
154
  await $.command.run({ command: 'clear', args: '' })
@@ -7,9 +7,9 @@ export function summarizeActiveWork(agents, background) {
7
7
  return { subagents, tasks: others, total: subagents + others }
8
8
  }
9
9
 
10
- export function activeWorkReason({ subagents, tasks }) {
10
+ export function activeWorkNote({ subagents, tasks }) {
11
11
  const parts = []
12
12
  if (subagents > 0) parts.push(subagents + ' subagent(s)')
13
13
  if (tasks > 0) parts.push(tasks + ' background task(s)')
14
- return parts.join(' and ') + ' still running: stop or wait for them first'
14
+ return 'Handoff continues with ' + parts.join(' and ') + ' still running; they are not stopped'
15
15
  }
@@ -1,6 +1,6 @@
1
1
  Prepare this session for a handoff. The session is cleared after you finish, so leave nothing only in this conversation. Do the steps in order. Do not ask questions.
2
2
 
3
- 0. Running work. List running subagents and background tasks. Do not go on until each has finished or you stopped it with TaskStop (only work you started). If one cannot finish, print `HANDOFF_ABORT` naming it.
3
+ 0. Running work. List any running subagents and background tasks (name and goal) in the open risks of the handoff file. Do not wait for them, stop them or abort because of them. Running work never blocks the handoff.
4
4
  1. Tasks. Use TaskList and TaskUpdate so every task matches reality (done, in progress, pending).
5
5
  2. PRD issue. Find the single open PRD issue for this session (task metadata or this conversation). Update its description (TODO mirror and status) and post one status comment, using the issue-tracker access this project already uses (a repo script or the tracker's CLI). Never print the token. If no PRD issue exists, write "none" in the PRD section.
6
6
  3. Docs. Update only the markdown docs, README rows and memory that this session touched or made stale.
@@ -9,4 +9,4 @@ Prepare this session for a handoff. The session is cleared after you finish, so
9
9
  6. Check. Run `{{validator_cmd}}`. Fix the file until it exits 0.
10
10
  7. Finish. Print exactly one final line: `HANDOFF_READY {{handoff_path}}`.
11
11
 
12
- Abort rule: if tests fail or the push fails, do not write the ready line. Print one final line `HANDOFF_ABORT <short reason>` instead. Keep the handoff file if you wrote it.
12
+ Abort rule: only if tests fail or the push fails, do not write the ready line. Print one final line `HANDOFF_ABORT <short reason>` instead. Keep the handoff file if you wrote it.
@@ -1,6 +1,6 @@
1
1
  import test from 'node:test'
2
2
  import assert from 'node:assert/strict'
3
- import { summarizeActiveWork, activeWorkReason } from '../lib/activework.mjs'
3
+ import { summarizeActiveWork, activeWorkNote } from '../lib/activework.mjs'
4
4
 
5
5
  test('only running agents count', () => {
6
6
  const agents = [{ status: 'running' }, { status: 'completed' }, { status: 'killed' }, { status: 'running' }]
@@ -17,10 +17,10 @@ test('bad input counts as nothing', () => {
17
17
  assert.deepEqual(summarizeActiveWork(undefined, null), { subagents: 0, tasks: 0, total: 0 })
18
18
  })
19
19
 
20
- test('reason names the counts and says stop or wait', () => {
20
+ test('note names the counts and says the work is not stopped', () => {
21
21
  assert.equal(
22
- activeWorkReason({ subagents: 2, tasks: 1 }),
23
- '2 subagent(s) and 1 background task(s) still running: stop or wait for them first',
22
+ activeWorkNote({ subagents: 2, tasks: 1 }),
23
+ 'Handoff continues with 2 subagent(s) and 1 background task(s) still running; they are not stopped',
24
24
  )
25
- assert.equal(activeWorkReason({ subagents: 0, tasks: 3 }), '3 background task(s) still running: stop or wait for them first')
25
+ assert.equal(activeWorkNote({ subagents: 0, tasks: 3 }), 'Handoff continues with 3 background task(s) still running; they are not stopped')
26
26
  })
@@ -502,24 +502,27 @@ test('handoff starts when nothing is running', async () => {
502
502
  assert.equal(h.toasts.length, 0)
503
503
  })
504
504
 
505
- test('handoff aborts before the prep turn while a subagent is running', async () => {
505
+ const NOTE = /^Handoff continues with .* still running; they are not stopped$/
506
+ const noteToasts = (h) => h.toasts.filter((t) => NOTE.test(t))
507
+
508
+ test('handoff proceeds to the prep turn while a subagent is running, with one note', async () => {
506
509
  const h = await harness()
507
510
  await h.start()
508
511
  h.agents = [{ id: 'a', status: 'running' }, { id: 'b', status: 'completed' }]
509
512
  await startHandoffFlow(h)
510
- assert.equal(prepSubmitted(h).length, 0)
511
- assert.equal(h.toasts.length, 1)
512
- assert.match(h.toasts[0], /1 subagent\(s\) still running: stop or wait for them first/)
513
+ assert.equal(prepSubmitted(h).length, 1)
514
+ assert.deepEqual(h.toasts, ['Handoff continues with 1 subagent(s) still running; they are not stopped'])
513
515
  })
514
516
 
515
- test('handoff aborts before the prep turn while a background task from the last turn is running', async () => {
517
+ test('handoff proceeds to the prep turn while background tasks from the last turn are running', async () => {
516
518
  const h = await harness()
517
519
  await h.start()
518
- await h.fire('turn.start', {})
520
+ const turnId = await h.startTurn('work')
519
521
  await h.fire('classic.Stop', { background_tasks: [{ id: 'b1', type: 'shell' }, { id: 'b2', type: 'monitor' }] })
522
+ await h.fire('turn.complete', { answer: 'ok', reason: 'answer', turnId })
520
523
  await startHandoffFlow(h)
521
- assert.equal(prepSubmitted(h).length, 0)
522
- assert.match(h.toasts[0], /2 background task\(s\) still running/)
524
+ assert.equal(prepSubmitted(h).length, 1)
525
+ assert.deepEqual(h.toasts, ['Handoff continues with 2 background task(s) still running; they are not stopped'])
523
526
  })
524
527
 
525
528
  test('handoff clears and submits the handoff when no work is running', async () => {
@@ -531,23 +534,31 @@ test('handoff clears and submits the handoff when no work is running', async ()
531
534
  assert.ok(h.submitted.some((s) => s.asUser && /Session handoff/.test(s.text)))
532
535
  })
533
536
 
534
- test('handoff does not clear when a subagent started during the prep turn', async () => {
537
+ test('handoff with 19 running subagents and 19 background tasks completes end to end', async () => {
535
538
  const h = await harness()
536
539
  await h.start()
540
+ h.agents = Array.from({ length: 19 }, (_, i) => ({ id: 'a' + i, status: 'running' }))
541
+ const tasks = Array.from({ length: 19 }, (_, i) => ({ id: 'b' + i, type: 'shell' }))
542
+ const turnId = await h.startTurn('work')
543
+ await h.fire('classic.Stop', { background_tasks: tasks })
544
+ await h.fire('turn.complete', { answer: 'ok', reason: 'answer', turnId })
537
545
  await startHandoffFlow(h)
538
- h.agents = [{ id: 'a', status: 'running' }]
539
- await finishPrep(h)
540
- assert.equal(h.cleared, 0)
541
- assert.match(h.toasts.at(-1), /Handoff aborted: 1 subagent\(s\) still running: stop or wait for them first/)
546
+ assert.equal(prepSubmitted(h).length, 1)
547
+ await finishPrep(h, tasks)
548
+ assert.equal(h.cleared, 1)
549
+ assert.ok(h.submitted.some((s) => s.asUser && /Session handoff/.test(s.text)))
550
+ assert.ok(!h.toasts.some((t) => /aborted/i.test(t)))
542
551
  })
543
552
 
544
- test('handoff does not clear when a background task is running at the end of the prep turn', async () => {
553
+ test('the running-work note shows once at start and not again at /clear', async () => {
545
554
  const h = await harness()
546
555
  await h.start()
556
+ h.agents = [{ id: 'a', status: 'running' }]
547
557
  await startHandoffFlow(h)
558
+ assert.equal(noteToasts(h).length, 1)
548
559
  await finishPrep(h, [{ id: 'b1', type: 'shell' }])
549
- assert.equal(h.cleared, 0)
550
- assert.match(h.toasts.at(-1), /1 background task\(s\) still running/)
560
+ assert.equal(h.cleared, 1)
561
+ assert.equal(noteToasts(h).length, 1)
551
562
  })
552
563
 
553
564
  test('handoff does not clear when the branch has unpushed commits and no upstream', async () => {
@@ -669,17 +680,18 @@ test('a user prompt waiting for its turn queues the handoff, and the tick releas
669
680
  assert.equal(prepSubmitted(h).length, 1)
670
681
  })
671
682
 
672
- test('a queued handoff aborts safely when the busy turn left a subagent running', async () => {
683
+ test('a queued handoff released while a subagent runs proceeds, with the note shown once at release', async () => {
673
684
  const h = await harness()
674
685
  await h.start()
675
686
  const busyId = await busyTurn(h)
676
687
  await startHandoffFlow(h)
688
+ assert.equal(noteToasts(h).length, 0)
677
689
  h.agents = [{ id: 'a', status: 'running' }]
678
690
  await h.fire('turn.complete', { answer: 'done', reason: 'answer', turnId: busyId })
679
691
  await new Promise((resolve) => setImmediate(resolve))
680
- assert.equal(prepSubmitted(h).length, 0)
681
- assert.match(h.toasts.at(-1), /Handoff aborted: 1 subagent\(s\) still running/)
682
- assert.equal(h.cleared, 0)
692
+ assert.equal(prepSubmitted(h).length, 1)
693
+ assert.equal(noteToasts(h).length, 1)
694
+ assert.ok(!h.toasts.some((t) => /aborted/i.test(t)))
683
695
  })
684
696
 
685
697
  test('cancel drops a queued handoff and nothing is submitted later', async () => {
@@ -827,13 +839,13 @@ test('auto: a busy turn that starts while the run is starting drops the run quie
827
839
  assert.equal((await h.render()).children[1].label, 'Handoff')
828
840
  })
829
841
 
830
- test('auto: gates still apply - a running subagent aborts the auto run before the prep prompt', async () => {
842
+ test('auto: a running subagent does not stop the auto run', async () => {
831
843
  const h = await autoHarness()
832
844
  h.agents = [{ id: 'a', status: 'running' }]
833
845
  await h.tick()
834
846
  await settle()
835
- assert.equal(prepSubmitted(h).length, 0)
836
- assert.match(h.toasts.at(-1), /Handoff aborted: 1 subagent\(s\) still running/)
847
+ assert.equal(prepSubmitted(h).length, 1)
848
+ assert.equal(noteToasts(h).length, 1)
837
849
  })
838
850
 
839
851
  test('auto: after an aborted auto run it waits for 5 more points; manual start always works', async () => {
@@ -27,9 +27,9 @@ test('template renders with no placeholder left and states the contract', () =>
27
27
  })
28
28
 
29
29
  test('template starts with the running-work step and carries rebase-conflict guidance', () => {
30
- assert.match(template, /\n0\. Running work\. List running subagents and background tasks\./)
31
- assert.ok(template.includes('TaskStop'))
32
- assert.ok(template.includes('HANDOFF_ABORT` naming it'))
30
+ assert.match(template, /\n0\. Running work\. List any running subagents and background tasks \(name and goal\) in the open risks.*never blocks the handoff\./)
31
+ assert.ok(!template.includes('TaskStop'))
32
+ assert.ok(!template.includes('naming it'))
33
33
  assert.ok(template.indexOf('0. Running work') < template.indexOf('1. Tasks'))
34
34
  assert.match(template, /4\. Code\..*conflict.*both sides' intent.*re-run the tests.*open risks/)
35
35
  })
@@ -60,11 +60,9 @@ Original checks, retained semantics (first correction wins where relevant):
60
60
  it stays correct for any farm-style project): `dispatch_tier:
61
61
  mandatory-review` bypasses the route lock the same way `dispatch_tier:
62
62
  safe` does, but marks a pending-review flag that execution_worker_review_gate.py
63
- checks before allowing `git commit`. A target that has adopted
64
- scripts/review_pass.py clears that flag only via a verified stamp, never
65
- by a dispatch; a target without it keeps the older behavior, where
66
- dispatching an agent whose frontmatter declares `clears_review: true`
67
- clears the flag directly (route_lock.clear_pending_review).
63
+ checks before allowing `git commit`. The flag lives at the target
64
+ worktree's own toplevel and is cleared only by a verified
65
+ scripts/review_pass.py stamp, never by a dispatch.
68
66
 
69
67
  Fails OPEN (prints nothing, exit 0) on any unexpected exception, missing
70
68
  registry file, or malformed stdin — mirrors agent_dispatch_guard.py.
@@ -258,42 +256,53 @@ def _parse_worktree_targets(prompt: str) -> list[str]:
258
256
 
259
257
 
260
258
  def _mark_pending_review_per_target(cwd: str, prompt: str) -> None:
261
- """Marks each `worktree:`-named target's OWN pending flag when it
262
- has adopted scripts/review_pass.py (per-target design) — bypassing
263
- route_lock's shared git-common-dir root so a worktree's flag never
264
- collapses onto its main checkout. A target without scripts/review_pass.py,
265
- or no `worktree:` line at all, keeps the exact old cwd-keyed behavior."""
266
- targets = _parse_worktree_targets(prompt)
267
- if not targets:
268
- route_lock.mark_pending_review(cwd)
269
- return
270
- for target in targets:
271
- if os.path.isfile(os.path.join(target, "scripts", "review_pass.py")):
272
- marker = os.path.join(target, ".claude", ".pending_review.json")
273
- try:
274
- os.makedirs(os.path.dirname(marker), exist_ok=True)
275
- with open(marker, "w", encoding="utf-8") as fh:
276
- json.dump({"pending_review": True, "ts": time.time()}, fh)
277
- except Exception:
278
- pass
279
- else:
280
- route_lock.mark_pending_review(target)
281
-
282
-
283
- def _clear_pending_review_per_target(cwd: str, prompt: str) -> None:
284
- """Mirrors _mark_pending_review_per_target: clears each `worktree:`-named
285
- target's OWN pending flag on a `clears_review: true` dispatch — but only
286
- for a target that has NOT adopted scripts/review_pass.py. A target with
287
- review_pass.py clears its flag exclusively via a verified stamp
288
- (commit_repo.py's _check_review_stamp), never by a mere dispatch."""
289
- targets = _parse_worktree_targets(prompt)
290
- if not targets:
291
- if not os.path.isfile(os.path.join(cwd, "scripts", "review_pass.py")):
292
- route_lock.clear_pending_review(cwd)
293
- return
294
- for target in targets:
295
- if not os.path.isfile(os.path.join(target, "scripts", "review_pass.py")):
296
- route_lock.clear_pending_review(target)
259
+ """Flags each `worktree:`-named target's OWN worktree (or the caller's cwd when none is named); never a root shared with other worktrees."""
260
+ for target in _parse_worktree_targets(prompt) or [cwd]:
261
+ route_lock.mark_pending_review(target)
262
+
263
+
264
+ DISPATCH_LOG_MAX_BYTES = 5 * 1024 * 1024
265
+
266
+
267
+ def _dispatch_log_path() -> str:
268
+ override = os.environ.get("CLAUDE_AGENT_DISPATCH_LOG")
269
+ if override:
270
+ return override
271
+ return os.path.join(os.path.expanduser("~"), ".claude", "logs", "agent_dispatch.jsonl")
272
+
273
+
274
+ def _record_dispatch_error(log_path: str, exc: Exception) -> None:
275
+ try:
276
+ with open(log_path + ".errors", "a", encoding="utf-8") as fh:
277
+ fh.write(f"{time.time():.3f} {type(exc).__name__}: {exc}\n")
278
+ except Exception:
279
+ pass
280
+
281
+
282
+ def _log_dispatch(session_id: str, name: str, subagent_type: str) -> None:
283
+ """Append one JSON line mapping dispatch name -> effective subagent_type; a write failure is logged, never raised."""
284
+ log_path = _dispatch_log_path()
285
+ try:
286
+ os.makedirs(os.path.dirname(log_path), exist_ok=True)
287
+ try:
288
+ if os.path.getsize(log_path) >= DISPATCH_LOG_MAX_BYTES:
289
+ os.replace(log_path, log_path + ".1")
290
+ except OSError:
291
+ pass
292
+ line = json.dumps({
293
+ "ts": time.time(),
294
+ "session_id": session_id,
295
+ "name": name,
296
+ "agent_id_prefix": None,
297
+ "subagent_type": subagent_type,
298
+ }) + "\n"
299
+ fd = os.open(log_path, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o644)
300
+ try:
301
+ os.write(fd, line.encode("utf-8"))
302
+ finally:
303
+ os.close(fd)
304
+ except Exception as exc:
305
+ _record_dispatch_error(log_path, exc)
297
306
 
298
307
 
299
308
  def _deny(reason: str) -> None:
@@ -385,6 +394,8 @@ def _safe_main() -> None:
385
394
  f"identifies this dispatch — address it by this name in teammate messages"
386
395
  )
387
396
 
397
+ _log_dispatch(str(data.get("session_id") or ""), corrected["name"], eff_type)
398
+
388
399
  # (a) registered agent + explicit model of a different family →
389
400
  # STRIP the param; frontmatter is the routing authority.
390
401
  if registered_model and corrected.get("model"):
@@ -451,10 +462,7 @@ def _safe_main() -> None:
451
462
  if route_lock.is_farm_style_project(cwd):
452
463
  _mark_pending_review_per_target(cwd, prompt)
453
464
  elif dispatch_tier == "safe":
454
- # A target that has adopted scripts/review_pass.py clears its flag
455
- # only via a verified stamp, never here — see _clear_pending_review_per_target.
456
- if route_lock.agent_clears_review(subagent_type, cwd) and route_lock.is_farm_style_project(cwd):
457
- _clear_pending_review_per_target(cwd, prompt)
465
+ pass # a worktree's flag is cleared only by a verified scripts/review_pass.py stamp, never by dispatching a reviewer
458
466
  elif subagent_type and _find_agent_file(subagent_type, cwd) and route_lock.is_farm_style_project(cwd):
459
467
  lock = route_lock.read_lock(cwd)
460
468
  if lock:
@@ -12,12 +12,9 @@ safe` agent it is not gated at dispatch time -- it can be dispatched with no
12
12
  @tag and no route lock. The compensating control lives here, at commit time:
13
13
  if a mandatory-review agent has run in this farm-style project and the
14
14
  target's pending-review flag is still set (_is_review_pending_per_target),
15
- any `git commit` is denied until it clears. A target that has adopted
16
- scripts/review_pass.py reads its OWN toplevel flag directly and clears it
17
- only via a verified review_pass.py stamp, never a mere dispatch. A target
18
- without it keeps the older behavior: dispatching an agent whose frontmatter
19
- declares `clears_review: true` (this project's reviewer-subagent) clears the
20
- shared route_lock flag directly (route_lock.clear_pending_review).
15
+ any `git commit` is denied until it clears. The flag is the target worktree's
16
+ OWN toplevel flag and is cleared only by a verified review_pass.py stamp,
17
+ never by dispatching a reviewer.
21
18
 
22
19
  Wired as a PreToolUse hook on the "Bash" matcher in ~/.claude/settings.json,
23
20
  scoped with an "if": "Bash(git commit *)" permission-rule clause so it only
@@ -173,9 +170,9 @@ def _toplevel(cwd: str) -> str | None:
173
170
 
174
171
 
175
172
  def _is_review_pending_per_target(cwd: str) -> bool:
176
- """When cwd's own toplevel has adopted scripts/review_pass.py, reads THAT target's own flag directly; otherwise keeps the exact old behavior."""
173
+ """Reads cwd's own worktree flag, falling back to route_lock's resolution outside a git work tree."""
177
174
  toplevel = _toplevel(cwd)
178
- if toplevel and os.path.isfile(os.path.join(toplevel, "scripts", "review_pass.py")):
175
+ if toplevel:
179
176
  try:
180
177
  with open(os.path.join(toplevel, ".claude", ".pending_review.json"), "r", encoding="utf-8") as fh:
181
178
  return json.load(fh).get("pending_review") is True
@@ -6,24 +6,25 @@ import sys
6
6
  from typing import Any
7
7
 
8
8
 
9
- def headless_popen_kwargs(extra_creationflags: int = 0) -> dict[str, Any]:
10
- """Windows-only creationflags/startupinfo/stdin trio for dict-building callers; no-op elsewhere."""
9
+ def headless_popen_kwargs(extra_creationflags: int = 0, no_window: bool = True) -> dict[str, Any]:
10
+ """Windows-only creationflags/startupinfo/stdin trio for dict-building callers; no-op elsewhere; no_window=False omits CREATE_NO_WINDOW."""
11
11
  if sys.platform != "win32":
12
12
  return {}
13
13
  startupinfo = subprocess.STARTUPINFO()
14
14
  startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
15
15
  startupinfo.wShowWindow = subprocess.SW_HIDE
16
16
  return {
17
- "creationflags": subprocess.CREATE_NO_WINDOW | extra_creationflags,
17
+ "creationflags": (subprocess.CREATE_NO_WINDOW if no_window else 0) | extra_creationflags,
18
18
  "startupinfo": startupinfo,
19
19
  "stdin": subprocess.DEVNULL,
20
20
  }
21
21
 
22
22
 
23
23
  def _apply_headless(kw: dict[str, Any], *, allow_input: bool) -> dict[str, Any]:
24
- """Mutates and returns kw with the Windows headless trio; new_process_group=True also ORs in CREATE_NEW_PROCESS_GROUP on win32 for a killable child group (no-op on POSIX, which signals the pid directly)."""
24
+ """Mutates and returns kw with the Windows headless trio; new_process_group=True also ORs in CREATE_NEW_PROCESS_GROUP on win32 for a killable child group (no-op on POSIX, which signals the pid directly); no_window=False omits CREATE_NO_WINDOW (window stays SW_HIDE) so a console child, e.g. Metro, can still receive CTRL_BREAK."""
25
25
  extra_creationflags = kw.pop("creationflags", 0)
26
26
  new_process_group = kw.pop("new_process_group", False)
27
+ no_window = kw.pop("no_window", True)
27
28
  if sys.platform != "win32":
28
29
  return kw
29
30
  if new_process_group:
@@ -32,7 +33,7 @@ def _apply_headless(kw: dict[str, Any], *, allow_input: bool) -> dict[str, Any]:
32
33
  startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
33
34
  startupinfo.wShowWindow = subprocess.SW_HIDE
34
35
  kw.setdefault("startupinfo", startupinfo)
35
- kw["creationflags"] = subprocess.CREATE_NO_WINDOW | extra_creationflags
36
+ kw["creationflags"] = (subprocess.CREATE_NO_WINDOW if no_window else 0) | extra_creationflags
36
37
  if "stdin" not in kw and not (allow_input and "input" in kw):
37
38
  kw["stdin"] = subprocess.DEVNULL
38
39
  return kw
@@ -579,8 +579,27 @@ def _git_common_dir_root(cwd: str) -> str | None:
579
579
  return root
580
580
 
581
581
 
582
+ def _worktree_toplevel(cwd: str) -> str | None:
583
+ """`cwd`'s own worktree toplevel (a linked worktree or a submodule is its own), or None if not in a git work tree."""
584
+ try:
585
+ result = headless_run(
586
+ ["git", "-C", cwd, "rev-parse", "--show-toplevel", "--path-format=absolute"],
587
+ capture_output=True,
588
+ text=True,
589
+ timeout=10,
590
+ env=_clean_git_env(),
591
+ )
592
+ except (OSError, subprocess.SubprocessError):
593
+ return None
594
+ out = result.stdout.strip()
595
+ if result.returncode != 0 or not out:
596
+ return None
597
+ return os.path.realpath(out)
598
+
599
+
582
600
  def pending_review_path(cwd: str) -> str:
583
- base = _git_common_dir_root(cwd) or find_project_root(cwd) or cwd
601
+ """One flag per worktree toplevel, never a root shared across worktrees; mirrors scripts/route_lock.py:resolve_flag_root."""
602
+ base = _worktree_toplevel(cwd) or find_project_root(cwd) or cwd
584
603
  return os.path.join(base, PENDING_REVIEW_RELPATH)
585
604
 
586
605
 
@@ -180,7 +180,7 @@ OVERRIDE_MARKER_MAX_WINDOW_SECONDS = 3600 # hard 1h cap, regardless of "until"
180
180
 
181
181
  # Fast path: skip all parsing if the raw text doesn't even mention git.
182
182
  _MENTIONS_GIT_RE = re.compile(r"\bgit\b")
183
- _RISKY_SUBCOMMAND_RE = re.compile(r"\b(checkout|restore|stash|reset|clean|switch)\b")
183
+ _RISKY_SUBCOMMAND_RE = re.compile(r"\b(checkout|restore|stash|reset|clean|switch|apply)\b")
184
184
  # PowerShell `-EncodedCommand`'s base64/UTF-16LE payload can hide a `git`
185
185
  # invocation from the raw-text `_MENTIONS_GIT_RE` fast path entirely (the
186
186
  # encoded bytes have no reason to contain the literal ASCII substring
@@ -496,6 +496,36 @@ def _restore_pathspec(rest_args: list[str], dynamic_source: bool = False):
496
496
  return (paths, False) if paths else None
497
497
 
498
498
 
499
+ _APPLY_READONLY_FLAGS = {"--check", "--stat", "--numstat", "--summary"}
500
+ _PATCH_PATH_RE = re.compile(r"^(?:\+\+\+|---) (?:[ab]/)?(\S+)", re.MULTILINE)
501
+
502
+
503
+ def _apply_reverse_pathspec(rest_args: list[str], repo_dir: Path):
504
+ """`git apply -R`/`--reverse` undoes a patch in the working tree,
505
+ discarding uncommitted work under the same paths. None when not a
506
+ reverse apply (or inspect-only); else (patch paths, False), or
507
+ ([], True) when the paths are unknowable (stdin patch, unreadable file)."""
508
+ if _APPLY_READONLY_FLAGS & set(rest_args):
509
+ return None
510
+ reverse = any(
511
+ a == "--reverse" or (a.startswith("-") and not a.startswith("--") and "R" in a)
512
+ for a in rest_args
513
+ )
514
+ if not reverse:
515
+ return None
516
+ patch_files = [a for a in rest_args if not a.startswith("-")]
517
+ if not patch_files:
518
+ return ([], True)
519
+ paths: list[str] = []
520
+ for name in patch_files:
521
+ try:
522
+ text = (repo_dir / name).read_text(encoding="utf-8", errors="replace")
523
+ except OSError:
524
+ return ([], True)
525
+ paths += [m for m in _PATCH_PATH_RE.findall(text) if m != "/dev/null"]
526
+ return (sorted(set(paths)), False) if paths else ([], True)
527
+
528
+
499
529
  def _stash_pathspec(rest_args: list[str]):
500
530
  """Only `stash push`/`stash save` accept a `-- <paths>` pathspec,
501
531
  narrowing the check to just those paths. Every other stash form checks
@@ -608,6 +638,9 @@ def _check_git_invocation_tokens(
608
638
  elif subcommand == "restore":
609
639
  result = _restore_pathspec(rest_args, dynamic_source=dynamic_pathspec_source)
610
640
  rule = "restore-dynamic-pathspec-unverifiable" if (result and result[1]) else "restore-path-revert"
641
+ elif subcommand == "apply":
642
+ result = _apply_reverse_pathspec(rest_args, repo_dir)
643
+ rule = "apply-reverse-patch-revert"
611
644
  elif subcommand == "stash":
612
645
  result = _stash_pathspec(rest_args)
613
646
  rule = "stash-may-discard-uncommitted-work"
@@ -23,13 +23,16 @@ Stdlib only. Atomic writes via tempfile + fsync + os.replace.
23
23
  from __future__ import annotations
24
24
 
25
25
  import argparse
26
+ import contextlib
26
27
  import difflib
28
+ import hashlib
27
29
  import json
28
30
  import os
29
31
  import re
30
32
  import subprocess
31
33
  import sys
32
34
  import tempfile
35
+ import time
33
36
  import urllib.parse
34
37
  import urllib.request
35
38
  from datetime import datetime, timezone
@@ -75,6 +78,53 @@ class _Refusal(Exception):
75
78
  pass
76
79
 
77
80
 
81
+ # ---------------------------------------------------------------------------
82
+ # Ledger lock — serializes the load-modify-write cycle of mutating commands
83
+ # ---------------------------------------------------------------------------
84
+
85
+ LOCK_TIMEOUT_S = 60
86
+ MUTATING_CMDS = {
87
+ "init", "pickup", "log", "finish", "handoff", "council-gate",
88
+ "concept-analysis", "ext-append", "ext-set",
89
+ }
90
+
91
+
92
+ @contextlib.contextmanager
93
+ def _ledger_lock(ledger: Path):
94
+ key = hashlib.sha1(str(ledger.resolve()).encode()).hexdigest()[:16]
95
+ lock_path = Path(tempfile.gettempdir()) / f"item_py_{key}.lock"
96
+ fh = open(lock_path, "a+b")
97
+ deadline = time.monotonic() + LOCK_TIMEOUT_S
98
+ try:
99
+ while True:
100
+ try:
101
+ if os.name == "nt":
102
+ import msvcrt
103
+ fh.seek(0)
104
+ msvcrt.locking(fh.fileno(), msvcrt.LK_NBLCK, 1)
105
+ else:
106
+ import fcntl
107
+ fcntl.flock(fh.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
108
+ break
109
+ except OSError:
110
+ if time.monotonic() > deadline:
111
+ raise _Refusal(f"could not lock ledger '{ledger}' within {LOCK_TIMEOUT_S}s")
112
+ time.sleep(0.05)
113
+ yield
114
+ finally:
115
+ try:
116
+ if os.name == "nt":
117
+ import msvcrt
118
+ fh.seek(0)
119
+ msvcrt.locking(fh.fileno(), msvcrt.LK_UNLCK, 1)
120
+ else:
121
+ import fcntl
122
+ fcntl.flock(fh.fileno(), fcntl.LOCK_UN)
123
+ except OSError:
124
+ pass
125
+ fh.close()
126
+
127
+
78
128
  # ---------------------------------------------------------------------------
79
129
  # Project root + ledger discovery
80
130
  # ---------------------------------------------------------------------------
@@ -791,6 +841,59 @@ def cmd_concept_analysis(args: argparse.Namespace, ctx: dict) -> int:
791
841
  return 0
792
842
 
793
843
 
844
+ # ---------------------------------------------------------------------------
845
+ # Subcommand: ext-append — append one JSON object to an allowlisted ext list
846
+ # ---------------------------------------------------------------------------
847
+
848
+ EXT_APPEND_PATHS = {"meshy.tasks"}
849
+ EXT_SET_VALUES = {"body_plan": {"biped", "quadruped", "other"}}
850
+
851
+
852
+ def cmd_ext_append(args: argparse.Namespace, ctx: dict) -> int:
853
+ if args.path not in EXT_APPEND_PATHS:
854
+ raise _Refusal(
855
+ f"ext path '{args.path}' is not appendable; allowed: {sorted(EXT_APPEND_PATHS)}"
856
+ )
857
+ try:
858
+ data = json.loads(args.json_str)
859
+ except json.JSONDecodeError as e:
860
+ raise _Refusal(f"--json is not valid JSON: {e}")
861
+ if not isinstance(data, dict):
862
+ raise _Refusal("ext-append payload must be a JSON object")
863
+
864
+ doc = ctx["doc"]
865
+ item = _find_item(doc, args.id)
866
+ node = item.setdefault("ext", {})
867
+ *parents, leaf = args.path.split(".")
868
+ for key in parents:
869
+ node = node.setdefault(key, {})
870
+ bucket = node.setdefault(leaf, [])
871
+ if not isinstance(bucket, list):
872
+ raise _Refusal(f"ext.{args.path} exists and is not a list")
873
+ bucket.append(data)
874
+ _touch(item)
875
+ _atomic_write(ctx["ledger_path"], doc)
876
+ print(json.dumps({
877
+ "ok": True, "id": args.id, "wrote": f"ext.{args.path}", "count": len(bucket),
878
+ }, indent=2))
879
+ return 0
880
+
881
+
882
+ def cmd_ext_set(args: argparse.Namespace, ctx: dict) -> int:
883
+ allowed = EXT_SET_VALUES.get(args.key)
884
+ if allowed is None:
885
+ raise _Refusal(f"ext key '{args.key}' is not settable; allowed: {sorted(EXT_SET_VALUES)}")
886
+ if args.value not in allowed:
887
+ raise _Refusal(f"ext.{args.key} must be one of {sorted(allowed)}")
888
+ doc = ctx["doc"]
889
+ item = _find_item(doc, args.id)
890
+ item.setdefault("ext", {})[args.key] = args.value
891
+ _touch(item)
892
+ _atomic_write(ctx["ledger_path"], doc)
893
+ print(json.dumps({"ok": True, "id": args.id, "wrote": f"ext.{args.key}", "value": args.value}, indent=2))
894
+ return 0
895
+
896
+
794
897
  # ---------------------------------------------------------------------------
795
898
  # Resolve — codified fuzzy ID lookup for free-text leaf dispatch
796
899
  # ---------------------------------------------------------------------------
@@ -1017,6 +1120,25 @@ def build_parser() -> argparse.ArgumentParser:
1017
1120
  help="JSON string literal")
1018
1121
  pca.set_defaults(func=cmd_concept_analysis)
1019
1122
 
1123
+ pea = sub.add_parser(
1124
+ "ext-append",
1125
+ help="append a JSON object to an allowlisted ext list (e.g. meshy.tasks)",
1126
+ )
1127
+ pea.add_argument("id")
1128
+ pea.add_argument("path", help="dotted ext path, e.g. meshy.tasks")
1129
+ pea.add_argument("--json", dest="json_str", required=True,
1130
+ help="JSON object literal to append")
1131
+ pea.set_defaults(func=cmd_ext_append)
1132
+
1133
+ pes = sub.add_parser(
1134
+ "ext-set",
1135
+ help="set an allowlisted scalar ext key (e.g. body_plan=biped)",
1136
+ )
1137
+ pes.add_argument("id")
1138
+ pes.add_argument("key", help="ext key, e.g. body_plan")
1139
+ pes.add_argument("--value", required=True)
1140
+ pes.set_defaults(func=cmd_ext_set)
1141
+
1020
1142
  pr = sub.add_parser(
1021
1143
  "resolve",
1022
1144
  help="resolve a free-text query to a single actionable item id (codified picker)",
@@ -1035,6 +1157,10 @@ def main(argv: list[str] | None = None) -> int:
1035
1157
  parser = build_parser()
1036
1158
  args = parser.parse_args(argv)
1037
1159
  try:
1160
+ if args.cmd in MUTATING_CMDS:
1161
+ with _ledger_lock(_ledger_path(_find_project_root())):
1162
+ ctx = _build_context(read_only=False)
1163
+ return args.func(args, ctx)
1038
1164
  ctx = _build_context(read_only=(args.cmd == "status"))
1039
1165
  return args.func(args, ctx)
1040
1166
  except _Refusal as e:
@@ -608,3 +608,69 @@ class TestCouncilGateRetry:
608
608
  out = json.loads(r.stdout)
609
609
  assert out["retry_count"] == 1
610
610
  assert out["verdict"] == "REJECT-RETRY"
611
+
612
+
613
+ # ---------------------------------------------------------------------------
614
+ # ext-append — codified append to an allowlisted ext list (ext.meshy.tasks)
615
+ # ---------------------------------------------------------------------------
616
+
617
+ class TestExtAppend:
618
+ def test_appends_record_to_allowlisted_list(self, test_repo):
619
+ _seed_item(test_repo["ledger"], "ENM-T1")
620
+ rec = {"task_id": "abc", "operation": "image-to-3d"}
621
+ _run_cli(["ext-append", "ENM-T1", "meshy.tasks", "--json", json.dumps(rec)],
622
+ test_repo["root"], expect_code=0, ledger=test_repo["ledger"])
623
+ rec2 = {"task_id": "def", "operation": "remesh"}
624
+ _run_cli(["ext-append", "ENM-T1", "meshy.tasks", "--json", json.dumps(rec2)],
625
+ test_repo["root"], expect_code=0, ledger=test_repo["ledger"])
626
+ item = _read(test_repo["ledger"])["items"][0]
627
+ assert item["ext"]["meshy"]["tasks"] == [rec, rec2]
628
+
629
+ def test_refuses_non_allowlisted_path(self, test_repo):
630
+ _seed_item(test_repo["ledger"], "ENM-T2")
631
+ r = _run_cli(["ext-append", "ENM-T2", "council_gate.cleared", "--json", "{}"],
632
+ test_repo["root"], expect_code=1, ledger=test_repo["ledger"])
633
+ assert "REFUSED" in r.stderr
634
+
635
+ def test_refuses_non_object_payload(self, test_repo):
636
+ _seed_item(test_repo["ledger"], "ENM-T3")
637
+ _run_cli(["ext-append", "ENM-T3", "meshy.tasks", "--json", "[1]"],
638
+ test_repo["root"], expect_code=1, ledger=test_repo["ledger"])
639
+
640
+ def test_unknown_item_refused(self, test_repo):
641
+ _run_cli(["ext-append", "NOPE-1", "meshy.tasks", "--json", "{}"],
642
+ test_repo["root"], expect_code=1, ledger=test_repo["ledger"])
643
+
644
+
645
+ class TestExtSet:
646
+ def test_sets_body_plan(self, test_repo):
647
+ _seed_item(test_repo["ledger"], "ENM-S1")
648
+ _run_cli(["ext-set", "ENM-S1", "body_plan", "--value", "biped"],
649
+ test_repo["root"], expect_code=0, ledger=test_repo["ledger"])
650
+ assert _read(test_repo["ledger"])["items"][0]["ext"]["body_plan"] == "biped"
651
+
652
+ def test_refuses_bad_value_and_bad_key(self, test_repo):
653
+ _seed_item(test_repo["ledger"], "ENM-S2")
654
+ _run_cli(["ext-set", "ENM-S2", "body_plan", "--value", "dragon"],
655
+ test_repo["root"], expect_code=1, ledger=test_repo["ledger"])
656
+ _run_cli(["ext-set", "ENM-S2", "council_gate", "--value", "x"],
657
+ test_repo["root"], expect_code=1, ledger=test_repo["ledger"])
658
+
659
+
660
+ class TestLedgerLock:
661
+ def test_concurrent_ext_append_loses_nothing(self, test_repo):
662
+ import subprocess as sp
663
+ _seed_item(test_repo["ledger"], "ENM-L1")
664
+ env = {**os.environ, "PYTHONIOENCODING": "utf-8", "ITEM_PY_JSON_PATH": str(test_repo["ledger"])}
665
+ n = 8
666
+ procs = [
667
+ sp.Popen([sys.executable, str(ITEM_PY), "ext-append", "ENM-L1", "meshy.tasks",
668
+ "--json", json.dumps({"task_id": f"t{i}"})],
669
+ env=env, cwd=str(test_repo["root"]), stdout=sp.PIPE, stderr=sp.PIPE)
670
+ for i in range(n)
671
+ ]
672
+ for p in procs:
673
+ p.communicate(timeout=60)
674
+ assert p.returncode == 0
675
+ tasks = _read(test_repo["ledger"])["items"][0]["ext"]["meshy"]["tasks"]
676
+ assert sorted(t["task_id"] for t in tasks) == sorted(f"t{i}" for i in range(n))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yasaswy.nagavolu/agents",
3
- "version": "0.26.3",
3
+ "version": "0.26.4",
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",