@sema-agent/core 7.68.4 → 7.68.6

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 (33) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/dist/agents/peer-held-queue.d.ts +6 -1
  3. package/dist/agents/peer-held-queue.js +10 -1
  4. package/dist/agents/peer-idle.d.ts +3 -1
  5. package/dist/agents/peer-idle.js +4 -4
  6. package/dist/agents/peer-session-drain.d.ts +9 -1
  7. package/dist/agents/peer-session-drain.js +184 -115
  8. package/dist/core/allow-entry.d.ts +2 -2
  9. package/dist/core/allow-entry.js +6 -5
  10. package/dist/core/ask-headline.d.ts +2 -2
  11. package/dist/core/ask-origin.d.ts +31 -31
  12. package/dist/core/ask-origin.js +20 -13
  13. package/dist/core/runner/end-of-run.d.ts +26 -13
  14. package/dist/core/runner/end-of-run.js +43 -12
  15. package/dist/core/runner/prepare-task.js +1 -1
  16. package/dist/core/runner/prepare-wiring-manifest.d.ts +1 -0
  17. package/dist/core/runner/prepare-wiring-manifest.js +2 -2
  18. package/dist/core/runner/runtask.js +2 -2
  19. package/dist/core/shell-read-silence.d.ts +2 -1
  20. package/dist/core/tool-policy.d.ts +4 -1
  21. package/dist/core/tool-policy.js +2 -2
  22. package/dist/tools/fs/removal-targets.js +7 -7
  23. package/package.json +2 -2
  24. package/wire-changes/core-stores-sql@7.68.5.json +39 -0
  25. package/wire-changes/core-stores-sql@7.68.6.json +39 -0
  26. package/wire-changes/core@7.68.5.json +141 -0
  27. package/wire-changes/core@7.68.6.json +125 -0
  28. package/wire-changes/mods-kernel@7.68.5.json +39 -0
  29. package/wire-changes/mods-kernel@7.68.6.json +39 -0
  30. package/wire-changes/primitives@7.68.5.json +39 -0
  31. package/wire-changes/primitives@7.68.6.json +39 -0
  32. package/wire-changes/wiki-gate@7.68.5.json +39 -0
  33. package/wire-changes/wiki-gate@7.68.6.json +39 -0
package/CHANGELOG.md CHANGED
@@ -1,3 +1,46 @@
1
+ ## 7.68.6 — 2026-11-17
2
+
3
+ ### What the engine cannot read or verify is an ordinary question, in every mode: a shell text it cannot read and a recursive delete whose target it cannot verify no longer stop `bypassPermissions`; their own class no longer keeps them from the auto-mode classifier or an allow rule; `echo $(( $(date -u +%s) + 3000 ))` runs under `bypassPermissions` with no card on either read face (#4784; the owner's direct ruling — a widening; what it lets run without a question is listed below, open to veto @cli @server @test; narrowing: one, below, open to veto @server — an approver's edit on resume, KL-4784-f; hard-breaking: none)
4
+
5
+ - **Before.** Since 7.49.0 the removal guard's two "could not check" questions — `unverifiable_shell_text` (a shell handed text the engine cannot read: `eval` over a built text, `… | sh`, `bash <(…)`, an expanding here-document fed to a shell, a text the lexer could not read, an arithmetic expansion whose evaluator reads back what a command substitution prints) and `unverifiable_delete` (`rm -rf` whose target the command does not settle: `rm -rf "$X"`, `… | xargs rm -rf`, an operand under a launcher-moved directory) — read the dangerous-removal breaker's row: `bypassPermissions` did not release them, the auto-mode classifier was not asked, no allow rule or "don't ask again" cleared them, and each carried `requiresRealApproval` (a blanket `onAsk: "allow"` and a class table could not answer it; a terminal reads that bit as "only a person"). So `echo $(( $(date -u +%s) + 3000 ))` stopped a `bypassPermissions` run and an `auto` run alike.
6
+ - **Now.** The two classes read the ordinary question's row (one frozen object with `ordinary`): `bypassPermissions` releases them (disclosed on `tool_end.gate.disposition.released`, as any release); their class no longer withholds the auto-mode classifier or an allow rule; `dontAsk` refuses them unless an allow covers the call; a class table (`declareClassAnswers`) may list them. The removal guard mints `requiresRealApproval` for neither any more (the bit is minted where the guard's class explains it — `RRA_EXPLAINERS` — and these two left that set); the read station's check that did not finish keeps it (below).
7
+ - **Read face (what the widening reaches).** On the open read face (`readFace: "open"`) `auto` hands these questions to the classifier, and a stored rule, a pre-approval or a class table clears them under `default`. On the narrowed face (`roots`, the engine's default) most of these commands also carry the read station's `probe` for the same unreadable text — one card, two classes — and the `probe` row there gives no classifier and no rule: such a call is still put to a person under `auto` and is not cleared by a rule, a pre-approval or a class table under `default` (`echo /usr | xargs rm -rf`, which raises no `probe`, is). A blanket `onAsk: "allow"` answers them on either face, and `bypassPermissions` releases both on either face. The `probe` half is #4789 (7.69.1).
8
+ - **What this lets run without a question — open to veto (@cli @server @test).** The two classes are ordinary questions now, so what clears an ordinary question clears them: a person's stored `Bash` allow (a whole-tool allow measured; a prefix allow read from the rows, not measured), a pre-approval, a host's blanket `onAsk: "allow"`, a class table, the auto-mode classifier and `bypassPermissions` — except that on the narrowed read face the read station's `probe` riding on the same card still holds most of these commands for a person (above). A command the engine cannot read then runs without being asked about, and the engine does not know what it reads, writes or removes. Measured on this release, one real run per cell, in `default` mode unless the column says `auto`; each cell reads narrowed read face (the default) / open read face; "asked" = put to a person (who said no); every removal ran under an inert shell, never a real one:
9
+
10
+ | Command | blanket `onAsk: "allow"` | stored whole-tool `Bash` allow | pre-approval (`allowedTools: ["Bash"]`) | class table (the classes a rule may clear) | `auto` (the classifier says yes) |
11
+ |---|---|---|---|---|---|
12
+ | `printf 'cat .env\n' \| bash` (`.env` deny-listed) | runs, reads it / runs, reads it | asked / runs, reads it | asked / runs, reads it | asked / runs, reads it | asked / runs, reads it |
13
+ | `printf 'cp f.txt .bashrc\n' \| bash` (`.bashrc` write-protected) | runs, writes it / runs, writes it | asked / runs, writes it | asked / runs, writes it | asked / runs, writes it | asked / runs, writes it |
14
+ | `rm -rf "$(printf /usr)"` | runs / runs | asked / runs | asked / runs | asked / runs | asked / runs |
15
+ | `printf 'rm -rf /usr\n' \| bash` | runs / runs | asked / runs | asked / runs | asked / runs | asked / runs |
16
+ | `bash -c "$(echo rm -rf ~)"` | runs / runs | asked / runs | asked / runs | asked / runs | asked / runs |
17
+ | `echo /usr \| xargs rm -rf` | runs / runs | runs / runs | runs / runs | runs / runs | runs / runs |
18
+
19
+ - On 7.68.5 every cell of that table was put to a person, and under the blanket allow refused without a question. Under `bypassPermissions` (a separate measurement) the four removals and the `.env` read run on both read faces and the `.bashrc` write runs on the narrowed face (its open face not measured). Beside a deployment policy's own bare real-approval bit, `ls junk | xargs rm -rf` now goes to the classifier under `auto` on both read faces (7.68.5: a person; measured): the bit's own row (`policy_rra`) admits the classifier, and the delete's class no longer withholds it (read from the rows). The same removal or read written plainly (`rm -rf /usr`, `rm -rf ~`, `cat .env`) is still stopped in every mode (KL-4784-b, KL-4784-e). Who notices: a host that answers every question with a blanket `onAsk: "allow"` (unattended runs) — these commands were refused and now run, on either read face; a person who stored a whole-tool `Bash` allow, a run with a pre-approval or a class table, and an `auto` run — on the open read face they used to stop for one question and now run, on the narrowed face they still ask, except the `xargs` form, which now runs; and every `bypassPermissions` run.
20
+ - **Not widened: a read check that did not finish — as in 7.68.5.** The read station's own state — the environment did not answer a lookup of the command's reads (a symlink it would not resolve, a home-anchored deny row such as `~/.npmrc` on an environment that declares no home), a deny floor whose spellings passed the station's bound (sixty-five values that may not have run), or a judge that hung past the gate's bound or threw — is in practice "the read-deny table was not judged", and the built-in credential rows are always there; releasing it would let an environment fault or a long spelling step past the read-deny table. So in every mode and on both read faces it reads as in 7.68.5: the question carries `requiresRealApproval`; `bypassPermissions` does not release it; the auto-mode classifier is not asked; a stored rule, a pre-approval, a blanket `onAsk: "allow"`, a class table and the read-only command arm do not answer it; `dontAsk` refuses it; a person answers it. Its class set is `unverifiable_shell_text` beside `policy_rra` (the bit no class explains, now that the shell-text class left the explainers); the class fold reads that pair as the removal breaker's row (no classifier, a hook's ask beside it floored). Known limitation KL-4784-d: such a card's class word is usually `policy_rra` (its headline reads "This deployment's policy asks for your approval here.", and beside a stored allow rule the reason the rule does not clear it reads "the deployment's policy requires a real approval for this call"), while the actual reason is that the read-deny table was not judged; the card's own sentence is 7.68.5's.
21
+ - **Not changed — and what that covers.** `dangerous_delete` — a removal the engine READS as targeting the filesystem root, a top-level directory, a home, a workspace directory or an ancestor of one — keeps the breaker's row and `requiresRealApproval`: a person under every mode, whether written plainly, through a variable the command sets, after a `cd`, or inside an arithmetic body (`$(( $(rm -rf ~; echo 1) + 1 ))`). It does not cover the same removal delivered through text the engine cannot read (a substitution, a pipe into a shell, `xargs`): that is the widened question above (KL-4784-e). Every other class's row. The class words stay in the closed set (no word added or removed). The default mode still asks one plain question about an arithmetic expansion over a command substitution (`echo $(( $(date -u +%s) + 3000 ))`): its evaluator re-reads the substitution's output, and an array subscript there runs a command — as the reference asks it. A shell text the engine cannot read beside a deployment policy's own bare real-approval bit is put to a person under `auto`, not to the classifier, on both read faces — as in 7.68.5, not a change in this release (measured); the same bit beside a delete whose target the engine cannot verify goes to the classifier (above), so the two classes differ there.
22
+ - **Wire changes (each a widening unless said).** ① `MODE_ARBITRATION.unverifiable_shell_text` and `.unverifiable_delete`: `bypassImmune` true→false, `classifierEligible` false→true, `sandboxAdmission` false→true, `ruleMayClear` false→true, `hookAskFloor` true→false. ② `ASK_CLASSES` order: the two words move from after `dangerous_delete` to after `mode` (just before `unstated`, `ordinary`): the classes a rule may clear stay the tail, so the disclosed word of a set that also holds a class no rule clears is now that class (the headline's "a saved rule would stop this" stays true); a park row written by 7.68.5 whose class set holds one of the two beside another class shows no class word or headline after the upgrade (inferred from the code, not measured: display only; the gate re-judges on resume). An approver's edit on a parked row whose class set is one of the two alone (parked by 7.68.5 or by this release) is refused on resume when the deployment's re-check of the edited input raises a bare real-approval bit, the stored class no longer explaining that bit; 7.68.5 accepted it (measured at the function level, not end to end; KL-4784-f). ③ `RRA_EXPLAINERS` loses the two. ④ `ORIGIN_IMPLIES_REAL_APPROVAL.integrity_guard`: `"at_mint"` → `false` (a guard's question carries the bit exactly when its class explains it). ⑤ On the removal guard's asks of the two classes: `AskRequest.requiresRealApproval` and the parked row's `tool_approval.requiresRealApproval` are absent (were `true`); `mandated` false and `ruleOffersAbsence` no longer `mandated` unless another member says so; the gate kind of a park is the ordinary one. ⑥ The read station's check that did not finish keeps the bit (unchanged); its class set is `["policy_rra", "unverifiable_shell_text"]` (was `["unverifiable_shell_text"]`), so its disclosed `askClass` — on `AskRequest`, the parked row, `tool_end.gate.disposition` (`denied_by_mode` under `dontAsk`), the shadow-reason and headless-remedy sentences — is usually `policy_rra` (was `unverifiable_shell_text`); when a class that sorts before it rides on the same question, that class is the word (measured: `target_unresolved`, `org_rule`, `ask_rule`, `hook`, `operator_forced`, `shell_floor`, `dangerous_delete`), so a reader that routes on the class word should not assume this form shows one word; `foldArbitrationRow` over that pair returns the removal breaker's row (`dangerous_delete`'s). ⑦ `SHADOW_REASON.unverifiable_delete` / `.unverifiable_shell_text`: the "arrived already marked" sentence `ordinary` has. ⑧ Card sentences: "Unverifiable recursive delete (fail-closed unless cleared): …" → "This delete could not be checked first: …"; "Unverifiable shell text (fail-closed unless cleared): …" → "This command could not be checked first: …"; the rows say what could not be checked in plain words and no longer say how the question is cleared.
23
+ - **Who needs it / who it harms / the compensation.** Needed by anyone running `bypassPermissions` or `auto` long tasks: arithmetic over a substitution, `eval`, pipes into a shell and `xargs rm` stopped them. Harmed: a run whose shell text or delete target hides a dangerous removal, a deny-listed read or a write-protected write the engine cannot see now runs it under `bypassPermissions` or a blanket `onAsk: "allow"` on either read face, and — where no `probe` rides beside it (the open read face, or the `xargs` form) — beside a stored whole-tool `Bash` allow, a pre-approval or a class table, and on the classifier's yes under `auto` — the risk the person chose with the mode or the standing allow. Compensation: the protected-location removal and the deny-listed read the engine does read are still stopped in every mode, including inside an arithmetic body; a read check that did not finish is a person's in every mode.
24
+ - **Rules.** −1 row (the breaker row now `dangerous_delete`'s alone; the two hold `ordinary`'s object), −2 explainer members; the removal guard's real-approval bit reads the explainer set (`explainsRealApprovalBit`) instead of a literal; +1 reading in the class fold — the unfinished check's pair (`unverifiable_shell_text` beside `policy_rra`) withholds the classifier and floors a hook, standing in for a class of its own (a closed-set change, not a patch's: 7.70.0 retires the reading with the word).
25
+ - **Pins.** `test/backlog4784-unverifiable-relax.test.ts` — M1 the owner's command, M1/M3/M4 the owner's command, its arithmetic neighbours, the unreadable texts and the deletes × bypass / auto / default / acceptEdits / dontAsk / a pre-approval / a stored rule, on both read faces, M2 arithmetic with no substitution and the stored rule's control, M5 the protected locations under bypass / auto / a pre-approval, M6 a removal in an arithmetic body, M7 ssh / scp under bypass, P1 the parked row's bits (and nothing parked under bypass), R1 the rows; `test/backlog4784-fix1-unfinished-check.test.ts` — U1 the read check that did not finish (a symlink the environment does not resolve, no home declared, sixty-five values past the deny floor's bound under a person's `Read(…)` deny rule) × bypass / auto on both read faces, default, acceptEdits, dontAsk, a blanket `onAsk: "allow"`, a class table, a pre-approval, a stored rule: refused before the program runs, the classifier never asked, no protected byte in the tool text; U2 the pair's row and the hook floor; U3 the same beside the session-transcript guard and an organization rule (the silence's bit stays bare), and the removal guard's shell-text ask still ordinary; `test/backlog1694-failing-resolver-is-not-no-face.test.ts` E5–E5d (default, acceptEdits, auto, bypass: a person asked, the deny-listed bytes never read); earlier pins of the breaker row (#1534, #1505) re-pinned to the new row, and #1672 ③ and #1329b W4 to the widened delete (the ordinary row); the read-check cells of #1693, #1672, #955 (two files), #1092 and #1329b W7 read as in 7.68.5 but for the disclosed word (`policy_rra`, or `target_unresolved` where the written target was not resolved either); 34 earlier pin files change against 7.68.5 in all. The read-check pins #1653, #1686, #1293b, #3536, #4060, #4067, #4077, #3562, #1709 and #3203 pass unchanged (their files are 7.68.5's).
26
+ - **Consumers.** @cli @server: the read check that did not finish still carries `requiresRealApproval` ("only a person"); its class word is `policy_rra` now (KL-4784-d). @cli: the "safety-class ask (blanket-allow refused)" line and the "only a person" arm read `requiresRealApproval`, which the removal guard's two asks no longer carry; a card that keys "no rule clears this" off the class word reads `MODE_ARBITRATION`'s new row. @server: an exit table that writes these two classes as "only a person / only a terminal" should treat them like `ordinary`. @client-core: a projection pinning `ASK_CLASSES` order or the five bits of these two rows. @test: bypass / auto regressions for `echo $(( $(date -u +%s) + 3000 ))`, `eval "echo $(date +%s)"` (no card under bypass on either read face; the classifier asked under auto on the open read face, a person on the narrowed one while #4789 is open), `ls x | xargs rm -rf` (no `probe`: no card under bypass, the classifier asked under auto, on either read face), the four removals and the read of KL-4784-e / -b, and the three protected-location removals (still a person under bypass); a read check that did not finish (`cat` of a symlink to a deny-listed file the environment does not resolve, a recursive read on an environment that declares no home) is put to a person under bypass and auto, the protected bytes never read.
27
+
28
+ no-notes: #1694(pins only: `test/backlog1694-failing-resolver-is-not-no-face.test.ts` gains E5b–E5d for the read check that did not finish, listed under Pins above; no change of its own)
29
+
30
+ ## 7.68.5 — 2026-11-16
31
+
32
+ ### A finished run lets go of what it handed its session's process-level seats: a long-lived host with a mailbox store no longer keeps each session's last leg for the life of the process (#4672; fix; behavior change: one, below, open to veto; narrowing: none; widening: none; hard-breaking: none; closed sets: none; exports: none; wire: none)
33
+
34
+ - **Before.** Since 7.4.0, on a deployment whose sessions have a session box (a mailbox store safe across processes over a session store that reads a row by id), every top-level leg mounts the box drain, which opens its session's idle machine and the held queue of each box it drains — process-level seats, one per session address. The drain bound them sinks built inside the leg; at the leg's loop end only the held queue's injector was detached, and every other sink still closed over the leg. A timer a seat armed for the leg (an idle ask's 12 h, a held card's deadline) also kept the async context of the run that armed it. So each session's last leg — its prepared state, tool table, guard rows, harness and conversation — stayed reachable for as long as the process lived. Measured on the engine alone (one Runner on the file backend, a new session per run, 50 caller tools, the session deleted through the store after each run, 300 runs, base and fix alternated twice): 771,232 and 771,686 bytes of heap and one whole leg (its harness, its session object, its 50 tools) kept per run on 7.68.4; 11,812 and 11,895 bytes and no leg with this fix (what is left is the "Not fixed" paragraph below).
35
+ - **Affected.** Long-lived hosts that wire a mailbox store: every session they ever ran keeps its last leg. A host that runs each request in a new session grows by one leg per request (about 770 KB in the measurement above; more with a longer conversation or a larger tool table) until the heap runs out.
36
+ - **Now.** What a leg binds its session's seats is handed through the run's end — the one end that already takes back the listeners a run hangs on a signal it does not own — and taken back once the run has settled, whatever way it ended: each seat is re-bound to the session's facts as the leg ended with them (its mode class, its name, its last turn's text) and to the deployment's own seats, nothing of the leg. A seat is re-bound only while it still holds this leg's binding: when two legs of one session are bound at once (two Runners in one process on one session id), the run's end of the one that ends first leaves the other's binding — its injector, its live readings — in place (that leg's loop end can still take the other's injector off the held queue until the other's next pass, as on every released version). A seat (a held queue, either idle half) arms its timers outside any run, on whatever clock it was given. Each seat is taken back on its own: if re-binding one throws, the others are still re-bound, and the fault reaches `RunnerDeps.onError` (`phase: "degraded"`, `classification: "run-end-take-back"`), never the process as an unhandled rejection; the run's result is unchanged. A Runner with no `onError` hears nothing of it, as with its other degraded arms.
37
+ - **Not changed.** Between legs the seats stand and work as before: a subscription recorded in one leg is fired at the end of a later one; a subscription fired after the leg ended reaches its requester, authored as before; a session's own idle ask answers it `expired` at 12 h; a held card expires at its deadline with its receipt, and an approval between legs answers `released_pending`. The host face (`peerIdleMachineIfAny`, `peerHeldQueueIfAny`, `listPeerHeldQueues`) reads them as before. Deleting a session does to its seats what it did before (nothing; a new occupant of the id replaces them). `realPeerClock` is a plain clock as before (a timer armed on it directly keeps its caller's async context).
38
+ - **Not fixed (as in every released version).** Each session whose legs mounted the drain keeps its idle machine and its held queue in this process until the process ends or a new occupant of the id replaces them — now without the leg: about 7.6 KB per session (measured: a host-owned session store, each session's box dropped, 2,400 sessions per pass, the heap slope with the seats kept less the slope with them cleared each round: 7,619 and 7,637 bytes in two passes). A host that calls the root `runTask(spec, deps)` once per request (a new Runner each call) keeps more: each session also keeps one Runner — about 22 KB per session in one measurement (an in-memory session store, 20 caller tools, one shared file mailbox; about 361 KB before the fix); what holds it is, by reading the code and not traced, the seats' resting form reaching that call's Runner through its error sink. A seat whose re-bind throws at the run's end keeps the leg it was bound (the fault reaches the error sink; no take-back is known to throw today). Deleting the session, through the engine's store or the host's own, does not remove them, and `listPeerHeldQueues()` keeps listing each ended session's empty queue. On the file backend, a host that does not drop a deleted session's box also keeps the box's open log in the mailbox store until the store closes: about 850 bytes (866 and 834 in the same two passes) and one open log per session, so one file descriptor each by reading the code (the descriptors were not counted). The drop is the deletion cascade's mailbox leg, `mailboxStore.drop`, at the scope the session's legs drained it in — the leg's `isolationScope`, else its `principal`, else `"default"`; the file mailbox keys a box by a digest of the scope's bytes, so another spelling drops another box.
39
+ - **Behavior change, an exit (open to veto).** `PeerIdleTarget.configure` no longer clears an exit the host declared (`exited`); `busy` (the session starts working) does. For a Runner's leg that begins it is the same moment as before (the leg binds and then begins). Two forms differ: a leg refused after the drain mounted and before it begins no longer clears the exit (measured: after `exited` and one such refused leg, a subscription was recorded on 7.68.4 and is answered `full` now; after the next leg that runs it is recorded on both), and between a leg's bind and its first turn a subscription is answered `full` where it was recorded (by reading the code, not measured); the run's end re-binding the seats no longer revives a target the host declared exited. A host that drives `createPeerIdleTarget` directly and re-binds it after `exited` sees subscriptions refused until it calls `busy`.
40
+ - **Rules.** The run's end gains one verb (`lend`: hand something over and name how it is taken back); listening to a signal is one use of it; the stream leg ends the run through one call that hands a take-back's fault to the error sink. The leg's seat logic (judgment, route, receipt, disclosure, the three sinks) has one spelling, read by the bound and the resting form; every bind of a seat goes through one function that records which leg's bind landed, and a leg whose run ended re-binds only a seat still its own (or one a failed bind left with no known holder). A seat's timers are armed outside any run (one clock wrapper, read by the three seat factories).
41
+ - **Pins.** `test/backlog4672-session-machine-lets-go-of-the-leg.test.ts` — R (an in-memory session store and the file backend; nothing after the run / the session deleted; a prepare that refuses after the drain mounted; the no-mailbox control), B1–B4 (each with the leg collected first: a subscriber told after the leg; a subscription across two legs; a session's own 12 h ask; a held card's deadline and an approval between legs), F1 (a real Runner whose seat throws when the run's end re-binds it: no unhandled rejection, one `run-end-take-back` error, every other take-back ran, the result unchanged), F2 (the first seat's re-bind throws: the others are still re-bound), O1 (two legs of one session bound at once: the first to end re-binds nothing the other bound), O2 (a bind that throws leaves no known holder: the earlier leg still takes the seat back), E1–E3, E5–E7 (a getter that throws at the run's end keeps nothing of the leg; a pass after the end binds the resting form; an exit stands across the take-back; with the real clock, and with a clock the host supplies, a leg whose idle ask is outstanding is collected; `realPeerClock` itself unchanged).
42
+ - **Consumers.** Nothing to change to get the fix. What a long-lived host still keeps per ended session is the "Not fixed" paragraph above: a host on the file backend that deletes sessions should drop each session's box at that exact scope; a host that shows `listPeerHeldQueues()` to people sees ended sessions' empty queues. A host whose `onError` sink sorts by `classification` has one more word, `run-end-take-back`.
43
+
1
44
  ## 7.68.4 — 2026-11-16
2
45
 
3
46
  ### A host can declare that every process opening a file data root runs in this one process table, and the directory locks under that root then judge a lock written by an engine before 7.67.0 by its pid; without the declaration nothing changes but the refusal's sentence and one re-read under the reclaim gate, below (#4667; ruled C-R2243; new host declaration; default unchanged; narrowing: none; widening: one, below, open to veto @server @cli; hard-breaking: none; closed sets: one, `EngineNoticeCode` +1; exports: two, `declareDataRoot`, `DataRootDeclaration`, and one optional member on the exported class `FileStoreLockError`, `ownerFingerprintUnread`; wire: none)
@@ -44,10 +44,15 @@ export interface PeerClock {
44
44
  clearTimeout(handle: unknown): void;
45
45
  }
46
46
  export declare const realPeerClock: PeerClock;
47
+ /** The clock a seat (a held queue, an idle half) arms its timers on: `clock`, with every timer armed outside any run. A timer
48
+ * keeps the async context it was armed in until it fires or is cleared, and with it the stores of the run whose code armed it
49
+ * (the run's whole state); a seat outlives every run (an idle ask waits 12 h), so its timers are armed, and fire, outside any. */
50
+ export declare function peerSeatClock(clock?: PeerClock): PeerClock;
47
51
  /** The live seats a bound run gives the queue. `inject` is the ONLY member that is run-scoped (a run's
48
52
  * own injection lane); the others survive the run (the receipt route rides the mailbox, the judge
49
53
  * reads the deployment's settings getter, the decision seat is the store) and are what a headless
50
- * deadline settles through. */
54
+ * deadline settles through — so what the queue keeps after the run closes over nothing of it (the
55
+ * queue is process-lived: the session-box drain hands its sinks through the run's end). */
51
56
  export interface PeerHeldQueueSink {
52
57
  /** Re-judge an entry against the recipient's CURRENT settings and mode class (CC `M`). */
53
58
  judge: (entry: PeerHeldEntry) => CrossSessionInboundVerdict;
@@ -1,3 +1,4 @@
1
+ import { AsyncResource } from "node:async_hooks";
1
2
  import { isMailboxDecisionDeliverable, isMailboxDecisionFinal } from "../core/mailbox-store.js";
2
3
  import { sameOccupant } from "../engine/session/repo-utils.js";
3
4
  import { PEER_HELD_QUEUE_CAP, PEER_HELD_REVIEW_CAUSES, peerHeldReceiptStateOf } from "./peer-notices.js";
@@ -18,10 +19,18 @@ export const realPeerClock = {
18
19
  },
19
20
  clearTimeout: (h) => clearTimeout(h),
20
21
  };
22
+ const outsideAnyRun = AsyncResource.bind((arm) => arm());
23
+ export function peerSeatClock(clock = realPeerClock) {
24
+ return {
25
+ now: () => clock.now(),
26
+ setTimeout: (fn, ms) => outsideAnyRun(() => clock.setTimeout(fn, ms)),
27
+ clearTimeout: (h) => clock.clearTimeout(h),
28
+ };
29
+ }
21
30
  const crashHandlers = new WeakMap();
22
31
  export function createPeerHeldQueue(key, opts = {}) {
23
32
  const cap = opts.cap ?? PEER_HELD_QUEUE_CAP;
24
- const clock = opts.clock ?? realPeerClock;
33
+ const clock = peerSeatClock(opts.clock);
25
34
  const entries = [];
26
35
  const deadlines = new Map();
27
36
  const releasedBy = new WeakMap();
@@ -36,6 +36,8 @@ export interface PeerIdleTargetSink {
36
36
  }
37
37
  export type PeerIdleSubscribeOutcome = "recorded" | "refreshed" | "full";
38
38
  export interface PeerIdleTarget {
39
+ /** Bind the sink the machine routes through (a leg's, then the session's resting one). Binding is not working: an exit stands
40
+ * until the session works again ({@link busy}). */
39
41
  configure(sink: PeerIdleTargetSink): void;
40
42
  configured(): boolean;
41
43
  /** CC `tYt` (sans pid classes): same requester ⇒ refresh; table full ⇒ `"full"` (the caller answers
@@ -43,7 +45,7 @@ export interface PeerIdleTarget {
43
45
  subscribe(sub: PeerIdleSubscriber): PeerIdleSubscribeOutcome;
44
46
  /** CC `A`: drop subscribers older than the TTL, silently. Returns how many. */
45
47
  sweep(now?: number): number;
46
- /** The session started working (a run began): cancel a pending fire. */
48
+ /** The session started working (a run began): cancel a pending fire; an earlier exit no longer stands (subscriptions are taken again). */
47
49
  busy(): void;
48
50
  /** The session's run ended with nothing queued: schedule the one-shot `idle` fire (debounced; parked
49
51
  * while the held buffer is non-empty and re-checked). `finishedAt` = when the turn ended. */
@@ -1,9 +1,9 @@
1
1
  import { sameOccupant } from "../engine/session/repo-utils.js";
2
2
  import { PEER_IDLE_FIRE_DEBOUNCE_MS, PEER_IDLE_HELD_BACKOFF_MS, PEER_IDLE_OUTSTANDING_CAP, PEER_IDLE_PRIORS_KEPT, PEER_IDLE_SUBSCRIBER_TABLE_CAP, PEER_IDLE_SUBSCRIPTION_TTL_MS } from "./peer-notices.js";
3
- import { realPeerClock } from "./peer-held-queue.js";
3
+ import { peerSeatClock } from "./peer-held-queue.js";
4
4
  import { peerSessionBoxHandle } from "./peer-directory.js";
5
5
  export function createPeerIdleTarget(opts = {}) {
6
- const clock = opts.clock ?? realPeerClock;
6
+ const clock = peerSeatClock(opts.clock);
7
7
  const cap = opts.tableCap ?? PEER_IDLE_SUBSCRIBER_TABLE_CAP;
8
8
  const ttl = opts.ttlMs ?? PEER_IDLE_SUBSCRIPTION_TTL_MS;
9
9
  const subs = [];
@@ -87,7 +87,6 @@ export function createPeerIdleTarget(opts = {}) {
87
87
  return {
88
88
  configure(next) {
89
89
  sink = next;
90
- exitedFlag = false;
91
90
  },
92
91
  configured: () => sink !== undefined,
93
92
  subscribe(sub) {
@@ -115,6 +114,7 @@ export function createPeerIdleTarget(opts = {}) {
115
114
  sweep,
116
115
  busy() {
117
116
  idleState = undefined;
117
+ exitedFlag = false;
118
118
  cancelPending();
119
119
  },
120
120
  idle(finishedAt) {
@@ -143,7 +143,7 @@ export function createPeerIdleTarget(opts = {}) {
143
143
  };
144
144
  }
145
145
  export function createPeerIdleRequester(opts = {}) {
146
- const clock = opts.clock ?? realPeerClock;
146
+ const clock = peerSeatClock(opts.clock);
147
147
  const cap = opts.cap ?? PEER_IDLE_OUTSTANDING_CAP;
148
148
  const priorsKept = opts.priorsKept ?? PEER_IDLE_PRIORS_KEPT;
149
149
  const ttl = opts.ttlMs ?? PEER_IDLE_SUBSCRIPTION_TTL_MS;
@@ -15,6 +15,7 @@ import type { SendMessageToolOptions } from "./send-message-tool.js";
15
15
  import type { PeerChannel } from "../core/peer-channel.js";
16
16
  import { type PeerClock, type PeerHeldQueue } from "./peer-held-queue.js";
17
17
  import { type PeerIdleMachine } from "./peer-idle.js";
18
+ import type { RunEnd } from "../core/runner/end-of-run.js";
18
19
  /** design/385 §1.2④ — the drain lease TTL. Same sizing law as the tier-3 revive lease: well under the
19
20
  * store's stale-row floor, long enough to cover one turn (a longer turn renews on the same owner at
20
21
  * its next boundary; an expired lease re-serves the batch — at-least-once). */
@@ -217,7 +218,8 @@ export interface PeerSessionDrainOptions {
217
218
  lane?: Partial<PeerLaneConfig>;
218
219
  /** The recipient's self-token set for the hop check, read live (the run's peer identity ref). */
219
220
  ownTokens: () => readonly string[];
220
- /** The recipient's `crossSessionInbound` layers, read at every drain. */
221
+ /** The recipient's `crossSessionInbound` layers, read at every drain — and by the session's seats after the leg (a held card's
222
+ * deadline or approval, an idle notice's detail), so it reads the deployment's seat and closes over nothing of the leg. */
221
223
  settingLayers: () => CrossSessionInboundSettingLayers | undefined;
222
224
  /** The recipient's own permission-mode class, read at every drain (the manifest's ask fold). */
223
225
  selfModeClass: () => PermissionModeClass | "unknown";
@@ -251,6 +253,10 @@ export interface PeerSessionDrainOptions {
251
253
  leaseTtlMs?: number;
252
254
  /** Tests: a virtual clock for the held deadlines and idle timers (honored when this process first sees the session). */
253
255
  clock?: PeerClock;
256
+ /** The run's end (end-of-run.ts): what this leg binds the session's process-level seats is handed through it, and taken back
257
+ * there — the seats then read the session's facts as the leg ended with them. Absent outside a Runner's stream: the leg's
258
+ * binding stays until the session's next leg binds its own. */
259
+ runEnd?: Pick<RunEnd, "lend">;
254
260
  }
255
261
  export interface PeerSessionDrain {
256
262
  /**
@@ -447,5 +453,7 @@ export declare function bindPeerLaneDrain(harness: PeerDrainHarness, args: {
447
453
  /** The assistant seat the host handed the leg (`RunInternals.principalInboxAssistant`, as handed): its letter observer rides the
448
454
  * `pullOnly` lane that seat made ({@link PeerSessionDrainOptions.onLetters}). */
449
455
  assistantSeat?: unknown;
456
+ /** The run's end ({@link PeerSessionDrainOptions.runEnd}). */
457
+ runEnd?: Pick<RunEnd, "lend">;
450
458
  }): PeerSessionDrain;
451
459
  export {};
@@ -137,6 +137,133 @@ export function sessionBoxVerdictOf(deps, at) {
137
137
  };
138
138
  }
139
139
  export const PEER_RESUPPLY_CAP = 1;
140
+ function readOnce(read) {
141
+ let read1;
142
+ try {
143
+ read1 = { value: read() };
144
+ }
145
+ catch (e) {
146
+ read1 = { fault: thrownText(e) };
147
+ }
148
+ if ("fault" in read1) {
149
+ const { fault } = read1;
150
+ return () => {
151
+ throw new Error(fault);
152
+ };
153
+ }
154
+ const { value } = read1;
155
+ return () => value;
156
+ }
157
+ function restingSeatFacts(live) {
158
+ const { mailbox, scope, sessionId, occupant, runId, settingLayers, onNotice, onError } = live;
159
+ return { mailbox, scope, sessionId, occupant, runId, settingLayers, onNotice, onError, selfModeClass: readOnce(live.selfModeClass), selfName: readOnce(live.selfName), lastTurnText: live.lastTurnText === undefined ? undefined : readOnce(live.lastTurnText) };
160
+ }
161
+ function readSeatJudgment(f) {
162
+ const layers = f.settingLayers() ?? {};
163
+ return { setting: resolveCrossSessionInboundSetting(layers), principalSetting: resolveCrossSessionInboundSetting(principalInboundLayers(layers)), selfModeClass: f.selfModeClass() };
164
+ }
165
+ function judgeSeatMeta(sessionId, facts, meta) {
166
+ return meta?.fromScope !== undefined
167
+ ? judgeCrossSessionInbound({ setting: facts.principalSetting, selfModeClass: facts.selfModeClass, sender: { fromScope: meta.fromScope } })
168
+ : judgeCrossSessionInbound({ setting: facts.setting, selfModeClass: facts.selfModeClass, sender: { ...(meta?.fromMode !== undefined ? { fromMode: meta.fromMode } : {}), selfSent: meta?.fromSession !== undefined && meta.fromSession.toLowerCase() === sessionId.toLowerCase() } });
169
+ }
170
+ function seatRoute(f) {
171
+ return {
172
+ mailbox: f.mailbox,
173
+ scope: f.scope,
174
+ self: { sessionId: f.sessionId, ...(f.selfName() !== undefined ? { name: f.selfName() } : {}), ...(f.occupant !== undefined ? { occupant: f.occupant } : {}), modeClass: f.selfModeClass },
175
+ ...(f.onError !== undefined ? { onError: f.onError } : {}),
176
+ };
177
+ }
178
+ function seatReceiptAddress(kind, entry) {
179
+ const from = kind === "session" ? entry.peerMeta?.fromSession : undefined;
180
+ return from === undefined ? undefined : { sessionId: from, occupant: entry.peerMeta?.fromOccupant };
181
+ }
182
+ function seatReceipt(f, kind) {
183
+ return async (entry, state, releasedBy) => {
184
+ const to = seatReceiptAddress(kind, entry);
185
+ if (to === undefined)
186
+ return;
187
+ const faults = [];
188
+ const via = {
189
+ ...seatRoute(f),
190
+ onError: (error, ctx) => {
191
+ faults.push(error);
192
+ f.onError?.(error, ctx);
193
+ },
194
+ };
195
+ if (state === "dropped")
196
+ await routePeerDroppedReceipt(via, to, entry.seq);
197
+ else
198
+ await routePeerDeliveryReceipt(via, to, state, entry.seq, releasedBy);
199
+ if (faults.length > 0)
200
+ throw faults[0];
201
+ };
202
+ }
203
+ function discloseSeatDisposition(f, lane, disposition, cause, m, heldNote) {
204
+ deliverEngineNotice(f.onNotice, {
205
+ code: "peer.inbound_disposition",
206
+ message: `cross-session message seq ${m.seq} in ${lane.label} was ${disposition === "held"
207
+ ? `HELD${heldNote !== undefined ? ` (${heldNote})` : lane.kind === "session" ? ` (it entered this session's held queue and STAYS IN THE BOX — the box is that queue's durable seat, so it is not acked until it settles; it is re-judged at every boundary, released or refused with a receipt to the sender, ${isCrossSessionHoldCause(cause) && peerHeldReceiptStateOf(cause) === "held" ? "and expires with a receipt under dialogExpiry" : "and has no expiry deadline: its cause is this session's own settings or state, not a review"})` : " (it entered this session's held queue for the principal inbox and STAYS IN THE BOX until it settles; it is re-judged at every boundary. The sender is another principal: no receipt reaches it from here — the delivery gate's receipt is its record)"}`
208
+ : disposition === "refused"
209
+ ? "refused by this session's crossSessionInbound setting"
210
+ : disposition === "resupply_exhausted"
211
+ ? "settled WITHOUT being read: its frame was summarized away by a compaction, re-supplied once, and summarized away again — the engine has stopped handing it over. The sender was not told; reply-worthy content is GONE from this session's context"
212
+ : disposition === "notice_unrouted"
213
+ ? "settled WITHOUT delivery (a notice-kind record the notice face cannot render)"
214
+ : disposition === "notice_user_only"
215
+ ? "surfaced to the user only (a notice whose sender this session's parity would hold; the model did not read it)"
216
+ : "refused by the inbound admission gate"}: ${cause}`,
217
+ detail: { disposition, cause, seq: m.seq, box: lane.boxHandle, ...(m.peerMeta?.fromSession !== undefined ? { fromSession: m.peerMeta.fromSession } : {}), sessionId: f.sessionId, runId: f.runId },
218
+ });
219
+ }
220
+ function idleTargetSink(f, queues) {
221
+ return {
222
+ notify: (sub, notice) => void routePeerIdleNotice(seatRoute(f), { sessionId: sub.requester, occupant: sub.requesterOccupant }, notice),
223
+ judge: (sub) => judgeSeatMeta(f.sessionId, readSeatJudgment(f), { ...(sub.fromMode !== undefined ? { fromMode: sub.fromMode } : {}), ...(sub.selfSent ? { fromSession: f.sessionId } : {}) }),
224
+ heldCount: () => queues.reduce((n, queue) => n + queue.size(), 0),
225
+ ...(f.lastTurnText !== undefined ? { lastTurnText: f.lastTurnText } : {}),
226
+ };
227
+ }
228
+ function idleRequesterSink(f) {
229
+ return { expired: (o) => void routePeerIdleNotice(seatRoute(f), { sessionId: f.sessionId, occupant: f.occupant }, { kind: "expired", label: o.label }) };
230
+ }
231
+ const seatBinders = new WeakMap();
232
+ function bindPeerSeat(seat, binder, legEnded, config) {
233
+ const holder = seatBinders.get(seat);
234
+ if (legEnded && holder !== undefined && holder !== binder)
235
+ return;
236
+ seatBinders.delete(seat);
237
+ seat.configure(config());
238
+ seatBinders.set(seat, binder);
239
+ }
240
+ function heldQueueSink(f, lane, drainOwner, leg) {
241
+ return {
242
+ judge: (entry) => judgeSeatMeta(f.sessionId, readSeatJudgment(f), entry.peerMeta),
243
+ ...(leg !== undefined ? { inject: leg.inject, canInject: leg.canInject } : {}),
244
+ receipt: seatReceipt(f, lane.kind),
245
+ tellsSender: (entry) => seatReceiptAddress(lane.kind, entry) !== undefined,
246
+ decide: (entry, expect, next) => moveMailboxDecision(f.mailbox, f.scope, lane.boxHandle, entry.seq, expect, next, drainOwner),
247
+ onFault: (entry, e) => f.onError?.(e, { phase: "degraded", sessionId: f.sessionId, classification: `peer-decision-move:${entry.box}#${entry.seq}` }),
248
+ onHeld: (entry, count, cause, reannounce) => {
249
+ if (!reannounce && leg?.disclosedHeld.has(entry.seq) === true)
250
+ return;
251
+ leg?.disclosedHeld.add(entry.seq);
252
+ discloseSeatDisposition(f, lane, "held", cause, entry, reannounce ? `still held; its cause moved to ${cause} (${count} held)` : undefined);
253
+ },
254
+ onSettled: (entry, settlement, reason, count) => {
255
+ if (leg !== undefined && entry.box === lane.boxHandle && settlement !== "delivered" && settlement !== "retired")
256
+ leg.settled(entry.seq, settlement);
257
+ const replyTo = seatReceiptAddress(lane.kind, entry);
258
+ const told = reason !== "decided_elsewhere" && settlement !== "retired" && replyTo !== undefined;
259
+ deliverEngineNotice(f.onNotice, {
260
+ code: "peer.held_settled",
261
+ message: `held cross-session message seq ${entry.seq} left this session's held queue: ${settlement} (${reason}); ${count} still held${settlement === "expired" && reason === "evicted" ? " — the held queue was full, so the oldest entry was expired to make room" : ""}${settlement === "retired" ? (reason === "superseded" ? " — its record is no longer in the box (another consumer settled it); nothing was decided here" : " — no decision was taken: it stays held in the box, and the next drain presents it again") : ""}${reason === "decided_elsewhere" ? " — another consumer of the box decided it first" : ""}. The sender ${told ? "was sent a receipt" : replyTo !== undefined ? "was not sent a receipt from here" : "has no reply address and was not told"}.`,
262
+ detail: { settlement, reason, seq: entry.seq, box: lane.boxHandle, ...(entry.peerMeta?.fromSession !== undefined ? { fromSession: entry.peerMeta.fromSession } : {}), heldCount: count, sessionId: f.sessionId, runId: f.runId },
263
+ });
264
+ },
265
+ };
266
+ }
140
267
  export function createPeerSessionDrain(opts) {
141
268
  const { mailbox, sessionId, runId, scope } = opts;
142
269
  const storedSessionAddress = (fromSession) => fromSession !== undefined && isPeerSessionId(fromSession) ? peerSessionBoxHandle(fromSession) : undefined;
@@ -171,34 +298,11 @@ export function createPeerSessionDrain(opts) {
171
298
  let noticeRound = 0;
172
299
  let currentRound;
173
300
  const idleMachine = peerIdleMachineFor(scope, sessionId, { ...clockOpt, ...occupantOpt });
174
- const disclose = (lane, disposition, cause, m, heldNote) => deliverEngineNotice(opts.onNotice, {
175
- code: "peer.inbound_disposition",
176
- message: `cross-session message seq ${m.seq} in ${lane.label} was ${disposition === "held"
177
- ? `HELD${heldNote !== undefined ? ` (${heldNote})` : lane.kind === "session" ? ` (it entered this session's held queue and STAYS IN THE BOX \u2014 the box is that queue's durable seat, so it is not acked until it settles; it is re-judged at every boundary, released or refused with a receipt to the sender, ${isCrossSessionHoldCause(cause) && peerHeldReceiptStateOf(cause) === "held" ? "and expires with a receipt under dialogExpiry" : "and has no expiry deadline: its cause is this session's own settings or state, not a review"})` : " (it entered this session's held queue for the principal inbox and STAYS IN THE BOX until it settles; it is re-judged at every boundary. The sender is another principal: no receipt reaches it from here \u2014 the delivery gate's receipt is its record)"}`
178
- : disposition === "refused"
179
- ? "refused by this session's crossSessionInbound setting"
180
- : disposition === "resupply_exhausted"
181
- ? "settled WITHOUT being read: its frame was summarized away by a compaction, re-supplied once, and summarized away again \u2014 the engine has stopped handing it over. The sender was not told; reply-worthy content is GONE from this session's context"
182
- : disposition === "notice_unrouted"
183
- ? "settled WITHOUT delivery (a notice-kind record the notice face cannot render)"
184
- : disposition === "notice_user_only"
185
- ? "surfaced to the user only (a notice whose sender this session's parity would hold; the model did not read it)"
186
- : "refused by the inbound admission gate"}: ${cause}`,
187
- detail: { disposition, cause, seq: m.seq, box: lane.boxHandle, ...(m.peerMeta?.fromSession !== undefined ? { fromSession: m.peerMeta.fromSession } : {}), sessionId, runId },
188
- });
189
- const readFacts = () => {
190
- const layers = opts.settingLayers() ?? {};
191
- return { setting: resolveCrossSessionInboundSetting(layers), principalSetting: resolveCrossSessionInboundSetting(principalInboundLayers(layers)), selfModeClass: opts.selfModeClass() };
192
- };
193
- const judgeMeta = (facts, meta) => meta?.fromScope !== undefined
194
- ? judgeCrossSessionInbound({ setting: facts.principalSetting, selfModeClass: facts.selfModeClass, sender: { fromScope: meta.fromScope } })
195
- : judgeCrossSessionInbound({ setting: facts.setting, selfModeClass: facts.selfModeClass, sender: { ...(meta?.fromMode !== undefined ? { fromMode: meta.fromMode } : {}), selfSent: meta?.fromSession !== undefined && meta.fromSession.toLowerCase() === sessionId.toLowerCase() } });
196
- const route = () => ({
197
- mailbox,
198
- scope,
199
- self: { sessionId, ...(opts.selfName?.() !== undefined ? { name: opts.selfName() } : {}), ...occupantOpt, modeClass: opts.selfModeClass },
200
- ...(opts.onError !== undefined ? { onError: opts.onError } : {}),
201
- });
301
+ const seat = { mailbox, scope, sessionId, occupant: opts.occupant, runId, settingLayers: opts.settingLayers, selfModeClass: opts.selfModeClass, selfName: () => opts.selfName?.(), lastTurnText: opts.lastTurnText, onNotice: opts.onNotice, onError: opts.onError };
302
+ const disclose = (lane, disposition, cause, m, heldNote) => discloseSeatDisposition(seat, lane, disposition, cause, m, heldNote);
303
+ const readFacts = () => readSeatJudgment(seat);
304
+ const judgeMeta = (facts, meta) => judgeSeatMeta(sessionId, facts, meta);
305
+ const route = () => seatRoute(seat);
202
306
  const buildPeerMessagePayload = (lane, m) => {
203
307
  const { boxHandle } = lane;
204
308
  const meta = m.peerMeta;
@@ -232,29 +336,7 @@ export function createPeerSessionDrain(opts) {
232
336
  crossSessionNotice: { kind, text },
233
337
  _sema_provenance: { kind: "cross_session_notice", from: encodePeerAddress(storedSessionAddress(m.peerMeta?.fromSession) ?? (m.from ?? "unknown")), taskId: boxHandle, seq: m.seq, ...(m.peerMeta !== undefined ? { peerMeta: { ...m.peerMeta } } : {}) },
234
338
  });
235
- const receiptAddress = (lane, entry) => {
236
- const from = lane.kind === "session" ? entry.peerMeta?.fromSession : undefined;
237
- return from === undefined ? undefined : { sessionId: from, occupant: entry.peerMeta?.fromOccupant };
238
- };
239
- const receipt = (lane) => async (entry, state, releasedBy) => {
240
- const to = receiptAddress(lane, entry);
241
- if (to === undefined)
242
- return;
243
- const faults = [];
244
- const via = {
245
- ...route(),
246
- onError: (error, ctx) => {
247
- faults.push(error);
248
- opts.onError?.(error, ctx);
249
- },
250
- };
251
- if (state === "dropped")
252
- await routePeerDroppedReceipt(via, to, entry.seq);
253
- else
254
- await routePeerDeliveryReceipt(via, to, state, entry.seq, releasedBy);
255
- if (faults.length > 0)
256
- throw faults[0];
257
- };
339
+ const receiptAddress = (lane, entry) => seatReceiptAddress(lane.kind, entry);
258
340
  const settleConsumed = (lane, seq, payload, by, reason) => {
259
341
  lane.ledger.set(seq, { kind: "terminal", why: "consumed" });
260
342
  const peerMeta = payload._sema_provenance?.kind === "cross_session_message" ? payload._sema_provenance.peerMeta : undefined;
@@ -262,63 +344,43 @@ export function createPeerSessionDrain(opts) {
262
344
  if (to !== undefined)
263
345
  void routePeerDeliveryReceipt(route(), to, "refused", seq, by === "engine" ? "the receiving engine (it could not judge the message)" : `extension ${by} of that session: ${reason}`);
264
346
  };
265
- const heldSink = (lane, live) => ({
266
- judge: (entry) => judgeMeta(readFacts(), entry.peerMeta),
267
- ...(live
268
- ? {
269
- inject: async (entry) => {
270
- if (currentRound === undefined || !currentRound.holds(lane))
271
- return "deferred";
272
- const payload = buildPeerMessagePayload(lane, entry);
273
- if (currentRound.out !== undefined && opts.receive?.listens() === true) {
274
- currentRound.batch.push({ lane, payload, priority: "next", urgent: false, seq: entry.seq, attempt: 1, source: entry });
275
- return undefined;
276
- }
277
- if (currentRound.out === undefined && payload._sema_provenance?.peerMeta?.fromScope !== undefined && opts.markExternalContent !== undefined) {
278
- const round = currentRound;
279
- try {
280
- await opts.markExternalContent(`a letter from another principal (cross-principal message seq ${entry.seq} in ${lane.boxHandle}) was delivered into this session`);
281
- }
282
- catch (e) {
283
- opts.onError?.(e, { phase: "degraded", sessionId, classification: "peer-external-mark" });
284
- return "deferred";
285
- }
286
- if (currentRound !== round || !round.holds(lane))
287
- return "deferred";
288
- }
289
- if (currentRound.deliver(payload, "next") === "deferred")
290
- return "deferred";
291
- noteDelivered(lane, entry.seq, 1, payload, entry, currentRound.carrier);
292
- return undefined;
293
- },
294
- canInject: () => currentRound !== undefined && currentRound.holds(lane) && !currentRound.spent,
347
+ const heldLegSeats = (lane) => ({
348
+ inject: async (entry) => {
349
+ if (currentRound === undefined || !currentRound.holds(lane))
350
+ return "deferred";
351
+ const payload = buildPeerMessagePayload(lane, entry);
352
+ if (currentRound.out !== undefined && opts.receive?.listens() === true) {
353
+ currentRound.batch.push({ lane, payload, priority: "next", urgent: false, seq: entry.seq, attempt: 1, source: entry });
354
+ return undefined;
295
355
  }
296
- : {}),
297
- receipt: receipt(lane),
298
- tellsSender: (entry) => receiptAddress(lane, entry) !== undefined,
299
- decide: (entry, expect, next) => moveMailboxDecision(mailbox, scope, lane.boxHandle, entry.seq, expect, next, drainOwner),
300
- onFault: (entry, e) => opts.onError?.(e, { phase: "degraded", sessionId, classification: `peer-decision-move:${entry.box}#${entry.seq}` }),
301
- onHeld: (entry, count, cause, reannounce) => {
302
- if (!reannounce && lane.disclosedHeld.has(entry.seq))
303
- return;
304
- lane.disclosedHeld.add(entry.seq);
305
- disclose(lane, "held", cause, entry, reannounce ? `still held; its cause moved to ${cause} (${count} held)` : undefined);
356
+ if (currentRound.out === undefined && payload._sema_provenance?.peerMeta?.fromScope !== undefined && opts.markExternalContent !== undefined) {
357
+ const round = currentRound;
358
+ try {
359
+ await opts.markExternalContent(`a letter from another principal (cross-principal message seq ${entry.seq} in ${lane.boxHandle}) was delivered into this session`);
360
+ }
361
+ catch (e) {
362
+ opts.onError?.(e, { phase: "degraded", sessionId, classification: "peer-external-mark" });
363
+ return "deferred";
364
+ }
365
+ if (currentRound !== round || !round.holds(lane))
366
+ return "deferred";
367
+ }
368
+ if (currentRound.deliver(payload, "next") === "deferred")
369
+ return "deferred";
370
+ noteDelivered(lane, entry.seq, 1, payload, entry, currentRound.carrier);
371
+ return undefined;
306
372
  },
307
- onSettled: (entry, settlement, reason, count) => {
308
- if (entry.box === lane.boxHandle && settlement !== "delivered" && settlement !== "retired")
309
- lane.ledger.set(entry.seq, { kind: "terminal", why: `held_${settlement}` });
310
- const replyTo = receiptAddress(lane, entry);
311
- const told = reason !== "decided_elsewhere" && settlement !== "retired" && replyTo !== undefined;
312
- deliverEngineNotice(opts.onNotice, {
313
- code: "peer.held_settled",
314
- message: `held cross-session message seq ${entry.seq} left this session's held queue: ${settlement} (${reason}); ${count} still held${settlement === "expired" && reason === "evicted" ? " — the held queue was full, so the oldest entry was expired to make room" : ""}${settlement === "retired" ? (reason === "superseded" ? " — its record is no longer in the box (another consumer settled it); nothing was decided here" : " — no decision was taken: it stays held in the box, and the next drain presents it again") : ""}${reason === "decided_elsewhere" ? " — another consumer of the box decided it first" : ""}. The sender ${told ? "was sent a receipt" : replyTo !== undefined ? "was not sent a receipt from here" : "has no reply address and was not told"}.`,
315
- detail: { settlement, reason, seq: entry.seq, box: lane.boxHandle, ...(entry.peerMeta?.fromSession !== undefined ? { fromSession: entry.peerMeta.fromSession } : {}), heldCount: count, sessionId, runId },
316
- });
373
+ canInject: () => currentRound !== undefined && currentRound.holds(lane) && !currentRound.spent,
374
+ settled: (seq, settlement) => {
375
+ lane.ledger.set(seq, { kind: "terminal", why: `held_${settlement}` });
317
376
  },
377
+ disclosedHeld: lane.disclosedHeld,
318
378
  });
319
379
  let dialogExpiryMs = resolveCrossSessionDialogExpiry(undefined).ms;
320
380
  let dialogExpiryAnnounced = false;
321
- const bindHeld = (lane, live) => {
381
+ const binder = Symbol("peer-seat-binder");
382
+ let resting;
383
+ const bindHeld = (lane) => {
322
384
  try {
323
385
  const resolved = resolveCrossSessionDialogExpiry(opts.dialogExpiry?.());
324
386
  dialogExpiryMs = resolved.ms;
@@ -330,19 +392,22 @@ export function createPeerSessionDrain(opts) {
330
392
  catch (e) {
331
393
  opts.onError?.(e, { phase: "degraded", sessionId, classification: "peer-dialog-expiry" });
332
394
  }
333
- lane.held.configure({ sink: heldSink(lane, live), dialogExpiryMs });
395
+ bindPeerSeat(lane.held, binder, resting !== undefined, () => ({ sink: heldSinkOf(lane), dialogExpiryMs }));
334
396
  };
397
+ const heldSinkOf = (lane) => (resting === undefined ? heldQueueSink(seat, lane, drainOwner, heldLegSeats(lane)) : heldQueueSink(resting, { kind: lane.kind, boxHandle: lane.boxHandle, label: lane.label }, drainOwner));
335
398
  for (const lane of lanes)
336
- bindHeld(lane, true);
337
- idleMachine.target.configure({
338
- notify: (sub, notice) => void routePeerIdleNotice(route(), { sessionId: sub.requester, occupant: sub.requesterOccupant }, notice),
339
- judge: (sub) => judgeMeta(readFacts(), { ...(sub.fromMode !== undefined ? { fromMode: sub.fromMode } : {}), ...(sub.selfSent ? { fromSession: sessionId } : {}) }),
340
- heldCount: () => lanes.reduce((n, lane) => n + lane.held.size(), 0),
341
- ...(opts.lastTurnText !== undefined ? { lastTurnText: opts.lastTurnText } : {}),
342
- });
343
- idleMachine.requester.configure({
344
- expired: (o) => void routePeerIdleNotice(route(), { sessionId, occupant: opts.occupant }, { kind: "expired", label: o.label }),
345
- });
399
+ bindHeld(lane);
400
+ const heldQueues = lanes.map((lane) => lane.held);
401
+ const bindTarget = () => bindPeerSeat(idleMachine.target, binder, resting !== undefined, () => idleTargetSink(resting ?? seat, heldQueues));
402
+ const bindRequester = () => bindPeerSeat(idleMachine.requester, binder, resting !== undefined, () => idleRequesterSink(resting ?? seat));
403
+ bindTarget();
404
+ bindRequester();
405
+ for (const bind of [bindTarget, bindRequester, ...lanes.map((lane) => () => bindPeerSeat(lane.held, binder, true, () => ({ sink: heldSinkOf(lane), dialogExpiryMs })))]) {
406
+ opts.runEnd?.lend(() => {
407
+ resting ??= restingSeatFacts(seat);
408
+ bind();
409
+ });
410
+ }
346
411
  const reconcileHeld = async (lane, lease) => {
347
412
  const live = lease.messages.filter((m) => lane.ackedUpTo === undefined || m.seq > lane.ackedUpTo);
348
413
  lane.held.reconcile(new Map(live.map((m) => [m.seq, m.decision])));
@@ -735,7 +800,7 @@ export function createPeerSessionDrain(opts) {
735
800
  return { pending: 0, urgent: 0 };
736
801
  round.lease(leased.map((c) => c.lane));
737
802
  for (const { lane, lease } of leased) {
738
- bindHeld(lane, true);
803
+ bindHeld(lane);
739
804
  await reconcileHeld(lane, lease);
740
805
  await lane.held.rejudge();
741
806
  }
@@ -1090,6 +1155,9 @@ export function mountListAgents(args) {
1090
1155
  ...(args.readSeats ?? {}),
1091
1156
  });
1092
1157
  }
1158
+ function crossSessionInboundOf(deps) {
1159
+ return () => (typeof deps.crossSessionInbound === "function" ? deps.crossSessionInbound() : deps.crossSessionInbound);
1160
+ }
1093
1161
  export function bindPeerSessionDrain(harness, opts) {
1094
1162
  const drain = createPeerSessionDrain(opts);
1095
1163
  const round = async () => {
@@ -1148,8 +1216,9 @@ export function bindPeerLaneDrain(harness, args) {
1148
1216
  inject: args.inject,
1149
1217
  ...(deps.peerLane !== undefined ? { lane: deps.peerLane } : {}),
1150
1218
  ownTokens: args.ownTokens,
1151
- settingLayers: () => (typeof deps.crossSessionInbound === "function" ? deps.crossSessionInbound() : deps.crossSessionInbound),
1219
+ settingLayers: crossSessionInboundOf(deps),
1152
1220
  selfModeClass: () => peerModeClassOf(args.refs),
1221
+ ...(args.runEnd !== undefined ? { runEnd: args.runEnd } : {}),
1153
1222
  dialogExpiry: () => (typeof deps.crossSessionDialogExpiry === "function" ? deps.crossSessionDialogExpiry() : deps.crossSessionDialogExpiry),
1154
1223
  selfName: () => rowName ?? args.selfName?.(),
1155
1224
  warmup: lookupRowName,
@@ -367,8 +367,6 @@ export declare const SHADOW_REASON: Readonly<{
367
367
  readonly hook: "an extension's screening asks about this call (a PreToolUse hook or a tool.check station) — the deployment's own screening is answered by a person";
368
368
  readonly ancestor: "the task that delegated this one owns this question";
369
369
  readonly dangerous_delete: "this removal targets a protected location (the filesystem root, a top-level directory, a home directory, or a workspace directory or one of its ancestors) — it is cleared by confirming this call, never by an allow rule";
370
- readonly unverifiable_delete: "this removal could not be verified safe — it is cleared by confirming this call, never by an allow rule";
371
- readonly unverifiable_shell_text: "the text this shell will run cannot be read by the engine — it is cleared by confirming this call, never by an allow rule";
372
370
  readonly transcript_write: "this write targets the session transcript — it is cleared by confirming this call, never by an allow rule";
373
371
  readonly org_rule: "an organization policy rule requires approval for this call";
374
372
  readonly rule_unreadable: "a rule that may govern this call cannot currently be read (this deployment's organization policy, a partition of the person's standing rules, or this call against a deny or ask rule), so whether one forbids it is unknown";
@@ -387,6 +385,8 @@ export declare const SHADOW_REASON: Readonly<{
387
385
  readonly policy_rra: "the deployment's policy requires a real approval for this call";
388
386
  readonly artifact_shared_read: "this read targets another task's shared artifact — it is cleared by confirming this call";
389
387
  readonly mode: "the permission mode puts this question to a person";
388
+ readonly unverifiable_delete: "this call arrived already marked as requiring confirmation (an earlier layer of this run, or the task that delegated it, judged it so) — it is cleared by confirming this call, never by a standing allow rule";
389
+ readonly unverifiable_shell_text: "this call arrived already marked as requiring confirmation (an earlier layer of this run, or the task that delegated it, judged it so) — it is cleared by confirming this call, never by a standing allow rule";
390
390
  readonly unstated: "this call arrived already marked as requiring confirmation (an earlier layer of this run, or the task that delegated it, judged it so) — it is cleared by confirming this call, never by a standing allow rule";
391
391
  readonly ordinary: "this call arrived already marked as requiring confirmation (an earlier layer of this run, or the task that delegated it, judged it so) — it is cleared by confirming this call, never by a standing allow rule";
392
392
  }>;