Skip to content

fix(runtime): detect a same-size terminal artifact swap the granted stat cannot see - #21436

Merged
nwparker merged 2 commits into
mainfrom
nwparker/terminal-artifact-swap-detection
Sep 19, 2026
Merged

nwparker merged 2 commits into
mainfrom
nwparker/terminal-artifact-swap-detection

Conversation

@nwparker

@nwparker nwparker commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​157 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​157
Prod 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​175 $\color{#cf222e}{\Huge{\mathbf{−}}}$​12 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​163

ELI5

When you click a file path in a terminal, Orca hands out a short-lived pass to read that one file. Before it actually reads it, it double-checks that the file on disk is still the same file it gave you the pass for — so that nothing can quietly substitute a different file in the moment between the two.

That double-check was doing its job by looking at the file's "identity card": which disk it's on, its inode number, its size, and when it was last modified. It turns out that on Linux, all four of those can stay identical even when the file has been completely replaced. So a replacement could slip past the check and get read as though it were the original.

This teaches the check to also remember what the file's contents actually were, so a replacement is caught even when the identity card looks unchanged.

What Changed

Before: a local terminal-artifact grant recorded the file as dev:ino:nlink:size:mtimeMs. If a file was deleted and recreated at the same path with content of the same length, and both writes fell inside the same 1 ms window, every field in that string was identical. The staleness check saw no change and served the replacement's bytes to the caller as if they were the granted file. The user would see the contents of a file they never asked for, with no indication anything had been substituted.

After: the replacement is rejected with terminal_file_grant_stale, exactly as it already was for the cases the old check could see (a size change, a symlink retarget, a new hard link).

Mechanism: local grants now additionally pin a sha256 of the artifact's content. The digest is read from the same open file handle as the stat, so the two describe the same inode and nothing can be swapped in between them. Every local read, preview, and write re-checks the digest against the bytes it actually read, before returning content or committing a write. After a successful write the grant's digest is refreshed alongside its stat identity, the same way it already was for the stat.

Three fields carried the weight in the old check, and on Linux none of them holds up:

Field Behaviour after an unlink + recreate in the same directory
dev unchanged (same filesystem)
ino reused 100% of the time (3000/3000 measured) — ext4 hands back the inode it just freed
nlink 1 before and after
size identical whenever the replacement is the same length
mtimeMs quantised to exactly 1 ms — the kernel's coarse clock only advances once per timer tick

Measured on Node 24 / Linux, replaying the exact sequence: full identity-string collision in 63.7% of iterations back-to-back, 19.8% with a 0.5 ms gap, and 0% at ≥1 ms. The same probe on macOS collided 0 times in 2000 — no inode reuse, and nanosecond-resolution mtimes.

This also explains an intermittent CI failure in orca-runtime-files-terminal-artifact-io.test.ts on rejects stale absolute terminal artifact previews before returning changed content. That test swaps an 8-byte artifact for 8 different bytes, so size cannot separate them and only the 1 ms mtime tick can. Whenever both writes landed in the same tick, the product genuinely could not tell the two files apart and the assertion failed. Its sibling tests never flaked because they change the file's length (11 → 12 bytes) or use symlinks and hard links, all of which the old check does catch. The test was correct; the product was not.

Why

The check exists to stop a world-writable /tmp artifact from being substituted between the moment a grant is issued and the moment it is read. A replacement of the same length is the obvious shape of that substitution, and it was precisely the shape the check could not see. ino was contributing no discriminating power at all against the exact case it was there to catch.

Why the digest sits alongside the stat identity rather than replacing it. The dev:ino:nlink:size:mtimeMs string is a host↔relay wire contract, not a host-local detail. src/relay/fs-handler-terminal-artifact.ts recomputes that same format field-for-field from its own stat and compares it against the expectedStatIdentity the host sends. Changing the format would mean a new host publishing a string that an older relay can never reproduce, so every remote terminal-artifact read would begin failing as terminal_file_grant_stale against any relay that had not been updated in lockstep — a break that reaches old clients with no wire-schema change at all, which is the case docs/reference/remote-wire-compatibility.md calls out. Adding a separate, host-local field leaves the wire untouched and keeps mixed versions working.

Alternatives considered:

  • Add ctimeMs or birthtimeMs to the identity. No help — they come from the same coarse kernel clock and collide in exactly the same 1 ms window.
  • Use bigint: true stats for nanosecond mtimeNs. No help either. The precision loss is not in Node's Number; the stored kernel timestamp itself is tick-quantised, so the extra digits are zeros.
  • Hold the grant's file descriptor open for its 10-minute lifetime and serve from it. Structurally sound, but it pins a file descriptor per outstanding grant and changes the contract from "reject if it changed" to "silently serve the old bytes," which is a different and worse behaviour.
  • Change the identity string format. Rejected for the wire-compatibility reason above.

Cost. Grant creation now reads and hashes the artifact, bounded by the existing 10 MB previewable cap. This happens once per explicit user action (tapping a path in terminal output), not in bulk, and it is the same volume of I/O the subsequent read or preview already performs. Files above the cap digest to null; both read paths already reject them on size before any content leaves the host.

Linked Issue

No tracking issue — this was found while root-causing a recurring CI failure on #19944, which is causally unrelated (it touches two renderer files). Happy to file one retroactively if that is preferred.

Fixes #

Visual Proof

N/A — no UI or interaction change. This is a main-process access check; the only user-visible difference is that a substituted artifact is now refused with the same terminal_file_grant_stale error already produced for the detectable cases.

Testing

New src/main/runtime/orca-runtime-files-terminal-artifact-swap-detection.test.ts makes the CI conditions deterministic instead of waiting on a 1 ms coin flip: it replays the first stat seen for a path on every later open, which is what Linux hands the check for free. It covers a same-size swap on the read, preview, and write paths, plus a bare-shape control asserting that the replayed stat alone does not cause a rejection.

Mutation-tested. With assertTerminalArtifactContentUnchanged neutered to a no-op, the three swap cases go red and the control stays green. Mutation reverted, tree confirmed clean, re-run green.

One pre-existing fixture was completed rather than worked around: a stubbed file handle in orca-runtime-files-terminal-link-host-translation.test.ts provided only stat and close, so it needed a read once grant creation began digesting.

  • pnpm tc — clean
  • pnpm run check:code-quality:changed — 0 findings across 40 changed files
  • pnpm test src/main — 37,407 passed
  • pnpm test mobile — 665 passed
  • pnpm test src/relay — 1,706 passed

Platforms actually exercised: macOS (full suites above) and Linux (the filesystem-level mechanism, via a Node 24 container). Not run on Windows or against a live SSH host; remote grants are unchanged by this PR.

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

AI Disclosure

Review

Residual windows, stated plainly

The digest narrows this check; it does not make it atomic. Reviewers should know exactly what is left:

  • Read and preview: closed. The bytes returned to the caller are the same in-memory buffer that was digested — there is no re-read between the check and the return, and the handle pins the inode for the whole operation.
  • Write: a real window remains. Between the final pre-rename verification and the rename() itself, the file at the target path can still be swapped, and the rename will clobber whatever is there. This is inherent to POSIX rename(), which has no "only if the target is still inode X" form. renameat2(RENAME_EXCHANGE) would help on Linux but is not exposed by Node and is not portable.
  • Artifacts above 10 MB carry a null digest and are therefore still guarded by the stat identity alone. No content can escape at that size — every read, preview, and write path rejects on size first — but the weakness is not fixed for them, only unreachable.
  • Remote/SSH grants are untouched and retain the full stat-only check, including the 1 ms weakness, on whatever filesystem the relay is running. Closing that requires a negotiated capability so an older relay is not sent a digest it cannot verify; it is deliberately out of scope here.

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • Security — strengthens an existing access check; see the residual-window section above for what is and is not closed.
  • Cross-platform — no platform-conditional code added. The defect was Linux-specific in practice (macOS showed 0/2000 collisions) but the fix is unconditional, so Windows and macOS gain the same guarantee.
  • Remote SSH — no wire change. The expectedStatIdentity format is deliberately untouched so mixed host/relay versions keep working; remote grants behave exactly as before.
  • Mobile — files.readTerminalArtifactPreview / readTerminalArtifactFile / writeTerminalArtifact are on the mobile allowlist and are the callers of this path. Full mobile suite passes; the only behavioural difference is a swapped artifact now being refused.
  • Backwards compatibility — contentDigest is a host-local, in-memory field on a grant that lives 10 minutes. Nothing is persisted and nothing is serialised.
  • Performance — one bounded read and hash per grant creation, on an explicit user action, capped at 10 MB and matching I/O the following access already does.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred) — typecheck, changed-code quality gate, and the main/mobile/relay suites run locally; pnpm build left to CI

@coderabbitai

coderabbitai Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

📝 Walkthrough

Walkthrough

The change adds nullable content-digest metadata to terminal file grants. Local artifact resolution computes a SHA-256 digest from the opened file handle for eligible files. Local reads, previews, and writes compare current content with the stored digest and reject mismatches with terminal_file_grant_stale. Writes refresh stat identity and content digest after replacement. Tests cover same-size swaps, unchanged previews, and file-handle reads.

Priority: ➖ Normal

Merge Risk: 🟡 Moderate · up to b67de

A concurrent replacement can still be overwritten during a terminal-artifact write. This integrity gap should be resolved or explicitly accepted before merge.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed and covers the change, rationale, testing, limitations, compatibility, and performance. However, the required Linked Issue is missing; it explicitly states that no tracking… Add the relevant issue reference and complete the Fixes # field. If no issue exists, create or link a tracking issue before merging.
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 10 functions across 7 files. (1 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: detecting same-size terminal artifact swaps that bypass the existing stat check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

The description is detailed and covers the change, rationale, testing, limitations, compatibility, and performance. However, the required Linked Issue is missing; it explicitly states that no tracking issue exists and leaves Fixes # blank.

Full details: Docstring Coverage

Explanation

Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 10 functions across 7 files. (1 skipped: 1 unsupported.)

✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

🟠 Major · Read local artifacts until the expected size or… · runtime-file-commands-terminal-artifact-access.ts:40-66

src/main/runtime/runtime-file-commands-terminal-artifact-access.ts:40-66
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Read local artifacts until the expected size or EOF. FileHandle.read returns the actual bytesRead and does not guarantee that one call fills the requested length. readFileHandleBufferBounded therefore can return fewer bytes than the file contains. The local grant path hashes this result in localTerminalArtifactContentDigest, and the local read and preview paths hash another result from the same helper. If both reads stop after the same unchanged prefix, a same-size changed suffix is not included in either digest, so access validation can accept the changed artifact. Loop until the expected file size or EOF, while preserving the configured byte bound.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 2c108cea-d69b-4a6b-842d-d6318e6e2b00

📥 Commits

Reviewing files that changed from the base of the PR and between ca2ae89 and 8bf40c3ae6f12b349303ea9cf965c54807025515.

📒 Files selected for processing (7)
  • src/main/runtime/orca-runtime-files-terminal-artifact-swap-detection.test.ts
  • src/main/runtime/orca-runtime-files-terminal-link-host-translation.test.ts
  • src/main/runtime/runtime-file-commands-mobile-file-list-limit.ts
  • src/main/runtime/runtime-file-commands-resolve-allowed-terminal-artifact-path.ts
  • src/main/runtime/runtime-file-commands-terminal-artifact-access.ts
  • src/main/runtime/runtime-file-commands-terminal-file-paths.ts
  • src/main/runtime/runtime-file-commands-write-terminal-artifact-file.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.

Comment on lines +99 to +102
assertTerminalArtifactContentUnchanged(
grant,
await readFileHandleBufferBounded(freshHandle, MOBILE_FILE_READ_MAX_BYTES + 1)
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

🔎 Supported by static analysis

🏁 Script executed:

sed -n '1,150p' src/main/runtime/runtime-file-commands-write-terminal-artifact-file.ts
rg -n 'writeTerminalArtifactFile|rename\(|assertTerminalArtifactContentUnchanged|lock|flock|exclusive|statIdentity' src/main/runtime

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

set -eu
printf '%s\n' '--- access helper ---'
cat -n src/main/runtime/runtime-file-commands-terminal-artifact-access.ts | sed -n '1,180p'
printf '%s\n' '--- write-path related definitions/usages ---'
rg -n -g '*.ts' 'openLocalTerminalArtifactGrant|statLocalTerminalArtifact|refreshTerminalFileGrant|requireTerminalFileGrant|writeTerminalArtifactFile|rename\(' src/main/runtime/runtime-file-commands-write-terminal-artifact-file.ts src/main/runtime/runtime-file-commands-terminal-file-paths.ts src/main/runtime/runtime-file-commands-terminal-artifact-access.ts src/main/runtime/runtime-file-commands-revoke-terminal-file-grants-for-client.ts src/main/runtime/orca-runtime-files-terminal-artifact-io.test.ts src/main/runtime/orca-runtime-files-terminal-artifact-swap-detection.test.ts src/main/runtime/orca-runtime-files-terminal-artifact-grants.test.ts
printf '%s\n' '--- focused tests ---'
cat -n src/main/runtime/orca-runtime-files-terminal-artifact-swap-detection.test.ts | sed -n '1,190p'
cat -n src/main/runtime/orca-runtime-files-terminal-artifact-io.test.ts | sed -n '150,330p'

Repository: stablyai/orca

Length of output: 24398


🏁 Script executed:

set -eu
printf '%s\n' '--- path opening helper ---'
cat -n src/main/runtime/runtime-file-commands-terminal-file-paths.ts | sed -n '115,175p'
printf '%s\n' '--- grant/stat definitions ---'
rg -n -g '*.ts' 'refreshTerminalFileGrant|statLocalTerminalArtifact|class RuntimeFileCommands|contentDigest|statIdentity' src/main/runtime | head -80
printf '%s\n' '--- relevant definitions ---'
for f in $(rg -l -g '*.ts' 'refreshTerminalFileGrant|statLocalTerminalArtifact'); do
  echo "--- $f"
  rg -n -A18 -B8 'refreshTerminalFileGrant|statLocalTerminalArtifact' "$f"
done

Repository: stablyai/orca

Length of output: 16702


Make the commit conditional on the validated artifact.

The code closes freshHandle before the pathname-based rename(tempPath, grant.absolutePath). If another local process replaces grant.absolutePath in that interval, rename can overwrite that replacement. The later stat and grant refresh then record the writer's artifact, so the replacement content is lost.

Coordinate writers with a shared lock across validation, rename, and grant refresh, or use a conditional-replace operation that rejects a changed destination.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No critical issues — a couple of minor suggestions inline.

Reviewed changes

  • Content digest pinned into local grants — TerminalFileGrant gains a host-local contentDigest, read from the same open handle as the stat, closing the same-size unlink+recreate swap the stat identity cannot see.
  • Digest enforced on every local access path — text read, binary preview, and both write verifications compare the served buffer against the granted digest; the digest is refreshed after a successful rename.
  • Deterministic regression test — freezes the first stat per path to replay the Linux collision; a control case guards against false positives.
  • Remote path untouched — the expectedStatIdentity wire format is unchanged and SSH grants stay stat-only, so mixed host/relay versions keep working.

ℹ️ Successful-write digest refresh is untested

The new grant.contentDigest = committed.contentDigest is load-bearing for any read after an in-place edit, but no test exercises a successful local writeTerminalArtifactFile: every write assertion in orca-runtime-files-terminal-artifact-io.test.ts expects a rejection (stale, ENOSPC, hard link, symlink, binary), and the new swap test also expects a throw. A single write-then-read case would pin the refresh — without it, dropping that assignment would make a post-edit read report terminal_file_grant_stale and the suite would stay green.

Technical details
# Successful-write refresh has no coverage

## Affected sites
- `src/main/runtime/runtime-file-commands-write-terminal-artifact-file.ts:107-109` — `statLocalTerminalArtifact` refreshes `statIdentity` and `contentDigest` after `rename`, untested on the success path.

## Required outcome
- A test that writes a new value through a local grant and then reads or previews the same grant, asserting the new content is served rather than `terminal_file_grant_stale`.

## Suggested approach (optional)
- Add it beside the swap cases in `orca-runtime-files-terminal-artifact-swap-detection.test.ts`; it does not need `replayFirstStatPerPath`.

ℹ️ Nitpicks

  • The read and write swap test names say "same-size", but those two fixtures change length ({"ok":true} 11 B to {"ok":ext} 10 B); only the preview case is actually same-size. Cosmetic since the stat is frozen, but the names overstate what is exercised.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

if (size > LOCAL_PREVIEWABLE_BINARY_MAX_BYTES) {
return null
}
const buffer = await readFileHandleBufferBounded(handle, LOCAL_PREVIEWABLE_BINARY_MAX_BYTES + 1)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

readFileHandleBufferBounded does Buffer.alloc(limit), so every local grant creation (and every post-write refresh) zero-fills a 10 MB buffer even for a two-byte artifact. Since size <= LOCAL_PREVIEWABLE_BINARY_MAX_BYTES is already guaranteed here, passing size + 1 reads the same bytes without the fixed 10 MB allocation.

@@ -135,10 +143,22 @@ export class RuntimeFileCommandsWithResolveAllowedTerminalArtifactPath extends R
protected async statLocalTerminalPath(
absolutePath: string
): Promise<RuntimeFileStatLike & { isDirectory: () => boolean }> {
return (await this.statLocalTerminalArtifact(absolutePath)).stats

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

statLocalTerminalPath no longer has any callers — resolveAbsoluteFileGrant now calls statLocalTerminalArtifact directly and a repo-wide search finds no other reference. Consider deleting the wrapper so this split file does not carry a dead extension point.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 5f4c5042-c00a-4a55-aae9-56560b8bae63

📥 Commits

Reviewing files that changed from the base of the PR and between 8bf40c3ae6f12b349303ea9cf965c54807025515 and b67de235e412d123853170e3e24d0d3e8ef22be2.

📒 Files selected for processing (2)
  • docs/reference/terminal-artifact-grant-integrity.md
  • src/main/runtime/runtime-file-commands-terminal-artifact-access.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/runtime/runtime-file-commands-terminal-artifact-access.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.

Comment on lines +14 to +15
A grant pins the file as `dev:ino:nlink:size:mtimeMs`. Four of those five fields
survive an unlink-and-recreate at the same path, measured on Linux (Node 24) by

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

rg -n -C 5 'terminalArtifactStatIdentity|terminalFileStatIdentity|unknown' src/main/runtime src/relay
sed -n '1,40p' docs/reference/terminal-artifact-grant-integrity.md

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- helper and direct callers ---'
rg -l --glob '*.ts' --glob '*.tsx' 'terminalArtifactStatIdentity' src | sort
printf '%s\n' '--- grant-related references ---'
rg -n --glob '*.ts' --glob '*.tsx' 'terminalArtifactStatIdentity|artifact.*grant|grant.*artifact|statIdentity' src/main src/relay | head -n 240
printf '%s\n' '--- document ---'
cat -n docs/reference/terminal-artifact-grant-integrity.md

Repository: stablyai/orca

Length of output: 13416


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- relay helper and caller ---'
cat -n src/relay/fs-handler-terminal-artifact.ts | sed -n '150,255p'
printf '%s\n' '--- grant-side identity definition and uses ---'
rg -n -C 8 'function terminalFileStatIdentity|const terminalFileStatIdentity|terminalFileStatIdentity\(' src/main/runtime
printf '%s\n' '--- grant construction ---'
cat -n src/main/runtime/runtime-file-commands-resolve-allowed-terminal-artifact-path.ts | sed -n '130,215p'
printf '%s\n' '--- access-side comparison ---'
cat -n src/main/runtime/runtime-file-commands-terminal-artifact-access.ts | sed -n '70,135p'

Repository: stablyai/orca

Length of output: 20318


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- grant construction callers ---'
rg -n -C 12 'createTerminalFileGrant\(' src/main/runtime --glob '*.ts'
printf '%s\n' '--- relay identity inputs ---'
rg -n -C 10 'expectedStatIdentity|fileStatFromHandleStats|verifiedTerminalArtifactOptions|assertTerminalArtifactStatIdentity' src/relay/fs-handler-terminal-artifact.ts
printf '%s\n' '--- runtime stat type ---'
rg -n -C 12 'interface RuntimeFileStatLike|type RuntimeFileStatLike' src/main/runtime src/main

Repository: stablyai/orca

Length of output: 15866


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- artifact resolution flow ---'
cat -n src/main/runtime/runtime-file-commands-resolve-allowed-terminal-artifact-path.ts | sed -n '1,145p'
printf '%s\n' '--- provider/stat declarations and implementations ---'
rg -n -C 8 'statLocalTerminalArtifact|statTerminal|TerminalArtifactStat|ResolvedRuntimeFileTarget|readVerifiedTerminalArtifact' src/main/runtime src/relay --glob '*.ts' | head -n 320

Repository: stablyai/orca

Length of output: 36237


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- statRemoteTerminalPath bindings ---'
rg -n -C 12 'statRemoteTerminalPath|statRemote|filesystem.*stat|provider\.stat' src/main/runtime src/main/providers src/relay --glob '*.ts'
printf '%s\n' '--- SSH filesystem provider types ---'
rg -n -C 12 'interface IFilesystemProvider|type IFilesystemProvider|stat:|stat\(' src/main/providers src/main/runtime --glob '*.ts'

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- exact remote stat references ---'
rg -n -C 6 'statRemoteTerminalPath' src/main/runtime --glob '*.ts'
printf '%s\n' '--- provider FileStat contract ---'
rg -n -C 8 'export (type|interface) FileStat|type FileStat|interface FileStat' src/main --glob '*.ts'

Repository: stablyai/orca

Length of output: 8494


Document both stat-identity fallbacks.

The SSH grant path forwards FileStat into createTerminalFileGrant, and FileStat makes dev, ino, and nlink optional. Therefore terminalFileStatIdentity can store size:mtimeMs or dev:ino:unknown:size:mtimeMs. Document both formats and their weaker guarantees. This page defines the grant identity contract, so presenting the five-field form as universal misstates reachable grants.

Comment on lines +61 to +62
form; Linux's `renameat2(RENAME_EXCHANGE)` would close it but is not portable and is
not exposed by Node. Narrowing this further means changing the commit strategy, not

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '52,68p' docs/reference/terminal-artifact-grant-integrity.md
sed -n '85,120p' src/main/runtime/runtime-file-commands-write-terminal-artifact-file.ts

Repository: stablyai/orca

Length of output: 2647


🌐 Web query:

Linux renameat2 RENAME_EXCHANGE man page semantics conditional expected inode

💡 Result:

<search_synthesis>
The renameat2 system call with the RENAME_EXCHANGE flag allows for the atomic exchange of two filesystem pathnames [1][2]. Its semantics regarding inodes and path resolution are as follows: 1. Existence Requirement: Both oldpath and newpath must exist in the filesystem for the operation to succeed [1][3]. If newpath does not exist, the operation fails with an ENOENT error [1][4]. 2. Atomic Exchange: The operation is atomic [2][5]. The names are swapped, meaning the file (or directory/symbolic link) originally at oldpath is now referred to by newpath, and the object originally at newpath is now referred to by oldpath [5]. No intermediate state is exposed to the system [2][5]. 3. Inode Handling: Because the operation is a rename-level exchange, the inodes themselves remain intact [2]. The filesystem metadata is updated to point the respective directory entries to the exchanged inodes. Since both files must exist, the exchange can occur between objects of different types (e.g., a non-empty directory can be exchanged with a symbolic link) [1][3]. 4. Restrictions: - RENAME_EXCHANGE cannot be used with RENAME_NOREPLACE or RENAME_WHITEOUT [1][5]. If these are combined in the flags argument, the call fails with an EINVAL error [1][4]. - The underlying filesystem must support the RENAME_EXCHANGE flag; if it does not, the call fails with an EINVAL error [1][3]. There is no conditional "expected inode" requirement other than the requirement that valid filesystem objects exist at both specified paths [1][5]. If the paths do not resolve to existing objects, the operation cannot proceed [1][4].
</search_synthesis>

<source_evidence>

<title>rename(2) - Linux manual page</title> https://man7.org/linux/man-pages/man2/renameat.2.html openat(2) ... renameat2() renameat2() has an additional flags argument. A renameat2() call with a zero flags argument is equivalent to renameat(). The flags argument is a bit mask consisting of zero or more of the following flags: RENAME_EXCHANGE Atomically exchange oldpath and newpath. Both pathnames must exist but may be of different types (e.g., one could be a non-empty directory and the other a symbolic link). RENAME_NOREPLACE Don&`#39`;t overwrite newpath of the rename. Return an error if newpath already exists. RENAME_NOREPLACE can&`#39`;t be employed together with RENAME_EXCHANGE. RENAME_NOREPLACE requires support from the underlying filesystem. Support for various filesystems was added as follows: • ext4 (Linux 3.15); • btrfs, tmpfs, and cifs (Linux 3.17); • xfs (Linux 4.0); • Support for many other filesystems was added in Linux 4.9, including ext2, minix, reiserfs, jfs, vfat, and bpf. RENAME_WHITEOUT (since Linux 3.18) This operation makes sense only for overlay/union filesystem implementations. Spec ... RENAME_WHITEOUT creates a "whiteout" object at ... the source of the rename at the same ... with RENAME_ ... The following additional errors can occur for renameat2(): EEXIST flags contains RENAME_NOREPLACE and newpath already exists. EINVAL An invalid flag was specified in flags. EINVAL Both RENAME_NOREPLACE and RENAME_EXCHANGE were specified in flags. EINVAL Both RENAME_WHITEOUT and RENAME_EXCHANGE were specified in flags. EINVAL The filesystem does not support one of the flags in flags. ENOENT flags contains RENAME_EXCHANGE and newpath does not exist. EPERM RENAME_WHITEOUT was specified in flags, but the caller does not have the CAP_MKNOD capability. ... ``` rename() C89, POSIX.1-2001, 4.3BSD. renameat() POSIX.1-2008. Linux 2.6.16, glibc 2.4. renameat2() Linux 3.15, glibc 2.28. glibc notes On older kernels where renameat() is unavailable, the glibc wrapper function falls back to the use of rename(). When oldpath and newpath are relative pathnames, glibc constructs pathnames based on the symbolic links in /proc/self/fd that correspond to the olddirfd and newdirfd arguments. <title>Exchanging two files [LWN.net]</title> https://lwn.net/Articles/569134/ # Exchanging two files By Jonathan Corbet October 2, 2013 The renameat() system call changes the name of the file given as an argument, possibly replacing an existing file in the process. This operation is atomic; the view of the filesystem from user space will reflect the situation before or after the renameat() call, but it will never expose an intermediate state. Things work well when one file is involved, but what happens when multiple rename operations need to be run as a single atomic operation? That is a big problem, but, thanks to a patch from Miklos Szeredi, we might have a solution to a smaller subset. The problem Miklos is trying to solve is the problem of exchanging two files — both files continue to exist, but their names have been swapped. To achieve this, he has posted a patch set adding a new renameat2() system call: ``` int renameat2(int olddir, const char *oldname, int newdir, const char *newname, unsigned int flags); ``` This system call differs from renameat() in that it has the new flags argument; if flags is zero, renameat2() behaves exactly as renameat() . If, instead, flags contains RENAME_EXCHANGE , an existing file at newname will not be deleted; instead, it will be renamed to oldname . Thus, with this flag, renameat2() can be used to atomically exchange two files. The main use case for renameat2() is to support union filesystems, where it is often desirable to atomically replace files or directories with "whiteouts" indicating that they have been deleted. One could imagine other possibilities as well; Miklos suggests atomically replacing a directory with a symbolic link as one of them. No review comments have been posted as of this writing. ... Exchanging two files Posted Jun 9, 2014 12:25 UTC (Mon) by roblucid (guest, `#48964`) [Link] Actually the new call is not just about exchanging : 0 - same as renameat() behaviour RENAME_NOREPLACE - avoids overwriting RENAME_EXCHANGE - atomic exchange So it&`#39`;s a modal renameat(2). Reply to this comment ... Reply to this ... Exchanging two files Posted Oct 4, 2013 7:42 UTC (Fri) by hansl (subscriber, `#5086`) [Link] Something like this may also be useful for Wine to emulate junctions points, which basically redirect one directory to another on the local filesystem. So you would exchange a directory with a symlink to another directory. A complication is that the original directory must be empty, and checking that with a separate call reintroduces a race condition. So renameat2 would need to gain a flag saying that it must fail if oldname is a non-emtpy directory. Reply to this comment <title>rename(2) - Linux manual page</title> https://www.man7.org/linux/man-pages/man2/renameat2.2.html openat(2) for an ... renameat2() renameat2() has an additional flags argument. A renameat2() call with a zero flags argument is equivalent to renameat(). The flags argument is a bit mask consisting of zero or more of the following flags: RENAME_EXCHANGE Atomically exchange oldpath and newpath. Both pathnames must exist but may be of different types (e.g., one could be a non-empty directory and the other a symbolic link). RENAME_NOREPLACE Don&`#39`;t overwrite newpath of the rename. Return an error if newpath already exists. RENAME_NOREPLACE can&`#39`;t be employed together with RENAME_EXCHANGE. RENAME_NOREPLACE requires support from the underlying filesystem. Support for various filesystems was added as follows: • ext4 (Linux 3.15); • btrfs, tmpfs, and cifs (Linux 3.17); • xfs (Linux 4.0); • Support for many other filesystems was added in Linux 4.9, including ext2, minix, reiserfs, jfs, vfat, and bpf. RENAME_WHITEOUT (since Linux 3.18) This operation makes sense only for overlay/union filesystem implementations. Spec ... RENAME_WHITEOUT ... "whiteout ... the rename at the ... RENAME_WHITEOUT can&`#39`;t be employed together with RENAME_EXCHANGE. ... The following additional errors can occur for renameat2(): EEXIST flags contains RENAME_NOREPLACE and newpath already exists. EINVAL An invalid flag was specified in flags. EINVAL Both RENAME_NOREPLACE and RENAME_EXCHANGE were specified in flags. EINVAL Both RENAME_WHITEOUT and RENAME_EXCHANGE were specified in flags. EINVAL The filesystem does not support one of the flags in flags. ENOENT flags contains RENAME_EXCHANGE and newpath does not exist. EPERM RENAME_WHITEOUT was specified in flags, but the caller does not have the CAP_MKNOD capability. ... ``` rename() C89, POSIX ... 1-2001, 4.3BSD. renameat() POSIX.1-2008. Linux 2.6.16, glibc 2.4. renameat2() Linux 3.15, glibc 2.28. glibc notes On older kernels where renameat() is unavailable, the glibc wrapper function falls back to the use of rename(). When oldpath and newpath are relative pathnames, glibc constructs pathnames based on the symbolic links in /proc/self/fd that correspond to the olddirfd and newdirfd arguments. <title>Result 4</title> https://python-renameat2.readthedocs.io/en/latest/renameat2.html - API documentation - Edit on GitHub --- # API documentation renameat2 is a wrapper around Linux’s renameat2 system call. The most likely reason you might want to use renameat2 is to atomically swap two files; the exchange() function is for you. If you just want to rename things with more control than os.rename(), and/or possibly do some weird overlayfs stuff, check out rename(). Finally, if you really just like the interface of renameat2 as it’s implemented in the system call, renameat2() recreates it in Python. class renameat2.Flags(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None) Bit flags accepted by the `flags` parameter of renameat2.renameat2() RENAME_EXCHANGE = 2 Atomically exchange oldpath and newpath. Both pathnames must exist but may be of different types (e.g., one could be a non-empty directory and the other a symbolic link). RENAME_EXCHANGE can’t be used in combination with RENAME_NOREPLACE or RENAME_WHITEOUT. RENAME_NOREPLACE = 1 Don’t overwrite newpath of the rename. Return an error if newpath already exists. RENAME_NOREPLACE requires support from the underlying filesystem. See the renameat(2) manpage for more information. RENAME_WHITEOUT = 4 Specifying RENAME_WHITEOUT creates a “whiteout” object at the source of the rename at the same time as performing the rename. The whole operation is atomic, so that if the rename succeeds then the whiteout will also have been created. This operation makes sense only for overlay/union filesystem implementations. See the renameat(2) man page for more information. renameat2.exchange(a: Union [Path, str], b: Union [Path, str]) → None Atomically swap two files. This is probably the main attraction of this module. After this call, the file originally referred to by the first path will be referred to by the second, and the file originally referred to by the second path will be referred to by the first. This is an atomic operation; that is to say, there is no possible intermediate state where the files could be “partially” swapped; either the call succeeds and the files are exchanged, or the call fails and the files are not exchanged. This function is implemented by passing RENAME_EXCHANGE to the system call. Parameters - a (Union [pathlib.Path, str]) – Path to a file - b (Union [pathlib.Path, str]) – Path to a file Raises OSError – if a and b cannot be swapped renameat2.rename(oldpath: Union [Path, str], newpath: Union [Path, str], replace: bool = True, whiteout: bool = False) → None Rename a file using the renameat2 system call. Parameters - oldpath (Union [pathlib.Path, str]) – Path to the file to rename - newpath (Union [pathlib.Path, str]) – Path to rename the file to - replace (bool) – If true, any existing file at newpath will be replaced. If false, any existing file at newpath will cause an error to be raised. False corresponds to passing RENAME_NOREPLACE to the system call. - whiteout (bool) – If true, a “whiteout” file will be left behind at oldpath. True corresponds to passing RENAME_WHITEOUT to the system call. Raises OSError – if the system call fails renameat2.renameat2(olddirfd: int, oldpath: str, newdirfd: int, newpath: str, flags: ~renameat2.Flags = Flags.None) → None A thin wrapper around the renameat2 C library function. Most people will likely prefer the more Pythonic interfaces provided by the rename() or exchange() wrapper functions; this one is for people who prefer their C library bindings without any sugar. Parameters - olddirfd (int) – A directory file descriptor - oldpath (str) – The name of a file in the directory represented by olddirfd - newdirfd (int) – A directory file descriptor - newpath (str) – The name of a file in the in the directory represented by newdirfd - flags (Flags) – A bit mask consisting of zero or more of `RENAME_EXCHANGE`, `RENAME_NOREPLACE`, or `RENAME_WHITEOUT`. Raises OSError – if the system call fails

Citations:


Do not claim that RENAME_EXCHANGE closes the write window.

renameat2(RENAME_EXCHANGE) atomically exchanges two existing pathnames. It does not compare the target with the verified inode. A target replacement after final verification would still be accepted by the exchange. Document that this operation does not provide a conditional rename.

Proposed wording
- Linux's `renameat2(RENAME_EXCHANGE)` would close it but is not portable and is
- not exposed by Node.
+ Linux's `renameat2(RENAME_EXCHANGE)` only swaps two names; it does not close
+ this window.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
form; Linux's `renameat2(RENAME_EXCHANGE)` would close it but is not portable and is
not exposed by Node. Narrowing this further means changing the commit strategy, not
form; Linux's `renameat2(RENAME_EXCHANGE)` only swaps two names; it does not close
this window. Narrowing this further means changing the commit strategy, not

Comment on lines +64 to +67
- **Artifacts over 10 MB fall back to stat-only.** They digest to `null`, so only the
identity guards them. Nothing leaks: every read, preview, and write path rejects on
size before reading. The weakness is unreachable, not fixed — a later cap change
could expose it.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '60,74p' docs/reference/terminal-artifact-grant-integrity.md
sed -n '40,110p' src/main/runtime/runtime-file-commands-terminal-artifact-access.ts
sed -n '70,130p' src/main/runtime/runtime-file-commands-terminal-file-paths.ts
sed -n '60,120p' src/main/runtime/runtime-file-commands-write-terminal-artifact-file.ts

Repository: stablyai/orca

Length of output: 7914


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- local helper definitions and consumers ---'
rg -n -C 4 'readFileHandleBufferBounded|readLocalTerminalArtifact(File|Preview)FromHandle|write.*TerminalArtifact|terminalArtifact' \
  src/main/runtime/runtime-file-commands-terminal-artifact-access.ts \
  src/main/runtime/runtime-file-commands-terminal-file-paths.ts \
  src/main/runtime/runtime-file-commands-write-terminal-artifact-file.ts
printf '%s\n' '--- local access file ---'
sed -n '1,280p' src/main/runtime/runtime-file-commands-terminal-artifact-access.ts
printf '%s\n' '--- local write file ---'
sed -n '1,150p' src/main/runtime/runtime-file-commands-write-terminal-artifact-file.ts
printf '%s\n' '--- relay helper and consumers ---'
sed -n '1,180p' src/relay/fs-handler-terminal-artifact.ts

Repository: stablyai/orca

Length of output: 32551


Scope the size statement by path. readBoundedFileFromHandle reads safeLimit + 1 bytes before the relay read and write paths reject oversized content. Local runtime paths check stat().size before their bounded reads, but an artifact can grow after that check. The binary preview branch checks the returned length; local file-read and write paths do not.

Proposed wording
- identity guards them. Nothing leaks: every read, preview, and write path rejects on
- size before reading. The weakness is unreachable, not fixed — a later cap change could expose it.
+ identity guards them. Relay read and write paths read up to `safeLimit + 1` bytes
+ before rejecting oversized content. Local runtime paths check `stat().size` before
+ their bounded reads, but an artifact can grow after that check. The binary preview
+ branch checks the returned length; local file-read and write paths do not.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
- **Artifacts over 10 MB fall back to stat-only.** They digest to `null`, so only the
identity guards them. Nothing leaks: every read, preview, and write path rejects on
size before reading. The weakness is unreachable, not fixed — a later cap change
could expose it.
- **Artifacts over 10 MB fall back to stat-only.** They digest to `null`, so only the
identity guards them. Relay read and write paths read up to `safeLimit + 1` bytes
before rejecting oversized content. Local runtime paths check `stat().size` before
their bounded reads, but an artifact can grow after that check. The binary preview
branch checks the returned length; local file-read and write paths do not.

Comment on lines +68 to +70
- **Remote and SSH grants are untouched.** They keep the stat-only check, with the full
1 ms weakness on whatever filesystem the relay runs. Closing it needs a negotiated
capability so an older relay is never sent a digest it cannot verify.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '14,34p' docs/reference/terminal-artifact-grant-integrity.md
sed -n '64,72p' docs/reference/terminal-artifact-grant-integrity.md
rg -n -C 3 'remote|SSH|statIdentity|terminalArtifactStatIdentity' src/main/runtime/runtime-file-commands-resolve-allowed-terminal-artifact-path.ts src/relay/fs-handler-terminal-artifact.ts

Repository: stablyai/orca

Length of output: 8965


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- relay identity and validation ---'
sed -n '150,245p' src/relay/fs-handler-terminal-artifact.ts
printf '%s\n' '--- relay digest/stat call sites ---'
rg -n -C 5 'terminalArtifactStatIdentity|contentDigest|statIdentity|validate.*Stat|digest' src/relay/fs-handler-terminal-artifact.ts src/main/runtime/runtime-file-commands-resolve-allowed-terminal-artifact-path.ts
printf '%s\n' '--- SSH grant construction path ---'
sed -n '1,215p' src/main/runtime/runtime-file-commands-resolve-allowed-terminal-artifact-path.ts

Repository: stablyai/orca

Length of output: 21486


Scope the 1 ms weakness to the measured Linux behavior.

Remote and SSH grants remain stat-only: SSH grants do not receive a contentDigest, and the relay validates only terminalArtifactStatIdentity. However, the 1 ms collision result was measured only on the tested Linux filesystem. The macOS probe reported zero collisions, so “on whatever filesystem the relay runs” overstates the evidence.

Limit the 1 ms claim to Linux filesystems with the measured behavior.

…tat cannot see

A local terminal-artifact grant pinned the file as `dev:ino:nlink:size:mtimeMs`.
On Linux every one of those can survive an unlink+recreate: ext4 reuses the
just-freed inode (measured: 100% of the time), nlink and size are unchanged for a
same-size replacement, and the mtime clock is tick-quantized to 1ms, so a swap
inside one tick produces a byte-identical identity string. The grant then served
the attacker's bytes as if nothing had changed.

Local grants now also pin a sha256 of the artifact's content, taken from the same
handle as the stat so nothing can swap the file between them, and every local
read, preview and write re-checks it before returning or committing content.

The stat identity string itself is unchanged: the relay recomputes it verbatim to
honour `expectedStatIdentity`, so its format is a wire contract. Remote grants
keep the stat-only check and are untouched.

This is also the mechanism behind the intermittent
`orca-runtime-files-terminal-artifact-io.test.ts` failure on
`rejects stale absolute terminal artifact previews before returning changed
content`: it replaces an 8-byte artifact with 8 different bytes, so whenever the
two writes shared a 1ms tick the product genuinely could not tell them apart.
…close

The digest makes the same-size swap detectable; it does not make the sequence
atomic. A reader arriving at the access module would reasonably assume otherwise,
so write down the measured limits of the stat identity, why the identity string
cannot change, and the four windows that stay open — the write path's surviving
rename() gap above all.
@nwparker
nwparker force-pushed the nwparker/terminal-artifact-swap-detection branch from b67de23 to bb86341 Compare September 18, 2026 11:24
@nwparker
nwparker merged commit 2bf538a into main Sep 19, 2026
28 checks passed
EgoSay added a commit to EgoSay/orca that referenced this pull request Sep 22, 2026
* fix(mobile): give the page its height and its long press; C1.7 device proof (OTA phase C, C1.9) (#21589)

* fix(mobile): give the Route A document the height its mounted tree measures against (OTA phase C, C1.9)

The document this builder emits carries no stylesheet, so `html`, `body` and `#root` have no
height, and every box react-native-web lays out below the mount is `flex: 1` against a parent
that measures 0. The collapse is silent in every check that existed: the entry stamps `mounted`,
the route tree commits, `innerText` holds every row, and the accessibility tree reports each one
at the offset it would have had. Nothing is painted below the header, and nothing takes a tap —
the list sits inside a scroller the collapse clipped, and a phone reads it to VoiceOver while no
row responds. Lane C1.7 found it on both an iPhone 17 Pro simulator and a Pixel 9 Pro emulator,
and the same bytes reproduce it in headless Chromium.

The fix is the reset Expo's own web template ships for a react-native-web root, emitted inline
because the shell's CSP already allows `style-src 'unsafe-inline'` for the sheet react-native-web
injects at runtime; a linked asset would paint the collapsed layout until it landed.

The render check gains the assertion that would have caught it: the root's box measured against
the viewport, and the one control this route paints with no RPC answered — the New Workspace
button, positioned against the bottom of the root, which the collapse moved to y = -72 — asked
for by `elementFromPoint` at its own centre. Laid out is not reachable, so the check is a hit
test and not another read of the DOM. Without the reset it fails `expected +0 to be 844`.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* fix(mobile): let the page have the long press WebKit was taking (OTA phase C, C1.9)

The shell's WKWebView is built with the default text interaction, so WebKit installs its selection
assistant over the page. A hold on a worktree row raises the selection loupe over the row's own
text and the touch is cancelled before the page's responder sees it, which leaves every
long-press action in the page dead on iOS while a tap works. Lane C1.7 measured it: the same
injected hold opens the row action sheet on the native list and on the page in the Android
WebView, and does nothing in the page on iOS.

It is not the document's to fix, which the device disproved one rule at a time:
`-webkit-touch-callout: none`, `-webkit-user-select: none`, and both together all left the loupe
and left the hold undelivered, and headless Chromium confirms the property computes to `none` on
the page's text, so the CSS reaches it and WebKit's own gesture wins anyway.

The cost is real and named here rather than discovered later: the page has no text selection on
iOS, so selectable `Text` — markdown, diff rows, file preview, chat — cannot be selected there
until a page-side copy affordance exists. Everything the shell already forbids is unchanged, and
Android is untouched.

No unit test: the module's Swift checks compile the seven WebKit-free logic files and never import
WebKit, so a `WKWebViewConfiguration` cannot be built in them. The device proof stands in.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* fix(mobile): make the root reset the template's bytes, not a copy with an addition

The comment said the reset is what Expo's web template ships, and `margin:0` was not in it.
`@expo/[email protected]/static/template/index.html` carries height, `overflow` and the root's flex box
and nothing else, and react-native-web emits `body{margin:0}` in the sheet it injects at runtime,
so the addition only covered the frames before that sheet landed. Nothing pinned it either:
removing it left all 60 tests green, which is the other way of saying it was never load-bearing.

Dropping it makes the string one thing with one source instead of a copy to keep in step with two.
The pins on the rest of the reset are unchanged, and so is the frame that mattered: the root still
has a definite height before the first paint, which is what the collapse needed.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* style(mobile): format the render check with the root formatter

`config/scripts` is formatted by the root oxfmt, not mobile's, and CI checks neither, so a 102-char
line I added sat over the root's `printWidth: 100` with nothing to catch it. Reflowed by
`./node_modules/.bin/oxfmt --write` from the repo root; no behaviour change.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* docs(mobile): say what the root reset shares with Expo's template, not that it is its bytes

"The bytes Expo's web template ships" is false and checkable: the template's own block is
pretty-printed with comments and trailing semicolons at 410 bytes, and this string is 112. What is
actually true, and what the next reader needs, is that it carries the same declaration set and the
same `id="expo-reset"`, minified.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): pin every rule of the root reset, not two substrings of itself

The check read the constant back against itself: `toContain(MOBILE_WEB_APP_ROOT_RESET)` plus two
substrings taken off that same constant. A rule dropped from it took the assertion with it, so
`body{overflow:hidden}`, `flex:1` and the `expo-reset` id were unpinned — and the render check
stays green without the overflow rule, so nothing else held them either.

Each rule is now a literal written here, named one at a time so a failure says which one went, and
the id is pinned beside them. Verified red-first: removing the overflow rule, the `flex:1`, or the
id each fails this test and only this test.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* fix(runtime): detect a same-size terminal artifact swap the granted stat cannot see (#21436)

* fix(runtime): detect a same-size terminal artifact swap the granted stat cannot see

A local terminal-artifact grant pinned the file as `dev:ino:nlink:size:mtimeMs`.
On Linux every one of those can survive an unlink+recreate: ext4 reuses the
just-freed inode (measured: 100% of the time), nlink and size are unchanged for a
same-size replacement, and the mtime clock is tick-quantized to 1ms, so a swap
inside one tick produces a byte-identical identity string. The grant then served
the attacker's bytes as if nothing had changed.

Local grants now also pin a sha256 of the artifact's content, taken from the same
handle as the stat so nothing can swap the file between them, and every local
read, preview and write re-checks it before returning or committing content.

The stat identity string itself is unchanged: the relay recomputes it verbatim to
honour `expectedStatIdentity`, so its format is a wire contract. Remote grants
keep the stat-only check and are untouched.

This is also the mechanism behind the intermittent
`orca-runtime-files-terminal-artifact-io.test.ts` failure on
`rejects stale absolute terminal artifact previews before returning changed
content`: it replaces an 8-byte artifact with 8 different bytes, so whenever the
two writes shared a 1ms tick the product genuinely could not tell them apart.

* docs(runtime): record what the terminal artifact grant checks do not close

The digest makes the same-size swap detectable; it does not make the sequence
atomic. A reader arriving at the access module would reasonably assume otherwise,
so write down the measured limits of the stat identity, why the identity string
cannot change, and the four windows that stay open — the write path's surviving
rename() gap above all.

* fix(remote): reassert terminal geometry after reveal (#21568)

* fix(remote): reassert terminal geometry after reveal

* test(remote): expose layout queues through fixture

* test(remote): narrow layout target assertion

* fix(omp): submit large prompts in one PTY frame (#21573)

* fix(omp): join prompt submit with large paste

* test(omp): cover joined submit timing

* ci: rerun PR checks after timing test fix

* test(omp): acknowledge joined submit activity

* fix(mobile): let the shell's page paint a file preview (OTA phase C, C3.0) (#21591)

* fix(mobile): let the shell's page paint a file preview

A file preview has one shape on the wire: the desktop answers a base64 body
and `normalizeMobileFilePreviewResult` composes `data:<mime>;base64,<content>`
for React Native Web's `Image`. Under `img-src 'self'` the browser refuses to
load it, so every image preview in the page paints nothing — reproduced in the
render check, which logged the refusal naming `img-src 'self'` before this.

`data:` is granted to images and to nothing else, so what it admits is what the
page itself composed out of a reply it already holds; `script-src 'self'` and
`connect-src 'self'` are untouched, and `blob:` is not added because nothing in
the closure needs one. Both platform pins narrow from "the header contains no
`data:`" to "`data:` appears on `img-src` and nowhere else", which is the check
that still fails if a later directive grows one.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* docs(mobile): say what the data: image case actually loads through

Round 1 is right on both counts. In react-native-web 0.21.2 the hidden <img>
the Image component renders carries `alt`, `style`, `draggable`, `ref` and
`src` and no load handlers at all — it is there for the browser's image context
menu and for `getBackgroundSize()`. The load signal comes from
`ImageLoader.load`, which is `new window.Image()` with `onload`/`onerror` on it,
so the `new Image()` in this case is the same mechanism the screen's own load
runs through rather than a stand-in for it.

And the screen maps `onImageError` to "Unable to load preview"
(`MobileFilePreviewScreen.tsx:282`); "Binary preview unavailable" is the
normalizer's `binary_file` branch, which a CSP refusal never reaches.

Comment only. No assertion moves.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* docs(mobile): state the img-src data: bound as the destination, not provenance

"admits only what the page itself built" read as a provenance guarantee, and CSP
has none to give: `data:` is matched as a scheme, so the directive admits any
`data:` image URL and the browser cannot tell one the page composed from one it
was handed. Nor is the content the page's own — the mime type and the base64
body both come from the host, and `normalizeImagePreviewResult` only checks the
mime type is a non-empty string.

The true bound is where the URL goes: it is never fetched as anything but an
image, `img-src` is the only directive admitting it, an image fetch executes
nothing (an SVG inside an `<img>` runs no script), and `script-src 'self'`,
`connect-src 'self'` and `object-src 'none'` are untouched.

Both copies reworded identically, since they are kept in step by the render
check's own policy comparison.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* Update README downloads badge

* fix(claude): stream transcript ancestry proofs

Stream transcript ancestry proofs without loading whole histories into memory.

* fix: read crash diagnostics without loading whole dumps into memory

Read crash diagnostics incrementally to avoid whole-dump memory spikes.

* ci: cache cloud workspace packages in unit tests

Include the cloud lockfile in the unit-test dependency cache key so repeated runs reuse cloud package downloads.

* fix(editor): share code-fence boundaries for Markdown links (#21574)

* fix(editor): share fence boundaries for Markdown links

* test(editor): assert highlighted lines across Monaco token spans

* perf(editor): scan fence lines without substring allocations

* fix(editor): match fence suffix whitespace rules

* ci: isolate cloud relay tests from unit shards

Run cloud relay integration tests once and exclude them from general shards, while caching the cloud lockfile inputs.

* fix(omp): acknowledge completion delivery and retire stale retries

* fix(omp): acknowledge completion delivery and retire stale retries

Co-authored-by: Tim Maximilian Lucas <[email protected]>

* test(omp): exercise completion recovery over native HTTP in platform CI

* test(omp): verify rendered status clears after completion retry

---------

Co-authored-by: Tim Maximilian Lucas <[email protected]>

* fix(omp): load task drafts through the status extension

* fix(omp): load task prefill through the status extension

* test(omp): capture installed runtime task prefill in hidden Orca

* fix(omp): resolve transcripts from active XDG and profile roots (#20633)

* fix(omp): resolve XDG session root fallback

* fix(omp): share profile-aware transcript root resolution

* test: verify actual OMP XDG transcript discovery and reading

* test(omp): satisfy reader smoke loop lint

* test(omp): resolve vault fixture paths without redundant cache

* fix(omp): refuse normalized Windows drive-relative roots

* fix: check host ownership before recovering OMP sessions (#20628)

* fix: gate startup agent recovery on host inventory

* fix: defer recovery while a live agent lacks conversation ownership

* fix(mobile): two known main bugs the RPC migration preserved (#20563)

* fix(mobile): two known main bugs the RPC migration preserved

A malformed host `error` and a null settings result both reach a property read that throws.
Both are deliberate behaviour changes; the goldens move in the follow-up commit.

`hostReplyErrorTextOrFallback` passed a truthy non-string through under a `string` annotation.
Its one caller is the in-band `git.commit` failure, and every consumer of that text is display or
prompt copy: `use-mobile-create-pr-runner` and `PrSidebarCreateEmptyState` record it as a commit
failure, `use-mobile-commit-failure-recovery` hands it to `summarizeCommitFailure`, which starts
with `raw.slice(...).replace(...)`. So no consumer needs the value, and the decision is the
fallback rather than `String(value)` — the relay handler declares
`commit(): Promise<{ success: boolean; error?: string }>`, so a non-string is a malformed reply,
and `generatedCommitMessageReader` in the same domain already reads a non-string host error as
absent. The parameter stays `unknown`, which it honestly is, and the `SAFETY` cast is gone.

`useNewWorkspaceRuntimeContext` read settings through `settingsRead`, whose reader preserves
main's `boxed!.settings` throw, so a `null` or absent result threw a TypeError out of the effect —
losing the trusted-hooks publish and the available-provider computation that follow it, not just
the settings. It now uses `optionalSettingsRead`, the operation that already reads a null or
absent result as absent settings, so the reply degrades exactly the way a reply with no `settings`
member does. Reply-side only: same method, same params, same barrier, no wire change.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): re-record the goldens the two bug fixes move

Baseline bumped to 3f71999237. Two goldens move an observation; the other 151 move only
`baseline` and `recorderSha256`, which `pilot-scenarios.json` is still digested into.

Observation moves, one claim each:

- `matrix-hostedreview.create-intent-git.commit-1`, partition `inner-false-object-error`:
  `settlements.run.value.error` and `state.outcome.error` go from `{"message":"inner refused"}` to
  `"Commit failed"`. A non-string in-band `git.commit` error is a malformed reply and now reads as
  the screen's copy, converging with `result-absent`, `result-null` and `outer-refused-no-message`,
  which already reported the fallback. The other ten partitions at this site are unchanged.
- `matrix-settings.workspace-context-settings.get-1`, partitions `result-null` and `result-absent`:
  the `unhandled-rejection` TypeError effect (`reading 'settings'`) is gone and `state.providers`
  goes from `[]` to `["github"]`. The effect no longer aborts the rest of the hook, so the
  provider computation runs; `state.settings` stays null because nothing was published, which is
  how a reply with no `settings` member already degraded. The other nine partitions are unchanged.

Header-only moves:

- 9 goldens of the `settings.workspace-context` family rename `namedDeltas` from
  `new-workspace-runtime-context-null-settings-typeerror` — the name now lies, the TypeError is
  fixed — to `new-workspace-runtime-context-null-settings-degrades-to-absent`.
- All 153 move `baseline` and `recorderSha256`. The digest covers `pilot-scenarios.json`, so the
  baseline bump and the rename re-digest every file.

No sender recording moved: both fixes are reply-side, and no golden's `sender` or `payloads` field
differs. The README paragraph that claimed the settings TypeError was preserved is updated, and
now records that the `ui.get` leg of the same hook still is.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* fix(mobile): degrade a null ui.get result the way the settings leg now does

One host answers both legs of useNewWorkspaceRuntimeContext, so fixing only
settings.get left the likelier failure in place: a null or absent ui.get result
still threw `reading 'ui'` out of the effect, skipping the provider commit.

Review follow-ups on the same files: reply() returns the literal uncast and the
stub client is FakeSession, dropping two assertions and their SAFETY disables;
the degradation cases now assert absolute state instead of comparing mounts.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): re-record the goldens the ui.get leg fix moves

Observational move, 1 golden:

- matrix-settings.workspace-context-ui.get-1: the `result-absent` and
  `result-null` partitions drop their `reading 'ui'` unhandled-rejection effect
  and their state commits `providers: ["github"]` instead of `[]`, because the
  effect no longer throws before the provider commit.

Header-only moves, 153 goldens: `baseline` to the fix commit and `recorderSha256`,
which covers `pilot-scenarios.json` and so re-digests on the delta rename.

The delta is renamed `new-workspace-runtime-context-null-settings-degrades-to-absent`
-> `new-workspace-runtime-context-null-results-degrade-to-absent` (9 goldens): it
now covers both reads, not just settings. README updated to match.

No sender recording moved: resolving the value pool across all 153 goldens shows
`sender` and `payloads` byte-identical everywhere.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* refactor(mobile): name the ui.get result shape so the changed cast carries a rationale

The inline union wrapped over four lines and tripped the changed-code casting gate
as a new assertion; a named alias keeps the cast on one line under a SAFETY note.
No behaviour change.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): repin the golden baseline to the cast-rationale commit

Header-only: `baseline` on all 153 goldens. The re-record is inert — no golden
moves observationally and no field other than `baseline` changes.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): pin the ui.get trust blank, and correct two stale acceptance comments

The goldens cannot catch a regression to `if (uiResult?.result)`: the scenario's
success reply is `{"ui":{}}`, so every partition of
matrix-settings.workspace-context-ui.get-1 records the same `trust:{}` state. The
new case answers once with real trust and again with a null result on a fresh
client, which is the only shape where skipping the blank is observable —
trustedOrcaHooks gates the setup-hook approval prompt in
use-new-workspace-create-submit.ts, so a stale value would skip it.

settingsRead's comment still claimed workspace context, which this branch moved to
optionalSettingsRead; both comments now name their real callers.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): repin the golden baseline to the trust-blank commit

The record fence rejected the previous pin ("Product sources or lockfile differ
from the pinned main baseline"), so the branch was no longer re-recordable.

Header-only: `baseline` and `recorderSha256` on all 153 goldens — the digest
covers pilot-scenarios.json, whose only edit is that baseline. The re-record is
inert: 0 goldens move observationally and no other field changes.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* docs(mobile): name the right operation per refuse-after-data probe

Three of the five probes read through optionalSettingsRead, not settingsRead:
repo metadata and resume metadata already did, and workspace context does as of
this branch. The sentence now splits them and states why the split does not move
what the probes record.

Markdown is excluded from recorderSha256, so no re-record.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): pin the recorder's unhandled-rejection capture

This branch removed the last two goldens that recorded an unhandled-rejection
effect, so nothing exercised unhandled-recording.ts any more: gutting the emit to
`void captureError(error)` leaves all 153 goldens comparing clean. The unit test
drives a detached rejection through the window and asserts both the effect and
the listener restore. README says so where it describes the capture.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): re-digest the goldens for the new recorder test

Header-only: `recorderSha256` on all 153 goldens, which covers every non-markdown
file under rpc-recording/ and so moves for the added test file. The re-record is
inert: 0 goldens move observationally and no other field changes.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): pin each RPC golden to its own scenario input, not the whole manifest (#20562)

* refactor(mobile): pin each golden to its own scenario input, not the whole manifest

`recorderSha256` covered the recorder directory plus `pilot-scenarios.json`, so every golden's
header was a function of every other family's scenarios. Adding a family for one domain re-digested
all 153 goldens and put a conflict on that line in every domain branch in flight, which serialized
the step-4 fan-out.

Split the two things it conflated. `recorderSha256` now covers the recorder directory only, with
unchanged semantics: a recorder edit still forces a full, deliberate re-record. A new
`scenarioSha256` pins the scenario input that golden was recorded from — every scenario
`runRecording` consumed for it, in order — canonicalised through `captureValue` so an
explicit-undefined param stays distinct from an absent one. `goldenRecording` takes that list
instead of just its first member.

The variants are hashed rather than the base they expand from because they are what was recorded: a
matrix site, its replayed normal result and its partition replies are all visible in them without
the derivation having to be restated. `derived-goldens.ts` is that derivation, extracted from
`family-recordings.test.ts` so the digest and the recording agree by construction — a property test
that restated how a matrix or schedule expands could agree with itself and with nothing else. It
reproduces exactly the 153 golden ids on disk, and the census the suite already ran (every family
matrixed, no stale normal-result inventory entry) now reads off its output.

`golden-header-digest.test.ts` pins the four properties:

- a new family in the manifest moves zero existing goldens' headers, and derives two of its own
- editing one field of `b1` moves exactly `b1` and its family's four matrix goldens — not the two
  other `legacy-inventory` scenarios, and not the goldens that expand from `inventory-lifecycle`
- editing a recorder file still moves every golden's `recorderSha256`, and no `scenarioSha256`
- `recorderSha256` is unchanged by the manifest's contents, and no longer reads the file at all

`GOLDEN_FORMAT_VERSION` goes to 4: a version-3 header has no `scenarioSha256`, and `compareGolden`
walks the expected header's keys, so a reader that accepted one would compare that golden's own
scenarios as though they were unpinned.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): re-record the 153 RPC goldens for the split digest

Recorder edit, so every golden needs rewriting. Recorded from the pinned baseline
`16d1ab81d3` with this branch's recorder overlaid, per the README's procedure: main has
moved past the baseline, so recording in place would have failed the product-source fence.

Three header fields moved and nothing else did:

- `recorderSha256` 6a12160a87… -> 2fda557f58…, one value across all 153 files
- `scenarioSha256` added, 153 distinct values
- `goldenFormatVersion` 3 -> 4

No observation, checkpoint, value-pool entry, `baseline`, `lockfileSha256` or `platform` changed:

    git diff -U0 -- mobile/rpc-foundation | grep -E '^[+-]' | grep -vE '^(\+\+\+|---)' \
      | grep -vcE 'recorderSha256|scenarioSha256|goldenFormatVersion'
    0

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* refactor(mobile): certify the pilot goldens from the derivation that digests them

`pilot-recordings.test.ts` restated `[scenario]` instead of consuming `pilotGoldens`, so the claim
that a golden's `scenarioSha256` is a function of the same derivation that records the file held
only for the 75 family goldens: dropping a scenario from `pilotGoldens` left the whole suite green
and put that golden outside the header oracle. The pilot suite now iterates `pilotGoldens`, and a
census fails if the derivation and the goldens directory disagree in either direction — which also
closes the pre-existing orphan-golden gap.

Also from review: pin the cross-sibling replay that hashing the generated variants buys (a matrix
golden's `normal` partition replays a sibling's recorded reply, so editing that sibling must move
it); state the real reason for the format bump, which is the diagnosis a version check gives rather
than a rejection the byte compare already made; drop the fourth property test, which re-proved what
tests 1 and 2 and `recording-runner`'s digest test already fail on; and drop a guard in
`scenarioSha256` that its only caller reaches after an identical one.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): re-record the 153 RPC goldens for the review edits

Recorder files changed, so `recorderSha256` moved. Recorded from the pinned baseline with this
branch's recorder laid over it, per the README's migration-branch procedure. That one header field
is the only line that moved in all 153 files: `scenarioSha256` and `goldenFormatVersion` are
unchanged, and no observation moved.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* docs(mobile): correct the recording suite's test count

Round-2 review: the README said 200 tests; the suite is 209 after the five
added here. Markdown is outside recorderSha256, so no golden moves.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): re-record the 153 goldens on the merged baseline

Four header fields moved and nothing else. Proven against origin/main: every
changed line in all 153 files is one of these, and the file set is unchanged.

- `recorderSha256` 70aa6f59e0 -> 58a461dbc9: this branch's recorder, and it now
  digests only the recorder directory, not the scenario manifest.
- `scenarioSha256` added, 153 distinct values over 153 goldens.
- `goldenFormatVersion` 3 -> 4 for that added field.
- `baseline` 5ec0b2698f -> e53f1557e1, the merge's repoint onto the real main
  commit. #20563's value was a branch commit the squash left unreachable, so the
  record fence's `git diff <baseline>` could not resolve it.

No checkpoint, value pool, effect or settlement byte moved, so main's recorded
behaviour is carried over intact.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* docs(mobile): account for main's added recorder test in the suite count

The merge brought in `unhandled-recording.test.ts`, one test, so the recording
suite is 210 rather than the 209 this branch documented. Markdown is excluded
from `recorderSha256`, so no golden moves.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* fix(native-chat): stop a bounded tail read from moving the chat cursor past unapplied rows (#20581)

* fix(native-chat): stop a bounded tail read from moving the chat cursor past unapplied rows

A structured chat pane could latch "Working for N" forever after the agent had
finished, showing the send arrow rather than Stop, while the sidebar and
`worktree ps` correctly read idle.

The client replica has one position (`state.cursor`) and one body. Two
operations keep those consistent: replace (both from one host snapshot) and
append (rows contiguous with the cursor). The `tail-page` branch was a third
thing: it took the cursor from the journal head, the items from a bounded page
(200 items, byte-capped), then merged retained client submissions over the
page's. Under continuous journal writes the client is always slightly behind,
so the branch ran on every window focus and on every pane re-activation. When
more than a page of rows had landed since a send, that send's user item fell
off the page, its submission was not carried, the retained `pending` survived,
and the cursor jumped past the dispatch-acceptance row. Nothing re-sends it: a
batch carries only touched items and that submission is never touched again.

Delete the third operation rather than guard it. A live subscription is now the
only thing that moves the cursor, and `subscribe({ cursor })` already replays
exactly the missed rows.

- remove the window `focus` listener and the owner/transport `refresh` contract
- skip warm hydration: a retained owner subscribes at its applied cursor
- cold hydration keeps its history read, applied as the existing `snapshot`
  (replace) event rather than `tail-page`
- delete the `tail-page` action and its reducer branch
- delete `resumeCursor` and `shouldAdvanceStructuredResumeCursor`; two cursors
  with two advancement rules were how position and body drifted apart

`older-page`/`loadOlder`, the unattached-refusal grace, generation guards and
the coalescer are unchanged. No host, wire or schema change.

Also fixes a second cost of the same branch: focus during a busy turn discarded
paged-in older items, shrinking the transcript to one bounded page mid-turn.

* fix(native-chat): preserve unavailable mixed-version session fences

* refactor(mobile): send the task workspace-creation domain through typed RpcOperations (#20568)

* test(mobile): record main's task workspace-creation RPC behaviour before migrating it

28 scenarios over nine task senders, recorded from main so the step-4 migration of
the workspace-creation half of src/tasks/ has a frozen answer to compare against.
Four senders mount as plain exported functions; three are model-chained hooks
mounted the way the settings adapters mount theirs.

The 153 existing goldens change header-only (`baseline`, `recorderSha256`): any new
scenario re-digests the recorder, and the pinned baseline had drifted from main
because the source-control migration landed. Content is byte-identical on all 153 —
verified field-by-field against HEAD.

`operation-module-loader.ts` now shares src/transport/rpc-delivery-ambiguity.ts with
mounted modules instead of evaluating a second copy. The mark is a WeakSet keyed on
the rejection object, so the copy the loader built had an empty registry and every
delivery-unknown rejection read as a definite failure inside the operation under
test — worktree.create's whole replay path was unreachable. With one registry,
`tw-create-retry-ambiguous-after-drop` records the create still pending at the
reconnect wait and abandoning at exactly 20000 ms, while the unstamped-create
scenario records the same rejection surfacing at 0 ms. No existing golden moves:
no other mounted module consumes the mark.

`task-preferences-optimistic` is re-anchored above the send rather than across it,
so migrating this file does not have to move the anchor. It still kills, and for
the same reason: the preset the screen shows no longer follows the tap.

Scenarios deliberately pin the empty-message refusals (`*-refused-empty-message`,
`*-empty-message`), because a refusal with no message falls back to the screen's
copy while a transport error with no message does not, and the two paths are easy
to collapse when a call site moves behind an acceptance policy.

Goldens: 153 -> 201, 2.9M -> 3.7M.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): format the recording manifest and re-digest the goldens

`oxfmt --check` from mobile/ collapses a one-element `sites` array in each new
scenario. The JSON value is unchanged — verified by comparing both files parsed
and key-sorted — but the manifest is inside `recorderSha256`, so all 201 goldens
carry a new digest. Every other field, header and observation alike, is
byte-identical.

Re-recorded in a separate worktree at the previous commit so the goldens stay
attributable to main's product source rather than to the migration that follows.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): separate the goldens from the migration, and re-digest

The previous commit accidentally carried the product migration alongside the
manifest format, which both broke the commit that is supposed to prove parity and
left the suite red: the digest was recorded without a comment move that a lint fix
had made inside the adapter, so all 201 goldens failed their `recorderSha256`
header.

This backs the product half straight out again — the next commit re-applies it
byte-for-byte — and re-records from the pinned baseline in a separate worktree
carrying this branch's recorder, per the procedure in the recording README. Every
field except `recorderSha256` is byte-identical to the previous commit's goldens on
all 201 files, so no observation moved in either direction. The suite is green here
with main's product source, which is what makes the next commit's "no golden
changed" claim mean something.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* refactor(mobile): send the task workspace-creation domain through typed RpcOperations

12 of src/tasks/'s 37 raw-port files now send through a declared operation instead of
the raw request port: 36 references to 0, leaving 25 files and 73 references for the
provider item/detail/mutation half. No golden moved — `git show --stat` on this commit
touches nothing under mobile/rpc-foundation/, which is the parity claim.

Twenty-two operations over twenty methods, in four modules named for what they send:
workspace create (create, PR/MR base resolution, create-time capabilities), workspace
source (SSH connect/state, agent detection, repo hooks, sparse presets, ref search),
task runtime (status, ui.get/ui.set, preflight, Linear status, settings.update) and the
Smart picker's provider reads.

Two methods carry two policies each, and both pairs are named. `status.get`: the Tasks
screen cannot hydrate without it and surfaces the host's message, while create-time
capability probing degrades to "no capabilities" and creates anyway — so one throws on
refusal and one skips. `ui.set`: two sites await it, one is fire-and-forget and never
interprets the reply at all. Both pairs share one reader, so no method has two readers.
No new acceptance policy.

worktree.create keeps its delivery-unknown contract. `request` returns the transport
promise itself, so the retry loop catches the object the transport marked; two new tests
assert `toBe(marked)` in one direction and that an unmarked rejection stays unmarked in
the other, because a mark added on the way out would replay a create the host never
received. `tw-create-retry-ambiguous-after-drop` records the create still pending at the
reconnect wait and abandoning at exactly 20000 ms.

Three sites still read the raw refusal envelope before interpreting, because the code or
the message decides the route and no acceptance policy carries either through: the create
retry needs the message for `isRetryableWorktreeCreateConflict`, and the paste lookup
needs `method_not_found` to retire the slug probe host-wide. Both are documented at the
site.

The hydration barrier keeps raw requests inside its `Promise.all`. main's group rejects as
soon as one leg rejects; `startRpcOperation` + `interpretAtRpcBarrier` would wait for the
slowest peer and let a later policy surface a different error. Interpretation stays after
the `stale` guard, where it was.

`WorkspaceCreateParams` is now `RpcSendParams<'worktree.create'>` rather than
`Record<string, unknown>`, which types the builder and the operation together; every field
the three builders already sent typechecks against the host schema unchanged.
`RpcSendArguments` now also makes params optional for a method whose params type has no
required field, because `preflight.check` is such a method and main sent it none —
requiring `{}` would have put a new object on the wire.

The Mobile Tasks source-parity hashes move for the same reason bound settings requests
moved them: the method string and the envelope read leave the screen. The signature diff
is evidence rather than a re-pin — `semantics` is a pure deletion of 22 `rpc:` call
signatures and 22 method literals with nothing added, statement/declaration/render/style
counts are unchanged, and render tokens, styles and declarations are byte-identical.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): split the task workspace adapters at the sender/hook seam

The single adapter file reached 344 lines against mobile's 300-line limit. CI lints
every file, so this is red there even though the changed-code gate does not report it.
Split along the seam the recording README already draws: exported async senders that
take a client and need no React host, and the drawer's three model-chained hooks.
No adapter body changed.

Both files are inside `recorderSha256`, so all 201 goldens carry a new digest. Every
other field is byte-identical, verified file by file. Re-recorded from the pinned
baseline in a separate worktree carrying this branch's recorder, so the goldens stay
attributable to main's product source.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* refactor(mobile): give the one-key unchecked reader a name

Four readers were the same three lines: read one property off the reply, wrap
it unchecked. `rpcUncheckedMemberReader` is the one-key sibling of the existing
`rpcUncheckedPayloadReader`, so the annotation and the closure go away at each
site. The pilot's `commitCompareEntriesReader` is converted too, so the helper
has no longhand twin left to copy from.

No behaviour change: the helper composes the same `rpcReadUnchecked` over
`rpcPayloadMember`, including the property-read exception on a null result.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): record the local arm of workspace agent detection

`preflight.detectAgents` was the one migrated operation with no recorded
coverage: the ssh adapter hardcoded `connectionId: 'ssh-1'`, so the detection
effect's ternary only ever took the remote arm and the local call site could be
repointed at another method without a golden noticing.

The adapter now takes the connectionId as a parameter and registers twice;
`tasks.workspace-ssh-local` mounts the same hook with no connection, which is
the only difference the effect branches on. Recorded at the pinned baseline
with this branch's recorder laid over it, so the new golden is main's
behaviour and the migrated code has to reproduce it — it does.

Goldens: two added (`tw-workspace-ssh-local-agents` and its reply matrix). The
other 201 changed on `recorderSha256` only, because the adapter edit moves the
recorder digest every golden pins.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): drive workspace create and the Linear list to a recorded wire

Two operations passed a policy swap unnoticed, both because no golden reached
their acceptance branch.

`worktree.create`: the create hook's fixture resolved setup to a prompt, so all
three settings.task-workspace scenarios stopped before the request and the only
consumer that hands a refusal to interpret was never recorded. The adapter now
takes the setup resolution as a parameter and registers a second family that
resolves it, so createWorkspace runs to the wire. Two scenarios: a Linear item
that creates directly, and a GitHub pull request that resolves its base first,
which also puts this hook's built params — start point, generated display name,
agent launch fields — in a golden for the first time. The existing prompt
family is untouched, so its recordings still pin that branch.

`linear.listIssues`: it appeared only in a non-base scenario, and the matrix
reads the family base, so the family had no partition for it. The base now
lists assigned issues after searching.

Goldens: five added. Five moved beyond the digest, all derived from the
smart-search base that gained the list leg. The other 198 changed on
`recorderSha256` only. Recorded at the pinned baseline with this branch's
recorder laid over it, so every new golden is main's behaviour.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): drop the unreachable unmount branches from the task adapters

Nothing dispatches `unmount` to these three adapters: the only producer is
`lifecycleSchedules`, driven from a hardcoded five-id list that names no
task-workspace family, and it pushes a `remount` right after, which these
adapters would throw on. The branch read as lifecycle coverage that was never
wired up. `dispose: hook.unmount` already tears the mount down.

Goldens re-recorded at the pinned baseline because the recorder digest moved;
`recorderSha256` is the only line that changed in all 208.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): re-record the goldens at main's post-squash baseline

Recorded from a detached checkout of e53f1557e1 (main's unmigrated
product code) with this branch's recorder laid over it, so the parity
claim stays non-circular.

- `baseline` repinned to e53f1557e1 on all 208 goldens; main pinned
  5ec0b2698f, a pre-squash branch commit not reachable from main.
- `recorderSha256` moved on all 208 because this branch's adapters are
  in the whole-manifest digest.
- 55 task-workspace goldens re-recorded at the new baseline.
- No other line in any of main's 153 goldens changed.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): re-record the goldens under #20562's per-scenario digest

Baseline repinned to 50e752fc66 and all 208 goldens recorded from that
commit's unmigrated product tree with this branch's recorder laid over it.
recorderSha256 moves on every golden because the task-workspace adapters
live in the recorder directory. scenarioSha256 does not move on any of
main's 153: the manifest only adds 31 scenarios and edits none, which is
the property #20562 was built to give.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* feat(ai-vault-search): construct the session search indexer in the scanner service behind a setting (#20516)

* feat(ai-vault-search): persist agent-session search consent and retention

Two booleans and nothing else: `enabled` and `historyDays`, off by default
because building the index reads every transcript on the machine. No `paused` --
the PR 3 indexer is immutable, so every change is close-and-construct.

The settings IPC normalizes a write like every other field and hands the change
to the index; there is no UI for it until PR 8.

* feat(ai-vault-search): hold one indexer and engine pair per host

The object that owns a host's live index and the three recipes that change it.
The indexer is immutable, so a settings change is close-and-construct, disabling
is close with no replacement, and clearing is close, remove the database,
construct. The new instance's first sweep purges a narrowed window and admits a
widened one, so neither needs a code path.

The database sits beside the scanner's parse cache, one file per host. A runtime
with no node:sqlite can hold no index at all, which the Node 18 floor on orcad
and the relay makes a real case rather than a hypothetical one.

* feat(ai-vault): let the scanner child own the session search index

The transcript reader runs in that child, so the index consumer has to as well:
one read serves both the session list and the index. Three request operations
(search, status, reconcile) and one fire-and-forget settings message carry
everything a parent needs; main never opens the database file.

The init frame becomes a factory because it is read at every spawn, so a
respawned child sees current consent rather than the first frame's. A child
holding a running index is never idle from the parent's side, so idle retirement
is suppressed while the index is on -- retiring it would stop the reconcile loop
until some later scan happened to respawn one.

Both files this lands in were already at the max-lines ceiling, so three
collaborators move to where they belong rather than being disabled around: the
invalidation deadline into the class that owns invalidations, call cancellation
and the start requeue into the call-state module, and orcad's flag parsing into
its own file.

* feat(ai-vault-search): register a search service on every host that answers

Without a registered service a host answers no-service, which means "this host
does not have the feature" rather than "the index is off". All three hosts now
answer the second thing.

The desktop forwards to the scanner child. orcad and the SSH relay daemon have
no such child -- orcad ships only the watcher and daemon entries, and the relay's
AI Vault sidecar runs the remote scanner, which publishes nothing to the
transcript channel -- so on those two the index lives in the process that would
drive its reads, gated on a runtime that has node:sqlite at all.

The relay registers with consent off and no way to turn it on: nothing carries a
setting to a remote host yet. That is the honest state, and it is still worth
registering, because it is what tells a client the difference between off and
too old.

* test(ai-vault-search): price a warm pass over five thousand transcripts

The number the reconcile interval will be revisited against, measured rather
than argued: a warm sweep stats every file under every root, a warm cycle stats
the newest N per agent, and neither reads what the index already holds. It does
not tune the interval.

* fix(ai-vault-search): answer the casting gate without assertions

main's new type-assertion rule reaches every file this branch touches. All nine
sites drop the cast rather than carry a SAFETY: rationale: the operation guard
narrows with `in`, the sqlite probe narrows the builtin it loads, the child test
keeps the discriminated reply instead of widening it, and the settings resolver
takes `unknown` -- which is what it really reads, since a persisted profile can
hold a value no version of this code wrote.

* fix(ai-vault-search): let a refreshed scan root reach the live index

The parent re-resolves scan roots before every policy push, precisely so a
WSL distro or extra Codex home that appeared since the child spawned enters
the window. The child forwarded only the settings to a live instance and used
the roots solely in its `??=` initializer, so those roots were dropped for the
child's lifetime.

The indexer stays immutable: a structurally different root set closes the pair
and constructs a new one, the same way a changed databasePath already does.
Compare via `sameSessionSearchRoots` rather than a plain JSON compare, because
nothing fixes the key order two producers write; lists are sorted too, since
the indexer walks every root and a re-enumeration that reorders is not a
change. An unchanged set still never restarts a running index.

The orcad and relay in-process hosts resolve roots once at install and never
re-apply, so they have no such seam.

* fix(ai-vault): restart the scanner child the index is holding

Three review items.

The hold keeps a child alive for the index, but only a queued call ever
started one: `pump()` skipped a hold with an empty queue, so an idle indexing
child that crashed, or an `ensureChild()` that failed at start, left indexing
stopped until an unrelated request happened to arrive. `pump()` now starts the
child the hold requires, which is also the restart callback the fault policy
already schedules, so the existing delay and circuit bound the retry exactly as
they bound a queued call's start. `updateSessionSearch` goes through the same
seam instead of its own `ensureChild` call.

A search registers no AbortController, so a cancel sent for a search id was
added to the `cancelled` set and never consumed. Nothing can reach that today
-- no caller passes a signal and the child answers in milliseconds -- so this
is only a leak of ids: consume it when the search settles.

The orcad argument doc claimed a `--`-prefixed value stays a flag. The parser
takes the next token regardless, and orcad-launch-contract.test.ts pins that,
so the doc is what was wrong. Behaviour is unchanged.

* fix(ai-vault): recover search indexing and refresh scan roots

* fix(ai-vault): defer search refresh policy reads

* fix(session-search): stabilize paging and host enablement

* fix(session-search): refresh host roots within full sweeps

* docs(session-search): clarify initial root fallback

* fix(native-chat): hide activity while awaiting input (#20496)

* fix(native-chat): hide activity while awaiting input

* fix(native-chat): keep approval turns cancellable

* test(native-chat): satisfy split PR quality gate

* fix(native-chat): catalog approval cancellation label

* fix(native-chat): include approval cancellation runtime label

* fix(codex): settle prompts when cancelled turns complete

* fix(codex): settle prompt registry fallbacks

* test(native-chat): cover pending interaction fallbacks

* test(native-chat): split prompt state coverage

* test(native-chat): keep prompt state isolated

* fix(native-chat): bound prompt turn backfill

* refactor(codex): centralize prompt registry bounds

---------

Co-authored-by: Merge Sim <sim@local>

* Update README downloads badge

* Bump mobile app.json to 0.0.50 (#20661)

* fix(native-chat): bound a dispatch reason before it reaches the journal row (#20654)

`AgentJournalSubmission.reason` was the only unbounded field written by
Orca's own code. `dispatchSafely` sets it from the adapter's raw
`error.message` and `journalDispatchRowBuilder` stored it verbatim, so a
provider error carrying a multi-megabyte body -- a stringified HTTP error
payload, say -- reached the row at whatever length the provider sent, and
stayed on disk at that size for the life of the journal.

It now goes through `boundInlineText` with the journal's existing inline
limit, the same idiom already applied to arbitrary text on the Claude and
Codex translation paths.

The bound must stay head-preserving. `dispatchRejectionWasTransportWriteFailure`
prefix-matches the value, and `dispatchRejectionReasonIsInternal` builds on
it, so a bound that kept the tail instead would stop classifying a clipped
transport failure and render raw provider text to the user as an ordinary
rejection notice. A test pins that, and clipping stays marked rather than
silent so a truncated reason is never presented as the provider's complete
explanation.

Rows written before this keep their full text, so readers can still meet an
unbounded reason.

* fix(native-chat): keep a resumed transcript pinned to its end (#20651)

* fix(native-chat): keep a resumed transcript pinned to its end

Follow state was recomputed from distance on every scroll event, and a pin writes scrollTop itself, so the browser reports that write back as a scroll event a frame later. Once a resumed session's later history pages and settling row heights had moved the end away from it, that echoed event read as the reader leaving and the pin was dropped for good, stranding them mid-transcript. Measured in Chromium: a pin followed by same-task growth delivers a scroll event reading 2000px from the bottom, indistinguishable from a reader scrolling up.

Pins now go through the virtualizer instead of writing scrollTop directly, so both parties resolve the end through the same maximum rather than holding rival definitions of it. Whether the reader left is now a question of provenance rather than distance: an offset this transcript wrote is never a departure. The end test reads live geometry, because the virtualizer's own isAtEnd subtracts a cached offset from a live maximum and this handler runs before that cache is refreshed. overflow-anchor:none stops the engine moving scrollTop under a settling row, which would otherwise look like the reader.

This does not make ownership singular. The virtualizer still writes autonomously from several paths and those writes stay unattributed; what this removes is the rival definition of the end, not the second writer.

* fix(native-chat): cancel stale end reconciliation

* fix(native-chat): attribute scroll ownership centrally

* Surface stage, unstage and discard failures with retry capability (#20423)

* fix(source-control): surface stage, unstage and discard failures

* fix(source-control): use single slot for entry failure toasts

- Consolidate entry failures to one stable slot instead of per-worktree
- Handle stale retries inline at click time rather than via a cleanup hook
- Remove retry button from discard failures to prevent destructive accidents

* test: improve type safety and mock patterns in source-control tests

- Add proper type definitions for toast options and test data instead of using `as never`
- Replace `mock.calls.at(-1)` with safer `mock.lastCall` pattern
- Create `entry()` helper to construct typed test entries
- Add explicit type annotations to mocked functions for better IDE support

* test: extract shared toast options type for source control tests

Consolidate duplicate `ToastOptions` type definitions across three test files into a single `SourceControlToastTestOptions` type, reducing duplication and improving consistency.

* fix(source-control): separate refresh failures from mutation failures

Post-mutation refresh failures are logged separately, not surfaced as toasts
(mutation already succeeded). Use preventDefault() on retry to prevent sonner's
auto-dismiss from swallowing re-raised failures. Consolidate stage/unstage into
a shared handler to reduce duplication.

* fix(source-control): only dismiss entry failures from the owning worktre

Track which worktree owns the shared entry-failure toast slot. When a mutation
completes, only dismiss the slot if the completing worktree is the one that
raised the failure — a slow retry in one worktree should not erase a failure
another worktree has since raised into the slot.

* Remove entry mutation status refresh helper

Inlined into the caller during consolidation of failure handling and
tracking in the source-control entry mutations flow.

* Simplify entry mutation refresh without wrapper

Call refreshActiveGitStatusAfterMutation directly instead of through the
refreshEntryMutationStatus helper. This ensures refresh failures propagate
directly from the callback without being caught as mutation failures.
Remove tests that validated the wrapper's error handling.

* Add copy button to code blocks (#20357)

* feat(native-chat): add copy button to code blocks

Enable users to copy code snippets directly from chat messages via a dedicated copy button on fenced code blocks. Supports language detection and integrates with markdown rendering via a `renderCodeBlock` prop.

* i18n: add English copy code button label

* refactor: use React.isValidElement type parameters for type narrowing

- Specify props types as type parameters to React.isValidElement instead
  of casting after the fact
- Allows TypeScript to narrow element.props type automatically
- Eliminates manual type assertions in extractCodeText and extractCodeFenceLanguage

* fix(source-control): prevent text wrapping in section headers and action buttons (#20046)

* fix(source-control): prevent text wrapping in section headers and action

Use flex layout constraints (flex-1, shrink-0) and text truncation instead of
wrapping to keep section labels and action buttons on a single line in the
right sidebar.

* test(source-control): add section action button alignment tests

Ensure View all button stays on single line with icon actions in
crowded section headers. Pin layout constraints (shrink-0, flex-wrap,
whitespace-nowrap) to prevent regression.

* Rely on Button base styles for action label wrapping

Remove redundant shrink-0 and whitespace-nowrap utilities from
section action buttons. These should be supplied by the Button
component's base variant, not duplicated at each usage site.

* fix(store): stop two no-op writes from re-running every selector in the app (#20641)

* fix(store): stop two no-op writes from re-running every selector in the app

zustand bails out of a `set` only when `Object.is(next, state)`. Two updaters that
mean "nothing changed" hand it a fresh reference instead:

- `setWorkspacePortScanRefreshing` wrote unconditionally — the one action in its
  file that did; its four siblings all early-return `state`.
- `applyGitHubPRRefreshEvent` ended its no-op branch with `: {}`, and
  `Object.assign({}, state, {})` reproduces every field unchanged while still
  notifying. ~20 sibling sites in the same store already use `return state`.

Both rebuild the root and wake every subscribed selector (~2.2k per the listener
census). Renders are unaffected — the selection is unchanged — so the cost is
wasted selector evaluation, not commit pressure. The resulting state looks
identical either way, which is why it goes unnoticed; both tests therefore count
subscriber notifications rather than asserting state.

* test(store): use checked initial state in notification regression

---------

Co-authored-by: m4air <[email protected]>
Co-authored-by: Neil <[email protected]>

* fix(ai-vault): bound streamed remote JSONL records (#20700)

* fix(ci): stop hourly versions dropping below a tagged or already-shipped build (#20699)

* fix(ci): stop hourly versions dropping below a tagged or already-shipped build

Hourly/daily/adhoc based their X.Y.Z on GitHub releases, not git tags. When
v1.4.202 was tagged and then its GitHub release vanished, the next hourlies
shipped as 1.4.202-hourly — below both stable 1.4.202 and the 1.4.203-hourly
builds already installed, so electron-updater stopped offering updates.

Read main's v* tags and already-published channel tags instead.

* docs(ci): record that 1.4.202's release was unpublished for a bug

The leftover tag is what hourly must still honor; this was not a failed cut.

* fix(store): preserve state identity for no-op updater branches (#20703)

* fix(codex): settle a structured send on admission, and stop minting a colliding identity (#20138)

* fix(codex): settle a structured send on admission, and stop minting a colliding identity

Two sends could be written into the journal under one durable identity.

Codex coalesces a mid-turn `turn/start` into the running turn rather than
refusing it -- measured against real `codex app-server` builds 0.147.0,
0.150.1 and 0.153.4, none of which refuse and none of which fire a second
`turn/started`. The dispatch path read the turn id from the turn/start
response and stamped every accepted send `ordinal: 0`. Since a coalesced
send gets the running turn's id back, two submissions persisted the same
`providerItemId`. That string is durable, and it is the key a restore uses
to match a submission against provider history, so the second message's real
history row matched nothing and rendered as an extra bubble on replay.

On 0.147.0 it is worse than a collision: the coalesced response returns a
turn id that never starts and never completes, so the persisted key named a
turn absent from history and NEITHER message could match.

Identity is now minted from the echoed user message at `identityFor` -- the
single point that mints the journal row's own identity -- so the settled key
is by construction the one replay computes, rather than a parallel
calculation that can drift.

Dispatch returns `admitted` when the transport write completes; identity
settles on the echo through a channel that did not previously exist for
Codex. Waiters are keyed by client message id instead of being shifted off
the front of an array by arrival order, and they are cleared on session
close and child exit -- previously a timeout was the only thing that ever
ended one.

`TURN_ID_WAIT_MS` is deleted. It was never reachable on any build measured:
`readCodexTurnId` returns non-null on all three, so the 10s wait never
fired. The comment justifying it claimed older builds acknowledge before the
id exists, which no tested build does.

Three comments asserting Codex answers a mid-turn send with `turn already
running` are corrected. Their only backing was a test fixture inventing that
error string. The correction is factual only -- every changed line in
`src/main/runtime/orchestration/` is a comment, and mid-turn delivery is
still refused for both providers. Whether that policy is right is a separate
question; it was resting on a false premise.

Known gap, stated rather than implied: this prevents new collisions and does
not repair journals already written with a colliding or phantom key. Those
conversations keep duplicating on restore. Repairing them means re-matching
persisted submissions against provider history and rewriting
`providerItemId` -- which is what `journal-submission-reconciler.ts` is
written for, and it still has no production caller.

* test(codex): drop the synchronous-accept contract and the colliding `:0` from the integration fakes

Three tests in the structured-session integration suites encoded the dispatch
contract this branch replaces, and two of them pinned the defect it fixes.

They asserted `agentSession.send` answers `dispatchState: 'accepted'` carrying
`providerItemId: codex:<thread>:<turn>:0` at send time. That ordinal was never
observed; it was stamped on every accepted send, which is exactly the collision
this branch removes -- a send coalesced into a running turn is answered with the
running turn's id, so two submissions persisted one durable key.

The visible failure was a 30s timeout rather than a failed assertion. The fake
client advertised no `agent-session.pending-send-result.v1`, and without it the
host holds the reply until the send settles: a shim for clients too old to
render a pending bubble. The fake provider then echoed the user message with no
`clientId`, so nothing could correlate that echo back to the submission, and the
wait ran to its own 30s ceiling. Real Codex sends `clientId` on that echo, and
the fake now does too, which is what makes it a model of the provider rather
than a sketch of one.

The identity assertion is kept rather than dropped. Each send now asserts
`pending` with no identity at admission, then asserts the submission settles
`accepted` at `codex:<thread>:<turn>:0` once the echo lands. Same ordinal, but
earned from `identityFor` on the echo -- the key a replay recomputes -- instead
of guessed from the turn/start response. Ablated: removing `clientId` from the
two echoes leaves both submissions `pending` and fails both assertions, so the
assertion is load-bearing and not satisfied by something incidental.

Both suites' client fixtures now advertise the capability set the desktop
renderer sends in `src/main/ipc/runtime.ts`, which is what these suites mean by
a client. The older-client settlement wait keeps its own coverage in
`src/main/runtime/rpc/methods/structured-agent-session.test.ts`.

`structured-agent-session-runtime-exit.test.ts` asserts `pending` for the same
reason; it drives the host directly, so it never took the compatibility path,
and what proves delivery there is still the turn the reacquired provider starts.

The replay suite's "without dispatching it twice" property is untouched: one
`turn/start` call, one replayed ledger row.

* fix(codex): preserve unsettled dispatch correlations

* test(codex): type the dispatch fixtures instead of asserting over them

main's new casting gate (#20367 base) flags type assertions on changed
lines. Replace them with checked types: the recording sink already
satisfies its interface, both CodexSession fixtures are now annotated and
carry real collaborators, the settlement assertion compares whole
identities, and the integration helper reads submissions through the
host…
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant