@sjawhar/claude-envoy 6.14.0 → 6.14.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.
@@ -16,9 +16,6 @@ import {
16
16
  type ConsumerGapNotice,
17
17
  createConsumerDelivery,
18
18
  gapNoticeText,
19
- inboundRestoredNoticeText,
20
- inboundUnavailable,
21
- inboundUnavailableNoticeText,
22
19
  } from "@legion/envoy-client/consumer-delivery"
23
20
  import {
24
21
  createDeliveryDedupe,
@@ -45,6 +42,11 @@ import {
45
42
  SHUTDOWN_SETTLE_MS,
46
43
  } from "@legion/envoy-client/envoy-settings"
47
44
  import { LoggableError, messageFor, natsFailureReason } from "@legion/envoy-client/errors"
45
+ import {
46
+ inboundRestoredNoticeText,
47
+ inboundUnavailable,
48
+ inboundUnavailableNoticeText,
49
+ } from "@legion/envoy-client/inbound-outage"
48
50
  import type { RelayOutage } from "@legion/envoy-client/listener-relay"
49
51
  import { machineID } from "@legion/envoy-client/machine"
50
52
  import { refusedTopicsNoticeText, registerWithRelay } from "@legion/envoy-client/relay-registration"
@@ -80,6 +82,7 @@ import {
80
82
  type EnvoyClient,
81
83
  expandSubscriptionTopics,
82
84
  holderStateOf,
85
+ isBusUnanswered,
83
86
  mayActOnRoleRecord,
84
87
  mergeInterestSources,
85
88
  newClientInstanceID,
@@ -87,6 +90,7 @@ import {
87
90
  type SubscribeResult,
88
91
  } from "@legion/envoy-client/transport"
89
92
  import { findPushedBranchHead, paneHandoffReport } from "@legion/pi-shared/handoff-record"
93
+ import { RoleClaimStoppingError } from "@legion/pi-shared/role-claim-stopping"
90
94
  import { Server } from "@modelcontextprotocol/sdk/server/index.js"
91
95
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
92
96
  import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js"
@@ -116,6 +120,7 @@ import {
116
120
  } from "./channel-topics"
117
121
  import { claudeProjectDirectory, claudeSessionId, configuredValue } from "./claude-session"
118
122
  import { inboundOffChannelSession, serveEnvoyOff } from "./envoy-off"
123
+ import { INBOUND_RESTORED_LINES, INBOUND_UNAVAILABLE_LINES } from "./inbound-outage-lines"
119
124
  import { channelConnectionName, installedPluginVersion } from "./installed-build"
120
125
  import {
121
126
  endPane,
@@ -168,6 +173,7 @@ import {
168
173
  touchStateFile,
169
174
  } from "./session-state"
170
175
  import { type SessionTitle, sessionTitle } from "./session-title"
176
+ import { gatedStderr } from "./stop-gates"
171
177
  import {
172
178
  createUserTurnRouter,
173
179
  type UserTurnRouter,
@@ -310,6 +316,12 @@ export interface ChannelSession {
310
316
  unfollow(topics: readonly string[]): Promise<readonly string[]>
311
317
  /** Persist the role held by an explicit envoy_role_set call, or by the Legion claim. */
312
318
  rememberRole(role: string): Promise<void>
319
+ /**
320
+ * Whether this session's stop has begun: from the server's stop on (`startSignal`), or from
321
+ * `shutdown()`. A role claim made from then on would land after the session's DELETE, with no
322
+ * heartbeat to renew it, so the role tool refuses it.
323
+ */
324
+ stopping(): boolean
313
325
  /**
314
326
  * Sets the one hook the heartbeat runs after it re-establishes this session as its held role's
315
327
  * live holder: `"reclaimed"` when the listener had stopped naming this session and a soft claim
@@ -396,8 +408,10 @@ export interface ChannelSessionOptions {
396
408
  * closed for good stays closed, and the session is told it receives nothing.
397
409
  */
398
410
  readonly reopen?: ReopenConnection
399
- /** Ends a start still waiting for its connection to come back (`flushThroughRedials`): the
400
- * process is stopping. */
411
+ /** Aborted as the process's stop begins: it ends a start still waiting for its connection to
412
+ * come back (`flushThroughRedials`), and from then on the session reads as stopping, so the
413
+ * rest of a start the stop overtook registers, claims, writes and tells nothing (R24 of
414
+ * dispatch://INFRA-3589). */
401
415
  readonly startSignal?: AbortSignal
402
416
  /** How long a deregistration waits for a registration already on the wire (default
403
417
  * `REGISTRATION_SETTLE_MS`), past which the DELETE goes out anyway. The shutdown path spends
@@ -452,9 +466,11 @@ export interface ChannelSessionOptions {
452
466
  readonly pluginName: string
453
467
  }
454
468
 
455
- // The shared tool contract builds schemas from each host's Zod API. Claude's
456
- // server emits JSON Schema with its own Zod but keeps validation canonical. The
457
- // specs are frozen module constants, so each schema is built once per spec.
469
+ // The shared tool contract builds schemas from each host's Zod API. Claude's server builds one
470
+ // schema per spec with its own Zod, and both the JSON Schema it serves (channelToolDefinitions)
471
+ // and the validation of a call (parseArguments) come from that one schema, so every value the
472
+ // schema lists is a value the call takes. The specs are frozen module constants, so each schema
473
+ // is built once per spec.
458
474
  const argumentSchemas = new WeakMap<ToolSpec, z.ZodObject<z.ZodRawShape>>()
459
475
  function argumentsSchema(spec: ToolSpec): z.ZodObject<z.ZodRawShape> {
460
476
  let schema = argumentSchemas.get(spec)
@@ -529,6 +545,10 @@ export async function postDispatchReply(
529
545
  await postDeliveryReply(config, identity.id, delivery, result)
530
546
  }
531
547
 
548
+ /** How the delivery queue's stderr line for a frame whose delivery failed begins; the failure's
549
+ * message follows it (`createChannelDelivery`). */
550
+ export const DELIVERY_FAILED_LINE = "envoy-channel: a delivery failed — "
551
+
532
552
  /**
533
553
  * The Dispatch client a person's message, command, pick or BTW is accepted and read through
534
554
  * (`UserTurnRouterOptions.dispatch`), bounded to `ms`, or undefined while nothing configures
@@ -574,6 +594,13 @@ export function createChannelDelivery(input: {
574
594
  readonly configFile: SessionConfigFile
575
595
  /** What a person's own message, command, pick or BTW becomes; omitted, every frame is a card. */
576
596
  readonly router?: () => UserTurnRouter | undefined
597
+ /** Writes one stderr line of the queue's own: the session's tell gate (`gatedStderr`), so
598
+ * a notice queued before the stop that fails after it says nothing. */
599
+ readonly stderr: (line: string) => void
600
+ /** Whether the session's stop has begun, read when a notice's turn in the queue comes: a
601
+ * notice queued before the stop is shown to nobody once the stop has begun. Omitted, the
602
+ * session never reads as stopping. */
603
+ readonly stopping?: () => boolean
577
604
  }): ChannelDeliveryPath {
578
605
  const inbox: ChannelInboxEntry[] = []
579
606
  let tail = Promise.resolve()
@@ -584,7 +611,7 @@ export function createChannelDelivery(input: {
584
611
  tail = run.then(
585
612
  () => undefined,
586
613
  (error: unknown) => {
587
- process.stderr.write(`envoy-channel: a delivery failed — ${messageFor(error)}\n`)
614
+ input.stderr(`${DELIVERY_FAILED_LINE}${messageFor(error)}\n`)
588
615
  },
589
616
  )
590
617
  return run
@@ -608,7 +635,7 @@ export function createChannelDelivery(input: {
608
635
  // A payload the card could not lay out is shown as the text its sender sent: said here, for
609
636
  // the message the inbox lists the first time, so a copy Envoy sends again says nothing new.
610
637
  if (rendered.payloadShownAsText !== undefined) {
611
- process.stderr.write(
638
+ input.stderr(
612
639
  `envoy-channel: message ${eventId ?? "unknown"}'s payload is shown as its text; the card could not lay it out (${rendered.payloadShownAsText})\n`,
613
640
  )
614
641
  }
@@ -633,7 +660,7 @@ export function createChannelDelivery(input: {
633
660
  // (`./user-turn-router`).
634
661
  const passOverLateBtw = (rendered: RenderInboundResult): boolean => {
635
662
  if (rendered.delivery?.mode !== "btw") return false
636
- process.stderr.write(
663
+ input.stderr(
637
664
  `envoy-channel: passing over late BTW ${rendered.envelope?.event_id ?? "unknown"}: it was asked while this session was not taking messages\n`,
638
665
  )
639
666
  return true
@@ -650,7 +677,7 @@ export function createChannelDelivery(input: {
650
677
  // answered the attempt, and its line says it landed.
651
678
  if (rendered.rejectedDelivery !== undefined) {
652
679
  const rejected = rendered.rejectedDelivery
653
- process.stderr.write(
680
+ input.stderr(
654
681
  `envoy-channel: rejecting malformed Dispatch targeted delivery ${rejected.id}\n`,
655
682
  )
656
683
  return postDispatchReply(input.identity, input.configFile, rejected, {
@@ -658,7 +685,7 @@ export function createChannelDelivery(input: {
658
685
  }).then(
659
686
  () => false,
660
687
  (error: unknown) => {
661
- process.stderr.write(
688
+ input.stderr(
662
689
  error instanceof DispatchWriteLandedError
663
690
  ? `envoy-channel: the report of the rejected delivery landed on Dispatch, which gave no copy of its answer — ${error.message}\n`
664
691
  : `envoy-channel: could not report the rejected delivery to Dispatch — ${messageFor(error)}\n`,
@@ -668,7 +695,7 @@ export function createChannelDelivery(input: {
668
695
  )
669
696
  }
670
697
  if (rendered.malformedDelivery === true) {
671
- process.stderr.write(
698
+ input.stderr(
672
699
  "envoy-channel: dropping malformed Dispatch targeted delivery without a reply address\n",
673
700
  )
674
701
  return tail.then(() => false)
@@ -696,6 +723,7 @@ export function createChannelDelivery(input: {
696
723
  },
697
724
  notice(content, addressed) {
698
725
  return queued(async () => {
726
+ if (input.stopping?.() === true) return
699
727
  if (addressed !== undefined && addressed !== input.identity.id) {
700
728
  throw new Error(
701
729
  `the notice names session ${addressed}, and this process serves ${input.identity.id}`,
@@ -860,15 +888,41 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
860
888
  /** The record the router above reads and writes, kept so a shutdown can wait for its writes
861
889
  * and so the live view can read which Dispatch message a row is (`messageOf`). */
862
890
  let turns: UserTurnState | undefined
891
+ const userTopics = new Set<string>()
892
+ let heldRole: string | undefined
893
+ // Whether this session's stop has begun (R24 of dispatch://INFRA-3589): from the server's
894
+ // `stop()` on, whose abort of `startSignal` comes first and can land while the start still
895
+ // runs, and from `shutdown()` on. Every gate and every control-flow read below takes it.
896
+ let shuttingDown = options.startSignal?.aborted === true
897
+ options.startSignal?.addEventListener(
898
+ "abort",
899
+ () => {
900
+ shuttingDown = true
901
+ },
902
+ { once: true },
903
+ )
904
+ // Whether `shutdown()` has run, which it does once, also where the abort above came first.
905
+ let shutdownStarted = false
906
+ // The stop gates (`./stop-gates`): once the stop has begun, the tell gate drops every notice
907
+ // card (`notice`) and stderr line (`sessionStderr`) of this session's own, and the write gate
908
+ // refuses every role record and ledger entry. Each reads `shuttingDown`. The stop's own lines
909
+ // are written to stderr with no gate (`shutdown`). A relay frame already past
910
+ // `deliverRelayed`'s read is a delivered message, not a notice: it passes no gate.
911
+ const sessionStderr = gatedStderr(() => shuttingDown)
863
912
  const delivery = createChannelDelivery({
864
913
  identity,
865
914
  notifier: options.notifier,
866
915
  configFile: options.configFile,
867
916
  router: () => router,
917
+ stderr: sessionStderr,
918
+ stopping: () => shuttingDown,
868
919
  })
869
- const userTopics = new Set<string>()
870
- let heldRole: string | undefined
871
- let shuttingDown = false
920
+ /** A notice card of Envoy's own (`ChannelDeliveryPath.notice`), through the tell gate: one the
921
+ * gate drops resolves at once, shown to nobody. A notice queued before the stop waits its turn
922
+ * behind the frames queued before it, and the queue reads the stop again when that turn comes
923
+ * (`createChannelDelivery`'s `stopping`). */
924
+ const showNotice = (content: string, addressed?: string): Promise<void> =>
925
+ shuttingDown ? Promise.resolve() : delivery.notice(content, addressed)
872
926
  const handoffFile =
873
927
  options.handoffPid === undefined
874
928
  ? undefined
@@ -944,8 +998,8 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
944
998
  * messages the session was shown, which the session itself must know of.
945
999
  */
946
1000
  const tellGapNotice = (notice: ConsumerGapNotice): void => {
947
- delivery.notice(gapNoticeText(notice)).catch((error: unknown) => {
948
- process.stderr.write(
1001
+ showNotice(gapNoticeText(notice)).catch((error: unknown) => {
1002
+ sessionStderr(
949
1003
  `envoy-channel: ${notice.message} (the session could not be told — ${messageFor(error)})\n`,
950
1004
  )
951
1005
  })
@@ -973,14 +1027,14 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
973
1027
  // as a notice that could not be shown, and nothing is carded to a conversation the
974
1028
  // message was never sent to.
975
1029
  showFailureNotice: (addressed, notice) =>
976
- delivery.notice(envoyNoticeText(failureNoticeFields(notice)), addressed),
1030
+ showNotice(envoyNoticeText(failureNoticeFields(notice)), addressed),
977
1031
  failureNoticeFailed: (notice, error) => {
978
- process.stderr.write(
1032
+ sessionStderr(
979
1033
  `envoy-channel: message ${notice.eventId} from ${notice.sender} was not shown, nor was the notice naming it — ${messageFor(error)}\n`,
980
1034
  )
981
1035
  },
982
1036
  log: (message, error) => {
983
- process.stderr.write(
1037
+ sessionStderr(
984
1038
  `envoy-channel: ${message}${error === undefined ? "" : ` — ${messageFor(error)}`}\n`,
985
1039
  )
986
1040
  },
@@ -998,7 +1052,7 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
998
1052
  const sessionId = identity.id
999
1053
  const file = replayStateFile(options.stateDirectory, sessionId)
1000
1054
  const snapshot = await readReplayState(file).catch((error: unknown): ReplayStateFile => {
1001
- process.stderr.write(
1055
+ sessionStderr(
1002
1056
  `envoy-channel: could not read the delivery state (${messageFor(error)}); this session's record starts over\n`,
1003
1057
  )
1004
1058
  return { ledger: [] }
@@ -1024,7 +1078,7 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1024
1078
  if (options.router === undefined) return
1025
1079
  const file = userTurnStateFile(options.stateDirectory, identity.id)
1026
1080
  const restored = await readUserTurnState(file).catch((error: unknown) => {
1027
- process.stderr.write(
1081
+ sessionStderr(
1028
1082
  `envoy-channel: could not read this session's record of the messages it took (${messageFor(error)}); its messages arrive as cards\n`,
1029
1083
  )
1030
1084
  return undefined
@@ -1143,7 +1197,7 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1143
1197
  deliver: (frame) => deliverRelayed(owner, frame),
1144
1198
  gap: tellGapNotice,
1145
1199
  log: (message, error) => {
1146
- process.stderr.write(
1200
+ sessionStderr(
1147
1201
  `envoy-channel: ${message}${error === undefined ? "" : ` — ${messageFor(error)}`}\n`,
1148
1202
  )
1149
1203
  },
@@ -1154,7 +1208,7 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1154
1208
  persist: (snapshot) => {
1155
1209
  if (relay !== owner) return false
1156
1210
  state.consumer(snapshot).catch((error: unknown) => {
1157
- process.stderr.write(
1211
+ sessionStderr(
1158
1212
  `envoy-channel: could not persist the consumer delivery state — ${messageFor(error)}\n`,
1159
1213
  )
1160
1214
  })
@@ -1207,7 +1261,7 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1207
1261
  owner.delivery.receive(message)
1208
1262
  }
1209
1263
  } catch (error) {
1210
- process.stderr.write(
1264
+ sessionStderr(
1211
1265
  `envoy-channel: the relay subscription of ${owner.sessionID} stopped — ${natsFailureReason(error)}\n`,
1212
1266
  )
1213
1267
  if (owner.subscription !== subscription) return
@@ -1286,7 +1340,9 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1286
1340
  if (shuttingDown || relay === undefined) return
1287
1341
  relay.delivery.beginEpoch()
1288
1342
  serialized(register).catch((error: unknown) => {
1289
- process.stderr.write(
1343
+ // A registration that fails once the stop has begun is retried by no heartbeat.
1344
+ if (shuttingDown) return
1345
+ sessionStderr(
1290
1346
  `envoy-channel: could not register again after a reconnect (${messageFor(error)}); the next heartbeat retries\n`,
1291
1347
  )
1292
1348
  })
@@ -1315,10 +1371,16 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1315
1371
  // flight at that moment adds them back; removing them again behind it undoes
1316
1372
  // that. A failure here is not retried by name: the heartbeat's own interest
1317
1373
  // reconciliation (below) brings the entry back in line with what this session
1318
- // actually follows, whatever caused the drift.
1374
+ // actually follows, whatever caused the drift, and its registration sets the
1375
+ // consumer's filter to the topics the entry holds. The listener's message bus
1376
+ // can fail to answer after the entry was written, when only the update of the
1377
+ // consumer's filter met a NATS reconnect, so that outage is not reported as a
1378
+ // removal that did not happen.
1319
1379
  dropFromTopicsAndRegistry(topics).catch((error: unknown) => {
1320
- process.stderr.write(
1321
- `envoy-channel: could not drop a removed subscription from the registry — ${messageFor(error)}; the next heartbeat reconciles it\n`,
1380
+ sessionStderr(
1381
+ isBusUnanswered(error)
1382
+ ? `envoy-channel: the listener's message bus did not answer a request to drop a removed subscription from the registry — ${messageFor(error)}; the registry may already be without it, and the next heartbeat reconciles the registry and sets the consumer's filter to the topics it holds\n`
1383
+ : `envoy-channel: could not drop a removed subscription from the registry — ${messageFor(error)}; the next heartbeat reconciles it\n`,
1322
1384
  )
1323
1385
  })
1324
1386
  }
@@ -1357,37 +1419,37 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1357
1419
  }
1358
1420
 
1359
1421
  /**
1360
- * Said once per outage: the listener refused this session's registration, so it has no consumer
1361
- * and receives nothing. The session still runs, and the heartbeat registers again every tick
1362
- * until one is accepted; the reason is the listener's own, one of those
1363
- * `ErrorWireSchema.reason` lists (`@legion/envoy-client`'s `transport.ts`), which the error
1364
- * carries in its message and which `inboundUnavailableNoticeText` words for every host. The
1365
- * accepted registration that ends the outage is said too, or the session would read itself as
1366
- * deaf after it recovered. Neither is said once shutdown has begun: a registration still on the
1367
- * wire as the session leaves is no outage of a running session.
1422
+ * Said once per outage: the listener refused this session's registration or may not have
1423
+ * recorded it, or the session holds no relay subject. The session still runs, and the heartbeat
1424
+ * registers again every tick until one is accepted. The outage's kind (`InboundOutageKind`,
1425
+ * which says what each kind means for what reaches the session) picks the stderr line
1426
+ * (`INBOUND_UNAVAILABLE_LINES`), and `inboundUnavailableNoticeText` words the notice card for
1427
+ * every host. An accepted registration after a told outage tells the session once, by the same
1428
+ * path, worded for the kind of the last outage it was told (`INBOUND_RESTORED_LINES`). A session
1429
+ * whose shutdown has begun is told neither (`stopping`): the shutdown closed the relay on
1430
+ * purpose, and the record is deleted next.
1368
1431
  */
1369
1432
  const inboundOutage = inboundUnavailable(
1370
- (why) => {
1371
- if (shuttingDown) return
1372
- process.stderr.write(
1373
- `envoy-channel: this session receives nothing (${why}); registering again every heartbeat\n`,
1374
- )
1375
- delivery.notice(inboundUnavailableNoticeText(why)).catch((noticeError: unknown) => {
1376
- process.stderr.write(
1377
- `envoy-channel: the session could not be told that it receives nothing — ${messageFor(noticeError)}\n`,
1433
+ (outage) => {
1434
+ const { line, told } = INBOUND_UNAVAILABLE_LINES[outage.kind]
1435
+ sessionStderr(line(outage.why))
1436
+ showNotice(inboundUnavailableNoticeText(outage)).catch((noticeError: unknown) => {
1437
+ sessionStderr(
1438
+ `envoy-channel: the session could not be told ${told} — ${messageFor(noticeError)}\n`,
1378
1439
  )
1379
1440
  })
1380
1441
  },
1381
- () => {
1382
- if (shuttingDown) return
1383
- process.stderr.write(
1384
- "envoy-channel: this session receives again: its registration was accepted\n",
1385
- )
1386
- delivery.notice(inboundRestoredNoticeText()).catch((noticeError: unknown) => {
1387
- process.stderr.write(
1388
- `envoy-channel: the session could not be told that it receives again — ${messageFor(noticeError)}\n`,
1389
- )
1390
- })
1442
+ {
1443
+ restored: ({ kind }) => {
1444
+ const { line, told } = INBOUND_RESTORED_LINES[kind]
1445
+ sessionStderr(line)
1446
+ showNotice(inboundRestoredNoticeText(kind)).catch((noticeError: unknown) => {
1447
+ sessionStderr(
1448
+ `envoy-channel: the session could not be told ${told} — ${messageFor(noticeError)}\n`,
1449
+ )
1450
+ })
1451
+ },
1452
+ stopping: () => shuttingDown,
1391
1453
  },
1392
1454
  )
1393
1455
  // A relay socket's refused trade is this session's outage too, told once with its
@@ -1406,6 +1468,13 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1406
1468
  * this session (`registrationTopics`), taken by the relay as followed first, the relay's
1407
1469
  * delivery request, the outage told once, and the answer's consumer taken
1408
1470
  * (`takeDeliveryAnswer`).
1471
+ *
1472
+ * A stopping session registers nothing (R24 of dispatch://INFRA-3589). Its shutdown closes the
1473
+ * relay on purpose and deletes the record next, so a registration the chain still holds when the
1474
+ * stop begins has nothing to ask for. It returns at once: made, it would find no relay subject
1475
+ * and be refused, which would only report an outage that the stop made on purpose. A
1476
+ * registration already on the wire when the stop begins is not sent again (`stopping`): a
1477
+ * project refusal answered after that drops no topic, and the session is not told of it.
1409
1478
  */
1410
1479
  const register = async (): Promise<void> => {
1411
1480
  // Nothing registers once shutdown has begun: a registration queued before it would find the
@@ -1428,10 +1497,12 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1428
1497
  options.handoffFlushTimeoutMs ?? HANDOFF_FLUSH_TIMEOUT_MS,
1429
1498
  "flushing NATS",
1430
1499
  ).catch((error: unknown) => {
1431
- process.stderr.write(
1500
+ sessionStderr(
1432
1501
  `envoy-channel: could not confirm the relay subscription of ${identity.id} — ${natsFailureReason(error)}\n`,
1433
1502
  )
1434
1503
  })
1504
+ // A stop that began during the handoff's waits registers nothing either.
1505
+ if (shuttingDown) return
1435
1506
  }
1436
1507
  const title = options.title?.(identity.id) ?? ""
1437
1508
  if (
@@ -1447,7 +1518,7 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1447
1518
  // Said once per failure run: every heartbeat retries it.
1448
1519
  if (!stampFailureReported) {
1449
1520
  stampFailureReported = true
1450
- process.stderr.write(
1521
+ sessionStderr(
1451
1522
  `envoy-channel: could not write the session title for the dispatch command (${messageFor(error)}); retrying every heartbeat, and the command names this session by its id\n`,
1452
1523
  )
1453
1524
  }
@@ -1500,8 +1571,12 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1500
1571
  return registering
1501
1572
  },
1502
1573
  // A registration the listener refused, for any of the reasons `ErrorWireSchema.reason`
1503
- // lists, leaves the session with no consumer at all, as every other failed registration
1504
- // does: the session is told once and the heartbeat asks again.
1574
+ // lists, leaves the session with no consumer at all: the session is told once, at once, and
1575
+ // the heartbeat asks again. A registration the bus-outage 503 answered (`isBusUnanswered`)
1576
+ // is not recorded for certain, but its consumer may still deliver. That failure is held
1577
+ // for the bound first (`INBOUND_FIRST_OPEN_BOUND_MS`): the session is told once only when
1578
+ // such a failure comes at or after the bound's end, and an accepted registration inside
1579
+ // the bound ends the hold with nothing said.
1505
1580
  answered: (result) => {
1506
1581
  if (asking !== undefined) takeDeliveryAnswer(sessionID, asking, result)
1507
1582
  },
@@ -1514,18 +1589,18 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1514
1589
  for (const topic of topics) userTopics.delete(topic)
1515
1590
  followedTopics.unfollow(topics)
1516
1591
  ledger.followedChanged().catch((error: unknown) => {
1517
- process.stderr.write(
1592
+ sessionStderr(
1518
1593
  `envoy-channel: the topics the listener refused stay in the delivery state until it is written next — ${messageFor(error)}\n`,
1519
1594
  )
1520
1595
  })
1521
- if (shuttingDown) return
1522
- delivery.notice(refusedTopicsNoticeText(topics, reason)).catch((noticeError: unknown) => {
1523
- process.stderr.write(
1596
+ showNotice(refusedTopicsNoticeText(topics, reason)).catch((noticeError: unknown) => {
1597
+ sessionStderr(
1524
1598
  `envoy-channel: the session could not be told which topics the listener refused — ${messageFor(noticeError)}\n`,
1525
1599
  )
1526
1600
  })
1527
1601
  },
1528
- log: (line) => process.stderr.write(`envoy-channel: ${line}\n`),
1602
+ log: (line) => sessionStderr(`envoy-channel: ${line}\n`),
1603
+ stopping: () => shuttingDown,
1529
1604
  })
1530
1605
  }
1531
1606
 
@@ -1534,13 +1609,26 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1534
1609
  * `claude` reading the same state directory — one that resumed this session id — tells its own
1535
1610
  * record from this one's. The destination is the caller's, because `restoreRole` resolves it
1536
1611
  * before it removes the predecessor's file while the record's `session_id` is read after.
1612
+ *
1613
+ * Every role record write goes through the write gate (R24 of dispatch://INFRA-3589): this, the
1614
+ * removal of a record (`removeRoleRecord`) and the touch of one (`refreshRoleRecord`) read it
1615
+ * as they start, so once the stop has begun no record is written, removed or touched, also
1616
+ * where the stop began during a removal just before.
1537
1617
  */
1538
- const writeRoleRecord = (file: string, role: string): Promise<void> =>
1539
- writePersistedRole(file, {
1618
+ const writeRoleRecord = async (file: string, role: string): Promise<void> => {
1619
+ if (shuttingDown) return
1620
+ await writePersistedRole(file, {
1540
1621
  session_id: identity.id,
1541
1622
  role,
1542
1623
  client_instance_id: options.clientInstanceID,
1543
1624
  })
1625
+ }
1626
+
1627
+ /** Removes the role record `file`, through the write gate (`writeRoleRecord`). */
1628
+ const removeRoleRecord = async (file: string): Promise<void> => {
1629
+ if (shuttingDown) return
1630
+ await rm(file, { force: true })
1631
+ }
1544
1632
 
1545
1633
  /**
1546
1634
  * The id whose role record is still to be taken back, read by `transferRole` on every
@@ -1559,7 +1647,9 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1559
1647
  *
1560
1648
  * Answers `"pending"` when the role is still to be taken back from that id and only time
1561
1649
  * decides it, `"settled"` when nothing more is to be asked of that record. The caller keeps
1562
- * the retry: a restore writes none of its own.
1650
+ * the retry: a restore writes none of its own. Once the shutdown has begun, it sends no claim
1651
+ * and changes no record, and answers `"pending"`, so the transfer stays as it was (R24 of
1652
+ * dispatch://INFRA-3589).
1563
1653
  *
1564
1654
  * A record another process wrote is pressed only while this process holds no role
1565
1655
  * (`mayActOnRoleRecord`, the one rule both clients read). One state directory is read by two
@@ -1588,6 +1678,7 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1588
1678
  const restoreRole = async (previousSessionID: string): Promise<"settled" | "pending"> => {
1589
1679
  const previousFile = roleStateFile(options.stateDirectory, previousSessionID)
1590
1680
  const persisted = await readPersistedRole(previousFile)
1681
+ if (shuttingDown) return "pending"
1591
1682
  if (persisted === undefined) return "settled"
1592
1683
  if (
1593
1684
  !mayActOnRoleRecord(
@@ -1606,15 +1697,17 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1606
1697
  previousSessionID: persisted.session_id,
1607
1698
  clientInstanceID: options.clientInstanceID,
1608
1699
  })
1700
+ // A claim answered after the shutdown began changes nothing here, granted or not.
1701
+ if (shuttingDown) return "pending"
1609
1702
  if (!claim.claimed) {
1610
1703
  if (claim.holder === identity.id) return "pending"
1611
- if (claim.holder !== persisted.session_id) await rm(previousFile, { force: true })
1704
+ if (claim.holder !== persisted.session_id) await removeRoleRecord(previousFile)
1612
1705
  return "settled"
1613
1706
  }
1614
1707
  logRoleClaimWarnings(warnOnStderr, persisted.role, sessionID, claim.warnings)
1615
1708
  heldRole = persisted.role
1616
1709
  const currentFile = roleStateFile(options.stateDirectory, identity.id)
1617
- if (previousFile !== currentFile) await rm(previousFile, { force: true })
1710
+ if (previousFile !== currentFile) await removeRoleRecord(previousFile)
1618
1711
  await writeRoleRecord(currentFile, persisted.role)
1619
1712
  return "settled"
1620
1713
  }
@@ -1628,7 +1721,7 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1628
1721
  void Promise.resolve()
1629
1722
  .then(() => hook(role, reason))
1630
1723
  .catch((error: unknown) => {
1631
- process.stderr.write(
1724
+ sessionStderr(
1632
1725
  `envoy-channel: role ${role} regain hook failed (${reason}) — ${messageFor(error)}\n`,
1633
1726
  )
1634
1727
  })
@@ -1648,6 +1741,8 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1648
1741
  * the record it could not touch is still there to restore from until the sweep's age.
1649
1742
  */
1650
1743
  const refreshRoleRecord = async (): Promise<void> => {
1744
+ // Through the write gate (`writeRoleRecord`): a stopping session touches no record.
1745
+ if (shuttingDown) return
1651
1746
  const roleFile = roleStateFile(options.stateDirectory, identity.id)
1652
1747
  try {
1653
1748
  await touchStateFile(roleFile)
@@ -1656,7 +1751,7 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1656
1751
  // Said once per failure run: every heartbeat retries it.
1657
1752
  if (!roleRefreshFailureReported) {
1658
1753
  roleRefreshFailureReported = true
1659
- process.stderr.write(
1754
+ sessionStderr(
1660
1755
  `envoy-channel: could not refresh the role record ${roleFile} (${messageFor(error)}); retrying every heartbeat\n`,
1661
1756
  )
1662
1757
  }
@@ -1680,14 +1775,19 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1680
1775
  * the moment that process stops renewing it; the role and its record stay, and the next
1681
1776
  * heartbeat asks again. The record's mtime is refreshed as it is on a confirmed holder, so the
1682
1777
  * age sweep never expires a record this process is still pressing a claim for.
1778
+ *
1779
+ * A shutdown that begins during the read or the claim ends the re-assertion there (R24 of
1780
+ * dispatch://INFRA-3589): no claim goes out after it, no record changes, and no regain hook
1781
+ * runs, since the DELETE follows and no heartbeat renews what this would do.
1683
1782
  */
1684
1783
  const reassertRole = async (afterOutage: boolean): Promise<void> => {
1685
1784
  if (heldRole === undefined) return
1686
1785
  const role = heldRole
1687
1786
  const holding = await options.client.getRole(role).catch(undefinedOnNotFound)
1787
+ if (shuttingDown) return
1688
1788
  if (roleHeldBy(holding, identity.id, options.clientInstanceID)) {
1689
1789
  await refreshRoleRecord()
1690
- if (afterOutage) fireRegained(role, "reregistered")
1790
+ if (afterOutage && !shuttingDown) fireRegained(role, "reregistered")
1691
1791
  return
1692
1792
  }
1693
1793
  const sessionID = identity.id
@@ -1697,10 +1797,11 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1697
1797
  soft: true,
1698
1798
  clientInstanceID: options.clientInstanceID,
1699
1799
  })
1800
+ if (shuttingDown) return
1700
1801
  if (!result.claimed) {
1701
1802
  if (result.holder !== identity.id) {
1702
1803
  heldRole = undefined
1703
- await rm(roleStateFile(options.stateDirectory, identity.id), { force: true })
1804
+ await removeRoleRecord(roleStateFile(options.stateDirectory, identity.id))
1704
1805
  return
1705
1806
  }
1706
1807
  await refreshRoleRecord()
@@ -1729,11 +1830,12 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1729
1830
  roleTransferFrom = (await restoreRole(from)) === "pending" ? from : undefined
1730
1831
  roleTransferFailureReported = false
1731
1832
  } catch (error) {
1732
- // `roleTransferFrom` is untouched, so the next heartbeat asks again.
1833
+ // A failure once the shutdown has begun is said nowhere (the tell gate): no heartbeat
1834
+ // retries it. `roleTransferFrom` is untouched, so the next heartbeat asks again.
1733
1835
  // Said once per failure run.
1734
1836
  if (!roleTransferFailureReported) {
1735
1837
  roleTransferFailureReported = true
1736
- process.stderr.write(
1838
+ sessionStderr(
1737
1839
  `envoy-channel: could not take back the role held by ${from} (${messageFor(error)}); retrying every heartbeat\n`,
1738
1840
  )
1739
1841
  }
@@ -1780,6 +1882,13 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1780
1882
  options.handoffFlushTimeoutMs ?? HANDOFF_FLUSH_TIMEOUT_MS,
1781
1883
  "flushing NATS",
1782
1884
  )
1885
+ // A stop that began during the flush ends the handoff here (R24 of dispatch://INFRA-3589):
1886
+ // the identity stays the old id, which the stop's own DELETE removes, and nothing is
1887
+ // deleted, registered or said for the new one.
1888
+ if (shuttingDown) {
1889
+ followedTopics.unfollow([nextSubject])
1890
+ return
1891
+ }
1783
1892
  // The old id's own registration first: one still on the wire writes the record back after
1784
1893
  // this DELETE, and the id Claude Code has left stays registered with nothing heartbeating
1785
1894
  // it.
@@ -1791,6 +1900,13 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1791
1900
  followedTopics.unfollow([nextSubject])
1792
1901
  throw error
1793
1902
  }
1903
+ // A stop that began while the old id's DELETE waited is read here too. That DELETE removed
1904
+ // the record of the id the identity still names, which is what the stop's own DELETE does,
1905
+ // and the handoff moves nothing more.
1906
+ if (shuttingDown) {
1907
+ followedTopics.unfollow([nextSubject])
1908
+ return
1909
+ }
1794
1910
  identity.set(next)
1795
1911
  options.adopted?.(previous, next)
1796
1912
  // The last call for the old id has been made (its deregistration above; the role moves to
@@ -1812,7 +1928,7 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1812
1928
  roleTransferFrom ??= previous
1813
1929
  await register()
1814
1930
  await transferRole()
1815
- process.stderr.write(`envoy: session id changed ${previous} -> ${next}; re-registered\n`)
1931
+ sessionStderr(`envoy: session id changed ${previous} -> ${next}; re-registered\n`)
1816
1932
  }
1817
1933
 
1818
1934
  /** Set by the first read `syncRegisteredInterests` completes, never cleared. */
@@ -1927,6 +2043,10 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1927
2043
  heartbeatInFlight = true
1928
2044
  try {
1929
2045
  await serialized(async () => {
2046
+ // A tick the chain held until the stop began does nothing: the DELETE follows it, so it
2047
+ // has no registration to refresh and no role to assert or take back for a session that is
2048
+ // going.
2049
+ if (shuttingDown) return
1930
2050
  await adoptHandoff()
1931
2051
  // A relay subscription that ended with an error of its own is taken again first, so this
1932
2052
  // registration asks for it.
@@ -1939,9 +2059,12 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1939
2059
  }
1940
2060
  // A body the chain held while shutdown began writes no role: `register` returned without
1941
2061
  // registering, and a role write the chain still holds past the shutdown's bounded wait
1942
- // would land after the DELETE.
2062
+ // would land after the DELETE. A shutdown that begins later, while a role step waits on
2063
+ // the listener, is read after each wait (`reassertRole`, `restoreRole`) and between the
2064
+ // steps, so no role write follows it.
1943
2065
  if (shuttingDown) return
1944
2066
  await reassertRole(registrationFailed)
2067
+ if (shuttingDown) return
1945
2068
  await transferRole()
1946
2069
  await syncRegisteredInterests()
1947
2070
  })
@@ -1951,6 +2074,9 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1951
2074
  // would refresh is fresh now, and a listener that is still slow is owed nothing.
1952
2075
  clearRetry()
1953
2076
  } catch (error) {
2077
+ // A tick that fails once the stop has begun is no outage: no heartbeat follows it, and the
2078
+ // DELETE does, so the line would promise a retry that never comes.
2079
+ if (shuttingDown) return
1954
2080
  // The extra call this failure buys, armed only from an interval tick: a retry that fails
1955
2081
  // is followed by the next tick, not by a second retry, so a listener that keeps refusing
1956
2082
  // sees one extra call per interval and no more. A handoff that unregistered the old id and
@@ -1964,7 +2090,7 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1964
2090
  retryIn === undefined
1965
2091
  ? "retrying at the next heartbeat"
1966
2092
  : `retrying once in ${Math.round(retryIn / 1000)} s, then every heartbeat`
1967
- process.stderr.write(
2093
+ sessionStderr(
1968
2094
  `envoy-channel: registry heartbeat failed (${messageFor(error)}); ${retrying}\n`,
1969
2095
  )
1970
2096
  } finally {
@@ -2018,7 +2144,7 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
2018
2144
  // `interestsRead` false, so the heartbeat retries the adopt and never
2019
2145
  // subtracts against a set this read could not populate.
2020
2146
  await syncRegisteredInterests().catch((error: unknown) => {
2021
- process.stderr.write(
2147
+ sessionStderr(
2022
2148
  `envoy-channel: could not read the registered interests (${messageFor(error)}); the next heartbeat retries\n`,
2023
2149
  )
2024
2150
  })
@@ -2046,7 +2172,7 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
2046
2172
  // asks again, and `registrationFailed` makes the first accepted one a regain of the role.
2047
2173
  await register().catch((error: unknown) => {
2048
2174
  registrationFailed = true
2049
- process.stderr.write(
2175
+ sessionStderr(
2050
2176
  `envoy-channel: the first registration failed (${messageFor(error)}); the next heartbeat retries\n`,
2051
2177
  )
2052
2178
  })
@@ -2071,15 +2197,13 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
2071
2197
  roleTransferFrom = (await restoreRole(identity.id)) === "pending" ? identity.id : undefined
2072
2198
  } catch (error) {
2073
2199
  if (error instanceof UnparseableRoleRecordError) {
2074
- process.stderr.write(
2075
- `envoy-channel: ${messageFor(error)}; the session starts without a role\n`,
2076
- )
2200
+ sessionStderr(`envoy-channel: ${messageFor(error)}; the session starts without a role\n`)
2077
2201
  } else {
2078
2202
  roleTransferFrom = identity.id
2079
2203
  // This is the first failure of the run `transferRole` reports, so it says nothing more
2080
2204
  // until the retry has succeeded once.
2081
2205
  roleTransferFailureReported = true
2082
- process.stderr.write(
2206
+ sessionStderr(
2083
2207
  `envoy-channel: could not restore the role (${messageFor(error)}); the next heartbeat retries\n`,
2084
2208
  )
2085
2209
  }
@@ -2090,7 +2214,9 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
2090
2214
  // here would take the session's whole channel down over a dead pid's handoff, a cosmetic title
2091
2215
  // or a role the session can restore anyway. Everything else this state adds degrades the same
2092
2216
  // way — the reader swallows a failed read, the hook always exits 0 — and a directory this run
2093
- // could not sweep is swept by the next session that starts.
2217
+ // could not sweep is swept by the next session that starts. A start the stop overtook sweeps
2218
+ // nothing: the role sweep removes role records, which the write gate refuses once the stop
2219
+ // has begun, and the next session sweeps the rest.
2094
2220
  for (const prune of [
2095
2221
  () => pruneStaleSessionHandoffs(options.stateDirectory),
2096
2222
  () => pruneStaleSessionTitles(options.stateDirectory),
@@ -2098,10 +2224,9 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
2098
2224
  // The role sweep is told whose session this is: see `pruneStaleSessionRoles`.
2099
2225
  () => pruneStaleSessionRoles(options.stateDirectory, identity.id),
2100
2226
  ]) {
2227
+ if (shuttingDown) break
2101
2228
  await prune().catch((error: unknown) => {
2102
- process.stderr.write(
2103
- `envoy-channel: could not prune stale session state (${messageFor(error)})\n`,
2104
- )
2229
+ sessionStderr(`envoy-channel: could not prune stale session state (${messageFor(error)})\n`)
2105
2230
  })
2106
2231
  }
2107
2232
  const heartbeatTimer = setInterval(() => {
@@ -2139,7 +2264,7 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
2139
2264
  connectionLost = { closeError, dialError: undefined }
2140
2265
  // Ended with its connection: nothing is relayed until a new one takes the subject again.
2141
2266
  if (relay !== undefined) relay.subscription = undefined
2142
- process.stderr.write(
2267
+ sessionStderr(
2143
2268
  `envoy-channel: the NATS connection closed for good (${lostConnectionReason(connectionLost)}); ${options.reopen === undefined ? "nothing dials a new one" : "dialing a new one"}\n`,
2144
2269
  )
2145
2270
  // Refused now rather than at the next heartbeat, since the session receives nothing from this
@@ -2182,9 +2307,9 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
2182
2307
  lost.dialError = dialError
2183
2308
  })
2184
2309
  } catch (error) {
2185
- if (shuttingDown || options.startSignal?.aborted === true) return
2310
+ if (shuttingDown) return
2186
2311
  lost.dialError = error
2187
- process.stderr.write(
2312
+ sessionStderr(
2188
2313
  `envoy-channel: gave up opening a new NATS connection (${natsFailureReason(error)}); dialing again at the next heartbeat\n`,
2189
2314
  )
2190
2315
  return
@@ -2209,7 +2334,7 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
2209
2334
  options.handoffFlushTimeoutMs ?? HANDOFF_FLUSH_TIMEOUT_MS,
2210
2335
  "flushing NATS",
2211
2336
  ).catch((error: unknown) => {
2212
- process.stderr.write(
2337
+ sessionStderr(
2213
2338
  `envoy-channel: could not confirm the relay subscription on the new NATS connection — ${natsFailureReason(error)}\n`,
2214
2339
  )
2215
2340
  })
@@ -2220,7 +2345,7 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
2220
2345
  await register()
2221
2346
  }).catch((error: unknown) => {
2222
2347
  registrationFailed = true
2223
- process.stderr.write(
2348
+ sessionStderr(
2224
2349
  `envoy-channel: could not register on the new NATS connection (${messageFor(error)}); the next heartbeat retries\n`,
2225
2350
  )
2226
2351
  })
@@ -2244,7 +2369,7 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
2244
2369
  renewRelayEpoch()
2245
2370
  }
2246
2371
  } catch (error) {
2247
- process.stderr.write(
2372
+ sessionStderr(
2248
2373
  `envoy-channel: the NATS connection's status reader failed — ${natsFailureReason(error)}\n`,
2249
2374
  )
2250
2375
  }
@@ -2288,6 +2413,10 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
2288
2413
  return fresh
2289
2414
  },
2290
2415
  async unfollow(topics) {
2416
+ // A stopping session drops no topic, as it follows none (R24 of dispatch://INFRA-3589): the
2417
+ // stop deletes the session's record next, so nothing is taken out of it, here or in the
2418
+ // ledger.
2419
+ if (shuttingDown) return []
2291
2420
  const requested = topics.length === 0 ? [...userTopics] : expandSubscriptionTopics(topics)
2292
2421
  const removed = requested.filter((topic) => userTopics.delete(topic))
2293
2422
  if (removed.length === 0) return []
@@ -2304,7 +2433,9 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
2304
2433
  if (shuttingDown) return
2305
2434
  // The same path a reconnect takes: one more registration, behind whatever is queued.
2306
2435
  serialized(register).catch((error: unknown) => {
2307
- process.stderr.write(
2436
+ // A registration that fails once the stop has begun is retried by no heartbeat.
2437
+ if (shuttingDown) return
2438
+ sessionStderr(
2308
2439
  `envoy-channel: could not advertise this session's delivery modes (${messageFor(error)}); the next heartbeat retries\n`,
2309
2440
  )
2310
2441
  })
@@ -2317,12 +2448,19 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
2317
2448
  },
2318
2449
  async rememberRole(role) {
2319
2450
  await serialized(async () => {
2451
+ // A stopping session keeps no role (the write gate): a claim the listener granted after
2452
+ // the stop began is not held here and leaves no record, as `envoy_role_set` keeps none.
2453
+ if (shuttingDown) return
2320
2454
  heldRole = role
2321
2455
  await writeRoleRecord(roleStateFile(options.stateDirectory, identity.id), role)
2322
2456
  })
2323
2457
  },
2458
+ stopping() {
2459
+ return shuttingDown
2460
+ },
2324
2461
  async shutdown() {
2325
- if (shuttingDown) return
2462
+ if (shutdownStarted) return
2463
+ shutdownStarted = true
2326
2464
  shuttingDown = true
2327
2465
  clearInterval(heartbeatTimer)
2328
2466
  // The extra call a failed tick scheduled goes too: nothing may register behind the DELETE,
@@ -2332,15 +2470,20 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
2332
2470
  // The relay's unanswered frames `nak`, so the listener sends them to whoever resumes.
2333
2471
  closeRelay()
2334
2472
  await followedTopics.close()
2335
- // The heartbeat is stopped and `follow` refuses while shutting down, so no registration
2336
- // starts from here. What the chain still holds is waited out — a registration it runs after
2337
- // the DELETE would write the record back — and so is one already on the wire, both bounded,
2473
+ // The heartbeat is stopped, `follow` refuses while shutting down, `register` does nothing
2474
+ // once it is, and a registration on the wire sends nothing again (`registerWithRelay`'s
2475
+ // `stopping`), so no registration starts from here: one the chain still holds does
2476
+ // nothing when its turn comes. A removal of topics the chain still holds is refused by the
2477
+ // client's stop gate, so it sends nothing either. The chain is still waited out, so a
2478
+ // registration already on the wire, which would write the record back if it landed after
2479
+ // the DELETE, lands before it. Both waits are bounded,
2338
2480
  // and on this path bounded together by `shutdownSettleMs`: a write this listener has
2339
2481
  // stalled on must not keep the deregistration off the wire entirely, since a record left
2340
2482
  // behind outlives this process by the whole gone horizon, and the process is not given the
2341
2483
  // two full waits before it is killed.
2342
2484
  const settleBy = Date.now() + shutdownSettleMs
2343
2485
  await settledOrGivenUp(registryWrites, shutdownSettleMs)
2486
+ // The stop's own line: written with no tell gate, which drops every other line from here.
2344
2487
  await deregister(identity.id, Math.max(0, settleBy - Date.now())).catch((error: unknown) => {
2345
2488
  process.stderr.write(
2346
2489
  `envoy-channel: session deregistration failed — ${messageFor(error)}\n`,
@@ -2457,6 +2600,10 @@ export async function executeEnvoyTool(
2457
2600
  }
2458
2601
  case EnvoyToolOperation.setRole: {
2459
2602
  const args = parseArguments(spec, input)
2603
+ // A stopping session claims no role (R24 of dispatch://INFRA-3589), and keeps nothing of a
2604
+ // claim that was in flight when its shutdown began: no record, so no later process takes
2605
+ // it back from one.
2606
+ refuseClaimWhileStopping(runtime.session, args.role)
2460
2607
  // The claim names this process, as every claim this server makes does: the listener
2461
2608
  // records it as the role's holder, so a second process on this session id cannot be
2462
2609
  // mistaken for the one holding the role.
@@ -2466,6 +2613,7 @@ export async function executeEnvoyTool(
2466
2613
  role: args.role,
2467
2614
  clientInstanceID: runtime.clientInstanceID,
2468
2615
  })
2616
+ refuseClaimWhileStopping(runtime.session, args.role)
2469
2617
  if (!result.claimed) throw new Error(`role ${args.role} is held by ${result.holder}`)
2470
2618
  // The listener's warnings about the claim go to the log and, beside the interest row, to the
2471
2619
  // agent, which must know of a handover of the replaced session the claim did not make.
@@ -2497,6 +2645,12 @@ export async function executeEnvoyTool(
2497
2645
  }
2498
2646
  }
2499
2647
 
2648
+ /** Refuses a role claim once `session`'s shutdown has begun, with the error the Oh My Pi plugin's
2649
+ * `envoy_role_set` throws for the same refusal. */
2650
+ function refuseClaimWhileStopping(session: ChannelSession, role: string): void {
2651
+ if (session.stopping()) throw new RoleClaimStoppingError(role)
2652
+ }
2653
+
2500
2654
  function pluginStateDirectory(): string {
2501
2655
  const pluginData = configuredValue(process.env["CLAUDE_PLUGIN_DATA"])
2502
2656
  if (pluginData === undefined) {
@@ -2521,6 +2675,18 @@ function pluginStateDirectory(): string {
2521
2675
  export async function runEnvoyChannelServer(): Promise<void> {
2522
2676
  const directory = projectDirectory()
2523
2677
  const pane = await legionPane(process.env)
2678
+ // Whether this server's stop has begun (`stop`, R24 of dispatch://INFRA-3589). The client's stop
2679
+ // gate reads it at every call, and the server's own stderr lines and Legion log lines go
2680
+ // through a tell gate over it (`serverStderr`, `logLegionLine`). The session reads its own from
2681
+ // the same moment (`startSignal`).
2682
+ let stopping = false
2683
+ const serverStderr = gatedStderr(() => stopping)
2684
+ /** One line of the pane's Legion log (`logLegion`), through the server's tell gate. */
2685
+ const logLegionLine = (line: string): void => {
2686
+ if (!stopping) logLegion(line)
2687
+ }
2688
+ /** What ends the pane (`stopPane`) reads: the server's stop, and its gated Legion log. */
2689
+ const paneServer = { stopping: () => stopping, log: logLegionLine }
2524
2690
  // The session's envoy.json, by Claude Code's rule (`$CLAUDE_CONFIG_DIR/envoy.json` when that is
2525
2691
  // set), worked out once as the server starts; Dispatch's URL and token are re-read from it on each
2526
2692
  // use, so a file that moved its server takes effect without a restart.
@@ -2533,7 +2699,7 @@ export async function runEnvoyChannelServer(): Promise<void> {
2533
2699
  session: currentSessionId,
2534
2700
  })
2535
2701
  // Claude Code logs the server's stderr: why a section is off, once.
2536
- if (notice !== null) process.stderr.write(`envoy-channel: ${notice}\n`)
2702
+ if (notice !== null) serverStderr(`envoy-channel: ${notice}\n`)
2537
2703
  const overrideSessionId = process.env["ENVOY_SESSION_ID"]
2538
2704
  // The title every registration sends, and the one the `dispatch` command stamps on this
2539
2705
  // session's Dispatch writes. Registration stamps it; with Envoy or its inbound messages off,
@@ -2573,7 +2739,7 @@ export async function runEnvoyChannelServer(): Promise<void> {
2573
2739
  const own = title(sessionId)
2574
2740
  if (own !== "") stampTitle(sessionId, own)
2575
2741
  } catch (error) {
2576
- process.stderr.write(
2742
+ serverStderr(
2577
2743
  `envoy-channel: could not write the session title for the dispatch command — ${messageFor(error)}; the dispatch command's writes carry no session title\n`,
2578
2744
  )
2579
2745
  }
@@ -2587,7 +2753,9 @@ export async function runEnvoyChannelServer(): Promise<void> {
2587
2753
  }),
2588
2754
  )
2589
2755
  const refusal = `Envoy is off for this session: ${envoy.error ?? envoy.notice}`
2590
- if (pane !== undefined) stopPane(`a Legion pane needs Envoy for its task; ${refusal}`)
2756
+ if (pane !== undefined) {
2757
+ stopPane(`a Legion pane needs Envoy for its task; ${refusal}`, paneServer)
2758
+ }
2591
2759
  await serveEnvoyOff(MCP_SERVER_INFO, refusal)
2592
2760
  return
2593
2761
  }
@@ -2616,6 +2784,9 @@ export async function runEnvoyChannelServer(): Promise<void> {
2616
2784
  baseUrl: envoy.url,
2617
2785
  fetch: globalThis.fetch,
2618
2786
  credential: envoy.credential,
2787
+ // The stop gate: once `stop` has begun, no call of the session's registration or role
2788
+ // state is sent, the DELETE of the stop apart.
2789
+ stopping: () => stopping,
2619
2790
  })
2620
2791
  // INFRA-404: this process, as the listener knows it. Minted once here and sent on every
2621
2792
  // registration and every deregistration, so the listener can tell the entry this process made
@@ -2633,7 +2804,7 @@ export async function runEnvoyChannelServer(): Promise<void> {
2633
2804
  // INFRA-220: the phase reminder's Claude Code host (`./legion-phase-hook`), which Claude Code's
2634
2805
  // own hooks drive through the `legion_phase_hook` tool. It is started here, beside the claim it
2635
2806
  // gates on, and restores this session's record as it starts, before any hook can be answered.
2636
- const phaseLog = paneReminderLog(logLegion)
2807
+ const phaseLog = paneReminderLog(logLegionLine)
2637
2808
  // The claim's boot, for the endpoint's resume reminder and its recreated-workspace notice: both
2638
2809
  // need the claim, and the claim starts further down, once the channel session exists.
2639
2810
  const claimBooted = Promise.withResolvers<void>()
@@ -2739,7 +2910,7 @@ export async function runEnvoyChannelServer(): Promise<void> {
2739
2910
  },
2740
2911
  connected: () => modLink?.connected() === true,
2741
2912
  },
2742
- warn: (text) => process.stderr.write(`envoy-channel: ${text}\n`),
2913
+ warn: (text) => serverStderr(`envoy-channel: ${text}\n`),
2743
2914
  })
2744
2915
  // Every line this server writes into the session: the bridge's inbox in a Legion pane, and the
2745
2916
  // mod's own write in a terminal session, which is a row of the turn running and the prompt of
@@ -2773,7 +2944,6 @@ export async function runEnvoyChannelServer(): Promise<void> {
2773
2944
  const booting = new AbortController()
2774
2945
 
2775
2946
  const stopped = Promise.withResolvers<void>()
2776
- let stopping = false
2777
2947
  let session: ChannelSession | undefined
2778
2948
  // Stops the keeper of the connection's broker token, where it presents one. Declared before
2779
2949
  // `stop`, which may run on a signal before the connection is dialled.
@@ -2814,7 +2984,7 @@ export async function runEnvoyChannelServer(): Promise<void> {
2814
2984
  // the ENVOY_SESSION_ID override names an Envoy identity, never a Claude Code session.
2815
2985
  sessionId: claudeSessionId({ CLAUDE_CODE_SESSION_ID: process.env["CLAUDE_CODE_SESSION_ID"] }),
2816
2986
  env: process.env,
2817
- warn: (text) => process.stderr.write(`envoy-channel: ${text}\n`),
2987
+ warn: (text) => serverStderr(`envoy-channel: ${text}\n`),
2818
2988
  }).then(
2819
2989
  (link) => {
2820
2990
  modLink = link
@@ -2823,7 +2993,7 @@ export async function runEnvoyChannelServer(): Promise<void> {
2823
2993
  else linked.resolve(link)
2824
2994
  },
2825
2995
  (error: unknown) => {
2826
- process.stderr.write(
2996
+ serverStderr(
2827
2997
  `envoy-channel: no link to this session's Claude Code mod — ${messageFor(error)}; the session runs on without one\n`,
2828
2998
  )
2829
2999
  },
@@ -2843,7 +3013,7 @@ export async function runEnvoyChannelServer(): Promise<void> {
2843
3013
  session: claude,
2844
3014
  sessionId: () => identity.id,
2845
3015
  state,
2846
- warn: (text) => process.stderr.write(`envoy-channel: ${text}\n`),
3016
+ warn: (text) => serverStderr(`envoy-channel: ${text}\n`),
2847
3017
  // A pane's person message is a line of the bridge's inbox, which makes it a user turn;
2848
3018
  // the phase endpoint is told of it as it is told of every line this server writes.
2849
3019
  ...(inboxSocket === undefined ? {} : { inbox: (input) => notifier.notification(input) }),
@@ -2858,11 +3028,17 @@ export async function runEnvoyChannelServer(): Promise<void> {
2858
3028
  if (pane !== undefined) {
2859
3029
  stopPane(
2860
3030
  `a Legion pane's task reaches it over NATS, and inbound messages are off: ${inbound.off}`,
3031
+ paneServer,
2861
3032
  )
2862
3033
  }
2863
3034
  // No registration happens here, so the title is stamped directly.
2864
3035
  stampOnce(() => identity.id)
2865
- session = inboundOffChannelSession({ identity, stateDirectory, why: inbound.off })
3036
+ session = inboundOffChannelSession({
3037
+ identity,
3038
+ stateDirectory,
3039
+ why: inbound.off,
3040
+ stopping: () => stopping,
3041
+ })
2866
3042
  } else {
2867
3043
  starting =
2868
3044
  "relaySetting" in inbound
@@ -2884,10 +3060,13 @@ export async function runEnvoyChannelServer(): Promise<void> {
2884
3060
  // A redial's warning names what the start waits on; the token keeper warns through the
2885
3061
  // same channel once the connection is up, and names nothing the start waits on.
2886
3062
  if (dialError !== undefined) starting = text
2887
- process.stderr.write(`envoy-channel: ${text}\n`)
3063
+ serverStderr(`envoy-channel: ${text}\n`)
2888
3064
  },
2889
3065
  connect,
2890
3066
  booting.signal,
3067
+ // The relay socket opens no socket again once the server's stop has begun, the start's
3068
+ // wait included: the session reads the same stop from `startSignal`.
3069
+ () => stopping,
2891
3070
  ).catch((error: unknown) => {
2892
3071
  // A stop asked for while the token or the dial was awaited, as in the start below.
2893
3072
  if (stopping) return undefined
@@ -2910,6 +3089,8 @@ export async function runEnvoyChannelServer(): Promise<void> {
2910
3089
  session: currentSessionId,
2911
3090
  name: natsName,
2912
3091
  signal: booting.signal,
3092
+ stopping: () => stopping,
3093
+ warn: (text) => serverStderr(`envoy-channel: ${text}\n`),
2913
3094
  swapKeeper: (stop) => {
2914
3095
  stopNatsKeeper()
2915
3096
  stopNatsKeeper = stop
@@ -2963,6 +3144,8 @@ export async function runEnvoyChannelServer(): Promise<void> {
2963
3144
  agentStream = startAgentStream({
2964
3145
  connection,
2965
3146
  liveView: dialled.liveView,
3147
+ // Through the server's tell gate: a read the link's close at the stop ends says nothing.
3148
+ warn: (text) => serverStderr(`envoy-channel: ${text}\n`),
2966
3149
  // Only a Claude-minted id follows `/clear`; the override names a fixed identity.
2967
3150
  followsSessionId: configuredValue(overrideSessionId) === undefined,
2968
3151
  ...(admission === undefined ? {} : { admitted: (id: string) => admission.admitted(id) }),
@@ -3017,7 +3200,7 @@ export async function runEnvoyChannelServer(): Promise<void> {
3017
3200
  clientInstanceID,
3018
3201
  session,
3019
3202
  signal: booting.signal,
3020
- log: logLegion,
3203
+ log: logLegionLine,
3021
3204
  stop: endPane,
3022
3205
  // The signal goes in the slot the phase hook's `UserPromptSubmit` calls. The boot fills
3023
3206
  // it when `claims/register` has answered, which is after the bridge's seed: that prompt