@yasaswy.nagavolu/agents 0.30.1 → 0.30.3

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 (45) hide show
  1. package/bin/cli.js +2 -1
  2. package/content/hooks/tracker_proof_gate.py +32 -13
  3. package/content/manifest.json +50 -1
  4. package/content/proxy/host_busy.py +319 -0
  5. package/content/proxy/log_retention.py +21 -3
  6. package/content/proxy/mem_sampler.py +8 -1
  7. package/content/proxy/memory_reclaim.py +3 -1
  8. package/content/skills/README.md +6 -2
  9. package/content/skills/heavy-gate-runner/SKILL.md +12 -1
  10. package/content/skills/heavy-gate-runner/heavy_gate_runner.py +39 -0
  11. package/content/skills/heavy-gate-runner/tests/test_heavy_gate_runner.py +58 -0
  12. package/content/skills/low-ram-advisor/SKILL.md +13 -1
  13. package/content/skills/low-ram-advisor/deep_report.py +19 -9
  14. package/content/skills/low-ram-advisor/handlecount.py +80 -0
  15. package/content/skills/low-ram-advisor/memwatch.py +24 -4
  16. package/content/skills/low-ram-advisor/pooltags.py +5 -2
  17. package/content/skills/low-ram-advisor/ram_optimize.py +178 -0
  18. package/content/skills/low-ram-advisor/ram_prompt.py +46 -5
  19. package/content/skills/low-ram-advisor/ram_thresholds.py +13 -0
  20. package/content/skills/low-ram-advisor/ramstatus.py +121 -0
  21. package/content/skills/low-ram-advisor/restart_verdict.py +72 -0
  22. package/content/skills/low-ram-advisor/tests/test_deep_report.py +10 -3
  23. package/content/skills/low-ram-advisor/tests/test_handlecount.py +36 -0
  24. package/content/skills/low-ram-advisor/tests/test_ram_optimize.py +155 -0
  25. package/content/skills/low-ram-advisor/tests/test_restart_verdict.py +123 -0
  26. package/content/skills/ram/SKILL.md +26 -0
  27. package/content/skills/ship-the-code/SKILL.md +5 -3
  28. package/content/skills/ship-the-code/ship.py +108 -10
  29. package/content/skills/ship-the-code/tests/test_ship_order.py +45 -6
  30. package/content/skills/ship-the-code/tests/test_ship_race.py +240 -0
  31. package/lib/components.js +4 -4
  32. package/lib/memSafety.js +2 -1
  33. package/lib/pyenv.js +4 -3
  34. package/lib/releaseLock.js +3 -2
  35. package/lib/runner/exec.js +2 -2
  36. package/lib/runner/index.js +6 -1
  37. package/lib/runner/janitorTask.js +2 -1
  38. package/lib/runner/managed.js +1 -1
  39. package/lib/runner/pool.js +1 -1
  40. package/lib/runner/profiles/linuxDocker.js +1 -1
  41. package/lib/runner/profiles/macosShell.js +1 -1
  42. package/lib/selfProfile.js +2 -1
  43. package/lib/staleCheckout.js +3 -2
  44. package/lib/testRun.js +12 -0
  45. package/package.json +1 -1
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');
@@ -1451,7 +1452,7 @@ function runDoctor(argv) {
1451
1452
  fix: args.fix,
1452
1453
  expectedRecords: expectedWiringRecordsForManifest(manifest, scope.targetBase),
1453
1454
  resolve: () => pyrun.resolvePython({ stateDir: path.join(scope.targetBase, 'state') }),
1454
- ...(process.env.NODE_ENV === 'test' && !process.env.AGENTS_CLI_PATH_STUBS ? { stubs: () => [] } : {}),
1455
+ ...(isTestRun() && !process.env.AGENTS_CLI_PATH_STUBS ? { stubs: () => [] } : {}),
1455
1456
  });
1456
1457
  py.fixRequested = args.fix;
1457
1458
  if (py.error) {
@@ -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": [],
@@ -219,6 +234,10 @@
219
234
  {
220
235
  "path": "skills/low-ram-advisor",
221
236
  "kind": "skill"
237
+ },
238
+ {
239
+ "path": "skills/ram",
240
+ "kind": "skill"
222
241
  }
223
242
  ],
224
243
  "deps": [],
@@ -309,6 +328,11 @@
309
328
  "path": "skills/low-ram-advisor",
310
329
  "kind": "skill",
311
330
  "note": "Ranking logic imported by memory_reclaim.py; also its own bundle, safe to double-claim."
331
+ },
332
+ {
333
+ "path": "proxy/host_busy.py",
334
+ "kind": "infra",
335
+ "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."
312
336
  }
313
337
  ],
314
338
  "deps": [],
@@ -714,6 +738,11 @@
714
738
  "kind": "skill",
715
739
  "note": "Ranking logic imported by memory_reclaim.py; also its own bundle, safe to double-claim."
716
740
  },
741
+ {
742
+ "path": "skills/ram",
743
+ "kind": "skill",
744
+ "note": "Thin /ram entry point over skills/low-ram-advisor/ram_optimize.py; also its own claim in low-ram-advisor, safe to double-claim."
745
+ },
717
746
  {
718
747
  "path": "proxy/memory_reclaim_hook.py",
719
748
  "kind": "hook",
@@ -801,6 +830,11 @@
801
830
  "kind": "hook",
802
831
  "targetPath": "hooks/pyrun.js",
803
832
  "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."
833
+ },
834
+ {
835
+ "path": "proxy/host_busy.py",
836
+ "kind": "infra",
837
+ "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."
804
838
  }
805
839
  ],
806
840
  "deps": [
@@ -1236,7 +1270,12 @@
1236
1270
  {
1237
1271
  "path": "skills/low-ram-advisor",
1238
1272
  "kind": "skill",
1239
- "note": "memwatch.py, memprobe.py, pooltags.py and autofree.py are loaded by file path from mem_sampler.py for the leak watch and WSL cache auto-free; also its own bundle and claimed by heavy-gate-runner and agent-orchestration, safe to double-claim."
1273
+ "note": "memwatch.py, memprobe.py, pooltags.py, autofree.py, restart_verdict.py, ram_thresholds.py and handlecount.py are loaded by file path from mem_sampler.py for the leak watch and WSL cache auto-free; also its own bundle and claimed by heavy-gate-runner and agent-orchestration, safe to double-claim."
1274
+ },
1275
+ {
1276
+ "path": "skills/ram",
1277
+ "kind": "skill",
1278
+ "note": "Thin /ram entry point over skills/low-ram-advisor/ram_optimize.py; also its own claim in low-ram-advisor, safe to double-claim."
1240
1279
  },
1241
1280
  {
1242
1281
  "path": "proxy/proc_policy.py",
@@ -1557,6 +1596,11 @@
1557
1596
  "path": "scripts",
1558
1597
  "kind": "infra"
1559
1598
  },
1599
+ {
1600
+ "path": "proxy/route_lock.py",
1601
+ "kind": "infra",
1602
+ "note": "Imported by scripts/backfill_armed_repos.py (route-lock state reader) - not wired to an event itself. Already deployed by other bundles too; safe to double-claim, install.js is idempotent per-file."
1603
+ },
1560
1604
  {
1561
1605
  "path": "proxy/agents_env.py",
1562
1606
  "kind": "hook",
@@ -1970,6 +2014,11 @@
1970
2014
  "kind": "hook",
1971
2015
  "note": "Shared reader of models.json imported by the model-aware hooks."
1972
2016
  },
2017
+ {
2018
+ "path": "proxy/project_resolver.py",
2019
+ "kind": "infra",
2020
+ "note": "Shared GitLab-project-slug resolver the hook imports (and its tests) - not wired to an event itself. Already deployed by other bundles too; safe to double-claim, install.js is idempotent per-file."
2021
+ },
1973
2022
  {
1974
2023
  "path": "hooks/conclusion-scribe",
1975
2024
  "targetPath": "hooks",
@@ -0,0 +1,319 @@
1
+ #!/usr/bin/env python3
2
+ """host_busy.py - one machine-wide "host busy" signal for device trains (phone or emulator runs); heavy work of other chats waits for idle (my-agents#55).
3
+
4
+ python host_busy.py status [--json] # exit 0 idle, 3 busy
5
+ python host_busy.py set --reason TEXT [--owner ID] [--pid N] [--ttl-s N]
6
+ python host_busy.py clear [--owner ID]
7
+ python host_busy.py wait [--label L] [--timeout-s N] [--override] # exit 0 idle or overridden, 3 timed out
8
+
9
+ Busy comes from two sources. A spine claim (device-serial or maestro-driver-port in maestro_launch_spine.db) whose pid still runs makes
10
+ the host busy by itself, so a train that claims a device needs no extra step. A marker file (set/clear) covers trains without a claim.
11
+ A marker is bound to its owner pid plus create time and has a ttl, so a dead or reused owner never leaves a stale flag. Nothing is
12
+ stopped or killed. The owner chat and its processes never wait on its own signal. Override: HOST_BUSY_OVERRIDE=1 or --override.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import contextlib
18
+ import json
19
+ import os
20
+ import re
21
+ import sqlite3
22
+ import sys
23
+ import time
24
+ from datetime import datetime, timezone
25
+ from pathlib import Path
26
+ from typing import Any, Callable
27
+
28
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
29
+ import chat_ledger as ledger # noqa: E402
30
+
31
+ BUSY_EXIT = 3
32
+ SPINE_KINDS = ("device-serial", "maestro-driver-port")
33
+ DEFAULT_MAX_AGE_S = 6 * 3600
34
+ DEFAULT_WAIT_S = 1800.0
35
+ DEFAULT_POLL_S = 5.0
36
+ OVERRIDE_ENV = "HOST_BUSY_OVERRIDE"
37
+ OWNER_ENV = "HOST_BUSY_OWNER"
38
+ WAIT_ENV = "HOST_BUSY_WAIT_S"
39
+ MAX_AGE_ENV = "HOST_BUSY_MAX_AGE_S"
40
+ _UNSAFE = re.compile(r"[^A-Za-z0-9._-]")
41
+
42
+
43
+ def state_dir() -> Path:
44
+ return Path(os.environ.get("HOST_BUSY_DIR") or Path.home() / ".claude" / "state" / "host_busy")
45
+
46
+
47
+ def spine_db_path() -> str:
48
+ return os.environ.get("MAESTRO_SPINE_DB") or os.path.join(os.path.expanduser("~"), ".claude", "logs", "maestro_launch_spine.db")
49
+
50
+
51
+ def _float_env(name: str, default: float) -> float:
52
+ try:
53
+ return float(os.environ[name])
54
+ except (KeyError, ValueError):
55
+ return default
56
+
57
+
58
+ def max_age_s() -> float:
59
+ return _float_env(MAX_AGE_ENV, DEFAULT_MAX_AGE_S)
60
+
61
+
62
+ def override_active(env: Any = os.environ) -> bool:
63
+ return str(env.get(OVERRIDE_ENV, "")).strip().lower() in ("1", "true", "yes", "on")
64
+
65
+
66
+ def _alive(procs: Any, pid: Any, create_time: Any = None) -> bool:
67
+ if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0:
68
+ return False
69
+ info = procs.get(pid)
70
+ if not info:
71
+ return False
72
+ return create_time is None or ledger.same_ctime(info["create_time"], create_time)
73
+
74
+
75
+ def _marker_path(owner: str) -> Path:
76
+ return state_dir() / f"{_UNSAFE.sub('_', owner) or 'unknown'}.json"
77
+
78
+
79
+ def _read_marker(path: Path) -> dict | None:
80
+ try:
81
+ doc = json.loads(path.read_text(encoding="utf-8"))
82
+ except (OSError, ValueError):
83
+ return None
84
+ return doc if isinstance(doc, dict) else None
85
+
86
+
87
+ def marker_holders(procs: Any, now: float) -> list[dict]:
88
+ try:
89
+ files = sorted(state_dir().glob("*.json"))
90
+ except OSError:
91
+ return []
92
+ out = []
93
+ for path in files:
94
+ doc = _read_marker(path)
95
+ if not doc or not isinstance(doc.get("owner"), str):
96
+ continue
97
+ expires = doc.get("expires_at")
98
+ if not isinstance(expires, (int, float)) or now >= expires:
99
+ continue
100
+ if not _alive(procs, doc.get("pid"), doc.get("create_time")):
101
+ continue
102
+ out.append({"source": "marker", "owner": doc["owner"], "pid": doc["pid"], "reason": doc.get("reason") or "device train",
103
+ "since": doc.get("since"), "ids": {doc["owner"]}})
104
+ return out
105
+
106
+
107
+ def _iso_epoch(text: Any) -> float | None:
108
+ try:
109
+ parsed = datetime.fromisoformat(str(text))
110
+ except ValueError:
111
+ return None
112
+ return (parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)).timestamp()
113
+
114
+
115
+ def spine_holders(procs: Any, now: float) -> list[dict]:
116
+ path = spine_db_path()
117
+ if not os.path.isfile(path):
118
+ return []
119
+ marks = ",".join("?" for _ in SPINE_KINDS)
120
+ try:
121
+ conn = sqlite3.connect(Path(path).resolve().as_uri() + "?mode=ro", uri=True, timeout=2)
122
+ try:
123
+ rows = conn.execute(f"SELECT resource_kind, resource_value, agent_id, task_id, pid, claimed_at FROM active_locks "
124
+ f"WHERE resource_kind IN ({marks})", SPINE_KINDS).fetchall()
125
+ finally:
126
+ conn.close()
127
+ except sqlite3.Error:
128
+ return []
129
+ out = []
130
+ for kind, value, agent, task, pid, claimed_at in rows:
131
+ claimed = _iso_epoch(claimed_at)
132
+ if claimed is not None and now - claimed > max_age_s():
133
+ continue
134
+ if not _alive(procs, pid):
135
+ continue
136
+ out.append({"source": "spine", "owner": agent, "pid": pid, "reason": f"spine claim {kind}={value}" + (f" task {task}" if task else ""),
137
+ "since": claimed_at, "ids": {x for x in (agent, task) if x}})
138
+ return out
139
+
140
+
141
+ def holders(procs: Any = None, now: float | None = None) -> list[dict]:
142
+ """Every live holder: marker files first, then spine device claims."""
143
+ procs = procs if procs is not None else ledger.snapshot()
144
+ now = time.time() if now is None else now
145
+ return marker_holders(procs, now) + spine_holders(procs, now)
146
+
147
+
148
+ def caller_identity(procs: Any = None, extra_ids: list[str] | None = None) -> dict:
149
+ """JSON-able identity of the calling chat: ids (owner env, session) and the pids of this process, its ancestors and its Claude process."""
150
+ procs = ledger.as_table(procs if procs is not None else ledger.snapshot())
151
+ ids = {x for x in (os.environ.get(OWNER_ENV), os.environ.get("CLAUDE_SESSION_ID"), *(extra_ids or [])) if x}
152
+ pids: set[int] = set()
153
+ cur, seen = procs.get(os.getpid()), set()
154
+ while cur and cur["pid"] not in seen:
155
+ seen.add(cur["pid"])
156
+ pids.add(cur["pid"])
157
+ cur = procs.get(cur["ppid"])
158
+ claude = ledger.claude_ancestor(os.getpid(), procs)
159
+ if claude:
160
+ pids.add(claude["pid"])
161
+ with contextlib.suppress(Exception):
162
+ ids.add(ledger._session_for_claude(claude))
163
+ return {"ids": sorted(ids), "pids": sorted(pids), "claude": {"pid": claude["pid"], "create_time": claude["create_time"]} if claude else None}
164
+
165
+
166
+ def is_own(holder: dict, identity: dict, procs: Any) -> bool:
167
+ if holder["ids"] & set(identity.get("ids") or ()):
168
+ return True
169
+ if holder["pid"] in set(identity.get("pids") or ()):
170
+ return True
171
+ claude = identity.get("claude")
172
+ if not claude:
173
+ return False
174
+ owner_claude = ledger.claude_ancestor(holder["pid"], procs)
175
+ return bool(owner_claude) and owner_claude["pid"] == claude["pid"] and ledger.same_ctime(owner_claude["create_time"], claude["create_time"])
176
+
177
+
178
+ def blockers(identity: dict | None = None, procs: Any = None, now: float | None = None) -> list[dict]:
179
+ """Live holders that belong to another chat than the caller."""
180
+ procs = ledger.as_table(procs if procs is not None else ledger.snapshot())
181
+ identity = identity if identity is not None else caller_identity(procs)
182
+ return [h for h in holders(procs, now) if not is_own(h, identity, procs)]
183
+
184
+
185
+ def _since_text(since: Any) -> str:
186
+ if isinstance(since, (int, float)):
187
+ return datetime.fromtimestamp(since).strftime("%Y-%m-%d %H:%M:%S")
188
+ return str(since or "unknown")
189
+
190
+
191
+ def describe(holder: dict) -> str:
192
+ return f"{holder['owner']} (pid {holder['pid']}, since {_since_text(holder.get('since'))}): {holder['reason']}"
193
+
194
+
195
+ def describe_all(held: list[dict]) -> str:
196
+ return "; ".join(describe(h) for h in held)
197
+
198
+
199
+ def wait_for_idle(label: str, *, timeout_s: float | None = None, poll_s: float = DEFAULT_POLL_S, override: bool | None = None,
200
+ identity: dict | None = None, procs: Any = None, say: Callable[[str], None] | None = None,
201
+ tick: Callable[[list[dict], float], bool] | None = None, clock: Callable[[], float] = time.monotonic,
202
+ sleep: Callable[[float], None] = time.sleep) -> dict:
203
+ """Block until no other chat holds the host. Returns {"status": idle|overridden|timeout|cancelled, "waited_s", "blockers"}.
204
+
205
+ `tick(blockers, waited_s)` runs on every poll while waiting; a True return cancels the wait. The wait is bounded by timeout_s
206
+ (env HOST_BUSY_WAIT_S, default 30 min). Nothing is ever stopped; a timeout only reports who holds the host.
207
+ """
208
+ say = say or (lambda text: print(text, file=sys.stderr, flush=True))
209
+ timeout_s = _float_env(WAIT_ENV, DEFAULT_WAIT_S) if timeout_s is None else timeout_s
210
+ override = override_active() if override is None else override
211
+ identity = identity if identity is not None else caller_identity(procs)
212
+ started, announced = clock(), False
213
+ while True:
214
+ held = blockers(identity, procs)
215
+ waited = clock() - started
216
+ if not held:
217
+ if announced:
218
+ say(f"host_busy: host is idle after {waited:.0f}s, {label} continues")
219
+ return {"status": "idle", "waited_s": waited, "blockers": []}
220
+ if override:
221
+ say(f"host_busy: OVERRIDE active ({OVERRIDE_ENV}=1 or --override); {label} runs although the host is busy: {describe_all(held)}")
222
+ return {"status": "overridden", "waited_s": waited, "blockers": held}
223
+ if waited >= timeout_s:
224
+ say(f"host_busy: {label} gave up after {waited:.0f}s; the host is still busy: {describe_all(held)}. Nothing was stopped. "
225
+ f"Retry when the device train ends, raise {WAIT_ENV}, or override with {OVERRIDE_ENV}=1.")
226
+ return {"status": "timeout", "waited_s": waited, "blockers": held}
227
+ if not announced:
228
+ say(f"host_busy: {label} waits for the host (device train of another chat, max {timeout_s:.0f}s): {describe_all(held)}")
229
+ announced = True
230
+ if tick and tick(held, waited):
231
+ return {"status": "cancelled", "waited_s": waited, "blockers": held}
232
+ sleep(min(poll_s, max(0.0, timeout_s - waited)) or poll_s)
233
+
234
+
235
+ def set_busy(reason: str, *, owner: str | None = None, pid: int | None = None, ttl_s: float | None = None, procs: Any = None,
236
+ now: float | None = None) -> dict:
237
+ """Publish a marker. Without --pid the owner is the calling chat's Claude process, so the marker dies with the chat."""
238
+ procs = ledger.as_table(procs if procs is not None else ledger.snapshot())
239
+ now = time.time() if now is None else now
240
+ if pid is None:
241
+ claude = ledger.claude_ancestor(os.getpid(), procs)
242
+ if not claude:
243
+ raise SystemExit("host_busy set: no Claude process above this one; pass --pid of a long-lived owner")
244
+ pid = claude["pid"]
245
+ owner = owner or ledger._session_for_claude(claude)
246
+ info = procs.get(pid)
247
+ if not info:
248
+ raise SystemExit(f"host_busy set: pid {pid} is not running")
249
+ owner = owner or os.environ.get(OWNER_ENV) or os.environ.get("CLAUDE_SESSION_ID") or f"pid-{pid}"
250
+ ttl = max_age_s() if ttl_s is None else ttl_s
251
+ doc = {"owner": owner, "pid": pid, "create_time": round(info["create_time"], 3), "reason": reason, "since": now,
252
+ "expires_at": now + ttl}
253
+ path = _marker_path(owner)
254
+ path.parent.mkdir(parents=True, exist_ok=True)
255
+ tmp = path.with_name(f"{path.name}.{os.getpid()}.tmp")
256
+ tmp.write_text(json.dumps(doc), encoding="utf-8")
257
+ os.replace(tmp, path)
258
+ return doc
259
+
260
+
261
+ def clear_busy(owner: str | None = None, procs: Any = None) -> bool:
262
+ """Remove the caller's marker (or --owner's). Only the marker file; never a process."""
263
+ if owner is None:
264
+ identity = caller_identity(procs)
265
+ candidates = list(identity["ids"])
266
+ else:
267
+ candidates = [owner]
268
+ removed = False
269
+ for cand in candidates:
270
+ with contextlib.suppress(FileNotFoundError):
271
+ _marker_path(cand).unlink()
272
+ removed = True
273
+ return removed
274
+
275
+
276
+ def _status_doc(held: list[dict]) -> dict:
277
+ return {"busy": bool(held), "holders": [{**h, "ids": sorted(h["ids"])} for h in held]}
278
+
279
+
280
+ def main(argv: list[str] | None = None) -> int:
281
+ ap = argparse.ArgumentParser(prog="host_busy", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
282
+ sub = ap.add_subparsers(dest="cmd", required=True)
283
+ st = sub.add_parser("status")
284
+ st.add_argument("--json", action="store_true")
285
+ st.add_argument("--all", action="store_true", help="include the caller's own holds")
286
+ setp = sub.add_parser("set")
287
+ setp.add_argument("--reason", required=True)
288
+ setp.add_argument("--owner")
289
+ setp.add_argument("--pid", type=int)
290
+ setp.add_argument("--ttl-s", dest="ttl_s", type=float)
291
+ clr = sub.add_parser("clear")
292
+ clr.add_argument("--owner")
293
+ wt = sub.add_parser("wait")
294
+ wt.add_argument("--label", default="heavy work")
295
+ wt.add_argument("--timeout-s", dest="timeout_s", type=float)
296
+ wt.add_argument("--poll-s", dest="poll_s", type=float, default=DEFAULT_POLL_S)
297
+ wt.add_argument("--override", action="store_true")
298
+ args = ap.parse_args(argv)
299
+ if args.cmd == "set":
300
+ print(json.dumps(set_busy(args.reason, owner=args.owner, pid=args.pid, ttl_s=args.ttl_s)))
301
+ return 0
302
+ if args.cmd == "clear":
303
+ print(json.dumps({"cleared": clear_busy(args.owner)}))
304
+ return 0
305
+ if args.cmd == "wait":
306
+ result = wait_for_idle(args.label, timeout_s=args.timeout_s, poll_s=args.poll_s, override=True if args.override else None)
307
+ return BUSY_EXIT if result["status"] == "timeout" else 0
308
+ procs = ledger.snapshot()
309
+ held = holders(procs) if args.all else blockers(procs=procs)
310
+ doc = _status_doc(held)
311
+ if args.json:
312
+ print(json.dumps(doc))
313
+ else:
314
+ print(f"host busy: {describe_all(held)}" if held else "host idle")
315
+ return BUSY_EXIT if held else 0
316
+
317
+
318
+ if __name__ == "__main__":
319
+ raise SystemExit(main())
@@ -10,6 +10,7 @@ import json
10
10
  import os
11
11
  import re
12
12
  import shutil
13
+ import stat
13
14
  import sys
14
15
  import time
15
16
  from typing import Any, Callable, Iterable
@@ -66,6 +67,19 @@ def _newest_mtime(path: str) -> float:
66
67
  return newest
67
68
 
68
69
 
70
+ def _clear_readonly(func: Callable, path: str, _exc: Any) -> None:
71
+ os.chmod(path, stat.S_IWRITE)
72
+ func(path)
73
+
74
+
75
+ def _remove(path: str) -> None:
76
+ if not os.path.isdir(path):
77
+ os.remove(path)
78
+ return
79
+ handler = {"onexc": _clear_readonly} if sys.version_info >= (3, 12) else {"onerror": _clear_readonly}
80
+ shutil.rmtree(path, **handler)
81
+
82
+
69
83
  def live_session_ids() -> set[str]:
70
84
  """Ids of sessions whose hosting Claude process is alive; empty when the ledger cannot be read."""
71
85
  here = os.path.dirname(os.path.abspath(__file__))
@@ -149,7 +163,7 @@ def prune_aged(policy: dict, claude_dir: str, now: float, live: set[str], dry_ru
149
163
  entries.sort(key=lambda item: item[1], reverse=True)
150
164
  cutoff = now - policy["max_age_days"] * DAY_S
151
165
  cap = policy.get("keep_last")
152
- deleted, freed, skipped_live = 0, 0, 0
166
+ deleted, freed, skipped_live, failed = 0, 0, 0, 0
153
167
  for rank, (path, newest) in enumerate(entries):
154
168
  if newest >= cutoff and (cap is None or rank < cap):
155
169
  continue
@@ -159,12 +173,16 @@ def prune_aged(policy: dict, claude_dir: str, now: float, live: set[str], dry_ru
159
173
  size = _size(path)
160
174
  if not dry_run:
161
175
  try:
162
- shutil.rmtree(path) if os.path.isdir(path) else os.remove(path)
176
+ _remove(path)
163
177
  except OSError:
178
+ pass
179
+ if os.path.exists(path):
180
+ freed += size - _size(path)
181
+ failed += 1
164
182
  continue
165
183
  deleted += 1
166
184
  freed += size
167
- return {"deleted": deleted, "freed_bytes": freed, "skipped_live": skipped_live}
185
+ return {"deleted": deleted, "freed_bytes": freed, "skipped_live": skipped_live, "failed": failed}
168
186
 
169
187
 
170
188
  def run(claude_dir: str | None = None, now: float | None = None, dry_run: bool = False, lock: Callable[[str], Any] | None = None) -> dict:
@@ -8,7 +8,7 @@
8
8
  Sample record: {kind:"sample", ts, available_mb, commit_gb, top10:[{name,pid,private_mb}], running_gate_ids}
9
9
  plus, on Windows with the low-ram-advisor skill installed (each key independent; a failing probe is named in watch_errors):
10
10
  commit_limit_gb; pool:{paged_gb,nonpaged_gb,top:[[tag,bytes,live]]}; vms:[{name,pid,private_mb,ws_mb}] for vmmem*, vmwp,
11
- vmware-vmx and Memory Compression; mem:{standby_mb,modified_mb,free_mb,paged_mb,paged_resident_mb,nonpaged_mb}.
11
+ vmware-vmx and Memory Compression; mem:{standby_mb,modified_mb,free_mb,paged_mb,paged_resident_mb,nonpaged_mb}; token_handles (open token handles in all processes).
12
12
  The loop also runs the leak watch (alerts file for chat) and the non-disruptive WSL cache auto-free from that skill.
13
13
  Other writers (reaper_kill_hook.py) share the file through append_record(). Never raises out of the loop.
14
14
  """
@@ -448,6 +448,12 @@ def pool_section(memwatch, pooltags) -> dict:
448
448
  return memwatch.pool_fields(tags, _watched)
449
449
 
450
450
 
451
+ def token_handle_total() -> int:
452
+ import handlecount
453
+
454
+ return handlecount.token_holders()["token_total"]
455
+
456
+
451
457
  def watch_fields() -> dict:
452
458
  """Leak-watch and attribution fields for a sample; {} off Windows or without the skill. A failing probe drops only its own key
453
459
  and is named in `watch_errors`."""
@@ -462,6 +468,7 @@ def watch_fields() -> dict:
462
468
  ("pool", lambda: pool_section(memwatch, pooltags)),
463
469
  ("vms", lambda: memprobe.vm_snapshot(memprobe.nt_processes())),
464
470
  ("mem", memprobe.memory_lists_mb),
471
+ ("token_handles", token_handle_total),
465
472
  ):
466
473
  try:
467
474
  value = build()
@@ -3,6 +3,7 @@
3
3
 
4
4
  memory_reclaim.py --trigger {gate_launch,subagent_dispatch,manual} [--session-id ID] [--apply | --dry-run]
5
5
  [--spine-release]
6
+ memory_reclaim.py ... [--budget-mb N] override the budget for this run
6
7
  memory_reclaim.py --preflight [--session-id ID] report only: RAM vs budget, decisions, top hogs
7
8
 
8
9
  Dry-run is the default; only --apply stops anything. Candidates are alive ledger rows, descendants of
@@ -471,6 +472,7 @@ def build_parser() -> argparse.ArgumentParser:
471
472
  ap.add_argument("--spine-release", action="store_true",
472
473
  help="release idle spine-claimed Metro of recorded owners through spine.py stop-metro (default off; always on for orphan Metro)")
473
474
  ap.add_argument("--preflight", action="store_true")
475
+ ap.add_argument("--budget-mb", type=float, help="treat this as the budget instead of memory_budget.json (the ram skill passes the machine total)")
474
476
  return ap
475
477
 
476
478
 
@@ -484,7 +486,7 @@ def main(argv: list[str] | None = None) -> int:
484
486
  print(render_preflight(preflight(session_id=args.session_id)))
485
487
  else:
486
488
  print(json.dumps(reclaim(args.trigger, session_id=args.session_id, dry_run=not args.apply,
487
- spine_release=args.spine_release)))
489
+ spine_release=args.spine_release, budget=args.budget_mb)))
488
490
  except SystemExit:
489
491
  raise
490
492
  except Exception as exc:
@@ -10,7 +10,8 @@ Global Claude Code skills. Installed to `~/.claude/skills/` — each subdirector
10
10
  | `graphic-novel-pipeline` | `/graphic-novel-pipeline` · "start a new graphic novel" · "plan the panels" · "generate the images" · "graphic novel status" | Skill |
11
11
  | `heavy-gate-runner` | no slash command · "run the full test gate" · "start a heavy gate" · "gate status" · "cancel the gate" | Skill |
12
12
  | `launch-litellm` | "start litellm" · "litellm is down" · "restart litellm" · "is litellm up" · any council/web-search/visual-check connection failure | Skill |
13
- | `low-ram-advisor` | no slash command · started in code by any free-RAM check · "free up RAM" · "what can I close" | Skill |
13
+ | `ram` | `/ram` · "optimize RAM" · "clear RAM" · "free up memory" | Skill |
14
+ | `low-ram-advisor` | no slash command · started in code by any free-RAM check · "free up RAM" · "what can I close" · "what's my RAM" · "should I restart" | Skill |
14
15
  | `android-emulator` | no slash command · "start an emulator" · "emulator on the GPU" | Skill |
15
16
  | `make-space` | "make space" · "make-space" · "disk critically low" · "free up space" · "we are out of space" | Skill |
16
17
  | `mattpocock-codebase-design` | `/codebase-design` · "design this module's interface" · "find a deepening opportunity" · "where should this seam go" | Skill |
@@ -40,7 +41,10 @@ Project-agnostic image generation behind one provider interface. Default provide
40
41
  Local headless emulator launcher for the Windows host. `emulator_launch.py start --avd NAME` tries `-accel on -gpu host`, then the AVD's own mode; a mode that exits or never reaches `sys.boot_completed` is stopped and the next one runs on the same port. Modes the installed emulator build rejects in a user-supplied chain (36.4.9 drops `angle_indirect`) are skipped, and a `host` request that silently lands on a software renderer is reported as `downgraded`. The result carries the emulator log line and the guest GLES renderer as proof. CI and non-Windows hosts keep the AVD default. Override with env `ANDROID_EMULATOR_GPU_CHAIN`. Stdlib only; tests in `skills/android-emulator/tests`.
41
42
 
42
43
  ### low-ram-advisor
43
- Non-blocking, suggest-only RAM triage, the memory analogue of `make-space`. Any free-RAM check runs `advisor.py start --source S --free-gb F --required-gb R`, which spawns a detached hidden analysis (`pythonw`, no window) and prints exactly one line, the report path, in under a second; the caller keeps working. Each calling session gets its own report (`~/.claude/logs/low-ram-advisor/latest-<key>.md` + `.json`, plus `state-<key>.json`; one shared raw `snapshot.json` per cooldown window) that groups Claude sessions, Metro/node, Gradle/Java, Maestro, emulator, browsers, WSL/Docker, local proxies and IDEs with owner, safe-to-stop (`yes` only for the caller's own dev processes; shared daemons and other live sessions never), RAM freed, rank and a graceful pwsh stop command. The cooldown (default 300 s) is per session, and an atomic lock prevents scan storms. Reports and state files older than 7 days (env `LOW_RAM_ADVISOR_RETENTION_DAYS`) are pruned best-effort by the detached child. The code has no kill/suspend path; tests assert it. Optional owner hints: `~/.claude/low-ram-advisor-hints.json`.
44
+ Non-blocking, suggest-only RAM triage, the memory analogue of `make-space`. Any free-RAM check runs `advisor.py start --source S --free-gb F --required-gb R`, which spawns a detached hidden analysis (`pythonw`, no window) and prints exactly one line, the report path, in under a second; the caller keeps working. Each calling session gets its own report (`~/.claude/logs/low-ram-advisor/latest-<key>.md` + `.json`, plus `state-<key>.json`; one shared raw `snapshot.json` per cooldown window) that groups Claude sessions, Metro/node, Gradle/Java, Maestro, emulator, browsers, WSL/Docker, local proxies and IDEs with owner, safe-to-stop (`yes` only for the caller's own dev processes; shared daemons and other live sessions never), RAM freed, rank and a graceful pwsh stop command. The cooldown (default 300 s) is per session, and an atomic lock prevents scan storms. Reports and state files older than 7 days (env `LOW_RAM_ADVISOR_RETENTION_DAYS`) are pruned best-effort by the detached child. The code has no kill/suspend path; tests assert it. Optional owner hints: `~/.claude/low-ram-advisor-hints.json`. `ramstatus.py` prints a 10-line live RAM summary and an OK / RESTART SOON / RESTART NOW verdict (token leak, kernel pools, commit; thresholds in `ram_thresholds.py`); chat questions like "what's my RAM" or "should I restart" run it, and the deep report and leak alerts carry the same verdict.
45
+
46
+ ### ram
47
+ Thin `/ram` entry point over `low-ram-advisor/ram_optimize.py`. One run frees what is safe (idle ledger-proven processes, CI janitor when no job runs, WSL page cache), prints MB freed per action, then RAM left, top groups, Windows kernel pools, the token leak size and the OK / RESTART SOON / RESTART NOW verdict, and lists user-app closes as suggestions only. Plain phrases like "optimize RAM" or "free up memory" start it through the chat hook.
44
48
 
45
49
  ### make-space
46
50
  One-call disk reclamation meant to run in a single background subagent so the calling chat only receives a compact JSON report. Thin layer over `disk-cleanup`: deletes only allowlisted regenerable data (package caches, gradle caches, recycle bin, Temp older than 1 day with `Temp\claude` excluded) behind a code-enforced path guard with a hard denylist and `.git` protection; judgment items and removable worktrees are reported, never deleted. `-DryRun` previews; `-RemoveWorktrees` removes only audit-clean worktrees after user approval.