@yasaswy.nagavolu/agents 0.30.0 → 0.30.2

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.
Files changed (46) hide show
  1. package/README.md +2 -0
  2. package/bin/cli.js +21 -3
  3. package/content/hooks/tracker_proof_gate.py +32 -13
  4. package/content/manifest.json +60 -0
  5. package/content/mods/handoff/lib/peek.mjs +3 -1
  6. package/content/mods/handoff/tests/peek.test.mjs +5 -0
  7. package/content/proxy/README.md +3 -3
  8. package/content/proxy/agent_model_guard.py +6 -4
  9. package/content/proxy/bg_process_reaper_hook.py +7 -9
  10. package/content/proxy/bg_process_register_hook.py +1 -0
  11. package/content/proxy/bg_process_registry.py +26 -25
  12. package/content/proxy/chat_ledger.py +15 -6
  13. package/content/proxy/host_busy.py +319 -0
  14. package/content/proxy/log_retention.py +221 -0
  15. package/content/proxy/mem_sampler.py +36 -4
  16. package/content/proxy/memory_reclaim.py +1 -1
  17. package/content/proxy/models_config.py +2 -1
  18. package/content/proxy/proc_policy.py +19 -5
  19. package/content/proxy/route_lock.py +80 -6
  20. package/content/proxy/routing_log.py +1 -1
  21. package/content/proxy/spine_sweep.py +143 -0
  22. package/content/proxy/tracking_sweep.py +19 -1
  23. package/content/skills/heavy-gate-runner/SKILL.md +12 -1
  24. package/content/skills/heavy-gate-runner/heavy_gate_runner.py +42 -3
  25. package/content/skills/heavy-gate-runner/tests/test_heavy_gate_runner.py +58 -0
  26. package/content/skills/low-ram-advisor/SKILL.md +1 -1
  27. package/content/skills/low-ram-advisor/memwatch.py +22 -4
  28. package/content/skills/low-ram-advisor/tests/test_memwatch.py +25 -0
  29. package/content/skills/ship-the-code/SKILL.md +8 -7
  30. package/content/skills/ship-the-code/ship.py +229 -44
  31. package/content/skills/ship-the-code/tests/test_ship.py +7 -0
  32. package/content/skills/ship-the-code/tests/test_ship_order.py +257 -0
  33. package/content/skills/ship-the-code/tests/test_ship_race.py +240 -0
  34. package/lib/codex.js +2 -2
  35. package/lib/components.js +4 -4
  36. package/lib/deployment.js +3 -1
  37. package/lib/memSafety.js +2 -1
  38. package/lib/modelsUsage.js +1 -1
  39. package/lib/pyenv.js +4 -3
  40. package/lib/releaseLock.js +150 -0
  41. package/lib/runner/janitorTask.js +2 -1
  42. package/lib/selfProfile.js +2 -1
  43. package/lib/staleCheckout.js +3 -2
  44. package/lib/testRun.js +12 -0
  45. package/lib/update.js +15 -3
  46. package/package.json +1 -1
package/README.md CHANGED
@@ -138,6 +138,8 @@ agents-cli install
138
138
  (Claude Code only matches `Edit(<path>)` for file writes); `--fix`, the `project_hook_repair.js` hook and the
139
139
  `--fix-project-hooks` flag of `install`/`update` rewrite them to `Edit(<path>)` in `settings.local.json` with duplicates
140
140
  dropped, a committed `settings.json` is reported and never edited, bare `Write`/`NotebookEdit` are left alone.
141
+ - `agents-cli update --repair` — also restores files whose source did not change but whose deployed copy differs from the install record (update otherwise keeps those as local edits, even with `--theirs`; Codex update names them and points here). Covers the Claude and Codex targets.
142
+ - `agents-cli release-lock <status|acquire|phase|release> [--pid N] [--phase P]` — the lock `tools/release.ps1` holds from its first gate to its end (`~/.claude/state/release.lock`: pid, start time, phase). While a live lock exists, `update` into the default `~/.claude` (no `--target-dir`/`--codex-dir`) and `ship.py`'s global sync refuse with exit 3, because the release's dogfood gate fails on any write into the real `~/.claude`. A lock whose pid is dead, or older than 6 hours, is stale and ignored. Skipped under `NODE_ENV=test` unless `AGENTS_CLI_RELEASE_LOCK_CHECK=1`.
141
143
  - `agents-cli sampler <status|register|unregister> [--dry-run] [--target-dir <path>]` — the hidden `ClaudeMemSampler` Windows logon task of the memory-safety stack. `install` and `update` register or start it on their own when the stack is installed (idempotent, hidden, default `~/.claude` install only, skipped under `NODE_ENV=test`; `--no-scheduled-tasks` or `AGENTS_CLI_NO_SCHEDULED_TASKS=1` skips it). `--dry-run` runs `register_mem_sampler.ps1` with `-WhatIf` and changes nothing. `doctor` adds a "Memory-safety stack" block (task, wired hooks, budget file, newest sample in `logs/mem-samples.jsonl`) and exits 1 on a missing task, an unwired hook, an invalid budget file or a stale sample. See [`docs/memory-safety.md`](../../docs/memory-safety.md).
142
144
  - `agents-cli --help` — show usage
143
145
 
package/bin/cli.js CHANGED
@@ -11,6 +11,7 @@ const pkg = JSON.parse(
11
11
 
12
12
  const { installBundle, defaultTargetBase, InstallError } = require('../lib/install');
13
13
  const { uninstallBundle, UninstallError } = require('../lib/uninstall');
14
+ const { isTestRun } = require('../lib/testRun');
14
15
  const { loadManifest, findBundle, ManifestError } = require('../lib/manifest');
15
16
  const { loadLedger, saveLedger, bundleKeysInLedger, LedgerError } = require('../lib/ledger');
16
17
  const { updateBundles, UpdateError } = require('../lib/update');
@@ -46,6 +47,7 @@ const { checkModVersions } = require('../lib/claudeVersion');
46
47
  const memSafety = require('../lib/memSafety');
47
48
  const portalHealth = require('../lib/portalHealth');
48
49
  const { staleCheckoutGate } = require('../lib/staleCheckout');
50
+ const releaseLock = require('../lib/releaseLock');
49
51
  const claudeProfile = require('../lib/claudeProfile');
50
52
 
51
53
  const PACKAGE_ROOT = path.join(__dirname, '..');
@@ -93,6 +95,8 @@ Usage:
93
95
  The hidden ClaudeMemSampler task of the memory-safety stack (Windows).
94
96
  install/update register it on their own for the default ~/.claude install;
95
97
  --dry-run runs the registration script with -WhatIf and changes nothing
98
+ agents-cli release-lock <status|acquire|phase|release> [--pid N] [--phase P]
99
+ The lock tools/release.ps1 holds while a release runs; update into ~/.claude refuses while it is live
96
100
  agents-cli runner <sub> [flags] Install and manage a self-hosted GitLab CI runner (see "Flags for runner")
97
101
  agents-cli --help Show this help
98
102
 
@@ -139,6 +143,8 @@ Flags for update:
139
143
  --json Print a machine-readable summary instead of prose
140
144
  --theirs Non-interactive: resolve every file conflict by taking the new source
141
145
  --keep-mine Non-interactive: resolve every file conflict by keeping your on-disk version
146
+ --repair Also restore files whose source did not change but whose deployed copy differs from the
147
+ install record (normally kept as local edits); use when doctor reports drift
142
148
  --allow-stale Update even when this checkout is behind origin's default branch (default: refused;
143
149
  doctor checks ledger hashes, not source drift, so it cannot catch a stale deploy)
144
150
 
@@ -1020,7 +1026,7 @@ async function runSecrets(argv) {
1020
1026
  }
1021
1027
 
1022
1028
  function parseUpdateArgs(argv) {
1023
- const args = { bundle: null, yes: false, targetDir: null, targetConfig: null, json: false, theirs: false, keepMine: false, noScheduledTasks: false, allowStale: false };
1029
+ const args = { bundle: null, yes: false, targetDir: null, targetConfig: null, json: false, theirs: false, keepMine: false, noScheduledTasks: false, allowStale: false, repair: false };
1024
1030
  for (let i = 0; i < argv.length; i += 1) {
1025
1031
  const arg = argv[i];
1026
1032
  if (arg === '--bundle') {
@@ -1044,6 +1050,8 @@ function parseUpdateArgs(argv) {
1044
1050
  args.noScheduledTasks = true;
1045
1051
  } else if (arg === '--allow-stale') {
1046
1052
  args.allowStale = true;
1053
+ } else if (arg === '--repair') {
1054
+ args.repair = true;
1047
1055
  } else {
1048
1056
  throw new UpdateError(`Unknown update flag: ${arg}`);
1049
1057
  }
@@ -1061,7 +1069,7 @@ function summarizeBundleUpdate(b) {
1061
1069
  const parts = [];
1062
1070
  if (b.overwritten.length) parts.push(`${b.overwritten.length} overwritten`);
1063
1071
  if (b.reinstalled.length) parts.push(`${b.reinstalled.length} reinstalled`);
1064
- if (b.kept.length) parts.push(`${b.kept.length} kept (locally edited, no upstream change)`);
1072
+ if (b.kept.length) parts.push(`${b.kept.length} kept (locally edited, no upstream change; update --repair restores the source copy)`);
1065
1073
  if (b.removedUpstream.length) parts.push(`${b.removedUpstream.length} removed (no longer shipped)`);
1066
1074
  if (b.keptUpstreamUserEdited.length) {
1067
1075
  parts.push(`${b.keptUpstreamUserEdited.length} kept-but-untracked (removed upstream, locally edited)`);
@@ -1117,6 +1125,7 @@ async function runUpdate(argv) {
1117
1125
  targetBase: args.targetDir,
1118
1126
  cliVersion: pkg.version,
1119
1127
  strategy,
1128
+ repair: args.repair,
1120
1129
  mcpConfigPath: args.targetConfig,
1121
1130
  });
1122
1131
 
@@ -1443,7 +1452,7 @@ function runDoctor(argv) {
1443
1452
  fix: args.fix,
1444
1453
  expectedRecords: expectedWiringRecordsForManifest(manifest, scope.targetBase),
1445
1454
  resolve: () => pyrun.resolvePython({ stateDir: path.join(scope.targetBase, 'state') }),
1446
- ...(process.env.NODE_ENV === 'test' && !process.env.AGENTS_CLI_PATH_STUBS ? { stubs: () => [] } : {}),
1455
+ ...(isTestRun() && !process.env.AGENTS_CLI_PATH_STUBS ? { stubs: () => [] } : {}),
1447
1456
  });
1448
1457
  py.fixRequested = args.fix;
1449
1458
  if (py.error) {
@@ -1603,6 +1612,11 @@ function runSampler(argv) {
1603
1612
 
1604
1613
  async function main(argv, { captureSelection = false } = {}) {
1605
1614
  const [command, ...rest] = argv;
1615
+ if (command === 'update' && !rest.includes('--target-dir') && !rest.includes('--codex-dir')) {
1616
+ const refused = releaseLock.releaseLockGate({ action: 'update' });
1617
+ if (refused !== null) return refused;
1618
+ }
1619
+
1606
1620
  if (['install','update','uninstall','doctor'].includes(command)) {
1607
1621
  const parsed = require('../lib/deployment').parseDeploymentArgs(rest);
1608
1622
  if (parsed.runtime !== 'claude') return require('../lib/deployment').runDeployment({command,argv:rest,packageRoot:PACKAGE_ROOT,cliVersion:pkg.version,runPrimary:async args=>{
@@ -1615,6 +1629,10 @@ async function main(argv, { captureSelection = false } = {}) {
1615
1629
  rest.splice(0,rest.length,...parsed.args);
1616
1630
  }
1617
1631
 
1632
+ if (command === 'release-lock') {
1633
+ return releaseLock.runReleaseLockCommand(rest);
1634
+ }
1635
+
1618
1636
  if (command === '--version' || command === '-v') {
1619
1637
  console.log(pkg.version);
1620
1638
  return 0;
@@ -81,8 +81,21 @@ NEGATION_RE = re.compile(
81
81
  NEGATION_WINDOW_CHARS = 30
82
82
 
83
83
 
84
- def _nearby(pos_a: int, pos_b: int) -> bool:
85
- return abs(pos_a - pos_b) <= PROXIMITY_CHARS
84
+ # "shipped work", "done items": the word describes a noun (a list of what
85
+ # landed), it does not claim the referenced issue is finished.
86
+ ATTRIBUTIVE_RE = re.compile(
87
+ r"\s+(work|items?|changes?|fix(?:es)?|commits?|features?|things|stuff|list)\b",
88
+ re.I,
89
+ )
90
+
91
+
92
+ def _nearby(text: str, pos_a: int, pos_b: int) -> bool:
93
+ lo, hi = sorted((pos_a, pos_b))
94
+ return hi - lo <= PROXIMITY_CHARS and "\n" not in text[lo:hi]
95
+
96
+
97
+ def _is_attributive(text: str, match_end: int) -> bool:
98
+ return ATTRIBUTIVE_RE.match(text, match_end) is not None
86
99
 
87
100
 
88
101
  def _is_negated(text: str, match_start: int) -> bool:
@@ -91,9 +104,11 @@ def _is_negated(text: str, match_start: int) -> bool:
91
104
 
92
105
 
93
106
  def _last_assistant_text(transcript_path: str) -> str:
94
- """Last assistant message's concatenated text blocks. Same pattern as
95
- conclusion_scribe_hook.py's helper of the same name (that file is not
96
- imported from here -- its own Stop-hook behavior must stay unmodified)."""
107
+ """Fallback when the Stop payload has no last_assistant_message: the
108
+ transcript may not yet hold the reply that just ended (flush race), so the
109
+ payload field is preferred. Last assistant message's concatenated text
110
+ blocks; same pattern as conclusion_scribe_hook.py's helper of the same
111
+ name (not imported -- that hook must stay unmodified)."""
97
112
  last = ""
98
113
  try:
99
114
  with open(transcript_path, "r", encoding="utf-8", errors="replace") as fh:
@@ -124,21 +139,23 @@ def _last_assistant_text(transcript_path: str) -> str:
124
139
 
125
140
  def _find_claim(text: str) -> tuple[str | None, int] | None:
126
141
  """Scans for completion language co-occurring with an issue reference
127
- within PROXIMITY_CHARS -- a char-distance window rather than strict
128
- same-sentence matching, since a natural claim often reads "Shipped! See
129
- https://gitlab.com/.../issues/42 for details." across two sentences. A
130
- full URL match (explicit slug) wins over a bare #N. Deliberately simple:
142
+ within PROXIMITY_CHARS on the same line -- a char-distance window rather
143
+ than strict same-sentence matching, since a natural claim often reads
144
+ "Shipped! See https://gitlab.com/.../issues/42 for details." across two
145
+ sentences. A line break ends the window: list and table rows are separate
146
+ statements. A full URL match (explicit slug) wins over a bare #N. Deliberately simple:
131
147
  false negatives here are safer than false positives."""
132
148
  completions = [
133
- m.start() for m in COMPLETION_RE.finditer(text) if not _is_negated(text, m.start())
149
+ m.start() for m in COMPLETION_RE.finditer(text)
150
+ if not _is_negated(text, m.start()) and not _is_attributive(text, m.end())
134
151
  ]
135
152
  if not completions:
136
153
  return None
137
154
  for m in ISSUE_URL_RE.finditer(text):
138
- if any(_nearby(m.start(), c) for c in completions):
155
+ if any(_nearby(text, m.start(), c) for c in completions):
139
156
  return m.group(1), int(m.group(2))
140
157
  for m in BARE_ISSUE_RE.finditer(text):
141
- if any(_nearby(m.start(), c) for c in completions):
158
+ if any(_nearby(text, m.start(), c) for c in completions):
142
159
  return None, int(m.group(1))
143
160
  return None
144
161
 
@@ -217,7 +234,9 @@ def _safe_main() -> None:
217
234
  return
218
235
  if data.get("hook_event_name") != "Stop":
219
236
  return
220
- text = _last_assistant_text(data.get("transcript_path") or "")
237
+ text = data.get("last_assistant_message")
238
+ if not isinstance(text, str) or not text.strip():
239
+ text = _last_assistant_text(data.get("transcript_path") or "")
221
240
  if not text:
222
241
  return
223
242
  try:
@@ -99,6 +99,21 @@
99
99
  "test_scribe_runner.py"
100
100
  ],
101
101
  "note": "ship.py loads scribe_runner.py by file path for its GitLab helpers (skills/ship-the-code/ship.py scribe_agent_path); scribe_runner.py launches scribe_item_read.py/scribe_item_write.py, so the folder ships whole. Also claimed by agent-orchestration; safe to double-claim."
102
+ },
103
+ {
104
+ "path": "proxy/host_busy.py",
105
+ "kind": "infra",
106
+ "note": "Machine-wide host-busy signal (device trains hold it; heavy gates, ship test gate and release.ps1 wait for idle) imported by heavy_gate_runner.py and ship.py — not wired to an event itself."
107
+ },
108
+ {
109
+ "path": "proxy/chat_ledger.py",
110
+ "kind": "hook",
111
+ "note": "Chat ledger and process lookup library imported by host_busy.py (ship.py test-gate wait) — not wired to an event itself. Also claimed by other bundles; safe to double-claim."
112
+ },
113
+ {
114
+ "path": "proxy/headless_process.py",
115
+ "kind": "hook",
116
+ "note": "Shared no-visible-window subprocess wrapper imported by chat_ledger.py — not wired to an event itself. Also claimed by other bundles; safe to double-claim."
102
117
  }
103
118
  ],
104
119
  "deps": [],
@@ -275,6 +290,21 @@
275
290
  "kind": "infra",
276
291
  "note": "Bounded cleanup of cross-chat tracking state (ledger, heartbeats, armed-review flags, Metro slots, spine history) run from the mem_sampler tick; fail-open per step — not wired to a settings.json event."
277
292
  },
293
+ {
294
+ "path": "proxy/spine_sweep.py",
295
+ "kind": "infra",
296
+ "note": "Frees Metro slots of deleted or empty checkouts and drives the project's spine_registry.py for dead claims and old history; imported by tracking_sweep.py — not wired to a settings.json event."
297
+ },
298
+ {
299
+ "path": "proxy/route_lock.py",
300
+ "kind": "hook",
301
+ "note": "Pending-review flag and armed-repo registry library whose sweep_armed is run by tracking_sweep.py — not wired to an event itself. Also claimed by other bundles; safe to double-claim."
302
+ },
303
+ {
304
+ "path": "proxy/log_retention.py",
305
+ "kind": "infra",
306
+ "note": "Bounded retention for ~/.claude logs, imported lazily by mem_sampler.py on an hourly tick; also claimed by every bundle that ships mem_sampler.py, safe to double-claim."
307
+ },
278
308
  {
279
309
  "path": "proxy/headless_process.py",
280
310
  "kind": "hook",
@@ -294,6 +324,11 @@
294
324
  "path": "skills/low-ram-advisor",
295
325
  "kind": "skill",
296
326
  "note": "Ranking logic imported by memory_reclaim.py; also its own bundle, safe to double-claim."
327
+ },
328
+ {
329
+ "path": "proxy/host_busy.py",
330
+ "kind": "infra",
331
+ "note": "Machine-wide host-busy signal (device trains hold it; heavy gates, ship test gate and release.ps1 wait for idle) imported by heavy_gate_runner.py and ship.py — not wired to an event itself."
297
332
  }
298
333
  ],
299
334
  "deps": [],
@@ -679,6 +714,16 @@
679
714
  "kind": "infra",
680
715
  "note": "Bounded cleanup of cross-chat tracking state (ledger, heartbeats, armed-review flags, Metro slots, spine history) run from the mem_sampler tick; fail-open per step — not wired to a settings.json event."
681
716
  },
717
+ {
718
+ "path": "proxy/spine_sweep.py",
719
+ "kind": "infra",
720
+ "note": "Frees Metro slots of deleted or empty checkouts and drives the project's spine_registry.py for dead claims and old history; imported by tracking_sweep.py — not wired to a settings.json event."
721
+ },
722
+ {
723
+ "path": "proxy/log_retention.py",
724
+ "kind": "infra",
725
+ "note": "Bounded retention for ~/.claude logs, imported lazily by mem_sampler.py on an hourly tick; also claimed by every bundle that ships mem_sampler.py, safe to double-claim."
726
+ },
682
727
  {
683
728
  "path": "proxy/memory_reclaim.py",
684
729
  "kind": "hook",
@@ -776,6 +821,11 @@
776
821
  "kind": "hook",
777
822
  "targetPath": "hooks/pyrun.js",
778
823
  "note": "Run-time Python resolver every Python hook command goes through (node ~/.claude/hooks/pyrun.js <script>); the CLI (packages/cli/lib/pyrun.js) re-exports this same file for doctor/update/install."
824
+ },
825
+ {
826
+ "path": "proxy/host_busy.py",
827
+ "kind": "infra",
828
+ "note": "Machine-wide host-busy signal (device trains hold it; heavy gates, ship test gate and release.ps1 wait for idle) imported by heavy_gate_runner.py and ship.py — not wired to an event itself."
779
829
  }
780
830
  ],
781
831
  "deps": [
@@ -1198,6 +1248,16 @@
1198
1248
  "kind": "infra",
1199
1249
  "note": "Bounded cleanup of cross-chat tracking state (ledger, heartbeats, armed-review flags, Metro slots, spine history) run from the mem_sampler tick; fail-open per step — not wired to a settings.json event."
1200
1250
  },
1251
+ {
1252
+ "path": "proxy/spine_sweep.py",
1253
+ "kind": "infra",
1254
+ "note": "Frees Metro slots of deleted or empty checkouts and drives the project's spine_registry.py for dead claims and old history; imported by tracking_sweep.py — not wired to a settings.json event."
1255
+ },
1256
+ {
1257
+ "path": "proxy/log_retention.py",
1258
+ "kind": "infra",
1259
+ "note": "Bounded retention for ~/.claude logs, imported lazily by mem_sampler.py on an hourly tick; also claimed by every bundle that ships mem_sampler.py, safe to double-claim."
1260
+ },
1201
1261
  {
1202
1262
  "path": "skills/low-ram-advisor",
1203
1263
  "kind": "skill",
@@ -10,7 +10,9 @@ export function recentDispatchNames(raw, limit) {
10
10
  for (const line of lines) {
11
11
  if (names.length >= limit) break
12
12
  try {
13
- const name = JSON.parse(line).name
13
+ const row = JSON.parse(line)
14
+ if (row.test_run) continue
15
+ const name = row.name
14
16
  if (typeof name === 'string' && name !== '' && !names.includes(name)) names.push(name)
15
17
  } catch (err) {
16
18
  continue
@@ -85,6 +85,11 @@ test('recentDispatchNames returns unique names, newest first, skipping bad rows'
85
85
  assert.deepEqual(recentDispatchNames(undefined, 5), [])
86
86
  })
87
87
 
88
+ test('recentDispatchNames skips rows written by a test run', () => {
89
+ const raw = ['{"name":"real"}', '{"name":"n","test_run":"abc"}'].join('\n')
90
+ assert.deepEqual(recentDispatchNames(raw, 5), ['real'])
91
+ })
92
+
88
93
  test('denyText turns host refusals into plain sentences', () => {
89
94
  assert.match(denyText('no main view here', 'w'), /interactive/)
90
95
  assert.match(denyText('not person-initiated', 'w'), /you type/)
@@ -223,14 +223,14 @@ Installed by the `agent-orchestration` bundle (my-agents#57). Rules, install, co
223
223
 
224
224
  ---
225
225
 
226
- ## bg_process_reaper (background dev-server cleanup at Stop)
226
+ ## bg_process_reaper (turn-end bookkeeping for recorded background launches)
227
227
 
228
228
  Stops the background dev servers (Expo/Metro/npm/yarn/jest) that a finishing subagent or session launched. Ownership rules, the never-list and the cross-chat reclaimer live in one place: [`docs/memory-safety.md`](../docs/memory-safety.md). This section only describes the hooks.
229
229
 
230
230
  Three files, sharing state through a JSON registry at `~/.claude/logs/bg_process_registry.json` and the chat ledger (`chat_ledger.py`):
231
231
  - `bg_process_registry.py` - shared library (not wired): dev-server-launch detection (`is_dev_server_launch`, shlex-token-exact matching so a launch string quoted in a commit message never matches), the registry read/write, and `reap`.
232
232
  - `bg_process_register_hook.py` (`PostToolUse`, matcher `Bash`) - when a Bash call has `run_in_background: true` and its command matches a dev-server launch shape, records the launch in the registry and writes ledger rows (pid + create_time) for the new process roots under the session's Claude process.
233
- - `bg_process_reaper_hook.py` (`SubagentStop` AND `Stop`, same script, dispatched by `hook_event_name`) - on `SubagentStop`, stops the non-`keep_alive` entries of that `session_id`+`agent_id`; on `Stop`, stops the remaining entries of that `session_id`. A pid is stopped only with ledger proof owned by the stopping session, graceful first, then the proven tree. Nothing is stopped by age, by command-line match or for another session. The cross-chat idle stop is the reclaimer's job, not this hook's.
233
+ - `bg_process_reaper_hook.py` (`SubagentStop` AND `Stop`, same script, dispatched by `hook_event_name`) - bookkeeping only: it stops nothing. Background (`run_in_background`) and detached launches outlive the turn by design; their entries are logged `KEPT` and dropped from the registry, the ledger rows (which carry `mode`) stay. Only the idle reclaimer may stop them (15 min, 3 looks, owner turn not running) and never while the owner chat is alive. Force-stop is limited to the idle reclaimer and gate cleanup (`stop_proven(force=True)`).
234
234
 
235
235
  **Escape hatch (intentionally-persistent servers)** - an entry is marked `keep_alive` and never stopped if either:
236
236
  1. the launching command contains the literal marker `# keep-alive`, or
@@ -258,7 +258,7 @@ Wire into `~/.claude/settings.json`:
258
258
  ]}]
259
259
  ```
260
260
 
261
- **Verify** - `proxy/tests/test_bg_process_reaper.py` covers the proof-based stop: only the stopping session's ledger-proven pids are stopped, and another session's stale entry is never touched.
261
+ **Verify** - `proxy/tests/test_bg_process_reaper.py` covers that Stop and SubagentStop leave a recorded background launch running, that own-scope cleanup refuses it, and that the idle reclaimer keeps it while its owner is alive.
262
262
 
263
263
  ---
264
264
 
@@ -278,11 +278,11 @@ def _review_targets(cwd: str, prompt: str) -> list[str]:
278
278
  return route_lock.review_target_toplevels(cwd, prompt, _parse_worktree_targets(prompt))
279
279
 
280
280
 
281
- def _mark_pending_review_per_target(cwd: str, prompt: str, targets: list[str] | None = None) -> list[str]:
282
- """Arms the flag in each distinct target toplevel (never only the session cwd); returns the targets marked."""
281
+ def _mark_pending_review_per_target(cwd: str, prompt: str, targets: list[str] | None = None, session_id: str | None = None) -> list[str]:
282
+ """Arms the flag in each distinct target toplevel (never only the session cwd), owned by the dispatching session; returns the targets marked."""
283
283
  targets = targets if targets is not None else _review_targets(cwd, prompt)
284
284
  for target in targets:
285
- route_lock.mark_pending_review(target)
285
+ route_lock.mark_pending_review(target, session_id)
286
286
  return targets
287
287
 
288
288
 
@@ -324,6 +324,8 @@ def _log_dispatch(session_id: str, name: str, subagent_type: str, model: str | N
324
324
  "role": role,
325
325
  }
326
326
  record.update(extra or {})
327
+ if os.environ.get("MA_TEST_RUN_ID"):
328
+ record["test_run"] = os.environ["MA_TEST_RUN_ID"]
327
329
  line = json.dumps(record) + "\n"
328
330
  fd = os.open(log_path, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o644)
329
331
  try:
@@ -638,7 +640,7 @@ def _safe_main() -> None:
638
640
  dispatch_tier = route_lock.agent_dispatch_tier(subagent_type, cwd) if subagent_type else None
639
641
  if dispatch_tier == "mandatory-review":
640
642
  if route_lock.is_farm_style_project(cwd):
641
- _mark_pending_review_per_target(cwd, prompt, review_targets)
643
+ _mark_pending_review_per_target(cwd, prompt, review_targets, str(data.get("session_id") or "") or None)
642
644
  elif dispatch_tier == "safe":
643
645
  pass # a worktree's flag is cleared only by a verified scripts/review_pass.py stamp, never by dispatching a reviewer
644
646
  elif subagent_type and _find_agent_file(subagent_type, cwd) and route_lock.is_farm_style_project(cwd):
@@ -1,13 +1,11 @@
1
1
  #!/usr/bin/env python3
2
- """bg_process_reaper_hook.py — SubagentStop and Stop hook that stops background dev-server
3
- processes (Expo/Metro/npm/yarn/jest) the finishing subagent/session launched, using the
4
- registry and chat_ledger rows written by bg_process_register_hook.py.
2
+ """bg_process_reaper_hook.py — SubagentStop and Stop hook: turn-end bookkeeping for the launches recorded by
3
+ bg_process_register_hook.py. It stops NO process: background and detached launches outlive the turn by design;
4
+ only the idle reclaimer (proc_policy scope "idle") may stop them, and never while the owner chat is alive.
5
5
 
6
- - SubagentStop: entries of that session_id+agent_id only.
7
- - Stop: all remaining entries of that session_id; also marks the session turn as not running.
8
- - A pid is stopped only with ledger proof owned by the stopping session (graceful first, then
9
- the proven tree); spine-claimed, fresh-heartbeat and unreadable-proof cases are kept.
10
- - Registry entries whose processes are all gone are dropped; nothing is stopped by age or by owner-blind sweep.
6
+ - SubagentStop: entries of that session_id+agent_id are logged as kept and dropped from the registry.
7
+ - Stop: same for all remaining entries of that session_id; also marks the session turn as not running.
8
+ - Registry entries whose processes are all gone are dropped; ledger rows stay for the idle reclaimer.
11
9
  - Every invocation also calls bg_process_registry.sweep_spine_dead_locks(cwd) (no-op without the spine skill).
12
10
 
13
11
  Fail-open: any malformed input or internal error exits 0, never blocks
@@ -57,7 +55,7 @@ def _safe_main() -> int:
57
55
  else:
58
56
  owned = []
59
57
  if owned:
60
- processed = registry.reap(owned, reason=hook_event or "stop", invoker_session=session_id)
58
+ processed = registry.release_at_turn_end(owned, reason=hook_event or "stop")
61
59
  to_remove.update(e["id"] for e in processed)
62
60
 
63
61
  dead = [e for e in registry.dead_entries(ledger.snapshot()) if e["id"] not in to_remove]
@@ -60,6 +60,7 @@ def _safe_main() -> int:
60
60
  label=label,
61
61
  keep_alive=keep_alive,
62
62
  window_s=window_s,
63
+ mode=registry.launch_mode(tool_input),
63
64
  )
64
65
  registry.record_entry_launch(entry)
65
66
  ledger.heartbeat(payload.get("session_id") or "", cwd=payload.get("cwd"))
@@ -3,8 +3,7 @@
3
3
 
4
4
  Not itself a hook. Imported by bg_process_register_hook.py (PostToolUse: records the launch and
5
5
  writes chat_ledger rows for the new process roots under the session's Claude process) and
6
- bg_process_reaper_hook.py (SubagentStop/Stop: stops only pids with ledger proof owned by the
7
- stopping session, graceful first, via proc_policy). Command-line text is never ownership proof.
6
+ bg_process_reaper_hook.py (SubagentStop/Stop: bookkeeping only, stops nothing). Command-line text is never ownership proof.
8
7
  """
9
8
  from __future__ import annotations
10
9
 
@@ -40,7 +39,6 @@ DISCOVERY_ATTEMPTS = 4
40
39
  DISCOVERY_DELAY_SECONDS = 0.5
41
40
  DETACHED_WINDOW_SECONDS = 60
42
41
  FRAGMENT_CHARS = 60
43
- RETAIN_REASONS = {"spine_claim", "fresh_heartbeat", "proof_unreadable"}
44
42
 
45
43
  # Agents/skills allowed to leave a background process running on purpose
46
44
  # (the escape hatch besides the inline `# keep-alive` command marker).
@@ -146,6 +144,11 @@ def launch_label(tool_input: dict) -> str | None:
146
144
  return "detached" if _DETACH_RE.search(command) else None
147
145
 
148
146
 
147
+ def launch_mode(tool_input: dict) -> str:
148
+ """How the process was launched: "background" (harness run_in_background task, outlives the turn by design) or "detached" (command text starts it)."""
149
+ return "background" if tool_input.get("run_in_background") else "detached"
150
+
151
+
149
152
  def call_window_seconds(label: str, duration_ms: object) -> float:
150
153
  """How far back from the hook a launch can have started: the tool call's own duration when reported, else a bounded default for detached launches."""
151
154
  if isinstance(duration_ms, (int, float)) and not isinstance(duration_ms, bool):
@@ -177,7 +180,8 @@ def _save_raw(entries: list[dict]) -> bool:
177
180
 
178
181
 
179
182
  def add_entry(*, session_id: str, agent_id: str | None, agent_type: str | None,
180
- cwd: str | None, command: str, label: str, keep_alive: bool, window_s: float = 0.0) -> dict:
183
+ cwd: str | None, command: str, label: str, keep_alive: bool, window_s: float = 0.0,
184
+ mode: str = "background") -> dict:
181
185
  entry = {
182
186
  "pids": [],
183
187
  "id": str(uuid.uuid4()),
@@ -189,6 +193,7 @@ def add_entry(*, session_id: str, agent_id: str | None, agent_type: str | None,
189
193
  "label": label,
190
194
  "ts": time.time(),
191
195
  "window_s": window_s,
196
+ "mode": mode,
192
197
  "keep_alive": keep_alive,
193
198
  }
194
199
  entries = _load_raw()
@@ -296,6 +301,14 @@ def _spelled_in_command(name: str, cmdline: str, command: str) -> bool:
296
301
  return all(_QUOTES_RE.sub("", t).strip(",").lower() in text for t in tokens)
297
302
 
298
303
 
304
+ def _parent_gone(p: dict, procs: ledger.ProcTable) -> bool:
305
+ """True when the launching parent is dead: missing from the table (Windows), re-parented to init (POSIX), or a reused pid younger than the child."""
306
+ if p["ppid"] <= 1:
307
+ return True
308
+ parent = procs.get(p["ppid"])
309
+ return parent is None or parent["create_time"] > p["create_time"] + ledger.CTIME_TOLERANCE
310
+
311
+
299
312
  def _orphan_roots(entry: dict, procs: ledger.ProcTable, since: float) -> list[dict]:
300
313
  """Detached processes whose launching shell already exited cannot be tied to Claude by ancestry; accepted only when no other
301
314
  live session has a turn running, the parent is gone, the process started inside the call window, and its image name appears in
@@ -306,7 +319,7 @@ def _orphan_roots(entry: dict, procs: ledger.ProcTable, since: float) -> list[di
306
319
  out = []
307
320
  for p in procs.values():
308
321
  stem = os.path.splitext((p["name"] or "").lower())[0]
309
- if (p["create_time"] >= since and p["pid"] != os.getpid() and procs.get(p["ppid"]) is None
322
+ if (p["create_time"] >= since and p["pid"] != os.getpid() and _parent_gone(p, procs)
310
323
  and len(stem) >= 3 and stem in command.lower() and not ledger._is_claude(p["name"], p["cmdline"])
311
324
  and "pyrun.js" not in p["cmdline"] and _spelled_in_command(p["name"], p["cmdline"], command)):
312
325
  out.append(p)
@@ -318,7 +331,7 @@ def discover_launch_roots(entry: dict, procs: ledger.ProcTable, claude: dict) ->
318
331
  subtree; other launches need the command text in the subtree's command lines (ancestry is the proof, the text only picks among
319
332
  the session's concurrent shells). Detached launches add window-attributed orphans."""
320
333
  since = entry["ts"] - (entry.get("window_s") or 0) - DISCOVERY_SLACK_SECONDS
321
- known = {(r["pid"], round(r["create_time"], 1)) for r in ledger.ledger_rows()}
334
+ known = {(r["pid"], round(r["create_time"], 1)) for r in ledger.recent_rows()}
322
335
  skip = _own_chain(procs, claude)
323
336
  frag = _fragment(entry.get("command"))
324
337
  dev = entry.get("label") not in ("background", "detached")
@@ -354,7 +367,7 @@ def record_entry_launch(entry: dict, claude: dict | None = None) -> list[dict]:
354
367
  for r in roots:
355
368
  row = ledger.record_launch(r["pid"], session_id=entry["session_id"], agent_id=agent, kind=entry["label"],
356
369
  source="bg_process_register_hook", cwd=entry.get("cwd"),
357
- create_time=r["create_time"])
370
+ create_time=r["create_time"], mode=entry.get("mode"))
358
371
  if row:
359
372
  rec.append({"pid": r["pid"], "create_time": r["create_time"]})
360
373
  set_entry_pids(entry["id"], rec)
@@ -440,22 +453,10 @@ def sweep_spine_dead_locks(cwd: str | None) -> None:
440
453
  pass
441
454
 
442
455
 
443
- def reap(entries: list[dict], *, reason: str, invoker_session: str | None = None, dry_run: bool = False) -> list[dict]:
444
- """Stop proven-own processes of each non-keep_alive entry, graceful first. Returns entries to drop from the
445
- registry; entries holding a spine claim, a fresh heartbeat or an unreadable proof stay tracked."""
446
- processed = []
456
+ def release_at_turn_end(entries: list[dict], *, reason: str) -> list[dict]:
457
+ """Turn end never stops anything: background and detached launches outlive the turn by design. Logs each recorded pid as
458
+ kept and returns the entries to drop from the registry; the ledger rows stay for the idle reclaimer."""
447
459
  for entry in entries:
448
- if entry.get("keep_alive"):
449
- _log(f"SKIP keep_alive id={entry['id']} cmd={entry.get('command')!r} reason={reason}")
450
- processed.append(entry)
451
- continue
452
- candidates = [(p["pid"], p["create_time"]) for p in entry.get("pids") or []]
453
- results = proc_policy.run_cleanup(
454
- candidates, invoker_session=invoker_session or entry.get("session_id"), scope="own",
455
- spine_check=lambda pid, cwd: is_spine_claimed(pid, cwd), dry_run=dry_run, reason=reason)
456
- for r in results:
457
- _log(f"{r['result'].upper()} id={entry['id']} pid={r['pid']} decision={r['decision']} why={r['reason']} reason={reason}")
458
- if any(r["reason"] in RETAIN_REASONS for r in results):
459
- continue
460
- processed.append(entry)
461
- return processed
460
+ for p in entry.get("pids") or []:
461
+ _log(f"KEPT id={entry['id']} pid={p['pid']} decision=keep why=outlives_turn mode={entry.get('mode') or 'background'} reason={reason}")
462
+ return list(entries)
@@ -184,7 +184,8 @@ def _append_line_text(path: str, line: str) -> bool:
184
184
  with open(path, "a", encoding="utf-8") as fh:
185
185
  fh.write(line)
186
186
 
187
- return _retry_io(op)
187
+ with _Locked(path):
188
+ return _retry_io(op)
188
189
 
189
190
 
190
191
  def _read_lines(path: str) -> list[dict]:
@@ -441,7 +442,7 @@ def current_claude(procs: Any = None) -> dict | None:
441
442
 
442
443
  def record_launch(pid: int, *, session_id: str, kind: str, source: str, agent_id: str | None = None,
443
444
  cwd: str | None = None, create_time: float | None = None,
444
- procs: Any = None) -> dict | None:
445
+ procs: Any = None, mode: str | None = None) -> dict | None:
445
446
  if create_time is None:
446
447
  info = as_table(procs if procs is not None else snapshot()).get(pid)
447
448
  if not info:
@@ -449,6 +450,8 @@ def record_launch(pid: int, *, session_id: str, kind: str, source: str, agent_id
449
450
  create_time = info["create_time"]
450
451
  row = {"pid": pid, "create_time": round(float(create_time), 3), "session_id": session_id or "",
451
452
  "agent_id": agent_id, "kind": kind, "source": source, "cwd": cwd, "launched_at": time.time()}
453
+ if mode:
454
+ row["mode"] = mode
452
455
  with _Locked("chat_ledger"):
453
456
  try:
454
457
  existing = _read_tail_lines(_path("chat_ledger.jsonl"), DEDUPE_TAIL_BYTES)
@@ -474,6 +477,11 @@ def _read_head_row(path: str) -> dict | None:
474
477
  return row if isinstance(row, dict) else None
475
478
 
476
479
 
480
+ def recent_rows() -> list[dict]:
481
+ """Rows from the ledger tail (last DEDUPE_TAIL_BYTES); enough to tell whether a just-started process is already recorded."""
482
+ return _read_tail_lines(_path("chat_ledger.jsonl"), DEDUPE_TAIL_BYTES)
483
+
484
+
477
485
  def ledger_rows() -> list[dict]:
478
486
  return _read_lines(_path("chat_ledger.jsonl"))
479
487
 
@@ -746,10 +754,11 @@ def consume_notes(session_id: str) -> list[dict]:
746
754
  if not os.path.exists(src):
747
755
  return []
748
756
  taken = f"{src}.{os.getpid()}.{threading.get_ident()}.taken"
749
- try:
750
- os.replace(src, taken)
751
- except OSError:
752
- return []
757
+ with _Locked(src):
758
+ try:
759
+ os.replace(src, taken)
760
+ except OSError:
761
+ return []
753
762
  try:
754
763
  return _read_lines(taken)
755
764
  except ProofUnreadable: