@yasaswy.nagavolu/agents 0.30.1 → 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.
- package/bin/cli.js +2 -1
- package/content/hooks/tracker_proof_gate.py +32 -13
- package/content/manifest.json +25 -0
- package/content/proxy/host_busy.py +319 -0
- package/content/proxy/log_retention.py +21 -3
- package/content/skills/heavy-gate-runner/SKILL.md +12 -1
- package/content/skills/heavy-gate-runner/heavy_gate_runner.py +39 -0
- package/content/skills/heavy-gate-runner/tests/test_heavy_gate_runner.py +58 -0
- package/content/skills/ship-the-code/SKILL.md +5 -3
- package/content/skills/ship-the-code/ship.py +108 -10
- package/content/skills/ship-the-code/tests/test_ship_order.py +45 -6
- package/content/skills/ship-the-code/tests/test_ship_race.py +240 -0
- package/lib/components.js +4 -4
- package/lib/memSafety.js +2 -1
- package/lib/pyenv.js +4 -3
- package/lib/releaseLock.js +3 -2
- package/lib/runner/janitorTask.js +2 -1
- package/lib/selfProfile.js +2 -1
- package/lib/staleCheckout.js +3 -2
- package/lib/testRun.js +12 -0
- 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
|
-
...(
|
|
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
|
-
|
|
85
|
-
|
|
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
|
-
"""
|
|
95
|
-
|
|
96
|
-
|
|
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
|
|
128
|
-
same-sentence matching, since a natural claim often reads
|
|
129
|
-
https://gitlab.com/.../issues/42 for details." across two
|
|
130
|
-
|
|
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)
|
|
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 =
|
|
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:
|
package/content/manifest.json
CHANGED
|
@@ -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": [],
|
|
@@ -309,6 +324,11 @@
|
|
|
309
324
|
"path": "skills/low-ram-advisor",
|
|
310
325
|
"kind": "skill",
|
|
311
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."
|
|
312
332
|
}
|
|
313
333
|
],
|
|
314
334
|
"deps": [],
|
|
@@ -801,6 +821,11 @@
|
|
|
801
821
|
"kind": "hook",
|
|
802
822
|
"targetPath": "hooks/pyrun.js",
|
|
803
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."
|
|
804
829
|
}
|
|
805
830
|
],
|
|
806
831
|
"deps": [
|
|
@@ -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
|
-
|
|
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:
|
|
@@ -14,7 +14,7 @@ Install and rules in one place: `docs/memory-safety.md` in the my-agents repo (t
|
|
|
14
14
|
|
|
15
15
|
| Command | Result |
|
|
16
16
|
|---|---|
|
|
17
|
-
| `start [--label L] [--cwd DIR] [--agent-id ID] [--session-id ID] [--stall-s N] [--dry-run] -- <gate command...>` | Prints `run_id`, `run_dir`, `workers` in under 1 s |
|
|
17
|
+
| `start [--label L] [--cwd DIR] [--agent-id ID] [--session-id ID] [--stall-s N] [--host-wait-s N] [--override-host-busy] [--dry-run] -- <gate command...>` | Prints `run_id`, `run_dir`, `workers` in under 1 s |
|
|
18
18
|
| `--status RUN_ID` | State, stage, heartbeat age, verdict `healthy` / `STUCK` / `finished` (exit 0 healthy or PASS, 1 otherwise, 2 unknown run) |
|
|
19
19
|
| `--cancel RUN_ID` | Cancel flag, graceful stop of the run's own recorded tree only, lands `CANCELLED` |
|
|
20
20
|
| `list [--running]` | One line per run |
|
|
@@ -33,6 +33,17 @@ Several args after `--` run as an argv list; one arg runs through the shell. Run
|
|
|
33
33
|
States: `starting`, `RUNNING`, `PASS`, `FAIL`, `CANCELLED`, `STALL` (no log or gate-heartbeat change for `--stall-s`, default 1800). A finished run shows stage `done` / `failed` / `cancelled`, which the mem sampler treats as not running.
|
|
34
34
|
Stage comes from `.claude/.tests_gate_status_<repo>.json` in the cwd when the command is `tests_gate`, else from the last log line.
|
|
35
35
|
|
|
36
|
+
## Host busy (device trains)
|
|
37
|
+
|
|
38
|
+
| Rule | Detail |
|
|
39
|
+
|---|---|
|
|
40
|
+
| Wait | While another chat's device train holds the host (`proxy/host_busy.py`: a live spine `device-serial` / `maestro-driver-port` claim or a `host_busy.py set` marker), the supervisor waits before it launches the gate. `start` still returns at once. Status shows `state: starting`, `stage: waiting_host_idle`, `host_busy.holders` |
|
|
41
|
+
| Bound | `--host-wait-s` (env `HOST_BUSY_WAIT_S`, default 1800). On timeout the run lands `FAIL`, `exit_code` 75, with the holder named in `run.log`; nothing is stopped |
|
|
42
|
+
| Own chat | A gate started by the train owner's own chat never waits |
|
|
43
|
+
| Override | `--override-host-busy` or env `HOST_BUSY_OVERRIDE=1` starts at once |
|
|
44
|
+
| Cancel | `--cancel` works during the wait and lands `CANCELLED` |
|
|
45
|
+
| Not RAM | The wait is about device trains only; free RAM never delays a gate |
|
|
46
|
+
|
|
36
47
|
## Memory policy (no waiting)
|
|
37
48
|
|
|
38
49
|
| Rule | Detail |
|
|
@@ -17,6 +17,7 @@ from typing import Any
|
|
|
17
17
|
|
|
18
18
|
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "proxy"))
|
|
19
19
|
import chat_ledger as ledger # noqa: E402
|
|
20
|
+
import host_busy # noqa: E402
|
|
20
21
|
import mem_sampler # noqa: E402
|
|
21
22
|
import proc_policy # noqa: E402
|
|
22
23
|
from headless_process import headless_popen, headless_popen_detached, headless_run # noqa: E402
|
|
@@ -246,6 +247,8 @@ def cmd_start(opts: argparse.Namespace, command: list[str]) -> int:
|
|
|
246
247
|
print(f"available_mb: {None if avail is None else round(avail)} budget_mb: {round(cfg['budget_mb'])} below_budget: {low}")
|
|
247
248
|
print(f"reclaimer_on_low_memory: {RECLAIM_SCRIPT.is_file()}")
|
|
248
249
|
print(f"existing_running_run: {existing['run_id'] if existing else 'none'}")
|
|
250
|
+
held = host_busy.blockers(host_busy.caller_identity())
|
|
251
|
+
print(f"host_busy: {host_busy.describe_all(held) if held else 'idle'}")
|
|
249
252
|
return 0
|
|
250
253
|
session = resolve_session(opts.session_id)
|
|
251
254
|
with start_lock():
|
|
@@ -266,6 +269,8 @@ def cmd_start(opts: argparse.Namespace, command: list[str]) -> int:
|
|
|
266
269
|
f"cwd={cwd} workers={workers} command={command}\n")
|
|
267
270
|
(run_dir / "run.log").write_text(header, encoding="utf-8")
|
|
268
271
|
spec = {"run_id": run_id, "command": command, "cwd": cwd, "checkout": checkout, "gate_key": key, "label": opts.label,
|
|
272
|
+
"host_busy": {"identity": host_busy.caller_identity(extra_ids=[session]), "override": opts.override_host_busy or host_busy.override_active(),
|
|
273
|
+
"timeout_s": opts.host_wait_s},
|
|
269
274
|
"session_id": session, "agent_id": opts.agent_id, "workers": workers, "stall_s": opts.stall_s,
|
|
270
275
|
"beat_s": float(os.environ.get("HEAVY_GATE_BEAT_S") or DEFAULT_BEAT_S), "low_memory": low_info,
|
|
271
276
|
"critical_mb": cfg["critical_mb"], "run_dir": str(run_dir), "started_at": started}
|
|
@@ -466,6 +471,32 @@ def note(log: Any, text: str) -> None:
|
|
|
466
471
|
log.flush()
|
|
467
472
|
|
|
468
473
|
|
|
474
|
+
HOST_BUSY_EXIT = 75
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
def wait_for_host(spec: dict, st: dict, status_path: Path, cancel_flag: Path, log: Any, guarded: Any) -> dict | None:
|
|
478
|
+
"""Wait (bounded) while another chat's device train holds the host. None = go on; else {"code": exit code} after a terminal status."""
|
|
479
|
+
cfg = spec.get("host_busy") or {}
|
|
480
|
+
|
|
481
|
+
def tick(held: list[dict], waited: float) -> bool:
|
|
482
|
+
write_json(status_path, {**st, "state": "starting", "stage": "waiting_host_idle", "heartbeat_at": time.time(),
|
|
483
|
+
"host_busy": {"waited_s": round(waited), "holders": host_busy.describe_all(held)}})
|
|
484
|
+
return cancel_flag.exists()
|
|
485
|
+
|
|
486
|
+
result = guarded("host_busy", lambda: host_busy.wait_for_idle(
|
|
487
|
+
f"gate {spec['run_id']}", timeout_s=cfg.get("timeout_s"), poll_s=min(float(spec["beat_s"]), host_busy.DEFAULT_POLL_S),
|
|
488
|
+
override=bool(cfg.get("override")), identity=cfg.get("identity") or {}, say=lambda text: note(log, text), tick=tick))
|
|
489
|
+
status = (result or {}).get("status", "idle")
|
|
490
|
+
if status == "cancelled":
|
|
491
|
+
write_json(status_path, {**st, "state": "CANCELLED", "stage": "cancelled", "finished_at": time.time()})
|
|
492
|
+
return {"code": 0}
|
|
493
|
+
if status == "timeout":
|
|
494
|
+
write_json(status_path, {**st, "state": "FAIL", "stage": "failed", "exit_code": HOST_BUSY_EXIT, "finished_at": time.time(),
|
|
495
|
+
"host_busy": {"timed_out": True, "holders": host_busy.describe_all(result["blockers"])}})
|
|
496
|
+
return {"code": 1}
|
|
497
|
+
return None
|
|
498
|
+
|
|
499
|
+
|
|
469
500
|
def _supervise(run_dir: Path, spec: dict, log: Any, holder: dict) -> int:
|
|
470
501
|
run_id, session = spec["run_id"], spec["session_id"]
|
|
471
502
|
me = os.getpid()
|
|
@@ -498,6 +529,10 @@ def _supervise(run_dir: Path, spec: dict, log: Any, holder: dict) -> int:
|
|
|
498
529
|
write_json(status_path, {**st, "state": "CANCELLED", "stage": "cancelled", "finished_at": time.time()})
|
|
499
530
|
return 0
|
|
500
531
|
|
|
532
|
+
outcome = wait_for_host(spec, st, status_path, cancel_flag, log, guarded)
|
|
533
|
+
if outcome:
|
|
534
|
+
return outcome["code"]
|
|
535
|
+
|
|
501
536
|
tmp_dir = run_dir / "tmp"
|
|
502
537
|
tmp_dir.mkdir(exist_ok=True)
|
|
503
538
|
env = dict(os.environ)
|
|
@@ -724,6 +759,10 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
724
759
|
start.add_argument("--session-id", dest="session_id")
|
|
725
760
|
start.add_argument("--stall-s", dest="stall_s", type=float, default=DEFAULT_STALL_S)
|
|
726
761
|
start.add_argument("--dry-run", dest="dry_run", action="store_true")
|
|
762
|
+
start.add_argument("--override-host-busy", dest="override_host_busy", action="store_true",
|
|
763
|
+
help="start now although another chat's device train holds the host")
|
|
764
|
+
start.add_argument("--host-wait-s", dest="host_wait_s", type=float, default=None,
|
|
765
|
+
help="longest wait for an idle host before the run fails (env HOST_BUSY_WAIT_S, default 1800)")
|
|
727
766
|
sub.add_parser("status").add_argument("run_id")
|
|
728
767
|
sub.add_parser("cancel").add_argument("run_id")
|
|
729
768
|
sub.add_parser("list").add_argument("--running", action="store_true")
|