@passioncode-ai/fabric-agent-adapter 0.35.0 → 0.35.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,33 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.35.1 - 2026-10-17
4
+
5
+ ### Added
6
+
7
+ - **`creating-fabric-agents` → `references/resilience-and-autonomy.md`**: the rules that kept about twenty production
8
+ agents working through limits, model errors and restarts, from their retrospectives of 2026-10-17 — limits as
9
+ pauses and resume-first workers, an acceptance parser per model call, cross-vendor fallbacks and checkers, spend as
10
+ a persisted ledger with idempotency keys, decisions recorded instead of asked, tests watched failing, run ownership,
11
+ owner-tagged resources and secrets kept out of every child's environment. The skill reads it before the first
12
+ stage that calls a model or spends money and reports its checklist.
13
+
14
+ ### Fixed
15
+
16
+ - **The Hermes native adapter dropped a helper's answer** (FAA-51): a helper that exits without reading its input broke
17
+ the pipe while the payload was written, and the broken pipe discarded the helper's output. It no longer does.
18
+ - **`test/validate.py` validated other checkouts as this tree** (FAA-50): its walks entered `.worktrees/` (git
19
+ worktrees of this repository, git-ignored), so the main checkout failed the pin check — 442 errors — whenever a
20
+ worktree of another branch sat beside it. Every walk now skips `.git` and `.worktrees`.
21
+ - **The tests left directories behind** (FAA-50): the Node tests made their temporary directories with `mkdtempSync`
22
+ and removed none, and five Python tests used `mkdtemp` without a cleanup, so every run left about 40 directories in
23
+ the system's temp folder. The Node tests take theirs from `test/temp-dir.mjs`, removed when the process exits; the
24
+ Python tests register `addCleanup`. A full run now leaves none.
25
+ - **The session hooks' spool grew without bound** (FAA-50): a session folder was removed only when its worker delivered
26
+ the session's end, so a failed delivery or a session that ended without SessionEnd left its folder forever. The next
27
+ spooling hook now removes folders untouched for 7 days, never its own.
28
+ - **`install-host-hooks --host codex --remove`** names the SessionStart hook groups after ours that it moves: Codex
29
+ keys a hook's trust by its position, and asks the person to approve those again in `/hooks` (FAA-49).
30
+
3
31
  ## 0.35.0 - 2026-10-16
4
32
 
5
33
  ### Fixed
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@passioncode-ai/fabric-agent-adapter",
3
- "version": "0.35.0",
3
+ "version": "0.35.1",
4
4
  "description": "Create Fabric-compatible agents, run them as always-alive local services with dashboards (fabric-service/0.1), and adapt existing projects to the Fabric Agent Contract. This package is the installer CLI.",
5
5
  "scripts": {
6
6
  "test": "python3 test/validate.py && python3 -m unittest discover -s test -q && node --test 'test/*.test.mjs'"
@@ -3,7 +3,7 @@
3
3
  "name": "fabric-agent-adapter",
4
4
  "displayName": "Fabric Agent Adapter",
5
5
  "description": "Create new Fabric-compatible agents, build them as always-alive local services with dashboards (fabric-service/0.1), and adapt existing projects to the Fabric Agent Contract through evidence-backed MCP, A2A, or local-runner provider bundles; and teach a coding agent to work in a project through Fabric (fabric-mcp, fabric_whoami, claim and release), with Claude Code session hooks.",
6
- "version": "0.35.0",
6
+ "version": "0.35.1",
7
7
  "author": {
8
8
  "name": "PassionCode.ai",
9
9
  "url": "https://passioncode.ai/"
@@ -5,7 +5,7 @@ license: AGPL-3.0-only OR LicenseRef-PassionCode-Commercial
5
5
  compatibility: Requires filesystem access and Python 3.9+. Exact schema checks additionally need git, Node.js, pnpm, and the pinned fabric-agent-contract checkout (a public repository). Works without those tools in an explicitly degraded structural-check mode.
6
6
  metadata:
7
7
  author: PassionCode.ai
8
- version: "0.35.0"
8
+ version: "0.35.1"
9
9
  contract-version: "0.1.0"
10
10
  contract-commit: "d8146cfb0a1c74fc6432284c4356bb0c864b37b5"
11
11
  ---
@@ -18,7 +18,7 @@ license: AGPL-3.0-only OR LicenseRef-PassionCode-Commercial
18
18
  compatibility: Python 3.9+ or Node.js 20+ for the kits; the probe needs Python 3.9+. launchd steps are macOS-only; Linux services install a systemd user unit and Windows ones a per-user Scheduled Task with the kits' writers. Dashboard handoff optionally uses Fabric Dashboards MCP link/host_status/open; without it, report unresolved host capability. The contract checkout is optional.
19
19
  metadata:
20
20
  author: PassionCode.ai
21
- version: "0.35.0"
21
+ version: "0.35.1"
22
22
  contract-version: "0.1.0"
23
23
  extension: "fabric-service/0.1"
24
24
  extension-commit: "d8146cfb0a1c74fc6432284c4356bb0c864b37b5"
@@ -5,7 +5,7 @@ license: AGPL-3.0-only OR LicenseRef-PassionCode-Commercial
5
5
  compatibility: Requires filesystem access and Python 3.9+. Exact schema checks additionally need git, Node.js, pnpm, and the pinned fabric-agent-contract checkout (a public repository). Works without those tools in an explicitly degraded structural-check mode. Ships in one plugin with adapting-projects-to-fabric, whose scripts it reuses.
6
6
  metadata:
7
7
  author: PassionCode.ai
8
- version: "0.35.0"
8
+ version: "0.35.1"
9
9
  contract-version: "0.1.0"
10
10
  contract-commit: "d8146cfb0a1c74fc6432284c4356bb0c864b37b5"
11
11
  ---
@@ -201,6 +201,15 @@ the pinned `schemas/operator-channel-status.schema.json`; the channel's runtime
201
201
  probe rule here yet, so report them `NOT_RUN`. An agent with neither stops nor notify
202
202
  events skips this step.
203
203
 
204
+ ## Resilience and autonomy
205
+
206
+ Before the first stage that calls a model or spends money, read
207
+ [resilience and autonomy](references/resilience-and-autonomy.md) and design its answers in:
208
+ a limit pauses and resumes, every model answer passes the call site's own acceptance, fallbacks
209
+ and checkers cross vendors, spend is a persisted ledger with idempotency keys, open questions
210
+ become recorded decisions, and every fix has a test seen failing. Report its checklist with a
211
+ file and a test per line, or `NOT_RUN` where the agent has no such stage.
212
+
204
213
  ## Completion format
205
214
 
206
215
  Report: capability, consumer, profile with the step-0 grill answers; the knowledge pack
@@ -0,0 +1,207 @@
1
+ # Resilience and autonomy — what kept agents working
2
+
3
+ Read when designing an agent's loop, its model calls, its spend and its stops — before the first
4
+ stage that calls a model or spends money. These rules come from a retrospective of about twenty
5
+ production agents (2026-10-17): each rule names the failure that taught it, generalized, and the
6
+ mechanism that held after the fix. Every rule is cheaper to build in than to retrofit.
7
+
8
+ ## Contents
9
+
10
+ - Limits are pauses
11
+ - Model answers are untrusted until accepted
12
+ - Money is a ledger
13
+ - Autonomy: decide, record, continue
14
+ - Verification you can believe
15
+ - Operations that survive restarts
16
+ - Secrets and confinement
17
+ - Checklist
18
+
19
+ ## Limits are pauses
20
+
21
+ 1. **A provider or subscription limit pauses the job; it never fails it.** Store a typed pause
22
+ (`quota_exhausted`, `retryable: true`, the reset time when known) and resume from the same
23
+ stage. Failing it cost callers whole jobs and resubmits.
24
+ 2. **Resume first.** Every worker reads its own state — checkpoint, worktree, branches, open
25
+ pull requests, notes — before it acts, and continues from there. Relaunching from scratch
26
+ after a limit recreated work over committed work and re-issued credentials already held.
27
+ 3. **A silent worker is a limit until proven otherwise.** A watcher that sees no progress for N
28
+ minutes, or limit text in the last output, resumes the run with the *same* run id.
29
+ 4. **Keep prompt cache keys stable across a resume.** One changed argument that every prompt
30
+ carries (today's date) re-keyed a finished stage and paid for it again.
31
+ 5. **Count only the job's own failures toward its retry limit.** A lost lease, a busy lock or a
32
+ provider outage is bounded by a time budget instead; five infrastructure stops a day ended a
33
+ healthy phase as FAILED.
34
+ 6. **Match concurrency to the account's rate, and cool down after a 429** per provider door: ten
35
+ parallel workers met a 429 about hourly and each lost a whole batch; three to five heavy ones,
36
+ resumed in batches, did not. A "busy" or "still starting" dependency is retried a bounded number
37
+ of times with spacing (a handful, seconds apart, only on refusals classified as transient) —
38
+ never once, never forever.
39
+ 7. **Inside a fallback chain, do not retry a provider that answered 429 or timed out** — move to
40
+ the next one. Retries there stalled a waiting user. Stagger many resumes; bound each worker's
41
+ working set (a narrow time window, a prefix), so one stop does not become a burst.
42
+
43
+ ## Model answers are untrusted until accepted
44
+
45
+ 1. **"Answered" is not "usable".** Each call site has its own `accept(text)` — the parser the
46
+ result must pass. Empty content, a refusal, a truncation (`finish_reason: length`) or an
47
+ unparseable answer is a failure, and only an accepted answer may be cached. A cached
48
+ unreadable answer once served "0 labelled" for hours.
49
+ 2. **Fallbacks cross vendors.** A chain is an ordered list of models from different vendors; a
50
+ same-vendor fallback refuses the same inputs. Build the chain where a test can refuse a lane
51
+ with no other-vendor route, and act on a new fallback only after measuring it.
52
+ 3. **The checker is never the drafter's vendor.** Choose it per turn from the model that
53
+ *actually* drafted (a fallback may have), in the router, not in configuration. No checker
54
+ left, or a checker outage, means hold or stay silent — never ship unchecked.
55
+ 4. **Size the output budget for the answer, not the input.** Reasoning tokens eat `max_tokens`:
56
+ a judge capped at 800 tokens returned no JSON in 8 of 14 calls. Give judges room or turn
57
+ reasoning off for that route; on `length`, retry once with a larger cap.
58
+ 5. **Run code checks before model checks**, and degrade to a fixed safe reply with a reason code.
59
+ 6. **A model's word verifies nothing.** A fact is verified by stored source text (or two truly
60
+ independent sources); an effect by the system of record it lands in — never by the page, a
61
+ flag the model set, or its "done".
62
+ 7. **A coding agent runs only on a model it knows.** One CLI agent on an unfamiliar vendor's model
63
+ read its instructions and ended its turn with nothing written; measure each (agent, model)
64
+ pair live before making it a default.
65
+ 8. **Pin what the agent says about itself.** A short block of true facts (what it can see, its
66
+ pipeline, its limits) lives in code; a test fails when a fact drifts. Forbid promises the
67
+ pipeline cannot keep.
68
+
69
+ ## Money is a ledger
70
+
71
+ 1. **Unknown is unknown, never zero** — in cost, in verdicts, in health — and nothing acts on it.
72
+ A missing price is a high estimate, a missing field is `NOT_RUN`, never a pass; a probe that
73
+ timed out is "unreadable", not "credential rejected"; a cooldown that could not be read is not
74
+ "never sent". An owner's refusal inside a successful response (`ok: false` over a 200) is a
75
+ refusal, never an empty result.
76
+ 2. **Persist the attempt before dispatch** — its route and a hash of its prompt — and finalize it
77
+ in `finally`; spend is Σ actual + Σ estimate for attempts without an actual. In-memory counters
78
+ reset on every resume. A call that broke before the provider answered is reconciled against
79
+ the provider's own history by that route and hash, never guessed; one provider request id
80
+ belongs to exactly one ledger row.
81
+ 3. **Check the cap before every HTTP attempt, retries included**, with one stop rule; record the
82
+ provider's own reported cost per call; count reserved or held tokens as spent.
83
+ 4. **A resend of an unknown outcome reuses its idempotency key — or does not happen.** Derive
84
+ keys from the intent (action and entity, or run and step), never from a clock or a random
85
+ value, and make them unique in storage: time-and-random keys let redelivered requests charge
86
+ again. A write whose effect is uncertain stops as `outcome_unknown`; a new key there pays twice.
87
+ 5. **A client error at submit is a rejection, not a lost task.** Settle it with known usage (zero
88
+ if none), release the reserved money in the same transaction, and never resend the identical
89
+ request; a 4xx while polling is still a lost task.
90
+ 6. **A failed outer job cancels the paid work it started**, and a cancel is a row the worker reads
91
+ at every claim and checkpoint — never an in-memory flag that a restart forgets.
92
+ 7. **Reuse what was paid for.** A restarted stage looks up the job's successful call with the
93
+ same route, prompt version and inputs before calling again (one restart made 117 paid calls
94
+ where 49 sufficed). Cache keys are content plus definition, never an identity alone.
95
+ 8. **Deny spending tools by enumerated name, and test the list** — a provider's newer tools were
96
+ missing from a deny list while older ones were denied.
97
+
98
+ ## Autonomy: decide, record, continue
99
+
100
+ 1. **An open question is a decision to make.** Decide from the recorded decisions, then the
101
+ goal, then the safest reversible option; write the decision and its source where the work
102
+ lives; batch the questions only a person can answer (sign-in, consent, payment, a typed
103
+ secret) and keep working around them.
104
+ 2. **Nothing in a user's path waits for a human approval.** Send now or not at all; when unsure,
105
+ say so, open a recorded question, and answer again automatically when the knowledge changes.
106
+ Drafts awaiting approval waited for days.
107
+ 3. **Every wait lives in durable storage**, rebuilt on start from a "debt" query — timers in
108
+ process memory died with every restart. A wait that must outlive a session (a credential that
109
+ has not landed yet) is an operating-system job, not a session's background task.
110
+ 4. **Stop at the third round.** Tuning wording or patching one heuristic a third time means
111
+ splitting the change or replacing the mechanism with one invariant and a property test.
112
+ Write a review's exit criterion before its rounds start, and block only on what breaks a
113
+ documented promise; the rest becomes a board row with its evidence.
114
+ 5. **Find the real cause before telling a person what to do** — a full disk once read as "the
115
+ service stopped" while the service was healthy; check free space and the service's own health
116
+ first.
117
+ 6. **Background chores never hold a finished command open**, unattended runs skip them, and an
118
+ unattended `--yes` never reverses a "no" a person saved.
119
+
120
+ ## Verification you can believe
121
+
122
+ 1. **A test counts once it was watched failing against a planted defect**; a mutation battery
123
+ asserts its own reach ("no tests ran" is not "all plants survived"). Exercise every guard
124
+ with a must-catch and a must-pass case.
125
+ 2. **Write expectations out; never compute them from the code under test**, and run a reference
126
+ function and its schema on the same inputs in one test — the most common defect a first reading
127
+ found was a function returning what its own schema refuses. A wall-clock bound sits far above a
128
+ loaded machine and far below the defect it guards.
129
+ 3. **Test against the real deployed instance behind its platform**, not a sample the same run
130
+ wrote: a probe passed the shipped sample and failed the first real service behind a router.
131
+ 4. **After each wave, three blind readings** — the changed units, everything that reaches them,
132
+ and the documented behaviour — then one fix round. Green suites hid six to ten real breaks.
133
+ 5. **Read a gate's exit code directly**, never through a pipe in the same command (`| tail` hid a
134
+ failed gate as success): write the output to a file, take the status, then read the file.
135
+ 6. **"Could not measure" is its own outcome.** An overloaded machine makes a gate refuse, and a
136
+ timeout under load is unmeasured, not failed or passed.
137
+ 7. **Measure noise before calling a regression**; release a retrieval change only with zero new
138
+ confident wrong answers against the previous version.
139
+ 8. **Compute a status from the whole group**, never incrementally; verify a release by the
140
+ commit it serves, from a fresh checkout of that commit.
141
+ 9. **Probe live after every deploy on every consumer channel**, not the default one; read the
142
+ nightly full-suite result first when resuming work, and release from a full local run, not a
143
+ selected subset.
144
+ 10. **Read an external contract from its raw documentation or a recorded live snapshot**, never
145
+ from a summarising fetch; fail closed on a field nobody documented.
146
+
147
+ ## Operations that survive restarts
148
+
149
+ 1. **One owner per run, named.** Only the holder of the run's lock changes its lifecycle, and each
150
+ concurrent worker has its own identity; a refused claim names the run that holds the task, never
151
+ a guessed race against a lease that lapsed long ago; a copy that a
152
+ supervisor started backs off on a held lock instead of exiting into a respawn loop. A failed
153
+ lease renewal is not a lost lease — stop only when the remaining margin runs out.
154
+ 2. **Health treats "never finished" as a fault.** Age each phase from its last completion; a
155
+ phase that only ever yielded looked healthy for fifteen days.
156
+ 3. **Everything a run creates carries its owner** (run id, pid); the next start sweeps what a dead
157
+ owner left — markers, test databases, temp roots, container volumes. Nothing a long job needs
158
+ lives in a temp directory; a cleaner removed a test database mid-deploy.
159
+ 4. **Check disk and load before heavy work**, and serialize heavy suites behind a lock held for
160
+ the whole run. A disk cleanup never deletes files version control tracks.
161
+ 5. **State that must survive a restart or a second instance lives in the shared store**, never in
162
+ process memory or on one instance's disk; a per-process cache is a cache with a TTL.
163
+ 6. **Every scheduled job leaves a trace when it dies, stalls or never starts**: a heartbeat at the
164
+ start of each tick, a queryable error row, re-arming in `finally`, an alert when quiet for two
165
+ intervals. Serialize every use of a connection threads share, reads included.
166
+ 7. **Bound every wait on a shared lock and survive a lost connection.** A lock timeout (a few
167
+ seconds) answers a retryable "busy", never a crash or a deadlock; every pooled connection has
168
+ an error listener, and readiness reports the store while liveness reports the process, so a
169
+ database blip takes the instance out of traffic instead of restarting it.
170
+ 8. **Every accumulating output has a cap in the code that writes it** — logs, receipts, caches —
171
+ with both bounds tested.
172
+ 9. **Name the account and context on every cloud CLI call** and verify the account before a write;
173
+ a saved default context once pointed a correct token at another team.
174
+ 10. **Log by error name and code**, never a driver's raw message, which can carry connection
175
+ details. A failed command logs its cause — deadline, signal, exit code, missing program — never a
176
+ bare "command failed"; a watched dependency logs once when it fails and once when it recovers,
177
+ never on every poll.
178
+ 11. **Admit work only when the machine can carry it** — free disk, swap, a cap on concurrent
179
+ sessions — and say why when you defer.
180
+
181
+ ## Secrets and confinement
182
+
183
+ 1. **A secret never enters an environment, argv, URL or log a child can read.** Hand it over a
184
+ pipe or file descriptor, or through a vault runner per command; never print a configuration
185
+ dump, and never filter one yourself.
186
+ 2. **Confine what an agent runs by the operating system**, per run (filesystem, network, ports),
187
+ and treat prompt rules and command guards as tripwires, not boundaries.
188
+ 3. **Fail closed.** When a reduced view or a scope cannot be built, answer an error, never the
189
+ wider view; a new matching rule fires only when every neighbouring input is on its allow-list.
190
+ 4. **Run the private-name gate chained before every public push** (`<gate> && git push`), not only
191
+ before merge: a `;` once let a private path reach a public branch.
192
+ 5. **Freeze every input at acceptance**, nested references included: copy it by hash and work on
193
+ the copy, so a file swapped between acceptance and use is never read.
194
+ 6. **Treat what a run wrote as untrusted** before the service copies, reads or renders it: a
195
+ regular file whose real path is inside the run's own tree.
196
+ 7. **An artefact missing a secret refuses to start**, never runs unauthenticated: validation rejects
197
+ placeholder-shaped values, and a test renders the configuration without the value and expects
198
+ an error.
199
+ 8. **Widen an access configuration first, code second**, so nothing is over-scoped even briefly.
200
+
201
+ ## Checklist
202
+
203
+ Before the first release, answer each with a file and a test: where a limit pauses and resumes;
204
+ what `accept` each model call has; which vendors its fallback and checker use; where the attempt
205
+ ledger and idempotency keys live; what happens to an unknown outcome; which waits are durable;
206
+ who owns the run lock; what the next start sweeps; how a cancel reaches paid inner work; which
207
+ outputs are capped; how a secret reaches a child; which test was seen failing for each fix.
@@ -19,7 +19,7 @@ compatibility: >-
19
19
  this plugin; Codex/Kimi use command hooks; Hermes/OpenCode/OpenClaw/Pi use native context plugins after opt-in.
20
20
  metadata:
21
21
  author: PassionCode.ai
22
- version: "0.35.0"
22
+ version: "0.35.1"
23
23
  ---
24
24
 
25
25
  # Working with Fabric
@@ -43,7 +43,9 @@ would add — never a value already in the file — and the `--apply --expect-sh
43
43
  backs the file up (`<file>.<UTC stamp>.bak`, never overwriting an earlier backup), keeps the file's mode, refuses a
44
44
  file whose shape is not `{"hooks": {"<Event>": [{"hooks": [...]}]}}` (Codex) or an array of `[[hooks]]` tables
45
45
  (Kimi Code, read back with `tomllib`: Python 3.11+), and refuses one that changed since the dry run. `--remove` takes
46
- the entry out again. Codex may ask the person to trust a new hook (`/hooks`) before it runs. The hook runs the
46
+ the entry out again. Codex may ask the person to trust a new hook (`/hooks`) before it runs. Codex keys that trust by event, group and index, so
47
+ `--remove` names the SessionStart groups after the removed one that it moves, which Codex asks the person to approve
48
+ again. The hook runs the
47
49
  `fabric_session.py` of the skills install (`~/.agents/skills/working-with-fabric/`) when there is one, else this
48
50
  script's own path; a plugin cache path changes with each update, so pass `--script <a stable path>` there.
49
51
 
@@ -93,7 +95,9 @@ only variable names are looked at, never a value (two of them carry the session'
93
95
  One line per event that did something, never content: `~/Library/Caches/ai.passioncode.fabric-agent-adapter/hooks.log`
94
96
  (macOS), `$XDG_CACHE_HOME/fabric-agent-adapter/hooks.log` (Linux, default `~/.cache`),
95
97
  `%LOCALAPPDATA%\fabric-agent-adapter\hooks.log` (Windows). Mode 0600, rotated at 1 MB to `hooks.log.1`. The
96
- per-session spool is `sessions/<session id>/` beside it (turn entries capped at 50, `board.json`, `board.shown`),
98
+ per-session spool is `sessions/<session id>/` beside it (turn entries capped at 50, `board.json`, `board.shown`; a
99
+ folder untouched for 7 days, whose worker failed or whose session ended without SessionEnd, is removed by the next
100
+ spooling hook),
97
101
  removed at the session's end.
98
102
 
99
103
  Turn them off with Claude Code's own switch (`/hooks`, or `"disableAllHooks": true` in settings), or remove the
@@ -53,6 +53,9 @@ PS_TIMEOUT_S = 0.5
53
53
  LOG_CAP_BYTES = 1_000_000
54
54
  SPOOL_CAP = 50
55
55
  LOCK_STALE_S = 30.0
56
+ #: A session folder untouched this long belongs to a session that will not spool again: its worker failed, or the
57
+ #: session ended without SessionEnd. Nothing retries it, so the next spooling hook removes it (FAA-50).
58
+ SESSION_STALE_S = 7 * 86400
56
59
  READ_CAP = 64 * 1024
57
60
  CONFIG_CAP = 32 * 1024 * 1024
58
61
  WATCH_MIN_INTERVAL_S = 10
@@ -60,7 +63,7 @@ WATCH_MAX_BACKOFF_S = 900
60
63
  SESSION_ID = re.compile(r"[A-Za-z0-9._:-]{1,128}")
61
64
  LOOPBACK_ORIGIN = re.compile(r"http://127\.0\.0\.1:(\d{1,5})")
62
65
  LOCAL_ORIGIN = re.compile(r'"origin": "http://(?:127\.0\.0\.1|localhost)')
63
- VERSION = "0.35.0"
66
+ VERSION = "0.35.1"
64
67
  HOSTS = {"claude": "Claude Code", "codex": "Codex", "kimi": "Kimi Code",
65
68
  "hermes": "Hermes", "opencode": "OpenCode", "openclaw": "OpenClaw", "pi": "Pi"}
66
69
  NATIVE_PLUGIN_HOSTS = frozenset(("hermes", "opencode", "openclaw", "pi"))
@@ -413,6 +416,30 @@ def spool(directory: Path, entry: Dict[str, Any]) -> Path:
413
416
  return path
414
417
 
415
418
 
419
+ def prune_stale_sessions(env: Optional[Dict[str, str]] = None, now: Optional[float] = None,
420
+ keep: Optional[str] = None) -> int:
421
+ """Remove session folders whose newest file is older than SESSION_STALE_S (a running worker's lock is a fresh file,
422
+ so its folder is never stale); never the folder of the session `keep`. Returns how many were removed. Never
423
+ raises."""
424
+ now = time.time() if now is None else now
425
+ removed = 0
426
+ try:
427
+ folders = list((state_root(env=env) / "sessions").iterdir())
428
+ except OSError:
429
+ return 0
430
+ for folder in folders:
431
+ try:
432
+ if folder.name == keep or not SESSION_ID.fullmatch(folder.name) or not folder.is_dir():
433
+ continue
434
+ newest = max([folder.stat().st_mtime] + [f.stat().st_mtime for f in folder.iterdir()])
435
+ if now - newest > SESSION_STALE_S:
436
+ _remove_tree(folder)
437
+ removed += 1
438
+ except OSError:
439
+ continue
440
+ return removed
441
+
442
+
416
443
  def lock_held(directory: Path) -> bool:
417
444
  lock = directory / "worker.lock"
418
445
  try:
@@ -528,6 +555,7 @@ def hook_spool(payload: Dict[str, Any], event: str, env: Optional[Dict[str, str]
528
555
  return "skipped: launched by Fabric"
529
556
  entry = {"event": event, "runtimeSessionId": session_id, "cwd": str(cwd),
530
557
  "observedAt": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}
558
+ prune_stale_sessions(env, keep=session_id)
531
559
  if event == "end" and isinstance(payload.get("reason"), str):
532
560
  entry["reason"] = payload["reason"][:64]
533
561
  spool(directory, entry)
@@ -1105,6 +1133,7 @@ def install_host_hooks_cli(argv: Sequence[str], env: Optional[Dict[str, str]] =
1105
1133
  else:
1106
1134
  path = _home(env) / ".kimi-code" / "config.toml"
1107
1135
  command = hook_command(str(args.script or default_hook_script(env)), args.host)
1136
+ shifted = 0 # Codex hook groups after ours, whose position a removal moves
1108
1137
  try:
1109
1138
  data = _read_bytes(path)
1110
1139
  digest = _digest(data)
@@ -1118,11 +1147,15 @@ def install_host_hooks_cli(argv: Sequence[str], env: Optional[Dict[str, str]] =
1118
1147
  if not present:
1119
1148
  out("install-host-hooks: no Fabric preamble hook in %s; nothing to change" % path)
1120
1149
  return 0
1121
- groups = []
1122
- for group in doc["hooks"]["SessionStart"]:
1150
+ groups, dropped = [], None
1151
+ for index, group in enumerate(doc["hooks"]["SessionStart"]):
1123
1152
  kept = [h for h in group.get("hooks", []) if not _is_ours(h.get("command"), args.host)]
1124
1153
  if kept or not group.get("hooks"):
1125
1154
  groups.append(dict(group, hooks=kept) if kept != group.get("hooks") else group)
1155
+ elif dropped is None:
1156
+ dropped = index # a group that held only our hook goes; the groups after it move up
1157
+ if dropped is not None:
1158
+ shifted = len(doc["hooks"]["SessionStart"]) - dropped - 1
1126
1159
  if groups:
1127
1160
  doc["hooks"]["SessionStart"] = groups
1128
1161
  else:
@@ -1187,6 +1220,11 @@ def install_host_hooks_cli(argv: Sequence[str], env: Optional[Dict[str, str]] =
1187
1220
  else "added the Fabric preamble hook to", path,
1188
1221
  "(backup: %s)" % backup if backup else "(new file)"))
1189
1222
  out("Undo: fabric_session.py install-host-hooks --host %s %s" % (args.host, "--apply" if args.remove else "--remove"))
1223
+ if shifted:
1224
+ # Codex keys a hook's trust by its event, group and index: the groups after ours moved up one, so Codex asks
1225
+ # the person to trust them again in /hooks before they run.
1226
+ out("Codex trusts a hook by its position: %d SessionStart hook group(s) after the removed one moved, and "
1227
+ "Codex will ask you to approve them again in /hooks." % shifted)
1190
1228
  return 0
1191
1229
  except Refused as exc:
1192
1230
  err("install-host-hooks: refused — %s" % exc)
@@ -53,8 +53,11 @@ def _capture(command, payload):
53
53
  reader = threading.Thread(target=read_output, daemon=True)
54
54
  reader.start()
55
55
  try:
56
- process.stdin.write(payload)
57
- process.stdin.close()
56
+ try:
57
+ process.stdin.write(payload)
58
+ process.stdin.close()
59
+ except BrokenPipeError:
60
+ pass # FAA-51: a helper may exit without reading its input; its output still counts
58
61
  process.wait(timeout=max(0.001, deadline - time.monotonic()))
59
62
  reader.join(timeout=max(0, deadline - time.monotonic()))
60
63
  if reader.is_alive() or invalid.is_set() or process.returncode != 0:
@@ -69,7 +72,10 @@ def _capture(command, payload):
69
72
  reader.join(timeout=0.2)
70
73
  if not reader.is_alive():
71
74
  process.stdout.close()
72
- process.stdin.close()
75
+ try:
76
+ process.stdin.close()
77
+ except BrokenPipeError:
78
+ pass
73
79
 
74
80
 
75
81
  def fabric_registered(config=None):