@shumkov/orchestra 0.5.0 → 0.7.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,237 @@
1
+ {
2
+ "cliVersion": "codex-cli 0.145.0",
3
+ "binarySha256": "1da3f4e0e96028b8a771814293c3033dafd1971f943f6c7e79b0897fe705f590",
4
+ "generatedProtocolV2CanonicalSha256": "1bc09dedc506075562d4d49b702ecab6d947dd5a8c2a9014a5cde592a0938efb",
5
+ "requestIdTypes": [
6
+ "integer",
7
+ "string"
8
+ ],
9
+ "clientRequests": {
10
+ "initialize": {
11
+ "required": [
12
+ "clientInfo",
13
+ "capabilities"
14
+ ],
15
+ "optional": [],
16
+ "internal": true,
17
+ "stateChanging": false
18
+ },
19
+ "config/read": {
20
+ "required": [
21
+ "cwd",
22
+ "includeLayers"
23
+ ],
24
+ "optional": [],
25
+ "stateChanging": false
26
+ },
27
+ "configRequirements/read": {
28
+ "required": [],
29
+ "optional": [],
30
+ "params": "omitted",
31
+ "stateChanging": false
32
+ },
33
+ "permissionProfile/list": {
34
+ "required": [
35
+ "cwd"
36
+ ],
37
+ "optional": [
38
+ "cursor"
39
+ ],
40
+ "stateChanging": false
41
+ },
42
+ "account/read": {
43
+ "required": [
44
+ "refreshToken"
45
+ ],
46
+ "optional": [],
47
+ "stateChanging": false
48
+ },
49
+ "model/list": {
50
+ "required": [
51
+ "includeHidden",
52
+ "limit"
53
+ ],
54
+ "optional": [
55
+ "cursor"
56
+ ],
57
+ "stateChanging": false
58
+ },
59
+ "thread/start": {
60
+ "required": [
61
+ "cwd",
62
+ "model"
63
+ ],
64
+ "optional": [],
65
+ "stateChanging": true
66
+ },
67
+ "thread/resume": {
68
+ "required": [
69
+ "threadId"
70
+ ],
71
+ "optional": [],
72
+ "stateChanging": true
73
+ },
74
+ "turn/start": {
75
+ "required": [
76
+ "threadId",
77
+ "input"
78
+ ],
79
+ "optional": [
80
+ "clientUserMessageId",
81
+ "model",
82
+ "effort"
83
+ ],
84
+ "stateChanging": true
85
+ },
86
+ "turn/steer": {
87
+ "required": [
88
+ "threadId",
89
+ "expectedTurnId",
90
+ "input"
91
+ ],
92
+ "optional": [
93
+ "clientUserMessageId"
94
+ ],
95
+ "stateChanging": true
96
+ },
97
+ "turn/interrupt": {
98
+ "required": [
99
+ "threadId",
100
+ "turnId"
101
+ ],
102
+ "optional": [],
103
+ "stateChanging": true
104
+ },
105
+ "thread/backgroundTerminals/list": {
106
+ "required": [
107
+ "threadId"
108
+ ],
109
+ "optional": [
110
+ "cursor",
111
+ "limit"
112
+ ],
113
+ "experimental": true,
114
+ "stateChanging": false
115
+ },
116
+ "thread/backgroundTerminals/clean": {
117
+ "required": [
118
+ "threadId"
119
+ ],
120
+ "optional": [],
121
+ "experimental": true,
122
+ "stateChanging": true
123
+ }
124
+ },
125
+ "clientNotifications": [
126
+ "initialized"
127
+ ],
128
+ "deniedClientRequests": [
129
+ "command/exec"
130
+ ],
131
+ "deliveredServerNotifications": [
132
+ "error",
133
+ "thread/status/changed",
134
+ "thread/settings/updated",
135
+ "turn/started",
136
+ "turn/completed",
137
+ "item/started",
138
+ "item/completed",
139
+ "item/agentMessage/delta"
140
+ ],
141
+ "droppedServerNotifications": [
142
+ "thread/started",
143
+ "thread/tokenUsage/updated",
144
+ "thread/goal/updated",
145
+ "thread/goal/cleared",
146
+ "turn/diff/updated",
147
+ "turn/plan/updated",
148
+ "item/plan/delta",
149
+ "item/commandExecution/outputDelta",
150
+ "item/commandExecution/terminalInteraction",
151
+ "item/fileChange/outputDelta",
152
+ "item/fileChange/patchUpdated",
153
+ "item/reasoning/summaryTextDelta",
154
+ "item/reasoning/summaryPartAdded",
155
+ "item/reasoning/textDelta",
156
+ "warning",
157
+ "deprecationNotice",
158
+ "configWarning",
159
+ "account/rateLimits/updated",
160
+ "remoteControl/status/changed",
161
+ "mcpServer/startupStatus/updated"
162
+ ],
163
+ "deniedServerRequests": {
164
+ "item/commandExecution/requestApproval": {
165
+ "result": {
166
+ "decision": "cancel"
167
+ }
168
+ },
169
+ "item/fileChange/requestApproval": {
170
+ "result": {
171
+ "decision": "cancel"
172
+ }
173
+ },
174
+ "item/tool/requestUserInput": {
175
+ "result": {
176
+ "answers": {}
177
+ }
178
+ },
179
+ "mcpServer/elicitation/request": {
180
+ "result": {
181
+ "action": "cancel"
182
+ }
183
+ },
184
+ "item/permissions/requestApproval": {
185
+ "result": {
186
+ "permissions": {},
187
+ "scope": "turn"
188
+ }
189
+ },
190
+ "item/tool/call": {
191
+ "result": {
192
+ "contentItems": [],
193
+ "success": false
194
+ }
195
+ },
196
+ "account/chatgptAuthTokens/refresh": {
197
+ "error": {
198
+ "code": -32601,
199
+ "message": "server request disabled"
200
+ }
201
+ },
202
+ "attestation/generate": {
203
+ "error": {
204
+ "code": -32601,
205
+ "message": "server request disabled"
206
+ }
207
+ },
208
+ "currentTime/read": {
209
+ "error": {
210
+ "code": -32601,
211
+ "message": "server request disabled"
212
+ }
213
+ },
214
+ "applyPatchApproval": {
215
+ "result": {
216
+ "decision": "abort"
217
+ }
218
+ },
219
+ "execCommandApproval": {
220
+ "result": {
221
+ "decision": "abort"
222
+ }
223
+ }
224
+ },
225
+ "recognizedRpcErrors": {
226
+ "thread/resume": [
227
+ "thread not found"
228
+ ],
229
+ "turn/steer": [
230
+ "no active turn to steer"
231
+ ],
232
+ "turn/interrupt": [
233
+ "no active turn to interrupt"
234
+ ]
235
+ },
236
+ "provenance": "Curated positive production subset derived from the pinned experimental v2 schema; the canonical generated bundle hash is verified by the U1 compatibility gate."
237
+ }
@@ -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();