@shumkov/orchestra 0.5.0 → 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
@@ -372,6 +374,9 @@ class CliProcess extends Process {
372
374
  // Set true when bridge writes {kind:'mcp-ready'} after claude's first
373
375
  // ListToolsRequest (Finding 0.3.A — cold-spawn race fix).
374
376
  this.mcpReady = false;
377
+ this._cancelBridgeHandshakeWait = null;
378
+ this._bridgeHandshakeCancellationError = null;
379
+ this.startupPingTimer = null;
375
380
  this.pingTimer = null;
376
381
  // Review P1 #6: daemon-side pong tracking. Without it, a half-open socket
377
382
  // (bridge frozen but TCP alive) is invisible to the daemon. We record the
@@ -570,6 +575,7 @@ class CliProcess extends Process {
570
575
  await this._createSocketServer();
571
576
  await this._spawnTmuxClaude({ tmuxName, opts });
572
577
  await this._waitForBridgeHandshake();
578
+ this._stopStartupPingLoop();
573
579
  // Phase 1.3: arm hook tail AFTER spawn so this._hookNdjsonPath is
574
580
  // populated (set inside _spawnTmuxClaude when writeHookFiles runs).
575
581
  // Mirrors tmux-process.js:_armHookTail timing.
@@ -604,6 +610,7 @@ class CliProcess extends Process {
604
610
  * preserves the calling pattern (teardown must not mask the start() error).
605
611
  */
606
612
  async _teardownOnStartFailure() {
613
+ this._stopStartupPingLoop();
607
614
  if (this.bridgeServer) {
608
615
  try { await this.bridgeServer.close(); } catch {}
609
616
  this.bridgeServer = null;
@@ -656,6 +663,7 @@ class CliProcess extends Process {
656
663
 
657
664
  this.bridgeServer.on('bridge-ready', () => {
658
665
  this.bridgeReady = true;
666
+ this._startStartupPingLoop();
659
667
  this.emit('bridge-ready');
660
668
  });
661
669
 
@@ -1153,23 +1161,81 @@ class CliProcess extends Process {
1153
1161
  // Both waits resolve race-safe via state flags set in _createSocketServer
1154
1162
  // listeners (bridgeReady, mcpReady).
1155
1163
  _waitForBridgeHandshake() {
1156
- const waitBridge = this.bridgeReady ? Promise.resolve() : new Promise((resolve, reject) => {
1157
- const timer = setTimeout(() => {
1158
- const err = new Error(`bridge handshake timeout (${this.handshakeTimeoutMs}ms)`);
1159
- err.code = 'CHANNELS_HANDSHAKE_TIMEOUT';
1160
- reject(err);
1161
- }, this.handshakeTimeoutMs);
1162
- this.once('bridge-ready', () => { clearTimeout(timer); resolve(); });
1163
- });
1164
- const waitMcp = this.mcpReady ? Promise.resolve() : new Promise((resolve, reject) => {
1165
- const timer = setTimeout(() => {
1166
- const err = new Error(`mcp-ready timeout (${this.mcpReadyTimeoutMs}ms) — bridge connected but claude never sent first ListToolsRequest`);
1167
- 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';
1168
1172
  reject(err);
1169
- }, this.mcpReadyTimeoutMs);
1170
- 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();
1171
1231
  });
1172
- 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);
1173
1239
  }
1174
1240
 
1175
1241
  // ─── bridge protocol semantics ─────────────────────────────────────
@@ -1344,20 +1410,161 @@ class CliProcess extends Process {
1344
1410
  || typeof ev.lastAssistantMessage !== 'string'
1345
1411
  || !normalizeVisibleText(ev.lastAssistantMessage)
1346
1412
  ) return null;
1413
+ let fd;
1347
1414
  try {
1348
- const stat = fs.statSync(ev.transcriptPath);
1349
- 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;
1350
1442
  return {
1351
1443
  transcriptPath: ev.transcriptPath,
1352
- 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(),
1353
1449
  sessionId: ev.sessionId || this.claudeSessionId,
1354
1450
  finalText: ev.lastAssistantMessage,
1451
+ workHookSeq: this._workHookSeq || 0,
1355
1452
  };
1356
1453
  } catch {
1357
1454
  return null;
1455
+ } finally {
1456
+ if (fd !== undefined) {
1457
+ try {
1458
+ fs.closeSync(fd);
1459
+ } catch {}
1460
+ }
1358
1461
  }
1359
1462
  }
1360
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
+ }
1564
+ }
1565
+ return ineligible('transcript-settle-timeout');
1566
+ }
1567
+
1361
1568
  _beginWorkflowCompletionDecision(snapshot) {
1362
1569
  if (!snapshot) {
1363
1570
  this._logEvent('workflow-completion-ineligible', { reason: 'snapshot-missing' });
@@ -1365,7 +1572,11 @@ class CliProcess extends Process {
1365
1572
  }
1366
1573
  const generation = this._deliveryGeneration;
1367
1574
  const decisionKey = crypto.createHash('sha256')
1368
- .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
+ )
1369
1580
  .digest('hex');
1370
1581
  const now = Date.now();
1371
1582
  for (const [key, expiry] of this._workflowDecisionKeys) {
@@ -1380,9 +1591,13 @@ class CliProcess extends Process {
1380
1591
  });
1381
1592
 
1382
1593
  Promise.resolve()
1383
- .then(() => correlateWorkflowCompletionSnapshot(snapshot))
1594
+ .then(() => this._correlateSettledWorkflowSnapshot(snapshot, generation))
1384
1595
  .then(async correlation => {
1385
- 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
+ }
1386
1601
  if (!correlation.eligible) {
1387
1602
  this._logEvent('workflow-completion-ineligible', { reason: correlation.reason });
1388
1603
  return;
@@ -1406,6 +1621,10 @@ class CliProcess extends Process {
1406
1621
  generation,
1407
1622
  );
1408
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
+ }
1409
1628
  if (outcome.outcome === 'missing' || outcome.outcome === 'mismatch' || outcome.outcome === 'invalidated') {
1410
1629
  this._logEvent('workflow-completion-ineligible', { reason: `attempt-${outcome.outcome}` });
1411
1630
  return;
@@ -1425,6 +1644,10 @@ class CliProcess extends Process {
1425
1644
  this._logEvent('workflow-completion-ineligible', { reason: 'overlapping-turn' });
1426
1645
  return;
1427
1646
  }
1647
+ if ((this._workHookSeq || 0) !== snapshot.workHookSeq) {
1648
+ this._logEvent('workflow-completion-ineligible', { reason: 'intervening-work' });
1649
+ return;
1650
+ }
1428
1651
  this.emit('autonomous-assistant-message', {
1429
1652
  text: snapshot.finalText,
1430
1653
  sessionId: this.claudeSessionId,
@@ -3819,6 +4042,7 @@ class CliProcess extends Process {
3819
4042
  async _handleBridgeDisconnected(reason = 'socket-close') {
3820
4043
  this.bridgeReady = false;
3821
4044
  this.mcpReady = false;
4045
+ this._stopStartupPingLoop();
3822
4046
  if (this.closed || this._bridgeDisconnecting) return;
3823
4047
  this._bridgeDisconnecting = true;
3824
4048
  this._bridgeDisconnectErrorPromise = this._bridgeDisconnectError();
@@ -3886,7 +4110,9 @@ class CliProcess extends Process {
3886
4110
  async _doKill(reason) {
3887
4111
  this.closed = true;
3888
4112
  this.inFlight = false;
4113
+ this._cancelPendingBridgeHandshake('KILLED', `session killed: ${reason}`);
3889
4114
  this._invalidatePendingDeliveryWork();
4115
+ this._stopStartupPingLoop();
3890
4116
 
3891
4117
  this._stopQuestionKeepAlive(); // 0.12: drop the interactive-question keep-alive
3892
4118
  this._openQuestions.clear();
@@ -4109,6 +4335,7 @@ class CliProcess extends Process {
4109
4335
  * @returns {Promise<{closed: boolean, drainedPendings: number}>}
4110
4336
  */
4111
4337
  async resetSession({ reason = 'reset' } = {}) {
4338
+ this._cancelPendingBridgeHandshake('RESET', `session reset: ${reason}`);
4112
4339
  this._invalidatePendingDeliveryWork();
4113
4340
  let drained = 0;
4114
4341
  // First drain pendingTurns (channels-native bookkeeping). Each entry
@@ -4176,6 +4403,7 @@ class CliProcess extends Process {
4176
4403
  // resetSession; channels cannot because there's no in-place re-init
4177
4404
  // path — claude needs a fresh spawn to reset its conversation state.)
4178
4405
  this.closed = true;
4406
+ this._stopStartupPingLoop();
4179
4407
  if (this.pingTimer) {
4180
4408
  clearInterval(this.pingTimer);
4181
4409
  this.pingTimer = null;
@@ -4334,6 +4562,21 @@ class CliProcess extends Process {
4334
4562
  }
4335
4563
  }
4336
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
+
4337
4580
  _startPingLoop() {
4338
4581
  // P1 #6: seed lastPongAt so the watchdog has a fresh baseline.
4339
4582
  this.lastPongAt = Date.now();
@@ -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,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shumkov/orchestra",
3
- "version": "0.5.0",
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",