@shumkov/orchestra 0.12.3 → 0.12.4

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,134 @@
1
+ # Folded reply credit without full consumption proof
2
+
3
+ Status: reviewed (lifecycle and simplicity lenses); implemented
4
+ Extends: `docs/FOLDED_REPLY_ATTRIBUTION_SPEC.md`
5
+
6
+ ## Problem
7
+
8
+ Polygram on the UMI VPS (Shumabit bot) still answers twice. On 2026-11-18 in
9
+ the UMI management `finance` topic:
10
+
11
+ 1. message 1238 starts the primary CLI turn (`3fbaba66`); the agent sends an
12
+ interim progress checklist (1239);
13
+ 2. message 1240 arrives and is autosteered into the live primary (ledger
14
+ turn `068875bb`);
15
+ 3. the agent answers the steer with one non-interim `reply` (1243). It echoes
16
+ the steer's `turn_id` and lists only the steer in `consumed_turn_ids`;
17
+ 4. `_resolveReplyAttribution` has no proof that the reply consumed the primary,
18
+ so `_recordReplyForPendingTurn` takes the late-reply branch
19
+ (`cli-late-reply-correlated`); the primary records nothing;
20
+ 5. 30 seconds later the combined CLI cycle stops. The primary has only the
21
+ interim checklist, so `_computeTurnDelivery` takes `interim-rescue` and
22
+ Polygram sends Stop's `last_assistant_message` as message 1245: a recap of
23
+ 1243, in English, quoting 1238.
24
+
25
+ With zero interim replies the same shape takes the `zero-reply` Stop fallback.
26
+ The August fix (`FOLDED_REPLY_ATTRIBUTION_SPEC.md`) only covers replies whose
27
+ `consumed_turn_ids` names both the steer and the primary; Claude does not
28
+ always do that.
29
+
30
+ Production, Shumabit, 30 days to 2026-11-18: 46 turns resolved with
31
+ `already_delivered=false` and a non-empty fallback text; in 16 of them a
32
+ `cli-late-reply-correlated` reply landed in the same session while the turn
33
+ was live (9 `interim-rescue`, 7 `zero-reply`). Each is a visible second answer.
34
+ The other 30 have no late reply and are not affected by this change.
35
+
36
+ ## Approach
37
+
38
+ Prove the fold from the follow-up's own UserPromptSubmit, and let the proof
39
+ change only what the host turn delivers at Stop.
40
+
41
+ 1. UserPromptSubmit handler: when it picks up a ledgered `autosteer` or
42
+ `edit-fold` entry that is not itself a pending turn, and exactly one
43
+ pending turn runs in the same query (`pending._promptId === ev.promptId`),
44
+ store that turn's id on the entry as `foldHostTurnId`.
45
+ The pinned CLI gives a follow-up folded into a running query that query's
46
+ `prompt_id`; a follow-up run as its own query gets a new one
47
+ (`CLI_API_ERROR_STOP_FAILURE_SPEC.md`, verified on 2.1.283). The finance
48
+ session on 2.1.322 shows the same shape: the follow-up is a
49
+ `queued_command` attachment inside the primary's single `promptId`.
50
+ 2. `_recordReplyForPendingTurn`, late-reply branch: keep everything it does
51
+ today. In addition, for a non-interim reply whose entry has a
52
+ `foldHostTurnId` that is still pending and not being interrupted, set
53
+ `host._foldReplyCredited = true` and log `cli-fold-reply-credited`
54
+ (`turn_id` = host, `reply_turn_id` = echoed id, `source`).
55
+ 3. `_computeTurnDelivery`: after the existing `final-reply` branch, a credited
56
+ turn with Stop text returns `alreadyDelivered: true`, branch
57
+ `fold-reply-credited`. The text is returned for the consumer's transcript
58
+ and telemetry only, as the consumed-ack branch already does.
59
+
60
+ Nothing else changes. The reply is not added to the host's `replies`, so
61
+ `_turnHasFinalReply`, activity-quiet finalization, quiet timers, the reply cap
62
+ and `_clearFollowUpsThrough` behave as today: the host still ends on its own
63
+ Stop. The API-error path does not read the flag, so a query that fails after
64
+ the follow-up was answered still reports the error for the primary. Dispatch,
65
+ the quoted message (the follow-up), ledger acknowledgement and content dedup
66
+ are unchanged.
67
+
68
+ If the follow-up's UserPromptSubmit has not been read when the reply arrives
69
+ (hook log lag), nothing is credited and the old behaviour (a possible second
70
+ message) applies. The change can only remove a message when the fold is
71
+ proven.
72
+
73
+ ## Trade-off (new, not covered by the August decision)
74
+
75
+ August's option 1 suppressed the Stop text only when the reply's
76
+ `consumed_turn_ids` named the primary, which is Claude's own claim that the
77
+ reply answered it. Here Claude named only the follow-up. If Claude answers the
78
+ follow-up, keeps working on the primary and puts the primary's answer only in
79
+ its closing text without a `reply`, that answer is no longer sent.
80
+
81
+ Evidence that this is the right trade-off: the 16 production cases above were
82
+ read (first lines of each message only). In all 16 the Stop text was an English
83
+ third-person recap of what had already been sent or done ("I sent Mai…",
84
+ "Waiting for Mai's answer…", "Yes, I researched the methods…"). None held an
85
+ answer that was not already in the chat. This matches August's 12/12.
86
+
87
+ Telemetry to watch after release: `cli-resolve-delivery` with branch
88
+ `fold-reply-credited` and its `text_len`; any user report of a missing answer
89
+ after a mid-turn follow-up.
90
+
91
+ ## Alternatives rejected
92
+
93
+ - Record the host at injection time and credit until its Stop is captured
94
+ (first draft). Stop is read 250 ms to 5 s after the bridge socket, and
95
+ `_stopHookData` is also set by sub-agent boundary Stops and not set for
96
+ unattributed Stops, so it is not a reliable "query ended" signal.
97
+ - Record the reply on the host through `_recordReplyForPendingTurn`. It would
98
+ make the host look answered, letting activity-quiet end it while Claude is
99
+ still working, and would hide an API error from the primary.
100
+ - Treat any late autosteer reply as the single pending turn's reply. Rejected
101
+ in the August spec: a follow-up folded into an earlier turn would be
102
+ credited to an unrelated later turn.
103
+ - Compare Stop text with delivered replies. The duplicates are recaps or
104
+ translations (1245 is English, 1243 Russian), so text equality misses them.
105
+ - Re-anchor the reply on the primary (as the proven-fold path does). It changes
106
+ which message the bubble quotes; the reply correctly quotes the follow-up
107
+ today. Quote placement is a separate open design (Polygram
108
+ `docs/STEER_VISUAL_SEGMENTS_SPEC.md`, unmerged).
109
+ - Fix it in the prompt only. Claude already has the instruction to list both
110
+ ids and does not always follow it.
111
+
112
+ ## Verification
113
+
114
+ Integration tests in `tests/cli-process-integration.test.js`:
115
+
116
+ - finance trace: primary, interim checklist, folded follow-up (same
117
+ `prompt_id`), final reply naming only the follow-up, Stop with different
118
+ text: `alreadyDelivered: true`, branch `fold-reply-credited`, reply still
119
+ quotes the follow-up. Red before the change.
120
+ - the same with no interim reply (`zero-reply` shape). Red before the change.
121
+ - interim reply to the follow-up: not credited, Stop text delivered.
122
+ - follow-up run as its own query (new `prompt_id`): not credited.
123
+ - follow-up whose UserPromptSubmit was not observed: not credited.
124
+ - StopFailure after a credited reply: the primary is still rejected with
125
+ `CLAUDE_API_ERROR`.
126
+ - follow-up folded into an earlier, finished turn and answered during a new
127
+ turn: stays late, not credited, the new turn delivers its own Stop text.
128
+ (Rewrite of the "unproven old autosteer reply" test, which injected into the
129
+ current primary and so encoded the bug.)
130
+
131
+ Then Polygram consumes the new exact Orchestra version and runs its full
132
+ suite. Production proof after deploy: `cli-fold-reply-credited` events appear,
133
+ and `cli-resolve-delivery` with `already_delivered=false` after a
134
+ `cli-late-reply-correlated` in the same turn drops from ~16/month toward zero.
@@ -2566,6 +2566,7 @@ class CliProcess extends Process {
2566
2566
  if (!interim) this._followUpAnswered(replyTurnId);
2567
2567
  this._ledgerTransition(replyTurnId, 'resolved');
2568
2568
  this._logEvent('cli-late-reply-correlated', { turn_id: replyTurnId, source: lEntry.source });
2569
+ if (!interim) this._creditFoldHost(replyTurnId, lEntry);
2569
2570
  this.emit('autonomous-assistant-message', {
2570
2571
  text,
2571
2572
  sessionId: this.claudeSessionId,
@@ -2701,6 +2702,43 @@ class CliProcess extends Process {
2701
2702
  return true;
2702
2703
  }
2703
2704
 
2705
+ /**
2706
+ * A follow-up picked up inside a pending turn's query (its UserPromptSubmit
2707
+ * carries that turn's prompt_id) was folded into that turn. Remember the
2708
+ * turn so a final reply to the follow-up can be credited to it. A follow-up
2709
+ * claude runs as its own query gets a new prompt_id and no host.
2710
+ */
2711
+ _noteFoldHost(lEntry, promptId) {
2712
+ if (!promptId || lEntry.foldHostTurnId) return;
2713
+ if (lEntry.source !== 'autosteer' && lEntry.source !== 'edit-fold') return;
2714
+ let hostId = null;
2715
+ for (const [turnId, pending] of this.pendingTurns) {
2716
+ if (pending._promptId !== promptId) continue;
2717
+ if (hostId) return; // ambiguous: credit nobody
2718
+ hostId = turnId;
2719
+ }
2720
+ if (hostId) lEntry.foldHostTurnId = hostId;
2721
+ }
2722
+
2723
+ /**
2724
+ * A final reply to a folded follow-up was delivered while its host turn is
2725
+ * still running. Claude often names only the follow-up in
2726
+ * consumed_turn_ids, so the reply stays attributed (and quoted) to the
2727
+ * follow-up, but the host must know its query already put a final answer
2728
+ * in the chat: otherwise Stop's closing text, usually a recap of that
2729
+ * answer, is sent again as a second message. Only delivery is affected;
2730
+ * the host still ends on its own Stop, and an API error still reports.
2731
+ */
2732
+ _creditFoldHost(replyTurnId, lEntry) {
2733
+ const hostId = lEntry.foldHostTurnId;
2734
+ const host = hostId ? this.pendingTurns.get(hostId) : null;
2735
+ if (!host || host._interruptRequested) return;
2736
+ host._foldReplyCredited = true;
2737
+ this._logEvent('cli-fold-reply-credited', {
2738
+ turn_id: hostId, reply_turn_id: replyTurnId, source: lEntry.source,
2739
+ });
2740
+ }
2741
+
2704
2742
  // ─── 0.13 D2: InputLedger ──────────────────────────────────────────
2705
2743
 
2706
2744
  _ledgerAdd(turnId, { source, msgId = null, participantJid = null } = {}) {
@@ -3282,6 +3320,11 @@ class CliProcess extends Process {
3282
3320
  if (this._turnHasFinalReply(pending)) {
3283
3321
  return { text: interimText, alreadyDelivered: true, branch: 'final-reply' };
3284
3322
  }
3323
+ if (pending._foldReplyCredited === true && fallbackText) {
3324
+ // A folded follow-up's final reply already answered in this query; the
3325
+ // Stop text is its closing recap, not a missing answer.
3326
+ return { text: fallbackText, alreadyDelivered: true, branch: 'fold-reply-credited' };
3327
+ }
3285
3328
  if (pending.replies.length === 0) {
3286
3329
  // 0.12 Phase 1.7 fallback: no reply tool call landed — use the Stop hook's
3287
3330
  // last_assistant_message so the user isn't left with silence (rc.41 H4).
@@ -4699,6 +4742,10 @@ class CliProcess extends Process {
4699
4742
  // picked up — the messages to answer if this prompt, owning no
4700
4743
  // pending turn, later ends in an API error.
4701
4744
  const followUps = [];
4745
+ // Ledgered inputs this prompt picked up that are not pending turns
4746
+ // themselves; matched to their host after every envelope is marked
4747
+ // seen, so a host listed later in the same prompt still counts.
4748
+ const foldCandidates = [];
4702
4749
  if (typeof ev.prompt === 'string' && ev.prompt) {
4703
4750
  for (const m of ev.prompt.matchAll(UPS_ENVELOPE_TURN_ID_RE)) {
4704
4751
  const seenPending = this.pendingTurns.get(m[1]);
@@ -4722,6 +4769,7 @@ class CliProcess extends Process {
4722
4769
  }
4723
4770
  // 0.13 D3: the picked-up message anchors the cycle's visuals.
4724
4771
  if (anchorMsgId == null && lEntry.msgId != null) anchorMsgId = lEntry.msgId;
4772
+ if (!seenPending) foldCandidates.push(lEntry);
4725
4773
  // A follow-up the user cancelled with /stop is not waiting for an
4726
4774
  // answer, even if claude still runs it.
4727
4775
  if (lEntry.source !== 'primary' && lEntry.msgId != null && lEntry.state !== 'cancelled') {
@@ -4730,6 +4778,7 @@ class CliProcess extends Process {
4730
4778
  }
4731
4779
  }
4732
4780
  }
4781
+ for (const lEntry of foldCandidates) this._noteFoldHost(lEntry, ev.promptId);
4733
4782
  // Track the prompt until its query ends (see _openPrompts). A prompt a
4734
4783
  // pending turn runs in is settled through that turn, so it answers no
4735
4784
  // follow-ups of its own: a late failure of an already-settled turn can
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shumkov/orchestra",
3
- "version": "0.12.3",
3
+ "version": "0.12.4",
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",