Skip to content

fix(orca): P5 fallback - resolve parent via git-common-dir or basename - #548

Closed
Andresito11-cpu wants to merge 55 commits into
kunchenguid:mainfrom
Andresito11-cpu:fix/orca-p5-fallback
Closed

Andresito11-cpu wants to merge 55 commits into
kunchenguid:mainfrom
Andresito11-cpu:fix/orca-p5-fallback

Conversation

@Andresito11-cpu

Copy link
Copy Markdown

When the orca backend passes --parent-path that doesn't exactly match an orca-registered cwd, the previous P5 register returned rc=4 (no parent session) and the worktree silently fell under orca's 'Hiding N discovered worktree' gate.

Most of the time, the parent's orca-registered path differs from the --parent-path arg only because the captain and firstmate each have a sibling clone (captain's ~/Desktop/falkordb-stak and firstmate's projects/falkordb-stak), and the .git directory underneath is the same.

Add a three-step fallback chain in resolve_parent_session_uuid:

  1. Exact cwd match (trailing-slash + realpath tolerant)
  2. Git-common-dir match: realpath --git-common-dir of parent vs each fmod-listed session's cwd. Sibling clones share this.
  3. Basename match: last-ditch when the repo's name is unique enough.

The script-level exit-4 error and the spawn-time 'warn: orca UI sidebar registration failed' message are unchanged so the captain can still diagnose the rare case where all three fail.

Follows #546 + the squashed #3.

Tests (all green): 16 assertions in tests/fm-mod-orca-ui.test.sh.

Andresito11-cpu and others added 30 commits July 11, 2026 10:20
…ia bin/fmod

The previous bin/backends/orca.sh wrapped the orca CLI, which could not
run while the orca GUI held the single-instance lock. Replace the CLI
calls with bin/fmod, a small firstmate-owned Python client over the
daemon's Unix-socket NDJSON protocol (per orca's src/main/daemon/types.ts
and daemon-server.ts). The adapter contract is unchanged: fm-spawn.sh,
fm-peek.sh, fm-teardown.sh, and the watcher see the same function
signatures.

Orca still owns the task worktree, acquired through 'git worktree add' on
a sibling dir of the project (the daemon has no worktree primitive).
Session id is fm-<task-name>; .fm-orca-session in the worktree stores it
so remove_worktree can find the terminal.

tests/fm-backend-orca.test.sh replaces the fake-orca-CLI fixture with a
fake-fmod one and verifies every primitive plus the dispatcher routing.
…xtures

- composer_state now accepts opencode's left-only ┃ border with the
  ╹▀▀▀... bottom underline, picks the bordered row that is NOT
  immediately followed by the underline (which is the footer 'Build
  · ...' line), and treats 'Ask anything...' as the idle placeholder.
- Updated tests/fm-backend-orca.test.sh fixtures to use the fm-<id>
  naming consistently (mirrors fm-spawn's W=fm-$ID) and added 3
  opencode composer-state tests covering pending, empty placeholder,
  and underline-skip behavior.
- Marked tests/fmod.test.sh SKIPPED with a note explaining the
  in-process fake-daemon races; integration coverage remains via the
  adapter tests and the live daemon smoke.
The shipped bin scripts were 0644 (read-only); ad-hoc invocation worked
through bash's PATH lookup but a shebang exec did not. Make every bin
script executable so future spawn flows do not depend on a shell wrapper.
fm_backend_orca_create_terminal and fm_backend_orca_worktree_create both
compared fmod get-cwd against the caller-supplied path with strict
equality. fmod get-cwd normalizes the path with a trailing slash; the
caller-supplied path never has one. Every fresh orca session therefore
failed the cwd check and aborted the spawn with a misleading
'attached at X/, expected X' error.

Strip both sides with ${var%/} before comparing so a sane create is not
misclassified as a cwd mismatch. Discovered while running the real-orca
smoke suite on a Linux AppImage install (daemon protocol v21).
pi 0.80's project-trust prompt ('Trust project folder?') blocks every
unattended spawn. claude has --dangerously-skip-permissions, codex has
--dangerously-bypass-approvals-and-sandbox, grok has --always-approve;
pi now has the targeted equivalent: -a / --approve ('Trust project-local
files for this run').

Both ship and secondmate templates now emit pi --approve; the external
-e <pi-ext> flag stays so the per-task turn-end extension lives outside
the worktree and never needs trust re-acquisition.

General firstmate bug, not orca-specific; candidate for upstream PR.
The orca daemon's hello handshake is strict on version: a hello whose
'version' does not match the daemon's own is rejected with 'Protocol
version mismatch'. When the installed AppImage daemon is newer than the
source tree this script was checked out from (a normal lag — the
AppImage ships ahead of the orca GitHub releases), the hardcoded
PROTOCOL_VERSION constant goes stale and every fmod call fails.

Add discover_protocol_version():
  1. Try the hardcoded PROTOCOL_VERSION first.
  2. If FMOD_PROTOCOL_VERSION env is set, pin to that (no discovery).
  3. Otherwise scan ~/.config/orca/daemon/ for any daemon-v*.sock file
     and try each as a hello candidate.
  4. Cache the discovered version for the rest of the process lifetime.

Wire the discovery into DaemonClient.connect():
  - FileNotFoundError on the hardcoded token path triggers discovery.
  - DaemonHelloError with 'Protocol version mismatch' or 'hello rejected'
    triggers a one-shot retry with the discovered version.

daemon_paths() also honors FMOD_PROTOCOL_VERSION so the env pin takes
effect on the FIRST call, not only after a failed connect.

Also update _hello() to use the discovered version instead of the
hardcoded constant, so hello after discovery uses the right version.
The orca GUI process is a single-instance AppImage; on Linux without a
desktop session, or after any crash, the daemon can die while
orca-runtime.json still reads runtimeState: stale_bootstrap. Every
spawn then refuses with the runtime check.

fm-supervise-orca.sh is the per-RUNTIME supervision loop, deliberately
separate from fm-watch.sh (per-TASK supervision). They have different
cadences, different escalation rules, and different restart semantics;
a flaky orca daemon should never widen into per-task noise.

Commands:
  start    background the supervisor (writes pid to state/.orca-supervisor.pid)
  stop     kill a running supervisor (idempotent)
  status   print supervisor liveness and daemon reachability
  once     one health check, exit 0 if reachable (no relaunch); for use
           from fm-bootstrap.sh so a single session start can recover
  --follow foreground loop (harness-tracked background)

Recovery: on dead daemon, reap any leftover orca-ide / orca.AppImage
processes owned by the current user, clear the single-instance lock and
per-version socket/token/pid files, unmount stale /tmp/.mount_orca.*
FUSE mounts, and relaunch via 'setsid --fork orca'. Env knobs:
FM_ORCA_CHECK_INTERVAL (default 30), FM_ORCA_BIN (default 'which orca'),
FM_ORCA_FMOD (default bin/fmod next to this script).
When config/backend or FM_BACKEND selects orca, fm-bootstrap.sh now:
  1. Probes the daemon via bin/fm-supervise-orca.sh once.
  2. Reports 'ORCA: daemon reachable' on success.
  3. In a mutating bootstrap, on probe failure, calls 'start' to relaunch
     and reports 'ORCA: daemon recovered' on success.
  4. In FM_BOOTSTRAP_DETECT_ONLY=1 (read-only / secondmate session), reports
     'ORCA: daemon unreachable' and leaves recovery to the lock holder.

Quiet for tmux / herdr / zellij / cmux — the probe never runs unless orca
is the active or explicit backend, so non-orca fleets see no extra noise.

If bin/fm-supervise-orca.sh itself is missing, reports MISSING so the
operator knows the supervisor script was lost (not just that orca is down).
…nux smoke

- Add 'Daemon protocol' section: explains why firstmate talks to the
  daemon directly via bin/fmod (the orca CLI is blocked by the GUI's
  single-instance lock) and documents the hello-version strictness plus
  the FMOD_PROTOCOL_VERSION env pin.
- Add 'Daemon supervision' section: documents bin/fm-supervise-orca.sh,
  the per-runtime vs per-task supervision split, and the bootstrap
  diagnostic integration.
- Add 'Live-Linux smoke' subsection to 'Verification': real smoke runs
  against the captain's AppImage install (daemon protocol v21), including
  the supervisor-recovery timing (~3s) and the two general bugs found
  (cwd trailing slash + pi --approve) that are candidates for upstream
  PRs.
Orca-backend operator procedures, internal to firstmate. Loads on
the trigger phrases documented in the skill description; never loaded
for tmux / herdr / zellij / cmux backends.

Covers: daemon liveness commands, direct fmod access, recovery
recipes for ORCA: daemon unreachable, protocol-version mismatch,
spawn refusal, pi trust-gate, wedged orca crewmates, cwd trailing-slash
false-positive, and edge cases (CLI hangs, two daemons, FUSE mount
survival, XDG_CONFIG_HOME).

Pairs with the operational change in docs/orca-backend.md.
first mate and others added 24 commits July 13, 2026 09:25
fm-use-orca.sh: one-call setup for the orca backend.
  1. Verify prerequisites (orca binary, node, setsid).
  2. Write config/backend=orca; if config/crew-harness is absent, write pi.
  3. Start bin/fm-supervise-orca.sh so a dead daemon self-heals.
  4. Install XDG autostart entry so the supervisor survives logout.
  5. Run a trivial orca+pi spawn as end-to-end smoke; teardown after.
  6. Print a daily-driver-ready summary with the next-action hints.

Subcommands: start (default; runs all), status, stop, restart, autostart
[install|remove], smoke.

fm-use-tmux.sh: symmetric switch back to the tmux backend.
  1. Stop the orca supervisor (idempotent).
  2. Remove the orca autostart entry (idempotent).
  3. Verify tmux is on PATH AND we are inside a tmux session.
  4. Clear config/backend (so tmux auto-detection wins; absent means tmux).
  5. Run a trivial tmux+pi smoke (optional via --no-smoke).

Subcommands: start (default), status, stop, restart.

Both scripts are idempotent and safe to re-run. They print a per-step
status with check marks so the captain can act without re-reading logs.
These three new scripts round out the orca daily-driver setup:
- supervisor + fmod client surface for the operator;
- symmetric one-call switch between orca and tmux backends.

Adds three rows to the bin/ toolbelt inventory in docs/scripts.md.
fm-use-orca.sh / fm-use-tmux.sh are the daily-driver entry points; the
recovery-recipe block now points at 'bin/fm-use-orca.sh start' as the
canonical re-setup path so a stranded captain does not have to remember
whether to run 'start' on the supervisor or the full setup script.
- bin/fm-use-orca.sh and bin/fm-use-tmux.sh now honor FM_HOME, FM_ROOT_OVERRIDE,
  FM_CONFIG_OVERRIDE, FM_STATE_OVERRIDE, and XDG_CONFIG_HOME (for autostart).
  Matches the firstmate standard pattern from fm-bootstrap.sh and
  fm-session-start.sh. Without this, the scripts always wrote to the repo
  they live in, ignoring FM_HOME - which broke any caller that expected
  isolated secondmate homes or scratch FM_HOME trees.
- bin/fm-use-orca.sh 'start' now treats supervisor exit 3 (already live) as
  success so a re-run reports cleanly instead of failing the step.
- tests/fm-use-orca.test.sh: 5 new tests covering:
  - status command is read-only and does not mutate state
  - status command does not leak daemon socket paths or tokens
  - start writes config/backend = orca under FM_HOME without leaking into
    the real FM_ROOT
  - autostart install + idempotent re-install + remove
  - stop is idempotent when no supervisor is running
…ifier

Daily-driver health check the captain can run before any orca-backed
session, or after a daemon or supervisor change, to confirm the
pipeline is healthy. Single command, single exit code, single PASS/FAIL
line so a tail -1 / && / || can read the verdict.

Checks (15):
  1. orca binary on PATH
  2. node on PATH (orca adapter JSON parser)
  3. setsid available (supervisor needs it for daemon relaunch)
  4. config/backend = orca (or --expected-backend override)
  5. config/crew-harness set
  6. orca daemon reachable (via bin/fmod ping)
  7. PROTOCOL_VERSION match (no Protocol version mismatch on the wire)
  8. supervisor running (live pid in state/.orca-supervisor.pid)
  9. supervisor logs recent (<600s) and error-free
 10. fmod list (sanity: daemon actually owns live sessions)
 11. spawn -> turn-end -> teardown full end-to-end (120s bound)
 12-14. unit tests: fm-backend-orca, fm-supervise-orca, fm-use-orca
 15. fm-bootstrap.sh reports ORCA: daemon reachable

Flags:
  --no-unit             skip the shell unit-test suites
  --no-spawn            skip the live end-to-end spawn check
  --expected-backend X  fail check 4 if config/backend is not X
  --json                emit JSON for programmatic consumption

Verified clean on a Linux AppImage install: 15/15 PASS.
- docs/scripts.md: new row in the bin/ toolbelt inventory.
- .agents/skills/firstmate-orca/SKILL.md: new 'Health check' block under
  the operator reference, listing the four invocations a captain reaches
  for: full suite, --json, --no-spawn, --no-unit, --expected-backend X.
The orca backend previously refused --secondmate spawns with
'secondmate-home semantics need a separate design'. This commit
implements the design:

Design: each secondmate = one orca daemon session whose id is
deterministic (fm-secondmate-<basename-of-home>). The secondmate
home is a pre-existing git worktree of the primary repo, registered
via bin/fm-home-seed.sh. The orca adapter does not call worktree_create
for secondmates (it must not create a worktree of a worktree); it uses
fm_backend_orca_create_terminal directly with the home path as cwd.
A recovery respawn with the same id reattaches to the existing daemon
session.

fm-spawn changes:
  - removed the orca+secondmate refusal (the 'needs design' note)
  - orca case block branches on KIND: ship/scout -> existing worktree
    flow; secondmate -> create_terminal at the home path
  - ORCA_WORKTREE_ID for secondmates is the home path itself
  - abort cleanup skips worktree removal for secondmates (the home
    is persistent state)

fm-teardown changes:
  - for orca+secondmate, kill the orca terminal and clean spawn state
    but DO NOT call remove_firstmate_home (which assumes a treehouse
    lease). The home and data/secondmates.md registry entry are
    preserved so a re-spawn can re-create the orca session without
    re-seeding.
  - for orca+secondmate, capture T_ORCA from meta (terminal id) so the
    final kill below can close it.

backends/orca changes:
  - fm_backend_orca_create_terminal now prints the session id on stdout
    so $(...) capture in fm-spawn works. Previously the function only
    created and verified, returning empty (a real bug found when wiring
    up the secondmate path - this was broken in the original commit
    and not caught by the existing tests).
  - on cwd mismatch, kill the new session before returning failure
    (best-effort; matches the existing worktree_create pattern).

Tests added in tests/fm-backend-orca.test.sh:
  - fm_backend_orca_create_terminal returns the session id on stdout
    for $(...) capture (the contract the secondmate path depends on)
  - fm-spawn.sh no longer refuses orca+secondmate

Docs and skill updated:
  - docs/orca-backend.md: 'Limitations' no longer lists secondmate
    refusal; new 'Secondmates' section documents the design, the
    deterministic id, the recovery reattach, and the teardown
    semantics
  - .agents/skills/firstmate-orca/SKILL.md: 'one screen' section now
    notes the secondmate support; new 'Secondmate-specific recipes'
    block with the spawn + teardown procedure; see-also updated

Verified end-to-end on a Linux AppImage install (daemon protocol v21):
a seeded secondmate home with charter + project spawns on orca, pi
loads the charter, processes it, fires the turn-end extension; a
teardown kills the orca terminal and leaves the home + registry
intact; a re-spawn reattaches to the same daemon session.
…shell issue

The pipeline's no-mistakes fixes added a set -u line and rewrote the smoke
section to reference $STATE inside a $(...) subshell, but the script's
top-level STATE= assignment was dropped. With set -u the rewrite hit
'unbound variable' on line 221.

Restore STATE='${FM_STATE_OVERRIDE:-$FM_HOME/state}' at the top of
fm-use-orca.sh, alongside CONFIG/DATA/PROJECTS, so the smoke function's
STATE references resolve under set -u.

In fm-use-tmux.sh, the smoke function had a similar subshell issue
(state_dir under set -u) - use ${FM_STATE_OVERRIDE:-$STATE} so the
expanded value never collapses to an empty subshell-visible variable.
feat(orca): daemon-direct backend with supervision, fmod resilience, and Linux smoke
…-orca-ui (#3)

* fix(orca): P5 - register spawned worktrees in orca sidebar via fm-mod-orca-ui

When the orca backend spawns a crewmate, fmod createOrAttach + git
worktree add creates a worktree whose git-common-dir differs from the
orca-registered repo path (firstmate's projects/<repo>/ copy vs the
captain's Desktop/<repo>/ copy are sibling clones). Orca's GUI gates
external-worktree visibility with externalWorktreeVisibility (default
'hide'), so the new worktree silently vanishes from the sidebar
('Hiding 1 discovered worktree'), hiding the dispatched crewmate.

Add bin/fm-mod-orca-ui.sh - an atomic writer for the worktreeMeta map
in ~/.config/orca/profiles/local-default/orca-data.json. Subcommands:
register (parent_path OR parent_key optional, falls back to fmod
list for parent discovery), unregister (by key), unregister-path (by
absolute path), list, show. Uses mkdir-lock for concurrent-caller
safety and caller-minted tmp filenames (no chance of two spawns
clobbering each other's atomic_write step).

Wire register into fm_backend_orca_worktree_create and unregister into
fm_backend_orca_remove_worktree in bin/backends/orca.sh. Both run
best-effort: registration is independent of the spawn succeeding, and
a daemon shutdown may clobber orca-data.json (known limitation; tracked
as future re-registration sweep work).

Other fixups bundled:

* fm_backend_orca_create_terminal uses readlink -f on cwd so symlinked
  FM_HOME still matches the daemon's realpath.
* fm-spawn.sh excludes .fm-orca-ui-key alongside .fm-orca-session.
* fm-teardown.sh dirty-check regex now also excludes .fm-orca-ui-key
  with an explicit comment that teardown must NOT delete the file
  (the orca backend owns it).
* fm-secondmate-status.sh exact-matches fm-secondmate-<id>-<sha256-8>
  against fmod list; previously startswith() matched nested ids.
* fm-secondmate-status.sh python heredoc no longer interpolates shell
  vars into the python source.
* fm-use-orca.sh dead FM_STATE_OVERRIDE assignment removed.
* fm-secondmate-retire.sh dead KILLED_ORCA_SIDS removed.
* fm-supervise-orca.sh per-instance log paths under $STATE (multi-home
  safe), legacy /tmp path fallback for the test suite.
* fm-supervise-orca.sh daemon_pong predicate hardened with isinstance
  guard.
* tests/fm-mod-orca-ui.test.sh - 16 assertions including concurrent
  register + atomic_write leaves no orphan.
* tests/fm-backend-orca.test.sh - 2 new realpath tolerance tests.
* tests/fm-secondmate-status.test.sh - exact-match stub aligned with the
  canonical id formula.
* .gitignore - remove quoted 'Skill bundle/' entry; add .pi/.

Validated:
* fm-mod-orca-ui.test.sh: 16/16 pass
* fm-backend-orca.test.sh: 51/51 pass
* fm-supervise-orca.test.sh: 6/6 pass
* fm-use-orca.test.sh: 20/20 pass
* fm-secondmate-status.test.sh: 33/33 pass
* fm-secondmate-retire.test.sh: 106/106 pass
* fm-orca-test-suite.sh --no-spawn: 16/16 pass

* fix(perms): mark newly copied secondmate scripts executable

---------

Co-authored-by: Captain <capt@firstmate.local>
When the orca backend passes --parent-path that doesn't exactly match
an orca-registered cwd, the previous P5 register returned rc=4 (no
parent session) and the worktree silently fell under orca's
'Hiding N discovered worktree' gate.

Most of the time, the parent's orca-registered path differs from the
parent_path arg only because the captain and firstmate each have a
sibling clone (captain's ~/Desktop/falkordb-stak and firstmate's
projects/falkordb-stak), and the .git directory underneath is the same.

Add a three-step fallback chain in resolve_parent_session_uuid:
  1. Exact cwd match (trailing-slash + realpath tolerant)
  2. Git-common-dir match: realpath --git-common-dir of parent vs
     each fmod-listed session's cwd. Sibling clones share this.
  3. Basename match: last-ditch when the repo's name is unique enough.

The script-level exit-4 error and the spawn-time 'warn: orca UI sidebar
registration failed' message are unchanged so the captain can still
diagnose the rare case where all three fail.
@Andresito11-cpu
Andresito11-cpu deleted the fix/orca-p5-fallback branch July 14, 2026 07:59
@ami230392

Copy link
Copy Markdown

Review — PR 548 (issue #527): "declare the gap — a Portal-listed file we did not read is never silent"

Reviewed at 1a3710f (merge-base b228e20), in a disposable worktree. Read-only review; no push, no PR.
Mandate: attack the detection path (can a listed-but-unread file still slip through silently?), the migration, and every return arm's test.

Verdict: approve with follow-ups. The core mechanism is right and the receipt is honest. I found one real residual silent false negative (F1, time-displaced, arguably #528's), one contract hole worth closing in this PR (F2), and one migration-level fence in the wrong layer (F3). None of them makes this PR worse than main; all three matter because #529 flips eligibility on top of this guarantee.


What I did

Command Result
git fetch origin pull/548/head && git checkout FETCH_HEAD at 1a3710f
pnpm --filter worker test read-tender (fresh checkout, stale shared/dist) 13 failed / 27 passed
pnpm --filter @tendersathi/shared build then re-run 40 passed (3 files) — matches the receipt
pnpm --filter web test coverage-gap-notice 7 passed — matches the receipt
red-before-green: git checkout origin/main -- apps/worker/src/documents/readTender.ts + pnpm --filter worker test read-tender-coverage 6 failed / 6 passed — reproduces the receipt exactly
6 adversarial probes written as a scratch vitest file against the real entry point + fakes (deleted after) see below

The first line is not a defect in this PR — it is the documented repo gotcha (root AGENTS.md: "CI and fresh clones must build @tendersathi/shared first"). Recording it because a reviewer on a clean checkout will hit it and mistake it for red CI.

Two parallel sub-agents ran the repo's standard two-axis review (Standards / Spec). Standards: no hard violations — hi.json/en.json are 1:1 on the three new keys, the fetch-loop catch logs route/tender/filename/error-class before degrading, safePortalUrl gates href to http(s), apps/worker/AGENTS.md's Last verified line is updated. Spec: all six acceptance criteria and all four Seam-1 tests in #527 are satisfied, with the record-bounding constants (MAX_DECLARED_*) being the only work beyond #527's literal text — justified by root AGENTS.md's validate-size-not-only-shape rule and disclosed in the PR body.

One claim from the spec agent I checked and rejected: it reported the coverageKnown: false branch as untested at the worker seam. It is tested — apps/worker/test/read-tender.test.ts:438 ("F5: never serves a row that recorded no coverage as complete coverage") seeds exactly that StoredRead through the store and asserts coverage_incomplete.

The detection path, attacked

Enumerated every way a listed file can leave performRead. Within one read the loop is airtight: listed is built from listing.files (readTender.ts:275), fetchable is its first 3, every entry either pushes to coveredFiles (:300) or to failed (:302), and everything past the bound is overflow (:281). There is no branch where a listed entry lands on neither list, and naming both lists off the listing rather than off PortalFileBytes.filename genuinely closes the rename hole the PR describes. serve() (:407) replays the stored gap on every later open, and a NULL-coverage row is served as a declared gap. All of that is correct.

The gaps are at the edges of that loop.

F1 — HIGH — the comparison happens once, at first read; a file listed later is silent

guardedRead returns from cache at readTender.ts:219-220, before deps.portal.list is ever called. So the listing-vs-read comparison is a one-shot at first read, and serve() can only replay the gap that was known then.

Probe (real entry point, fake Portal):

P1 first: facts_available  second: facts_available
   portal reqs: [ 'list:1111…', 'fetch:NIT.pdf' ]

— read a Tender listing one file (complete coverage, facts_available), then add Eligibility_annexure.pdf to the Portal listing, then open it again as a second org. The second open serves facts_available from cache and makes zero Portal requests. The newly listed, never-read eligibility attachment is invisible.

This is #527's exact failure mode, displaced in time — and the displacement is not hypothetical: a buyer adding an eligibility annexure by corrigendum after publication is a routine GePNIC event, and #528 exists precisely because corrigenda invalidate a stored extract. The fix is almost certainly #528's, not this PR's. But two things should change:

  1. The PR body's NOT checked section should say it: "coverage is compared once, at first read; a file the Portal lists after that is not detected until test: hermeticize bootstrap fixtures #528 invalidates the row." Right now the body says the gap "comes back on EVERY open", which is true of the record and easy to read as a claim about the Portal.
  2. test: hermeticize bootstrap fixtures #528 must invalidate the coverage columns, not only the extract, and carry a test for it. If a corrigendum re-read writes a fresh row, F1 closes. If it only marks the extract stale while covered_files/unread_files survive, F1 stays open under a ticket that looks like it closed it.

This matters most for #529: the flag flips on a guarantee that currently holds at t=0 and decays afterwards.

F2 — MEDIUM — coverage is credited on fetch return, not on the file being readable

coveredFiles.push(entry.name) runs as soon as deps.portal.fetch resolves (readTender.ts:299-300). What makes an unextractable file honest today is sniffPortalFile (documents/fileSniff.ts:50) throwing PortalReadError("file_unreadable") — but that lives in the adapter, and performRead never re-checks PortalFileBytes.mime against EXTRACTABLE_MIME_TYPES before making the coverage claim.

Probe: a Portal that returns { filename: "drawings.zip", mime: "application/zip" } without sniffing →

P2: facts_available   coveredFiles: ["NIT.pdf","drawings.zip"]

A file the model never read, recorded as covered, served as complete coverage. No real adapter exists yet (#526), so this is a hole in a contract rather than a live bug — which is exactly why it is cheap to close now, before #526 is written against it. Three lines in the fetch loop:

const bytes = await deps.portal.fetch(tender, entry.file);
if (!EXTRACTABLE_MIME_TYPES.has(bytes.mime)) throw new PortalReadError("file_unreadable", `${entry.name}: ${bytes.mime}`);

The coverage claim should be made at the point where the file is proved readable, not where it is proved downloadable. Everything else in this PR follows exactly that principle — the listing is the source of truth because an adapter must not be trusted to keep a name. The same distrust applies to the format.

F3 — MEDIUM — the migration turns "coverage unknown" into "coverage complete"

Migration 0049 (already applied, not touched by this PR) is explicit: "NULL means coverage unknown", and store.ts:55 derives coverageKnown from exactly that NULL-ness. But the RPC body writes:

values (p_tender, 'ok', p_extract, coalesce(p_covered, '{}'), coalesce(p_unread, '{}'), …)

(supabase/migrations/0049_tender_read_attempts.sql:206-215)

A caller passing NULL therefore persists '{}' / '{}' — non-NULL, so coverageKnown reads true, unreadFiles is empty, and serve() answers facts_available. Probe P6 confirms serve() treats that row as complete coverage. The only caller today spreads real arrays (store.ts:68-69), so nothing is broken in production — but the fence protecting this feature's central invariant lives in TypeScript, while the SQL actively converts unknown into complete. Next migration: if p_covered is null or p_unread is null then return 'invalid'; end if; (or just drop the two coalesces and let NULL persist as NULL). Additive, no rewrite of 0049.

F4 — LOW/MED — declaredName bounds length but strips no control characters

declaredName (readTender.ts:84-88) trims, substitutes a positional stand-in, and truncates by code point. It does not remove C0 controls. Probe P3 with a listed filename containing U+0000:

P3 unreadFiles: ["bad[NUL]name.pdf"]

Postgres rejects NUL in text/jsonb, so the store_tender_read_extract call throws, store.write logs "paid extract not stored", and the caller's catch turns a fully paid read (Portal requests + rupee-lane debit + model tokens) into could_not_read. That is the exact cost the code-point-truncation docblock argues about, one character class short of covered. One-line fix in the same function: strip \p{C} before bounding.

F5 — LOW — duplicate listed names make the record un-keyable

Probe P4, listing ["dup.pdf","dup.pdf","other.pdf"] → coveredFiles: ["dup.pdf","dup.pdf","other.pdf"]. If one copy fetches and the other fails, the identical string sits on both lists, and any later listing-vs-record comparison (F1's eventual fix) cannot match them. The positional stand-in mechanism already exists for nameless files; extending it to disambiguate duplicates would make the record a key rather than a label. Not worth blocking on.

What holds up

  • Naming both lists off the listing — the PR's headline claim — is real and is what the six red-before-green tests prove.
  • coverageGapNotice as the single mapping, carrying no count and no filenames, is the right call: it is the only copy that stays true across the coverageKnown: false arm, and the component test proves 1, 3 and 40 unread files render an identical DOM.
  • could_not_read when nothing was read at all (readTender.ts:313) is correct, not a narrowing of fix: align Grok effort handling with 0.2.99 #527: a gap declared against zero facts is not a gap.
  • quota_exhausted → null notice: correct per spec fix: watcher ended-without-status handling for idle turn-ended #512 Decision 10, unit-tested.
  • Bounding applied once over [...failed, ...overflow] rather than per-list — the comment explains why, and the test covers failures-plus-overflow together.
  • Hindi copy reads like a person wrote it and renders from the shipped messages/hi.json.
  • The receipt's "NOT checked" section is unusually honest and every claim in it I could check held.

Recommendation

Merge, with: F2 and F4 folded into this PR (each is a few lines in readTender.ts, both are inside the unit this PR already owns), F3 filed as a one-line migration follow-up, and F1 written into both the PR body's NOT-checked section and #528's acceptance criteria before #529 flips the flag. F5 optional.

@OwenHu

OwenHu commented Oct 16, 2026

Copy link
Copy Markdown

PR2 of 2 (PR1 was #546): the Gmail-style toolbar + contenteditable Owner Email editor posting sanitised Gmail markup, and the edits page showing the formatted final with a "Formatting changed" note.

Halo: #3498

@redeye1011

Copy link
Copy Markdown

Live proof on production, 2026-10-27 ~18:25 UTC.

Evidence for the close. At check time two QA runs were active. Anonymous PostgREST operators?slug=like.qa-* returned their 4 public QA operators. None of them showed up for users:

  • Web: /api/operators returns []. /en/explore and sitemap.xml have no qa-jrn or qa-operator entries. /operators/qa-operator-staging returns 404.
  • Customer app, signed out: Explore shows 0 operators ("No operators match this view"), and Home shows "0 Available now". The anonymous queries now drop QA fixtures (feat: add autodeploy alerting, NAS deploy sync, and dispatch guardrails #625).

A run's operator page still opens by its direct slug, because the journeys suite needs that. The page is not listed or linked anywhere.

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.

4 participants