@sjawhar/claude-envoy 4.11.0 → 4.11.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/.omp-plugin/plugin.json +1 -1
- package/AGENTS.md +43 -497
- package/dist/codex-hook.js +2076 -2042
- package/dist/dispatch.js +2106 -2050
- package/dist/envoy-channel.js +2077 -2043
- package/dist/session-hook.js +2076 -2042
- package/legion/skills/legion-architect/SKILL.md +88 -66
- package/legion/skills/legion-architect/references/acceptance.md +89 -258
- package/legion/skills/legion-architect/references/decomposition.md +94 -213
- package/legion/skills/legion-architect/references/design-gate.md +88 -353
- package/legion/skills/legion-architect/references/wake-routing.md +51 -43
- package/legion/skills/legion-controller/SKILL.md +50 -181
- package/legion/skills/legion-controller/references/admission.md +25 -54
- package/legion/skills/legion-controller/references/backlog-stewardship.md +23 -119
- package/legion/skills/legion-controller/references/consolidation.md +9 -93
- package/legion/skills/legion-controller/references/daily-report.md +21 -99
- package/legion/skills/legion-controller/references/escalation.md +16 -118
- package/legion/skills/legion-controller/references/finding-asks.md +31 -162
- package/legion/skills/legion-controller/references/park-asks.md +33 -0
- package/legion/skills/legion-controller/references/parked-decisions.md +20 -264
- package/legion/skills/legion-controller/references/session.md +26 -84
- package/legion/skills/legion-controller/references/slack-mentions.md +18 -134
- package/legion/skills/legion-controller/references/triage.md +18 -89
- package/legion/skills/legion-controller/references/wakes.md +22 -549
- package/legion/skills/legion-controller/references/weekly-audit.md +9 -90
- package/legion/skills/legion-oracle/SKILL.md +19 -28
- package/legion/skills/legion-retro/SKILL.md +54 -93
- package/legion/skills/legion-retro/references/learnings.md +21 -33
- package/legion/skills/legion-retro/references/pr-body-content.md +21 -37
- package/legion/skills/legion-worker/SKILL.md +50 -64
- package/legion/skills/legion-worker/references/ci-checks.md +16 -84
- package/legion/skills/legion-worker/references/conflicts-and-rewrites.md +34 -93
- package/legion/skills/legion-worker/references/default-branch-check.md +22 -60
- package/legion/skills/legion-worker/references/findings.md +25 -180
- package/legion/skills/legion-worker/references/foreign-path.md +14 -22
- package/legion/skills/legion-worker/references/gvisor.md +20 -0
- package/legion/skills/legion-worker/references/merge-gate.md +43 -419
- package/legion/skills/legion-worker/references/plan-tests.md +8 -28
- package/legion/skills/legion-worker/references/pr-body.md +19 -218
- package/legion/skills/legion-worker/references/review-threads.md +16 -70
- package/legion/skills/legion-worker/references/tools.md +31 -578
- package/legion/skills/legion-worker/references/withheld-capability.md +12 -163
- package/legion/skills/simplify-settled-diff/SKILL.md +23 -41
- package/legion/skills/simplify-settled-diff/references/personas/code-quality-reviewer.md +14 -14
- package/legion/skills/simplify-settled-diff/references/personas/code-reuse-reviewer.md +4 -4
- package/legion/skills/simplify-settled-diff/references/personas/efficiency-reviewer.md +8 -8
- package/package.json +1 -1
- package/skills/agent-secrets/SKILL.md +46 -312
- package/skills/agent-secrets/references/store-a-secret.md +9 -0
- package/skills/approval-review/SKILL.md +20 -76
- package/skills/asd-ste100/SKILL.md +43 -85
- package/skills/asd-ste100/examples/before-after.md +18 -53
- package/skills/dispatch/SKILL.md +1 -1
- package/skills/dispatch-writing-specs/SKILL.md +1 -1
- package/skills/envoy/SKILL.md +56 -126
- package/skills/envoy/references/check-settlement.md +26 -43
- package/skills/envoy/references/deliveries.md +26 -144
- package/skills/envoy/references/legion.md +12 -45
- package/skills/envoy/references/roles.md +11 -9
- package/skills/envoy/references/sources.md +13 -25
- package/skills/outside-message/SKILL.md +24 -81
- package/skills/plain-words/SKILL.md +24 -55
- package/skills/thermonuclear-code-quality/SKILL.md +16 -26
- package/skills/thermonuclear-deep-review/SKILL.md +22 -31
- package/legion/skills/legion-worker/references/cleanup-deletion.md +0 -22
- package/legion/skills/legion-worker/references/systematic-rename.md +0 -19
- package/skills/asd-ste100/references/writing-rules.md +0 -59
- package/skills/plain-words/references/mechanics.md +0 -49
package/AGENTS.md
CHANGED
|
@@ -1,518 +1,64 @@
|
|
|
1
|
-
# Claude Envoy
|
|
1
|
+
# Claude Envoy
|
|
2
2
|
|
|
3
|
-
Claude Code plugin
|
|
3
|
+
`@sjawhar/claude-envoy` is the Claude Code plugin for Envoy and Dispatch.
|
|
4
|
+
One MCP stdio server (`src/envoy-channel-server.ts`) is the session's Envoy ingress and serves the `envoy_*` tools; the mod (`hooks/mod.ts`) writes into a terminal session; `bin/dispatch` puts the `dispatch` command on the Bash tool's `PATH`.
|
|
5
|
+
In a pane `legion claude-bridge` launched, the server also runs the Legion phase worker (`src/legion-*.ts`).
|
|
6
|
+
`codex/` and `src/codex/` are the Codex CLI plugin, `@sjawhar/codex-envoy`, built from this source.
|
|
7
|
+
`README.md` has the architecture, the bundle and release, and the manual smokes.
|
|
4
8
|
|
|
5
|
-
##
|
|
9
|
+
## Commands
|
|
6
10
|
|
|
7
|
-
|
|
8
|
-
It subscribes NATS to two subjects.
|
|
9
|
-
Every Envoy message reaches it on the session's relay subject, where the listener serves the
|
|
10
|
-
session's own durable consumer, and it answers no receipt.
|
|
11
|
-
The other is the Agents page live view's control subject
|
|
12
|
-
(`agentstream.<session_id>.control`, `src/agent-stream-runner.ts`), which carries a viewer's
|
|
13
|
-
replay request and its watch pings and no Envoy traffic.
|
|
14
|
-
It renders each
|
|
15
|
-
envelope through `@legion/envoy-client/delivery`, then writes it into the session's own
|
|
16
|
-
conversation through the mod (`src/mod-session.ts`), or, in a Legion pane, through the bridge's
|
|
17
|
-
inbox.
|
|
18
|
-
There is no Monitor and no native Claude messaging socket path. The server's tools are the
|
|
19
|
-
`envoyToolSpecs` alone, the ten `envoy_*` tools and `slack_post`: agents reach Dispatch through the
|
|
20
|
-
`dispatch` command, which `bin/dispatch` puts on the Bash tool's `PATH`.
|
|
11
|
+
- From this directory: `bun run test` (one file: `bun test --timeout=60000 tests/mod.test.ts`), `bun run typecheck` and `bun run lint`.
|
|
21
12
|
|
|
22
|
-
|
|
23
|
-
relays it on `notifications.envoy.deliver.<session_id>`, which is where the session's messages
|
|
24
|
-
come from ("Session consumers" in
|
|
25
|
-
`packages/envoy/AGENTS.md` states the rule), with the protocol both plugins share,
|
|
26
|
-
`@legion/envoy-client/consumer-delivery`. The server subscribes the current id's relay subject
|
|
27
|
-
before it registers, and every registration asks for consumer delivery with the relay's epoch
|
|
28
|
-
(one per NATS connection; a nats.js `reconnect` begins another and registers at once,
|
|
29
|
-
`renewRelayEpoch`) and its resume point. The answer's one mode is `consumer`, and the relay
|
|
30
|
-
carries the agent subject and every followed topic, each of which the stream stores, in stream
|
|
31
|
-
order: each frame is answered `received`
|
|
32
|
-
as it decodes, goes to the server's write queue, and is answered `done` once the
|
|
33
|
-
notifier resolved its write and the ledger recorded it (`deliverRelayed`), at once for a frame
|
|
34
|
-
skipped, already shown or a late BTW, which is passed over. In a Legion pane the notifier
|
|
35
|
-
resolves when `legion claude-bridge` answers its inbox, which it does once Claude Code re-emits
|
|
36
|
-
the delivery as the user message it took (`--replay-user-messages`); in a terminal session it
|
|
37
|
-
resolves once the mod has stored the row, and while the session is idle the card is a prompt
|
|
38
|
-
instead and the write resolves once the mod reports that the engine took it (`show`). A write
|
|
39
|
-
that fails
|
|
40
|
-
answers `nak`, and from the frame's third delivery `done` with a notice naming it; a frame that
|
|
41
|
-
arrives after a `/clear` moved the session to another id is answered `nak`. The relay's snapshot
|
|
42
|
-
(the resume point and each topic's follow time) is the
|
|
43
|
-
`consumer` part of the id's state file, written whenever it changes. An id with no snapshot of
|
|
44
|
-
its own starts its consumer at the stream's end, so it is shown nothing published before it
|
|
45
|
-
first registered. A registration the listener can give no consumer is refused by name, with the
|
|
46
|
-
reason the one canonical list holds (`ErrorWireSchema.reason`,
|
|
47
|
-
`packages/envoy-client/src/transport.ts`), and nothing is
|
|
48
|
-
registered: the server says so on stderr and asks again at each heartbeat. There is no second
|
|
49
|
-
path to fall back to.
|
|
13
|
+
- `bun scripts/build.ts --out "$(mktemp -d)"` builds a runnable copy outside the repository, and `--codex-out <dir>` the Codex plugin; `bun run verify-build "$(mktemp -d)/built.tar"` builds twice and compares, as the release does.
|
|
50
14
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
path a frame taken live takes (the mod's write into the conversation, or the Legion bridge's
|
|
54
|
-
inbox), with a last line saying when it was published while the
|
|
55
|
-
connection was down (`storedText`, worded by `@legion/envoy-client/delivery-ledger`, as are the
|
|
56
|
-
notices, which its `envoyNoticeText` renders in TOON as every card is); such a frame runs
|
|
57
|
-
nothing. The server records
|
|
58
|
-
each frame Claude Code was handed in the delivery ledger before its claim settles, and drops a
|
|
59
|
-
frame the ledger holds (a repeat the relay's restart at the ack floor sent again). The state is one file per session id,
|
|
60
|
-
`replay-<url-encoded session id>.json` in the
|
|
61
|
-
plugin's state directory (`src/replay-state.ts`, mode 0600, written by rename): the resume point,
|
|
62
|
-
the followed subjects, which the server follows again at start even after the listener reaped its
|
|
63
|
-
interests, and at most 72 hours of ledger, at most 20,000 entries; nothing prunes these files,
|
|
64
|
-
since Claude Code can resume a session at any later time. A `/clear` handoff to a new id starts a
|
|
65
|
-
fresh file, as a new session does, so nothing from before it comes back. A frame that fails three
|
|
66
|
-
times is replaced by a notice naming it on
|
|
67
|
-
the same path; a notice that cannot be shown goes to stderr. A crash between the hand-off and the ledger
|
|
68
|
-
write can show a frame twice, never lose it. The host policy pi-envoy shares is the ledger's too:
|
|
69
|
-
which subjects the session follows (`replayFollowedSubjects`: the agent subject and every
|
|
70
|
-
topic but a role's or one reaching a private stream subject), which remembered topics come back
|
|
71
|
-
at start (`rememberedTopics`), when a `subscription.removed` frame closes a topic and takes it
|
|
72
|
-
out of the registry, and which topics a registration carries (`registrationTopics`: the
|
|
73
|
-
session's own agent subject and every followed topic the listener will store for it, leaving out
|
|
74
|
-
one reaching a private stream subject that is not this session's — `reachesPrivateStreamSubject`,
|
|
75
|
-
the listener's rule: another session's agent subject, a failed-delivery lane, a controller notice
|
|
76
|
-
lane of a project whose controller role this session does not hold, or a wildcard reaching one —
|
|
77
|
-
and one nothing would ever be delivered on, `streamDeliversNothing`, which the listener stores
|
|
78
|
-
for no session: it leaves such a topic out of the row and warns about it, so a topic the session
|
|
79
|
-
follows from its row or its remembered state wedges nothing); those rules are
|
|
80
|
-
`@legion/envoy-client/stream-topics`'s, and this server keeps only how it shows a card, where it
|
|
81
|
-
warns, and its file. A caller that names such a topic itself is refused by name: `follow`, which
|
|
82
|
-
is the `envoy_subscribe` tool's call and nothing else, throws `uncapturedTopicRefusal`, the
|
|
83
|
-
listener's own warning for that topic, and follows nothing of that call.
|
|
15
|
+
- The real-binary tests skip unless `LEGION_TEST_CLAUDE` names a Claude Code binary (README, "Local checks").
|
|
16
|
+
`tests/envoy-channel-stall.test.ts` runs only with `LEGION_E2E_ENVOY_STACK=1` and `go` on `PATH`.
|
|
84
17
|
|
|
85
|
-
|
|
86
|
-
`@legion/envoy-client/nats-connection` (`natsConnectionOptions`): a ping every 10 s and the
|
|
87
|
-
connection dropped on the tick that finds two pings unanswered, so a path that freezes without
|
|
88
|
-
closing (packets stop, neither side closes) is left within 30 s and redialed at once, 52 s when
|
|
89
|
-
that redial also hangs on nats.js's 20 s dial timeout and the 2 s reconnect wait; it reconnects
|
|
90
|
-
forever, 2 s apart, and each `reconnect` status renews the relay's epoch. nats.js's default 120 s
|
|
91
|
-
ping interval left a frozen path for up to 6 minutes. Every registration names the plugin:
|
|
92
|
-
`plugin` `@sjawhar/claude-envoy` and `plugin_version` the version segment of the plugin-cache
|
|
93
|
-
directory the bundle runs from (`…/plugins/cache/<marketplace>/<plugin>/<version>/`, the npm
|
|
94
|
-
version Claude Code installed, since the marketplace entry is an `npm` source;
|
|
95
|
-
`installedPluginVersion` in
|
|
96
|
-
`src/installed-build.ts`), or `source` for a bundle outside the plugin cache (a checkout,
|
|
97
|
-
`--plugin-dir`); a checkout's `package.json` `version` names no release and is never sent.
|
|
18
|
+
## Build and release
|
|
98
19
|
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
only through its mod (`hooks/mod.ts`, `src/mod-session.ts`), so it advertises nothing until the
|
|
102
|
-
mod connects and `aside`, `btw` and `steer` once it has; it registers again as soon as the link
|
|
103
|
-
hears from the mod, by its hello or by its first poll, since a mod says hello once per Claude
|
|
104
|
-
Code process and a server Claude Code starts again inside that process hears only polls.
|
|
105
|
-
A Legion pane whose deliveries go to `legion claude-bridge`'s inbox advertises
|
|
106
|
-
`aside` and `steer` (`INBOX_CAPABILITIES` in `src/legion-inbox.ts`) whether or not the mod is
|
|
107
|
-
there — the bridge starts a turn with a delivery when Claude Code is idle and sends it as the
|
|
108
|
-
next user message of the running turn otherwise — and gains `btw` with the mod.
|
|
109
|
-
Permission relay is also intentionally absent: without a sender-authenticated reply path and
|
|
110
|
-
reply-ack design, declaring it would allow an Envoy input to decide Claude Code permissions.
|
|
111
|
-
Dispatch asks stay on Dispatch.
|
|
20
|
+
- Nothing commits `dist/` or `legion/`, and nothing run locally writes them.
|
|
21
|
+
The `claude_envoy_build` job of `.github/workflows/release.yaml` builds and publishes after a merge that touches a path of `$CLAUDE_ENVOY_VERSION_ARGS`.
|
|
112
22
|
|
|
113
|
-
|
|
23
|
+
- The plugin cache has no `node_modules`, so the bundles inline every dependency, `@legion/contracts` and `@legion/envoy-client` among them.
|
|
114
24
|
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
| Claude plugin manifest | `.claude-plugin/plugin.json` | Declares the MCP configuration only; it must not declare a Monitor. `hooks/hooks.json` is auto-discovered. The committed file declares no `version`, and neither does the plugin's entry in the root `.claude-plugin/marketplace.json` (tested): what that entry carries is a range on its `npm` source, `version: ">=1.0.0"`, which keeps an install off the 0.0.0 placeholder published so that trusted publishing could attach to the package and otherwise takes `latest`, and `release.yaml`'s `claude_envoy_build` writes the release's version into the `.claude-plugin/plugin.json` it packs. That is what Claude Code reads — it names an installed plugin by that manifest's `version` and never by the version the registry served, so a package published without one is cached as `unknown` and no later release reads as an update (measured on 2.1.311, and the build job's tarball check pins it). `claude plugin marketplace update legion-plugins`, then `claude plugin update claude-envoy@legion-plugins`, installs the newest `@sjawhar/claude-envoy` (README "Updates"). A `version` committed here would instead hold every install at that string until someone changed it. |
|
|
118
|
-
| Oh My Pi plugin manifest | `.omp-plugin/plugin.json` | Empty `mcpServers`, which is how omp is told this plugin has no MCP server: the channel server exits without Claude Code's session identity, and omp gets Envoy and Dispatch from `@sjawhar/pi-envoy`. omp reads this file before `.claude-plugin/plugin.json` and a manifest `mcpServers` replaces `.mcp.json` rather than merging; omitting the key falls through to `.mcp.json` and relaunches the server. Claude Code never reads it. Its `version` equals `package.json`'s (tested); omp reads only the file's `mcpServers` and that it exists, never its `version`. |
|
|
119
|
-
| Skills | `skills/agent-secrets`, `skills/asd-ste100`, `skills/envoy`, `skills/dispatch`, `skills/dispatch-first`, `skills/dispatch-writing-specs`, `skills/outside-message`, `skills/plain-words`, `skills/approval-review`, `skills/thermonuclear-code-quality`, `skills/thermonuclear-deep-review` | Relative symlinks into the root `skills/`; the plugin ships these eleven and no other — the eight a standalone Claude Code session uses, `approval-review`, which only a session judging an approval request reads, and the reviewer's pair, which ships in both plugins so one copy of each rubric reaches both harnesses (the rest belong to Legion roles on Oh My Pi; README "Skills"). The pack resolves them, not the install: `bun pm pack` packs a link as nothing at all, so `package.json`'s `prepack` (`scripts/pack-skills.sh`) replaces each link with the skill's own files, which `files`' `skills/**` then packs, and its `postpack` puts the links back. `scripts/check-packed-skills.sh` reads them back out of the tarball for `release.yaml`'s `claude_envoy_build`, and `tests/packed-skills.test.ts` packs a tarball of its own. |
|
|
120
|
-
| Built bundle | `dist/`, `scripts/build.ts`, `scripts/verify-build.sh` | Built, never committed: `release.yaml`'s `claude_envoy_build` builds it and packs it into the tarball it publishes to npm (its `bun run verify-build <tar>` builds it twice in a scratch directory, checks it as the release will and packs it, writing no file of the checkout, and nothing a person runs locally writes `dist/` or `legion/`; the jobs that run `verify-build` are named in its header and the jobs that run `release-push.sh extract-built` in that subcommand's paragraph; convention below), and `bun scripts/build.ts --out <dir>` builds a runnable copy outside the repository. The plugin cache has no `node_modules`, so the four executables (the channel server, the session hook, the title hook and the `dispatch` CLI, `BUNDLE_ENTRYPOINTS`) ship bundled, with `dist/THIRD_PARTY_NOTICES` (the inlined packages' licenses, from Bun's metafile through the root `scripts/third-party-notices.ts`); the build runs only on the pinned Bun (`.bun-version`). A mode folded into an existing bundle is paid for by that bundle's every other mode: an ESM entrypoint evaluates its whole module graph before it reads `argv`, which is why the title hook has an entrypoint of its own and why a hook on a blocking event is weighed by what its bundle imports, not by what its mode runs. |
|
|
121
|
-
| The `dispatch` CLI | `bin/dispatch` (the shim, mode 755), `dist/dispatch.js` (built from `../envoy-client/bin/dispatch.ts`), `hooks/session-hook.ts` | Claude Code puts the plugin's `bin/` on the Bash tool's `PATH`. The `open-asks` hook writes `export DISPATCH_HOST=claude` and `export ENVOY_CONFIG_FILE='<path>'` (the envoy.json Claude Code's rule picks, `$CLAUDE_CONFIG_DIR/envoy.json` when that is set; single-quoted, which Claude Code's PowerShell bridge reads for a value holding no quote; `singleQuoted` in `hooks/session-hook.ts` gives the rest) to `CLAUDE_ENV_FILE`, each unless the file already holds that line, since every `SessionStart` of a session runs it; with no workable file location (a relative `CLAUDE_CONFIG_DIR`, `ENVOY_CONFIG_FILE` or `XDG_CONFIG_HOME`) it writes no `ENVOY_CONFIG_FILE` line. For a Legion pane (`LEGION_STATE_DIR` set) it writes the pane's jj attribution overlay too, and keeps exactly one `export JJ_CONFIG='<chain>'` line in that file: the line replaces an earlier one in its place rather than joining it, since a resume or a compaction of the same session id runs the hook again over the file it already wrote and the chain it resolves can differ, where two such lines in one sourced file would leave which overlay wins to the order they were written in. When no overlay could be written the file is left as it is, no line written and none removed: `CLAUDE_ENV_FILE` is `<config>/session-env/<session id>/sessionstart-hook-<n>.sh` (read on the pinned 2.1.311), one file per session id, so a `/clear` gets a new and empty one and a line already there names this same session's own overlay, still on disk — removing it would leave the session with no trailer, where keeping it leaves it the trailers it had. The command reads the file `ENVOY_CONFIG_FILE` names whenever `DISPATCH_HOST` is set. A Bash that takes nothing from that file, as a subagent's can (Claude Code issue 46696), has `DISPATCH_HOST` unset and the `CLAUDE_CODE_CHILD_SESSION=1` Claude Code sets in every Bash, so its `dispatch` command takes host `claude` and reads `CLAUDE_CONFIG_DIR` itself, by the plugin's own rule. The command reads the session id from `CLAUDE_CODE_SESSION_ID`, which Claude Code sets fresh in every Bash command and moves on `/clear`. The command prints the follow notice itself, once per ask. |
|
|
122
|
-
| Channel configuration | `.mcp.json`, `bin/envoy-channel.ts` | Launch is `bun ${CLAUDE_PLUGIN_ROOT}/dist/envoy-channel.js`; stdout remains pure MCP protocol. The `env` block passes through `CLAUDE_PROJECT_DIR` only — an unset `${VAR}` is substituted literally, so optional inputs are inherited, never listed. |
|
|
123
|
-
| Hook command | `hooks/hooks.json`, `hooks/session-hook.ts`, `hooks/session-title-hook.ts` | Two bundles. `dist/session-hook.js` takes its mode as an argument — `open-asks`, `dispatch-first` or `answers`, plus `answers-refresh`, which only the `answers` mode starts and hooks.json never names; an argument naming none of them throws — and each mode is a hook of its own, because Claude Code caps each hook's output at 10,000 characters. `open-asks` (every `SessionStart`) names the `dispatch` command's host and hands on the session's envoy.json in `CLAUDE_ENV_FILE`, records the current session id per Claude process, records the session's chosen title and injects the open-asks summary; always exits 0. For a Legion pane (`LEGION_STATE_DIR` set) it writes the pane's jj attribution overlay under that directory too, and keeps exactly one `export JJ_CONFIG='<chain>'` line in `CLAUDE_ENV_FILE`: the line replaces an earlier one in its place rather than joining it, since a resume or a compaction of the same session id runs the hook again over the file it already wrote and the chain it resolves can differ; when no overlay could be written the file is left as it is, no line written and none removed, since `CLAUDE_ENV_FILE` is one file per session id (`<config>/session-env/<session id>/sessionstart-hook-<n>.sh`, read on the pinned 2.1.311) — a `/clear` gets a new and empty one, and a line already there names this same session's own overlay, still on disk and still correct. `dispatch-first` (every `SessionStart`, and every `SubagentStart`, since a subagent runs the same `dispatch` command) injects the `dispatch-first` skill as `hookSpecificOutput.additionalContext` under the input's `hook_event_name` when Dispatch is configured, reading `${CLAUDE_PLUGIN_ROOT}/skills/dispatch-first/SKILL.md` at run time and exiting non-zero naming it when it is missing. On a resume or fork Claude Code adds a SessionStart hook's context only when the transcript does not already hold the same text (measured on 2.1.283), so a resumed session keeps one copy and one opened without the skill gets it; the hook itself checks nothing. `answers` (every `SessionStart`, and every `SubagentStart`) injects what people wrote to the session in the last 72 hours as `hookSpecificOutput.additionalContext`: `readSessionAnswers` from `@legion/envoy-client/session-answers` for the input's `session_id` (at `SubagentStart` the parent's, which `tests/answers-claude.test.ts` checks on the real binary), the list pi-envoy puts on every model request, or its failure line naming why when a read failed and no list read before has an item to show, and nothing when there is nothing to show, Dispatch answered its own `404 NOT_FOUND` "no route for …" (`isNoAnswersRoute`, which `dispatch answers` cannot read past either; the hook then writes the read's `notice`, naming that Dispatch, to stderr, one line per process), or Dispatch is not configured; a proxy's 404 page or a 200 that is no answers list is a failed read. Its bound is counted from its process's start, Bun's start-up included: it prints by `ANSWERS_BY_MS` (800 ms, `SESSION_ANSWERS_DEADLINE_MS`), or `ANSWERS_LEAST_WAIT_MS` (150 ms) after its code begins when the start-up took longer, carrying the last list read from `answers.json` in the session's Dispatch state directory (`readSessionAnswers` works it out from `env`) when Dispatch has not answered, then waits on `sessionAnswersSettled` for `ANSWERS_SETTLE_MS` (50 ms) more so a read that answered late still writes that file for the next hook, and calls `process.exit(0)` whatever happened, a malformed input included (stderr names why), so nothing still in flight holds it. Dispatch is resolved with `commands: "kept"` first; a fresh process has kept no `!` command's outcome, so when that resolution is off with an error the mode starts the refresher: this bundle again (`process.execPath`, `Bun.main`) in mode `answers-refresh` with the session id and project directory, detached (its own session, so a signal to the hook's process group does not reach it), stdio ignored (so it holds none of the hook's pipes) and `unref()`ed, unless `answers-refresh.lock` in the session's state directory names a live refresher (its pid; a lock older than 30 s, or whose pid is gone, is stale). The refresher takes that lock (`wx`; a second one exits at once, so a burst of `SubagentStart` hooks runs the command once), resolves Dispatch with commands run, so `envoy-config`'s run of the command ends in its own process with its own clean-up (the group killed at the 10 s timeout, the stdout file's directory removed), reads with a 12 s deadline (which writes `answers.json`), writes `{finished_at, dispatch_url, text, notice}` to `answers-refresh.json` and removes the lock. The hook polls that file every 20 ms until its print deadline and carries its `text`, and reports its `notice` on stderr, when it finished after the hook started; otherwise it carries the last list read from the Dispatch URL envoy.json names now (`sessionDispatchUrl`, resolved before the wait without reading the token, passed as `readSessionAnswers`' `dispatchUrl`; a list another Dispatch answered never stands in) or the failure line naming that the command had not finished, and exits, so the next hook carries the list the refresher read. Its `timeout` is 5. Measured with Dispatch hanging: about 870 ms wall from spawn to exit; healthy, about 220 ms. `dist/session-title-hook.js` (every `UserPromptSubmit`, no argument) records the payload's `session_title` — the name a person gave the session, which Claude Code hands a hook and the plugin nowhere else — under `${CLAUDE_PLUGIN_DATA}/titles/`, and removes that file when the field is absent or blank, which is how a rename is undone. It writes nothing to stdout and exits 0 whatever happens, a payload that is not JSON included (`open-asks` and `dispatch-first` still fail loudly on one), because Claude Code adds a `UserPromptSubmit` hook's stdout to the model's context and reads its exit code 2 as a block of the prompt, and a cosmetic title may do neither; a failure goes to stderr. Claude Code blocks the user's prompt on it, so it is a bundle apart from the other two and keeps zod, the Dispatch client and `session-settings` out of its import graph (`src/session-state.ts` holds the file helpers for that reason, `src/session-identity.ts` imports zod and is not reachable from here): 5 kB and ~68 ms against the shared bundle's 811 kB and ~165 ms, the latter all but 3 ms of it bare `bun` start-up. It checks the payload itself — a non-empty string `session_id`, an optional string `session_title` — rather than carry a schema library. Its `timeout` is 5, not the 20 the `open-asks` and `dispatch-first` hooks carry. |
|
|
124
|
-
| Real Claude Code test | `tests/answers-claude.test.ts`, `/.claude-code-pin`, `/.github/actions/install-claude-code` | The `answers` hook on the real binary: Claude Code runs with this package as `--plugin-dir`, an isolated HOME and `CLAUDE_CONFIG_DIR`, and one stand-in as its Messages endpoint (`ANTHROPIC_BASE_URL`, server-sent events as the API streams them) and Dispatch (`DISPATCH_URL`); each case reads the list off the Messages request after the moment: startup (`claude -p --session-id`), `--resume <id>`, `/compact` sent in stream-json as `legion claude-bridge` sends turns, and a subagent (the stand-in answers with an `Agent` tool call, the API name of Claude Code's Task tool). `LEGION_TEST_CLAUDE` names the binary; the test skips without it, except on GitHub Actions, where the claude-envoy job installs the release `.claude-code-pin` pins (`bun add` into the runner's temp directory). A pin bump that changes a request shape is fixed in that file. |
|
|
125
|
-
| Inbound channel server | `src/envoy-channel-server.ts`, `src/envoy-off.ts` | MCP capability, notification queue, NATS registration, session-id handoff, role persistence, rejected-frame replies, and the Envoy tools, on the envoy.json Claude Code's rule picks (`@legion/envoy-client/session-settings`); why a section is off, and that inbound messages are off, goes to stderr once as `envoy-channel: <notice>`. A tool whose `executeEnvoyTool` call throws answers a tool result with `isError: true` and the error's text (`messageFor`), so the model reads the listener's own sentence, a refusal for the sender's rate among them; an unknown tool (`UnsupportedEnvoyToolError`, which MCP counts among protocol errors) and a call before the channel session has started stay JSON-RPC errors. `runEnvoyChannelServer` chooses between that server and the two reduced modes of `src/envoy-off.ts`. With Envoy off it runs `serveEnvoyOff` instead: an MCP server that lists no tool, refuses every call with `Envoy is off for this session: <why>` (the section's notice or error), opens no NATS connection and calls no listener, and exits 0 when stdin ends or on SIGTERM, SIGINT or SIGHUP. With Envoy on and inbound messages off (`inbound.off`: no NATS server, from `envoy.natsUrls` or `ENVOY_NATS_URL`, or its seed refused), it serves the tools on `inboundOffChannelSession`: no NATS connection, nothing registered with the listener, an empty inbox, `envoy_subscribe` refused naming why, and a role `envoy_role_set` claims still persisted. |
|
|
126
|
-
| A person's message | `src/user-turn-router.ts`, `src/mod-session.ts`, `src/user-turn-state.ts`, `src/claude-rows.ts` | What a frame from Dispatch's Agents page becomes (INFRA-1026). The accept step is `acceptUserTurn` (`@legion/pi-shared/accept-user-turn`), the one step both Envoy plugins take — this router and `acceptedUserTurn` in `packages/pi-envoy/extensions/envoy.ts` — so a fix to the rule lands in both: a candidate frame (`isUserTurnCandidate`), an attempt this session has not handled, the attempt recorded **before** Dispatch is asked (a 404 included), the accept, and the stored body it answers — never the frame's own text. This host supplies the record, the Dispatch client, the session id and the wording of each refusal. The record lives in `turns/<url-encoded session id>.json` and outlives the process, so no restart spends an attempt twice; it also maps each delivered row to the Dispatch message it is, which tags that row on the live view. A row is matched to a message by the shared line rule (`comparableLines`, `@legion/contracts`), which the Agents page reads a stored body by too, so the two cannot drift and show a person's message twice. A terminal session takes the body through the mod (`$.session.append` during a turn, `$.prompt.submit({asUser:true})` while idle, one submit in flight at a time, and one plain submit at a row the turn never read); a pane's goes to the bridge's inbox, with its pictures as `blocks`. That plain submit carries each unread message's own words and its Dispatch id and never points at the row (`unreadRowPrompt`): driven live, a prompt saying "Read the message above" was answered `I don't see an actual Dispatch message content above` and `it looks like an injection and I'm not going to act on it`. A `/` message runs through `$.command.run` and its output is the reply — the result's `text`, else its `context` entries, which is where a terminal `/context` puts its table and the only place it puts it, else the `<local-command-stdout>` row Claude Code wrote for that run (`src/claude-rows.ts`, which the live view parses the same rows with), waited for two seconds since the row and the result reach this process on separate posts and cross — with a waiting reply after ten seconds, and a reply saying so when the command printed nothing, since `typedInputReply` has nothing to say for an empty output; `/model` and `/effort` are picks (`$.config.set`, `set-effort`), answered with `typedInputReply`'s text once the settings frame is refreshed; a BTW is `$.model.fork`. A row of the `command` door is a run's by when it arrives and by nothing else: a run claims the first echo row to arrive inside one second of its own answer (`runsCommandRow`), and the `<local-command-stdout>` row directly behind that claimed echo is that run's output, while an echo no run claimed — and the output row behind it — is a command the person typed at their own terminal and belongs to no run. Never by the command the row names: Claude Code runs `/cost` as `/usage` and `/model anthropic/haiku` as `/model haiku`. `origin` separates nothing, measured on live Claude Code 2.1.310 (INFRA-1026): a `/model haiku` this session ran answered at 08:14:06.839 and wrote its caveat (`{"kind":"plugin"}`, `isMeta`) at .844, its echo (`{"kind":"plugin"}`) at .858 and its stdout (`{"kind":"engine"}`) at .888, a `/config` a person typed at a terminal wrote its echo and its stdout with `{"kind":"engine"}` too, and a Dispatch `/cost` whose dialog waited for the person had written no row of its own when that `/config` arrived 36 seconds later. The live view draws nothing of a claimed echo row — the person's own line reaches the page as the message Dispatch stored beside the stream — and nothing of any row Claude Code marks `isMeta`, such as the `<system-reminder>` naming the session that a terminal `/rename` leaves behind its own two rows. |
|
|
127
|
-
| Session identity | `src/session-identity.ts`, `src/session-state.ts`, `src/claude-session.ts` | `SessionIdentity` is the one mutable id holder; handoff file `sessions/<claude-pid>/session-id`; role file `roles/<url-encoded session id>.json` (`readPersistedRole`, `writePersistedRole`; the suffix is what keeps a session id of `.` or `..` inside `roles/`, since `encodeURIComponent` leaves a dot alone), whose record carries the writing process's `client_instance_id` beside the session id and the role, optional so a record written before the field loads unchanged. `CLAUDE_CODE_SESSION_ID`, or explicit `ENVOY_SESSION_ID` for QA. `src/session-state.ts` holds what the state files share and nothing that imports zod: `writeAtomicStateFile`, and `pruneStateDirectory(directory, isStale)`, the one ENOENT-tolerant sweep behind all three of them — handoffs by liveness (a `sessions/<pid>` whose Claude process is gone, anything else there left alone), titles and roles by age (`writtenLongAgo`, `STATE_FILE_MAX_AGE_MS`, thirty days). The role sweep exists because exactly one path removes a role file by hand — a soft `setRole` the listener refuses naming a session that is **not** the one the record is for, which says that session no longer holds the role. A refusal naming the record's own session keeps the file: the role is then held under that id by another process sharing this state directory, and the refused process goes on pressing its claim, refreshing the record's mtime on each heartbeat as a confirmed holder does, so the age sweep never reaches a record a process is still claiming for. The handoff sweep cannot reach either, keyed as it is by session id with no process left to ask about. All three run at startup in `startChannelSession`, each under its own `.catch` that logs and swallows: the heartbeat timer is not armed yet, so housekeeping must never cost a session its channel. |
|
|
128
|
-
| Session title | `src/session-title.ts`, `src/session-state.ts` | The title every registration sends, which Dispatch's Agents page shows in place of the id: `ENVOY_SESSION_TITLE` on one line when it holds a character that shows; else the name the person running the session gave it (`claude -n`, `--name`, `/rename`), alone, with no short id after it, since a name a person chose needs nothing to tell it apart; else a name and the current id's first eight characters (a function of the id, so it follows a `/clear` handoff, and keeps two sessions in one tmux window apart). The chosen name is read, through `readChosenTitleSync`, from the `titles/<url-encoded session id>.txt` file the hooks write under `CLAUDE_PLUGIN_DATA` (keyed by id, like the role file, so `claude --resume <id>` finds it and a `/clear`'s new id starts without one; the suffix keeps a session id of `.` or `..` inside `titles/`, since `encodeURIComponent` leaves a dot alone), and every writer and reader goes through `sessionTitleFile` so the file the hook writes is the file the server reads; that read is synchronous and swallows every error, because a cosmetic title must leave the session on its fallback rather than fail the registration carrying it, and the name goes through the same `oneLine`/`visible` pair the other sources do, so a blank or invisible one falls through to the fallback while a multi-line one is put on one line and kept. The fallback's name is the pane's tmux name (`TMUX` and `TMUX_PANE`, one bounded `tmux -u -S <socket> display-message` at startup, used only when the answering server's pid is the one in `TMUX` and the pane's process is one of this process's ancestors (`isAncestor`); `session:window` when the window's `automatic-rename` is off, else the session, never a window index; for grouped sessions the group's name), else the project directory's name (outside tmux, a refused or missing answer, or a session named only by digits in a window nobody named). That name is worked out once as the server starts; the chosen name is asked for on every call instead, so a rename reaches the page on the session's next prompt plus a heartbeat, with no watcher anywhere. `pruneStaleSessionTitles` drops title files untouched for thirty days at startup, through the sweep the handoff and role prunes share and under the same best-effort guard, since nothing else deletes a file keyed by a session id. The listener replaces the stored title on every registration, and `register` also stamps it (`stampTitle`: `writeSessionTitle` in the session's Dispatch state directory) once per id, where the `dispatch` command reads it for the `session_title` on its writes; with inbound messages or Envoy off, nothing registers, so `runEnvoyChannelServer` stamps it once for the starting id (a `/clear` there leaves the new id unstamped); nothing is stamped when the session starts with Dispatch off or under `ENVOY_SESSION_ID`. |
|
|
129
|
-
| NATS topic consumer | `src/channel-topics.ts` | Dedupe through the shared `createDeliveryDedupe`: a re-send by its `dedupe_key` (never by `event_id` alone, which the listener mints fresh for every send, so a Dispatch Retry would pass as new), and a second copy of one publish arriving on overlapping subscriptions by its `event_id`; surface the envelope's topic, and drain safely at shutdown. The promise the dedupe keeps is stated on `DELIVERY_DUPLICATE_WINDOW_MS` in `packages/contracts`. |
|
|
130
|
-
| Consumer delivery | `src/envoy-channel-server.ts` (`openRelay`, `deliverRelayed`, `renewRelayEpoch`), `src/replay-state.ts` (the `consumer` part of `replay-<session id>.json`), `../envoy-client/src/consumer-delivery.ts`, `../../scripts/e2e/envoy-session-delivery.sh` | The listener's relay of the session's durable consumer ("Overview"): the relay subscription and epoch, each frame's `received`, `done` and `nak`, and the persisted resume point. The repository's `scripts/e2e/envoy-session-delivery.sh` is the live proof under `legion claude-bridge` (`scripts/e2e/README.md`). |
|
|
131
|
-
| Outbound transport | `bin/envoy-send.ts` | `envoy-send` sends through `@legion/envoy-client`'s `createEnvoyClient(...).send`, the transport every other client uses, to the listener and with the bearer `envoySettings` resolves over the envoy.json `envoyConfigPath("command")` chooses. It names its shell's session as `source_session`, so the listener's limit on each session's sending counts it; a refusal prints the listener's own sentence and exits 1, and the message is not sent again. |
|
|
132
|
-
| Send CLI parsing | `src/send-arguments.ts` | Validates destination and message arguments. |
|
|
133
|
-
| Manual `/clear` smoke | `scripts/smoke-clear-rebind.sh` | Real `/clear` against the live listener with the build in `CLAUDE_PLUGIN_DIR` (default: a `--out` build of this tree in the smoke's scratch directory); checks the registry entry moves to the new id without the old direct subject. Sends no prompt to the model; excluded from CI. |
|
|
134
|
-
| Manual session-title smoke | `scripts/smoke-session-title.sh` | Real nats-server, a listener built from this tree, and the `dist/` of its own `--out` build of this tree for both the hook and the channel server: a chosen name registers, a rename replaces it, taking the name away restores the folder-and-short-id fallback, and the `dispatch` command's stamp carries the same name, each read back through the listener's `GET /v1/sessions`; the base revision's committed bundle is the negative control. Claude Code is not installed in an issue pod's image, though it runs there from `bunx --package @anthropic-ai/claude-code@<version> claude`, as `scripts/e2e/envoy-session-delivery.sh` runs it; this smoke writes the two hook payloads to their documented shape instead. Excluded from CI. |
|
|
135
|
-
| NATS stall test | `tests/envoy-channel-stall.test.ts`, `../envoy-client/test/stall-proxy.ts`, `../envoy-client/test/envoy-stack.ts`, `../envoy-client/test/stall-scenario.ts` | Runs only with `LEGION_E2E_ENVOY_STACK=1` (CI's `envoy-session-stall` job), and needs `go` on `PATH` to build natsd and the listener from `packages/envoy`: with the gate set, a missing `go` or a failed build fails it rather than skipping it. The real channel server process registers against that listener (its row shows `plugin` `@sjawhar/claude-envoy` and `plugin_version` `source`), which answers `consumer`, and the proxy freezes its NATS path. Within 60 s the connection nats.js dials in place of the frozen one subscribes the relay subject again (natsd's `/connz`), the session registers a new epoch (its `envoy_sessions` entry), and the message sent during the freeze and one sent after it are each handed over once, neither as a replay: the freeze and what it checks are `runFreezeScenario`, which pi-envoy's stall row runs too. |
|
|
136
|
-
| Legion phase worker on Claude Code | `src/legion-claim.ts`, `src/legion-tool.ts`, `src/legion-inbox.ts`, `src/legion-phase-hook.ts` | Active only when `legion claude-bridge` launched the pane (`LEGION_BOOT_TOKEN_FILE`, `LEGION_DAEMON_URL`, `CLAUDE_CONFIG_DIR` set). The claim waits for the session transcript, then boots through the claim boot `@sjawhar/pi-legion` shares (`bootLegionClaim`, `@legion/pi-shared/legion-claim-core`): registers with the daemon, calls ready, again on every `onRoleRegained`, and claims the issue's Envoy role soft last of all — at this session's first turn or at the bound (`claimFirstTurnBoundMs`, 30 s, `LEGION_CLAIM_FIRST_TURN_BOUND_MS`), whichever comes first, so a message the listener kept for the role arrives inside a turn that is already running rather than ahead of the daemon's task (INFRA-1573). The first turn is the phase hook's `UserPromptSubmit`, this process's only sight of one: the endpoint fires it before its phase gate, for every prompt and whatever claim exists, and the server holds the boot's first-turn signal in one slot (`reportFirstTurn` in `src/envoy-channel-server.ts`), filled the moment `claims/register` answers — so the bridge's seeding `/rename`, which runs before any claim exists, finds it empty and signals nothing, a prompt that arrives while the boot's `claims/ready` is still being retried is counted, and a later prompt runs a step that has already run. The `legion` MCP tool is the phase ops `@sjawhar/pi-legion`'s tool serves too (`@legion/pi-shared/legion-phase-ops`: one schema, one executor, and the shared description template with its `read_record` and `request_backward_move` sentences, naming `mcp__legion__envoy_publish`). `src/legion-phase-hook.ts` is the endless phase reminder's Claude Code host (the section below). With `LEGION_CLAUDE_INBOX` set, deliveries go to the bridge's socket instead of the mod's `$.session.append`. `package.json` `legion.daemonApiVersion` is pinned by `tests/daemon-api-version.test.ts`. |
|
|
137
|
-
| Generated Legion plugin | `legion/`, `scripts/build.ts` | Never edit by hand, and never committed (convention below): `scripts/build.ts` stages pi-legion's skills, converts `packages/pi-legion/agents` (tool names mapped to Claude Code's, `glob`/`grep`/`todo` dropped) and writes the phase reminder's five hook entries (`LEGION_HOOKS` → `legion/hooks/hooks.json`, the section below). `scripts/verify-build.sh` builds the tree twice and fails when the two builds differ, so the release publishes what the source builds to; `tests/dist-fresh.test.ts`, `tests/legion-plugin-fresh.test.ts` and `tests/build-out.test.ts` build fresh and read no file of the package. `tests/legion-pane-mcp.test.ts` runs a Legion pane's server end to end against stand-ins. |
|
|
138
|
-
| The phase reminder on the real Claude Code binary | `tests/legion-phase-hook-claude.test.ts` | The one check that Claude Code arms the generated `legion/hooks/hooks.json` entries at all: it runs the real binary under Legion's own agent command (`claudelaunch.Argv`, `--debug` added for the log it reads), with a fresh `scripts/build.ts --out` build of this tree — its generated `legion/` tree, and its `dist/envoy-channel.js` as the `legion` MCP server — against stand-ins for the Anthropic API, the daemon, the listener and NATS. `LEGION_TEST_CLAUDE` names the binary — in a worker pod, the one installed from `packages/daemon/docker/claude-code/package-lock.json`, at `node_modules/@anthropic-ai/claude-code-linux-x64/claude` (the `node_modules/.bin/claude` symlink is a `.exe` shim that does not exec on Linux): `cd packages/claude-envoy && LEGION_TEST_CLAUDE=<that path> bun test tests/legion-phase-hook-claude.test.ts`. A run without it skips the file, and nothing in CI installs the binary. |
|
|
25
|
+
- `scripts/build-inputs.txt` and `$CLAUDE_ENVOY_VERSION_ARGS` list the same paths.
|
|
26
|
+
A change that makes `scripts/build.ts` or `scripts/verify-build.sh` read a new file adds it to both.
|
|
139
27
|
|
|
140
|
-
|
|
28
|
+
- The build refuses a Bun other than `.bun-version`'s; call the pinned binary by path when a version manager's default differs.
|
|
141
29
|
|
|
142
|
-
|
|
143
|
-
since the daemon's assignment — is reminded at the end of every turn, for as long as the phase
|
|
144
|
-
stays open. The machine is not this package's: `@legion/pi-shared` holds it once for both
|
|
145
|
-
harnesses (`phase-stall.ts`, the states and the count; `phase-reminder.ts`, the runner that
|
|
146
|
-
delivers each reminder, tells the architect and reads the daemon's record; `stall-limits.ts`, the
|
|
147
|
-
four numbers), `@sjawhar/pi-legion` drives it from Oh My Pi's session hooks
|
|
148
|
-
(`packages/pi-legion/AGENTS.md`), and `src/legion-phase-hook.ts` drives it here, from Claude
|
|
149
|
-
Code's own hooks. Nothing of the machine is re-decided in this package. `legion claude-bridge` is
|
|
150
|
-
transport and holds no copy of it (`packages/daemon/internal/claudebridge`).
|
|
30
|
+
- `.omp-plugin/plugin.json`'s empty `mcpServers` keeps Oh My Pi from starting the server, and `.mcp.json`'s `env` passes `CLAUDE_PROJECT_DIR` alone, since Claude Code substitutes an unset `${VAR}` literally.
|
|
151
31
|
|
|
152
|
-
|
|
153
|
-
`legion/hooks/hooks.json`, each an `mcp_tool` hook on the server `legion` — the pane's own MCP
|
|
154
|
-
server, which `--mcp-config` registers under that bare name
|
|
155
|
-
(`packages/daemon/internal/claudelaunch`) — calling the tool `legion_phase_hook` that
|
|
156
|
-
`src/envoy-channel-server.ts` registers from `phaseHookToolDefinition()`. Claude Code substitutes
|
|
157
|
-
each `${…}` as a string, which the endpoint parses. `Stop` (30 s, since its answer waits on the
|
|
158
|
-
runner's record check, which bounds its own daemon read at 5 s) carries `${last_assistant_message}`
|
|
159
|
-
and `${stop_hook_active}`; `StopFailure` (10 s) the last message; `PostToolUse` and
|
|
160
|
-
`PostToolUseFailure` (10 s) `${tool_name}` and `${agent_id}`; `UserPromptSubmit` (10 s)
|
|
161
|
-
`${prompt}`. They belong to the generated `legion/` plugin alone, never to `hooks/hooks.json`:
|
|
162
|
-
this package is also installed as a plain Claude Code plugin, where no `legion` server exists and
|
|
163
|
-
every entry would be a hook error on every turn. A Legion pane loads both plugin directories, so
|
|
164
|
-
its worker gets them.
|
|
32
|
+
## Rules
|
|
165
33
|
|
|
166
|
-
|
|
167
|
-
every hook with `{}` for a session that holds no claim yet (the bridge's seeding `/rename` turn)
|
|
168
|
-
or whose role is `architect` — the same gate `phaseWorkerSession` applies in pi-legion. `Stop`
|
|
169
|
-
settles the machine: the first reminder of a run comes back as
|
|
170
|
-
`{"decision":"block","reason":<the reminder>}`, which Claude Code turns into one more turn of the
|
|
171
|
-
same session, and it is the only one of that run; every later one is written into the session over
|
|
172
|
-
the bridge's inbox from a timer, because a line written while a turn runs is appended to that turn
|
|
173
|
-
and the run would never settle for the daemon. `StopFailure` runs instead of `Stop` when the turn
|
|
174
|
-
ended on an API error ("Hooks reference", code.claude.com/docs/en/hooks), and its
|
|
175
|
-
`${last_assistant_message}` is then the error text itself, not what the worker said: that is the
|
|
176
|
-
provider refusing the turn, so the machine takes it as `refused`: it earns no continuation, since
|
|
177
|
-
continuing into another turn at once would only buy another refusal, which is what left
|
|
178
|
-
dispatch://INFRA-264's implementer reminded for ever.
|
|
179
|
-
It does arm one timer, because the task that refused turn carried ended with it and nothing else
|
|
180
|
-
would wake this worker, so one transient refusal would leave the issue idle.
|
|
181
|
-
Claude Code ignores whatever this hook returns, which now costs nothing. What ends a session the provider keeps refusing is the daemon: the bridge reports each
|
|
182
|
-
turn's outcome to `POST /legion/v1/claims/turn-outcome` and the daemon fails the claim once the
|
|
183
|
-
trailing run of refusals reaches `launch_failure_limit`, and the runner's record check then drops
|
|
184
|
-
every reminder, since a failed claim is replaced by a retry in a session of its own.
|
|
185
|
-
`PostToolUse` and `PostToolUseFailure` are the worker
|
|
186
|
-
working, which puts the count back to zero; a non-empty `${agent_id}` is a subagent's
|
|
187
|
-
call and is ignored. `UserPromptSubmit` is this server's only sight of an inbound turn — the
|
|
188
|
-
daemon's task reaches Claude Code's stdin from the bridge, never this process — so it declares the
|
|
189
|
-
turn, drops the armed timer, and classifies the prompt: the reminder it last wrote is itself and
|
|
190
|
-
changes nothing, a line this server wrote (an Envoy delivery, the recreated-workspace notice) is
|
|
191
|
-
an inbound event, and anything else is an assignment. The tool is visible to the model, and a call
|
|
192
|
-
it does not recognise is answered with `PHASE_HOOK_REFUSAL` and records nothing, so the model
|
|
193
|
-
cannot zero its own count.
|
|
34
|
+
- `renderInbound` (`@legion/envoy-client/delivery`) is the only inbound renderer, and no receipt is published: a reply inbox on a frame belongs to the JetStream acknowledgement.
|
|
194
35
|
|
|
195
|
-
|
|
196
|
-
`request_backward_move`, are calls of the same MCP server, and its CallTool handler tells the
|
|
197
|
-
endpoint (`phaseClosed`) once one of the two returned without throwing — the two operations
|
|
198
|
-
`createLegionTool` closes the Oh My Pi host's phase on. Until that lands, a completed worker's
|
|
199
|
-
record still says `open`, and only the runner's record check, which fails open when the daemon
|
|
200
|
-
does not answer, stands between it and a reminder telling it to complete again.
|
|
36
|
+
- Subscribe the relay subject (`notifications.envoy.deliver.<session_id>`) before any registration under that id, and read the id from the shared `SessionIdentity` at each use: a `/clear` moves the session to a new id.
|
|
201
37
|
|
|
202
|
-
|
|
203
|
-
(`updateAnswered`) once the `legion` tool's `ready_for_update` returned without throwing
|
|
204
|
-
(INFRA-484). It closes no phase — answering is not completing — and moves the machine to
|
|
205
|
-
`awaiting-update`, the wait the daemon ends: the `Stop` of the turn the worker answered in blocks
|
|
206
|
-
nothing, so that turn ends and the daemon sees it end. The daemon replaces the pod once every
|
|
207
|
-
role in it has answered and no turn runs, or at the round's bound.
|
|
208
|
-
A blocked `Stop` would instead continue that turn, and the work it did
|
|
209
|
-
would go with the pod. Nothing is written into that wait and no timer is armed in it, because the
|
|
210
|
-
daemon is what wakes the worker: a round, once opened, ends only by replacing its pod or because
|
|
211
|
-
that pod is gone, so the process is replaced and the task the round held behind it reaches the
|
|
212
|
-
worker on the new pod, in the same session. The record holds the wait as the plain `waiting` a
|
|
213
|
-
WAITING reply buys (`recordedPhaseStall`): only a relaunched process reads a record, and that
|
|
214
|
-
relaunch is the round over.
|
|
38
|
+
- Hand the relay the nats.js `Msg` itself: its `data`, `headers` and `reply` are prototype getters that an object spread drops.
|
|
215
39
|
|
|
216
|
-
|
|
217
|
-
`<CLAUDE_CONFIG_DIR>/legion-phase-stall-<session id>.json` (`phaseStallFile`), written whole
|
|
218
|
-
through a temporary file in the same directory renamed into place, before the hook answers. It
|
|
219
|
-
carries the shared entry — `state` (`closed`, `open`, `waiting`), `count`, `reported`, the
|
|
220
|
-
architect notice's `reportKey` and `lastMessage`, the head of what the worker last said, which the
|
|
221
|
-
notice quotes after a relaunch — and one key only this host keeps, `recreatedNoticeSent`. A
|
|
222
|
-
missing file is a fresh session; an unreadable one, one that is not JSON, or one holding no state
|
|
223
|
-
this build knows is one `warn` and a fresh start. A file the build now in the pods wrote holds
|
|
224
|
-
`{"state":"quiet"}` or `{"state":"text-call"}`, which read as an open phase with no reminder yet,
|
|
225
|
-
so a session carried across the cutover is reminded rather than left alone. Claude Code may
|
|
226
|
-
restart this server inside the same `claude` process, which is why the count is on disk and not
|
|
227
|
-
in memory alone, and the only reason `recreatedNoticeSent` is: a launch whose
|
|
228
|
-
`LEGION_WORKSPACE_RECREATED` is not `true` clears it, so the next launch that recreates the
|
|
229
|
-
workspace is told again.
|
|
40
|
+
- Every registry write goes through the session's one `serialized` chain, and nothing in it waits without a bound, since shutdown's deregistration queues behind it.
|
|
230
41
|
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
later reminder waits), `LEGION_STALL_WAITING_MS` (900000, what a reply starting WAITING buys),
|
|
234
|
-
`LEGION_STALL_RESUME_MS` (120000, the reminder for a worker relaunched into an open phase) and
|
|
235
|
-
`LEGION_STALL_ARCHITECT_AFTER` (3 unanswered reminders before the architect is told over Envoy,
|
|
236
|
-
through this server's own listener client). A worker whose launcher recreated its workspace is
|
|
237
|
-
told so over the same inbox, once per launch, as an Oh My Pi worker is
|
|
238
|
-
(`LEGION_WORKSPACE_RECREATED`, `@legion/pi-shared/workspace-recreated`). `tests/legion-phase-hook.test.ts`
|
|
239
|
-
drives the endpoint over a real state file, and `tests/legion-pane-mcp.test.ts` proves the tool is
|
|
240
|
-
on a Legion pane's server. Both drive this package alone: that Claude Code arms these hook entries
|
|
241
|
-
at all, reaches the server under the bare name `legion`, turns the `Stop` block into one more turn
|
|
242
|
-
of the same session, and fires `PostToolUse` for the model's own call and not for the hook's own
|
|
243
|
-
MCP call, is proved only on the real binary, by `tests/legion-phase-hook-claude.test.ts` (the row
|
|
244
|
-
above says how to run it).
|
|
42
|
+
- Register the capabilities `sessionCapabilities` computes, never a constant.
|
|
43
|
+
The role record rules are `roleHeldBy` and `mayActOnRoleRecord` in `@legion/envoy-client/transport`, which pi-envoy shares.
|
|
245
44
|
|
|
246
|
-
|
|
45
|
+
- No Dispatch call goes through the MCP server, and no permission relay is carried: no reply path here authenticates its sender.
|
|
247
46
|
|
|
248
|
-
|
|
249
|
-
adapter-specific renderer or emit raw envelope bytes.
|
|
250
|
-
- A frame's identity fields are `event_id`, `dedupe_key`, `source`, `source_event_id` and
|
|
251
|
-
`topic` (`deliveryIdentity` in `src/channel-topics.ts`), each parsed on its own and kept
|
|
252
|
-
only when valid, so one field the rule refuses still leaves its sibling able to recognise a
|
|
253
|
-
repeat.
|
|
254
|
-
Nothing else of an envelope leaves the renderer: what reaches the session is the rendered
|
|
255
|
-
text, and, where a line carries more than text (a person's pictures), Claude Code's own
|
|
256
|
-
content blocks for it.
|
|
257
|
-
- Subscribe NATS before registering the self-subscribed session route — on startup, on a session-id
|
|
258
|
-
handoff (new direct subject first, then deregister the old id, drop the old subject, register,
|
|
259
|
-
move the role by soft claim; a handoff that fails before the id switch drops the new subject
|
|
260
|
-
again), and when rebuilding the interests a resumed id already registered. Subscribe the current
|
|
261
|
-
id's relay subject (`notifications.envoy.deliver.<session_id>`) before any registration under
|
|
262
|
-
that id, since that registration asks for consumer delivery. The handoff's
|
|
263
|
-
deregistration carries this process's client instance id, so the listener removes that entry
|
|
264
|
-
only while it is still this instance's: a process that resumed the old id and registered it
|
|
265
|
-
keeps its registration, and the soft claim that follows is then weighed against a predecessor
|
|
266
|
-
that is live, rather than against one this handoff cleared.
|
|
267
|
-
A handoff is adopted within 250 ms of the SessionStart hook writing the handoff file: the server
|
|
268
|
-
polls the file by path (`fs.watchFile`), because a directory watch reports only the hook's
|
|
269
|
-
temporary file, not the rename onto `session-id`. The heartbeat is the fallback. On shutdown
|
|
270
|
-
(stdin end, SIGTERM, SIGINT, SIGHUP) drain NATS, deregister the session, close the transport, and
|
|
271
|
-
let the stdio process exit.
|
|
272
|
-
The relay subscription also answers the listener's connection probe, through the shared
|
|
273
|
-
`receive` in `@legion/envoy-client/consumer-delivery` (the probe's format is in
|
|
274
|
-
`packages/envoy/AGENTS.md`, "Session consumers"), and the server holds no subscription for it
|
|
275
|
-
beyond the relay subject: while that subject is open a send reads `connected`, and once the
|
|
276
|
-
connection closes, or a `/clear` handoff moves the relay to the new id and drops the old
|
|
277
|
-
subject, nothing answers and a send to the id left behind reads `stopped`.
|
|
278
|
-
- The listener merges each registration's topics into the entry and never removes one. So every
|
|
279
|
-
registry write (register, unsubscribe, deregister, the handoff) goes through the session's one
|
|
280
|
-
`serialized` chain, a registration reads the id and topics when it runs, and a topic leaves the
|
|
281
|
-
followed topic list (`unfollow` removes it before its first await) before the listener is
|
|
282
|
-
told or the next registration is sent. A human Dispatch subscription removal is repeated to the
|
|
283
|
-
listener through the same chain. Nothing inside the chain may wait without a bound (the
|
|
284
|
-
handoff's NATS flush has a timeout), because shutdown's deregistration queues behind it.
|
|
285
|
-
- Publish no receipt. No session answers one any more: the listener forwards a role message to the
|
|
286
|
-
holder's agent subject and waits only for the stream's acknowledgement that it stored it, and
|
|
287
|
-
the holder's own consumer relays that stored copy, which the relay frame's `done` answers. A
|
|
288
|
-
reply inbox on a frame belongs to the server's JetStream acknowledgement; an empty receipt there
|
|
289
|
-
makes a publisher report `invalid jetstream publish response` for an event that was delivered.
|
|
290
|
-
- Every capture of the session id goes through the shared `SessionIdentity` (`identity.id` at the
|
|
291
|
-
moment of use), never a copied string: after a `/clear` handoff the model posts to Dispatch,
|
|
292
|
-
registers, unfollows, remembers roles, and deregisters under the current id.
|
|
293
|
-
- Hand the relay the nats.js `Msg` itself (`decodeRelayFrame` in
|
|
294
|
-
`@legion/envoy-client/consumer-delivery` reads its `data`, `headers` and `reply`): a `Msg` exposes
|
|
295
|
-
them through prototype getters that an object spread silently drops. The relay decodes `data`
|
|
296
|
-
once into the frame's text; downstream code reads that, never re-decodes.
|
|
297
|
-
- Register what the session can take now, never a constant: `sessionCapabilities`
|
|
298
|
-
(`src/envoy-channel-server.ts`) reads whether this is a pane and whether the mod is connected,
|
|
299
|
-
and `ChannelSession.capabilitiesChanged()` registers again when that changes. Dispatch refuses
|
|
300
|
-
a targeted delivery in a mode the session does
|
|
301
|
-
not advertise, and a message with no command goes in the mode the addressed sessions take
|
|
302
|
-
(`plainDelivery`), as a broadcast does (`broadcastDelivery`).
|
|
303
|
-
A relayed frame's `done` waits for the write: the mod's write into the conversation in a
|
|
304
|
-
terminal session, and the bridge's inbox answer in a Legion pane, which comes once Claude Code
|
|
305
|
-
re-emits the delivery (`--replay-user-messages`). Neither says the model read the message —
|
|
306
|
-
nothing in the mod protocol does — only that the session holds it.
|
|
307
|
-
- Write every message into a terminal session through the one call `hooks/mod.ts` serves,
|
|
308
|
-
whether a person sent it or Envoy delivered it: `session.message` hands the mod the message,
|
|
309
|
-
and the mod decides what it becomes (`hooks/mod-writer.ts`, which holds these rules while
|
|
310
|
-
`hooks/mod.ts` holds the socket, the event queue and the hooks) — the prompt of a new turn
|
|
311
|
-
while nothing is running
|
|
312
|
-
(`$.prompt.submit`), a row of the turn running (`$.session.append`), and one prompt of its own
|
|
313
|
-
quoting such a row in full when the turn ends without a request having read it
|
|
314
|
-
(`unreadRowPrompt`, `hooks/mod-protocol.ts`). The mod decides because the mod is the one
|
|
315
|
-
process where the turn's events and this plugin's writes arrive in one order; three review
|
|
316
|
-
rounds found a race in deciding it in the server, each from two posts whose order was not the
|
|
317
|
-
order the session saw (INFRA-1026 review, rounds nine to eleven). An appended row starts
|
|
318
|
-
nothing, so a card appended to an idle session would wait for the person to type and one
|
|
319
|
-
appended after a turn's last request is never read at all. A person's message goes with
|
|
320
|
-
`asUser`, so Claude Code frames it as their own words; a card goes without it, so Claude Code
|
|
321
|
-
frames it as the plugin speaking, since nobody at the session typed it.
|
|
322
|
-
- Put a card in front of the model once. While the session is idle the card is the prompt
|
|
323
|
-
itself and nothing is stored for it — no `$.session.append`, and no second prompt quoting
|
|
324
|
-
one — since a row beside a prompt that quotes it is the same message twice (INFRA-1026,
|
|
325
|
-
handoff v6: rows 8 and 10 of session 225642d4 carried the one card, and two subtests of the
|
|
326
|
-
`envoy-session-stall` lane read it twice). A card that arrives during a turn keeps the row
|
|
327
|
-
and the unread-row prompt behind it.
|
|
328
|
-
- Answer a card's Envoy frame on the write the mod reports - a row appended, or a prompt the
|
|
329
|
-
engine took - and on nothing else: that answer is the proof the session has the message.
|
|
330
|
-
Nothing else is: a `$.prompt.submit` can wait for a
|
|
331
|
-
turn already running before the engine takes it, and a request handed to a poll is a write
|
|
332
|
-
into a socket buffer that a SIGSTOPped process never reads (INFRA-1026 review, round eleven,
|
|
333
|
-
repro `R-A`). `show` waits up to `SHOW_TIMEOUT_MS` and rejects without an answer, which leaves
|
|
334
|
-
the frame unanswered and has the listener send the card again. Driven live (INFRA-1026, k7's
|
|
335
|
-
second clause — Claude Code SIGSTOPped, an Envoy message sent to it, then SIGKILL and `claude
|
|
336
|
-
--resume <id>`), a branch that answered on the submit held that message zero times in the
|
|
337
|
-
resumed conversation. A person's message is the same, except that a prompt the session
|
|
338
|
-
*dropped* reaches them as a reply on Dispatch (`failed`): their own words were refused, and
|
|
339
|
-
Dispatch is where they are waiting.
|
|
340
|
-
- Make the mod's write idempotent by the Envoy event id, since the server is at-least-once.
|
|
341
|
-
Every request for a frame of Envoy's carries its `eventId` — a card and a person's own
|
|
342
|
-
message alike (`show` and `deliver`, `src/mod-session.ts`), since a person's message whose
|
|
343
|
-
answer is late is sent again and arrives as a card, the accept having spent its Dispatch
|
|
344
|
-
attempt, so the two writes are one write or the model reads their words twice. Before it
|
|
345
|
-
appends or submits, the mod looks that id up in `$.store` and answers a copy it already
|
|
346
|
-
wrote with the recorded write, writing nothing (`writeOnce`, `hooks/mod-writer.ts`). Every
|
|
347
|
-
write is recorded, a prompt included, which has no row to record: a prompt the engine took is
|
|
348
|
-
in the session, and answered as a drop instead it was recorded nowhere, so its resend
|
|
349
|
-
submitted the message a second time and a person's own message had Dispatch tell them their
|
|
350
|
-
session dropped a prompt it took (INFRA-1026 review).
|
|
351
|
-
The store has no compare-and-set — two `get`s of an unset key
|
|
352
|
-
both answered undefined, 0 ms and 2 s apart, in one session and across two
|
|
353
|
-
(`/legion/scratch/tmp/infra-1026-store`) — so the mod chains the look-up and the write per
|
|
354
|
-
event id, which holds inside the one process, and the store covers what crosses a restart:
|
|
355
|
-
`set` had written the file before it resolved, and a later session on the same configuration
|
|
356
|
-
directory read it back after a `kill -9` taken at that moment. Keep the record capped and
|
|
357
|
-
evicted (`CARD_RECORD_MAX`, `keys()` in insertion order): every call parses the whole file,
|
|
358
|
-
so at 3.9 MiB a `get` cost 7–20 ms and a `set` 44 ms against about 1 ms on an empty store, and
|
|
359
|
-
`set` refuses past 4 MiB outright. Two things can still show a card twice: this process
|
|
360
|
-
ending between the write and the record, the crash case
|
|
361
|
-
`docs/site/src/content/docs/dispatch/envoy.md` states, and a store that refuses the `set`,
|
|
362
|
-
which leaves the write standing with no record of it (`remember`, where a refusal costs
|
|
363
|
-
nothing a session could report to).
|
|
364
|
-
- Nothing of a subagent is the session's turn. Every hook whose event carries `agentId`
|
|
365
|
-
returns `next(e)` first when it is set and does nothing else (`ofSubagent`, `hooks/mod.ts`):
|
|
366
|
-
the three turn hooks and `session.append`, which is the registration that keeps a subagent's
|
|
367
|
-
rows out of the live view. Measured on 2.1.310
|
|
368
|
-
(`/legion/scratch/tmp/infra-1026-turn`), a subagent's `turn.start`, `turn.step`,
|
|
369
|
-
`turn.complete`, `tool.call`, `tool.check`, `prompt.attachment`, `session.receive` and
|
|
370
|
-
`session.append` on every door carry `agentId` while the main loop's carry no such key at
|
|
371
|
-
all, a foreground subagent's whole turn opens and closes inside the main turn between two of
|
|
372
|
-
its steps, and a background subagent's turn can still be open after the main turn completed.
|
|
373
|
-
Counted as the main turn's, that turn's `turn.complete` cleared the turn a message joins, its
|
|
374
|
-
steps raised the request count a row's unread check reads, and its rows and steps reached the
|
|
375
|
-
live view as the main conversation's, which the spec puts out of scope ("their work shows as
|
|
376
|
-
the parent's tool call"). The rule is the key and never a turn this mod watched start: when
|
|
377
|
-
the plugin itself spawns a subagent, that loop's `turn.start` and `turn.step` never reach the
|
|
378
|
-
spawning plugin and only its `turn.complete` does.
|
|
379
|
-
- Report from the mod every row the mod itself appends: Claude Code does not re-enter a mod's
|
|
380
|
-
own `session.append` hook for such a row (measured in the issue's spike —
|
|
381
|
-
`logs/mod3-q1q3q5.jsonl:36,64`, two calls whose uuids no hook ever carried), so a card
|
|
382
|
-
delivered during a turn reached no mapper and the live view drew nothing for it. `hooks/mod.ts`
|
|
383
|
-
sends an `append` event built from what `$.session.append` answered (`{message, uuid}`), by
|
|
384
|
-
the `note` door under a `plugin` origin naming this plugin (`MOD_PLUGIN_NAME`), and the
|
|
385
|
-
server ignores an `append` event whose row id it has already read
|
|
386
|
-
(`AGENT_STREAM_SEEN_ROWS_MAX`, `src/agent-stream-runner.ts`) in case a host fires the hook as
|
|
387
|
-
well.
|
|
388
|
-
- Claim every row of the conversation this session wrote by its uuid, never by what the row says
|
|
389
|
-
(`src/mod-session.ts`, `appendedRow`, `runsUnreadPrompt`, `runsCommandRow`). Draw a row
|
|
390
|
-
Claude Code marks `isMeta` only where this session appended it: the engine marks every row
|
|
391
|
-
`$.session.append` writes, so a card delivered during a turn — which is that row and nothing
|
|
392
|
-
else — is the one `isMeta` row the page must show, while a terminal `/rename`'s
|
|
393
|
-
`<system-reminder>` and the `<local-command-caveat>` row of a run stay model-facing and are
|
|
394
|
-
drawn nothing for. The claim rides on the stamp the mod puts on the row's own event
|
|
395
|
-
(`ModEvent`'s `wrote`: `message` for the row a message became, `pointer` for the prompt at
|
|
396
|
-
unread rows), never on the answer of the call that wrote the row — the two cross, since the
|
|
397
|
-
mod holds an event behind a post already in flight while a result goes out on a fetch of its
|
|
398
|
-
own, and a claim made from the answer landed after the view had read the row and dropped it
|
|
399
|
-
(INFRA-1026 k2, measured live on 2.1.310). The server hands the session every event before the
|
|
400
|
-
view records it (`src/envoy-channel-server.ts`), so the stamp is in place for the row being
|
|
401
|
-
drawn. The stamp is the whole signal: another installed mod's appends reach this mod's hook
|
|
402
|
-
under a `plugin` origin of their own, so a rule on the origin drew another mod's context as
|
|
403
|
-
the person's words. Of the two prompts this plugin submits without `asUser`, the card an idle
|
|
404
|
-
session took is drawn, because it is the card, and the prompt at unread rows is not, because
|
|
405
|
-
it quotes rows the view has already drawn — told apart by the stamp, since a card may quote
|
|
406
|
-
that prompt's own words.
|
|
407
|
-
- Keep the mod's socket where only its own user can create anything: `resolveModSocketPath`
|
|
408
|
-
(`hooks/mod-protocol.ts`) puts `claude-envoy/ce-<hash of the session id>.sock` under
|
|
409
|
-
`XDG_RUNTIME_DIR`, else Claude Code's own configuration directory (`CLAUDE_CONFIG_DIR`, else
|
|
410
|
-
`$HOME/.claude`), the way ssh's `ControlPath` and gpg-agent place theirs. `TMPDIR` and `/tmp`
|
|
411
|
-
are no bases: no co-user can get into a home or a run directory to bind the path first, which
|
|
412
|
-
is why the mod needs no owner check — and could make none, since `$.fs.stat` answers
|
|
413
|
-
`{kind, size, mtimeMs, isLink, realPath?}` and carries neither owner nor mode. `startModLink`
|
|
414
|
-
still refuses a directory that is not this user's own `0700` one rather than binding in it. A
|
|
415
|
-
session with no base of its own gets no link, the reason on stderr. The whole path has 100
|
|
416
|
-
bytes (Claude Code's bound on `HttpInit.socketPath`), which is why the name is the id's hash:
|
|
417
|
-
a macOS `/Users/<name>/.claude` makes 62 bytes and a Legion pane's `CLAUDE_CONFIG_DIR` 78,
|
|
418
|
-
while the id spelled out passed 100 on a macOS temp directory. A path past the bound is
|
|
419
|
-
refused with that reason, never served out of a shared base.
|
|
420
|
-
- One link serves one mod: the first instance to name itself in `MOD_INSTANCE_HEADER` holds it
|
|
421
|
-
and every other post is refused with `MOD_STATUS_TAKEN`, which stops that mod. Two Claude Code
|
|
422
|
-
processes can boot on one session id (`claude -c`, `claude --resume <id>` in a second
|
|
423
|
-
terminal), and the one that got there first owns the session's live view and its Send.
|
|
424
|
-
- Preserve the held role at `${CLAUDE_PLUGIN_DATA}/roles/<session-id>.json` (keyed by session id so
|
|
425
|
-
`claude --resume <id>` finds it), with this process's client instance id in the record beside
|
|
426
|
-
the session id and the role, since two `claude` processes of one user read one state directory
|
|
427
|
-
and a record keyed by session id alone names no writer; soft-reclaim it with its
|
|
428
|
-
`previous_session_id` after registration, then reassert it on each registration heartbeat. A
|
|
429
|
-
record another process wrote is pressed only while this process holds no role, and a record
|
|
430
|
-
from a build before the writer was named is pressed as it always was. The listener grants such
|
|
431
|
-
a claim only when that predecessor has no live registry entry, when its live entry carries this
|
|
432
|
-
process's own client instance id, or when either side carries no instance id. A predecessor
|
|
433
|
-
still live under another client instance keeps the role, and the claim is refused naming it.
|
|
434
|
-
That refusal keeps the predecessor's role file, because the record belongs to the live holder.
|
|
435
|
-
A claim of a role already held under this session's own id is decided on the standing claim:
|
|
436
|
-
granted to the process that claim names, granted once nobody renewed it inside the listener's
|
|
437
|
-
live window, and otherwise refused naming this very session. The re-assertion confirms the
|
|
438
|
-
role only when the lookup names this session *and* this process and reports no hand-back,
|
|
439
|
-
since a claim another process made under this id is not this one's to renew and a claim the
|
|
440
|
-
listener marked handed back is nobody's to renew; a refusal naming this session keeps the role,
|
|
441
|
-
refreshes the record's mtime and asks again on the next heartbeat, and only a refusal naming a
|
|
442
|
-
different session ends the role and removes the file. The restore keeps asking on the same
|
|
443
|
-
rule: a refusal naming this session's own id leaves the restore pending on `roleTransferFrom`,
|
|
444
|
-
which every heartbeat presses again until the claim is granted, since one claim at boot and no
|
|
445
|
-
more would cost a `--resume` or a channel-server restart inside the live window its role for
|
|
446
|
-
the life of the process. The Legion pane's claim waits the same refusal out rather than
|
|
447
|
-
stopping the pane, asking every `ROLE_CLAIM_RETRY_MS` (10 s) for the live window and one
|
|
448
|
-
attempt more. That wait runs after the pane's `claims/ready`, since the role is claimed last,
|
|
449
|
-
at the session's first turn or at the bound, so the daemon's registration deadline
|
|
450
|
-
(`worker_boot_timeout_seconds` × `worker_boot_registration_deadline_intervals` from the
|
|
451
|
-
registration) is already met when the first attempt goes out and nothing outside the pane is
|
|
452
|
-
counting the wait; what bounds it is the listener's own live window, after which the standing
|
|
453
|
-
claim of the process this pane replaced is granted to nobody. It throws only on a refusal
|
|
454
|
-
naming a different session. The
|
|
455
|
-
lookup's rule and the record's are the client contract's own,
|
|
456
|
-
`roleHeldBy` and `mayActOnRoleRecord` in `@legion/envoy-client/transport`, which
|
|
457
|
-
`packages/pi-envoy` calls too and which read an empty instance id as none, the lookup leaving
|
|
458
|
-
`client_instance_id` out where the claim names no process. Every claim and every topic
|
|
459
|
-
hand-back states this process's instance too, so a release frees only the role claims this
|
|
460
|
-
process holds, and a release the holder's own renewal beat under each of the route's three
|
|
461
|
-
conditional deletes fails rather than reporting one it did not make. The registration that
|
|
462
|
-
renews those claims renews every one of them whatever topics it carries, and renews no claim
|
|
463
|
-
the listener has marked handed back: what says a role was given up is the mark a hand-back
|
|
464
|
-
leaves on a claim it could not free. This process writes no such mark — it gives a role up by
|
|
465
|
-
deregistering the session, not by releasing the lane — but a client built before a release
|
|
466
|
-
stated its process can leave one on this session's claim, and the re-assertion above claims
|
|
467
|
-
the role back on the next heartbeat, its grant a fresh record with no mark.
|
|
468
|
-
The handoff directory `sessions/<claude-pid>/` is pruned at startup when its pid is gone —
|
|
469
|
-
never deleted on shutdown, because Claude Code restarts the server inside the same `claude`
|
|
470
|
-
process — and the two id-keyed directories, `roles/` and `titles/`, are pruned there too at
|
|
471
|
-
thirty days, since a session that ends while it still holds its role deletes neither file
|
|
472
|
-
itself.
|
|
473
|
-
- Shared logic remains shared: use `sessionDispatchSettings`, `formatOpenAsksSummary`,
|
|
474
|
-
`postDeliveryReply`, `mergeInterestSources`, and `sendConfirmationText`. No Dispatch call goes
|
|
475
|
-
through the MCP server; the `dispatch` command runs the shared executor, and a `dispatch_*` tool
|
|
476
|
-
name is an unknown tool here. Rejected targeted frames answer Dispatch with
|
|
477
|
-
`Invalid Dispatch targeted delivery frame`; malformed ones without a reply address are logged and
|
|
478
|
-
dropped — never shown to the model.
|
|
479
|
-
- `envoy_inbox` is bounded to 50 metadata-only entries. Keep full payloads in neither the tool
|
|
480
|
-
output nor plugin data.
|
|
481
|
-
- Deployment needs nothing enabled on the machine: Claude Code 2.1.310 or newer loads the mod
|
|
482
|
-
from the plugin's `hooks.json`.
|
|
483
|
-
A session takes no message and shows no conversation when its Claude Code is older, when it
|
|
484
|
-
starts with `--bare` or `--safe-mode`, or when settings turn mods off (`disableAllHooks`, or
|
|
485
|
-
`allowManagedModsOnly` or `allowManagedHooksOnly` in managed settings).
|
|
486
|
-
`claude -p` has no interactive plan approval, multiple-choice, or consent surfaces; workers
|
|
487
|
-
need pre-approved configuration.
|
|
488
|
-
- Nothing commits `dist/` or `legion/`, and `.gitignore` names both. `release.yaml`'s
|
|
489
|
-
`claude_envoy_build` builds them after each merge that bumps this plugin's version, packs them
|
|
490
|
-
into the tarball with the rest of the package, and the `publish` job uploads that tarball to
|
|
491
|
-
npm as `@sjawhar/claude-envoy`; the marketplace entry names that package and bounds it with the
|
|
492
|
-
range `>=1.0.0` on its `npm` source, which leaves out the 0.0.0 placeholder, so an install or a
|
|
493
|
-
`claude plugin update` takes the newest release.
|
|
494
|
-
A merge whose commits touch none of `$CLAUDE_ENVOY_VERSION_ARGS`' paths releases nothing and
|
|
495
|
-
leaves the newest release standing.
|
|
496
|
-
`tests/build-inputs.test.ts`, in the required test job, fails when the bundles' module graph (with
|
|
497
|
-
each reached package's manifest, tsconfig and license files, and the lockfile, root manifest and
|
|
498
|
-
patches `bun install` applies) or the skills and agents `buildLegionPlugin` reads reach a file
|
|
499
|
-
`scripts/build-inputs.txt` does not match. The rest of the list is listed by hand, as its header
|
|
500
|
-
names it (`.bun-version`, `bunfig.toml`, the `.gitattributes` files, the scripts
|
|
501
|
-
`build.ts` imports or runs, and the files `verify-build.sh` reads): a pull
|
|
502
|
-
request that makes `build.ts` or `verify-build.sh` read a new file adds it to the
|
|
503
|
-
list itself, and a path added or dropped there is owed the same change in
|
|
504
|
-
`$CLAUDE_ENVOY_VERSION_ARGS`.
|
|
505
|
-
The hand-written plugin files (`hooks/hooks.json`, `.mcp.json`, `bin/`,
|
|
506
|
-
`.claude-plugin/`) are packed from the same tree as the build beside them, so a change that
|
|
507
|
-
makes one of them name a new or renamed bundle ships with that bundle in one release.
|
|
508
|
-
To run the plugin from a tree, build it with `bun scripts/build.ts --out <dir>` into a directory
|
|
509
|
-
outside the repository. A reviewer asks for any change under the two directories to be dropped.
|
|
510
|
-
The production check of a pull request that changes the plugin's built output names the release
|
|
511
|
-
the merge published and the version npm then carries: `npm view @sjawhar/claude-envoy version`,
|
|
512
|
-
and `npm pack @sjawhar/claude-envoy` unpacked holds `dist/envoy-channel.js` and
|
|
513
|
-
`legion/.claude-plugin/plugin.json`. A release that did not publish is a finding for the
|
|
514
|
-
controller.
|
|
47
|
+
## The mod
|
|
515
48
|
|
|
516
|
-
|
|
49
|
+
- Every message into a terminal session goes through the mod's `session.message`, and `hooks/mod-writer.ts` decides whether it becomes a prompt or a row: only the mod sees the turn's events and this plugin's writes in one order.
|
|
517
50
|
|
|
518
|
-
-
|
|
51
|
+
- Answer a frame `done` only on the write the mod reports, a row appended or a prompt the engine took; the writes are idempotent by Envoy event id (`writeOnce`).
|
|
52
|
+
|
|
53
|
+
- An event that carries `agentId` is a subagent's, never the session's turn (`ofSubagent`).
|
|
54
|
+
|
|
55
|
+
- `resolveModSocketPath` puts the socket under `XDG_RUNTIME_DIR` or Claude Code's configuration directory, never `TMPDIR`, within a 100-byte path.
|
|
56
|
+
|
|
57
|
+
- The mod needs Claude Code 2.1.310 or newer; `--bare`, `--safe-mode` and settings that turn hooks or mods off leave a session with no messages.
|
|
58
|
+
|
|
59
|
+
## Legion panes
|
|
60
|
+
|
|
61
|
+
- The phase reminder's machine is `@legion/pi-shared`'s; `src/legion-phase-hook.ts` only drives it from Claude Code's hooks.
|
|
62
|
+
|
|
63
|
+
- Its hook entries are generated into `legion/hooks/hooks.json` (`LEGION_HOOKS` in `scripts/build.ts`), never `hooks/hooks.json`: a plain install has no `legion` server, so each would fail on every turn.
|
|
64
|
+
Only `tests/legion-phase-hook-claude.test.ts`, on the real binary, proves Claude Code arms them.
|