@shumkov/orchestra 0.4.2 → 0.5.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.
@@ -60,6 +60,11 @@ const { DEFAULT_ATTACHMENT_BASE } = require('./attachment-base');
60
60
  const { resolveCompactionWarnConfig } = require('../compaction-warn');
61
61
  const { readContextTokens, contextPct } = require('../context-usage');
62
62
  const { runStartupGate } = require('../tmux/startup-gate');
63
+ const {
64
+ correlateWorkflowCompletionSnapshot,
65
+ hashDeliveryArguments,
66
+ normalizeVisibleText,
67
+ } = require('./workflow-completion-correlation');
63
68
 
64
69
  const BRIDGE_PATH = path.resolve(__dirname, 'channels-bridge.mjs');
65
70
  const DEFAULT_HANDSHAKE_TIMEOUT_MS = 15_000;
@@ -112,6 +117,26 @@ const DEFAULT_TOOL_RATE_LIMIT_PER_SEC = 5; // P2 ADV-6: cap on reply tool call
112
117
  const DEFAULT_TOOL_RATE_BURST = 20; // ADV-6: token bucket capacity
113
118
  const DEFAULT_QUEUE_CAP = 50; // Parity P2: match SDK/tmux pendingQueue cap
114
119
 
120
+ function validateSessionLauncher(sessionLauncher) {
121
+ if (!sessionLauncher) return null;
122
+ if (typeof sessionLauncher !== 'string' || !path.isAbsolute(sessionLauncher)) {
123
+ throw Object.assign(new TypeError('CliProcess: sessionLauncher must be an absolute executable path'), {
124
+ code: 'SESSION_LAUNCHER_INVALID',
125
+ });
126
+ }
127
+ try {
128
+ if (!fs.statSync(sessionLauncher).isFile()) {
129
+ throw new Error('not a regular file');
130
+ }
131
+ fs.accessSync(sessionLauncher, fs.constants.X_OK);
132
+ } catch {
133
+ throw Object.assign(new TypeError(`CliProcess: sessionLauncher is not an executable file: ${sessionLauncher}`), {
134
+ code: 'SESSION_LAUNCHER_INVALID',
135
+ });
136
+ }
137
+ return sessionLauncher;
138
+ }
139
+
115
140
  // Review F#17: mid-turn dialog watchdog. Even though channels uses MCP for IO,
116
141
  // the underlying claude TUI can still pop interactive prompts mid-turn that
117
142
  // don't surface as MCP notifications (session-age, future "approaching usage
@@ -248,6 +273,7 @@ class CliProcess extends Process {
248
273
  sessionKey, chatId, threadId, label,
249
274
  tmuxRunner, botName,
250
275
  claudeBin = null,
276
+ sessionLauncher = process.env.ORCHESTRA_SESSION_LAUNCHER || null,
251
277
  toolDispatcher,
252
278
  // Extraction-time API (orchestra): the consumer injects its surface-rendering
253
279
  // hint (appended to the system prompt) and outbound file-size cap, so the engine
@@ -303,6 +329,7 @@ class CliProcess extends Process {
303
329
  throw new TypeError('CliProcess: claudeBin required (or ORCHESTRA_CLAUDE_BIN env)');
304
330
  }
305
331
  this.claudeBin = claudeBin || process.env.ORCHESTRA_CLAUDE_BIN;
332
+ this.sessionLauncher = validateSessionLauncher(sessionLauncher);
306
333
  this.toolDispatcher = toolDispatcher;
307
334
  this.displayHint = displayHint;
308
335
  this._injectedMaxOutboundFileBytes = maxOutboundFileBytes;
@@ -340,6 +367,7 @@ class CliProcess extends Process {
340
367
  this.mcpConfigPath = null; // P0 #1: 0o600 tmp file holding bridge env (no argv leak)
341
368
  this.tmuxSession = null; // tmux session name
342
369
  this.bridgeReady = false;
370
+ this._bridgeDisconnectErrorPromise = null;
343
371
  // 0.12 Phase 1.6: claude-side MCP-server registration completion flag.
344
372
  // Set true when bridge writes {kind:'mcp-ready'} after claude's first
345
373
  // ListToolsRequest (Finding 0.3.A — cold-spawn race fix).
@@ -383,7 +411,7 @@ class CliProcess extends Process {
383
411
  // doesn't re-invoke the dispatcher → duplicate TG send. Set is bounded
384
412
  // to RECENT_TOOL_CALL_LIMIT entries via FIFO eviction.
385
413
  this.recentToolCallIds = new Set();
386
- this.recentToolCallResults = new Map(); // tool_call_id → message_id (0.13: replay on re-ACK)
414
+ this.recentToolCallResults = new Map(); // tool_call_id → successful direct-dispatch receipt
387
415
  this.recentToolCallOrder = []; // FIFO bound
388
416
  // Review F#17: per-pattern last-fired timestamp for the mid-turn dialog
389
417
  // watchdog. Dedups within MID_TURN_DEDUP_WINDOW_MS so a lingering dialog
@@ -403,7 +431,7 @@ class CliProcess extends Process {
403
431
  // message. Track (chat_id, sha256(text)) for 60s to catch this even when
404
432
  // the tool_call_id changes. TTL is tight enough that legitimate repeated
405
433
  // sends ("ok" twice in a row) eventually pass.
406
- this.recentContentHashes = new Map(); // key → expiryTs
434
+ this.recentContentHashes = new Map(); // key → { expiry, message_id, attempt_id }
407
435
  this.contentDedupWindowMs = 60_000;
408
436
  // Content-dedup key → Promise<dispatch result> for a reply dispatch that
409
437
  // is STILL AWAITING the dispatcher (e.g. a large file upload running past
@@ -412,6 +440,15 @@ class CliProcess extends Process {
412
440
  // tool_call_id, same content) re-delivers text + file. A duplicate
413
441
  // arriving in that window joins the in-flight promise instead.
414
442
  this._inFlightDispatches = new Map();
443
+ // Only unresolved dispatcher attempts and transcript decisions are
444
+ // lifecycle state. Settled delivery authority lives in Claude's transcript;
445
+ // the bounded outcome ledger exists solely to resolve a bridge timeout that
446
+ // names the same opaque attempt id and immutable argument hash.
447
+ this._deliveryAttempts = new Map();
448
+ this._deliveryAttemptOrder = [];
449
+ this._workflowDecisionKeys = new Map();
450
+ this._activeWorkflowDecisions = new Set();
451
+ this._deliveryGeneration = 0;
415
452
 
416
453
  // pending turn(s): turn_id → { resolve, reject, replies: [], seen, quietTimer,
417
454
  // hardTimer, absoluteTimer, _activityQuietTimer, startedAt }
@@ -633,7 +670,11 @@ class CliProcess extends Process {
633
670
 
634
671
  this.bridgeServer.on('bridge-message', msg => this._handleBridgeMessage(msg));
635
672
 
636
- this.bridgeServer.on('bridge-disconnected', () => this._handleBridgeDisconnected());
673
+ this.bridgeServer.on('bridge-disconnected', () => {
674
+ this._handleBridgeDisconnected().catch(err => {
675
+ this.logger.error?.(`[${this.label}] channels: bridge disconnect handling failed: ${err.message}`);
676
+ });
677
+ });
637
678
 
638
679
  await this.bridgeServer.listen();
639
680
  }
@@ -991,8 +1032,8 @@ class CliProcess extends Process {
991
1032
  await this.runner.spawn({
992
1033
  name: tmuxName,
993
1034
  cwd: resolvedCwd || opts.cwd || process.cwd(),
994
- command: this.claudeBin,
995
- args: claudeArgs,
1035
+ command: this.sessionLauncher || this.claudeBin,
1036
+ args: this.sessionLauncher ? [this.claudeBin, ...claudeArgs] : claudeArgs,
996
1037
  envExtras: {
997
1038
  // Resume-dialog suppression (docs/0.13-resume-dialog-fix-spec.md B1):
998
1039
  // claude's session-age "resume-return" dialog fires when sessionAge ≥
@@ -1218,17 +1259,198 @@ class CliProcess extends Process {
1218
1259
  }
1219
1260
 
1220
1261
  /**
1221
- * Review F#16: stable dedup key for content-based deduplication of reply
1222
- * tool calls. We hash (chat_id || text) so identical text to different chats
1223
- * never collides. SHA-256 truncated to 32 hex chars is plenty for collision
1224
- * resistance within the 60s window.
1262
+ * Stable dedup key for immutable reply delivery arguments. Including the
1263
+ * destination prevents identical content sent to different chats from
1264
+ * colliding.
1225
1265
  */
1226
- _buildContentDedupKey(chatId, text) {
1227
- return `${chatId}::${crypto
1228
- .createHash('sha256')
1229
- .update(text, 'utf8')
1230
- .digest('hex')
1231
- .slice(0, 32)}`;
1266
+ _buildContentDedupKey(args) {
1267
+ return hashDeliveryArguments('reply', args);
1268
+ }
1269
+
1270
+ _pruneDeliveryAttempts(now = Date.now()) {
1271
+ for (const [attemptId, entry] of this._deliveryAttempts) {
1272
+ if (entry.outcome !== 'pending' && entry.expiry <= now) {
1273
+ this._deliveryAttempts.delete(attemptId);
1274
+ }
1275
+ }
1276
+ while (this._deliveryAttemptOrder.length > RECENT_TOOL_CALL_LIMIT) {
1277
+ const attemptId = this._deliveryAttemptOrder.shift();
1278
+ const entry = this._deliveryAttempts.get(attemptId);
1279
+ if (entry?.outcome !== 'pending') this._deliveryAttempts.delete(attemptId);
1280
+ }
1281
+ }
1282
+
1283
+ _registerDeliveryAttempt(attemptId, argumentHash) {
1284
+ const generation = this._deliveryGeneration;
1285
+ let settle;
1286
+ const promise = new Promise(resolve => { settle = resolve; });
1287
+ const entry = {
1288
+ attemptId,
1289
+ argumentHash,
1290
+ generation,
1291
+ outcome: 'pending',
1292
+ expiry: Infinity,
1293
+ promise,
1294
+ settle,
1295
+ };
1296
+ this._deliveryAttempts.set(attemptId, entry);
1297
+ return entry;
1298
+ }
1299
+
1300
+ _settleDeliveryAttempt(entry, outcome) {
1301
+ if (
1302
+ entry.generation !== this._deliveryGeneration
1303
+ || this._deliveryAttempts.get(entry.attemptId) !== entry
1304
+ ) {
1305
+ entry.settle();
1306
+ return;
1307
+ }
1308
+ entry.outcome = outcome;
1309
+ entry.expiry = Date.now() + this.contentDedupWindowMs;
1310
+ entry.settle();
1311
+ this._deliveryAttemptOrder.push(entry.attemptId);
1312
+ this._pruneDeliveryAttempts();
1313
+ this.emit('delivery-work-settled');
1314
+ }
1315
+
1316
+ async _readDeliveryAttempt(attemptId, argumentHash, generation) {
1317
+ const entry = this._deliveryAttempts.get(attemptId);
1318
+ if (!entry || entry.generation !== generation) return { outcome: 'missing' };
1319
+ if (entry.argumentHash !== argumentHash) return { outcome: 'mismatch' };
1320
+ if (entry.outcome === 'pending') await entry.promise;
1321
+ if (generation !== this._deliveryGeneration) return { outcome: 'invalidated' };
1322
+ const current = this._deliveryAttempts.get(attemptId);
1323
+ if (!current || current.argumentHash !== argumentHash) return { outcome: 'missing' };
1324
+ return { outcome: current.outcome };
1325
+ }
1326
+
1327
+ _invalidatePendingDeliveryWork() {
1328
+ const hadPending = this.hasPendingDeliveryWork();
1329
+ this._deliveryGeneration++;
1330
+ for (const entry of this._deliveryAttempts.values()) {
1331
+ if (entry.outcome === 'pending') entry.settle();
1332
+ }
1333
+ this._deliveryAttempts.clear();
1334
+ this._deliveryAttemptOrder.length = 0;
1335
+ this._activeWorkflowDecisions.clear();
1336
+ this._workflowDecisionKeys.clear();
1337
+ if (hadPending) this.emit('delivery-work-settled');
1338
+ }
1339
+
1340
+ _captureWorkflowCompletionSnapshot(ev) {
1341
+ if (
1342
+ typeof ev.transcriptPath !== 'string'
1343
+ || !ev.transcriptPath
1344
+ || typeof ev.lastAssistantMessage !== 'string'
1345
+ || !normalizeVisibleText(ev.lastAssistantMessage)
1346
+ ) return null;
1347
+ try {
1348
+ const stat = fs.statSync(ev.transcriptPath);
1349
+ if (!stat.isFile() || stat.size <= 0) return null;
1350
+ return {
1351
+ transcriptPath: ev.transcriptPath,
1352
+ byteSize: stat.size,
1353
+ sessionId: ev.sessionId || this.claudeSessionId,
1354
+ finalText: ev.lastAssistantMessage,
1355
+ };
1356
+ } catch {
1357
+ return null;
1358
+ }
1359
+ }
1360
+
1361
+ _beginWorkflowCompletionDecision(snapshot) {
1362
+ if (!snapshot) {
1363
+ this._logEvent('workflow-completion-ineligible', { reason: 'snapshot-missing' });
1364
+ return;
1365
+ }
1366
+ const generation = this._deliveryGeneration;
1367
+ const decisionKey = crypto.createHash('sha256')
1368
+ .update(`${snapshot.transcriptPath}\0${snapshot.byteSize}\0${normalizeVisibleText(snapshot.finalText)}`, 'utf8')
1369
+ .digest('hex');
1370
+ const now = Date.now();
1371
+ for (const [key, expiry] of this._workflowDecisionKeys) {
1372
+ if (expiry <= now) this._workflowDecisionKeys.delete(key);
1373
+ }
1374
+ if (this._activeWorkflowDecisions.has(decisionKey) || this._workflowDecisionKeys.has(decisionKey)) return;
1375
+
1376
+ this._activeWorkflowDecisions.add(decisionKey);
1377
+ this._logEvent('workflow-completion-decision-started', {
1378
+ transcript_bytes: snapshot.byteSize,
1379
+ final_len: snapshot.finalText.length,
1380
+ });
1381
+
1382
+ Promise.resolve()
1383
+ .then(() => correlateWorkflowCompletionSnapshot(snapshot))
1384
+ .then(async correlation => {
1385
+ if (generation !== this._deliveryGeneration || this.closed) return;
1386
+ if (!correlation.eligible) {
1387
+ this._logEvent('workflow-completion-ineligible', { reason: correlation.reason });
1388
+ return;
1389
+ }
1390
+ if (correlation.deliveredFinal) {
1391
+ this._logEvent('workflow-completion-suppressed', { reason: 'direct-final' });
1392
+ return;
1393
+ }
1394
+ if (correlation.visibleHashes.includes(correlation.finalHash)) {
1395
+ this._logEvent('workflow-completion-suppressed', { reason: 'visible-text-match' });
1396
+ return;
1397
+ }
1398
+
1399
+ for (const pending of correlation.unresolvedAttempts) {
1400
+ this._logEvent('workflow-completion-deferred', {
1401
+ attempt_id_hash: crypto.createHash('sha256').update(pending.attemptId, 'utf8').digest('hex'),
1402
+ });
1403
+ const outcome = await this._readDeliveryAttempt(
1404
+ pending.attemptId,
1405
+ pending.argumentHash,
1406
+ generation,
1407
+ );
1408
+ if (generation !== this._deliveryGeneration || this.closed) return;
1409
+ if (outcome.outcome === 'missing' || outcome.outcome === 'mismatch' || outcome.outcome === 'invalidated') {
1410
+ this._logEvent('workflow-completion-ineligible', { reason: `attempt-${outcome.outcome}` });
1411
+ return;
1412
+ }
1413
+ if (
1414
+ outcome.outcome === 'sent'
1415
+ && (pending.finalReply || pending.visibleHash === correlation.finalHash)
1416
+ ) {
1417
+ this._logEvent('workflow-completion-suppressed', { reason: 'late-direct-success' });
1418
+ return;
1419
+ }
1420
+ }
1421
+
1422
+ // A new consumer turn makes Stop ownership ambiguous. The fallback
1423
+ // covers only the non-overlapping autonomous cycle.
1424
+ if (this.pendingTurns.size !== 0) {
1425
+ this._logEvent('workflow-completion-ineligible', { reason: 'overlapping-turn' });
1426
+ return;
1427
+ }
1428
+ this.emit('autonomous-assistant-message', {
1429
+ text: snapshot.finalText,
1430
+ sessionId: this.claudeSessionId,
1431
+ backend: this.backend,
1432
+ alreadyDelivered: false,
1433
+ });
1434
+ this._logEvent('workflow-completion-fallback', {
1435
+ final_len: snapshot.finalText.length,
1436
+ receipt_count: correlation.visibleHashes.length + correlation.unresolvedAttempts.length,
1437
+ });
1438
+ })
1439
+ .catch(err => {
1440
+ this._logEvent('workflow-completion-ineligible', {
1441
+ reason: 'decision-error',
1442
+ error_name: err?.name || 'Error',
1443
+ });
1444
+ })
1445
+ .finally(() => {
1446
+ if (generation !== this._deliveryGeneration) return;
1447
+ this._activeWorkflowDecisions.delete(decisionKey);
1448
+ this._workflowDecisionKeys.set(decisionKey, Date.now() + this.contentDedupWindowMs);
1449
+ while (this._workflowDecisionKeys.size > RECENT_TOOL_CALL_LIMIT) {
1450
+ this._workflowDecisionKeys.delete(this._workflowDecisionKeys.keys().next().value);
1451
+ }
1452
+ this.emit('delivery-work-settled');
1453
+ });
1232
1454
  }
1233
1455
 
1234
1456
  async _dispatchToolCall(msg) {
@@ -1257,12 +1479,32 @@ class CliProcess extends Process {
1257
1479
  // Without this, Claude's reply-retry on isError (which can fire after a
1258
1480
  // slow ack timeout) → double-send of the same TG message.
1259
1481
  if (msg.tool_call_id && this.recentToolCallIds.has(msg.tool_call_id)) {
1482
+ const prior = this.recentToolCallResults.get(msg.tool_call_id);
1483
+ const argumentHash = hashDeliveryArguments(msg.name, args);
1484
+ if (!prior || !argumentHash || prior.argumentHash !== argumentHash) {
1485
+ this._writeToBridge({
1486
+ kind: 'tool_ack',
1487
+ tool_call_id: msg.tool_call_id,
1488
+ ok: false,
1489
+ error: 'duplicate attempt arguments mismatch',
1490
+ attempt_id: msg.tool_call_id,
1491
+ });
1492
+ return;
1493
+ }
1260
1494
  this.logger.warn?.(
1261
1495
  `[${this.label}] channels: duplicate tool_call_id=${msg.tool_call_id} — re-ACKing without dispatch`,
1262
1496
  );
1263
1497
  // 0.13: replay the cached message_id so a retried reply keeps its edit handle
1264
1498
  // (re-ACKing without it would null the handle → progressive status silently breaks).
1265
- this._writeToBridge({ kind: 'tool_ack', tool_call_id: msg.tool_call_id, ok: true, message_id: this.recentToolCallResults.get(msg.tool_call_id) ?? null });
1499
+ this._writeToBridge({
1500
+ kind: 'tool_ack',
1501
+ tool_call_id: msg.tool_call_id,
1502
+ ok: true,
1503
+ message_id: prior.message_id,
1504
+ attempt_id: msg.tool_call_id,
1505
+ delivery: 'replayed',
1506
+ replay_of: prior.attempt_id,
1507
+ });
1266
1508
  return;
1267
1509
  }
1268
1510
 
@@ -1324,8 +1566,10 @@ class CliProcess extends Process {
1324
1566
  // Review F#16: secondary content-hash dedup catches retries that come in
1325
1567
  // with a NEW tool_call_id (Claude regenerates the id on each retry after
1326
1568
  // an isError ack). Window-based so legit repeat sends eventually pass.
1569
+ let replyDedupKey = null;
1327
1570
  if (msg.name === 'reply' && typeof args.text === 'string' && args.chat_id != null) {
1328
- const dedupKey = this._buildContentDedupKey(args.chat_id, args.text);
1571
+ replyDedupKey = this._buildContentDedupKey(args);
1572
+ const dedupKey = replyDedupKey;
1329
1573
  const entry = this.recentContentHashes.get(dedupKey); // { expiry, message_id }
1330
1574
  const nowDedup = Date.now();
1331
1575
  // Evict stale entries opportunistically (avoids unbounded growth).
@@ -1346,7 +1590,15 @@ class CliProcess extends Process {
1346
1590
  });
1347
1591
  // 0.13: replay the ORIGINAL bubble's message_id so a retried identical reply
1348
1592
  // keeps its edit handle (the slow-ack-retry case progressive status targets).
1349
- this._writeToBridge({ kind: 'tool_ack', tool_call_id: msg.tool_call_id, ok: true, message_id: entry.message_id ?? null });
1593
+ this._writeToBridge({
1594
+ kind: 'tool_ack',
1595
+ tool_call_id: msg.tool_call_id,
1596
+ ok: true,
1597
+ message_id: entry.message_id ?? null,
1598
+ attempt_id: msg.tool_call_id,
1599
+ delivery: 'replayed',
1600
+ replay_of: entry.attempt_id,
1601
+ });
1350
1602
  return;
1351
1603
  }
1352
1604
  // The same content may be dispatching RIGHT NOW (slow upload past the
@@ -1363,12 +1615,23 @@ class CliProcess extends Process {
1363
1615
  tool_call_id: msg.tool_call_id,
1364
1616
  chat_id: args.chat_id,
1365
1617
  });
1366
- const prior = await inflight;
1618
+ const joinedAttempt = this._registerDeliveryAttempt(msg.tool_call_id, dedupKey);
1619
+ let prior;
1620
+ try {
1621
+ prior = await inflight.promise;
1622
+ this._settleDeliveryAttempt(joinedAttempt, prior?.ok ? 'sent' : 'failed');
1623
+ } catch (err) {
1624
+ this._settleDeliveryAttempt(joinedAttempt, 'failed');
1625
+ prior = { ok: false, error: err?.message || 'in-flight dispatch failed' };
1626
+ }
1367
1627
  this._writeToBridge({
1368
1628
  kind: 'tool_ack', tool_call_id: msg.tool_call_id,
1369
1629
  ok: !!prior?.ok,
1370
1630
  error: prior?.ok ? undefined : (prior?.error || 'in-flight dispatch failed'),
1371
1631
  message_id: prior?.message_id ?? null,
1632
+ attempt_id: msg.tool_call_id,
1633
+ delivery: prior?.ok ? 'replayed' : undefined,
1634
+ replay_of: inflight.attemptId,
1372
1635
  });
1373
1636
  return;
1374
1637
  }
@@ -1391,6 +1654,7 @@ class CliProcess extends Process {
1391
1654
  this._writeToBridge({
1392
1655
  kind: 'tool_ack', tool_call_id: msg.tool_call_id, ok: false,
1393
1656
  error: `rate limit exceeded (${this.toolRatePerSec}/s)`,
1657
+ attempt_id: msg.tool_call_id,
1394
1658
  });
1395
1659
  return;
1396
1660
  }
@@ -1408,7 +1672,13 @@ class CliProcess extends Process {
1408
1672
  `[${this.label}] channels: tool chat_id mismatch (got ${args.chat_id}, expected ${this.chatId}) — dropping`,
1409
1673
  );
1410
1674
  }
1411
- this._writeToBridge({ kind: 'tool_ack', tool_call_id: msg.tool_call_id, ok: false, error: 'chat_id mismatch' });
1675
+ this._writeToBridge({
1676
+ kind: 'tool_ack',
1677
+ tool_call_id: msg.tool_call_id,
1678
+ ok: false,
1679
+ error: 'chat_id mismatch',
1680
+ attempt_id: msg.tool_call_id,
1681
+ });
1412
1682
  return;
1413
1683
  }
1414
1684
 
@@ -1449,18 +1719,21 @@ class CliProcess extends Process {
1449
1719
  }
1450
1720
  }
1451
1721
 
1452
- // Mark this reply's content in-flight BEFORE awaiting the dispatcher so
1453
- // a retry arriving mid-dispatch joins it (see the in-flight check above).
1454
- let inflightKey = null;
1455
- let inflightSettle = null;
1456
- if (msg.name === 'reply' && typeof args.text === 'string' && args.chat_id != null) {
1457
- inflightKey = this._buildContentDedupKey(args.chat_id, args.text);
1458
- this._inFlightDispatches.set(inflightKey, new Promise(res => { inflightSettle = res; }));
1722
+ const argumentHash = replyDedupKey || hashDeliveryArguments(msg.name, args);
1723
+ if ((msg.name === 'reply' || msg.name === 'edit_message') && !argumentHash) {
1724
+ this._writeToBridge({
1725
+ kind: 'tool_ack',
1726
+ tool_call_id: msg.tool_call_id,
1727
+ ok: false,
1728
+ error: 'invalid delivery arguments',
1729
+ attempt_id: msg.tool_call_id,
1730
+ });
1731
+ return;
1459
1732
  }
1460
-
1461
- let result;
1462
- try {
1463
- result = await this.toolDispatcher({
1733
+ const attempt = argumentHash
1734
+ ? this._registerDeliveryAttempt(msg.tool_call_id, argumentHash)
1735
+ : null;
1736
+ const dispatchPromise = Promise.resolve().then(() => this.toolDispatcher({
1464
1737
  sessionKey: this.sessionKey,
1465
1738
  chatId: this.chatId,
1466
1739
  threadId: this.threadId,
@@ -1477,14 +1750,39 @@ class CliProcess extends Process {
1477
1750
  participantJid: sourceMsgId != null ? (sourceEntry?.participantJid ?? null) : null,
1478
1751
  sessionCwd: this.sessionCwd, // P0 #2: dispatcher uses this to allowlist file roots
1479
1752
  maxOutboundFileBytes: this.maxOutboundFileBytes, // backend/chat-derived upload cap
1753
+ }));
1754
+
1755
+ // Mark this reply's immutable delivery arguments in-flight before awaiting
1756
+ // the dispatcher so a retry can join the exact original attempt.
1757
+ let inflightKey = null;
1758
+ if (replyDedupKey) {
1759
+ inflightKey = replyDedupKey;
1760
+ this._inFlightDispatches.set(inflightKey, {
1761
+ promise: dispatchPromise,
1762
+ attemptId: msg.tool_call_id,
1480
1763
  });
1764
+ }
1765
+
1766
+ let result;
1767
+ try {
1768
+ result = await dispatchPromise;
1769
+ if (attempt) this._settleDeliveryAttempt(attempt, result?.ok ? 'sent' : 'failed');
1481
1770
  } catch (err) {
1482
- this._writeToBridge({ kind: 'tool_ack', tool_call_id: msg.tool_call_id, ok: false, error: err.message });
1771
+ if (attempt) this._settleDeliveryAttempt(attempt, 'failed');
1772
+ this._writeToBridge({
1773
+ kind: 'tool_ack',
1774
+ tool_call_id: msg.tool_call_id,
1775
+ ok: false,
1776
+ error: err.message,
1777
+ attempt_id: msg.tool_call_id,
1778
+ });
1483
1779
  return;
1484
1780
  } finally {
1485
- if (inflightKey) {
1781
+ if (
1782
+ inflightKey
1783
+ && this._inFlightDispatches.get(inflightKey)?.attemptId === msg.tool_call_id
1784
+ ) {
1486
1785
  this._inFlightDispatches.delete(inflightKey);
1487
- inflightSettle(result); // undefined on throw → joiners ack ok:false
1488
1786
  }
1489
1787
  }
1490
1788
 
@@ -1496,14 +1794,26 @@ class CliProcess extends Process {
1496
1794
 
1497
1795
  // 0.13: carry the delivered message_id back so the bridge hands it to claude
1498
1796
  // (reply → edit_message progressive status).
1499
- this._writeToBridge({ kind: 'tool_ack', tool_call_id: msg.tool_call_id, ok: !!result?.ok, error: result?.error, message_id: result?.message_id });
1797
+ this._writeToBridge({
1798
+ kind: 'tool_ack',
1799
+ tool_call_id: msg.tool_call_id,
1800
+ ok: !!result?.ok,
1801
+ error: result?.error,
1802
+ message_id: result?.message_id,
1803
+ attempt_id: msg.tool_call_id,
1804
+ delivery: result?.ok ? 'sent' : undefined,
1805
+ });
1500
1806
 
1501
1807
  // P1 #7: remember the tool_call_id so duplicates re-ACK without dispatch.
1502
1808
  // Only cache on SUCCESS — failed calls should be retryable (transient TG
1503
1809
  // outage etc).
1504
1810
  if (result?.ok && msg.tool_call_id) {
1505
1811
  this.recentToolCallIds.add(msg.tool_call_id);
1506
- this.recentToolCallResults.set(msg.tool_call_id, result.message_id ?? null); // 0.13: for re-ACK replay
1812
+ this.recentToolCallResults.set(msg.tool_call_id, {
1813
+ message_id: result.message_id ?? null,
1814
+ attempt_id: msg.tool_call_id,
1815
+ argumentHash,
1816
+ });
1507
1817
  this.recentToolCallOrder.push(msg.tool_call_id);
1508
1818
  // FIFO eviction at cap
1509
1819
  while (this.recentToolCallOrder.length > RECENT_TOOL_CALL_LIMIT) {
@@ -1516,10 +1826,14 @@ class CliProcess extends Process {
1516
1826
  // Review F#16: also record the (chat_id, content-hash) so a retry with a
1517
1827
  // NEW tool_call_id still dedups. TTL-based via expiry timestamp.
1518
1828
  if (result?.ok && msg.name === 'reply' && typeof args.text === 'string' && args.chat_id != null) {
1519
- const dedupKey = this._buildContentDedupKey(args.chat_id, args.text);
1829
+ const dedupKey = replyDedupKey;
1520
1830
  // 0.13: store the delivered message_id alongside the expiry so a deduped retry
1521
1831
  // can replay it (keeps claude's edit handle for progressive status).
1522
- this.recentContentHashes.set(dedupKey, { expiry: Date.now() + this.contentDedupWindowMs, message_id: result.message_id ?? null });
1832
+ this.recentContentHashes.set(dedupKey, {
1833
+ expiry: Date.now() + this.contentDedupWindowMs,
1834
+ message_id: result.message_id ?? null,
1835
+ attempt_id: msg.tool_call_id,
1836
+ });
1523
1837
  }
1524
1838
 
1525
1839
  // Review #16 + C9: only record the reply for pending-turn resolution when
@@ -2338,6 +2652,9 @@ class CliProcess extends Process {
2338
2652
  // ─── public Process API ──────────────────────────────────────────
2339
2653
 
2340
2654
  async send(prompt, opts = {}) {
2655
+ if (this._bridgeDisconnecting) {
2656
+ throw await this._bridgeDisconnectErrorPromise;
2657
+ }
2341
2658
  if (this.closed) {
2342
2659
  // Parity P21: PROCESS_CLOSED code for cross-backend symmetry.
2343
2660
  const err = new Error('CliProcess: send on closed instance');
@@ -2880,6 +3197,14 @@ class CliProcess extends Process {
2880
3197
  return this._bgWorkSince !== null;
2881
3198
  }
2882
3199
 
3200
+ hasPendingDeliveryWork() {
3201
+ if (this._activeWorkflowDecisions.size > 0) return true;
3202
+ for (const entry of this._deliveryAttempts.values()) {
3203
+ if (entry.outcome === 'pending') return true;
3204
+ }
3205
+ return false;
3206
+ }
3207
+
2883
3208
  /**
2884
3209
  * 0.16 (MF-B): does any in-flight turn have a busy-aware ceiling EXTENSION
2885
3210
  * active? Such a turn can hold its slot up to the hard backstop, so the LRU
@@ -3272,6 +3597,10 @@ class CliProcess extends Process {
3272
3597
  // single pending on ANY Stop — a foreign cycle's Stop could close a
3273
3598
  // queued, never-picked-up user turn and deliver the FOREIGN cycle's
3274
3599
  // last_assistant_message as its answer (seam S5's Stop-identity gap).
3600
+ const preStopPendingCount = this.pendingTurns.size;
3601
+ const workflowSnapshot = preStopPendingCount === 0 && ev.stopHookActive !== true
3602
+ ? this._captureWorkflowCompletionSnapshot(ev)
3603
+ : null;
3275
3604
  const info = {
3276
3605
  stopHookActive: ev.stopHookActive,
3277
3606
  lastAssistantMessage: ev.lastAssistantMessage,
@@ -3323,6 +3652,10 @@ class CliProcess extends Process {
3323
3652
  this._logEvent('cli-stop-unattributed', { pending_count: this.pendingTurns.size });
3324
3653
  }
3325
3654
 
3655
+ if (preStopPendingCount === 0 && this.pendingTurns.size === 0) {
3656
+ this._beginWorkflowCompletionDecision(workflowSnapshot);
3657
+ }
3658
+
3326
3659
  // 0.12.0-rc.13 proactive compaction warning: on turn-end, if enabled
3327
3660
  // for this chat and not already warned this climb, sample context
3328
3661
  // occupancy from the transcript and warn (propose /compact) BEFORE
@@ -3483,10 +3816,14 @@ class CliProcess extends Process {
3483
3816
  * landing just before the disconnect would otherwise leave a stray
3484
3817
  * timer on the dead instance).
3485
3818
  */
3486
- _handleBridgeDisconnected(reason = 'socket-close') {
3819
+ async _handleBridgeDisconnected(reason = 'socket-close') {
3487
3820
  this.bridgeReady = false;
3488
3821
  this.mcpReady = false;
3489
- if (this.closed) return;
3822
+ if (this.closed || this._bridgeDisconnecting) return;
3823
+ this._bridgeDisconnecting = true;
3824
+ this._bridgeDisconnectErrorPromise = this._bridgeDisconnectError();
3825
+ const disconnectError = await this._bridgeDisconnectErrorPromise;
3826
+ this._invalidatePendingDeliveryWork();
3490
3827
  this.logger.warn?.(`[${this.label}] channels: bridge disconnected unexpectedly (${reason})`);
3491
3828
  // L6: clear the interrupt grace timer alongside the rest of the lifecycle.
3492
3829
  if (this._interruptGraceTimer) {
@@ -3503,9 +3840,7 @@ class CliProcess extends Process {
3503
3840
  // L5: remove the per-turn stop-hook listener (this path bypasses
3504
3841
  // Process.kill()'s removeAllListeners).
3505
3842
  if (pending._onStop) this.off('stop-hook', pending._onStop);
3506
- const err = new Error('bridge disconnected');
3507
- err.code = 'BRIDGE_DISCONNECTED';
3508
- try { pending.reject(err); } catch {}
3843
+ try { pending.reject(disconnectError); } catch {}
3509
3844
  }
3510
3845
  this.pendingTurns.clear();
3511
3846
  this.pendingQueue.length = 0;
@@ -3516,13 +3851,42 @@ class CliProcess extends Process {
3516
3851
  this._stopQuestionKeepAlive();
3517
3852
  this._openQuestions.clear();
3518
3853
  this._clearLedgerTimers(); // 0.13 D2
3519
- this.emit('bridge-disconnected');
3520
- this._logEvent('bridge-disconnected', { reason });
3854
+ this.emit('bridge-disconnected', { code: disconnectError.code });
3855
+ this._logEvent('bridge-disconnected', { reason, code: disconnectError.code });
3856
+ }
3857
+
3858
+ async _bridgeDisconnectError() {
3859
+ if (!this.sessionLauncher) {
3860
+ return Object.assign(new Error('bridge disconnected'), { code: 'BRIDGE_DISCONNECTED' });
3861
+ }
3862
+
3863
+ let processAlive = false;
3864
+ if (this.tmuxSession && typeof this.runner?.sessionProcessAlive === 'function') {
3865
+ let timeout;
3866
+ try {
3867
+ processAlive = await Promise.race([
3868
+ this.runner.sessionProcessAlive(this.tmuxSession),
3869
+ new Promise(resolve => {
3870
+ timeout = setTimeout(() => resolve(false), 250);
3871
+ timeout.unref?.();
3872
+ }),
3873
+ ]);
3874
+ } catch (err) {
3875
+ this.logger.warn?.(`[${this.label}] channels: could not verify contained process after bridge disconnect: ${err.message}`);
3876
+ } finally {
3877
+ if (timeout) clearTimeout(timeout);
3878
+ }
3879
+ }
3880
+ if (processAlive) {
3881
+ return Object.assign(new Error('bridge disconnected'), { code: 'BRIDGE_DISCONNECTED' });
3882
+ }
3883
+ return Object.assign(new Error('contained session process was lost'), { code: 'SESSION_PROCESS_LOST' });
3521
3884
  }
3522
3885
 
3523
3886
  async _doKill(reason) {
3524
3887
  this.closed = true;
3525
3888
  this.inFlight = false;
3889
+ this._invalidatePendingDeliveryWork();
3526
3890
 
3527
3891
  this._stopQuestionKeepAlive(); // 0.12: drop the interactive-question keep-alive
3528
3892
  this._openQuestions.clear();
@@ -3745,6 +4109,7 @@ class CliProcess extends Process {
3745
4109
  * @returns {Promise<{closed: boolean, drainedPendings: number}>}
3746
4110
  */
3747
4111
  async resetSession({ reason = 'reset' } = {}) {
4112
+ this._invalidatePendingDeliveryWork();
3748
4113
  let drained = 0;
3749
4114
  // First drain pendingTurns (channels-native bookkeeping). Each entry
3750
4115
  // ALSO has a matching pendingQueue row pushed at send(); we remove the