@shumkov/orchestra 0.10.20 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,92 @@
1
+ # Claude Code 2.1.283 compatibility
2
+
3
+ Orchestra 0.11.0 pins the channels backend to Claude Code 2.1.283. The pin is
4
+ now defined by the Agent SDK: `@anthropic-ai/claude-agent-sdk` 0.3.283 is
5
+ pinned exactly, `CLAUDE_CLI_PINNED_VERSION` must equal its `claudeCodeVersion`
6
+ (a unit test enforces it), and the vendored binary is copied from the SDK's
7
+ per-platform package. On darwin-arm64 that binary is byte-identical to the
8
+ auto-updater's 2.1.283 (SHA-256 `d8cb1e5c…1d21e`, same Anthropic signature).
9
+
10
+ ## Behavior changes handled
11
+
12
+ - **Workspace trust dialog.** 2.1.283 lists "❯ No, exit" first and pre-selects
13
+ it; Enter exits claude. The dialog can also render before it accepts input.
14
+ The startup gate now presses Down until "❯ Yes, I trust this folder" is
15
+ visibly selected, then Enter. Not in the upstream changelog; found by a live
16
+ probe.
17
+ - **System prompt recording** (2.1.267+). A conversation records its appended
18
+ system prompt once and replays it on resume until compaction. `CliProcess`
19
+ passes `--system-prompt-snapshot off` when `--help` lists it, so display
20
+ rules and the reply contract rebuilt on each spawn reach resumed chats.
21
+ 2.1.220 rejects the flag, so it is feature-detected once per binary. Tool
22
+ definitions stay recorded even with the snapshot off.
23
+ - **Opus 5.5** is what `--model opus` resolves to (2.1.280).
24
+
25
+ ## Live probes (2.1.283, real sessions through `CliProcess`)
26
+
27
+ | Probe | Result |
28
+ |---|---|
29
+ | Footer while streaming | `esc to interrupt` present in 14 of 16 mid-turn captures; `STREAMING_HINT_RE` unchanged |
30
+ | Footer with a background shell | `⏵⏵ bypass permissions on · 1 shell`; `BACKGROUND_SHELL_RE` extracts 1 |
31
+ | Dangerous `rm` in bypass mode, 4 triggers | Triggers 1–3 show "Do you want to proceed?" with an auto-deny countdown and are denied after ~2 min (129–148 s); the turn continues and replies. Trigger 4 is denied without a dialog (14 s) after 3 unanswered prompts. No approval card is emitted; the dialog only produces `cli-mid-turn-unknown-prompt` telemetry. |
32
+ | Trust dialog | Handled by the new gate (see above) |
33
+ | Session-age dialog | Option order unchanged ("Resume from summary" first); `CLAUDE_CODE_RESUME_THRESHOLD_MINUTES` still present, so the dialog stays suppressed |
34
+ | Rollback direction | 2.1.220 resumes a session written by 2.1.283 and recalls its context |
35
+
36
+ ## Known upstream regression: auto-backgrounded MCP calls (SDK)
37
+
38
+ With `CLAUDE_AUTO_BACKGROUND_TASKS=1`, 2.1.283 moves a slow MCP tool call to
39
+ the background after about 1 s, ends the turn, then reports the background
40
+ task as `failed`; every retry returns "The tool call was interrupted before a
41
+ result was received" (3 of 3 gate runs; 2.1.220 completes it). Without the
42
+ opt-in, which is how production runs, the call stays in the foreground and
43
+ completes (2 of 2 runs plus the authoritative matrix). Do not enable
44
+ `CLAUDE_AUTO_BACKGROUND_TASKS` on this pin. The gate records this cell as a
45
+ known regression for 2.1.283 and keeps gating the foreground path.
46
+
47
+ ## Known limitation: long working directories
48
+
49
+ Claude Code truncates the `~/.claude/projects/<encoded-cwd>` directory name at
50
+ about 200 characters and appends a short hash (observed on 2.1.220, e.g.
51
+ `…-workflow-workspace--d9uh4m`). Orchestra's and Polygram's session-log path
52
+ helpers assume the plain encoding, so session-log reading fails for a cwd whose
53
+ encoded name exceeds that length. Production cwds are far shorter; the gate
54
+ must run with a short artifact base.
55
+
56
+ ## Compatibility gate
57
+
58
+ Polygram's serial real-Claude matrix (2.1.220 ↔ 2.1.283, run
59
+ `2026-09-26T16-30-19-568Z`) passed all 22 authoritative runs and was accepted:
60
+
61
+ - two independent CLI contract runs per version;
62
+ - direct and failed-reply Workflow completion delivery;
63
+ - delayed MCP completion on the default (foreground) path;
64
+ - SDK PostToolBatch, subagent, resume, manual compact, and tool-less drain;
65
+ - the candidate Opus 5.5 production projection;
66
+ - the candidate system-prompt snapshot cell: with recording forced on the
67
+ resumed session kept the first prompt, and with `--system-prompt-snapshot
68
+ off` it saw the changed prompt, so recording is active for the account and
69
+ the flag is what keeps prompt changes reaching resumed chats.
70
+
71
+ Two cells are waived and listed in every summary: the
72
+ `CLAUDE_AUTO_BACKGROUND_TASKS=1` delayed-MCP path (a 2.1.283 regression, see
73
+ above; intermittent on 2.1.220; unused in production).
74
+
75
+ 2.1.283 lifecycle differences the matrix declares per version: an extra
76
+ UserPromptSubmit hook for a prompt folded into a running turn; eight passive
77
+ context attachments recorded once per session (counted, position-free, since
78
+ their order against the first queued message is a race); an `auto_mode`
79
+ attachment in Opus sessions; new `atis-latch` and `cost-state` transcript rows;
80
+ SDK `tool_progress` heartbeats and a variable number of `status` notices.
81
+ `total_tokens_reminder` attachments appear on both versions.
82
+
83
+ Acceptance note: the run's evidence tree held one hook ndjson a late hook had
84
+ recreated as 0644 after the session was torn down (fixed in this release:
85
+ the hook helper now creates files 0600). It was set to 0600 before
86
+ acceptance; its content is outside the evaluated evidence.
87
+
88
+ ## Rollback
89
+
90
+ Reinstall the previous Orchestra/Polygram. Boot deletes every vendored version
91
+ except the pin, so preserve the 2.1.220 binary outside the vendor directory
92
+ before deploying and copy it back before restarting the old version.
@@ -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.
package/lib/claude-bin.js CHANGED
@@ -5,10 +5,15 @@ const os = require('os');
5
5
  const path = require('path');
6
6
  const fs = require('fs');
7
7
  const { execFileSync } = require('child_process');
8
+ const { createRequire } = require('module');
8
9
 
9
10
  // The channels backend consumes Claude Code's private TUI, hook, and session
10
11
  // formats. Change this pin only after the real-CLI compatibility gate passes.
11
- const CLAUDE_CLI_PINNED_VERSION = '2.1.220';
12
+ // It must equal the `claudeCodeVersion` of the exact Agent SDK version in
13
+ // package.json: that SDK's platform package supplies the vendored binary, and
14
+ // a unit test fails when the two drift apart. It stays a literal because
15
+ // consumers that omit optional dependencies have no SDK to derive it from.
16
+ const CLAUDE_CLI_PINNED_VERSION = '2.1.283';
12
17
 
13
18
  /**
14
19
  * Resolve + verify the pinned claude CLI binary.
@@ -108,14 +113,126 @@ function isExecutable(p) {
108
113
  try { fs.accessSync(p, fs.constants.X_OK); return true; } catch { return false; }
109
114
  }
110
115
 
111
- // Atomic: copy to a unique tmp in the same dir, chmod, then rename over.
112
- function _atomicCopyExec(src, dst) {
116
+ // `claude --version` prints e.g. "2.1.283 (Claude Code)".
117
+ function _reportedVersion(bin) {
118
+ const out = execFileSync(bin, ['--version'], { timeout: 30_000, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
119
+ return out.trim().split(/\s+/)[0];
120
+ }
121
+
122
+ // Atomic and validated: copy to a unique tmp in the same dir, chmod, check the
123
+ // copy, then rename over. The check matters because the fast path trusts any
124
+ // executable file in the vendor dir forever, and a source can be caught
125
+ // mid-write (`npm i -g` extracts in place while a service may be restarting).
126
+ function _atomicCopyExec(src, dst, version) {
113
127
  const tmp = `${dst}.tmp.${process.pid}.${Date.now()}`;
114
- fs.copyFileSync(src, tmp);
115
- fs.chmodSync(tmp, 0o755);
116
- fs.renameSync(tmp, dst);
128
+ try {
129
+ fs.copyFileSync(src, tmp);
130
+ fs.chmodSync(tmp, 0o755);
131
+ const srcSize = fs.statSync(src).size;
132
+ const tmpSize = fs.statSync(tmp).size;
133
+ if (srcSize !== tmpSize) {
134
+ throw new Error(`copied ${tmpSize} of ${srcSize} bytes`);
135
+ }
136
+ let reported;
137
+ try { reported = _reportedVersion(tmp); } catch (e) {
138
+ throw new Error(`\`--version\` failed: ${e.message}`);
139
+ }
140
+ if (reported !== version) {
141
+ throw new Error(`\`--version\` reported ${JSON.stringify(reported)}, expected ${version}`);
142
+ }
143
+ fs.renameSync(tmp, dst);
144
+ } catch (e) {
145
+ try { fs.rmSync(tmp, { force: true }); } catch {}
146
+ throw e;
147
+ }
148
+ }
149
+
150
+ const SDK_PACKAGE = '@anthropic-ai/claude-agent-sdk';
151
+
152
+ // True on Linux hosts without glibc (e.g. Alpine). Same test the SDK uses.
153
+ function _hostPrefersMusl() {
154
+ if (process.platform !== 'linux') return false;
155
+ const report = typeof process.report?.getReport === 'function' ? process.report.getReport() : null;
156
+ return report != null && report.header?.glibcVersionRuntime === undefined;
157
+ }
158
+
159
+ /**
160
+ * Locate the claude binary shipped in the Agent SDK's per-platform optional
161
+ * package, resolving it the way the SDK itself does. Resolution starts from
162
+ * the SDK's own directory so a nested SDK copy finds its matching platform
163
+ * package.
164
+ *
165
+ * @param {object} [opts]
166
+ * @param {NodeRequire} [opts.requireFrom] — require used to find the SDK
167
+ * @param {string} [opts.platform] [opts.arch] [opts.preferMusl]
168
+ * @returns {{ ok: boolean, path?: string, claudeCodeVersion?: string, sdkVersion?: string, reason?: string }}
169
+ */
170
+ function findSdkClaudeBin({
171
+ requireFrom = require,
172
+ platform = process.platform,
173
+ arch = process.arch,
174
+ preferMusl = _hostPrefersMusl(),
175
+ } = {}) {
176
+ let sdkPkgPath;
177
+ try {
178
+ sdkPkgPath = path.join(path.dirname(requireFrom.resolve(SDK_PACKAGE)), 'package.json');
179
+ } catch (e) {
180
+ return { ok: false, reason: `${SDK_PACKAGE} not installed (${e.code || e.message})` };
181
+ }
182
+ let sdkPkg;
183
+ try { sdkPkg = JSON.parse(fs.readFileSync(sdkPkgPath, 'utf8')); } catch (e) {
184
+ return { ok: false, reason: `cannot read ${sdkPkgPath}: ${e.message}` };
185
+ }
186
+ const suffixes = platform === 'linux'
187
+ ? (preferMusl ? [`linux-${arch}-musl`, `linux-${arch}`] : [`linux-${arch}`, `linux-${arch}-musl`])
188
+ : [`${platform}-${arch}`];
189
+ const sdkRequire = createRequire(sdkPkgPath);
190
+ for (const suffix of suffixes) {
191
+ let bin;
192
+ try { bin = sdkRequire.resolve(`${SDK_PACKAGE}-${suffix}/claude${platform === 'win32' ? '.exe' : ''}`); } catch { continue; }
193
+ let platformPkg;
194
+ try { platformPkg = JSON.parse(fs.readFileSync(path.join(path.dirname(bin), 'package.json'), 'utf8')); } catch { continue; }
195
+ if (platformPkg.version !== sdkPkg.version) {
196
+ return {
197
+ ok: false,
198
+ reason: `${SDK_PACKAGE}-${suffix}@${platformPkg.version} does not match ${SDK_PACKAGE}@${sdkPkg.version}`,
199
+ };
200
+ }
201
+ return { ok: true, path: bin, claudeCodeVersion: sdkPkg.claudeCodeVersion, sdkVersion: sdkPkg.version };
202
+ }
203
+ return { ok: false, reason: `no ${SDK_PACKAGE} platform package for ${platform}/${arch}` };
204
+ }
205
+
206
+ // `claude --help` costs 0.5–1.5s, so it runs at most once per binary path.
207
+ const _helpTextCache = new Map();
208
+
209
+ /**
210
+ * Whether a claude binary accepts a command-line flag, judged by its --help
211
+ * output. Older binaries reject unknown options at startup, so a flag added in
212
+ * a newer CLI must be feature-detected rather than assumed from the pin
213
+ * (overrides and rollbacks can point at older binaries). Failures report false.
214
+ *
215
+ * @param {string} bin
216
+ * @param {string} flag — e.g. '--system-prompt-snapshot'
217
+ * @param {{ logger?: object }} [opts] — a failed --help is warned about once per binary
218
+ * @returns {boolean}
219
+ */
220
+ function supportsClaudeFlag(bin, flag, { logger = console } = {}) {
221
+ if (!_helpTextCache.has(bin)) {
222
+ let help = '';
223
+ try {
224
+ help = execFileSync(bin, ['--help'], { timeout: 30_000, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
225
+ } catch (e) {
226
+ logger?.warn?.(`[claude-bin] \`${bin} --help\` failed (${e.message}); newer claude flags will not be passed to it`);
227
+ }
228
+ _helpTextCache.set(bin, help);
229
+ }
230
+ const escaped = flag.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
231
+ return new RegExp(`(^|\\s)${escaped}(?![\\w-])`, 'm').test(_helpTextCache.get(bin));
117
232
  }
118
233
 
234
+ const STALE_TMP_MS = 10 * 60_000;
235
+
119
236
  // Remove vendored binaries (and stale .tmp.*) that aren't the live version.
120
237
  function _gcVendored(dir, keepVersion, logger) {
121
238
  let entries = [];
@@ -124,11 +241,20 @@ function _gcVendored(dir, keepVersion, logger) {
124
241
  if (name === keepVersion) continue;
125
242
  // Never delete an in-flight copy: a CONCURRENT boot (multi-bot host shares
126
243
  // this dir) may be mid-copy into `<keepVersion>.tmp.<pid>.<ts>`; removing it
127
- // ENOENTs that boot's rename → it falls back to SDK. Skip all .tmp.* — a
128
- // genuinely orphaned tmp is cheap to leave (cleaned when its version is GC'd
129
- // by name, or harmless). Defense-in-depth: only GC version-shaped names so a
130
- // misconfigured vendor dir can't nuke unrelated files.
131
- if (name.includes('.tmp.')) continue;
244
+ // ENOENTs that boot's rename → it falls back to SDK. A copy plus its
245
+ // `--version` check finishes within about a minute, so only temp files
246
+ // untouched for longer than STALE_TMP_MS are orphans (a boot killed
247
+ // mid-copy) and are removed. Defense-in-depth: only GC version-shaped names
248
+ // so a misconfigured vendor dir can't nuke unrelated files.
249
+ if (/^\d+\.\d+\.\d+\.tmp\./.test(name)) {
250
+ try {
251
+ const p = path.join(dir, name);
252
+ if (Date.now() - fs.statSync(p).mtimeMs > STALE_TMP_MS) fs.rmSync(p, { force: true });
253
+ } catch (e) {
254
+ logger?.warn?.(`[claude-bin] vendor GC: could not remove ${name}: ${e.message}`);
255
+ }
256
+ continue;
257
+ }
132
258
  if (!/^\d+\.\d+\.\d+$/.test(name)) continue;
133
259
  try { fs.rmSync(path.join(dir, name), { force: true }); } catch (e) {
134
260
  logger?.warn?.(`[claude-bin] vendor GC: could not remove ${name}: ${e.message}`);
@@ -139,14 +265,14 @@ function _gcVendored(dir, keepVersion, logger) {
139
265
  /**
140
266
  * Ensure a polygram-owned copy of the pinned claude binary exists and return
141
267
  * its path. Steady state is a single stat (fast). On a cold/pruned host it
142
- * obtains the binary once (copy from the system install, else `claude install`
143
- * then copy) and caches it forever.
268
+ * obtains the binary once and caches it forever, trying in order: the Agent
269
+ * SDK's platform package, the system install, then `claude install`.
144
270
  *
145
271
  * @param {string} version
146
- * @param {{ logger?: object }} [opts]
272
+ * @param {{ logger?: object, sdk?: object }} [opts] — `sdk` is passed to findSdkClaudeBin
147
273
  * @returns {{ ok: boolean, path: string, vendored?: boolean, reason?: string }}
148
274
  */
149
- function ensureVendoredClaudeBin(version, { logger = console } = {}) {
275
+ function ensureVendoredClaudeBin(version, { logger = console, sdk = {} } = {}) {
150
276
  // Explicit override wins, unchanged — non-standard installs / CI / tests.
151
277
  const override = process.env.ORCHESTRA_CLAUDE_BIN;
152
278
  if (override) {
@@ -173,10 +299,28 @@ function ensureVendoredClaudeBin(version, { logger = console } = {}) {
173
299
  || path.join(os.homedir(), '.local', 'share', 'claude', 'versions');
174
300
  const systemPath = path.join(versionsDir, version);
175
301
 
302
+ // (0) copy from the Agent SDK's platform package when it bundles exactly
303
+ // this version. Any mismatch or failed validation falls through.
304
+ const fromSdk = findSdkClaudeBin(sdk);
305
+ if (fromSdk.ok && fromSdk.claudeCodeVersion !== version) {
306
+ logger?.log?.(`[claude-bin] Agent SDK ${fromSdk.sdkVersion} bundles claude v${fromSdk.claudeCodeVersion}, not v${version}; skipping it`);
307
+ } else if (fromSdk.ok) {
308
+ try {
309
+ _atomicCopyExec(fromSdk.path, vendored, version);
310
+ logger?.log?.(`[claude-bin] vendored claude v${version} ← Agent SDK ${fromSdk.sdkVersion} (${fromSdk.path}) → ${vendored}`);
311
+ _gcVendored(dir, version, logger);
312
+ return { ok: true, path: vendored, vendored: true };
313
+ } catch (e) {
314
+ logger?.warn?.(`[claude-bin] Agent SDK copy of claude v${version} rejected (${e.message}); trying ${systemPath}`);
315
+ }
316
+ } else {
317
+ logger?.log?.(`[claude-bin] ${fromSdk.reason}; trying ${systemPath}`);
318
+ }
319
+
176
320
  // (a) copy from the system install if present.
177
321
  if (isExecutable(systemPath)) {
178
322
  try {
179
- _atomicCopyExec(systemPath, vendored);
323
+ _atomicCopyExec(systemPath, vendored, version);
180
324
  logger?.log?.(`[claude-bin] vendored claude v${version} ← ${systemPath} → ${vendored}`);
181
325
  } catch (e) {
182
326
  return { ok: false, path: vendored, reason: `copy ${systemPath} → ${vendored} failed: ${e.message}` };
@@ -210,7 +354,7 @@ function ensureVendoredClaudeBin(version, { logger = console } = {}) {
210
354
  return { ok: false, path: vendored, reason: `claude install ${version} ran but ${systemPath} still missing` };
211
355
  }
212
356
  try {
213
- _atomicCopyExec(systemPath, vendored);
357
+ _atomicCopyExec(systemPath, vendored, version);
214
358
  logger?.log?.(`[claude-bin] installed + vendored claude v${version} → ${vendored}`);
215
359
  } catch (e) {
216
360
  return { ok: false, path: vendored, reason: `copy after install failed: ${e.message}` };
@@ -268,6 +412,8 @@ module.exports = {
268
412
  resolvePinnedClaudeBin,
269
413
  verifyPinnedClaudeBin,
270
414
  ensureVendoredClaudeBin,
415
+ findSdkClaudeBin,
416
+ supportsClaudeFlag,
271
417
  vendorDir,
272
418
  CLAUDE_CLI_PINNED_VERSION,
273
419
  checkClaudeAuthHealth,
@@ -58,6 +58,7 @@ const { DEFAULT_TIMEOUT_MS: QUESTION_TIMEOUT_MS } = require('../questions/store'
58
58
  // /private/tmp drift — one of the original Music-topic failures).
59
59
  const { DEFAULT_ATTACHMENT_BASE } = require('./attachment-base');
60
60
  const { resolveCompactionWarnConfig } = require('../compaction-warn');
61
+ const { supportsClaudeFlag } = require('../claude-bin');
61
62
  const { readContextTokens, contextPct } = require('../context-usage');
62
63
  const { runStartupGate } = require('../tmux/startup-gate');
63
64
  const {
@@ -1014,6 +1015,11 @@ class CliProcess extends Process {
1014
1015
  `DROPPED — it gets re-sent to you or flagged as a lost message. When unsure,`,
1015
1016
  'include the id.',
1016
1017
  '',
1018
+ 'A <channel> message whose text is a slash command (`/name some args`) is a',
1019
+ 'request to run that skill: call the Skill tool with `skill` set to `name` and',
1020
+ '`args` set to only the text after `/name` (here `some args`). Never include the',
1021
+ 'command name or its leading slash in `args`.',
1022
+ '',
1017
1023
  '### Staying responsive on a long task — HARD CONTRACT',
1018
1024
  '',
1019
1025
  'The user sees NOTHING while you work — no inline text, no tool output reaches',
@@ -1187,6 +1193,16 @@ class CliProcess extends Process {
1187
1193
  'else as documents.',
1188
1194
  ].join('\n'));
1189
1195
 
1196
+ // Claude Code records the appended system prompt once per conversation
1197
+ // and replays that record on every --resume until compaction. This block
1198
+ // is rebuilt on every spawn (display rules, richText, reply contract), so
1199
+ // turn the recording off to make changes reach resumed chats. Older
1200
+ // binaries reject the option at startup, hence the --help check. Kept
1201
+ // before the variadic --settings / --mcp-config / --add-dir flags.
1202
+ if (supportsClaudeFlag(this.claudeBin, '--system-prompt-snapshot', { logger: this.logger })) {
1203
+ claudeArgs.push('--system-prompt-snapshot', 'off');
1204
+ }
1205
+
1190
1206
  // Parity audit P6: honor isolateUserConfig — mirrors tmux pattern at
1191
1207
  // lib/process/tmux-process.js:502-505,543-546. Channels ALWAYS uses
1192
1208
  // --strict-mcp-config (the bridge requires it), so the MCP half is
@@ -1277,12 +1293,24 @@ class CliProcess extends Process {
1277
1293
  // Dev-channels confirmation — always fires under
1278
1294
  // --dangerously-load-development-channels.
1279
1295
  { name: 'dev-channels', regex: /WARNING: Loading development channels/i, key: 'Enter' },
1280
- // Workspace trust prompt — fires on first-time cwd or untrusted. claude
1281
- // 2.1.158 renders "Quick safety check: Is this a project you created or
1282
- // one you trust? … ❯ 1. Yes, I trust this folder" (Enter confirms the
1283
- // pre-selected "trust" option). The older "trust the files in this folder"
1284
- // wording is kept for back-compat; both anchor on "trust … this folder".
1285
- { name: 'trust', regex: /trust (?:the files in )?this folder/i, key: 'Enter' },
1296
+ // Workspace trust prompt — fires on first-time cwd or untrusted. Enter
1297
+ // confirms whatever the ❯ cursor is on, so it is only sent once the
1298
+ // pane shows "Yes, I trust this folder" selected:
1299
+ // - 2.1.283 lists "❯ No, exit" first and pre-selects it. Press Down
1300
+ // until the cursor visibly moves (the dialog can render before it
1301
+ // accepts input and drop the first key), then the Yes-selected
1302
+ // trigger below confirms.
1303
+ // - 2.1.158–2.1.220 pre-select "❯ 1. Yes, I trust this folder" → Enter.
1304
+ // - older builds ask "Do you trust the files in this folder?" with
1305
+ // "Yes" pre-selected → Enter.
1306
+ // The menu wraps, so each key waits for two identical-state captures:
1307
+ // a lagging Down must not be followed by a second Down (back to "No")
1308
+ // or by an Enter while its redraw is pending. Both regexes only match
1309
+ // the newest dialog frame; the capture includes scrollback. The
1310
+ // confirming variants share one name, so only one ever fires.
1311
+ { name: 'trust-select', regex: /❯\s*(?:\d+\.\s*)?No, exit[^\n]*\n\s*(?:\d+\.\s*)?Yes, I trust this folder(?![\s\S]*I trust this folder)/i, key: 'Down', repeat: true, stablePolls: 2 },
1312
+ { name: 'trust', regex: /❯\s*(?:\d+\.\s*)?Yes, I trust this folder(?![\s\S]*I trust this folder)/i, key: 'Enter', stablePolls: 2 },
1313
+ { name: 'trust', regex: /trust the files in this folder/i, key: 'Enter' },
1286
1314
  // Review F#12 + 2026-06-11 resume-dialog fix: session-age
1287
1315
  // "resume-return" prompt on aged sessions. Bare Enter selects the
1288
1316
  // pre-selected "Resume from summary" — which literally runs /compact
@@ -1990,7 +2018,6 @@ class CliProcess extends Process {
1990
2018
  if (chatIdMatches && Array.isArray(args.consumed_turn_ids) && args.consumed_turn_ids.length) {
1991
2019
  this._ledgerAckConsumed(
1992
2020
  args.consumed_turn_ids.filter((x) => typeof x === 'string'),
1993
- typeof args.text === 'string' ? args.text : '',
1994
2021
  );
1995
2022
  } else if (chatIdMatches && msg.name === 'reply' && 'consumed_turn_ids' in args) {
1996
2023
  this._lastAckFieldAt = Date.now(); // field present but empty — contract observed
@@ -2143,27 +2170,25 @@ class CliProcess extends Process {
2143
2170
  return;
2144
2171
  }
2145
2172
 
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.
2173
+ // Resolve ownership once so dispatch, quoting, and pending-turn bookkeeping
2174
+ // cannot disagree. A folded input can own the model's echoed turn_id while
2175
+ // the one live primary owns the combined answer; consumed_turn_ids is the
2176
+ // explicit proof that connects those two identities.
2177
+ const replyAttribution = this._resolveReplyAttribution(
2178
+ args.turn_id,
2179
+ args.consumed_turn_ids,
2180
+ );
2181
+
2182
+ // Resolve the reply's originating message so the dispatcher has a target
2183
+ // for reactions and reply-quoting. Anything unattributable stays null; it
2184
+ // must never react to or quote an unrelated message.
2154
2185
  //
2155
2186
  // Review F1: quote only the FIRST delivered reply per turn. On SDK,
2156
2187
  // deliverReplies fires once per turn → one quote; the channels dispatcher
2157
2188
  // fires per reply tool call, and an N-reply turn must not produce N
2158
2189
  // bubbles all quoting the same user message.
2159
2190
  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
- }
2191
+ const sourceEntry = replyAttribution.sourceEntry;
2167
2192
  if (sourceEntry && !sourceEntry._quoteUsed) {
2168
2193
  // Message ids may be numeric (Telegram) OR opaque strings (WhatsApp stanza ids).
2169
2194
  // A purely-numeric id coerces to Number so number-based quote/reaction call sites
@@ -2194,6 +2219,12 @@ class CliProcess extends Process {
2194
2219
  const attempt = argumentHash
2195
2220
  ? this._registerDeliveryAttempt(msg.tool_call_id, argumentHash)
2196
2221
  : null;
2222
+ const trackedReplyDeliveries = msg.name === 'reply'
2223
+ ? this._beginReplyDeliveries([
2224
+ replyAttribution.effectiveTurnId,
2225
+ ...(Array.isArray(args.consumed_turn_ids) ? args.consumed_turn_ids : []),
2226
+ ])
2227
+ : [];
2197
2228
  const dispatchPromise = Promise.resolve().then(() => this.toolDispatcher({
2198
2229
  sessionKey: this.sessionKey,
2199
2230
  chatId: this.chatId,
@@ -2203,7 +2234,7 @@ class CliProcess extends Process {
2203
2234
  // The turn this call names. A consumer holding per-turn state needs it
2204
2235
  // to refuse a late reply from an earlier turn — without it, a delayed
2205
2236
  // reply lands on whatever turn the session is holding NOW.
2206
- turnId: typeof args.turn_id === 'string' ? args.turn_id : null,
2237
+ turnId: replyAttribution.effectiveTurnId,
2207
2238
  interim: args.interim === true, // status/progress reply — not the turn's answer
2208
2239
  files: args.files,
2209
2240
  messageId: args.message_id, // 0.13: edit_message target bubble
@@ -2234,6 +2265,7 @@ class CliProcess extends Process {
2234
2265
  if (attempt) this._settleDeliveryAttempt(attempt, result?.ok ? 'sent' : 'failed');
2235
2266
  } catch (err) {
2236
2267
  if (attempt) this._settleDeliveryAttempt(attempt, 'failed');
2268
+ this._finishReplyDeliveries(trackedReplyDeliveries);
2237
2269
  this._writeToBridge({
2238
2270
  kind: 'tool_ack',
2239
2271
  tool_call_id: msg.tool_call_id,
@@ -2301,6 +2333,10 @@ class CliProcess extends Process {
2301
2333
  });
2302
2334
  }
2303
2335
 
2336
+ if (result?.ok && msg.name === 'reply') {
2337
+ this._recordConsumedReplyDelivery(args.consumed_turn_ids, args.text);
2338
+ }
2339
+
2304
2340
  // Review #16 + C9: only record the reply for pending-turn resolution when
2305
2341
  // the dispatcher actually delivered AND the text is a non-empty string.
2306
2342
  // Review P1 #4: route by turn_id (echoed from inbound <channel> meta) so
@@ -2309,8 +2345,21 @@ class CliProcess extends Process {
2309
2345
  // fall back to the SINGLE pending turn if exactly one exists, else the
2310
2346
  // oldest pending — log a warning either way so we can audit drift.
2311
2347
  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);
2348
+ const recorded = this._recordReplyForPendingTurn(
2349
+ args.text,
2350
+ replyAttribution.effectiveTurnId,
2351
+ args.interim === true,
2352
+ );
2353
+ if (recorded && replyAttribution.foldSource) {
2354
+ this._logEvent('cli-fold-reply-attributed', {
2355
+ echoed_turn_id: replyAttribution.echoedTurnId,
2356
+ effective_turn_id: replyAttribution.effectiveTurnId,
2357
+ source: replyAttribution.foldSource,
2358
+ interim: args.interim === true,
2359
+ });
2360
+ }
2313
2361
  }
2362
+ this._finishReplyDeliveries(trackedReplyDeliveries);
2314
2363
  }
2315
2364
 
2316
2365
  /**
@@ -2431,6 +2480,41 @@ class CliProcess extends Process {
2431
2480
  ack();
2432
2481
  }
2433
2482
 
2483
+ /**
2484
+ * Resolve the turn and ledger entry that own a reply without changing the
2485
+ * model-supplied arguments. Fold remapping requires both an echoed fold id
2486
+ * and exactly one live pending id in consumed_turn_ids; every other shape
2487
+ * preserves the existing late/unknown reply behavior.
2488
+ */
2489
+ _resolveReplyAttribution(replyTurnId, consumedTurnIds) {
2490
+ const echoedTurnId = typeof replyTurnId === 'string' ? replyTurnId : null;
2491
+ let effectiveTurnId = echoedTurnId;
2492
+ let sourceEntry = echoedTurnId ? (this.inputLedger.get(echoedTurnId) || null) : null;
2493
+ let foldSource = null;
2494
+
2495
+ if (sourceEntry
2496
+ && !this.pendingTurns.has(echoedTurnId)
2497
+ && (sourceEntry.source === 'autosteer' || sourceEntry.source === 'edit-fold')
2498
+ && Array.isArray(consumedTurnIds)
2499
+ && consumedTurnIds.includes(echoedTurnId)) {
2500
+ const pendingIds = new Set(
2501
+ consumedTurnIds.filter(id => typeof id === 'string' && this.pendingTurns.has(id)),
2502
+ );
2503
+ if (pendingIds.size === 1) {
2504
+ [effectiveTurnId] = pendingIds;
2505
+ foldSource = sourceEntry.source;
2506
+ sourceEntry = this.inputLedger.get(effectiveTurnId) || null;
2507
+ }
2508
+ }
2509
+
2510
+ if (!sourceEntry && this.pendingTurns.size === 1) {
2511
+ const [[onlyTurnId]] = this.pendingTurns;
2512
+ sourceEntry = this.inputLedger.get(onlyTurnId) || null;
2513
+ }
2514
+
2515
+ return { echoedTurnId, effectiveTurnId, sourceEntry, foldSource };
2516
+ }
2517
+
2434
2518
  /**
2435
2519
  * Route a reply text to the pending turn it belongs to.
2436
2520
  *
@@ -2456,7 +2540,7 @@ class CliProcess extends Process {
2456
2540
  backend: this.backend,
2457
2541
  alreadyDelivered: true,
2458
2542
  });
2459
- return;
2543
+ return false;
2460
2544
  }
2461
2545
  let target = null;
2462
2546
  if (replyTurnId && this.pendingTurns.has(replyTurnId)) {
@@ -2498,7 +2582,7 @@ class CliProcess extends Process {
2498
2582
  pending_turn_ids: pendingIds,
2499
2583
  reply_len: text.length,
2500
2584
  });
2501
- return;
2585
+ return false;
2502
2586
  }
2503
2587
  // No pending turns at all → emit canonical 'autonomous-assistant-message'
2504
2588
  // event so polygram's autonomous-msg path (sdk/callbacks.js
@@ -2520,7 +2604,7 @@ class CliProcess extends Process {
2520
2604
  backend: this.backend,
2521
2605
  alreadyDelivered: true,
2522
2606
  });
2523
- return;
2607
+ return false;
2524
2608
  }
2525
2609
 
2526
2610
  target.replies.push(text);
@@ -2546,7 +2630,7 @@ class CliProcess extends Process {
2546
2630
  this._logEvent('cli-reply-cap-noted', { reply_count: target.replyCount });
2547
2631
  }
2548
2632
  this._noteActivity('reply');
2549
- return;
2633
+ return true;
2550
2634
  }
2551
2635
 
2552
2636
  // ── Legacy (rung 3, hook stream never came up): pre-D1 path, byte-identical ──
@@ -2576,6 +2660,7 @@ class CliProcess extends Process {
2576
2660
  } else {
2577
2661
  target.quietTimer = setTimeout(() => this._resolveTurn(target._turnId), this.turnQuietMs);
2578
2662
  }
2663
+ return true;
2579
2664
  }
2580
2665
 
2581
2666
  // ─── 0.13 D2: InputLedger ──────────────────────────────────────────
@@ -2624,16 +2709,8 @@ class CliProcess extends Process {
2624
2709
  if (e._watchdogTimer) { clearTimeout(e._watchdogTimer); e._watchdogTimer = null; }
2625
2710
  }
2626
2711
 
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 = '') {
2712
+ /** A reply carried consumed_turn_ids — acknowledge every known input id. */
2713
+ _ledgerAckConsumed(ids) {
2637
2714
  this._lastAckFieldAt = Date.now();
2638
2715
  for (const id of ids) {
2639
2716
  const e = this.inputLedger.get(id);
@@ -2650,14 +2727,6 @@ class CliProcess extends Process {
2650
2727
  const pending = this.pendingTurns.get(id);
2651
2728
  if (pending) {
2652
2729
  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
2730
  // The ack itself flips rung-2 eligibility on — arm now. (The turn's
2662
2731
  // last _noteActivity ran BEFORE this flag was set, so without this
2663
2732
  // a quiet tail would never re-arm and the turn would sit until a
@@ -2667,6 +2736,51 @@ class CliProcess extends Process {
2667
2736
  }
2668
2737
  }
2669
2738
 
2739
+ /** Record text only after the dispatcher confirms that the consuming reply arrived. */
2740
+ _recordConsumedReplyDelivery(ids, consumingText) {
2741
+ if (!Array.isArray(ids) || typeof consumingText !== 'string') return;
2742
+ for (const id of new Set(ids)) {
2743
+ const pending = this.pendingTurns.get(id);
2744
+ if (pending && consumingText.length > (pending._consumedByText?.length || 0)) {
2745
+ pending._consumedByText = consumingText;
2746
+ }
2747
+ }
2748
+ }
2749
+
2750
+ /** Keep turn finalization behind the outcome of a consuming reply dispatch. */
2751
+ _beginReplyDeliveries(ids) {
2752
+ if (!Array.isArray(ids)) return [];
2753
+ const tracked = [];
2754
+ for (const turnId of new Set(ids)) {
2755
+ const pending = this.pendingTurns.get(turnId);
2756
+ if (!pending) continue;
2757
+ pending._replyDeliveriesInFlight = (pending._replyDeliveriesInFlight || 0) + 1;
2758
+ tracked.push({ turnId, pending });
2759
+ }
2760
+ return tracked;
2761
+ }
2762
+
2763
+ _finishReplyDeliveries(tracked) {
2764
+ for (const { turnId, pending } of tracked) {
2765
+ pending._replyDeliveriesInFlight = Math.max(
2766
+ 0,
2767
+ (pending._replyDeliveriesInFlight || 0) - 1,
2768
+ );
2769
+ if (pending._replyDeliveriesInFlight > 0 || this.pendingTurns.get(turnId) !== pending) {
2770
+ continue;
2771
+ }
2772
+ if (pending._finalizeAfterReplyDelivery) {
2773
+ pending._finalizeAfterReplyDelivery = false;
2774
+ pending._timeoutAfterReplyDelivery = null;
2775
+ this._finalizeTurn(turnId);
2776
+ } else if (pending._timeoutAfterReplyDelivery) {
2777
+ const deferred = pending._timeoutAfterReplyDelivery;
2778
+ pending._timeoutAfterReplyDelivery = null;
2779
+ pending._fireTimeout?.(deferred.reason, deferred.probeResult);
2780
+ }
2781
+ }
2782
+ }
2783
+
2670
2784
  _clearLedgerTimers() {
2671
2785
  for (const e of this.inputLedger.values()) {
2672
2786
  if (e._dropTimer) { clearTimeout(e._dropTimer); e._dropTimer = null; }
@@ -3157,6 +3271,10 @@ class CliProcess extends Process {
3157
3271
  _finalizeTurn(turnId) {
3158
3272
  const pending = this.pendingTurns.get(turnId);
3159
3273
  if (!pending) return;
3274
+ if ((pending._replyDeliveriesInFlight || 0) > 0) {
3275
+ pending._finalizeAfterReplyDelivery = true;
3276
+ return;
3277
+ }
3160
3278
  this.pendingTurns.delete(turnId);
3161
3279
  // Review P1 #14: pop the matching pendingQueue entry too so downstream
3162
3280
  // pm callbacks (sdk/callbacks.js context lookup) see a clean queue.
@@ -3328,6 +3446,10 @@ class CliProcess extends Process {
3328
3446
  const fireTimeout = (reason, probeResult = null) => {
3329
3447
  if (!this.pendingTurns.has(turnId)) return;
3330
3448
  const pending = this.pendingTurns.get(turnId);
3449
+ if ((pending._replyDeliveriesInFlight || 0) > 0) {
3450
+ pending._timeoutAfterReplyDelivery = { reason, probeResult };
3451
+ return;
3452
+ }
3331
3453
  // A question waits for the user: while an `ask` is open the turn must NOT
3332
3454
  // time out and die mid-question. Defer — re-arm the absolute checkpoint and
3333
3455
  // keep waiting; the question store's long safety backstop is the only bound
@@ -59,7 +59,9 @@ process.stdin.on('end', () => {
59
59
  }
60
60
  let fd;
61
61
  try {
62
- fd = fs.openSync(outPath, 'a');
62
+ // Owner-only on creation: payloads carry prompts and tool inputs, and a
63
+ // late hook can recreate the file after cleanup under claude's umask.
64
+ fd = fs.openSync(outPath, 'a', 0o600);
63
65
  fs.writeSync(fd, line + '\n');
64
66
  } catch (err) {
65
67
  process.stderr.write(`water-hook-append: write failed: ${err.message}\n`);
@@ -305,6 +305,13 @@ function collectToolReceipts(branch) {
305
305
  };
306
306
  }
307
307
 
308
+ // Attachment rows that may sit between the Workflow notification and the
309
+ // final text without disqualifying the fallback. Claude Code inserts
310
+ // `total_tokens_reminder` (a context-usage reminder) at points the service
311
+ // chooses. Every other attachment type, e.g. a folded `queued_command`,
312
+ // still fails closed.
313
+ const PASSIVE_ATTACHMENT_TYPES = new Set(['total_tokens_reminder']);
314
+
308
315
  async function correlateWorkflowCompletionSnapshot({
309
316
  transcriptPath,
310
317
  byteSize,
@@ -445,6 +452,9 @@ async function correlateWorkflowCompletionSnapshot({
445
452
  break;
446
453
  }
447
454
  if (!content.toolResultOnly) return result('user-content-empty');
455
+ } else if (row.type === 'attachment' && PASSIVE_ATTACHMENT_TYPES.has(row.attachment?.type)) {
456
+ // Informational context injected by Claude Code; it carries no user
457
+ // input or tool traffic, so it cannot change who owns the final text.
448
458
  } else if (row.type !== 'assistant') {
449
459
  return result('ancestry-row-ineligible');
450
460
  }
@@ -31,7 +31,18 @@
31
31
  * terminates. When `stallMs` is omitted (default), behavior is the pure
32
32
  * `deadlineMs` wall-clock exactly as before.
33
33
  *
34
- * Each trigger is one-shot per gate run (tracked by `name` in a Set).
34
+ * Each trigger is one-shot per gate run (tracked by `name` in a Set),
35
+ * unless it sets `repeat: true`: then it fires on every poll where its regex
36
+ * still matches, up to `maxRepeats` (default 10). Use it for a navigation
37
+ * key the TUI may drop while a dialog is still becoming interactive, and pair
38
+ * it with a one-shot confirming trigger that matches only once the
39
+ * navigation is visible in the pane.
40
+ *
41
+ * `stablePolls: n` (default 1) makes a trigger fire only after its regex has
42
+ * matched n consecutive captures. After any key is sent every trigger's
43
+ * streak restarts, so a key is never sent into a frame that may still be
44
+ * redrawing from the previous one (a wrapping menu can otherwise take a
45
+ * lagging second navigation key back to the option it just left).
35
46
  *
36
47
  * Caller supplies:
37
48
  * - runner: object with `captureWide(tmuxName)` and `sendControl(tmuxName, key)`
@@ -52,7 +63,7 @@ const DEFAULT_SETTLE_MS = 500;
52
63
  * @param {object} opts
53
64
  * @param {object} opts.runner — tmux runner with captureWide + sendControl
54
65
  * @param {string} opts.tmuxName — tmux session name to poll
55
- * @param {Array<{name:string, regex:RegExp, key:string}>} opts.triggers
66
+ * @param {Array<{name:string, regex:RegExp, key?:string, keys?:string[], repeat?:boolean, maxRepeats?:number, stablePolls?:number}>} opts.triggers
56
67
  * @param {RegExp} opts.readySignal — match → resolve
57
68
  * @param {number} [opts.deadlineMs=30000] — absolute backstop
58
69
  * @param {number} [opts.stallMs] — if set, fail after this much
@@ -95,6 +106,8 @@ async function runStartupGate({
95
106
  const deadline = startedAt + deadlineMs;
96
107
  const stallEnabled = Number.isFinite(stallMs) && stallMs > 0;
97
108
  const seen = new Set();
109
+ const fireCounts = new Map();
110
+ const streaks = new Map();
98
111
  const matchedTriggers = [];
99
112
  // rc.4: remember the most recent successful pane snapshot. If the gate
100
113
  // fails (deadline OR session-gone), include the snapshot in the error
@@ -175,11 +188,17 @@ async function runStartupGate({
175
188
  if (pane !== lastPane) lastActivityAt = Date.now();
176
189
  lastPane = pane;
177
190
 
178
- // Walk triggers in declaration order — first match (and not yet seen) wins
191
+ // Update every trigger's consecutive-match streak, then walk triggers in
192
+ // declaration order — the first (not yet seen) whose streak is long
193
+ // enough wins.
194
+ for (const trigger of triggers) {
195
+ streaks.set(trigger, trigger.regex.test(pane) ? (streaks.get(trigger) || 0) + 1 : 0);
196
+ }
179
197
  let matched = false;
180
198
  for (const trigger of triggers) {
181
199
  if (seen.has(trigger.name)) continue;
182
- if (!trigger.regex.test(pane)) continue;
200
+ if (streaks.get(trigger) < (trigger.stablePolls ?? 1)) continue;
201
+ streaks.clear();
183
202
  // `keys: [...]` sends a sequence (dialog navigation — e.g. Down,Enter
184
203
  // to pick a non-default option); `key:` remains the single-key form.
185
204
  // Sequence keys go as separate send-keys calls with a short delay —
@@ -193,9 +212,13 @@ async function runStartupGate({
193
212
  logger.warn?.(`[${label}] sendControl(${keySeq[ki]}) failed for trigger=${trigger.name}: ${err.message}`);
194
213
  }
195
214
  }
196
- seen.add(trigger.name);
197
- matchedTriggers.push(trigger.name);
198
- try { onTrigger?.(trigger.name); } catch { /* telemetry must not break the gate */ }
215
+ const fired = (fireCounts.get(trigger.name) || 0) + 1;
216
+ fireCounts.set(trigger.name, fired);
217
+ if (!trigger.repeat || fired >= (trigger.maxRepeats ?? 10)) seen.add(trigger.name);
218
+ if (fired === 1) {
219
+ matchedTriggers.push(trigger.name);
220
+ try { onTrigger?.(trigger.name); } catch { /* telemetry must not break the gate */ }
221
+ }
199
222
  matched = true;
200
223
  // Sending a key is activity — navigating the TUI counts as progress
201
224
  // even if the pre-transition pane text was static (e.g. a dialog we
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shumkov/orchestra",
3
- "version": "0.10.20",
3
+ "version": "0.11.0",
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",
@@ -43,6 +43,7 @@
43
43
  "url": "git+https://github.com/shumkov/orchestra.git"
44
44
  },
45
45
  "optionalDependencies": {
46
- "@anthropic-ai/claude-agent-sdk": "0.2.123"
46
+ "@anthropic-ai/claude-agent-sdk": "0.3.283",
47
+ "@anthropic-ai/sdk": "0.128.0"
47
48
  }
48
49
  }