@shumkov/orchestra 0.4.2 → 0.4.3

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.
@@ -122,6 +122,9 @@ const ToolAckMessageSchema = z.object({
122
122
  tool_call_id: ToolCallId,
123
123
  ok: z.boolean(),
124
124
  error: z.string().optional(),
125
+ attempt_id: NonEmptyString.optional(),
126
+ delivery: z.enum(['sent', 'replayed']).optional(),
127
+ replay_of: NonEmptyString.optional(),
125
128
  // 0.13: the delivered Telegram message_id, surfaced back to claude so it can
126
129
  // `edit_message` that bubble for progressive status. Present on a successful
127
130
  // `reply`/`edit_message` ack; absent on errors / re-acks.
@@ -173,6 +176,48 @@ function parseDaemonToBridgeMessage(raw) {
173
176
  return { ok: false, error: zodErrorBrief(r.error, raw?.kind) };
174
177
  }
175
178
 
179
+ function formatToolAckResult({ ack, error, toolCallId }) {
180
+ if (error) {
181
+ return {
182
+ content: [{
183
+ type: 'text',
184
+ text: JSON.stringify({
185
+ ok: false,
186
+ error: error.message,
187
+ timeout: error.code === 'TOOL_ACK_TIMEOUT',
188
+ attempt_id: toolCallId,
189
+ }),
190
+ }],
191
+ isError: true,
192
+ };
193
+ }
194
+ if (ack?.ok !== true) {
195
+ return {
196
+ content: [{
197
+ type: 'text',
198
+ text: JSON.stringify({
199
+ ok: false,
200
+ error: ack?.error || 'daemon rejected delivery',
201
+ attempt_id: ack?.attempt_id || toolCallId,
202
+ }),
203
+ }],
204
+ isError: true,
205
+ };
206
+ }
207
+ return {
208
+ content: [{
209
+ type: 'text',
210
+ text: JSON.stringify({
211
+ ok: true,
212
+ message_id: ack.message_id ?? null,
213
+ attempt_id: ack.attempt_id,
214
+ delivery: ack.delivery,
215
+ ...(ack.replay_of ? { replay_of: ack.replay_of } : {}),
216
+ }),
217
+ }],
218
+ };
219
+ }
220
+
176
221
  function zodErrorBrief(err, kindHint) {
177
222
  const issues = (err?.issues || []).slice(0, 3).map(i => `${i.path.join('.')}: ${i.message}`);
178
223
  return `kind=${kindHint || '?'} — ${issues.join('; ') || 'unknown'}`;
@@ -197,4 +242,5 @@ module.exports = {
197
242
  // helpers
198
243
  parseBridgeToDaemonMessage,
199
244
  parseDaemonToBridgeMessage,
245
+ formatToolAckResult,
200
246
  };
@@ -30,7 +30,10 @@ import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprot
30
30
  // string "undefined" into Claude's prompt; a malformed tool_ack with
31
31
  // null tool_call_id silently no-op'd and the bridge timed out on
32
32
  // awaitToolAck → isError → Claude retry.
33
- import { parseDaemonToBridgeMessage } from './channels-bridge-protocol.js'
33
+ import {
34
+ formatToolAckResult,
35
+ parseDaemonToBridgeMessage,
36
+ } from './channels-bridge-protocol.js'
34
37
  import { z } from 'zod'
35
38
  import { connect } from 'node:net'
36
39
  import { randomUUID } from 'node:crypto'
@@ -103,20 +106,29 @@ function awaitToolAck(toolCallId) {
103
106
  return new Promise((resolve, reject) => {
104
107
  const timer = setTimeout(() => {
105
108
  pendingToolCalls.delete(toolCallId)
106
- reject(new Error('daemon ack timeout'))
109
+ const error = new Error('daemon ack timeout')
110
+ error.code = 'TOOL_ACK_TIMEOUT'
111
+ reject(error)
107
112
  }, TOOL_ACK_TIMEOUT_MS)
108
113
  pendingToolCalls.set(toolCallId, { resolve, reject, timer })
109
114
  })
110
115
  }
111
116
 
112
- function resolveToolAck(toolCallId, ok, error, messageId) {
113
- const p = pendingToolCalls.get(toolCallId)
117
+ function resolveToolAck(msg) {
118
+ const p = pendingToolCalls.get(msg.tool_call_id)
114
119
  if (!p) return
115
- pendingToolCalls.delete(toolCallId)
120
+ pendingToolCalls.delete(msg.tool_call_id)
116
121
  clearTimeout(p.timer)
117
122
  // 0.13: resolve with the delivered message_id so the CallTool handler can hand
118
123
  // it back to claude (for edit_message). null when the daemon didn't carry one.
119
- ok ? p.resolve({ message_id: messageId ?? null }) : p.reject(new Error(error || 'daemon rejected delivery'))
124
+ p.resolve({
125
+ ok: msg.ok,
126
+ error: msg.error,
127
+ message_id: msg.message_id ?? null,
128
+ attempt_id: msg.attempt_id,
129
+ delivery: msg.delivery,
130
+ replay_of: msg.replay_of,
131
+ })
120
132
  }
121
133
 
122
134
  // ─── 0.12 interactive questions: `ask` blocks for the user's answer ──
@@ -251,7 +263,7 @@ function handleDaemonMessage(msg) {
251
263
  break
252
264
 
253
265
  case 'tool_ack':
254
- resolveToolAck(msg.tool_call_id, msg.ok, msg.error, msg.message_id)
266
+ resolveToolAck(msg)
255
267
  break
256
268
 
257
269
  case 'question_answer':
@@ -321,7 +333,7 @@ mcp.setRequestHandler(ListToolsRequestSchema, async () => {
321
333
  'ALWAYS set consumed_turn_ids to the turn_id of EVERY <channel> message this ' +
322
334
  'reply answers or absorbs (including mid-turn follow-ups) — it is how polygram ' +
323
335
  'confirms delivery of follow-ups. ' +
324
- 'Returns {ok, message_id}: keep the message_id to update that bubble in place ' +
336
+ 'Returns {ok, message_id, attempt_id, delivery, replay_of?}: keep the message_id to update that bubble in place ' +
325
337
  'with `edit_message` (progressive status on long tasks).',
326
338
  inputSchema: {
327
339
  type: 'object',
@@ -440,12 +452,9 @@ mcp.setRequestHandler(CallToolRequestSchema, async req => {
440
452
  }) + '\n')
441
453
  try {
442
454
  const ack = await ackP
443
- // Return {ok, message_id} as JSON so claude can read the delivered bubble's
444
- // id and `edit_message` it later (progressive status). For a plain reply with
445
- // no id (solo sticker/reaction) message_id is null.
446
- return { content: [{ type: 'text', text: JSON.stringify({ ok: true, message_id: ack?.message_id ?? null }) }] }
455
+ return formatToolAckResult({ ack, toolCallId })
447
456
  } catch (err) {
448
- return { content: [{ type: 'text', text: `delivery failed: ${err.message}` }], isError: true }
457
+ return formatToolAckResult({ error: err, toolCallId })
449
458
  }
450
459
  })
451
460
 
@@ -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;
@@ -383,7 +388,7 @@ class CliProcess extends Process {
383
388
  // doesn't re-invoke the dispatcher → duplicate TG send. Set is bounded
384
389
  // to RECENT_TOOL_CALL_LIMIT entries via FIFO eviction.
385
390
  this.recentToolCallIds = new Set();
386
- this.recentToolCallResults = new Map(); // tool_call_id → message_id (0.13: replay on re-ACK)
391
+ this.recentToolCallResults = new Map(); // tool_call_id → successful direct-dispatch receipt
387
392
  this.recentToolCallOrder = []; // FIFO bound
388
393
  // Review F#17: per-pattern last-fired timestamp for the mid-turn dialog
389
394
  // watchdog. Dedups within MID_TURN_DEDUP_WINDOW_MS so a lingering dialog
@@ -403,7 +408,7 @@ class CliProcess extends Process {
403
408
  // message. Track (chat_id, sha256(text)) for 60s to catch this even when
404
409
  // the tool_call_id changes. TTL is tight enough that legitimate repeated
405
410
  // sends ("ok" twice in a row) eventually pass.
406
- this.recentContentHashes = new Map(); // key → expiryTs
411
+ this.recentContentHashes = new Map(); // key → { expiry, message_id, attempt_id }
407
412
  this.contentDedupWindowMs = 60_000;
408
413
  // Content-dedup key → Promise<dispatch result> for a reply dispatch that
409
414
  // is STILL AWAITING the dispatcher (e.g. a large file upload running past
@@ -412,6 +417,15 @@ class CliProcess extends Process {
412
417
  // tool_call_id, same content) re-delivers text + file. A duplicate
413
418
  // arriving in that window joins the in-flight promise instead.
414
419
  this._inFlightDispatches = new Map();
420
+ // Only unresolved dispatcher attempts and transcript decisions are
421
+ // lifecycle state. Settled delivery authority lives in Claude's transcript;
422
+ // the bounded outcome ledger exists solely to resolve a bridge timeout that
423
+ // names the same opaque attempt id and immutable argument hash.
424
+ this._deliveryAttempts = new Map();
425
+ this._deliveryAttemptOrder = [];
426
+ this._workflowDecisionKeys = new Map();
427
+ this._activeWorkflowDecisions = new Set();
428
+ this._deliveryGeneration = 0;
415
429
 
416
430
  // pending turn(s): turn_id → { resolve, reject, replies: [], seen, quietTimer,
417
431
  // hardTimer, absoluteTimer, _activityQuietTimer, startedAt }
@@ -1218,17 +1232,198 @@ class CliProcess extends Process {
1218
1232
  }
1219
1233
 
1220
1234
  /**
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.
1235
+ * Stable dedup key for immutable reply delivery arguments. Including the
1236
+ * destination prevents identical content sent to different chats from
1237
+ * colliding.
1225
1238
  */
1226
- _buildContentDedupKey(chatId, text) {
1227
- return `${chatId}::${crypto
1228
- .createHash('sha256')
1229
- .update(text, 'utf8')
1230
- .digest('hex')
1231
- .slice(0, 32)}`;
1239
+ _buildContentDedupKey(args) {
1240
+ return hashDeliveryArguments('reply', args);
1241
+ }
1242
+
1243
+ _pruneDeliveryAttempts(now = Date.now()) {
1244
+ for (const [attemptId, entry] of this._deliveryAttempts) {
1245
+ if (entry.outcome !== 'pending' && entry.expiry <= now) {
1246
+ this._deliveryAttempts.delete(attemptId);
1247
+ }
1248
+ }
1249
+ while (this._deliveryAttemptOrder.length > RECENT_TOOL_CALL_LIMIT) {
1250
+ const attemptId = this._deliveryAttemptOrder.shift();
1251
+ const entry = this._deliveryAttempts.get(attemptId);
1252
+ if (entry?.outcome !== 'pending') this._deliveryAttempts.delete(attemptId);
1253
+ }
1254
+ }
1255
+
1256
+ _registerDeliveryAttempt(attemptId, argumentHash) {
1257
+ const generation = this._deliveryGeneration;
1258
+ let settle;
1259
+ const promise = new Promise(resolve => { settle = resolve; });
1260
+ const entry = {
1261
+ attemptId,
1262
+ argumentHash,
1263
+ generation,
1264
+ outcome: 'pending',
1265
+ expiry: Infinity,
1266
+ promise,
1267
+ settle,
1268
+ };
1269
+ this._deliveryAttempts.set(attemptId, entry);
1270
+ return entry;
1271
+ }
1272
+
1273
+ _settleDeliveryAttempt(entry, outcome) {
1274
+ if (
1275
+ entry.generation !== this._deliveryGeneration
1276
+ || this._deliveryAttempts.get(entry.attemptId) !== entry
1277
+ ) {
1278
+ entry.settle();
1279
+ return;
1280
+ }
1281
+ entry.outcome = outcome;
1282
+ entry.expiry = Date.now() + this.contentDedupWindowMs;
1283
+ entry.settle();
1284
+ this._deliveryAttemptOrder.push(entry.attemptId);
1285
+ this._pruneDeliveryAttempts();
1286
+ this.emit('delivery-work-settled');
1287
+ }
1288
+
1289
+ async _readDeliveryAttempt(attemptId, argumentHash, generation) {
1290
+ const entry = this._deliveryAttempts.get(attemptId);
1291
+ if (!entry || entry.generation !== generation) return { outcome: 'missing' };
1292
+ if (entry.argumentHash !== argumentHash) return { outcome: 'mismatch' };
1293
+ if (entry.outcome === 'pending') await entry.promise;
1294
+ if (generation !== this._deliveryGeneration) return { outcome: 'invalidated' };
1295
+ const current = this._deliveryAttempts.get(attemptId);
1296
+ if (!current || current.argumentHash !== argumentHash) return { outcome: 'missing' };
1297
+ return { outcome: current.outcome };
1298
+ }
1299
+
1300
+ _invalidatePendingDeliveryWork() {
1301
+ const hadPending = this.hasPendingDeliveryWork();
1302
+ this._deliveryGeneration++;
1303
+ for (const entry of this._deliveryAttempts.values()) {
1304
+ if (entry.outcome === 'pending') entry.settle();
1305
+ }
1306
+ this._deliveryAttempts.clear();
1307
+ this._deliveryAttemptOrder.length = 0;
1308
+ this._activeWorkflowDecisions.clear();
1309
+ this._workflowDecisionKeys.clear();
1310
+ if (hadPending) this.emit('delivery-work-settled');
1311
+ }
1312
+
1313
+ _captureWorkflowCompletionSnapshot(ev) {
1314
+ if (
1315
+ typeof ev.transcriptPath !== 'string'
1316
+ || !ev.transcriptPath
1317
+ || typeof ev.lastAssistantMessage !== 'string'
1318
+ || !normalizeVisibleText(ev.lastAssistantMessage)
1319
+ ) return null;
1320
+ try {
1321
+ const stat = fs.statSync(ev.transcriptPath);
1322
+ if (!stat.isFile() || stat.size <= 0) return null;
1323
+ return {
1324
+ transcriptPath: ev.transcriptPath,
1325
+ byteSize: stat.size,
1326
+ sessionId: ev.sessionId || this.claudeSessionId,
1327
+ finalText: ev.lastAssistantMessage,
1328
+ };
1329
+ } catch {
1330
+ return null;
1331
+ }
1332
+ }
1333
+
1334
+ _beginWorkflowCompletionDecision(snapshot) {
1335
+ if (!snapshot) {
1336
+ this._logEvent('workflow-completion-ineligible', { reason: 'snapshot-missing' });
1337
+ return;
1338
+ }
1339
+ const generation = this._deliveryGeneration;
1340
+ const decisionKey = crypto.createHash('sha256')
1341
+ .update(`${snapshot.transcriptPath}\0${snapshot.byteSize}\0${normalizeVisibleText(snapshot.finalText)}`, 'utf8')
1342
+ .digest('hex');
1343
+ const now = Date.now();
1344
+ for (const [key, expiry] of this._workflowDecisionKeys) {
1345
+ if (expiry <= now) this._workflowDecisionKeys.delete(key);
1346
+ }
1347
+ if (this._activeWorkflowDecisions.has(decisionKey) || this._workflowDecisionKeys.has(decisionKey)) return;
1348
+
1349
+ this._activeWorkflowDecisions.add(decisionKey);
1350
+ this._logEvent('workflow-completion-decision-started', {
1351
+ transcript_bytes: snapshot.byteSize,
1352
+ final_len: snapshot.finalText.length,
1353
+ });
1354
+
1355
+ Promise.resolve()
1356
+ .then(() => correlateWorkflowCompletionSnapshot(snapshot))
1357
+ .then(async correlation => {
1358
+ if (generation !== this._deliveryGeneration || this.closed) return;
1359
+ if (!correlation.eligible) {
1360
+ this._logEvent('workflow-completion-ineligible', { reason: correlation.reason });
1361
+ return;
1362
+ }
1363
+ if (correlation.deliveredFinal) {
1364
+ this._logEvent('workflow-completion-suppressed', { reason: 'direct-final' });
1365
+ return;
1366
+ }
1367
+ if (correlation.visibleHashes.includes(correlation.finalHash)) {
1368
+ this._logEvent('workflow-completion-suppressed', { reason: 'visible-text-match' });
1369
+ return;
1370
+ }
1371
+
1372
+ for (const pending of correlation.unresolvedAttempts) {
1373
+ this._logEvent('workflow-completion-deferred', {
1374
+ attempt_id_hash: crypto.createHash('sha256').update(pending.attemptId, 'utf8').digest('hex'),
1375
+ });
1376
+ const outcome = await this._readDeliveryAttempt(
1377
+ pending.attemptId,
1378
+ pending.argumentHash,
1379
+ generation,
1380
+ );
1381
+ if (generation !== this._deliveryGeneration || this.closed) return;
1382
+ if (outcome.outcome === 'missing' || outcome.outcome === 'mismatch' || outcome.outcome === 'invalidated') {
1383
+ this._logEvent('workflow-completion-ineligible', { reason: `attempt-${outcome.outcome}` });
1384
+ return;
1385
+ }
1386
+ if (
1387
+ outcome.outcome === 'sent'
1388
+ && (pending.finalReply || pending.visibleHash === correlation.finalHash)
1389
+ ) {
1390
+ this._logEvent('workflow-completion-suppressed', { reason: 'late-direct-success' });
1391
+ return;
1392
+ }
1393
+ }
1394
+
1395
+ // A new consumer turn makes Stop ownership ambiguous. The fallback
1396
+ // covers only the non-overlapping autonomous cycle.
1397
+ if (this.pendingTurns.size !== 0) {
1398
+ this._logEvent('workflow-completion-ineligible', { reason: 'overlapping-turn' });
1399
+ return;
1400
+ }
1401
+ this.emit('autonomous-assistant-message', {
1402
+ text: snapshot.finalText,
1403
+ sessionId: this.claudeSessionId,
1404
+ backend: this.backend,
1405
+ alreadyDelivered: false,
1406
+ });
1407
+ this._logEvent('workflow-completion-fallback', {
1408
+ final_len: snapshot.finalText.length,
1409
+ receipt_count: correlation.visibleHashes.length + correlation.unresolvedAttempts.length,
1410
+ });
1411
+ })
1412
+ .catch(err => {
1413
+ this._logEvent('workflow-completion-ineligible', {
1414
+ reason: 'decision-error',
1415
+ error_name: err?.name || 'Error',
1416
+ });
1417
+ })
1418
+ .finally(() => {
1419
+ if (generation !== this._deliveryGeneration) return;
1420
+ this._activeWorkflowDecisions.delete(decisionKey);
1421
+ this._workflowDecisionKeys.set(decisionKey, Date.now() + this.contentDedupWindowMs);
1422
+ while (this._workflowDecisionKeys.size > RECENT_TOOL_CALL_LIMIT) {
1423
+ this._workflowDecisionKeys.delete(this._workflowDecisionKeys.keys().next().value);
1424
+ }
1425
+ this.emit('delivery-work-settled');
1426
+ });
1232
1427
  }
1233
1428
 
1234
1429
  async _dispatchToolCall(msg) {
@@ -1257,12 +1452,32 @@ class CliProcess extends Process {
1257
1452
  // Without this, Claude's reply-retry on isError (which can fire after a
1258
1453
  // slow ack timeout) → double-send of the same TG message.
1259
1454
  if (msg.tool_call_id && this.recentToolCallIds.has(msg.tool_call_id)) {
1455
+ const prior = this.recentToolCallResults.get(msg.tool_call_id);
1456
+ const argumentHash = hashDeliveryArguments(msg.name, args);
1457
+ if (!prior || !argumentHash || prior.argumentHash !== argumentHash) {
1458
+ this._writeToBridge({
1459
+ kind: 'tool_ack',
1460
+ tool_call_id: msg.tool_call_id,
1461
+ ok: false,
1462
+ error: 'duplicate attempt arguments mismatch',
1463
+ attempt_id: msg.tool_call_id,
1464
+ });
1465
+ return;
1466
+ }
1260
1467
  this.logger.warn?.(
1261
1468
  `[${this.label}] channels: duplicate tool_call_id=${msg.tool_call_id} — re-ACKing without dispatch`,
1262
1469
  );
1263
1470
  // 0.13: replay the cached message_id so a retried reply keeps its edit handle
1264
1471
  // (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 });
1472
+ this._writeToBridge({
1473
+ kind: 'tool_ack',
1474
+ tool_call_id: msg.tool_call_id,
1475
+ ok: true,
1476
+ message_id: prior.message_id,
1477
+ attempt_id: msg.tool_call_id,
1478
+ delivery: 'replayed',
1479
+ replay_of: prior.attempt_id,
1480
+ });
1266
1481
  return;
1267
1482
  }
1268
1483
 
@@ -1324,8 +1539,10 @@ class CliProcess extends Process {
1324
1539
  // Review F#16: secondary content-hash dedup catches retries that come in
1325
1540
  // with a NEW tool_call_id (Claude regenerates the id on each retry after
1326
1541
  // an isError ack). Window-based so legit repeat sends eventually pass.
1542
+ let replyDedupKey = null;
1327
1543
  if (msg.name === 'reply' && typeof args.text === 'string' && args.chat_id != null) {
1328
- const dedupKey = this._buildContentDedupKey(args.chat_id, args.text);
1544
+ replyDedupKey = this._buildContentDedupKey(args);
1545
+ const dedupKey = replyDedupKey;
1329
1546
  const entry = this.recentContentHashes.get(dedupKey); // { expiry, message_id }
1330
1547
  const nowDedup = Date.now();
1331
1548
  // Evict stale entries opportunistically (avoids unbounded growth).
@@ -1346,7 +1563,15 @@ class CliProcess extends Process {
1346
1563
  });
1347
1564
  // 0.13: replay the ORIGINAL bubble's message_id so a retried identical reply
1348
1565
  // 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 });
1566
+ this._writeToBridge({
1567
+ kind: 'tool_ack',
1568
+ tool_call_id: msg.tool_call_id,
1569
+ ok: true,
1570
+ message_id: entry.message_id ?? null,
1571
+ attempt_id: msg.tool_call_id,
1572
+ delivery: 'replayed',
1573
+ replay_of: entry.attempt_id,
1574
+ });
1350
1575
  return;
1351
1576
  }
1352
1577
  // The same content may be dispatching RIGHT NOW (slow upload past the
@@ -1363,12 +1588,23 @@ class CliProcess extends Process {
1363
1588
  tool_call_id: msg.tool_call_id,
1364
1589
  chat_id: args.chat_id,
1365
1590
  });
1366
- const prior = await inflight;
1591
+ const joinedAttempt = this._registerDeliveryAttempt(msg.tool_call_id, dedupKey);
1592
+ let prior;
1593
+ try {
1594
+ prior = await inflight.promise;
1595
+ this._settleDeliveryAttempt(joinedAttempt, prior?.ok ? 'sent' : 'failed');
1596
+ } catch (err) {
1597
+ this._settleDeliveryAttempt(joinedAttempt, 'failed');
1598
+ prior = { ok: false, error: err?.message || 'in-flight dispatch failed' };
1599
+ }
1367
1600
  this._writeToBridge({
1368
1601
  kind: 'tool_ack', tool_call_id: msg.tool_call_id,
1369
1602
  ok: !!prior?.ok,
1370
1603
  error: prior?.ok ? undefined : (prior?.error || 'in-flight dispatch failed'),
1371
1604
  message_id: prior?.message_id ?? null,
1605
+ attempt_id: msg.tool_call_id,
1606
+ delivery: prior?.ok ? 'replayed' : undefined,
1607
+ replay_of: inflight.attemptId,
1372
1608
  });
1373
1609
  return;
1374
1610
  }
@@ -1391,6 +1627,7 @@ class CliProcess extends Process {
1391
1627
  this._writeToBridge({
1392
1628
  kind: 'tool_ack', tool_call_id: msg.tool_call_id, ok: false,
1393
1629
  error: `rate limit exceeded (${this.toolRatePerSec}/s)`,
1630
+ attempt_id: msg.tool_call_id,
1394
1631
  });
1395
1632
  return;
1396
1633
  }
@@ -1408,7 +1645,13 @@ class CliProcess extends Process {
1408
1645
  `[${this.label}] channels: tool chat_id mismatch (got ${args.chat_id}, expected ${this.chatId}) — dropping`,
1409
1646
  );
1410
1647
  }
1411
- this._writeToBridge({ kind: 'tool_ack', tool_call_id: msg.tool_call_id, ok: false, error: 'chat_id mismatch' });
1648
+ this._writeToBridge({
1649
+ kind: 'tool_ack',
1650
+ tool_call_id: msg.tool_call_id,
1651
+ ok: false,
1652
+ error: 'chat_id mismatch',
1653
+ attempt_id: msg.tool_call_id,
1654
+ });
1412
1655
  return;
1413
1656
  }
1414
1657
 
@@ -1449,18 +1692,21 @@ class CliProcess extends Process {
1449
1692
  }
1450
1693
  }
1451
1694
 
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; }));
1695
+ const argumentHash = replyDedupKey || hashDeliveryArguments(msg.name, args);
1696
+ if ((msg.name === 'reply' || msg.name === 'edit_message') && !argumentHash) {
1697
+ this._writeToBridge({
1698
+ kind: 'tool_ack',
1699
+ tool_call_id: msg.tool_call_id,
1700
+ ok: false,
1701
+ error: 'invalid delivery arguments',
1702
+ attempt_id: msg.tool_call_id,
1703
+ });
1704
+ return;
1459
1705
  }
1460
-
1461
- let result;
1462
- try {
1463
- result = await this.toolDispatcher({
1706
+ const attempt = argumentHash
1707
+ ? this._registerDeliveryAttempt(msg.tool_call_id, argumentHash)
1708
+ : null;
1709
+ const dispatchPromise = Promise.resolve().then(() => this.toolDispatcher({
1464
1710
  sessionKey: this.sessionKey,
1465
1711
  chatId: this.chatId,
1466
1712
  threadId: this.threadId,
@@ -1477,14 +1723,39 @@ class CliProcess extends Process {
1477
1723
  participantJid: sourceMsgId != null ? (sourceEntry?.participantJid ?? null) : null,
1478
1724
  sessionCwd: this.sessionCwd, // P0 #2: dispatcher uses this to allowlist file roots
1479
1725
  maxOutboundFileBytes: this.maxOutboundFileBytes, // backend/chat-derived upload cap
1726
+ }));
1727
+
1728
+ // Mark this reply's immutable delivery arguments in-flight before awaiting
1729
+ // the dispatcher so a retry can join the exact original attempt.
1730
+ let inflightKey = null;
1731
+ if (replyDedupKey) {
1732
+ inflightKey = replyDedupKey;
1733
+ this._inFlightDispatches.set(inflightKey, {
1734
+ promise: dispatchPromise,
1735
+ attemptId: msg.tool_call_id,
1480
1736
  });
1737
+ }
1738
+
1739
+ let result;
1740
+ try {
1741
+ result = await dispatchPromise;
1742
+ if (attempt) this._settleDeliveryAttempt(attempt, result?.ok ? 'sent' : 'failed');
1481
1743
  } catch (err) {
1482
- this._writeToBridge({ kind: 'tool_ack', tool_call_id: msg.tool_call_id, ok: false, error: err.message });
1744
+ if (attempt) this._settleDeliveryAttempt(attempt, 'failed');
1745
+ this._writeToBridge({
1746
+ kind: 'tool_ack',
1747
+ tool_call_id: msg.tool_call_id,
1748
+ ok: false,
1749
+ error: err.message,
1750
+ attempt_id: msg.tool_call_id,
1751
+ });
1483
1752
  return;
1484
1753
  } finally {
1485
- if (inflightKey) {
1754
+ if (
1755
+ inflightKey
1756
+ && this._inFlightDispatches.get(inflightKey)?.attemptId === msg.tool_call_id
1757
+ ) {
1486
1758
  this._inFlightDispatches.delete(inflightKey);
1487
- inflightSettle(result); // undefined on throw → joiners ack ok:false
1488
1759
  }
1489
1760
  }
1490
1761
 
@@ -1496,14 +1767,26 @@ class CliProcess extends Process {
1496
1767
 
1497
1768
  // 0.13: carry the delivered message_id back so the bridge hands it to claude
1498
1769
  // (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 });
1770
+ this._writeToBridge({
1771
+ kind: 'tool_ack',
1772
+ tool_call_id: msg.tool_call_id,
1773
+ ok: !!result?.ok,
1774
+ error: result?.error,
1775
+ message_id: result?.message_id,
1776
+ attempt_id: msg.tool_call_id,
1777
+ delivery: result?.ok ? 'sent' : undefined,
1778
+ });
1500
1779
 
1501
1780
  // P1 #7: remember the tool_call_id so duplicates re-ACK without dispatch.
1502
1781
  // Only cache on SUCCESS — failed calls should be retryable (transient TG
1503
1782
  // outage etc).
1504
1783
  if (result?.ok && msg.tool_call_id) {
1505
1784
  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
1785
+ this.recentToolCallResults.set(msg.tool_call_id, {
1786
+ message_id: result.message_id ?? null,
1787
+ attempt_id: msg.tool_call_id,
1788
+ argumentHash,
1789
+ });
1507
1790
  this.recentToolCallOrder.push(msg.tool_call_id);
1508
1791
  // FIFO eviction at cap
1509
1792
  while (this.recentToolCallOrder.length > RECENT_TOOL_CALL_LIMIT) {
@@ -1516,10 +1799,14 @@ class CliProcess extends Process {
1516
1799
  // Review F#16: also record the (chat_id, content-hash) so a retry with a
1517
1800
  // NEW tool_call_id still dedups. TTL-based via expiry timestamp.
1518
1801
  if (result?.ok && msg.name === 'reply' && typeof args.text === 'string' && args.chat_id != null) {
1519
- const dedupKey = this._buildContentDedupKey(args.chat_id, args.text);
1802
+ const dedupKey = replyDedupKey;
1520
1803
  // 0.13: store the delivered message_id alongside the expiry so a deduped retry
1521
1804
  // 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 });
1805
+ this.recentContentHashes.set(dedupKey, {
1806
+ expiry: Date.now() + this.contentDedupWindowMs,
1807
+ message_id: result.message_id ?? null,
1808
+ attempt_id: msg.tool_call_id,
1809
+ });
1523
1810
  }
1524
1811
 
1525
1812
  // Review #16 + C9: only record the reply for pending-turn resolution when
@@ -2880,6 +3167,14 @@ class CliProcess extends Process {
2880
3167
  return this._bgWorkSince !== null;
2881
3168
  }
2882
3169
 
3170
+ hasPendingDeliveryWork() {
3171
+ if (this._activeWorkflowDecisions.size > 0) return true;
3172
+ for (const entry of this._deliveryAttempts.values()) {
3173
+ if (entry.outcome === 'pending') return true;
3174
+ }
3175
+ return false;
3176
+ }
3177
+
2883
3178
  /**
2884
3179
  * 0.16 (MF-B): does any in-flight turn have a busy-aware ceiling EXTENSION
2885
3180
  * active? Such a turn can hold its slot up to the hard backstop, so the LRU
@@ -3272,6 +3567,10 @@ class CliProcess extends Process {
3272
3567
  // single pending on ANY Stop — a foreign cycle's Stop could close a
3273
3568
  // queued, never-picked-up user turn and deliver the FOREIGN cycle's
3274
3569
  // last_assistant_message as its answer (seam S5's Stop-identity gap).
3570
+ const preStopPendingCount = this.pendingTurns.size;
3571
+ const workflowSnapshot = preStopPendingCount === 0 && ev.stopHookActive !== true
3572
+ ? this._captureWorkflowCompletionSnapshot(ev)
3573
+ : null;
3275
3574
  const info = {
3276
3575
  stopHookActive: ev.stopHookActive,
3277
3576
  lastAssistantMessage: ev.lastAssistantMessage,
@@ -3323,6 +3622,10 @@ class CliProcess extends Process {
3323
3622
  this._logEvent('cli-stop-unattributed', { pending_count: this.pendingTurns.size });
3324
3623
  }
3325
3624
 
3625
+ if (preStopPendingCount === 0 && this.pendingTurns.size === 0) {
3626
+ this._beginWorkflowCompletionDecision(workflowSnapshot);
3627
+ }
3628
+
3326
3629
  // 0.12.0-rc.13 proactive compaction warning: on turn-end, if enabled
3327
3630
  // for this chat and not already warned this climb, sample context
3328
3631
  // occupancy from the transcript and warn (propose /compact) BEFORE
@@ -3487,6 +3790,7 @@ class CliProcess extends Process {
3487
3790
  this.bridgeReady = false;
3488
3791
  this.mcpReady = false;
3489
3792
  if (this.closed) return;
3793
+ this._invalidatePendingDeliveryWork();
3490
3794
  this.logger.warn?.(`[${this.label}] channels: bridge disconnected unexpectedly (${reason})`);
3491
3795
  // L6: clear the interrupt grace timer alongside the rest of the lifecycle.
3492
3796
  if (this._interruptGraceTimer) {
@@ -3523,6 +3827,7 @@ class CliProcess extends Process {
3523
3827
  async _doKill(reason) {
3524
3828
  this.closed = true;
3525
3829
  this.inFlight = false;
3830
+ this._invalidatePendingDeliveryWork();
3526
3831
 
3527
3832
  this._stopQuestionKeepAlive(); // 0.12: drop the interactive-question keep-alive
3528
3833
  this._openQuestions.clear();
@@ -3745,6 +4050,7 @@ class CliProcess extends Process {
3745
4050
  * @returns {Promise<{closed: boolean, drainedPendings: number}>}
3746
4051
  */
3747
4052
  async resetSession({ reason = 'reset' } = {}) {
4053
+ this._invalidatePendingDeliveryWork();
3748
4054
  let drained = 0;
3749
4055
  // First drain pendingTurns (channels-native bookkeeping). Each entry
3750
4056
  // ALSO has a matching pendingQueue row pushed at send(); we remove the
@@ -339,6 +339,10 @@ class ProcessManager {
339
339
  // NOT evictable — the keyboard is live and claude is blocked on the ask;
340
340
  // killing it silently strands both. Skip like inFlight.
341
341
  if (typeof p.hasOpenQuestions === 'function' && p.hasOpenQuestions()) { pinnedSkipped++; continue; }
342
+ if (typeof p.hasPendingDeliveryWork === 'function' && p.hasPendingDeliveryWork()) {
343
+ pinnedSkipped++;
344
+ continue;
345
+ }
342
346
  if (!oldest || (p.lastUsedTs || 0) < (oldest.lastUsedTs || 0)) {
343
347
  oldest = p;
344
348
  oldestKey = k;
@@ -372,6 +376,7 @@ class ProcessManager {
372
376
  _hasPinnedSession() {
373
377
  for (const p of this.procs.values()) {
374
378
  if (!p.inFlight && p.hasActiveBackgroundWork()) return true;
379
+ if (typeof p.hasPendingDeliveryWork === 'function' && p.hasPendingDeliveryWork()) return true;
375
380
  // 0.16 (MF-B): an extended busy-aware-ceiling turn is a DURABLE blocker —
376
381
  // it can hold its slot up to the hard backstop (90min), not "seconds" like
377
382
  // a normal in-flight turn. Treat it as a pin so getOrSpawn SOFT-overflows
@@ -386,6 +391,7 @@ class ProcessManager {
386
391
  const keys = [];
387
392
  for (const [k, p] of this.procs.entries()) {
388
393
  if (!p.inFlight && p.hasActiveBackgroundWork()) keys.push(k);
394
+ else if (typeof p.hasPendingDeliveryWork === 'function' && p.hasPendingDeliveryWork()) keys.push(k);
389
395
  else if (p.inFlight && typeof p.hasExtendedTurn === 'function' && p.hasExtendedTurn()) keys.push(k);
390
396
  }
391
397
  return keys;
@@ -599,6 +605,7 @@ class ProcessManager {
599
605
  // 'idle': a turn completed and pendingQueue is empty. Signal any
600
606
  // parked LRU waiter that a non-in-flight slot is available.
601
607
  proc.on('idle', () => this._maybeSignalLruWaiter());
608
+ proc.on('delivery-work-settled', () => this._maybeSignalLruWaiter());
602
609
  // 'close': process closed itself (iteration loop exited or
603
610
  // _closeQuery returned). Remove from the Map + signal LRU.
604
611
  proc.on('close', () => {
@@ -174,6 +174,15 @@ class Process extends EventEmitter {
174
174
  return false;
175
175
  }
176
176
 
177
+ /**
178
+ * Does this process have delivery work whose settlement can still emit or
179
+ * suppress user-visible output? ProcessManager treats it as an eviction pin.
180
+ * Backends without deferred delivery decisions return false.
181
+ */
182
+ hasPendingDeliveryWork() {
183
+ return false;
184
+ }
185
+
177
186
  /**
178
187
  * 0.13 D1 (S9): does this process have an open interactive question?
179
188
  * Backends without the ask feature return false; CliProcess overrides.
@@ -0,0 +1,417 @@
1
+ 'use strict';
2
+
3
+ const crypto = require('node:crypto');
4
+ const fs = require('node:fs');
5
+ const { canonicalizeToolInput } = require('../canonical-json');
6
+
7
+ const TASK_NOTIFICATION_ID_RE = /<tool-use-id>\s*([^<]+?)\s*<\/tool-use-id>/g;
8
+
9
+ function normalizeVisibleText(value) {
10
+ return typeof value === 'string'
11
+ ? value.replace(/\r\n?/g, '\n').trim()
12
+ : '';
13
+ }
14
+
15
+ function hashText(value) {
16
+ return crypto.createHash('sha256').update(normalizeVisibleText(value), 'utf8').digest('hex');
17
+ }
18
+
19
+ function normalizedToolName(name) {
20
+ if (name === 'reply' || /__reply$/.test(name || '')) return 'reply';
21
+ if (name === 'edit_message' || /__edit_message$/.test(name || '')) return 'edit_message';
22
+ return null;
23
+ }
24
+
25
+ function hashDeliveryArguments(name, input = {}) {
26
+ const toolName = normalizedToolName(name);
27
+ if (!toolName) return null;
28
+ const value = {
29
+ tool: toolName,
30
+ chat_id: input.chat_id == null ? null : String(input.chat_id),
31
+ message_id: toolName === 'edit_message' && input.message_id != null
32
+ ? String(input.message_id)
33
+ : null,
34
+ interim: toolName === 'reply' && input.interim === true,
35
+ text: normalizeVisibleText(input.text),
36
+ files: Array.isArray(input.files) ? input.files.map(file => String(file)) : [],
37
+ };
38
+ return crypto.createHash('sha256').update(canonicalizeToolInput(value), 'utf8').digest('hex');
39
+ }
40
+
41
+ function textFromMessage(message) {
42
+ if (!message) return { text: '', toolResultOnly: false, invalid: true };
43
+ if (typeof message.content === 'string') {
44
+ return { text: message.content, toolResultOnly: false, invalid: false };
45
+ }
46
+ if (!Array.isArray(message.content)) {
47
+ return { text: '', toolResultOnly: false, invalid: true };
48
+ }
49
+ const texts = [];
50
+ let hasToolResult = false;
51
+ let hasOther = false;
52
+ for (const block of message.content) {
53
+ if (!block || typeof block !== 'object') {
54
+ hasOther = true;
55
+ } else if (block.type === 'text' && typeof block.text === 'string') {
56
+ texts.push(block.text);
57
+ } else if (block.type === 'tool_result') {
58
+ hasToolResult = true;
59
+ } else {
60
+ hasOther = true;
61
+ }
62
+ }
63
+ return {
64
+ text: texts.join('\n\n'),
65
+ toolResultOnly: hasToolResult && texts.length === 0 && !hasOther,
66
+ invalid: hasOther || (hasToolResult && texts.length > 0),
67
+ };
68
+ }
69
+
70
+ function parseToolResult(block) {
71
+ let value = block?.content;
72
+ if (Array.isArray(value)) {
73
+ const textBlocks = value.filter(item => item?.type === 'text' && typeof item.text === 'string');
74
+ if (textBlocks.length !== value.length) return null;
75
+ value = textBlocks.map(item => item.text).join('');
76
+ }
77
+ if (typeof value !== 'string') return null;
78
+ try {
79
+ const parsed = JSON.parse(value);
80
+ return parsed && typeof parsed === 'object' ? parsed : null;
81
+ } catch {
82
+ return null;
83
+ }
84
+ }
85
+
86
+ function result(reason, extra = {}) {
87
+ return {
88
+ eligible: false,
89
+ reason,
90
+ deliveredFinal: false,
91
+ visibleHashes: [],
92
+ unresolvedAttempts: [],
93
+ ...extra,
94
+ };
95
+ }
96
+
97
+ async function readSnapshot(filePath, byteSize) {
98
+ if (typeof filePath !== 'string' || !filePath || !Number.isSafeInteger(byteSize) || byteSize <= 0) {
99
+ return { ok: false, reason: 'snapshot-missing' };
100
+ }
101
+ let handle;
102
+ try {
103
+ handle = await fs.promises.open(filePath, 'r');
104
+ const buffer = Buffer.allocUnsafe(byteSize);
105
+ let offset = 0;
106
+ while (offset < byteSize) {
107
+ const { bytesRead } = await handle.read(buffer, offset, byteSize - offset, offset);
108
+ if (bytesRead === 0) break;
109
+ offset += bytesRead;
110
+ }
111
+ if (offset !== byteSize) return { ok: false, reason: 'snapshot-truncated' };
112
+ if (buffer[byteSize - 1] !== 0x0a) return { ok: false, reason: 'partial-line' };
113
+ return { ok: true, text: buffer.toString('utf8') };
114
+ } catch {
115
+ return { ok: false, reason: 'snapshot-unreadable' };
116
+ } finally {
117
+ await handle?.close().catch(() => {});
118
+ }
119
+ }
120
+
121
+ function collectToolReceipts(branch) {
122
+ const toolUses = new Map();
123
+ const toolResults = new Map();
124
+ let ordinal = 0;
125
+
126
+ for (const row of branch) {
127
+ if (row.type === 'assistant' && Array.isArray(row.message?.content)) {
128
+ for (const block of row.message.content) {
129
+ const blockOrdinal = ordinal++;
130
+ const toolName = normalizedToolName(block?.name);
131
+ if (block?.type !== 'tool_use' || !toolName) continue;
132
+ if (typeof block.id !== 'string' || !block.id || toolUses.has(block.id)) {
133
+ return { ok: false, reason: 'delivery-tool-ambiguous' };
134
+ }
135
+ const argumentHash = hashDeliveryArguments(toolName, block.input);
136
+ if (!argumentHash) return { ok: false, reason: 'delivery-arguments-invalid' };
137
+ toolUses.set(block.id, {
138
+ id: block.id,
139
+ toolName,
140
+ input: block.input || {},
141
+ argumentHash,
142
+ });
143
+ }
144
+ }
145
+ if (row.type === 'user' && Array.isArray(row.message?.content)) {
146
+ for (const block of row.message.content) {
147
+ const blockOrdinal = ordinal++;
148
+ if (block?.type !== 'tool_result' || !toolUses.has(block.tool_use_id)) continue;
149
+ if (toolResults.has(block.tool_use_id)) {
150
+ return { ok: false, reason: 'delivery-result-ambiguous' };
151
+ }
152
+ toolResults.set(block.tool_use_id, {
153
+ receipt: parseToolResult(block),
154
+ ordinal: blockOrdinal,
155
+ });
156
+ }
157
+ }
158
+ }
159
+
160
+ const delivered = [];
161
+ const failuresByAttempt = new Map();
162
+ const attemptIds = new Set();
163
+ for (const toolUse of toolUses.values()) {
164
+ const toolResult = toolResults.get(toolUse.id);
165
+ if (!toolResult?.receipt) return { ok: false, reason: 'delivery-result-missing' };
166
+ const { receipt, ordinal: resultOrdinal } = toolResult;
167
+ if (typeof receipt.attempt_id !== 'string' || !receipt.attempt_id) {
168
+ return { ok: false, reason: 'delivery-attempt-missing' };
169
+ }
170
+ if (attemptIds.has(receipt.attempt_id)) {
171
+ return { ok: false, reason: 'delivery-attempt-ambiguous' };
172
+ }
173
+ attemptIds.add(receipt.attempt_id);
174
+ if (receipt.ok === true) {
175
+ if (receipt.delivery !== 'sent' && receipt.delivery !== 'replayed') {
176
+ return { ok: false, reason: 'delivery-discriminator-missing' };
177
+ }
178
+ delivered.push({ toolUse, receipt, resultOrdinal });
179
+ } else if (receipt.ok === false) {
180
+ failuresByAttempt.set(receipt.attempt_id, { toolUse, receipt, resultOrdinal });
181
+ } else {
182
+ return { ok: false, reason: 'delivery-result-invalid' };
183
+ }
184
+ }
185
+
186
+ let deliveredFinal = false;
187
+ const visibleHashes = new Set();
188
+ const linkedReplaySources = new Set();
189
+
190
+ for (const item of delivered) {
191
+ const { toolUse, receipt, resultOrdinal } = item;
192
+ let provesDelivery = receipt.delivery === 'sent';
193
+ if (receipt.delivery === 'replayed') {
194
+ if (typeof receipt.replay_of !== 'string' || !receipt.replay_of) {
195
+ return { ok: false, reason: 'delivery-replay-source-missing' };
196
+ }
197
+ const source = failuresByAttempt.get(receipt.replay_of);
198
+ if (source && source.resultOrdinal >= resultOrdinal) {
199
+ return { ok: false, reason: 'delivery-replay-order-invalid' };
200
+ }
201
+ provesDelivery = !!source
202
+ && source.toolUse.toolName === toolUse.toolName
203
+ && source.toolUse.argumentHash === toolUse.argumentHash;
204
+ if (provesDelivery) linkedReplaySources.add(receipt.replay_of);
205
+ }
206
+ if (!provesDelivery) continue;
207
+ if (toolUse.toolName === 'reply' && toolUse.input.interim !== true) {
208
+ deliveredFinal = true;
209
+ } else {
210
+ visibleHashes.add(hashText(toolUse.input.text));
211
+ }
212
+ }
213
+
214
+ const unresolvedAttempts = [];
215
+ for (const [attemptId, item] of failuresByAttempt) {
216
+ if (linkedReplaySources.has(attemptId) || item.receipt.timeout !== true) continue;
217
+ unresolvedAttempts.push({
218
+ attemptId,
219
+ argumentHash: item.toolUse.argumentHash,
220
+ finalReply: item.toolUse.toolName === 'reply' && item.toolUse.input.interim !== true,
221
+ visibleHash: hashText(item.toolUse.input.text),
222
+ });
223
+ }
224
+
225
+ return {
226
+ ok: true,
227
+ deliveredFinal,
228
+ visibleHashes: [...visibleHashes],
229
+ unresolvedAttempts,
230
+ };
231
+ }
232
+
233
+ async function correlateWorkflowCompletionSnapshot({
234
+ transcriptPath,
235
+ byteSize,
236
+ sessionId,
237
+ finalText,
238
+ } = {}) {
239
+ const normalizedFinal = normalizeVisibleText(finalText);
240
+ if (!normalizedFinal) return result('final-empty');
241
+ if (typeof sessionId !== 'string' || !sessionId) return result('session-missing');
242
+
243
+ const snapshot = await readSnapshot(transcriptPath, byteSize);
244
+ if (!snapshot.ok) return result(snapshot.reason);
245
+
246
+ const rows = [];
247
+ const lines = snapshot.text.split('\n');
248
+ lines.pop();
249
+ for (let index = 0; index < lines.length; index++) {
250
+ if (!lines[index].trim()) continue;
251
+ let row;
252
+ try {
253
+ row = JSON.parse(lines[index]);
254
+ } catch {
255
+ return result('json-invalid');
256
+ }
257
+ if (!row || typeof row !== 'object') return result('row-invalid');
258
+ rows.push(row);
259
+ }
260
+
261
+ const mainline = rows.filter(row => (
262
+ row.sessionId === sessionId
263
+ && row.isSidechain === false
264
+ && (row.type === 'assistant' || row.type === 'user')
265
+ ));
266
+ if (!mainline.length) return result('session-mainline-missing');
267
+
268
+ const byUuid = new Map();
269
+ const children = new Map();
270
+ for (const row of mainline) {
271
+ if (
272
+ typeof row.uuid !== 'string'
273
+ || !row.uuid
274
+ || (row.parentUuid !== null && typeof row.parentUuid !== 'string')
275
+ ) {
276
+ return result('ancestry-field-missing');
277
+ }
278
+ if (byUuid.has(row.uuid)) return result('duplicate-uuid');
279
+ byUuid.set(row.uuid, row);
280
+ if (row.parentUuid) {
281
+ const list = children.get(row.parentUuid) || [];
282
+ list.push(row.uuid);
283
+ children.set(row.parentUuid, list);
284
+ }
285
+ }
286
+
287
+ let terminalIndex = -1;
288
+ for (let index = mainline.length - 1; index >= 0; index--) {
289
+ if (mainline[index].type === 'assistant') {
290
+ terminalIndex = index;
291
+ break;
292
+ }
293
+ }
294
+ if (terminalIndex < 0) return result('terminal-missing');
295
+ if (terminalIndex !== mainline.length - 1) return result('terminal-not-last-mainline');
296
+
297
+ const terminal = mainline[terminalIndex];
298
+ if (
299
+ typeof terminal.requestId !== 'string' || !terminal.requestId
300
+ || typeof terminal.message?.id !== 'string' || !terminal.message.id
301
+ ) {
302
+ return result('terminal-identity-missing');
303
+ }
304
+
305
+ const group = [terminal];
306
+ for (let index = terminalIndex - 1; index >= 0; index--) {
307
+ const prior = mainline[index];
308
+ const first = group[0];
309
+ if (
310
+ prior.type !== 'assistant'
311
+ || prior.sessionId !== terminal.sessionId
312
+ || prior.requestId !== terminal.requestId
313
+ || prior.message?.id !== terminal.message.id
314
+ ) break;
315
+ if (first.parentUuid !== prior.uuid) return result('terminal-fragment-chain-broken');
316
+ group.unshift(prior);
317
+ }
318
+
319
+ if (terminal.message?.stop_reason !== 'end_turn') return result('terminal-not-end-turn');
320
+ const terminalTexts = [];
321
+ for (const row of group) {
322
+ if (!Array.isArray(row.message?.content)) return result('terminal-content-invalid');
323
+ for (const block of row.message.content) {
324
+ if (block?.type === 'tool_use') return result('terminal-has-tool-use');
325
+ if (block?.type === 'text') {
326
+ if (typeof block.text !== 'string') return result('terminal-text-invalid');
327
+ terminalTexts.push(block.text);
328
+ } else if (block?.type !== 'thinking') {
329
+ return result('terminal-block-invalid');
330
+ }
331
+ }
332
+ }
333
+ if (normalizeVisibleText(terminalTexts.join('\n\n')) !== normalizedFinal) {
334
+ return result('final-mismatch');
335
+ }
336
+
337
+ const reversePath = [];
338
+ const visited = new Set(group.map(row => row.uuid));
339
+ let cursorUuid = group[0].parentUuid;
340
+ let notification = null;
341
+ while (cursorUuid) {
342
+ if (visited.has(cursorUuid)) return result('ancestry-cycle');
343
+ visited.add(cursorUuid);
344
+ const row = byUuid.get(cursorUuid);
345
+ if (!row) return result('ancestry-broken');
346
+ reversePath.push(row);
347
+ if ((children.get(row.uuid) || []).length > 1) return result('ancestry-fork');
348
+ if (row.type === 'user') {
349
+ const content = textFromMessage(row.message);
350
+ if (content.invalid) return result('user-content-ambiguous');
351
+ if (normalizeVisibleText(content.text)) {
352
+ notification = row;
353
+ break;
354
+ }
355
+ if (!content.toolResultOnly) return result('user-content-empty');
356
+ } else if (row.type !== 'assistant') {
357
+ return result('ancestry-row-ineligible');
358
+ }
359
+ cursorUuid = row.parentUuid;
360
+ }
361
+ if (!notification) return result('notification-missing');
362
+ if (
363
+ notification.origin?.kind !== 'task-notification'
364
+ || notification.promptSource !== 'system'
365
+ || notification.isSidechain !== false
366
+ ) {
367
+ return result('notification-provenance-invalid');
368
+ }
369
+
370
+ const notificationText = textFromMessage(notification.message).text;
371
+ if (!notificationText.includes('<task-notification>')) {
372
+ return result('notification-shape-invalid');
373
+ }
374
+ const notificationIds = [...notificationText.matchAll(TASK_NOTIFICATION_ID_RE)].map(match => match[1].trim());
375
+ if (notificationIds.length !== 1 || !notificationIds[0]) {
376
+ return result('notification-tool-id-ambiguous');
377
+ }
378
+
379
+ const workflowToolId = notificationIds[0];
380
+ const workflowMatches = [];
381
+ cursorUuid = notification.parentUuid;
382
+ const launchVisited = new Set();
383
+ while (cursorUuid) {
384
+ if (launchVisited.has(cursorUuid)) return result('launch-ancestry-cycle');
385
+ launchVisited.add(cursorUuid);
386
+ const row = byUuid.get(cursorUuid);
387
+ if (!row) return result('launch-ancestry-broken');
388
+ if ((children.get(row.uuid) || []).length > 1) return result('launch-ancestry-fork');
389
+ if (row.type === 'assistant' && Array.isArray(row.message?.content)) {
390
+ for (const block of row.message.content) {
391
+ if (block?.type === 'tool_use' && block.id === workflowToolId && block.name === 'Workflow') {
392
+ workflowMatches.push(block);
393
+ }
394
+ }
395
+ }
396
+ cursorUuid = row.parentUuid;
397
+ }
398
+ if (workflowMatches.length !== 1) return result('workflow-tool-match-invalid');
399
+
400
+ const branch = [notification, ...reversePath.slice(0, -1).reverse(), ...group];
401
+ const receipts = collectToolReceipts(branch);
402
+ if (!receipts.ok) return result(receipts.reason);
403
+
404
+ return result('eligible', {
405
+ eligible: true,
406
+ finalHash: hashText(normalizedFinal),
407
+ deliveredFinal: receipts.deliveredFinal,
408
+ visibleHashes: receipts.visibleHashes,
409
+ unresolvedAttempts: receipts.unresolvedAttempts,
410
+ });
411
+ }
412
+
413
+ module.exports = {
414
+ correlateWorkflowCompletionSnapshot,
415
+ hashDeliveryArguments,
416
+ normalizeVisibleText,
417
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shumkov/orchestra",
3
- "version": "0.4.2",
3
+ "version": "0.4.3",
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",