@shumkov/orchestra 0.10.20 → 0.10.21

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,317 @@
1
+ # Folded reply attribution and duplicate fallback suppression
2
+
3
+ Status: independently reviewed; option 1 selected by the operator on
4
+ 2026-08-18 and implemented pending release verification.
5
+
6
+ ## Problem
7
+
8
+ On 2026-08-17 at 22:31 Asia/Bangkok, Shumabit@home topic `routine`
9
+ received a primary Telegram message (6406) followed by an autosteered message
10
+ (6407). Claude answered both in one rich `reply` tool call. The call echoed the
11
+ autosteer turn ID and named both the primary and autosteer IDs in
12
+ `consumed_turn_ids`.
13
+
14
+ The combined rich answer was sent as Telegram message 6408, quoting 6407.
15
+ Orchestra then classified that already-delivered reply as a late reply from an
16
+ older cycle instead of recording it on the active primary turn. The primary
17
+ therefore still had zero recorded replies. At Stop, its different
18
+ `last_assistant_message` was treated as an undelivered fallback and Polygram
19
+ sent message 6409 quoting 6406. The user saw two substantially overlapping
20
+ answers with reversed ownership.
21
+
22
+ The incident was not caused by Telegram rich-text rendering. Production runs
23
+ Polygram 0.38.0 with Orchestra 0.10.14, and the installed Polygram contains the
24
+ non-streamed rich-delivery path. Message 6408 rendered rich (13 blocks, 1,718
25
+ characters). Message 6409 came from the zero-reply fallback branch and its
26
+ content did not qualify for rich rendering, so it fell back to the plain
27
+ sender. Fixing attribution removes that accidental second message; the existing
28
+ non-streamed rich path remains the safety net for genuine zero-reply turns.
29
+
30
+ ## Production evidence
31
+
32
+ Read-only SQLite queries against the user-authorized Shumabit@home production
33
+ chat found, over the 14 days ending 2026-08-17:
34
+
35
+ - 37 `cli-late-reply-correlated` events whose ledger source was `autosteer`
36
+ (30 distinct echoed turn IDs).
37
+ - 12 distinct cases immediately followed by
38
+ `cli-consumed-ack-fallback-rescued`; 13 resolved with zero recorded replies.
39
+ - In topic `routine`, 7 late-autosteer events covered 6 distinct turn IDs; 3
40
+ distinct turns produced a zero-reply fallback rescue.
41
+ - The reported turn's event chain was:
42
+ `autosteer` → both inputs `cli-input-acked` →
43
+ `stream-preview-turn-mismatch` → rich 6408 →
44
+ `cli-late-reply-correlated(source=autosteer)` →
45
+ `cli-turn-resolved-by-stop(reply_count=0)` →
46
+ `cli-consumed-ack-fallback-rescued` → plain 6409.
47
+
48
+ Content review of all 12 Shumabit@home rescue cases found that every rescued
49
+ Stop text was a shorter recap, translation, or subset of the already-delivered
50
+ channels reply. None contained the only copy of a final outcome. This corrects
51
+ the older fallback design's assumption that differing text necessarily means
52
+ new user-visible content: in current production, 12/12 differing texts in this
53
+ fold shape were duplicates.
54
+
55
+ The last two `routine` rescue cases before and including the report produced
56
+ the same structural outcome: an already-delivered channels reply followed by a
57
+ primary zero-reply fallback. This is a lifecycle classification defect, not a
58
+ message-specific content error.
59
+
60
+ ## Operator decision
61
+
62
+ The user's literal report asks for the two existing messages to have their
63
+ anchors swapped. The recommended behavior below instead removes the accidental
64
+ second message and keeps one combined answer anchored to the primary. Product
65
+ and interaction review agree that this visible behavior change requires
66
+ explicit operator alignment before implementation.
67
+
68
+ There is one reliability trade-off. A successful `reply` call is final unless
69
+ it explicitly sets `interim:true`; that is the bridge's current hard contract.
70
+ In June 2026, Claude violated the contract once: it sent “Researching now…”
71
+ without `interim:true`, then left the real answer only in Stop. The existing
72
+ different-text rescue was added for that incident. Recording a proven folded
73
+ non-interim reply on the primary trusts the protocol again and would suppress
74
+ such an unmarked status if it recurred. Against that historical risk, the new
75
+ production review found 12/12 current rescues were duplicates, including the
76
+ reported case.
77
+
78
+ The operator selected option 1 from these product contracts:
79
+
80
+ 1. Recommended: one combined answer anchored to the primary; a successful
81
+ non-interim reply is authoritative final, while `interim:true` retains the
82
+ produced-final rescue.
83
+ 2. Conservative: preserve two outputs and explicitly map the Stop fallback to
84
+ the folded source. This protects unmarked statuses but intentionally keeps
85
+ the 12/12 observed duplicate shape and requires a cross-package source
86
+ override.
87
+
88
+ Option 2 matches the screenshot's requested anchor swap, but assigns the Stop
89
+ transcript to the autosteer without protocol evidence. It makes model
90
+ transcript leakage part of normal steering semantics and adds a cross-layer
91
+ source override for result delivery. Those costs make it the conservative
92
+ reliability option, not the recommendation, but it remains a legitimate choice
93
+ at this gate.
94
+
95
+ The remainder of this spec describes option 1.
96
+
97
+ ## Intended behavior
98
+
99
+ Polygram's autosteer contract is “merge into active”: a follow-up injected
100
+ while a primary turn is in flight is context absorbed by that primary turn.
101
+ The bridge contract explicitly supports one combined reply covering several
102
+ inputs through `consumed_turn_ids`, while `turn_id` can echo only one of them.
103
+
104
+ Therefore:
105
+
106
+ 1. A combined reply proven to consume the active primary belongs to the active
107
+ primary turn, even when Claude echoes a folded input's ID.
108
+ 2. Its first Telegram bubble quotes the primary source message.
109
+ 3. It is recorded as a delivered reply on the primary, so a different Stop
110
+ transcript does not become a second fallback answer.
111
+ 4. The folded input is still resolved through `consumed_turn_ids`; it does not
112
+ receive a separate answer because it was merged rather than queued as a new
113
+ turn.
114
+ 5. A genuine later cycle for a non-folded autosteer remains independently
115
+ attributable to that autosteer message.
116
+
117
+ For the reported incident, the intended visible result is one combined rich
118
+ answer quoting 6406. It is not two existing answers with their quotes swapped.
119
+ Preserving the second answer would elevate an accidental Stop fallback into a
120
+ first-class steering response even though it has no protocol identity proving
121
+ that ownership.
122
+
123
+ ## Recommended option 1
124
+
125
+ ### 1. Resolve one effective owner before dispatch
126
+
127
+ In `CliProcess`, resolve reply ownership once and reuse it for Telegram
128
+ dispatch and pending-turn bookkeeping. A reply that echoes a ledgered,
129
+ non-pending fold entry is remapped to a live pending turn only when all of the
130
+ following deterministic evidence is present:
131
+
132
+ - the echoed ledger entry source is a fold source (`autosteer` or
133
+ `edit-fold`);
134
+ - `consumed_turn_ids` contains the echoed fold ID;
135
+ - `consumed_turn_ids` contains exactly one currently pending turn ID; and
136
+ - the chat ID has already passed the existing session chat guard.
137
+
138
+ The uniquely consumed pending turn is the effective owner. Every other shape
139
+ keeps current behavior, including the late-reply safeguard for an old ledgered
140
+ ID. The implementation must not infer folding merely from “one pending turn.”
141
+
142
+ ### 2. Use the effective owner consistently
143
+
144
+ For a proven fold reply, use the effective pending owner for:
145
+
146
+ - dispatcher `turnId`, so the active stream preview accepts the final reply;
147
+ - `sourceMsgId` and `participantJid`, so the first bubble quotes/reacts to the
148
+ primary source;
149
+ - the entry whose `_quoteUsed` flag is spent after successful delivery; and
150
+ - `_recordReplyForPendingTurn`, so the active primary records the delivered
151
+ final or interim reply.
152
+
153
+ Keep the model-echoed ID for ledger acknowledgement, content deduplication, and
154
+ diagnostic fields. After successful dispatch and pending-turn recording, emit a
155
+ metadata-only `cli-fold-reply-attributed` event with the echoed fold ID,
156
+ effective pending ID, fold source, and whether the reply was interim. Thus the
157
+ event means a delivered attribution, not merely a pre-dispatch decision. Do not
158
+ log message content.
159
+
160
+ The attribution resolver should return explicit fields rather than mutate the
161
+ tool arguments. This preserves the wire receipt and makes it difficult for
162
+ dispatch attribution and bookkeeping attribution to drift apart again.
163
+
164
+ ### 3. Let existing finalization suppress the accidental fallback
165
+
166
+ Once the combined final reply is recorded on the primary,
167
+ `_computeTurnDelivery` takes its existing final-reply/already-delivered branch.
168
+ The Stop hook's different `last_assistant_message` is not re-sent. No new
169
+ fallback heuristic is needed.
170
+
171
+ If the proven fold reply is `interim:true`, it remains interim on the primary;
172
+ the existing interim-final rescue rules continue to apply. This change must
173
+ not turn a status message into a final answer.
174
+
175
+ If the reply omitted `interim:true`, it is authoritative final under the
176
+ bridge contract even when Stop later contains different text. This deliberately
177
+ revises the older “different means new” fallback assumption for proven current
178
+ folds; the 12-case production classification above is the evidence. The hard
179
+ prompt and schema wording for `interim` remain in place, and the rollout watches
180
+ for missing-final reports.
181
+
182
+ ### 4. Release through Orchestra, then consume in Polygram
183
+
184
+ The behavioral fix belongs in Orchestra because it owns the input ledger,
185
+ pending turns, reply-tool dispatch, and Stop finalization. After its focused and
186
+ full tests pass, release a new exact Orchestra version, update Polygram's exact
187
+ dependency, run Polygram's focused rich/non-streamed tests and full suite, then
188
+ roll out through the normal staged deploy path.
189
+
190
+ No database migration, Telegram API change, prompt change, or configuration
191
+ change is required.
192
+
193
+ ## Alternatives rejected
194
+
195
+ ### Trust the echoed `turn_id` unconditionally
196
+
197
+ Rejected. The bridge schema can express only one `turn_id`, while the existing
198
+ contract explicitly allows one reply to consume several inputs. Production
199
+ shows Claude can echo the fold ID for a combined reply.
200
+
201
+ ### Prompt Claude to echo the primary ID
202
+
203
+ Rejected. This is deterministic routing and must not depend on model
204
+ compliance. It would also regress silently when model behavior changes.
205
+
206
+ ### Route any ledgered fold ID to the sole pending turn
207
+
208
+ Rejected. This reopens the late-reply cross-attribution defect that the input
209
+ ledger was designed to close. Explicit `consumed_turn_ids` membership is the
210
+ proof that distinguishes a current fold from an old reply.
211
+
212
+ ### Suppress every different Stop fallback after a consumed ack
213
+
214
+ Rejected. A prior production incident established that a short consuming
215
+ status can be followed by a distinct real final answer in the Stop transcript.
216
+ The current rescue protects that case. Recording a proven combined final reply
217
+ on its actual owner solves this incident without weakening the rescue for
218
+ correctly marked `interim:true` replies.
219
+
220
+ The narrower chosen rule is different: only a successfully delivered reply
221
+ that the protocol marks final is authoritative. `interim:true` continues to
222
+ rescue a distinct produced final. The remaining risk is a model contract
223
+ violation that omits `interim:true`; it is called out in the operator decision
224
+ rather than hidden behind a text-difference heuristic that produced 12/12
225
+ duplicates in the measured current population.
226
+
227
+ ## Failure modes and boundaries
228
+
229
+ - Missing, empty, foreign, or ambiguous `consumed_turn_ids`: do not remap; keep
230
+ current late/orphan behavior and telemetry.
231
+ - More than one consumed pending turn: do not guess an owner.
232
+ - A ledgered `primary` or `system` ID that is not pending: remains a late reply.
233
+ - A fold reply after the primary finalized and with no consumed live pending
234
+ owner: remains independently attributed to the fold source.
235
+ - Dispatcher failure: do not spend the effective owner's quote, record the
236
+ consuming text, or record a delivered reply; preserve existing retry and
237
+ Stop-fallback behavior. Turn finalization waits while the consuming reply is
238
+ in flight so neither a successful delivery nor a failed-delivery fallback is
239
+ lost to the race.
240
+ - Multiple folded inputs in one reply: one uniquely consumed live primary may
241
+ own the combined reply; all named folds are acknowledged normally.
242
+ - Interim fold reply: quote ownership is corrected, but finalization remains
243
+ interim-aware.
244
+ - Non-interim fold reply followed by different Stop text: the reply is final by
245
+ contract and Stop is suppressed. This removes the measured duplicates but
246
+ no longer compensates for an omitted `interim:true` in this proven-fold
247
+ shape; the operator decision explicitly accepts or rejects that trade-off.
248
+ - WhatsApp opaque source IDs: preserve the existing numeric-or-opaque
249
+ conversion and participant binding by selecting an entry, not coercing IDs
250
+ differently.
251
+ - A model that falsely names the current primary in `consumed_turn_ids` can
252
+ still misattribute a reply. That field is already the system's explicit
253
+ fold-ack contract and is the strongest available protocol evidence; the new
254
+ telemetry makes its use measurable.
255
+
256
+ ## Test and verification plan
257
+
258
+ Follow bug-fix TDD: add the exact regression first, run it against unmodified
259
+ Orchestra and record the failure, then implement and rerun it green.
260
+
261
+ Focused regression cases:
262
+
263
+ 1. Primary source 6406 + autosteer source 6407; a successful final reply echoes
264
+ the fold ID and consumes both. Before the fix, dispatcher source is 6407,
265
+ its turn ID is the fold ID, the primary has zero replies, and a distinct Stop
266
+ fallback is deliverable. After the fix, dispatcher source is 6406, effective
267
+ turn ID is the primary, the primary records one final reply, and finalization
268
+ is already-delivered with no fallback send.
269
+ 2. The same shape with an active stream preview must not emit a turn-mismatch
270
+ and must finalize the primary preview.
271
+ 3. An old ledgered autosteer reply that does not consume the current pending ID
272
+ remains late and never quotes or records against the current primary.
273
+ 4. A true extra-turn autosteer with no live primary still quotes its own source.
274
+ 5. An `edit-fold` combined reply follows the same proven-fold rule.
275
+ 6. Ambiguous consumed pending IDs do not remap.
276
+ 7. A failed delivery neither spends the primary quote nor records the reply.
277
+ 8. An interim fold reply stays interim and still permits the existing produced-
278
+ final rescue.
279
+ 9. A non-interim fold reply followed by distinct Stop text stays
280
+ already-delivered and does not produce a duplicate fallback.
281
+
282
+ Verification gates:
283
+
284
+ - Focused Orchestra regression test shows red before and green after.
285
+ - All Orchestra unit/integration tests pass with no unexpected skips.
286
+ - Polygram's non-streamed rich tests pass against the new exact Orchestra pin.
287
+ - Full Polygram test suite passes with no unexpected skips.
288
+ - A controlled Shumorobot fold scenario produces one combined rich reply
289
+ quoting the primary and a `cli-fold-reply-attributed` event, with no
290
+ `stream-preview-turn-mismatch`, `cli-late-reply-correlated`, or
291
+ `cli-consumed-ack-fallback-rescued` for that turn.
292
+ - Deploy Shumabit only after the canary passes; verify unrelated UMI Assistant,
293
+ Water, and tmux owners are unchanged according to the normal deploy gate.
294
+
295
+ ## Soak and rollback
296
+
297
+ For 24 hours after Shumabit rollout, compare against the 14-day baseline:
298
+
299
+ - proven fold replies produce `cli-fold-reply-attributed`;
300
+ - late-autosteer events followed by zero-reply fallback rescue trend to zero;
301
+ - no rise in `channels-orphan-reply-dropped`, turn timeouts, or missing final
302
+ answers; and
303
+ - no duplicate-answer report in the affected chat.
304
+
305
+ Rollback is an exact Polygram/Orchestra version rollback through the normal
306
+ release/deploy procedure. There is no persistent state to unwind.
307
+
308
+ ## Success criteria
309
+
310
+ - The reported production shape yields one combined answer quoting the primary
311
+ message.
312
+ - A proven folded reply is owned consistently by dispatch, preview, quoting,
313
+ and pending-turn finalization.
314
+ - True late replies remain isolated from a newer pending turn.
315
+ - Genuine zero-reply and interim-only fallbacks retain their current rescue.
316
+ - Rich formatting remains available on both reply-tool and genuine
317
+ non-streamed paths.
@@ -1990,7 +1990,6 @@ class CliProcess extends Process {
1990
1990
  if (chatIdMatches && Array.isArray(args.consumed_turn_ids) && args.consumed_turn_ids.length) {
1991
1991
  this._ledgerAckConsumed(
1992
1992
  args.consumed_turn_ids.filter((x) => typeof x === 'string'),
1993
- typeof args.text === 'string' ? args.text : '',
1994
1993
  );
1995
1994
  } else if (chatIdMatches && msg.name === 'reply' && 'consumed_turn_ids' in args) {
1996
1995
  this._lastAckFieldAt = Date.now(); // field present but empty — contract observed
@@ -2143,27 +2142,25 @@ class CliProcess extends Process {
2143
2142
  return;
2144
2143
  }
2145
2144
 
2146
- // Dropped-"4" fix A2 (docs/0.13-resume-dialog-fix-spec.md): resolve the
2147
- // reply's originating TG message so the dispatcher has a target for solo
2148
- // reactions (and reply-quoting). Resolution order strictly mirrors
2149
- // _recordReplyForPendingTurn so quote/reaction attribution can never
2150
- // disagree with reply attribution: echoed turn_id → InputLedger entry's
2151
- // msgId (registered at send/inject time); no echo → the single pending
2152
- // turn's ledger entry. Anything else stays null — an unattributable
2153
- // reply must never react to / quote an unrelated message.
2145
+ // Resolve ownership once so dispatch, quoting, and pending-turn bookkeeping
2146
+ // cannot disagree. A folded input can own the model's echoed turn_id while
2147
+ // the one live primary owns the combined answer; consumed_turn_ids is the
2148
+ // explicit proof that connects those two identities.
2149
+ const replyAttribution = this._resolveReplyAttribution(
2150
+ args.turn_id,
2151
+ args.consumed_turn_ids,
2152
+ );
2153
+
2154
+ // Resolve the reply's originating message so the dispatcher has a target
2155
+ // for reactions and reply-quoting. Anything unattributable stays null; it
2156
+ // must never react to or quote an unrelated message.
2154
2157
  //
2155
2158
  // Review F1: quote only the FIRST delivered reply per turn. On SDK,
2156
2159
  // deliverReplies fires once per turn → one quote; the channels dispatcher
2157
2160
  // fires per reply tool call, and an N-reply turn must not produce N
2158
2161
  // bubbles all quoting the same user message.
2159
2162
  let sourceMsgId = null;
2160
- let sourceEntry = null;
2161
- if (args.turn_id && this.inputLedger.has(args.turn_id)) {
2162
- sourceEntry = this.inputLedger.get(args.turn_id);
2163
- } else if (this.pendingTurns.size === 1) {
2164
- const [[onlyTurnId]] = this.pendingTurns;
2165
- sourceEntry = this.inputLedger.get(onlyTurnId) || null;
2166
- }
2163
+ const sourceEntry = replyAttribution.sourceEntry;
2167
2164
  if (sourceEntry && !sourceEntry._quoteUsed) {
2168
2165
  // Message ids may be numeric (Telegram) OR opaque strings (WhatsApp stanza ids).
2169
2166
  // A purely-numeric id coerces to Number so number-based quote/reaction call sites
@@ -2194,6 +2191,12 @@ class CliProcess extends Process {
2194
2191
  const attempt = argumentHash
2195
2192
  ? this._registerDeliveryAttempt(msg.tool_call_id, argumentHash)
2196
2193
  : null;
2194
+ const trackedReplyDeliveries = msg.name === 'reply'
2195
+ ? this._beginReplyDeliveries([
2196
+ replyAttribution.effectiveTurnId,
2197
+ ...(Array.isArray(args.consumed_turn_ids) ? args.consumed_turn_ids : []),
2198
+ ])
2199
+ : [];
2197
2200
  const dispatchPromise = Promise.resolve().then(() => this.toolDispatcher({
2198
2201
  sessionKey: this.sessionKey,
2199
2202
  chatId: this.chatId,
@@ -2203,7 +2206,7 @@ class CliProcess extends Process {
2203
2206
  // The turn this call names. A consumer holding per-turn state needs it
2204
2207
  // to refuse a late reply from an earlier turn — without it, a delayed
2205
2208
  // reply lands on whatever turn the session is holding NOW.
2206
- turnId: typeof args.turn_id === 'string' ? args.turn_id : null,
2209
+ turnId: replyAttribution.effectiveTurnId,
2207
2210
  interim: args.interim === true, // status/progress reply — not the turn's answer
2208
2211
  files: args.files,
2209
2212
  messageId: args.message_id, // 0.13: edit_message target bubble
@@ -2234,6 +2237,7 @@ class CliProcess extends Process {
2234
2237
  if (attempt) this._settleDeliveryAttempt(attempt, result?.ok ? 'sent' : 'failed');
2235
2238
  } catch (err) {
2236
2239
  if (attempt) this._settleDeliveryAttempt(attempt, 'failed');
2240
+ this._finishReplyDeliveries(trackedReplyDeliveries);
2237
2241
  this._writeToBridge({
2238
2242
  kind: 'tool_ack',
2239
2243
  tool_call_id: msg.tool_call_id,
@@ -2301,6 +2305,10 @@ class CliProcess extends Process {
2301
2305
  });
2302
2306
  }
2303
2307
 
2308
+ if (result?.ok && msg.name === 'reply') {
2309
+ this._recordConsumedReplyDelivery(args.consumed_turn_ids, args.text);
2310
+ }
2311
+
2304
2312
  // Review #16 + C9: only record the reply for pending-turn resolution when
2305
2313
  // the dispatcher actually delivered AND the text is a non-empty string.
2306
2314
  // Review P1 #4: route by turn_id (echoed from inbound <channel> meta) so
@@ -2309,8 +2317,21 @@ class CliProcess extends Process {
2309
2317
  // fall back to the SINGLE pending turn if exactly one exists, else the
2310
2318
  // oldest pending — log a warning either way so we can audit drift.
2311
2319
  if (msg.name === 'reply' && result?.ok && typeof args.text === 'string' && args.text.length > 0) {
2312
- this._recordReplyForPendingTurn(args.text, args.turn_id, args.interim === true);
2320
+ const recorded = this._recordReplyForPendingTurn(
2321
+ args.text,
2322
+ replyAttribution.effectiveTurnId,
2323
+ args.interim === true,
2324
+ );
2325
+ if (recorded && replyAttribution.foldSource) {
2326
+ this._logEvent('cli-fold-reply-attributed', {
2327
+ echoed_turn_id: replyAttribution.echoedTurnId,
2328
+ effective_turn_id: replyAttribution.effectiveTurnId,
2329
+ source: replyAttribution.foldSource,
2330
+ interim: args.interim === true,
2331
+ });
2332
+ }
2313
2333
  }
2334
+ this._finishReplyDeliveries(trackedReplyDeliveries);
2314
2335
  }
2315
2336
 
2316
2337
  /**
@@ -2431,6 +2452,41 @@ class CliProcess extends Process {
2431
2452
  ack();
2432
2453
  }
2433
2454
 
2455
+ /**
2456
+ * Resolve the turn and ledger entry that own a reply without changing the
2457
+ * model-supplied arguments. Fold remapping requires both an echoed fold id
2458
+ * and exactly one live pending id in consumed_turn_ids; every other shape
2459
+ * preserves the existing late/unknown reply behavior.
2460
+ */
2461
+ _resolveReplyAttribution(replyTurnId, consumedTurnIds) {
2462
+ const echoedTurnId = typeof replyTurnId === 'string' ? replyTurnId : null;
2463
+ let effectiveTurnId = echoedTurnId;
2464
+ let sourceEntry = echoedTurnId ? (this.inputLedger.get(echoedTurnId) || null) : null;
2465
+ let foldSource = null;
2466
+
2467
+ if (sourceEntry
2468
+ && !this.pendingTurns.has(echoedTurnId)
2469
+ && (sourceEntry.source === 'autosteer' || sourceEntry.source === 'edit-fold')
2470
+ && Array.isArray(consumedTurnIds)
2471
+ && consumedTurnIds.includes(echoedTurnId)) {
2472
+ const pendingIds = new Set(
2473
+ consumedTurnIds.filter(id => typeof id === 'string' && this.pendingTurns.has(id)),
2474
+ );
2475
+ if (pendingIds.size === 1) {
2476
+ [effectiveTurnId] = pendingIds;
2477
+ foldSource = sourceEntry.source;
2478
+ sourceEntry = this.inputLedger.get(effectiveTurnId) || null;
2479
+ }
2480
+ }
2481
+
2482
+ if (!sourceEntry && this.pendingTurns.size === 1) {
2483
+ const [[onlyTurnId]] = this.pendingTurns;
2484
+ sourceEntry = this.inputLedger.get(onlyTurnId) || null;
2485
+ }
2486
+
2487
+ return { echoedTurnId, effectiveTurnId, sourceEntry, foldSource };
2488
+ }
2489
+
2434
2490
  /**
2435
2491
  * Route a reply text to the pending turn it belongs to.
2436
2492
  *
@@ -2456,7 +2512,7 @@ class CliProcess extends Process {
2456
2512
  backend: this.backend,
2457
2513
  alreadyDelivered: true,
2458
2514
  });
2459
- return;
2515
+ return false;
2460
2516
  }
2461
2517
  let target = null;
2462
2518
  if (replyTurnId && this.pendingTurns.has(replyTurnId)) {
@@ -2498,7 +2554,7 @@ class CliProcess extends Process {
2498
2554
  pending_turn_ids: pendingIds,
2499
2555
  reply_len: text.length,
2500
2556
  });
2501
- return;
2557
+ return false;
2502
2558
  }
2503
2559
  // No pending turns at all → emit canonical 'autonomous-assistant-message'
2504
2560
  // event so polygram's autonomous-msg path (sdk/callbacks.js
@@ -2520,7 +2576,7 @@ class CliProcess extends Process {
2520
2576
  backend: this.backend,
2521
2577
  alreadyDelivered: true,
2522
2578
  });
2523
- return;
2579
+ return false;
2524
2580
  }
2525
2581
 
2526
2582
  target.replies.push(text);
@@ -2546,7 +2602,7 @@ class CliProcess extends Process {
2546
2602
  this._logEvent('cli-reply-cap-noted', { reply_count: target.replyCount });
2547
2603
  }
2548
2604
  this._noteActivity('reply');
2549
- return;
2605
+ return true;
2550
2606
  }
2551
2607
 
2552
2608
  // ── Legacy (rung 3, hook stream never came up): pre-D1 path, byte-identical ──
@@ -2576,6 +2632,7 @@ class CliProcess extends Process {
2576
2632
  } else {
2577
2633
  target.quietTimer = setTimeout(() => this._resolveTurn(target._turnId), this.turnQuietMs);
2578
2634
  }
2635
+ return true;
2579
2636
  }
2580
2637
 
2581
2638
  // ─── 0.13 D2: InputLedger ──────────────────────────────────────────
@@ -2624,16 +2681,8 @@ class CliProcess extends Process {
2624
2681
  if (e._watchdogTimer) { clearTimeout(e._watchdogTimer); e._watchdogTimer = null; }
2625
2682
  }
2626
2683
 
2627
- /**
2628
- * Tier 2C: a reply carried consumed_turn_ids — acknowledge every known id.
2629
- * `consumingText` is the text the consuming reply actually delivered; it is
2630
- * recorded on each consumed pending so _finalizeTurn can tell a genuine fold
2631
- * (the answer rode the sibling reply) from an early ack that DIDN'T carry the
2632
- * answer (prod 2026-06-13: a 294-char "Researching now…" ack, then the real
2633
- * answer arrived as Stop-fallback text — which must NOT be suppressed).
2634
- * See docs/0.13-consumed-ack-stop-fallback-drop-spec.md.
2635
- */
2636
- _ledgerAckConsumed(ids, consumingText = '') {
2684
+ /** A reply carried consumed_turn_ids — acknowledge every known input id. */
2685
+ _ledgerAckConsumed(ids) {
2637
2686
  this._lastAckFieldAt = Date.now();
2638
2687
  for (const id of ids) {
2639
2688
  const e = this.inputLedger.get(id);
@@ -2650,14 +2699,6 @@ class CliProcess extends Process {
2650
2699
  const pending = this.pendingTurns.get(id);
2651
2700
  if (pending) {
2652
2701
  pending._consumedAcked = true;
2653
- // Remember WHAT the consuming reply delivered for this turn. The last
2654
- // ack wins; a longer subsequent ack is the safer record (more likely to
2655
- // actually contain the answer). _finalizeTurn only suppresses a
2656
- // Stop-fallback finalize when its text matches this.
2657
- if (typeof consumingText === 'string'
2658
- && consumingText.length > (pending._consumedByText?.length || 0)) {
2659
- pending._consumedByText = consumingText;
2660
- }
2661
2702
  // The ack itself flips rung-2 eligibility on — arm now. (The turn's
2662
2703
  // last _noteActivity ran BEFORE this flag was set, so without this
2663
2704
  // a quiet tail would never re-arm and the turn would sit until a
@@ -2667,6 +2708,51 @@ class CliProcess extends Process {
2667
2708
  }
2668
2709
  }
2669
2710
 
2711
+ /** Record text only after the dispatcher confirms that the consuming reply arrived. */
2712
+ _recordConsumedReplyDelivery(ids, consumingText) {
2713
+ if (!Array.isArray(ids) || typeof consumingText !== 'string') return;
2714
+ for (const id of new Set(ids)) {
2715
+ const pending = this.pendingTurns.get(id);
2716
+ if (pending && consumingText.length > (pending._consumedByText?.length || 0)) {
2717
+ pending._consumedByText = consumingText;
2718
+ }
2719
+ }
2720
+ }
2721
+
2722
+ /** Keep turn finalization behind the outcome of a consuming reply dispatch. */
2723
+ _beginReplyDeliveries(ids) {
2724
+ if (!Array.isArray(ids)) return [];
2725
+ const tracked = [];
2726
+ for (const turnId of new Set(ids)) {
2727
+ const pending = this.pendingTurns.get(turnId);
2728
+ if (!pending) continue;
2729
+ pending._replyDeliveriesInFlight = (pending._replyDeliveriesInFlight || 0) + 1;
2730
+ tracked.push({ turnId, pending });
2731
+ }
2732
+ return tracked;
2733
+ }
2734
+
2735
+ _finishReplyDeliveries(tracked) {
2736
+ for (const { turnId, pending } of tracked) {
2737
+ pending._replyDeliveriesInFlight = Math.max(
2738
+ 0,
2739
+ (pending._replyDeliveriesInFlight || 0) - 1,
2740
+ );
2741
+ if (pending._replyDeliveriesInFlight > 0 || this.pendingTurns.get(turnId) !== pending) {
2742
+ continue;
2743
+ }
2744
+ if (pending._finalizeAfterReplyDelivery) {
2745
+ pending._finalizeAfterReplyDelivery = false;
2746
+ pending._timeoutAfterReplyDelivery = null;
2747
+ this._finalizeTurn(turnId);
2748
+ } else if (pending._timeoutAfterReplyDelivery) {
2749
+ const deferred = pending._timeoutAfterReplyDelivery;
2750
+ pending._timeoutAfterReplyDelivery = null;
2751
+ pending._fireTimeout?.(deferred.reason, deferred.probeResult);
2752
+ }
2753
+ }
2754
+ }
2755
+
2670
2756
  _clearLedgerTimers() {
2671
2757
  for (const e of this.inputLedger.values()) {
2672
2758
  if (e._dropTimer) { clearTimeout(e._dropTimer); e._dropTimer = null; }
@@ -3157,6 +3243,10 @@ class CliProcess extends Process {
3157
3243
  _finalizeTurn(turnId) {
3158
3244
  const pending = this.pendingTurns.get(turnId);
3159
3245
  if (!pending) return;
3246
+ if ((pending._replyDeliveriesInFlight || 0) > 0) {
3247
+ pending._finalizeAfterReplyDelivery = true;
3248
+ return;
3249
+ }
3160
3250
  this.pendingTurns.delete(turnId);
3161
3251
  // Review P1 #14: pop the matching pendingQueue entry too so downstream
3162
3252
  // pm callbacks (sdk/callbacks.js context lookup) see a clean queue.
@@ -3328,6 +3418,10 @@ class CliProcess extends Process {
3328
3418
  const fireTimeout = (reason, probeResult = null) => {
3329
3419
  if (!this.pendingTurns.has(turnId)) return;
3330
3420
  const pending = this.pendingTurns.get(turnId);
3421
+ if ((pending._replyDeliveriesInFlight || 0) > 0) {
3422
+ pending._timeoutAfterReplyDelivery = { reason, probeResult };
3423
+ return;
3424
+ }
3331
3425
  // A question waits for the user: while an `ask` is open the turn must NOT
3332
3426
  // time out and die mid-question. Defer — re-arm the absolute checkpoint and
3333
3427
  // keep waiting; the question store's long safety backstop is the only bound
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shumkov/orchestra",
3
- "version": "0.10.20",
3
+ "version": "0.10.21",
4
4
  "description": "Transport-agnostic session engine for Claude Code and the native Codex app-server: spawn, steer, supervise, observe turns, and recover.",
5
5
  "type": "commonjs",
6
6
  "main": "index.js",