@shumkov/orchestra 0.12.2 → 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.
@@ -205,6 +205,7 @@ const CONSTRUCTOR_KEYS = new Set([
205
205
  // Keyed by the pending record itself, so a forged record inserted into the
206
206
  // pending map carries no projector and can never yield a raw response.
207
207
  const RESULT_PROJECTORS = new WeakMap();
208
+ const THREAD_READ_IDS = new WeakMap();
208
209
  const CLIENT_REQUESTS = new Map(Object.entries(protocolSchema.clientRequests));
209
210
  const CLIENT_NOTIFICATIONS = new Set(protocolSchema.clientNotifications);
210
211
  const DENIED_CLIENT_REQUESTS = new Set(protocolSchema.deniedClientRequests);
@@ -1491,8 +1492,29 @@ function projectRuntimeWorkspaceRoots(value, ownedCwd) {
1491
1492
  };
1492
1493
  }
1493
1494
 
1494
- function projectRpcResult(method, value, ownedCwd) {
1495
+ function projectRpcResult(method, value, ownedCwd, readThreadId) {
1495
1496
  const result = protocolObject(value, `${method} result`);
1497
+ if (method === 'thread/read') {
1498
+ const thread = protocolObject(result.thread, 'saved thread');
1499
+ if (
1500
+ thread.id !== readThreadId
1501
+ || !Array.isArray(thread.turns)
1502
+ || thread.turns.length !== 0
1503
+ ) {
1504
+ throw new CodexAppServerError(
1505
+ 'app-server saved thread identity is inconsistent',
1506
+ 'CODEX_PROTOCOL_ERROR',
1507
+ );
1508
+ }
1509
+ return {
1510
+ thread: projectThread(
1511
+ thread,
1512
+ 'saved thread',
1513
+ ownedCwd,
1514
+ protocolRequiredString(thread.modelProvider, 'saved thread provider'),
1515
+ ),
1516
+ };
1517
+ }
1496
1518
  if (method === 'initialize') {
1497
1519
  return {
1498
1520
  codexHome: protocolRequiredString(
@@ -2170,6 +2192,15 @@ function projectRequestParams(method, params, spec, ownedCwd) {
2170
2192
  }
2171
2193
  return { cwds: [ownedCwd] };
2172
2194
  }
2195
+ if (method === 'thread/read') {
2196
+ if (params.includeTurns !== false) {
2197
+ throw new CodexAppServerError(
2198
+ 'app-server saved thread read cannot request history',
2199
+ 'CODEX_RPC_REJECTED',
2200
+ );
2201
+ }
2202
+ return { threadId: threadId(), includeTurns: false };
2203
+ }
2173
2204
  if (method === 'thread/resume') return { threadId: threadId() };
2174
2205
  if (method === 'turn/start') {
2175
2206
  const projected = {
@@ -2373,6 +2404,7 @@ function dispatchRequest(client, method, params, {
2373
2404
  timer: null,
2374
2405
  sinkController: null,
2375
2406
  };
2407
+ if (method === 'thread/read') THREAD_READ_IDS.set(pending, projectedParams.threadId);
2376
2408
  pending.timer = client.setTimer(() => {
2377
2409
  if (client.pending.get(id) !== pending) return;
2378
2410
  const timeoutError = new CodexAppServerError(
@@ -3306,7 +3338,7 @@ class CodexAppServerClient extends EventEmitter {
3306
3338
  const projectResult = RESULT_PROJECTORS.get(pending);
3307
3339
  projectedResult = typeof projectResult === 'function'
3308
3340
  ? projectResult(message.result)
3309
- : projectRpcResult(pending.method, message.result, this.cwd);
3341
+ : projectRpcResult(pending.method, message.result, this.cwd, THREAD_READ_IDS.get(pending));
3310
3342
  } else {
3311
3343
  projectedError = projectRpcError(message.error);
3312
3344
  }
@@ -3352,9 +3384,12 @@ class CodexAppServerClient extends EventEmitter {
3352
3384
  if (this.pending.get(message.id) !== pending) return;
3353
3385
  this.pending.delete(message.id);
3354
3386
  if (hasError) {
3387
+ const missingThread = pending.method === 'thread/read'
3388
+ && projectedError.code === -32600
3389
+ && projectedError.message === `thread not loaded: ${THREAD_READ_IDS.get(pending)}`;
3355
3390
  const error = new CodexAppServerError(
3356
3391
  `app-server ${pending.method} failed`,
3357
- 'CODEX_RPC_ERROR',
3392
+ missingThread ? 'CODEX_THREAD_UNAVAILABLE' : 'CODEX_RPC_ERROR',
3358
3393
  );
3359
3394
  error.rpcCode = projectedError.code;
3360
3395
  if (
@@ -68,6 +68,11 @@
68
68
  "optional": [],
69
69
  "stateChanging": true
70
70
  },
71
+ "thread/read": {
72
+ "required": ["threadId", "includeTurns"],
73
+ "optional": [],
74
+ "stateChanging": false
75
+ },
71
76
  "thread/resume": {
72
77
  "required": [
73
78
  "threadId"
@@ -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
@@ -633,6 +633,16 @@ class CodexProcess extends Process {
633
633
  // is proven before either kind of attachment.
634
634
  await this._verifyHookTrust();
635
635
  this._assertLifecycle(lifecycle);
636
+ if (existingSessionId) {
637
+ const metadata = await this.client.request('thread/read', {
638
+ threadId: existingSessionId,
639
+ includeTurns: false,
640
+ });
641
+ this._assertLifecycle(lifecycle);
642
+ if (metadata?.thread?.id !== existingSessionId || metadata.thread.ephemeral !== false) {
643
+ throw processError('Codex saved thread metadata is inconsistent', 'CODEX_PROTOCOL_ERROR');
644
+ }
645
+ }
636
646
  this.state = 'AttachingThread';
637
647
  this.attachingThreadId = existingSessionId;
638
648
  const result = await this._withSettingsGate(async () => (
@@ -3008,9 +3018,11 @@ class CodexProcess extends Process {
3008
3018
  readClientFaultProvenance(outcome),
3009
3019
  );
3010
3020
  await this._enterContainment(
3011
- outcome?.errorCode === 'CODEX_RPC_OUTCOME_UNKNOWN'
3012
- ? 'rpc-outcome-unknown'
3013
- : 'app-server-fault',
3021
+ this.state === 'AttachingThread' && this.providerSessionId == null
3022
+ ? 'thread-attach-outcome-unknown'
3023
+ : outcome?.errorCode === 'CODEX_RPC_OUTCOME_UNKNOWN'
3024
+ ? 'rpc-outcome-unknown'
3025
+ : 'app-server-fault',
3014
3026
  error,
3015
3027
  );
3016
3028
  }
@@ -3241,6 +3253,7 @@ class CodexProcess extends Process {
3241
3253
  try {
3242
3254
  await this._checkpoint('containment-entered', {
3243
3255
  reason,
3256
+ threadId: this.providerSessionId ?? this.attachingThreadId ?? null,
3244
3257
  errorCode: error?.code ?? null,
3245
3258
  turnId: ownedTurnId ?? null,
3246
3259
  ...this.containmentProvenance,
@@ -3300,6 +3313,7 @@ class CodexProcess extends Process {
3300
3313
  if (this.state !== 'ContainmentFailed') return null;
3301
3314
  await this._checkpoint('containment-cleanup-completed', {
3302
3315
  reason: this.containmentReason,
3316
+ threadId: this.providerSessionId ?? this.attachingThreadId ?? null,
3303
3317
  errorCode: this.containmentErrorCode,
3304
3318
  turnId: this.containmentTurnId,
3305
3319
  ...this.containmentProvenance,
@@ -916,6 +916,17 @@ class ProcessManager {
916
916
  }
917
917
  if (this._isCodex(existing)) {
918
918
  this._assertStrictResumeReuse(existing, spawnContext);
919
+ const failedStateCodes = {
920
+ ContainmentFailed: 'CODEX_CONTAINMENT_FAILED',
921
+ FailedAmbiguous: 'CODEX_RPC_OUTCOME_UNKNOWN',
922
+ DurabilityBlocked: 'CODEX_DURABILITY_FAILED',
923
+ };
924
+ if (failedStateCodes[existing.state]) {
925
+ throw managerError(
926
+ 'Codex generation remains fenced pending verified cleanup',
927
+ failedStateCodes[existing.state],
928
+ );
929
+ }
919
930
  }
920
931
  // Reload-on-drift (cli): a warm cli proc can't hot-swap model/effort or
921
932
  // its display hint (all spawn-time). If the resolved config has drifted
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shumkov/orchestra",
3
- "version": "0.12.2",
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",