@shumkov/orchestra 0.4.3 → 0.6.0

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.
@@ -0,0 +1,22 @@
1
+ # Claude Code 2.1.220 compatibility
2
+
3
+ Orchestra 0.6.0 pins the channels backend to Claude Code 2.1.220. The pin is
4
+ deliberate because the backend consumes private Claude Code TUI, hook, session,
5
+ queue, and MCP-registration behavior.
6
+
7
+ The upgrade was validated against the preserved 2.1.173 binary with Polygram's
8
+ serial real-Claude matrix. All 21 cells passed:
9
+
10
+ - two independent CLI contract runs per version;
11
+ - direct and failed-reply Workflow completion delivery;
12
+ - delayed MCP completion;
13
+ - SDK PostToolBatch, subagent, resume, manual compact, and tool-less drain;
14
+ - the 2.1.220 Opus 5/default-Workflow production projection.
15
+
16
+ The candidate takes longer than five seconds on some cold starts to send its
17
+ first MCP `ListToolsRequest` after the channels bridge authenticates. Orchestra
18
+ therefore keeps the authenticated bridge alive and allows up to 30 seconds for
19
+ MCP readiness, while still failing immediately on disconnect.
20
+
21
+ Rollback remains possible by selecting the preserved 2.1.173 executable with
22
+ `ORCHESTRA_CLAUDE_BIN`. The normal default resolves and vendors 2.1.220.
package/lib/claude-bin.js CHANGED
@@ -6,23 +6,9 @@ const path = require('path');
6
6
  const fs = require('fs');
7
7
  const { execFileSync } = require('child_process');
8
8
 
9
- // 0.12 Phase 4: moved from lib/process/tmux-process.js into the helper module
10
- // that consumes it, so the constant survives TmuxProcess deletion. CliProcess
11
- // + spike scripts + polygram boot all import from here now.
12
- // 0.12.0-rc.18: bumped 2.1.142 → 2.1.158 (latest installed) chasing the
13
- // dev-channels reliability issues (see docs/0.12.0-known-issues.md).
14
- // 0.12.0-rc.38: bumped 2.1.158 → 2.1.173. Two reasons: (1) the ~32s startup
15
- // deaths root-caused 2026-06-11 to a stale MCP connect-timeout racing the
16
- // --resume session-id swap — a newer claude may fix the timer (2.1.173 also
17
- // adds "Channel notifications re-registered after reconnect"); (2) keep the
18
- // research-preview channels current. Per-bump re-validation done 2026-06-11:
19
- // resume-dialog env vars survive (CLAUDE_CODE_RESUME_THRESHOLD_MINUTES /
20
- // _TOKEN_THRESHOLD), trust + dev-channels dialogs unchanged, "esc to
21
- // interrupt" hint unchanged (template-rendered), but the channels READY
22
- // banner text CHANGED → readySignal in cli-process.js matches both forms.
23
- // Re-validate the channel flow on each bump via
24
- // tests/e2e-channels-real-claude.test.js (run with E2E_REAL_CLAUDE=1).
25
- const CLAUDE_CLI_PINNED_VERSION = '2.1.173';
9
+ // The channels backend consumes Claude Code's private TUI, hook, and session
10
+ // formats. Change this pin only after the real-CLI compatibility gate passes.
11
+ const CLAUDE_CLI_PINNED_VERSION = '2.1.220';
26
12
 
27
13
  /**
28
14
  * Resolve + verify the pinned claude CLI binary.
@@ -61,6 +61,7 @@ const { resolveCompactionWarnConfig } = require('../compaction-warn');
61
61
  const { readContextTokens, contextPct } = require('../context-usage');
62
62
  const { runStartupGate } = require('../tmux/startup-gate');
63
63
  const {
64
+ MAX_WORKFLOW_TRANSCRIPT_BYTES,
64
65
  correlateWorkflowCompletionSnapshot,
65
66
  hashDeliveryArguments,
66
67
  normalizeVisibleText,
@@ -68,17 +69,18 @@ const {
68
69
 
69
70
  const BRIDGE_PATH = path.resolve(__dirname, 'channels-bridge.mjs');
70
71
  const DEFAULT_HANDSHAKE_TIMEOUT_MS = 15_000;
71
- // 0.12 Phase 1.6: claude-side MCP-init can lag behind daemon-side bridge
72
- // handshake by 100ms in normal conditions, up to a few seconds on cold
73
- // machines or fresh git worktrees. 5s default tolerates that without
74
- // being so long that a genuinely-stuck bridge wedges the chat unnoticed.
75
- const DEFAULT_MCP_READY_TIMEOUT_MS = 5_000;
72
+ // Claude-side MCP registration can lag well behind daemon-side bridge
73
+ // authentication on cold starts. Keep this below the wider TUI startup bound
74
+ // while leaving enough room for a healthy bridge to finish ListTools.
75
+ const DEFAULT_MCP_READY_TIMEOUT_MS = 30_000;
76
76
  // 0.12 Phase 1.7 (Finding 0.1.A): Stop hook fires AFTER the channel result
77
77
  // event. We wait this long after a channel result before finalizing the
78
78
  // turn, so the Stop hook can land and we can use its last_assistant_message
79
79
  // as a text fallback when the channel result delivered empty replies.
80
80
  // Mirrors rc.41 H4 stopGraceMs from tmux backend. 2s default = same as tmux.
81
81
  const DEFAULT_STOP_GRACE_MS = 2_000;
82
+ const WORKFLOW_TRANSCRIPT_SETTLE_MS = 1_000;
83
+ const WORKFLOW_TRANSCRIPT_POLL_MS = 25;
82
84
  const DEFAULT_TURN_QUIET_MS = 2_000; // after first reply, wait this long for more before resolving turn
83
85
  // 0.13 D1 rung 2 (docs/0.13-channels-lifecycle-design.md §3 D1): once a turn has
84
86
  // ≥1 delivered reply AND the hook stream is live, the turn finalizes when the
@@ -117,6 +119,26 @@ const DEFAULT_TOOL_RATE_LIMIT_PER_SEC = 5; // P2 ADV-6: cap on reply tool call
117
119
  const DEFAULT_TOOL_RATE_BURST = 20; // ADV-6: token bucket capacity
118
120
  const DEFAULT_QUEUE_CAP = 50; // Parity P2: match SDK/tmux pendingQueue cap
119
121
 
122
+ function validateSessionLauncher(sessionLauncher) {
123
+ if (!sessionLauncher) return null;
124
+ if (typeof sessionLauncher !== 'string' || !path.isAbsolute(sessionLauncher)) {
125
+ throw Object.assign(new TypeError('CliProcess: sessionLauncher must be an absolute executable path'), {
126
+ code: 'SESSION_LAUNCHER_INVALID',
127
+ });
128
+ }
129
+ try {
130
+ if (!fs.statSync(sessionLauncher).isFile()) {
131
+ throw new Error('not a regular file');
132
+ }
133
+ fs.accessSync(sessionLauncher, fs.constants.X_OK);
134
+ } catch {
135
+ throw Object.assign(new TypeError(`CliProcess: sessionLauncher is not an executable file: ${sessionLauncher}`), {
136
+ code: 'SESSION_LAUNCHER_INVALID',
137
+ });
138
+ }
139
+ return sessionLauncher;
140
+ }
141
+
120
142
  // Review F#17: mid-turn dialog watchdog. Even though channels uses MCP for IO,
121
143
  // the underlying claude TUI can still pop interactive prompts mid-turn that
122
144
  // don't surface as MCP notifications (session-age, future "approaching usage
@@ -253,6 +275,7 @@ class CliProcess extends Process {
253
275
  sessionKey, chatId, threadId, label,
254
276
  tmuxRunner, botName,
255
277
  claudeBin = null,
278
+ sessionLauncher = process.env.ORCHESTRA_SESSION_LAUNCHER || null,
256
279
  toolDispatcher,
257
280
  // Extraction-time API (orchestra): the consumer injects its surface-rendering
258
281
  // hint (appended to the system prompt) and outbound file-size cap, so the engine
@@ -308,6 +331,7 @@ class CliProcess extends Process {
308
331
  throw new TypeError('CliProcess: claudeBin required (or ORCHESTRA_CLAUDE_BIN env)');
309
332
  }
310
333
  this.claudeBin = claudeBin || process.env.ORCHESTRA_CLAUDE_BIN;
334
+ this.sessionLauncher = validateSessionLauncher(sessionLauncher);
311
335
  this.toolDispatcher = toolDispatcher;
312
336
  this.displayHint = displayHint;
313
337
  this._injectedMaxOutboundFileBytes = maxOutboundFileBytes;
@@ -345,10 +369,14 @@ class CliProcess extends Process {
345
369
  this.mcpConfigPath = null; // P0 #1: 0o600 tmp file holding bridge env (no argv leak)
346
370
  this.tmuxSession = null; // tmux session name
347
371
  this.bridgeReady = false;
372
+ this._bridgeDisconnectErrorPromise = null;
348
373
  // 0.12 Phase 1.6: claude-side MCP-server registration completion flag.
349
374
  // Set true when bridge writes {kind:'mcp-ready'} after claude's first
350
375
  // ListToolsRequest (Finding 0.3.A — cold-spawn race fix).
351
376
  this.mcpReady = false;
377
+ this._cancelBridgeHandshakeWait = null;
378
+ this._bridgeHandshakeCancellationError = null;
379
+ this.startupPingTimer = null;
352
380
  this.pingTimer = null;
353
381
  // Review P1 #6: daemon-side pong tracking. Without it, a half-open socket
354
382
  // (bridge frozen but TCP alive) is invisible to the daemon. We record the
@@ -547,6 +575,7 @@ class CliProcess extends Process {
547
575
  await this._createSocketServer();
548
576
  await this._spawnTmuxClaude({ tmuxName, opts });
549
577
  await this._waitForBridgeHandshake();
578
+ this._stopStartupPingLoop();
550
579
  // Phase 1.3: arm hook tail AFTER spawn so this._hookNdjsonPath is
551
580
  // populated (set inside _spawnTmuxClaude when writeHookFiles runs).
552
581
  // Mirrors tmux-process.js:_armHookTail timing.
@@ -581,6 +610,7 @@ class CliProcess extends Process {
581
610
  * preserves the calling pattern (teardown must not mask the start() error).
582
611
  */
583
612
  async _teardownOnStartFailure() {
613
+ this._stopStartupPingLoop();
584
614
  if (this.bridgeServer) {
585
615
  try { await this.bridgeServer.close(); } catch {}
586
616
  this.bridgeServer = null;
@@ -633,6 +663,7 @@ class CliProcess extends Process {
633
663
 
634
664
  this.bridgeServer.on('bridge-ready', () => {
635
665
  this.bridgeReady = true;
666
+ this._startStartupPingLoop();
636
667
  this.emit('bridge-ready');
637
668
  });
638
669
 
@@ -647,7 +678,11 @@ class CliProcess extends Process {
647
678
 
648
679
  this.bridgeServer.on('bridge-message', msg => this._handleBridgeMessage(msg));
649
680
 
650
- this.bridgeServer.on('bridge-disconnected', () => this._handleBridgeDisconnected());
681
+ this.bridgeServer.on('bridge-disconnected', () => {
682
+ this._handleBridgeDisconnected().catch(err => {
683
+ this.logger.error?.(`[${this.label}] channels: bridge disconnect handling failed: ${err.message}`);
684
+ });
685
+ });
651
686
 
652
687
  await this.bridgeServer.listen();
653
688
  }
@@ -1005,8 +1040,8 @@ class CliProcess extends Process {
1005
1040
  await this.runner.spawn({
1006
1041
  name: tmuxName,
1007
1042
  cwd: resolvedCwd || opts.cwd || process.cwd(),
1008
- command: this.claudeBin,
1009
- args: claudeArgs,
1043
+ command: this.sessionLauncher || this.claudeBin,
1044
+ args: this.sessionLauncher ? [this.claudeBin, ...claudeArgs] : claudeArgs,
1010
1045
  envExtras: {
1011
1046
  // Resume-dialog suppression (docs/0.13-resume-dialog-fix-spec.md B1):
1012
1047
  // claude's session-age "resume-return" dialog fires when sessionAge ≥
@@ -1126,23 +1161,81 @@ class CliProcess extends Process {
1126
1161
  // Both waits resolve race-safe via state flags set in _createSocketServer
1127
1162
  // listeners (bridgeReady, mcpReady).
1128
1163
  _waitForBridgeHandshake() {
1129
- const waitBridge = this.bridgeReady ? Promise.resolve() : new Promise((resolve, reject) => {
1130
- const timer = setTimeout(() => {
1131
- const err = new Error(`bridge handshake timeout (${this.handshakeTimeoutMs}ms)`);
1132
- err.code = 'CHANNELS_HANDSHAKE_TIMEOUT';
1133
- reject(err);
1134
- }, this.handshakeTimeoutMs);
1135
- this.once('bridge-ready', () => { clearTimeout(timer); resolve(); });
1136
- });
1137
- const waitMcp = this.mcpReady ? Promise.resolve() : new Promise((resolve, reject) => {
1138
- const timer = setTimeout(() => {
1139
- const err = new Error(`mcp-ready timeout (${this.mcpReadyTimeoutMs}ms) — bridge connected but claude never sent first ListToolsRequest`);
1140
- err.code = 'CHANNELS_MCP_READY_TIMEOUT';
1164
+ return new Promise((resolve, reject) => {
1165
+ if (this._bridgeHandshakeCancellationError) {
1166
+ reject(this._bridgeHandshakeCancellationError);
1167
+ return;
1168
+ }
1169
+ if (this._bridgeDisconnecting || this._bridgeDisconnectErrorPromise) {
1170
+ const err = new Error('bridge disconnected before MCP registration completed');
1171
+ err.code = 'BRIDGE_DISCONNECTED';
1141
1172
  reject(err);
1142
- }, this.mcpReadyTimeoutMs);
1143
- this.once('mcp-ready', () => { clearTimeout(timer); resolve(); });
1173
+ return;
1174
+ }
1175
+ const bridgeServer = this.bridgeServer;
1176
+ let settled = false;
1177
+ let bridgeTimer = null;
1178
+ let mcpTimer = null;
1179
+ const maybeResolve = () => {
1180
+ if (this.bridgeReady && this.mcpReady) settle(resolve);
1181
+ };
1182
+ const onBridgeReady = () => {
1183
+ this.bridgeReady = true;
1184
+ maybeResolve();
1185
+ };
1186
+ const onMcpReady = () => {
1187
+ this.mcpReady = true;
1188
+ maybeResolve();
1189
+ };
1190
+ const onBridgeDisconnected = () => {
1191
+ const err = new Error('bridge disconnected before MCP registration completed');
1192
+ err.code = 'BRIDGE_DISCONNECTED';
1193
+ settle(reject, err);
1194
+ };
1195
+ const cleanup = () => {
1196
+ if (bridgeTimer) clearTimeout(bridgeTimer);
1197
+ if (mcpTimer) clearTimeout(mcpTimer);
1198
+ this.off('bridge-ready', onBridgeReady);
1199
+ this.off('mcp-ready', onMcpReady);
1200
+ bridgeServer?.off?.('bridge-disconnected', onBridgeDisconnected);
1201
+ if (this._cancelBridgeHandshakeWait === cancelWait) {
1202
+ this._cancelBridgeHandshakeWait = null;
1203
+ }
1204
+ };
1205
+ const settle = (callback, value) => {
1206
+ if (settled) return;
1207
+ settled = true;
1208
+ cleanup();
1209
+ callback(value);
1210
+ };
1211
+ const cancelWait = (error) => settle(reject, error);
1212
+ this._cancelBridgeHandshakeWait = cancelWait;
1213
+ if (!this.bridgeReady) {
1214
+ this.on('bridge-ready', onBridgeReady);
1215
+ bridgeTimer = setTimeout(() => {
1216
+ const err = new Error(`bridge handshake timeout (${this.handshakeTimeoutMs}ms)`);
1217
+ err.code = 'CHANNELS_HANDSHAKE_TIMEOUT';
1218
+ settle(reject, err);
1219
+ }, this.handshakeTimeoutMs);
1220
+ }
1221
+ if (!this.mcpReady) {
1222
+ this.on('mcp-ready', onMcpReady);
1223
+ mcpTimer = setTimeout(() => {
1224
+ const err = new Error(`mcp-ready timeout (${this.mcpReadyTimeoutMs}ms) — bridge connected but claude never sent first ListToolsRequest`);
1225
+ err.code = 'CHANNELS_MCP_READY_TIMEOUT';
1226
+ settle(reject, err);
1227
+ }, this.mcpReadyTimeoutMs);
1228
+ }
1229
+ bridgeServer?.once?.('bridge-disconnected', onBridgeDisconnected);
1230
+ maybeResolve();
1144
1231
  });
1145
- return Promise.all([waitBridge, waitMcp]).then(() => undefined);
1232
+ }
1233
+
1234
+ _cancelPendingBridgeHandshake(code, message) {
1235
+ const error = new Error(message);
1236
+ error.code = code;
1237
+ this._bridgeHandshakeCancellationError = error;
1238
+ this._cancelBridgeHandshakeWait?.(error);
1146
1239
  }
1147
1240
 
1148
1241
  // ─── bridge protocol semantics ─────────────────────────────────────
@@ -1317,18 +1410,159 @@ class CliProcess extends Process {
1317
1410
  || typeof ev.lastAssistantMessage !== 'string'
1318
1411
  || !normalizeVisibleText(ev.lastAssistantMessage)
1319
1412
  ) return null;
1413
+ let fd;
1320
1414
  try {
1321
- const stat = fs.statSync(ev.transcriptPath);
1322
- if (!stat.isFile() || stat.size <= 0) return null;
1415
+ fd = fs.openSync(ev.transcriptPath, 'r');
1416
+ const before = fs.fstatSync(fd, { bigint: true });
1417
+ if (
1418
+ !before.isFile()
1419
+ || before.size <= 0n
1420
+ || before.size > BigInt(MAX_WORKFLOW_TRANSCRIPT_BYTES)
1421
+ ) return null;
1422
+ const byteSize = Number(before.size);
1423
+ const buffer = Buffer.allocUnsafe(byteSize);
1424
+ let offset = 0;
1425
+ while (offset < byteSize) {
1426
+ const bytesRead = fs.readSync(fd, buffer, offset, byteSize - offset, offset);
1427
+ if (bytesRead === 0) break;
1428
+ offset += bytesRead;
1429
+ }
1430
+ if (offset !== byteSize) return null;
1431
+ const after = fs.fstatSync(fd, { bigint: true });
1432
+ if (
1433
+ !after.isFile()
1434
+ || after.dev !== before.dev
1435
+ || after.ino !== before.ino
1436
+ || after.size < before.size
1437
+ ) return null;
1438
+ if (
1439
+ after.size === before.size
1440
+ && (after.mtimeNs !== before.mtimeNs || after.ctimeNs !== before.ctimeNs)
1441
+ ) return null;
1323
1442
  return {
1324
1443
  transcriptPath: ev.transcriptPath,
1325
- byteSize: stat.size,
1444
+ byteSize,
1445
+ prefixByteSize: byteSize,
1446
+ prefixHash: crypto.createHash('sha256').update(buffer).digest('hex'),
1447
+ fileDevice: before.dev.toString(),
1448
+ fileInode: before.ino.toString(),
1326
1449
  sessionId: ev.sessionId || this.claudeSessionId,
1327
1450
  finalText: ev.lastAssistantMessage,
1451
+ workHookSeq: this._workHookSeq || 0,
1328
1452
  };
1329
1453
  } catch {
1330
1454
  return null;
1455
+ } finally {
1456
+ if (fd !== undefined) {
1457
+ try {
1458
+ fs.closeSync(fd);
1459
+ } catch {}
1460
+ }
1461
+ }
1462
+ }
1463
+
1464
+ async _correlateSettledWorkflowSnapshot(snapshot, generation) {
1465
+ const ineligible = reason => ({
1466
+ eligible: false,
1467
+ reason,
1468
+ deliveredFinal: false,
1469
+ visibleHashes: [],
1470
+ unresolvedAttempts: [],
1471
+ });
1472
+ const invalidated = () => (
1473
+ generation !== this._deliveryGeneration || this.closed
1474
+ );
1475
+ const identityChanged = stat => (
1476
+ stat.dev.toString() !== snapshot.fileDevice
1477
+ || stat.ino.toString() !== snapshot.fileInode
1478
+ );
1479
+ const verifyEligible = async correlation => {
1480
+ if (
1481
+ !Number.isSafeInteger(correlation.snapshotByteSize)
1482
+ || typeof correlation.snapshotHash !== 'string'
1483
+ ) {
1484
+ return ineligible('snapshot-proof-missing');
1485
+ }
1486
+ const verified = await correlateWorkflowCompletionSnapshot({
1487
+ ...snapshot,
1488
+ byteSize: correlation.snapshotByteSize,
1489
+ prefixByteSize: correlation.snapshotByteSize,
1490
+ prefixHash: correlation.snapshotHash,
1491
+ });
1492
+ if (invalidated()) return null;
1493
+ if (
1494
+ !verified.eligible
1495
+ || verified.snapshotHash !== correlation.snapshotHash
1496
+ ) {
1497
+ return ineligible('snapshot-changed-before-decision');
1498
+ }
1499
+ return verified;
1500
+ };
1501
+
1502
+ let correlation = await correlateWorkflowCompletionSnapshot(snapshot);
1503
+ if (invalidated()) return null;
1504
+ if (correlation.eligible) return verifyEligible(correlation);
1505
+ if (correlation.reason !== 'terminal-not-last-mainline') return correlation;
1506
+ if (typeof correlation.snapshotHash !== 'string') {
1507
+ return ineligible('snapshot-prefix-missing');
1508
+ }
1509
+
1510
+ const prefixHash = snapshot.prefixHash;
1511
+ const deadline = Date.now() + WORKFLOW_TRANSCRIPT_SETTLE_MS;
1512
+ let observedSize = snapshot.byteSize;
1513
+ while (Date.now() < deadline) {
1514
+ if (invalidated()) return null;
1515
+ if ((this._workHookSeq || 0) !== snapshot.workHookSeq) {
1516
+ return ineligible('intervening-work');
1517
+ }
1518
+
1519
+ let stat;
1520
+ try {
1521
+ stat = await fs.promises.stat(snapshot.transcriptPath);
1522
+ } catch {
1523
+ return ineligible('snapshot-unreadable');
1524
+ }
1525
+ if (invalidated()) return null;
1526
+ if (!stat.isFile() || identityChanged(stat)) {
1527
+ return ineligible('snapshot-replaced');
1528
+ }
1529
+ if (stat.size < observedSize) return ineligible('snapshot-shrunk');
1530
+ if (stat.size === observedSize) {
1531
+ await new Promise(resolve => setTimeout(resolve, WORKFLOW_TRANSCRIPT_POLL_MS));
1532
+ continue;
1533
+ }
1534
+
1535
+ const candidateSize = stat.size;
1536
+ correlation = await correlateWorkflowCompletionSnapshot({
1537
+ ...snapshot,
1538
+ byteSize: candidateSize,
1539
+ prefixByteSize: snapshot.byteSize,
1540
+ prefixHash,
1541
+ });
1542
+ if (invalidated()) return null;
1543
+
1544
+ let after;
1545
+ try {
1546
+ after = await fs.promises.stat(snapshot.transcriptPath);
1547
+ } catch {
1548
+ return ineligible('snapshot-unreadable');
1549
+ }
1550
+ if (invalidated()) return null;
1551
+ if (!after.isFile() || identityChanged(after)) {
1552
+ return ineligible('snapshot-replaced');
1553
+ }
1554
+ if (after.size < candidateSize) return ineligible('snapshot-shrunk');
1555
+ observedSize = candidateSize;
1556
+ if (after.size > candidateSize) continue;
1557
+ if (correlation.eligible) return verifyEligible(correlation);
1558
+ if (
1559
+ correlation.reason !== 'terminal-not-last-mainline'
1560
+ && correlation.reason !== 'partial-line'
1561
+ ) {
1562
+ return correlation;
1563
+ }
1331
1564
  }
1565
+ return ineligible('transcript-settle-timeout');
1332
1566
  }
1333
1567
 
1334
1568
  _beginWorkflowCompletionDecision(snapshot) {
@@ -1338,7 +1572,11 @@ class CliProcess extends Process {
1338
1572
  }
1339
1573
  const generation = this._deliveryGeneration;
1340
1574
  const decisionKey = crypto.createHash('sha256')
1341
- .update(`${snapshot.transcriptPath}\0${snapshot.byteSize}\0${normalizeVisibleText(snapshot.finalText)}`, 'utf8')
1575
+ .update(
1576
+ `${snapshot.transcriptPath}\0${snapshot.sessionId || ''}\0`
1577
+ + `${snapshot.workHookSeq}\0${normalizeVisibleText(snapshot.finalText)}`,
1578
+ 'utf8',
1579
+ )
1342
1580
  .digest('hex');
1343
1581
  const now = Date.now();
1344
1582
  for (const [key, expiry] of this._workflowDecisionKeys) {
@@ -1353,9 +1591,13 @@ class CliProcess extends Process {
1353
1591
  });
1354
1592
 
1355
1593
  Promise.resolve()
1356
- .then(() => correlateWorkflowCompletionSnapshot(snapshot))
1594
+ .then(() => this._correlateSettledWorkflowSnapshot(snapshot, generation))
1357
1595
  .then(async correlation => {
1358
- if (generation !== this._deliveryGeneration || this.closed) return;
1596
+ if (!correlation || generation !== this._deliveryGeneration || this.closed) return;
1597
+ if ((this._workHookSeq || 0) !== snapshot.workHookSeq) {
1598
+ this._logEvent('workflow-completion-ineligible', { reason: 'intervening-work' });
1599
+ return;
1600
+ }
1359
1601
  if (!correlation.eligible) {
1360
1602
  this._logEvent('workflow-completion-ineligible', { reason: correlation.reason });
1361
1603
  return;
@@ -1379,6 +1621,10 @@ class CliProcess extends Process {
1379
1621
  generation,
1380
1622
  );
1381
1623
  if (generation !== this._deliveryGeneration || this.closed) return;
1624
+ if ((this._workHookSeq || 0) !== snapshot.workHookSeq) {
1625
+ this._logEvent('workflow-completion-ineligible', { reason: 'intervening-work' });
1626
+ return;
1627
+ }
1382
1628
  if (outcome.outcome === 'missing' || outcome.outcome === 'mismatch' || outcome.outcome === 'invalidated') {
1383
1629
  this._logEvent('workflow-completion-ineligible', { reason: `attempt-${outcome.outcome}` });
1384
1630
  return;
@@ -1398,6 +1644,10 @@ class CliProcess extends Process {
1398
1644
  this._logEvent('workflow-completion-ineligible', { reason: 'overlapping-turn' });
1399
1645
  return;
1400
1646
  }
1647
+ if ((this._workHookSeq || 0) !== snapshot.workHookSeq) {
1648
+ this._logEvent('workflow-completion-ineligible', { reason: 'intervening-work' });
1649
+ return;
1650
+ }
1401
1651
  this.emit('autonomous-assistant-message', {
1402
1652
  text: snapshot.finalText,
1403
1653
  sessionId: this.claudeSessionId,
@@ -2625,6 +2875,9 @@ class CliProcess extends Process {
2625
2875
  // ─── public Process API ──────────────────────────────────────────
2626
2876
 
2627
2877
  async send(prompt, opts = {}) {
2878
+ if (this._bridgeDisconnecting) {
2879
+ throw await this._bridgeDisconnectErrorPromise;
2880
+ }
2628
2881
  if (this.closed) {
2629
2882
  // Parity P21: PROCESS_CLOSED code for cross-backend symmetry.
2630
2883
  const err = new Error('CliProcess: send on closed instance');
@@ -3786,10 +4039,14 @@ class CliProcess extends Process {
3786
4039
  * landing just before the disconnect would otherwise leave a stray
3787
4040
  * timer on the dead instance).
3788
4041
  */
3789
- _handleBridgeDisconnected(reason = 'socket-close') {
4042
+ async _handleBridgeDisconnected(reason = 'socket-close') {
3790
4043
  this.bridgeReady = false;
3791
4044
  this.mcpReady = false;
3792
- if (this.closed) return;
4045
+ this._stopStartupPingLoop();
4046
+ if (this.closed || this._bridgeDisconnecting) return;
4047
+ this._bridgeDisconnecting = true;
4048
+ this._bridgeDisconnectErrorPromise = this._bridgeDisconnectError();
4049
+ const disconnectError = await this._bridgeDisconnectErrorPromise;
3793
4050
  this._invalidatePendingDeliveryWork();
3794
4051
  this.logger.warn?.(`[${this.label}] channels: bridge disconnected unexpectedly (${reason})`);
3795
4052
  // L6: clear the interrupt grace timer alongside the rest of the lifecycle.
@@ -3807,9 +4064,7 @@ class CliProcess extends Process {
3807
4064
  // L5: remove the per-turn stop-hook listener (this path bypasses
3808
4065
  // Process.kill()'s removeAllListeners).
3809
4066
  if (pending._onStop) this.off('stop-hook', pending._onStop);
3810
- const err = new Error('bridge disconnected');
3811
- err.code = 'BRIDGE_DISCONNECTED';
3812
- try { pending.reject(err); } catch {}
4067
+ try { pending.reject(disconnectError); } catch {}
3813
4068
  }
3814
4069
  this.pendingTurns.clear();
3815
4070
  this.pendingQueue.length = 0;
@@ -3820,14 +4075,44 @@ class CliProcess extends Process {
3820
4075
  this._stopQuestionKeepAlive();
3821
4076
  this._openQuestions.clear();
3822
4077
  this._clearLedgerTimers(); // 0.13 D2
3823
- this.emit('bridge-disconnected');
3824
- this._logEvent('bridge-disconnected', { reason });
4078
+ this.emit('bridge-disconnected', { code: disconnectError.code });
4079
+ this._logEvent('bridge-disconnected', { reason, code: disconnectError.code });
4080
+ }
4081
+
4082
+ async _bridgeDisconnectError() {
4083
+ if (!this.sessionLauncher) {
4084
+ return Object.assign(new Error('bridge disconnected'), { code: 'BRIDGE_DISCONNECTED' });
4085
+ }
4086
+
4087
+ let processAlive = false;
4088
+ if (this.tmuxSession && typeof this.runner?.sessionProcessAlive === 'function') {
4089
+ let timeout;
4090
+ try {
4091
+ processAlive = await Promise.race([
4092
+ this.runner.sessionProcessAlive(this.tmuxSession),
4093
+ new Promise(resolve => {
4094
+ timeout = setTimeout(() => resolve(false), 250);
4095
+ timeout.unref?.();
4096
+ }),
4097
+ ]);
4098
+ } catch (err) {
4099
+ this.logger.warn?.(`[${this.label}] channels: could not verify contained process after bridge disconnect: ${err.message}`);
4100
+ } finally {
4101
+ if (timeout) clearTimeout(timeout);
4102
+ }
4103
+ }
4104
+ if (processAlive) {
4105
+ return Object.assign(new Error('bridge disconnected'), { code: 'BRIDGE_DISCONNECTED' });
4106
+ }
4107
+ return Object.assign(new Error('contained session process was lost'), { code: 'SESSION_PROCESS_LOST' });
3825
4108
  }
3826
4109
 
3827
4110
  async _doKill(reason) {
3828
4111
  this.closed = true;
3829
4112
  this.inFlight = false;
4113
+ this._cancelPendingBridgeHandshake('KILLED', `session killed: ${reason}`);
3830
4114
  this._invalidatePendingDeliveryWork();
4115
+ this._stopStartupPingLoop();
3831
4116
 
3832
4117
  this._stopQuestionKeepAlive(); // 0.12: drop the interactive-question keep-alive
3833
4118
  this._openQuestions.clear();
@@ -4050,6 +4335,7 @@ class CliProcess extends Process {
4050
4335
  * @returns {Promise<{closed: boolean, drainedPendings: number}>}
4051
4336
  */
4052
4337
  async resetSession({ reason = 'reset' } = {}) {
4338
+ this._cancelPendingBridgeHandshake('RESET', `session reset: ${reason}`);
4053
4339
  this._invalidatePendingDeliveryWork();
4054
4340
  let drained = 0;
4055
4341
  // First drain pendingTurns (channels-native bookkeeping). Each entry
@@ -4117,6 +4403,7 @@ class CliProcess extends Process {
4117
4403
  // resetSession; channels cannot because there's no in-place re-init
4118
4404
  // path — claude needs a fresh spawn to reset its conversation state.)
4119
4405
  this.closed = true;
4406
+ this._stopStartupPingLoop();
4120
4407
  if (this.pingTimer) {
4121
4408
  clearInterval(this.pingTimer);
4122
4409
  this.pingTimer = null;
@@ -4275,6 +4562,21 @@ class CliProcess extends Process {
4275
4562
  }
4276
4563
  }
4277
4564
 
4565
+ _startStartupPingLoop() {
4566
+ if (this.startupPingTimer) return;
4567
+ this._writeToBridge({ kind: 'ping' });
4568
+ this.startupPingTimer = setInterval(() => {
4569
+ this._writeToBridge({ kind: 'ping' });
4570
+ }, PING_INTERVAL_MS);
4571
+ this.startupPingTimer.unref?.();
4572
+ }
4573
+
4574
+ _stopStartupPingLoop() {
4575
+ if (!this.startupPingTimer) return;
4576
+ clearInterval(this.startupPingTimer);
4577
+ this.startupPingTimer = null;
4578
+ }
4579
+
4278
4580
  _startPingLoop() {
4279
4581
  // P1 #6: seed lastPongAt so the watchdog has a fresh baseline.
4280
4582
  this.lastPongAt = Date.now();
@@ -105,6 +105,9 @@ function _maybeWarnR12Migration({ rawPm, canonical, chatId, threadId, chatCfg, t
105
105
  * @param {string} [opts.channelsClaudeBin] — absolute path to pinned claude binary;
106
106
  * required when ANY chat routes to 'cli'. (Name kept for back-compat with
107
107
  * existing wiring; can be renamed to `claudeBin` in a future refactor.)
108
+ * @param {string|null} [opts.sessionLauncher] — optional absolute executable
109
+ * wrapper that receives the pinned Claude binary as its first argument. Defaults to
110
+ * ORCHESTRA_SESSION_LAUNCHER when configured by the consumer.
108
111
  * @param {string|Function} [opts.displayHint] — surface-rendering hint prepended to
109
112
  * the CliProcess system prompt. Accepts EITHER a static string (applied to every
110
113
  * session) OR a resolver `(chatId, threadId, config) => string` invoked once per
@@ -127,6 +130,7 @@ function createProcessFactory({
127
130
  botName = null,
128
131
  toolDispatcher = null,
129
132
  channelsClaudeBin = null,
133
+ sessionLauncher = process.env.ORCHESTRA_SESSION_LAUNCHER || null,
130
134
  displayHint = '', // orchestra: consumer surface-rendering hint
131
135
  maxOutboundFileBytes = 100 * 1024 * 1024, // orchestra: consumer outbound file cap
132
136
  // orchestra identity — forwarded to every CliProcess so the engine is neutral.
@@ -174,6 +178,7 @@ function createProcessFactory({
174
178
  tmuxRunner,
175
179
  botName,
176
180
  claudeBin: channelsClaudeBin,
181
+ sessionLauncher,
177
182
  toolDispatcher,
178
183
  displayHint: resolvedDisplayHint,
179
184
  maxOutboundFileBytes,
@@ -5,6 +5,7 @@ const fs = require('node:fs');
5
5
  const { canonicalizeToolInput } = require('../canonical-json');
6
6
 
7
7
  const TASK_NOTIFICATION_ID_RE = /<tool-use-id>\s*([^<]+?)\s*<\/tool-use-id>/g;
8
+ const MAX_WORKFLOW_TRANSCRIPT_BYTES = 16 * 1024 * 1024;
8
9
 
9
10
  function normalizeVisibleText(value) {
10
11
  return typeof value === 'string'
@@ -94,13 +95,62 @@ function result(reason, extra = {}) {
94
95
  };
95
96
  }
96
97
 
97
- async function readSnapshot(filePath, byteSize) {
98
+ async function readSnapshot(filePath, byteSize, {
99
+ prefixByteSize = null,
100
+ prefixHash = null,
101
+ fileDevice = null,
102
+ fileInode = null,
103
+ } = {}) {
98
104
  if (typeof filePath !== 'string' || !filePath || !Number.isSafeInteger(byteSize) || byteSize <= 0) {
99
105
  return { ok: false, reason: 'snapshot-missing' };
100
106
  }
107
+ if (byteSize > MAX_WORKFLOW_TRANSCRIPT_BYTES) {
108
+ return { ok: false, reason: 'snapshot-too-large' };
109
+ }
110
+ const validatesPrefix = prefixByteSize !== null || prefixHash !== null;
111
+ if (
112
+ validatesPrefix
113
+ && (
114
+ !Number.isSafeInteger(prefixByteSize)
115
+ || prefixByteSize <= 0
116
+ || prefixByteSize > byteSize
117
+ || typeof prefixHash !== 'string'
118
+ || !/^[0-9a-f]{64}$/.test(prefixHash)
119
+ )
120
+ ) {
121
+ return { ok: false, reason: 'snapshot-prefix-invalid' };
122
+ }
123
+ const validatesIdentity = fileDevice !== null || fileInode !== null;
124
+ if (
125
+ validatesIdentity
126
+ && (
127
+ typeof fileDevice !== 'string'
128
+ || !/^\d+$/.test(fileDevice)
129
+ || typeof fileInode !== 'string'
130
+ || !/^\d+$/.test(fileInode)
131
+ )
132
+ ) {
133
+ return { ok: false, reason: 'snapshot-identity-invalid' };
134
+ }
101
135
  let handle;
102
136
  try {
103
137
  handle = await fs.promises.open(filePath, 'r');
138
+ const before = await handle.stat({ bigint: true });
139
+ if (
140
+ !before.isFile()
141
+ || (
142
+ validatesIdentity
143
+ && (
144
+ before.dev.toString() !== fileDevice
145
+ || before.ino.toString() !== fileInode
146
+ )
147
+ )
148
+ ) {
149
+ return { ok: false, reason: 'snapshot-replaced' };
150
+ }
151
+ if (before.size < BigInt(byteSize)) {
152
+ return { ok: false, reason: 'snapshot-truncated' };
153
+ }
104
154
  const buffer = Buffer.allocUnsafe(byteSize);
105
155
  let offset = 0;
106
156
  while (offset < byteSize) {
@@ -109,8 +159,33 @@ async function readSnapshot(filePath, byteSize) {
109
159
  offset += bytesRead;
110
160
  }
111
161
  if (offset !== byteSize) return { ok: false, reason: 'snapshot-truncated' };
162
+ const after = await handle.stat({ bigint: true });
163
+ if (
164
+ !after.isFile()
165
+ || after.dev !== before.dev
166
+ || after.ino !== before.ino
167
+ || after.size < BigInt(byteSize)
168
+ ) {
169
+ return { ok: false, reason: 'snapshot-changed-during-read' };
170
+ }
171
+ if (
172
+ after.size === before.size
173
+ && (after.mtimeNs !== before.mtimeNs || after.ctimeNs !== before.ctimeNs)
174
+ ) {
175
+ return { ok: false, reason: 'snapshot-changed-during-read' };
176
+ }
177
+ if (
178
+ validatesPrefix
179
+ && crypto.createHash('sha256').update(buffer.subarray(0, prefixByteSize)).digest('hex') !== prefixHash
180
+ ) {
181
+ return { ok: false, reason: 'snapshot-prefix-changed' };
182
+ }
112
183
  if (buffer[byteSize - 1] !== 0x0a) return { ok: false, reason: 'partial-line' };
113
- return { ok: true, text: buffer.toString('utf8') };
184
+ return {
185
+ ok: true,
186
+ text: buffer.toString('utf8'),
187
+ hash: crypto.createHash('sha256').update(buffer).digest('hex'),
188
+ };
114
189
  } catch {
115
190
  return { ok: false, reason: 'snapshot-unreadable' };
116
191
  } finally {
@@ -235,12 +310,21 @@ async function correlateWorkflowCompletionSnapshot({
235
310
  byteSize,
236
311
  sessionId,
237
312
  finalText,
313
+ prefixByteSize,
314
+ prefixHash,
315
+ fileDevice,
316
+ fileInode,
238
317
  } = {}) {
239
318
  const normalizedFinal = normalizeVisibleText(finalText);
240
319
  if (!normalizedFinal) return result('final-empty');
241
320
  if (typeof sessionId !== 'string' || !sessionId) return result('session-missing');
242
321
 
243
- const snapshot = await readSnapshot(transcriptPath, byteSize);
322
+ const snapshot = await readSnapshot(transcriptPath, byteSize, {
323
+ prefixByteSize,
324
+ prefixHash,
325
+ fileDevice,
326
+ fileInode,
327
+ });
244
328
  if (!snapshot.ok) return result(snapshot.reason);
245
329
 
246
330
  const rows = [];
@@ -264,10 +348,13 @@ async function correlateWorkflowCompletionSnapshot({
264
348
  && (row.type === 'assistant' || row.type === 'user')
265
349
  ));
266
350
  if (!mainline.length) return result('session-mainline-missing');
351
+ const ancestryRows = rows.filter(row => (
352
+ row.sessionId === sessionId && row.isSidechain === false
353
+ ));
267
354
 
268
355
  const byUuid = new Map();
269
356
  const children = new Map();
270
- for (const row of mainline) {
357
+ for (const row of ancestryRows) {
271
358
  if (
272
359
  typeof row.uuid !== 'string'
273
360
  || !row.uuid
@@ -292,7 +379,12 @@ async function correlateWorkflowCompletionSnapshot({
292
379
  }
293
380
  }
294
381
  if (terminalIndex < 0) return result('terminal-missing');
295
- if (terminalIndex !== mainline.length - 1) return result('terminal-not-last-mainline');
382
+ if (terminalIndex !== mainline.length - 1) {
383
+ return result('terminal-not-last-mainline', {
384
+ snapshotByteSize: byteSize,
385
+ snapshotHash: snapshot.hash,
386
+ });
387
+ }
296
388
 
297
389
  const terminal = mainline[terminalIndex];
298
390
  if (
@@ -403,6 +495,8 @@ async function correlateWorkflowCompletionSnapshot({
403
495
 
404
496
  return result('eligible', {
405
497
  eligible: true,
498
+ snapshotByteSize: byteSize,
499
+ snapshotHash: snapshot.hash,
406
500
  finalHash: hashText(normalizedFinal),
407
501
  deliveredFinal: receipts.deliveredFinal,
408
502
  visibleHashes: receipts.visibleHashes,
@@ -411,6 +505,7 @@ async function correlateWorkflowCompletionSnapshot({
411
505
  }
412
506
 
413
507
  module.exports = {
508
+ MAX_WORKFLOW_TRANSCRIPT_BYTES,
414
509
  correlateWorkflowCompletionSnapshot,
415
510
  hashDeliveryArguments,
416
511
  normalizeVisibleText,
@@ -188,8 +188,10 @@ function createTmuxRunner({
188
188
  sessionPrefix = 'orchestra',
189
189
  logger = console,
190
190
  runFn = run,
191
+ requireExistingServer = false,
191
192
  } = {}) {
192
193
  const runnerPrefix = sessionPrefix;
194
+ const runTmux = (args, opts) => runFn('tmux', requireExistingServer ? ['-N', ...args] : args, opts);
193
195
  async function spawn({
194
196
  name,
195
197
  cwd,
@@ -213,7 +215,7 @@ function createTmuxRunner({
213
215
  }
214
216
  sessArgs.push(command, ...args);
215
217
  try {
216
- await runFn('tmux', sessArgs);
218
+ await runTmux(sessArgs);
217
219
  } catch (err) {
218
220
  throw Object.assign(new Error(`tmux spawn failed: ${err.message}`), {
219
221
  code: 'TMUX_SPAWN_FAILED',
@@ -229,7 +231,7 @@ function createTmuxRunner({
229
231
  // settable option). capture-pane -J in captureWide() handles
230
232
  // any remaining wrap artifacts.
231
233
  try {
232
- await runFn('tmux', ['resize-window', '-t', name, '-x', String(paneWidth)]);
234
+ await runTmux(['resize-window', '-t', name, '-x', String(paneWidth)]);
233
235
  } catch (err) {
234
236
  logger.debug?.(`[tmux-runner] resize-window failed for ${name}: ${err.message} (capture-pane -J handles wrap)`);
235
237
  }
@@ -242,7 +244,7 @@ function createTmuxRunner({
242
244
  * key names like "Enter" and "C-c".
243
245
  */
244
246
  async function sendControl(name, key) {
245
- await runFn('tmux', ['send-keys', '-t', name, key]);
247
+ await runTmux(['send-keys', '-t', name, key]);
246
248
  }
247
249
 
248
250
  // rc.13.1: paste+Enter must be ATOMIC per session. Pre-rc.13.1 two
@@ -318,13 +320,13 @@ function createTmuxRunner({
318
320
  const sanitized = sanitize(text);
319
321
  const oneLine = sanitized.replace(/\r?\n/g, MULTILINE_SEPARATOR);
320
322
  const bufName = `${runnerPrefix}-buf-${crypto.randomBytes(3).toString('hex')}`;
321
- await runFn('tmux', ['set-buffer', '-b', bufName, oneLine]);
323
+ await runTmux(['set-buffer', '-b', bufName, oneLine]);
322
324
  try {
323
325
  // -d (delete after) so the buffer doesn't accumulate.
324
- await runFn('tmux', ['paste-buffer', '-t', name, '-b', bufName, '-d']);
326
+ await runTmux(['paste-buffer', '-t', name, '-b', bufName, '-d']);
325
327
  } catch (err) {
326
328
  // Best-effort buffer cleanup if paste fails.
327
- await runFn('tmux', ['delete-buffer', '-b', bufName]).catch(() => {});
329
+ await runTmux(['delete-buffer', '-b', bufName]).catch(() => {});
328
330
  throw err;
329
331
  }
330
332
  // Drain delay — see incident note above.
@@ -346,7 +348,7 @@ function createTmuxRunner({
346
348
  const args = ['capture-pane', '-t', name, '-p'];
347
349
  if (joinWrapped) args.push('-J');
348
350
  args.push('-S', `-${lines}`);
349
- const { stdout } = await runFn('tmux', args);
351
+ const { stdout } = await runTmux(args);
350
352
  return stdout;
351
353
  }
352
354
 
@@ -360,15 +362,33 @@ function createTmuxRunner({
360
362
 
361
363
  async function sessionExists(name) {
362
364
  try {
363
- await runFn('tmux', ['has-session', '-t', name]);
365
+ await runTmux(['has-session', '-t', name]);
364
366
  return true;
365
367
  } catch {
366
368
  return false;
367
369
  }
368
370
  }
369
371
 
372
+ async function sessionProcessAlive(name) {
373
+ try {
374
+ const { stdout } = await runTmux([
375
+ 'list-panes',
376
+ '-t',
377
+ name,
378
+ '-F',
379
+ '#{pane_dead} #{pane_pid}',
380
+ ]);
381
+ return stdout
382
+ .trim()
383
+ .split('\n')
384
+ .some(line => /^0 [1-9][0-9]*$/.test(line.trim()));
385
+ } catch {
386
+ return false;
387
+ }
388
+ }
389
+
370
390
  async function killSession(name) {
371
- await runFn('tmux', ['kill-session', '-t', name]).catch(() => {});
391
+ await runTmux(['kill-session', '-t', name]).catch(() => {});
372
392
  }
373
393
 
374
394
  /**
@@ -377,7 +397,7 @@ function createTmuxRunner({
377
397
  */
378
398
  async function listPolygramSessions(botName = null) {
379
399
  try {
380
- const { stdout } = await runFn('tmux', ['list-sessions', '-F', '#{session_name}']);
400
+ const { stdout } = await runTmux(['list-sessions', '-F', '#{session_name}']);
381
401
  const all = stdout.trim().split('\n').filter(Boolean);
382
402
  const prefix = botName ? `${runnerPrefix}-${String(botName).replace(/[^\w-]/g, '_')}-` : `${runnerPrefix}-`;
383
403
  return all.filter((n) => n.startsWith(prefix));
@@ -394,6 +414,7 @@ function createTmuxRunner({
394
414
  capturePane,
395
415
  captureWide,
396
416
  sessionExists,
417
+ sessionProcessAlive,
397
418
  killSession,
398
419
  listPolygramSessions,
399
420
  sessionName: (b, c, t) => sessionName(b, c, t, sessionPrefix),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shumkov/orchestra",
3
- "version": "0.4.3",
3
+ "version": "0.6.0",
4
4
  "description": "Drive interactive Claude Code CLI sessions: spawn, inject messages via the MCP channels bridge, observe turns, recover. The transport-agnostic session engine extracted from polygram, shared by polygram (Telegram) and water (WhatsApp).",
5
5
  "type": "commonjs",
6
6
  "main": "index.js",