@yasaswy.nagavolu/agents 0.30.0 → 0.30.1

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 (34) hide show
  1. package/README.md +2 -0
  2. package/bin/cli.js +19 -2
  3. package/content/manifest.json +35 -0
  4. package/content/mods/handoff/lib/peek.mjs +3 -1
  5. package/content/mods/handoff/tests/peek.test.mjs +5 -0
  6. package/content/proxy/README.md +3 -3
  7. package/content/proxy/agent_model_guard.py +6 -4
  8. package/content/proxy/bg_process_reaper_hook.py +7 -9
  9. package/content/proxy/bg_process_register_hook.py +1 -0
  10. package/content/proxy/bg_process_registry.py +26 -25
  11. package/content/proxy/chat_ledger.py +15 -6
  12. package/content/proxy/log_retention.py +203 -0
  13. package/content/proxy/mem_sampler.py +36 -4
  14. package/content/proxy/memory_reclaim.py +1 -1
  15. package/content/proxy/models_config.py +2 -1
  16. package/content/proxy/proc_policy.py +19 -5
  17. package/content/proxy/route_lock.py +80 -6
  18. package/content/proxy/routing_log.py +1 -1
  19. package/content/proxy/spine_sweep.py +143 -0
  20. package/content/proxy/tracking_sweep.py +19 -1
  21. package/content/skills/heavy-gate-runner/heavy_gate_runner.py +3 -3
  22. package/content/skills/low-ram-advisor/SKILL.md +1 -1
  23. package/content/skills/low-ram-advisor/memwatch.py +22 -4
  24. package/content/skills/low-ram-advisor/tests/test_memwatch.py +25 -0
  25. package/content/skills/ship-the-code/SKILL.md +5 -6
  26. package/content/skills/ship-the-code/ship.py +125 -38
  27. package/content/skills/ship-the-code/tests/test_ship.py +7 -0
  28. package/content/skills/ship-the-code/tests/test_ship_order.py +218 -0
  29. package/lib/codex.js +2 -2
  30. package/lib/deployment.js +3 -1
  31. package/lib/modelsUsage.js +1 -1
  32. package/lib/releaseLock.js +149 -0
  33. package/lib/update.js +15 -3
  34. 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
@@ -46,6 +46,7 @@ const { checkModVersions } = require('../lib/claudeVersion');
46
46
  const memSafety = require('../lib/memSafety');
47
47
  const portalHealth = require('../lib/portalHealth');
48
48
  const { staleCheckoutGate } = require('../lib/staleCheckout');
49
+ const releaseLock = require('../lib/releaseLock');
49
50
  const claudeProfile = require('../lib/claudeProfile');
50
51
 
51
52
  const PACKAGE_ROOT = path.join(__dirname, '..');
@@ -93,6 +94,8 @@ Usage:
93
94
  The hidden ClaudeMemSampler task of the memory-safety stack (Windows).
94
95
  install/update register it on their own for the default ~/.claude install;
95
96
  --dry-run runs the registration script with -WhatIf and changes nothing
97
+ agents-cli release-lock <status|acquire|phase|release> [--pid N] [--phase P]
98
+ The lock tools/release.ps1 holds while a release runs; update into ~/.claude refuses while it is live
96
99
  agents-cli runner <sub> [flags] Install and manage a self-hosted GitLab CI runner (see "Flags for runner")
97
100
  agents-cli --help Show this help
98
101
 
@@ -139,6 +142,8 @@ Flags for update:
139
142
  --json Print a machine-readable summary instead of prose
140
143
  --theirs Non-interactive: resolve every file conflict by taking the new source
141
144
  --keep-mine Non-interactive: resolve every file conflict by keeping your on-disk version
145
+ --repair Also restore files whose source did not change but whose deployed copy differs from the
146
+ install record (normally kept as local edits); use when doctor reports drift
142
147
  --allow-stale Update even when this checkout is behind origin's default branch (default: refused;
143
148
  doctor checks ledger hashes, not source drift, so it cannot catch a stale deploy)
144
149
 
@@ -1020,7 +1025,7 @@ async function runSecrets(argv) {
1020
1025
  }
1021
1026
 
1022
1027
  function parseUpdateArgs(argv) {
1023
- const args = { bundle: null, yes: false, targetDir: null, targetConfig: null, json: false, theirs: false, keepMine: false, noScheduledTasks: false, allowStale: false };
1028
+ const args = { bundle: null, yes: false, targetDir: null, targetConfig: null, json: false, theirs: false, keepMine: false, noScheduledTasks: false, allowStale: false, repair: false };
1024
1029
  for (let i = 0; i < argv.length; i += 1) {
1025
1030
  const arg = argv[i];
1026
1031
  if (arg === '--bundle') {
@@ -1044,6 +1049,8 @@ function parseUpdateArgs(argv) {
1044
1049
  args.noScheduledTasks = true;
1045
1050
  } else if (arg === '--allow-stale') {
1046
1051
  args.allowStale = true;
1052
+ } else if (arg === '--repair') {
1053
+ args.repair = true;
1047
1054
  } else {
1048
1055
  throw new UpdateError(`Unknown update flag: ${arg}`);
1049
1056
  }
@@ -1061,7 +1068,7 @@ function summarizeBundleUpdate(b) {
1061
1068
  const parts = [];
1062
1069
  if (b.overwritten.length) parts.push(`${b.overwritten.length} overwritten`);
1063
1070
  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)`);
1071
+ if (b.kept.length) parts.push(`${b.kept.length} kept (locally edited, no upstream change; update --repair restores the source copy)`);
1065
1072
  if (b.removedUpstream.length) parts.push(`${b.removedUpstream.length} removed (no longer shipped)`);
1066
1073
  if (b.keptUpstreamUserEdited.length) {
1067
1074
  parts.push(`${b.keptUpstreamUserEdited.length} kept-but-untracked (removed upstream, locally edited)`);
@@ -1117,6 +1124,7 @@ async function runUpdate(argv) {
1117
1124
  targetBase: args.targetDir,
1118
1125
  cliVersion: pkg.version,
1119
1126
  strategy,
1127
+ repair: args.repair,
1120
1128
  mcpConfigPath: args.targetConfig,
1121
1129
  });
1122
1130
 
@@ -1603,6 +1611,11 @@ function runSampler(argv) {
1603
1611
 
1604
1612
  async function main(argv, { captureSelection = false } = {}) {
1605
1613
  const [command, ...rest] = argv;
1614
+ if (command === 'update' && !rest.includes('--target-dir') && !rest.includes('--codex-dir')) {
1615
+ const refused = releaseLock.releaseLockGate({ action: 'update' });
1616
+ if (refused !== null) return refused;
1617
+ }
1618
+
1606
1619
  if (['install','update','uninstall','doctor'].includes(command)) {
1607
1620
  const parsed = require('../lib/deployment').parseDeploymentArgs(rest);
1608
1621
  if (parsed.runtime !== 'claude') return require('../lib/deployment').runDeployment({command,argv:rest,packageRoot:PACKAGE_ROOT,cliVersion:pkg.version,runPrimary:async args=>{
@@ -1615,6 +1628,10 @@ async function main(argv, { captureSelection = false } = {}) {
1615
1628
  rest.splice(0,rest.length,...parsed.args);
1616
1629
  }
1617
1630
 
1631
+ if (command === 'release-lock') {
1632
+ return releaseLock.runReleaseLockCommand(rest);
1633
+ }
1634
+
1618
1635
  if (command === '--version' || command === '-v') {
1619
1636
  console.log(pkg.version);
1620
1637
  return 0;
@@ -275,6 +275,21 @@
275
275
  "kind": "infra",
276
276
  "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
277
  },
278
+ {
279
+ "path": "proxy/spine_sweep.py",
280
+ "kind": "infra",
281
+ "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."
282
+ },
283
+ {
284
+ "path": "proxy/route_lock.py",
285
+ "kind": "hook",
286
+ "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."
287
+ },
288
+ {
289
+ "path": "proxy/log_retention.py",
290
+ "kind": "infra",
291
+ "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."
292
+ },
278
293
  {
279
294
  "path": "proxy/headless_process.py",
280
295
  "kind": "hook",
@@ -679,6 +694,16 @@
679
694
  "kind": "infra",
680
695
  "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
696
  },
697
+ {
698
+ "path": "proxy/spine_sweep.py",
699
+ "kind": "infra",
700
+ "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."
701
+ },
702
+ {
703
+ "path": "proxy/log_retention.py",
704
+ "kind": "infra",
705
+ "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."
706
+ },
682
707
  {
683
708
  "path": "proxy/memory_reclaim.py",
684
709
  "kind": "hook",
@@ -1198,6 +1223,16 @@
1198
1223
  "kind": "infra",
1199
1224
  "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
1225
  },
1226
+ {
1227
+ "path": "proxy/spine_sweep.py",
1228
+ "kind": "infra",
1229
+ "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."
1230
+ },
1231
+ {
1232
+ "path": "proxy/log_retention.py",
1233
+ "kind": "infra",
1234
+ "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."
1235
+ },
1201
1236
  {
1202
1237
  "path": "skills/low-ram-advisor",
1203
1238
  "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: