@sjawhar/claude-envoy 1.28.0 → 1.28.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.
@@ -2,5 +2,5 @@
2
2
  "name": "claude-envoy",
3
3
  "description": "Put Envoy events into the Claude Code session's own conversation and expose Envoy MCP tools.",
4
4
  "mcpServers": "./.mcp.json",
5
- "version": "1.28.0"
5
+ "version": "1.28.2"
6
6
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-envoy",
3
- "version": "1.28.0",
3
+ "version": "1.28.2",
4
4
  "description": "Put Envoy events into the Claude Code session's own conversation and expose Envoy MCP tools.",
5
5
  "mcpServers": {}
6
6
  }
package/AGENTS.md CHANGED
@@ -134,7 +134,7 @@ Dispatch asks stay on Dispatch.
134
134
  | 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. |
135
135
  | 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. |
136
136
  | 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. |
137
- | 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, claims the issue's Envoy role soft and calls ready, again on every `onRoleRegained`. 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
+ | 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`. |
138
138
  | 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. |
139
139
  | 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. |
140
140
 
@@ -432,9 +432,13 @@ above says how to run it).
432
432
  more would cost a `--resume` or a channel-server restart inside the live window its role for
433
433
  the life of the process. The Legion pane's claim waits the same refusal out rather than
434
434
  stopping the pane, asking every `ROLE_CLAIM_RETRY_MS` (10 s) for the live window and one
435
- attempt more, so the grant lands inside the daemon's registration deadline for the pane's
436
- `claims/ready` — `worker_boot_timeout_seconds` × `worker_boot_registration_deadline_intervals`
437
- from the registration — and it throws only on a refusal naming a different session. The
435
+ attempt more. That wait runs after the pane's `claims/ready`, since the role is claimed last,
436
+ at the session's first turn or at the bound, so the daemon's registration deadline
437
+ (`worker_boot_timeout_seconds` × `worker_boot_registration_deadline_intervals` from the
438
+ registration) is already met when the first attempt goes out and nothing outside the pane is
439
+ counting the wait; what bounds it is the listener's own live window, after which the standing
440
+ claim of the process this pane replaced is granted to nobody. It throws only on a refusal
441
+ naming a different session. The
438
442
  lookup's rule and the record's are the client contract's own,
439
443
  `roleHeldBy` and `mayActOnRoleRecord` in `@legion/envoy-client/transport`, which
440
444
  `packages/pi-envoy` calls too and which read an empty instance id as none, the lookup leaving
@@ -55391,7 +55391,7 @@ var import_nats2 = __toESM(require_mod4(), 1);
55391
55391
 
55392
55392
  // package.json
55393
55393
  var name = "@sjawhar/claude-envoy";
55394
- var version2 = "1.28.0";
55394
+ var version2 = "1.28.2";
55395
55395
  var legion = {
55396
55396
  daemonApiVersion: 59
55397
55397
  };
@@ -56588,9 +56588,59 @@ function installedPluginVersion(bundlePath) {
56588
56588
 
56589
56589
  // src/legion-claim.ts
56590
56590
  import { readdir as readdir2, stat as stat2 } from "fs/promises";
56591
- import { join as join8 } from "path";
56591
+ import { join as join9 } from "path";
56592
56592
  import { setTimeout as delay } from "timers/promises";
56593
56593
 
56594
+ // ../pi-shared/src/stall-limits.ts
56595
+ var DEFAULT_STALL_LIMITS = {
56596
+ reminderMs: 300000,
56597
+ waitingMs: 900000,
56598
+ resumeMs: 120000,
56599
+ architectAfter: 3,
56600
+ callGraceMs: 300000,
56601
+ callBoundMs: 3600000,
56602
+ stepMs: 120000
56603
+ };
56604
+ var LONG_CALL_BOUND_MS = 14400000;
56605
+ var LONG_CALL_BOUND_ROLES = [
56606
+ "implementer",
56607
+ "reviewer"
56608
+ ];
56609
+ function defaultCallBoundMs(role) {
56610
+ return role !== undefined && LONG_CALL_BOUND_ROLES.includes(role) ? LONG_CALL_BOUND_MS : DEFAULT_STALL_LIMITS.callBoundMs;
56611
+ }
56612
+ function integerSetting(env, log, name, fallback, least) {
56613
+ const raw = env[name];
56614
+ if (raw === undefined)
56615
+ return fallback;
56616
+ const value = raw.trim() === "" ? Number.NaN : Number(raw);
56617
+ if (!Number.isInteger(value) || value < least) {
56618
+ log.warn(`legion: ${name} is not an integer of ${least} or more; using ${fallback}`, {
56619
+ value: raw
56620
+ });
56621
+ return fallback;
56622
+ }
56623
+ return value;
56624
+ }
56625
+ function stallLimits(env, log, role) {
56626
+ return {
56627
+ reminderMs: integerSetting(env, log, "LEGION_STALL_REMINDER_MS", DEFAULT_STALL_LIMITS.reminderMs, 0),
56628
+ waitingMs: integerSetting(env, log, "LEGION_STALL_WAITING_MS", DEFAULT_STALL_LIMITS.waitingMs, 0),
56629
+ resumeMs: integerSetting(env, log, "LEGION_STALL_RESUME_MS", DEFAULT_STALL_LIMITS.resumeMs, 0),
56630
+ architectAfter: integerSetting(env, log, "LEGION_STALL_ARCHITECT_AFTER", DEFAULT_STALL_LIMITS.architectAfter, 2),
56631
+ callGraceMs: integerSetting(env, log, "LEGION_STALL_CALL_GRACE_MS", DEFAULT_STALL_LIMITS.callGraceMs, 0),
56632
+ callBoundMs: integerSetting(env, log, "LEGION_STALL_CALL_BOUND_MS", defaultCallBoundMs(role), 0),
56633
+ stepMs: integerSetting(env, log, "LEGION_STALL_STEP_MS", DEFAULT_STALL_LIMITS.stepMs, 0)
56634
+ };
56635
+ }
56636
+
56637
+ // ../pi-shared/src/claim-first-turn-bound.ts
56638
+ var DEFAULT_CLAIM_FIRST_TURN_BOUND_MS = 30000;
56639
+ var BOUND_VARIABLE = "LEGION_CLAIM_FIRST_TURN_BOUND_MS";
56640
+ function claimFirstTurnBoundMs(env, log) {
56641
+ return integerSetting(env, log, BOUND_VARIABLE, DEFAULT_CLAIM_FIRST_TURN_BOUND_MS, 0);
56642
+ }
56643
+
56594
56644
  // ../pi-shared/src/legion-claim-core.ts
56595
56645
  async function bootLegionClaim(host) {
56596
56646
  const { daemon } = host;
@@ -56604,8 +56654,9 @@ async function bootLegionClaim(host) {
56604
56654
  if (error.status < 400 || error.status >= 500)
56605
56655
  throw error;
56606
56656
  host.stop();
56607
- return;
56657
+ return { claimed: Promise.resolve() };
56608
56658
  }
56659
+ const firstTurn = listenForFirstTurn(host);
56609
56660
  try {
56610
56661
  await host.afterRegister?.(claim);
56611
56662
  host.setCapability({
@@ -56618,7 +56669,6 @@ async function bootLegionClaim(host) {
56618
56669
  secret: claim.secret,
56619
56670
  promptAgents: claim.promptAgents
56620
56671
  });
56621
- await host.claimRole(claim.claimToken);
56622
56672
  const ready = {
56623
56673
  claimToken: claim.claimToken,
56624
56674
  sessionId: host.registration.sessionId,
@@ -56637,217 +56687,58 @@ async function bootLegionClaim(host) {
56637
56687
  }
56638
56688
  });
56639
56689
  } catch (error) {
56640
- host.log(`claim boot failed after claims/register registered ${claim.claimToken}; ${host.stopping}: ${messageFor(error)}`);
56641
- host.stop();
56642
- }
56643
- }
56644
-
56645
- // src/legion-claim.ts
56646
- function legionPane(env) {
56647
- const pointer = env["LEGION_BOOT_TOKEN_FILE"];
56648
- if (pointer === undefined && configuredValue(env["LEGION_BOOT_TOKEN"]) === undefined) {
56649
- return;
56650
- }
56651
- const required = (key) => {
56652
- const value = configuredValue(env[key]);
56653
- if (value === undefined) {
56654
- throw new Error(`${key} is required for Legion: the pane carries a boot token`);
56655
- }
56656
- return value;
56657
- };
56658
- return {
56659
- daemonUrl: required("LEGION_DAEMON_URL"),
56660
- configDir: required("CLAUDE_CONFIG_DIR"),
56661
- bootToken: pointer === undefined ? required("LEGION_BOOT_TOKEN") : readSecretFile("LEGION_BOOT_TOKEN_FILE", pointer),
56662
- launcherSaves: configuredValue(env["LEGION_CLAUDE_SESSION_ID"]) !== undefined
56663
- };
56664
- }
56665
- function logLegion(line) {
56666
- process.stderr.write(`[legion] ${line}
56667
- `);
56668
- }
56669
- function endPane() {
56670
- process.kill(process.ppid, "SIGTERM");
56671
- }
56672
- function stopPane(why) {
56673
- logLegion(`${why}; stopping the pane so the daemon launches it again`);
56674
- endPane();
56675
- }
56676
- async function waitForTranscript(configDir, sessionID, signal, pollMs = 100) {
56677
- const projects = join8(configDir, "projects");
56678
- const name = `${sessionID}.jsonl`;
56679
- for (;; ) {
56680
- signal.throwIfAborted();
56681
- for (const directory of await readdir2(projects).catch(() => [])) {
56682
- const file = join8(projects, directory, name);
56683
- if (await isFile(file))
56684
- return file;
56685
- }
56686
- await delay(pollMs, undefined, { signal });
56690
+ stopAfterRegistration(host, claim.claimToken, error);
56691
+ return { claimed: Promise.resolve() };
56687
56692
  }
56693
+ return { claimed: claimRoleAtFirstTurn(host, claim.claimToken, firstTurn) };
56688
56694
  }
56689
- var SAVED_MARKER_SUFFIX = ".legion-saved";
56690
- async function waitForSavedTranscript(transcript, signal, pollMs = 100) {
56691
- const marker = `${transcript}${SAVED_MARKER_SUFFIX}`;
56692
- for (;; ) {
56693
- signal.throwIfAborted();
56694
- if (await isFile(marker))
56695
- return;
56696
- await delay(pollMs, undefined, { signal });
56697
- }
56698
- }
56699
- function isFile(file) {
56700
- return stat2(file).then((info) => info.isFile(), () => false);
56695
+ function stopAfterRegistration(host, role, error) {
56696
+ host.log(`claim boot failed after claims/register registered ${role}; ${host.stopping}: ${messageFor(error)}`);
56697
+ host.stop();
56701
56698
  }
56702
- var ROLE_CLAIM_RETRY_MS = 1e4;
56703
- var ROLE_CLAIM_WAIT_MS = SESSION_LIVE_WINDOW_MS + ROLE_CLAIM_RETRY_MS;
56704
- function startLegionClaim(deps) {
56705
- let capability;
56706
- const { sessionID } = deps;
56707
- const roleWaitMs = deps.roleWaitMs ?? ROLE_CLAIM_WAIT_MS;
56708
- const roleRetryMs = deps.roleRetryMs ?? ROLE_CLAIM_RETRY_MS;
56709
- const boot = async () => {
56710
- const transcript = await waitForTranscript(deps.pane.configDir, sessionID, deps.signal, deps.pollMs);
56711
- if (deps.pane.launcherSaves) {
56712
- await waitForSavedTranscript(transcript, deps.signal, deps.pollMs);
56713
- }
56714
- await bootLegionClaim({
56715
- daemon: deps.daemon,
56716
- registration: {
56717
- bootToken: deps.pane.bootToken,
56718
- sessionId: sessionID,
56719
- ompSessionFile: transcript,
56720
- agentId: sessionID,
56721
- pluginContract: legion.daemonApiVersion
56722
- },
56723
- setCapability: (registered) => {
56724
- capability = registered;
56725
- },
56726
- claimRole: async (role) => {
56727
- const deadline = Date.now() + roleWaitMs;
56728
- let waited = false;
56729
- for (;; ) {
56730
- const claimed = await deps.client.setRole({
56731
- sessionID,
56732
- role,
56733
- soft: true,
56734
- clientInstanceID: deps.clientInstanceID
56735
- });
56736
- if (claimed.claimed)
56737
- break;
56738
- if (claimed.holder !== sessionID) {
56739
- throw new Error(`Envoy role ${role} is held by live session ${claimed.holder}`);
56740
- }
56741
- const left = deadline - Date.now();
56742
- if (left <= 0) {
56743
- throw new Error(`Envoy role ${role} is still claimed under this session by another process after ${roleWaitMs} ms of asking`);
56744
- }
56745
- if (!waited) {
56746
- waited = true;
56747
- deps.log(`Envoy role ${role} is claimed under this session by the process this pane replaced; asking again every ${roleRetryMs} ms for up to ${roleWaitMs} ms, until nobody has answered for that claim inside the listener's live window`);
56748
- }
56749
- await delay(Math.min(roleRetryMs, left), undefined, { signal: deps.signal });
56750
- }
56751
- await deps.session.rememberRole(role);
56752
- },
56753
- onRoleRegained: (listener) => deps.session.onRoleRegained(listener),
56754
- log: deps.log,
56755
- stopping: "stopping the pane so the daemon launches it again",
56756
- stop: () => {
56757
- if (!deps.signal.aborted)
56758
- deps.stop();
56759
- }
56760
- });
56761
- };
56762
- const booted = boot().catch((error) => {
56763
- if (deps.signal.aborted)
56764
- return;
56765
- deps.log(`claim boot failed before a registration; the daemon's registration deadline relaunches the pane: ${messageFor(error)}`);
56699
+ function listenForFirstTurn(host) {
56700
+ let started = false;
56701
+ let claim;
56702
+ host.onFirstTurn(() => {
56703
+ started = true;
56704
+ claim?.();
56766
56705
  });
56767
- return { capability: () => capability, booted };
56768
- }
56769
-
56770
- // src/legion-inbox.ts
56771
- import { randomUUID as randomUUID2 } from "crypto";
56772
- import { createConnection } from "net";
56773
- var INBOX_VARIABLE = "LEGION_CLAUDE_INBOX";
56774
- var INBOX_CAPABILITIES = [
56775
- "aside",
56776
- "steer"
56777
- ];
56778
- function createInboxNotifier(socketPath) {
56779
- let socket;
56780
- let buffered = "";
56781
- const waiting = [];
56782
- const fail = (error) => {
56783
- for (const pending of waiting.splice(0))
56784
- pending.settle.reject(error);
56706
+ return (step) => {
56707
+ claim = step;
56708
+ if (started)
56709
+ step();
56785
56710
  };
56786
- const answer = (line) => {
56787
- const pending = waiting.shift();
56788
- if (pending === undefined)
56789
- return;
56790
- let parsed;
56791
- try {
56792
- parsed = JSON.parse(line);
56793
- } catch {
56794
- pending.settle.reject(new Error(`the Legion inbox answered ${JSON.stringify(line)}`));
56711
+ }
56712
+ function claimRoleAtFirstTurn(host, role, firstTurn) {
56713
+ const done = Promise.withResolvers();
56714
+ let ran = false;
56715
+ const claim = () => {
56716
+ if (ran)
56795
56717
  return;
56796
- }
56797
- if (parsed.ok === true && parsed.id === pending.id)
56798
- pending.settle.resolve();
56799
- else {
56800
- pending.settle.reject(new Error(`the Legion inbox refused delivery ${pending.id}: ${parsed.error ?? `answered ${line}`}`));
56801
- }
56802
- };
56803
- const connected = () => {
56804
- if (socket !== undefined && !socket.destroyed)
56805
- return socket;
56806
- buffered = "";
56807
- const opened = createConnection(socketPath);
56808
- opened.setEncoding("utf8");
56809
- opened.on("data", (chunk) => {
56810
- buffered += chunk;
56811
- for (let end = buffered.indexOf(`
56812
- `);end >= 0; end = buffered.indexOf(`
56813
- `)) {
56814
- const line = buffered.slice(0, end);
56815
- buffered = buffered.slice(end + 1);
56816
- answer(line);
56718
+ ran = true;
56719
+ clearTimeout(bound);
56720
+ (async () => {
56721
+ try {
56722
+ await host.claimRole(role);
56723
+ } catch (error) {
56724
+ stopAfterRegistration(host, role, error);
56817
56725
  }
56818
- });
56819
- opened.on("error", (error) => fail(new Error(`the Legion inbox ${socketPath}: ${error.message}`)));
56820
- opened.on("close", () => {
56821
- fail(new Error(`the Legion inbox ${socketPath} closed before it answered`));
56822
- if (socket === opened)
56823
- socket = undefined;
56824
- });
56825
- socket = opened;
56826
- return opened;
56827
- };
56828
- return {
56829
- notification(notification) {
56830
- const id = notification.eventId ?? randomUUID2();
56831
- const settle = Promise.withResolvers();
56832
- waiting.push({ id, settle });
56833
- connected().write(`${JSON.stringify({
56834
- id,
56835
- content: notification.content,
56836
- ...notification.blocks === undefined ? {} : { blocks: notification.blocks }
56837
- })}
56838
- `);
56839
- return settle.promise;
56840
- }
56726
+ done.resolve();
56727
+ })();
56841
56728
  };
56729
+ const bound = setTimeout(claim, host.firstTurnBoundMs);
56730
+ bound.unref?.();
56731
+ firstTurn(claim);
56732
+ return done.promise;
56842
56733
  }
56843
56734
 
56844
56735
  // src/legion-phase-hook.ts
56845
- import { randomUUID as randomUUID4 } from "crypto";
56736
+ import { randomUUID as randomUUID3 } from "crypto";
56846
56737
  import { readFileSync as readFileSync7, renameSync as renameSync3, rmSync as rmSync5, writeFileSync as writeFileSync4 } from "fs";
56847
- import { dirname as dirname3, join as join9 } from "path";
56738
+ import { dirname as dirname3, join as join8 } from "path";
56848
56739
 
56849
56740
  // ../pi-shared/src/phase-reminder.ts
56850
- import { randomUUID as randomUUID3 } from "crypto";
56741
+ import { randomUUID as randomUUID2 } from "crypto";
56851
56742
 
56852
56743
  // ../pi-shared/src/phase-stall.ts
56853
56744
  var WAITING_REPLY = /^\W*WAITING\b/m;
@@ -57036,7 +56927,7 @@ function createPhaseReminder(deps) {
57036
56927
  });
57037
56928
  return;
57038
56929
  }
57039
- reportKey ??= randomUUID3();
56930
+ reportKey ??= randomUUID2();
57040
56931
  const key = reportKey;
57041
56932
  writeEntry();
57042
56933
  const phase = record?.phase ?? "unknown";
@@ -57222,49 +57113,6 @@ function sessionActivityRequest(input) {
57222
57113
  };
57223
57114
  }
57224
57115
 
57225
- // ../pi-shared/src/stall-limits.ts
57226
- var DEFAULT_STALL_LIMITS = {
57227
- reminderMs: 300000,
57228
- waitingMs: 900000,
57229
- resumeMs: 120000,
57230
- architectAfter: 3,
57231
- callGraceMs: 300000,
57232
- callBoundMs: 3600000,
57233
- stepMs: 120000
57234
- };
57235
- var LONG_CALL_BOUND_MS = 14400000;
57236
- var LONG_CALL_BOUND_ROLES = [
57237
- "implementer",
57238
- "reviewer"
57239
- ];
57240
- function defaultCallBoundMs(role) {
57241
- return role !== undefined && LONG_CALL_BOUND_ROLES.includes(role) ? LONG_CALL_BOUND_MS : DEFAULT_STALL_LIMITS.callBoundMs;
57242
- }
57243
- function integerSetting(env, log, name, fallback, least) {
57244
- const raw = env[name];
57245
- if (raw === undefined)
57246
- return fallback;
57247
- const value = raw.trim() === "" ? Number.NaN : Number(raw);
57248
- if (!Number.isInteger(value) || value < least) {
57249
- log.warn(`legion: ${name} is not an integer of ${least} or more; using ${fallback}`, {
57250
- value: raw
57251
- });
57252
- return fallback;
57253
- }
57254
- return value;
57255
- }
57256
- function stallLimits(env, log, role) {
57257
- return {
57258
- reminderMs: integerSetting(env, log, "LEGION_STALL_REMINDER_MS", DEFAULT_STALL_LIMITS.reminderMs, 0),
57259
- waitingMs: integerSetting(env, log, "LEGION_STALL_WAITING_MS", DEFAULT_STALL_LIMITS.waitingMs, 0),
57260
- resumeMs: integerSetting(env, log, "LEGION_STALL_RESUME_MS", DEFAULT_STALL_LIMITS.resumeMs, 0),
57261
- architectAfter: integerSetting(env, log, "LEGION_STALL_ARCHITECT_AFTER", DEFAULT_STALL_LIMITS.architectAfter, 2),
57262
- callGraceMs: integerSetting(env, log, "LEGION_STALL_CALL_GRACE_MS", DEFAULT_STALL_LIMITS.callGraceMs, 0),
57263
- callBoundMs: integerSetting(env, log, "LEGION_STALL_CALL_BOUND_MS", defaultCallBoundMs(role), 0),
57264
- stepMs: integerSetting(env, log, "LEGION_STALL_STEP_MS", DEFAULT_STALL_LIMITS.stepMs, 0)
57265
- };
57266
- }
57267
-
57268
57116
  // ../pi-shared/src/workspace-recreated.ts
57269
57117
  var WORKSPACE_RECREATED_VARIABLE = "LEGION_WORKSPACE_RECREATED";
57270
57118
  var WORKSPACE_RESTORED_VARIABLE = "LEGION_WORKSPACE_RESTORED";
@@ -57327,7 +57175,7 @@ function phaseHookToolDefinition() {
57327
57175
  };
57328
57176
  }
57329
57177
  function phaseStallFile(configDir, sessionID) {
57330
- return join9(configDir, `legion-phase-stall-${sessionID}.json`);
57178
+ return join8(configDir, `legion-phase-stall-${sessionID}.json`);
57331
57179
  }
57332
57180
  function paneReminderLog(write) {
57333
57181
  const line = (level, message, context) => {
@@ -57380,7 +57228,7 @@ function readPhaseStallRecord(file, log) {
57380
57228
  };
57381
57229
  }
57382
57230
  function writePhaseStallRecord(file, entry, recreatedNoticeSent, log) {
57383
- const temporary = join9(dirname3(file), `.legion-phase-stall-${randomUUID4()}`);
57231
+ const temporary = join8(dirname3(file), `.legion-phase-stall-${randomUUID3()}`);
57384
57232
  try {
57385
57233
  writeFileSync4(temporary, JSON.stringify({ ...entry, ...recreatedNoticeSent ? { recreatedNoticeSent } : {} }), { mode: 384 });
57386
57234
  renameSync3(temporary, file);
@@ -57505,6 +57353,8 @@ function createPhaseHookEndpoint(deps) {
57505
57353
  if (!parsed.success)
57506
57354
  return { error: PHASE_HOOK_REFUSAL };
57507
57355
  const event = parsed.data;
57356
+ if (event.event === "UserPromptSubmit")
57357
+ deps.firstTurnStarted();
57508
57358
  const claim = deps.claim();
57509
57359
  if (claim === undefined || claim.role === "architect")
57510
57360
  return {};
@@ -57549,6 +57399,214 @@ function createPhaseHookEndpoint(deps) {
57549
57399
  };
57550
57400
  }
57551
57401
 
57402
+ // src/legion-claim.ts
57403
+ function legionPane(env) {
57404
+ const pointer = env["LEGION_BOOT_TOKEN_FILE"];
57405
+ if (pointer === undefined && configuredValue(env["LEGION_BOOT_TOKEN"]) === undefined) {
57406
+ return;
57407
+ }
57408
+ const required = (key) => {
57409
+ const value = configuredValue(env[key]);
57410
+ if (value === undefined) {
57411
+ throw new Error(`${key} is required for Legion: the pane carries a boot token`);
57412
+ }
57413
+ return value;
57414
+ };
57415
+ return {
57416
+ daemonUrl: required("LEGION_DAEMON_URL"),
57417
+ configDir: required("CLAUDE_CONFIG_DIR"),
57418
+ bootToken: pointer === undefined ? required("LEGION_BOOT_TOKEN") : readSecretFile("LEGION_BOOT_TOKEN_FILE", pointer),
57419
+ launcherSaves: configuredValue(env["LEGION_CLAUDE_SESSION_ID"]) !== undefined
57420
+ };
57421
+ }
57422
+ function logLegion(line) {
57423
+ process.stderr.write(`[legion] ${line}
57424
+ `);
57425
+ }
57426
+ function endPane() {
57427
+ process.kill(process.ppid, "SIGTERM");
57428
+ }
57429
+ function stopPane(why) {
57430
+ logLegion(`${why}; stopping the pane so the daemon launches it again`);
57431
+ endPane();
57432
+ }
57433
+ async function waitForTranscript(configDir, sessionID, signal, pollMs = 100) {
57434
+ const projects = join9(configDir, "projects");
57435
+ const name = `${sessionID}.jsonl`;
57436
+ for (;; ) {
57437
+ signal.throwIfAborted();
57438
+ for (const directory of await readdir2(projects).catch(() => [])) {
57439
+ const file = join9(projects, directory, name);
57440
+ if (await isFile(file))
57441
+ return file;
57442
+ }
57443
+ await delay(pollMs, undefined, { signal });
57444
+ }
57445
+ }
57446
+ var SAVED_MARKER_SUFFIX = ".legion-saved";
57447
+ async function waitForSavedTranscript(transcript, signal, pollMs = 100) {
57448
+ const marker = `${transcript}${SAVED_MARKER_SUFFIX}`;
57449
+ for (;; ) {
57450
+ signal.throwIfAborted();
57451
+ if (await isFile(marker))
57452
+ return;
57453
+ await delay(pollMs, undefined, { signal });
57454
+ }
57455
+ }
57456
+ function isFile(file) {
57457
+ return stat2(file).then((info) => info.isFile(), () => false);
57458
+ }
57459
+ var ROLE_CLAIM_RETRY_MS = 1e4;
57460
+ var ROLE_CLAIM_WAIT_MS = SESSION_LIVE_WINDOW_MS + ROLE_CLAIM_RETRY_MS;
57461
+ function startLegionClaim(deps) {
57462
+ let capability;
57463
+ const { sessionID } = deps;
57464
+ const roleWaitMs = deps.roleWaitMs ?? ROLE_CLAIM_WAIT_MS;
57465
+ const roleRetryMs = deps.roleRetryMs ?? ROLE_CLAIM_RETRY_MS;
57466
+ const boot = async () => {
57467
+ const transcript = await waitForTranscript(deps.pane.configDir, sessionID, deps.signal, deps.pollMs);
57468
+ if (deps.pane.launcherSaves) {
57469
+ await waitForSavedTranscript(transcript, deps.signal, deps.pollMs);
57470
+ }
57471
+ return await bootLegionClaim({
57472
+ daemon: deps.daemon,
57473
+ registration: {
57474
+ bootToken: deps.pane.bootToken,
57475
+ sessionId: sessionID,
57476
+ ompSessionFile: transcript,
57477
+ agentId: sessionID,
57478
+ pluginContract: legion.daemonApiVersion
57479
+ },
57480
+ setCapability: (registered) => {
57481
+ capability = registered;
57482
+ },
57483
+ claimRole: async (role) => {
57484
+ const deadline = Date.now() + roleWaitMs;
57485
+ let waited = false;
57486
+ for (;; ) {
57487
+ const claimed = await deps.client.setRole({
57488
+ sessionID,
57489
+ role,
57490
+ soft: true,
57491
+ clientInstanceID: deps.clientInstanceID
57492
+ });
57493
+ if (claimed.claimed)
57494
+ break;
57495
+ if (claimed.holder !== sessionID) {
57496
+ throw new Error(`Envoy role ${role} is held by live session ${claimed.holder}`);
57497
+ }
57498
+ const left = deadline - Date.now();
57499
+ if (left <= 0) {
57500
+ throw new Error(`Envoy role ${role} is still claimed under this session by another process after ${roleWaitMs} ms of asking`);
57501
+ }
57502
+ if (!waited) {
57503
+ waited = true;
57504
+ deps.log(`Envoy role ${role} is claimed under this session by the process this pane replaced; asking again every ${roleRetryMs} ms for up to ${roleWaitMs} ms, until nobody has answered for that claim inside the listener's live window`);
57505
+ }
57506
+ await delay(Math.min(roleRetryMs, left), undefined, { signal: deps.signal });
57507
+ }
57508
+ await deps.session.rememberRole(role);
57509
+ },
57510
+ onFirstTurn: deps.onFirstTurn,
57511
+ firstTurnBoundMs: claimFirstTurnBoundMs(deps.env ?? process.env, paneReminderLog(deps.log)),
57512
+ onRoleRegained: (listener) => deps.session.onRoleRegained(listener),
57513
+ log: deps.log,
57514
+ stopping: "stopping the pane so the daemon launches it again",
57515
+ stop: () => {
57516
+ if (!deps.signal.aborted)
57517
+ deps.stop();
57518
+ }
57519
+ });
57520
+ };
57521
+ const started = boot().catch((error) => {
57522
+ if (!deps.signal.aborted) {
57523
+ deps.log(`claim boot failed before a registration; the daemon's registration deadline relaunches the pane: ${messageFor(error)}`);
57524
+ }
57525
+ return { claimed: Promise.resolve() };
57526
+ });
57527
+ return {
57528
+ capability: () => capability,
57529
+ booted: started.then(() => {
57530
+ return;
57531
+ }),
57532
+ claimed: started.then((claimBoot) => claimBoot.claimed)
57533
+ };
57534
+ }
57535
+
57536
+ // src/legion-inbox.ts
57537
+ import { randomUUID as randomUUID4 } from "crypto";
57538
+ import { createConnection } from "net";
57539
+ var INBOX_VARIABLE = "LEGION_CLAUDE_INBOX";
57540
+ var INBOX_CAPABILITIES = [
57541
+ "aside",
57542
+ "steer"
57543
+ ];
57544
+ function createInboxNotifier(socketPath) {
57545
+ let socket;
57546
+ let buffered = "";
57547
+ const waiting = [];
57548
+ const fail = (error) => {
57549
+ for (const pending of waiting.splice(0))
57550
+ pending.settle.reject(error);
57551
+ };
57552
+ const answer = (line) => {
57553
+ const pending = waiting.shift();
57554
+ if (pending === undefined)
57555
+ return;
57556
+ let parsed;
57557
+ try {
57558
+ parsed = JSON.parse(line);
57559
+ } catch {
57560
+ pending.settle.reject(new Error(`the Legion inbox answered ${JSON.stringify(line)}`));
57561
+ return;
57562
+ }
57563
+ if (parsed.ok === true && parsed.id === pending.id)
57564
+ pending.settle.resolve();
57565
+ else {
57566
+ pending.settle.reject(new Error(`the Legion inbox refused delivery ${pending.id}: ${parsed.error ?? `answered ${line}`}`));
57567
+ }
57568
+ };
57569
+ const connected = () => {
57570
+ if (socket !== undefined && !socket.destroyed)
57571
+ return socket;
57572
+ buffered = "";
57573
+ const opened = createConnection(socketPath);
57574
+ opened.setEncoding("utf8");
57575
+ opened.on("data", (chunk) => {
57576
+ buffered += chunk;
57577
+ for (let end = buffered.indexOf(`
57578
+ `);end >= 0; end = buffered.indexOf(`
57579
+ `)) {
57580
+ const line = buffered.slice(0, end);
57581
+ buffered = buffered.slice(end + 1);
57582
+ answer(line);
57583
+ }
57584
+ });
57585
+ opened.on("error", (error) => fail(new Error(`the Legion inbox ${socketPath}: ${error.message}`)));
57586
+ opened.on("close", () => {
57587
+ fail(new Error(`the Legion inbox ${socketPath} closed before it answered`));
57588
+ if (socket === opened)
57589
+ socket = undefined;
57590
+ });
57591
+ socket = opened;
57592
+ return opened;
57593
+ };
57594
+ return {
57595
+ notification(notification) {
57596
+ const id = notification.eventId ?? randomUUID4();
57597
+ const settle = Promise.withResolvers();
57598
+ waiting.push({ id, settle });
57599
+ connected().write(`${JSON.stringify({
57600
+ id,
57601
+ content: notification.content,
57602
+ ...notification.blocks === undefined ? {} : { blocks: notification.blocks }
57603
+ })}
57604
+ `);
57605
+ return settle.promise;
57606
+ }
57607
+ };
57608
+ }
57609
+
57552
57610
  // ../pi-shared/src/legion-phase-ops.ts
57553
57611
  var PHASE_OPS = [
57554
57612
  "read_record",
@@ -60120,10 +60178,12 @@ async function runEnvoyChannelServer() {
60120
60178
  const daemon = pane === undefined ? undefined : createLegionDaemonClient(pane.daemonUrl);
60121
60179
  const phaseLog = paneReminderLog(logLegion);
60122
60180
  const claimBooted = Promise.withResolvers();
60181
+ let reportFirstTurn;
60123
60182
  const phaseHook = pane === undefined || daemon === undefined ? undefined : createPhaseHookEndpoint({
60124
60183
  stateFile: phaseStallFile(pane.configDir, identity.id),
60125
60184
  claim: () => claim?.capability(),
60126
60185
  booted: claimBooted.promise,
60186
+ firstTurnStarted: () => reportFirstTurn?.(),
60127
60187
  readState: (signal) => daemon.state({ signal }),
60128
60188
  reportActivity: (input) => daemon.activity(input),
60129
60189
  inbox: inbox === undefined ? undefined : (text) => inbox.notification({ content: text }),
@@ -60320,7 +60380,10 @@ async function runEnvoyChannelServer() {
60320
60380
  session,
60321
60381
  signal: booting.signal,
60322
60382
  log: logLegion,
60323
- stop: endPane
60383
+ stop: endPane,
60384
+ onFirstTurn: (started) => {
60385
+ reportFirstTurn = started;
60386
+ }
60324
60387
  });
60325
60388
  claim.booted.then(claimBooted.resolve);
60326
60389
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sjawhar/claude-envoy",
3
- "version": "1.28.0",
3
+ "version": "1.28.2",
4
4
  "license": "Apache-2.0",
5
5
  "description": "Claude Code plugin for Legion's Envoy bus",
6
6
  "type": "module",
@@ -80,4 +80,4 @@ Every topic starts with `notifications.`.
80
80
  - A message that must reach more than 4 role topics is the project controller's to send, not yours. Each publish wakes a session, and a woken session reads its whole context again, which the provider charges as uncached input: a mean of 576,083 tokens a wake, a median of 493,636 and a ninetieth percentile of 1,327,888. The controller is also the one session that can read whether a wave of wakes is already running, and a fan-out sent into a daemon restart or a pod roll is what puts an Anthropic organization over its per-minute uncached-input cap. Send the controller the topics and the text, and it sends them at its own rate (`skill://legion-controller`).
81
81
  - For a team, the group subscribes to `notifications.team.<name>.>`, and any member publishes to `notifications.team.<name>.all`. Envoy treats any other `notifications.` topic that no source in the table uses the same way. It reaches every session subscribed when it is published, yours too when you subscribe. The listener also asks each other session that holds its own NATS connection and registered the topic (every session that follows it with `envoy_subscribe`) to confirm the message; your own session is never asked. A publish returns an error naming each such session that did not confirm within about 4 seconds, and you see it after about 8 seconds, because the client tries once more. A session named with `receipt_timeout` still gets the message: the listener kept a copy in that session's inbox, which the session reads back once its connection returns. An `unresponsive` session is sent the message the same way, asked for no receipt and named under `unresponsive` in the answer, which is no failure. A session that stopped without unregistering stays in the registry until the reaper finds it `gone`, and is named until then; a named session is not a failed delivery to the others. A team topic is not kept for a session that subscribes later. A topic outside `notifications.` is refused.
82
82
  - How a role claim survives a resume, a fork or a dead process: `skill://envoy/references/roles.md`.
83
- - In a Legion pane, the plugin claims your role at session start; read `skill://envoy/references/legion.md` before you claim, release or publish to a role, or answer a role delivery failure there.
83
+ - In a Legion pane, the plugin claims your role for you, at your session's first turn; read `skill://envoy/references/legion.md` before you claim, release or publish to a role, or answer a role delivery failure there.
@@ -2,7 +2,7 @@
2
2
 
3
3
  Read this in a Legion pane before you touch a role claim, or when a Legion role message fails.
4
4
 
5
- - The Legion plugin claims your assigned role at session start through a daemon-minted role token. Never call `envoy_role_set` and never subscribe to your role topic yourself, because the claim is already made (`packages/pi-shared/src/legion-claim-core.ts`).
5
+ - The Legion plugin claims your assigned role for you, through a daemon-minted role token: it registers your session and reports it ready at session start, and takes the role at your first turn, or at a bound (30 s by default) when no turn comes first. Never call `envoy_role_set` and never subscribe to your role topic yourself, because the claim is already made (`packages/pi-shared/src/legion-claim-core.ts`).
6
6
  - Never build a role token from an issue number or title: only the daemon maps tokens to issues.
7
7
  - A Legion claim is last-claim-wins. It survives parking and worker re-creation, and stays through the issue's linger after close (the deployment's `linger_hours`).
8
8
  - `no_holder`, `holder_lapsed`, `delivery_failed` and `receipt_timeout` on a Legion role are the daemon's liveness signals. Never add a second subscriber or retry by hand: the daemon revives or recreates the worker and re-delivers, or relaunches the root process, which gets a `catch-up` notice of its tree and reads each issue's handoffs on its Dispatch issue (`dispatch handoff-read`).
@@ -2171,6 +2171,26 @@ export async function runEnvoyChannelServer(): Promise<void> {
2171
2171
  // The claim's boot, for the endpoint's resume reminder and its recreated-workspace notice: both
2172
2172
  // need the claim, and the claim starts further down, once the channel session exists.
2173
2173
  const claimBooted = Promise.withResolvers<void>()
2174
+ // The other way round: the hook endpoint is built here, before the claim, and the boot's
2175
+ // first-turn signal fills this slot. The endpoint calls it at every `UserPromptSubmit`, this
2176
+ // process's only sight of a turn starting; the call reports that turn and claims nothing, and
2177
+ // the boot's own claim step, which runs after `claims/ready`, is what takes the Envoy name —
2178
+ // inside a running turn rather than ahead of the daemon's task (INFRA-1573).
2179
+ //
2180
+ // A slot, rather than a promise that remembers every prompt this process ever saw, because on
2181
+ // this host the first prompt is always the bridge's seeding `/rename`
2182
+ // (`packages/daemon/internal/claudebridge`), which runs before the claim exists — it is what
2183
+ // writes the transcript the boot waits for, so no registration can precede it. A signal kept
2184
+ // from before the boot filled this slot would take the name the moment `claims/ready` answers,
2185
+ // ahead of the daemon's task, which is the ordering this defers.
2186
+ //
2187
+ // The boot fills the slot as soon as `claims/register` has answered, before the ready that
2188
+ // follows, so a prompt that arrives while that ready is still being retried — the daemon took
2189
+ // the first one and its answer was lost, and its task reaches Claude Code meanwhile — is this
2190
+ // session's first turn and the name is taken as soon as ready answers, rather than at the
2191
+ // bound. A pane given no task at all is the bound's to cover, and a later prompt costs
2192
+ // nothing — the step itself claims once however often it runs.
2193
+ let reportFirstTurn: (() => void) | undefined
2174
2194
  const phaseHook =
2175
2195
  pane === undefined || daemon === undefined
2176
2196
  ? undefined
@@ -2178,6 +2198,7 @@ export async function runEnvoyChannelServer(): Promise<void> {
2178
2198
  stateFile: phaseStallFile(pane.configDir, identity.id),
2179
2199
  claim: () => claim?.capability(),
2180
2200
  booted: claimBooted.promise,
2201
+ firstTurnStarted: () => reportFirstTurn?.(),
2181
2202
  readState: (signal) => daemon.state({ signal }),
2182
2203
  reportActivity: (input) => daemon.activity(input),
2183
2204
  inbox: inbox === undefined ? undefined : (text) => inbox.notification({ content: text }),
@@ -2454,6 +2475,12 @@ export async function runEnvoyChannelServer(): Promise<void> {
2454
2475
  signal: booting.signal,
2455
2476
  log: logLegion,
2456
2477
  stop: endPane,
2478
+ // The signal goes in the slot the phase hook's `UserPromptSubmit` calls. The boot fills
2479
+ // it when `claims/register` has answered, which is after the bridge's seed: that prompt
2480
+ // found the slot empty and reported nothing.
2481
+ onFirstTurn: (started) => {
2482
+ reportFirstTurn = started
2483
+ },
2457
2484
  })
2458
2485
  // What `claimSession.bootstrap` returning is to the Oh My Pi host: the point the phase
2459
2486
  // endpoint may read the claim, arm its resume reminder and tell the worker its workspace
@@ -5,12 +5,14 @@ import { SESSION_LIVE_WINDOW_MS } from "@legion/contracts"
5
5
  import { messageFor } from "@legion/envoy-client/errors"
6
6
  import { readSecretFile } from "@legion/envoy-client/secret-file"
7
7
  import type { EnvoyClient } from "@legion/envoy-client/transport"
8
+ import { claimFirstTurnBoundMs } from "@legion/pi-shared/claim-first-turn-bound"
8
9
  import type { LegionDaemonClient } from "@legion/pi-shared/daemon-client"
9
- import { bootLegionClaim } from "@legion/pi-shared/legion-claim-core"
10
+ import { bootLegionClaim, type LegionClaimBoot } from "@legion/pi-shared/legion-claim-core"
10
11
  import type { ClaimCapability } from "@legion/pi-shared/legion-phase-ops"
11
12
  import { legion } from "../package.json" with { type: "json" }
12
13
  import { configuredValue } from "./claude-session"
13
14
  import type { ChannelSession } from "./envoy-channel-server"
15
+ import { paneReminderLog } from "./legion-phase-hook"
14
16
 
15
17
  /**
16
18
  * A Claude Code phase worker's claim on the Legion daemon, made by the MCP server Claude Code runs
@@ -137,18 +139,21 @@ function isFile(file: string): Promise<boolean> {
137
139
  * How long apart the attempts of {@link startLegionClaim}'s wait on a claim the listener refused
138
140
  * naming this very session are.
139
141
  *
140
- * The wait runs between `claims/register` and `claims/ready`, and the daemon retires a pane that
141
- * has not said it is ready `worker_boot_timeout_seconds` ×
142
- * `worker_boot_registration_deadline_intervals` after its registration armed that deadline — 120
143
- * s × 3 = 360 s with the shipped defaults (`packages/daemon/internal/config/config.go`, armed by
144
- * `register` through `armRegistration` in `packages/daemon/internal/supervise`). So the interval
145
- * is what stands between the grant and that deadline: the listener grants the standing claim on
146
- * the first attempt that falls after the live window its last renewal bought it, which is at
147
- * most `SESSION_LIVE_WINDOW_MS` after this pane registered, and every part of an interval past
148
- * that point is dead waiting. At a heartbeat's cadence the attempt at 270 s is still refused
149
- * whenever that renewal fell inside the 30 s before the registration, and the next one is at 360
150
- * s — the deadline itself. At 10 s the grant lands inside 310 s of the registration, 50 s of
151
- * room for `claims/ready` and its own retries.
142
+ * The wait runs after `claims/ready`, not before it: the role is claimed last, at the session's
143
+ * first turn or at the bound (INFRA-1573), so the daemon's registration deadline —
144
+ * `worker_boot_timeout_seconds` × `worker_boot_registration_deadline_intervals`, 120 s × 3 = 360
145
+ * s with the shipped defaults (`packages/daemon/internal/config/config.go`, armed by `register`
146
+ * through `armRegistration` in `packages/daemon/internal/supervise`) — is already met when the
147
+ * first attempt goes out, and no part of this wait is spent against it.
148
+ *
149
+ * What bounds the wait now is the listener's own live window: the standing claim of the process
150
+ * this pane replaced is granted to nobody until a whole `SESSION_LIVE_WINDOW_MS` has passed with
151
+ * no answer for it, so no interval can bring the grant forward, and every part of an interval
152
+ * past that point is dead waiting with the session already ready — the daemon may have handed it
153
+ * a task, and the lane the listener keeps for a role no session holds is handed over only when
154
+ * the claim lands. The interval is kept at 10 s for that: the grant falls at most 10 s after the
155
+ * window passes, where the session heartbeat's own cadence (`SESSION_HEARTBEAT_MS`, 90 s) would
156
+ * leave the pane unaddressable for up to 90 s more.
152
157
  *
153
158
  * What the shorter interval costs: one `POST /v1/roles/set` per interval, a conditional write the
154
159
  * listener refuses without touching the claim, at most about 30 of them, and only in a pane the
@@ -161,11 +166,12 @@ export const ROLE_CLAIM_RETRY_MS = 10_000
161
166
  * How long that same wait keeps asking before it gives up and the pane is stopped: the live
162
167
  * window and one attempt more, so the last attempt falls after the window the process this pane
163
168
  * replaced could still have been answering for its claim in, even when it answered for it at the
164
- * very moment this pane registered.
169
+ * very moment this pane first asked.
165
170
  *
166
- * Inside the daemon's registration deadline on purpose: a pane that cannot have its role writes
167
- * why to its log and is launched again, rather than being retired by a deadline that would
168
- * otherwise fire first and say nothing.
171
+ * That window is the whole of what can explain a refusal naming this session, and `claims/ready`
172
+ * is already answered, so nothing outside the pane is counting: past the wait, the claim is
173
+ * stopped on as every other failure after a registration is, and the pane writes why to its log
174
+ * and is launched again rather than sitting nameless for a lane it can never be handed.
169
175
  */
170
176
  export const ROLE_CLAIM_WAIT_MS = SESSION_LIVE_WINDOW_MS + ROLE_CLAIM_RETRY_MS
171
177
 
@@ -174,17 +180,23 @@ export interface LegionClaim {
174
180
  readonly capability: () => ClaimCapability | undefined
175
181
  /** Settles once the boot has run: ready sent, or the failure reported. Never rejects. */
176
182
  readonly booted: Promise<void>
183
+ /** Settles once the boot's last step has run — the Envoy role claimed at this session's first
184
+ * turn or at the bound, or the refusal logged and the pane stopped — and at once for a boot
185
+ * that never reached that step (`LegionClaimBoot.claimed`). Never rejects. */
186
+ readonly claimed: Promise<void>
177
187
  }
178
188
 
179
189
  /**
180
190
  * Boots the pane's claim in the background of the server (`bootLegionClaim`): waits for the
181
191
  * transcript, and in a pod whose launcher keeps it (`launcherSaves`) for the launcher's first save
182
192
  * of it too, registers with it as the session file (`agentId` is the session id,
183
- * `pluginContract` this package's `legion.daemonApiVersion`), claims the claim token's Envoy role
184
- * soft and records it with the channel session, whose heartbeat re-asserts it, and sends
185
- * `claims/ready` with no capability report, again each time the heartbeat regains the role. A
186
- * failure the core stops on ends the pane through `stop`; a failure before a registration is
187
- * logged and leaves the pane to the daemon's registration deadline.
193
+ * `pluginContract` this package's `legion.daemonApiVersion`), sends `claims/ready` with no
194
+ * capability report, again each time the heartbeat regains the role, and claims the claim
195
+ * token's Envoy role soft last of all — at this session's first turn (`onFirstTurn`) or at the
196
+ * bound this pane's environment names, whichever comes first — recording it with the channel
197
+ * session, whose heartbeat re-asserts it. A failure the core stops on ends the pane through
198
+ * `stop`; a failure before a registration is logged and leaves the pane to the daemon's
199
+ * registration deadline.
188
200
  *
189
201
  * A claim the listener refuses naming this very session is waited out rather than stopped on:
190
202
  * the pane the daemon relaunched with `--resume` meets the standing claim of the process it
@@ -193,8 +205,8 @@ export interface LegionClaim {
193
205
  * meets the same claim, for a whole window of relaunches.
194
206
  *
195
207
  * The claim is asked again every {@link ROLE_CLAIM_RETRY_MS} for up to
196
- * {@link ROLE_CLAIM_WAIT_MS}, both sized so the grant, and the give-up behind it, fall inside the
197
- * daemon's registration deadline for this pane's `claims/ready`.
208
+ * {@link ROLE_CLAIM_WAIT_MS}, the listener's live window and one attempt more, which is the
209
+ * whole of what can explain such a refusal.
198
210
  */
199
211
  export function startLegionClaim(deps: {
200
212
  readonly pane: LegionPane
@@ -210,6 +222,14 @@ export function startLegionClaim(deps: {
210
222
  readonly log: (line: string) => void
211
223
  /** Ends the pane's Claude Code, this server's parent, so the daemon launches the claim again. */
212
224
  readonly stop: () => void
225
+ /** Registers the step that takes this session's Envoy name, to be run once a turn of this
226
+ * session has started: the channel server holds it in a slot the phase hook's
227
+ * `UserPromptSubmit` calls, the only sight this process has of a turn beginning
228
+ * (`./legion-phase-hook`). It is called once the boot has registered, and a prompt submitted
229
+ * before that — the bridge's seeding `/rename`, which runs before any claim exists — runs
230
+ * nothing, so the name is never taken ahead of the daemon's task
231
+ * (`src/envoy-channel-server.ts`). */
232
+ readonly onFirstTurn: (claim: () => void) => void
213
233
  /**
214
234
  * How long a claim refused by a standing claim under this very session id keeps asking before
215
235
  * it gives up and the pane is stopped: {@link ROLE_CLAIM_WAIT_MS}.
@@ -217,6 +237,10 @@ export function startLegionClaim(deps: {
217
237
  readonly roleWaitMs?: number
218
238
  /** How long between those attempts: {@link ROLE_CLAIM_RETRY_MS}. */
219
239
  readonly roleRetryMs?: number
240
+ /** The pane's own environment, which the first-turn bound is read from
241
+ * (`claimFirstTurnBoundMs`): `process.env` for the server, and a case's own map in a test that
242
+ * will not wait 30 seconds. */
243
+ readonly env?: NodeJS.ProcessEnv
220
244
  readonly pollMs?: number
221
245
  }): LegionClaim {
222
246
  let capability: ClaimCapability | undefined
@@ -224,7 +248,7 @@ export function startLegionClaim(deps: {
224
248
  const roleWaitMs = deps.roleWaitMs ?? ROLE_CLAIM_WAIT_MS
225
249
  const roleRetryMs = deps.roleRetryMs ?? ROLE_CLAIM_RETRY_MS
226
250
 
227
- const boot = async (): Promise<void> => {
251
+ const boot = async (): Promise<LegionClaimBoot> => {
228
252
  const transcript = await waitForTranscript(
229
253
  deps.pane.configDir,
230
254
  sessionID,
@@ -234,7 +258,7 @@ export function startLegionClaim(deps: {
234
258
  if (deps.pane.launcherSaves) {
235
259
  await waitForSavedTranscript(transcript, deps.signal, deps.pollMs)
236
260
  }
237
- await bootLegionClaim({
261
+ return await bootLegionClaim({
238
262
  daemon: deps.daemon,
239
263
  registration: {
240
264
  bootToken: deps.pane.bootToken,
@@ -289,6 +313,10 @@ export function startLegionClaim(deps: {
289
313
  }
290
314
  await deps.session.rememberRole(role)
291
315
  },
316
+ onFirstTurn: deps.onFirstTurn,
317
+ // The pane's own bound, read from its environment as the reminder's four numbers are
318
+ // (`stallLimits` in `./legion-phase-hook`), and warned about on the pane's own log line.
319
+ firstTurnBoundMs: claimFirstTurnBoundMs(deps.env ?? process.env, paneReminderLog(deps.log)),
292
320
  onRoleRegained: (listener) => deps.session.onRoleRegained(listener),
293
321
  log: deps.log,
294
322
  stopping: "stopping the pane so the daemon launches it again",
@@ -300,11 +328,20 @@ export function startLegionClaim(deps: {
300
328
  })
301
329
  }
302
330
 
303
- const booted = boot().catch((error: unknown) => {
304
- if (deps.signal.aborted) return
305
- deps.log(
306
- `claim boot failed before a registration; the daemon's registration deadline relaunches the pane: ${messageFor(error)}`,
307
- )
331
+ // A boot that failed before a registration claims nothing, and says so with a `claimed` that
332
+ // is already settled: a caller waiting on the name is not left waiting for a step that is
333
+ // never coming.
334
+ const started = boot().catch((error: unknown): LegionClaimBoot => {
335
+ if (!deps.signal.aborted) {
336
+ deps.log(
337
+ `claim boot failed before a registration; the daemon's registration deadline relaunches the pane: ${messageFor(error)}`,
338
+ )
339
+ }
340
+ return { claimed: Promise.resolve() }
308
341
  })
309
- return { capability: () => capability, booted }
342
+ return {
343
+ capability: () => capability,
344
+ booted: started.then(() => undefined),
345
+ claimed: started.then((claimBoot) => claimBoot.claimed),
346
+ }
310
347
  }
@@ -165,6 +165,14 @@ export interface PhaseHookDeps {
165
165
  * reminder and the recreated-workspace notice both need the claim, and neither is sent before
166
166
  * one exists. Never rejects. */
167
167
  readonly booted: Promise<void>
168
+ /** A turn of this session has started, whatever started it: the daemon's task, an Envoy
169
+ * delivery, a reminder, a person. The channel server answers it by firing the claim boot's
170
+ * deferred role claim (`startLegionClaim`'s `onFirstTurn`), so the session takes its Envoy
171
+ * name inside a turn that is already running (INFRA-1573). It is called for every
172
+ * `UserPromptSubmit`, and the server decides which of them counts: one before the boot
173
+ * registered its step — the bridge's seeding `/rename` — signals nothing, and one after the
174
+ * name is taken costs nothing. */
175
+ readonly firstTurnStarted: () => void
168
176
  /** The daemon's whole state, for the reminder's record check, aborted with `signal` once the
169
177
  * check's bound passes (`PhaseReminderDeps.readState`). */
170
178
  readonly readState: (signal: AbortSignal) => Promise<LegionState>
@@ -481,6 +489,13 @@ export function createPhaseHookEndpoint(deps: PhaseHookDeps): PhaseHookEndpoint
481
489
  // itself: it is refused, and no state moves, so it cannot zero its own count.
482
490
  if (!parsed.success) return { error: PHASE_HOOK_REFUSAL }
483
491
  const event = parsed.data
492
+ // Before the gate below, and before anything else this endpoint does: the claim's own
493
+ // first-turn signal is not the reminder's business, and a turn is a turn whether or not a
494
+ // claim has registered yet (the bridge's seeding `/rename` turn runs before one has) and
495
+ // whatever role this pane holds, an architect's included. What a prompt before the boot
496
+ // registered its step comes to is the server's to decide, not this endpoint's: it holds
497
+ // the step the signal runs (`src/envoy-channel-server.ts`).
498
+ if (event.event === "UserPromptSubmit") deps.firstTurnStarted()
484
499
  // The same gate as `phaseWorkerSession` in `packages/pi-legion/extensions/legion.ts`: the
485
500
  // machine runs for a phase worker whose claim has booted, and for nobody else. The bridge's
486
501
  // seeding `/rename` turn is what writes the transcript the claim boot waits for
@@ -1,99 +0,0 @@
1
- ---
2
- name: leading-a-work-stream
3
- description: Use when you lead a work stream or team of agents, when an agent asks you to approve, confirm or review its step or pull request, when you want to know the state of the stream, when an agent starts a long project, or when you consider building tooling or a restriction for agents.
4
- ---
5
-
6
- # Leading a work stream
7
-
8
- If this skill disagrees with the code, a command's output or its `--help`, follow those and say which line of this skill is wrong.
9
-
10
- A lead raises the stream's numbers by making its agents faster, and is not a gate: agents waiting on your reply are a queue, and a queue is the stream's largest hidden cost. Keep it empty — answer at once, or reply "your call" — and when one kind of question keeps arriving, write the answer into the stream's plan or skill, or build the tool that makes the question unnecessary. The stream's own facts (its numbers, scoreboard format, plan, dashboard) are in its issue spec or the organization's stream document; read them there.
11
-
12
- In a Legion tree, the daemon's workflow and your role prompt decide who starts a worker, who accepts the work and how it merges. This skill does not change that sequence. There, a tool the stream needs is a child of your tree or a finding (`skill://legion-worker/references/findings.md`), not an agent you start on your own. Why each rule below works: [sources.md](skill://leading-a-work-stream/references/sources.md).
13
-
14
- Once Legion runs a stream, its controller is that stream's lead; there is no separate lead beside it. Hand an idle stream to Legion as one short-lived agent per issue, each with a handoff comment on its issue, and never hand-apply a program taken from a lead's session, because the program's reasons stayed in that session.
15
-
16
- ## What a lead does
17
-
18
- 1. **Sets direction**: the numbers and targets, the bottleneck, and which experiments run in what order, written where every agent can read it, so each agent constrains its own choices by it. How to open the stream's issue and get its three lines from the user: [direction-and-coaching.md](skill://leading-a-work-stream/references/direction-and-coaching.md).
19
- 2. **Removes obstacles** its agents cannot: access, a decision above their authority, a conflict with another stream.
20
- 3. **Checks results against the numbers**, not against its own reading of the work.
21
- 4. **Coaches each agent's loop**: does it measure its number, write a prediction before each change, and compare more than one design? Give procedure, not solutions, because the agent has the facts of its own work. Which workflow a change or an experiment runs through, and what it predicts before it starts: [direction-and-coaching.md](skill://leading-a-work-stream/references/direction-and-coaching.md).
22
- 5. **Makes the stream faster**: finds where agents lose time and changes the skill, tool or step that causes it.
23
- 6. **Proves its facts with a command.** A claim about what exists or what a thing can do rests on a command and its output, not on a reading. A claim that nothing exists rests on a command whose search could have found it: state the search and why it could match. A lead's facts about its own stream are the ones nobody else checks.
24
- 7. **Keeps the stream's record of what each agent accepted.** At each check-in, read it against the agents' issues and open asks. An item that is neither done, in progress, nor an open ask is dropped work. The lead finds its owner and has it recorded at once.
25
-
26
- ## The speed loop
27
-
28
- Arm a reminder that wakes you every 3 hours and run the six-step loop it names: [speed-tick.md](skill://leading-a-work-stream/references/speed-tick.md). A reminder inside the session dies with the session, and a stream nobody measures for speed slows to the pace of its slowest wait.
29
-
30
- ## Dates
31
-
32
- A date is the time the work takes at agent speed, plus only the waits nobody can shorten. Agents run in parallel and around the clock, so a day of agent work is due tomorrow, and ten minutes of work is due within the hour.
33
-
34
- - Each date carries its basis in one line ("about 3 h of work, 2 h of benchmark runs"), so padding is visible.
35
- - A key performance indicator (KPI) is one of the stream's numbers in its issue spec. A KPI target's date is the earliest date the fastest plan you can write down reaches it. Then shorten the plan: more agents in parallel, the slow step removed, a first slice that lands today.
36
- - When a date will slip, say so the moment you know, with the new date and why. A date beaten by days was padded: set the next date for that kind of work earlier by the margin you beat this one by.
37
-
38
- ## What a lead does not do
39
-
40
- - Gate a decision an agent can make. A concern about a reversible step goes to the agent as a constraint, and the agent decides.
41
- - Review every pull request. Peer review and tests are the approval.
42
- - Require a plan, spec or confirmation to be sent to it before an agent acts.
43
- - Ask agents for a report of each decision or step. Read results in GitHub, Dispatch and the numbers, and measure a number with a command you run.
44
- - Ration a shared resource (disk, VMs, compute) by approving each use. Set the limit, and the agents apply it themselves or through a tool.
45
- - Relay messages between agents who can talk directly.
46
- - Give an agent orders specific to its own work (which task to launch, at what size, what to regrade): the agent has the facts of its own work and the lead does not. Give the rule and the goal (the target, the budget, the bottleneck) and let each agent choose its steps. Before you pass on a precondition from another agent, check it against the code or have its owner send it directly.
47
-
48
- ## Decision rights
49
-
50
- A step that is easy to undo is the agent's: it acts and reports to nobody, and you read the result in GitHub, Dispatch and the numbers. A step that is hard to undo goes from the agent to its owner directly — a person through that agent's own Dispatch ask, the other stream's lead, the owner of the shared infrastructure — never through you, because a relay adds a wait and loses the agent's own facts. Which steps fall where: [decision-rights.md](skill://leading-a-work-stream/references/decision-rights.md).
51
-
52
- When an agent asks permission for an easy-to-undo step, reply "your call" and state any constraint it must keep; add no check of your own before it may act. Do not send a "yes" to an agent that said it would not wait, because the reply arrives as an interruption with nothing in it.
53
-
54
- ## Rules reach agents through what they read
55
-
56
- A rule sent only by message reaches the agents online that day, in the lead's paraphrase, and is gone for the next session. Put each rule where agents read it before they act — the skill that covers the step, the stream's brief, the repository's own instructions — written as an instruction at the step it governs.
57
-
58
- Keep one record of the words of the person the stream works for, each quoted with its date and source, and link that quote wherever a text says the person wants something ([user-quotes.md](skill://leading-a-work-stream/references/user-quotes.md)). Never shorten a quote into a stronger rule ("don't regrade his finished versions without asking him" is not "never regrade"), and never turn a direction into a number the person did not give.
59
-
60
- ## Keep every request and wait in Dispatch
61
-
62
- You answer for every request the user gives any of your agents, and for every wait any of them has.
63
-
64
- - **A request from the user goes on a claimed Dispatch issue before work on it starts**: a line in that issue's `open-items.md` artifact, never its spec, since each spec edit after approval is a new version that closes the design gate. Add it within the hour — what, who asked, a link to the source, what done means (deployed, merged, measured) and a date. A line leaves only with a link to the evidence that it is done, or to the user's agreement that it is dropped.
65
- - **Done is delivered and checked: you saw the result yourself** (deployed, merged, measured). Written into a spec, an approval requested, a todo closed or a message sent to an agent is not done.
66
- - **A wait on a person is an open Dispatch ask the moment you know it** — never only a chat question, a note, a peer message, a comment on an answered ask, or a review request, because nobody tracks those. A wait on anything else is an `open-items.md` line naming the blocker, its owner and its link. Keep working on everything else.
67
- - **Every hour, run the stream's Dispatch check,** the command its brief names. **Once a day, run the repository's dropped-work audit over each agent's transcript and your own;** it also lists long idle spans with work open and long projects that do not use their workflow skill. Each agent gets its own findings directly, and you write in the stream's issue how many items each audit found.
68
- - Three more rules of this upkeep — checking a delegated result, a step held back from a hand-over, and what to re-read after a restart — are in [dispatch-upkeep.md](skill://leading-a-work-stream/references/dispatch-upkeep.md).
69
-
70
- ## Plan the day with the team
71
-
72
- Every morning by 09:00 Pacific, you and your agents agree on Envoy what the stream will merge today, and you write that list into the stream's record, checking that each item has an agent that committed to land it; without it each agent optimises its own day and the stream's numbers move by accident. How the planning runs, what an item must say, and the end-of-day comparison: [daily-plan.md](skill://leading-a-work-stream/references/daily-plan.md).
73
-
74
- ## Knowing the state of the stream
75
-
76
- From records you read yourself (GitHub, Dispatch, the numbers), answer: what is the target; what is the actual value now; what is the obstacle, and which one is being worked on; what is the next step and what should it do to the number; when will we know? Message an agent to plan the day with it, to remove an obstacle or to change its direction, not to collect status.
77
-
78
- ## Before you say something is blocked
79
-
80
- **Read the thing itself, not the thing next to it.** Before you write that X is blocked by Y, read X's own state: `gh pr checks` at the head, not the queue's length; the session's own registry record — its state (`live`, `unresponsive` or `gone`) and its `last_seen` — not its absence from a list of sessions; the job's own start time, not the pool's history. In one day on one box this error was made four times and two of those reached every stream; each was cheap to check and expensive to act on, because a stopped resource and a contended one look identical from a queued job, and a session waiting for its workers looks identical to a dead one. `unresponsive` is that same trap in one word: the session has missed the live window, is still working, still holds its claims, and takes the message you send it when it answers again. Only `gone` is a session that ended.
81
-
82
- **A blocker you relay to other streams carries the command that shows it.** Without it, each stream spends a check to disprove it after acting on it.
83
-
84
- **Ask a fresh reviewer, for each claimed cause, to name the command or record that would show it FALSE, and to run it.** A reviewer that reads only the prose confirms a confident wrong cause. The causes that cost most are the ones nobody could falsify, because nobody looked for what would disprove them.
85
-
86
- **Run a watch that names quiet sessions, and let it restart nothing.** A session that dies mid-task stays dead until a person notices: measured at about 7 hours on a day when one credential failure stopped a box, and at 5 minutes or less once a watch existed. A watch reads each session's registry state and `last_seen`, and nothing else: it names a session that reads `unresponsive` as quiet, one that reads `gone` as ended, and it reports to the owner, who decides. Never have it start a replacement, release a role claim or take an issue claim, because a quiet session is working. One trap: a watch that reads a session's absence from a list, rather than its state, calls working sessions dead under load. Test it by making it report something you know is true.
87
-
88
- ## Delegation and tooling
89
-
90
- - Use subagents and peer agents for review, research and skill improvement. Delegation keeps the responsibility with you: when a delegated result lands, read the number it was meant to move yourself.
91
- - When an agent starts a long project, check that it uses the workflow skill for that kind of work and name the skill: the `/sdd` workflow for an engineering project, `building-and-delivering-tasks` for RL task work. That skill's own review steps replace review by the lead.
92
- - When agents keep losing time to the same chore, start an agent to build the tool that removes it. Do not wait to be asked.
93
- - Do not build, file or ask for a restriction, guard or gate against a failure nobody has seen. Fix a real failure at its cause, after it happens.
94
- - When the user asks the stream for an explainer video, you own it: have a subagent make it with the `making-explainer-videos` skill.
95
- - When a problem is named, fix it now — run the audit, apply the label, change the thing — instead of another round of agents agreeing it is a problem. Routing every change through you for review is a slowdown, not safety; the stream's own peer review and tests stay. When a neighbour names a problem, swarm on it rather than file an issue and wait.
96
-
97
- ## Improving this skill
98
-
99
- When a rule here failed or was missing, edit this file directly, and put the evidence in the commit message, so the next lead gets the fix instead of the same failure.
@@ -1,8 +0,0 @@
1
- # Planning the day with the team
2
-
3
- Every morning, by 09:00 Pacific, the lead and its agents agree on Envoy what the stream will merge today, as a working team does at its daily planning: each agent says what it can land and what stands in the way, the team settles the list, and the lead writes it into the stream's record. The lead owns the list and that it is real.
4
-
5
- - Each item starts with the key performance indicator (KPI, one of the stream's numbers) it moves and the change expected, for example "Grade wall time 7,104 s -> 5,700 s: ...", so the day can be checked against the numbers.
6
- - Work that moves no KPI goes on the list only when it unblocks an item that does, and names that item.
7
- - During the day, an agent that will miss an item says so as soon as it knows, so the team can move work.
8
- - At the end of the day, post each item's actual KPI reading next to its prediction in the stream's record, and ask the owner of each missed item on Envoy what blocked it.
@@ -1,6 +0,0 @@
1
- # Decision rights
2
-
3
- | The step | Who decides |
4
- | --- | --- |
5
- | Easy to undo: a code change, a flag, a branch, opening or merging a pull request that passed peer review and tests, a planned experiment, and any spending the workflow itself calls for (a paid-API review, compute, a VM, a model run the task needs) | The agent. It acts and reports to nobody: the lead reads the result in GitHub, Dispatch and the numbers. |
6
- | Hard to undo: deleting data someone else created, a new financial commitment (a contract, a subscription), a message outside the organization, security, another stream's work or shared state | The agent takes it to its owner directly: a person through the agent's own Dispatch ask, the other stream's agent or lead, the owner of the shared infrastructure. It does not pass through the lead. |
@@ -1,13 +0,0 @@
1
- # Setting direction and coaching the loop
2
-
3
- ## The stream's three lines
4
-
5
- Open the stream's issue with three lines above its targets: the problem the stream exists to solve, the one approach it commits to, and what it will not do. Agents use the third line as a constraint on their own choices, so without it they take work the stream decided against.
6
-
7
- Ask the user those three questions once, in one message, each with a draft answer taken from the user's own words. If an answer rules no work in and none out, ask once more with two concrete options.
8
-
9
- ## Coaching an agent's loop
10
-
11
- - An experiment on a number, with a benchmark that runs in minutes, goes through `/autoresearch`: the expected gain is in its notes before each run, and the change is run again before it is kept, so a result that came from noise does not survive.
12
- - Use the `ce-optimize` skill instead when the result is noisy or has several objectives.
13
- - A one-off change still gets its prediction written in the scoreboard before it starts, so a wrong prediction is visible instead of explained away afterwards.
@@ -1,8 +0,0 @@
1
- # Dispatch upkeep: the rest of the lead's rules
2
-
3
- These go with the "Keep every request and wait in Dispatch" section of the skill.
4
-
5
- - **Check a delegated or relayed result against its done before you report it**, because an agent's "done" is often a message sent, not a thing delivered. Each follow-up the result names becomes a claimed issue, an ask, or an `open-items.md` line, the same hour.
6
- - **A step you keep back from a hand-over becomes its own claimed issue,** blocked by the handed-over one, or it is lost when the hand-over closes.
7
- - **An owner whose session reads `unresponsive` has not dropped its work**: it is past the live window and inside the gone horizon, it keeps its issue claim and its role claim, and the message you send it waits for it. Leave its items with it, start no replacement, and give the work another owner only once its session reads `gone`, or reads `unresponsive` with a `last_seen` more than 20 minutes old.
8
- - **After a restart or a compaction, first re-read your claimed issues and your open asks** (`dispatch open-asks`), then the transcript since your last audit, because what you were waiting for is not in the new context.
@@ -1,9 +0,0 @@
1
- # Why these rules
2
-
3
- - Bezos, [2015 shareholder letter](https://www.sec.gov/Archives/edgar/data/1018724/000119312516530910/d168744dex991.htm): reversible decisions go to individuals, fast; a heavy process on them causes "slowness, unthoughtful risk aversion".
4
- - DORA, [Streamlining change approval](https://dora.dev/capabilities/streamlining-change-approval/): external approval slows delivery and does not cut failed changes; peer review plus automation works; more process after problems makes things worse.
5
- - US Army, [ADP 6-0 Mission Command](https://armypubs.army.mil/epubs/DR_pubs/DR_a/ARN47032-ADP_6-0-000-WEB-1.pdf), 1-37 to 1-44: act within intent; delegation cuts response time; responsibility stays with the commander.
6
- - Google re:Work, [research behind great managers](https://rework.withgoogle.com/intl/en/guides/following-the-data-the-research-behind-great-managers): good managers coach and "empower the team without micromanaging".
7
- - Rother & Liker, [A Kata for PDCA](https://cdn.prod.website-files.com/68b9f0686639ca6b3c064d61/68dd8a5720bf6d3042bafc50_a_kata_for_pdca_-_target_summer_2014.pdf), and [LEI, Kata](https://www.lean.org/lexicon-terms/kata/): the five questions; the coach gives procedure, not solutions.
8
- - Reinertsen, [Product Development Flow, ch. 1](http://lpd2.com/wp-content/uploads/2013/06/ReinertsenFLOWChap1.pdf): queues are the largest hidden cost.
9
- - [Summary of Grove's High Output Management](https://www.becausetech.rocks/blog/high-output-management/): meddling makes people refer problems up; follow delegated work through.
@@ -1,44 +0,0 @@
1
- # The speed tick: the 3-hourly loop and a reminder that survives restarts
2
-
3
- ## The loop, on each tick
4
-
5
- 1. Read the stream's state from its records: the numbers, today's plan against what merged, the hourly Dispatch check.
6
- 2. Ask each agent on Envoy what slows it down most right now. Not status.
7
- 3. Answer in writing: how can I help this go faster while the targets and the checks that gate them stay unchanged; how can I do better work faster; how can I help the team do better work faster?
8
- 4. Give the answers to a fresh subagent to attack — is each target ambitious, is each change concrete, is each date padded — and rewrite what it finds weak, because your own answers read better to you than they are.
9
- 5. Make the change now, or start an agent on it.
10
- 6. Append the tick to the stream's speed log (an artifact `speed-log.md` on the stream issue): the time, the change, the number it should move and by how much; on the next tick, what it did.
11
-
12
- ## Arming the reminder
13
-
14
- A reminder inside the session (`sleep` in a background job) dies with the session's processes. A systemd user timer survives them and wakes the session with an Envoy message. Arm it once, from a shell on the machine the session runs on.
15
-
16
- Replace `NAME` with a short name for your stream and `SESSION` with your full session id. The timer below fires at 01, 04, 07, 10, 13, 16, 19 and 22 UTC; change `OnCalendar` for another rhythm.
17
-
18
- ```bash
19
- mkdir -p ~/.config/systemd/user
20
- cat > ~/.config/systemd/user/speed-tick-NAME.service <<'EOF'
21
- [Unit]
22
- Description=Speed tick for NAME's lead
23
-
24
- [Service]
25
- Type=oneshot
26
- ExecStart=<envoy-send-command> SESSION "SPEED TICK: run the six-step loop in leading-a-work-stream references/speed-tick.md now."
27
- EOF
28
- cat > ~/.config/systemd/user/speed-tick-NAME.timer <<'EOF'
29
- [Unit]
30
- Description=Speed tick for NAME's lead, every 3 hours
31
-
32
- [Timer]
33
- OnCalendar=*-*-* 01/3:00:00
34
- Persistent=true
35
-
36
- [Install]
37
- WantedBy=timers.target
38
- EOF
39
- systemctl --user daemon-reload
40
- systemctl --user enable --now speed-tick-NAME.timer
41
- systemctl --user list-timers speed-tick-NAME.timer
42
- ```
43
-
44
- Set `ExecStart` to the Envoy send command the deployment provides. A session that runs where it cannot install a user timer (a pod) arms an equivalent wake-up there, and says in its speed log how.
@@ -1,7 +0,0 @@
1
- # The record of the user's own words
2
-
3
- Keep one record of the words of the person the stream works for, each quoted with its date and source.
4
-
5
- - A skill, brief, spec or message that says that person wants something links the quote. Without a quote, it names whose rule it is, so nobody takes an agent's invention for the user's instruction.
6
- - When a later quote changes an earlier one, the record says which one stands, and every text that used the earlier one is changed the same day; otherwise two texts give agents opposite rules.
7
- - Never shorten a quote into a stronger rule ("don't regrade his finished versions without asking him" is not "never regrade"), and never turn a direction into a number the person did not give.