Skip to content

Sync Remote - #216

Closed
korallis wants to merge 4 commits into
kunchenguid:mainfrom
korallis:main
Closed

korallis wants to merge 4 commits into
kunchenguid:mainfrom
korallis:main

Conversation

@korallis

@korallis korallis commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Intent

MAV-13 (MAV-5 piece P7), plan task W1-A4: an attorney asks a question about one claimant's records and gets an answer whose every claim quotes the cited page exactly, or a plain refusal ("The records do not say.") with the coverage that was searched. The search runs on the page-text chunks that https://github.com/korallis/matilda-v3/pull/148 added to main. This PR publishes the unpublished branch fm/task-b3e3d835 from agent/matilda-w1-a4, merged with current main. fm/task-b3e3d835 itself is unchanged.

What changed

  • Page-text chunks: main's, not a copy. feat(notify): native out-of-band notifier for captain escalations #148 merged first, so this branch dropped its own PageTextChunks family and its chunk migration and uses main's app.page_text_chunk and app.page_text_chunk_progress (V20261204050000). Ask needs two things main's version lacks, so it adds them:
    • A search vector per chunk. app.page_text_chunk.search (tsvector, GIN-indexed) holds the English search terms of that chunk's window only; the words stay in app.page. PageChunkQueue.write computes it from the page text in the same insert. The migration backfills chunks already written; a chunk whose page text has since changed keeps an empty vector, and Ask never reads it because it matches on the current text revision.
    • Evidence pages first. PageChunkQueue.nextEvidence takes one unfinished ready page of a document assigned whole to a claimant as evidence, which are the pages Ask reads. PageChunkWorker asks for one before main's key-order walk and rests MATILDA_PARSE_CHUNK_IDLE_SECONDS when none is left. Without it, Ask would wait for every page that sorts before the evidence (about 660,000 ready pages on production).
  • Ask the records (medchron/AskQuestions, AskJobs, AskWorker, AskRetrieval, AskWriter, AskProperties). MATILDA_ASK_ENABLED switches the phase and is off by default. While it is off, every Ask route answers 503 phase_not_enabled before any matter read and makes no model call, as on main. When it is on:
    • ask stores one app.ask_question row as processing and returns 202 with its Location. The same key with the same question returns the same question. A different question under that key is 422 idempotency_key_reused. A second unfinished question for one asker and claimant is 409 ask_in_flight. More than six asks a minute is 429.
    • AskWorker (worker profile) answers one leased question and holds no database transaction across the model call.
    • AskRetrieval searches the claimant's whole record set through the chunks, reading only documents the asker may read under JdbcMedchronSourcePolicy and never a record the record set excludes or holds. Each question word is a prefix of its English stem, so a plural question finds the singular on the page. Words that name the records themselves ("record", "recorded", "claimant") are not searched, because they match nearly every chunk and outranked the subject asked about.
    • AskWriter makes one call on the router's gateway lane (the zero-data-retention route). Each claim must cite an exact quote. A quote that is not found contiguously in its passage is withheld. A found quote becomes an immutable app.source_citation. The writer prompt (ask-writer-2) now tells it that each claim is judged alone on its own quotes, so a claim may not lean on another one ("the same", "also").
    • Jev judges each claim alone against its quotes and page (ask.claim_support, registered threshold 0.80, uncalibrated). Only claims at or above the threshold are kept. When none remains, the question is refused with records_do_not_answer and its coverage. When nothing is chunked yet, the refusal is not_processed.
    • A read returns a question only while the asker still has live access to every document it touched (input_documents), and drops a claim whose citation is no longer current. pin answers 503 adapter_missing until piece P10.
  • Cross-family review fixes (four P1 findings on 96f44a3).
    • An answer is page text only. For a claim Jev passes, each cited span becomes one answer line whose text is exactly that span's page text and whose only citation is that span (AskWorker.lines). The writer's sentence is judged but never stored or shown. A read also withholds any line whose text is not exactly one of its citations' current quotes.
    • A question keeps its full input set. Asking and reading need the B1 ceiling (fullDocumentAccess), and the full potential input set (inputDocuments: document, version, hash, path) is saved when the question is accepted. Every read, in every state including processing, refused and failed, checks each saved input with retainedInputsAccessible before the history is queried or counted. finish and fail no longer narrow it, the column is NOT NULL, and the guard trigger makes it immutable.
    • A claim is shown only with its whole judged citation set. If any citation it was judged with is missing, stale or no longer permitted, the whole claim is withheld.
    • Jev's key covers what Jev saw. The evidence key (ask-claim-2) digests the claim, each quote, the surrounding page text, record name and page, each source's page-text revision, the prompt and the threshold registration; the judged state uses sorted maps so the digest is stable.
    • Re-check fixes on 896157b:
      • An idempotent ask replay matches key and fingerprint first (422 idempotency_key_reused on a mismatch), then returns the saved question only under the same retained-input check as GET; otherwise 404.
      • The search and its refusal coverage read only records in the question's saved input set, at the saved version, hash and path (AskRetrieval SAVED/IN_SAVED), so a record that arrives or is revised after acceptance is never searched, counted or quoted. The saved set is still never narrowed.
      • Each answer line keeps its claim's whole judged citation set (not only its own span) and the record name Jev saw for each; losing any one withholds every line under that verdict.
      • Retrieval carries the record name citations display (document.name); the writer and Jev are shown it, the evidence key digests it, and a read withholds a line whose citation now shows another name.
    • The writer prompt (ask-writer-3) says only the quotes are shown. The proof now checks each answer line equals a cited quote and that a restricted attorney's ask is a plain 404.
  • Fixes the final proof found after the code review approved e659200 (each with a server test; gate at 25ba786 below):
    • 4d5ebed: two writer replies stopped at 4000 output tokens (invalid_model_response) because the schema allowed 12 claims of up to six quotes while an answer keeps the configured number; the writer is now asked for that number (ask-writer-4).
    • dd2ef9d: a quote copied with single spaces where the OCR page has line breaks was not located; runs of whitespace now match any run, and what is stored and shown is still exactly the page's text (a changed word is still withheld). Each withheld claim logs its reason, without text.
    • 7c3d510: quotes of lists of findings ran past the old 400-character limit and were withheld; the limit is 1000 and surrounding whitespace is trimmed (ask-writer-5).
    • d47d0e0 and 25ba786: the history read took 16.6 s for 27 questions. Each citation is now resolved once per read, and the saved-input check is a set difference (measured on the copy as the app role: 7.85 s per-input probe, 0.99 s set difference, both returning 27 questions); the history then read in 3.1 s.
  • Faster reads (found by the witness proof). A history read computes the asker's readable record set once (materialized) instead of once per touched document; a citation read skips the photo-region and Bates policy joins when the matter has no region or mapping to find; listing citations skips the source PDF's geometry. On the witness copy, the history with 11 questions and 38 citations went from over 10 s (503, read deadline) to 0.7 s.
  • Front end. medchron-ask-api.ts parses refusal.checked as the contract's Coverage. screens/ask.tsx shows the plain refusal with the pages and records searched. No useEffect or useLayoutEffect. No hot file (app.tsx, case-tabs.tsx, SpaController.java, documents.tsx) is touched.
  • Migration V20261204144000__ask_the_records.sql (number assigned by firstmate after main passed the P7 block and then V20261204110000 and V20261204140000): app.ask_question, its guard trigger and policies, the source_citation insert policy for an answer being written, the initial ask.claim_support threshold (never overwrites an existing row), and the chunk search column with its backfill and index. The backfill lifts FORCE ROW LEVEL SECURITY on app.page_text_chunk for the owner and restores it in the same migration.
  • Proof ops/proof/proofs/ask-records.mjs: ten real questions answered with every quote checked against the page text at its span, three unanswerable ones refused plainly, the refusal coverage, a held record that is not searched, the history read within ten seconds, idempotency and in-flight refusals, and a restricted attorney who sees nothing. The questions come from --questions <file> kept on the server, or from built-in generic questions that name no person, provider, date or amount.
  • Tests. AskSafetyTest (18, real migrations as the runtime role, model services stubbed): writer prose, a blend of two quotes, a quote-only claim and instruction-like record text are each shown only as exact page text; a stored line that is not its citation's quote is withheld on read; the full input set is kept from acceptance even with no search hits; processing, refused-with-no-hits and failed questions are hidden once an input moves; an asker without every classification can neither ask nor read; losing one judged citation withholds the claim; changed page text around the same quote and span gives a new Jev key while identical text reuses it; a replayed ask of a processing or refused question is hidden once an input moves, while a changed body under the same key is still 422; a record that arrives or is revised after acceptance is never searched (real retrieval SQL); a refusal counts only saved records; losing one citation of a real worker judgement withholds every line; a different displayed record name is a new Jev key and a name-only correction withholds the old line. AskAnswerRulesTest; AskRetrievalQueryTest (plural finds singular, record words are not searched); PageChunkQueueTest gains "a page of assigned evidence is taken before the key-order walk and each chunk carries its search terms".

Verified on matilda-srv

All commands ran in /data/fm-agent/homes/matilda/data/matilda-w1-a4/repo after git fetch and git checkout -B agent/matilda-w1-a4 origin/agent/matilda-w1-a4, with the checked-out sha compared to the pushed head.

  • Gate at 25ba786afe60b412b88890f00932b95c0c27eb53: FM_HEAVY_SLOTS=6 ~/.local/bin/fm-heavy bash -c "./scripts/check-local.sh && ./gradlew --no-daemon test --tests com.matilda.v3.medchron.* --tests com.matilda.v3.parse.* && ./gradlew --no-daemon bootJar", run in the foreground, exited 0: eleven Python suites OK, ./gradlew check BUILD SUCCESSFUL, frontend 14 test files and 78 tests passed, then tsc and vite build, ModularityVerificationTest passed, medchron and parse tests 186 with 0 failures, 0 errors, 2 skipped, bootJar built.
  • Migration checks at 4d5ebed against origin/main 050103f8 (this stands in for GitHub's "Migration order" check, which cannot run):

Final Ask proof (passed)

On matilda-srv, at 25ba786afe60b412b88890f00932b95c0c27eb53, on a disposable copy of production (the closed pilot matter):

  1. cd /data/fm-agent/homes/matilda/data/matilda-w1-a4/repo && sudo -n python3 scripts/witness.py up w1-a4-ask --jar /data/fm-agent/homes/matilda/data/matilda-w1-a4/matilda-v3-<sha>.jar --matter <closed pilot>
  2. The copy's app with MATILDA_ASK_ENABLED=true, and a branch worker with page-text chunking and Ask on and MATILDA_ASK_CLAIMS=3. The worker gets only the gateway and Jev keys it needs (AI_GATEWAY_*, TYPESAFE_*, the extraction model and chat path), selected as root with umask 077 into a key file under the copy's private state, passed with --env-file and deleted after start; the whole runtime file is never passed. All 247 pages of the assigned evidence were chunked first.
  3. cd ops/proof && node proofs/ask-records.mjs --slug w1-a4-ask --out <evidence dir> --claimant <claimant> (built-in generic questions that name no person, provider, date or amount).

Result: {"passed":true,"steps":9}, exit 0:

Step Result
Ask panel opens on the claimant passed
A question no record mentions is refused plainly, with coverage refused; searched 241 pages in 49 records, none pending
Ten real questions, each answered only with exact quotes (each line equals a cited quote; each quote equals the page text at its span; each citation opens) 10 of 10 answered; 58 lines with 140 citations in total, 2 claims withheld
Three unanswerable questions refused plainly 3 of 3 refused, each with 241 pages and 49 records searched
A held record is not searched answered without citing it; records searched 49 before the hold, 48 after
A question citing a record later held is no longer shown passed
The whole history, with every cited claim, within ten seconds 43 questions, 443 citations, 2.9 s
Same key with a different question; a second unfinished ask 422 idempotency_key_reused; 409
An attorney with no grant on the matter no question, no history, ask answers 404, nothing stored

Model calls, counted from the copy's own audit (ask.writer model calls) and app.jev_verdict:

Writer calls (claude-opus-5 via the gateway) Writer tokens in / out Jev checks Jev cost
Passing run (run 12) 17 313,807 / 19,328 33 $0.0034
This copy in total (runs 10 to 12) 44 824,121 / 57,348 91 $0.0094
Earlier copies (runs 1 to 9 and one single-question Jev check) 235 writer and Jev calls together (37, 70, 38 and 90 by copy)

The gateway does not report a writer price to Matilda, so writer spend is given in tokens. Earlier runs, each followed by witness.py down: runs 1 to 6 found the search and history defects fixed before the review; runs 7 to 11 found the five fixes listed above.

Not done

  • Re-review of the proof's fixes. The code review approved e659200; the five small fixes above came after it.
  • Limits in this PR's own code (captain, 20 October: no AI call caps). The writer's max_tokens 4000, the claims per answer (MATILDA_ASK_CLAIMS) and per-claim citation count, the 1000-character quote bound, the 12 search words and the 16 passages a question reads are still in this code. Removing them is raised with firstmate; the 16-passage read in particular needs the passages split across several writer calls rather than a larger single call.
  • Earlier proof copies. Runs 1 to 6 (19 October) handed the copy's worker the whole production runtime file by --env-file; every worker start since passes only the named keys.
  • Merge order. Firstmate assigns this PR's migration a slot below https://github.com/korallis/matilda-v3/pull/235's V20261204140500 after the proof; origin/main has moved since and will be merged with that renumber.
  • Rule G1. V20261204144000 must not be deployed before the pending lower migrations ahead of it are deployed.
  • Production. Switching on MATILDA_ASK_ENABLED and MATILDA_PARSE_CHUNKS_ENABLED in production is a runtime flag plus model spend, and needs approval. Both stay off. During a blue/green overlap an older app writes chunks with an empty search vector (the column's default); none exist while the chunk worker is off. Pins remain with piece P10.
  • Review. The cross-family review approved the code at e659200 after two rounds of fixes; the proof fixes since then need firstmate's re-check. GitHub CI credits are exhausted, so this PR rests on the server gate above.

Risk

Medium-low while the flags are off: one additive migration (new table, functions, policies, one threshold row inserted only if absent, and a defaulted column with an index on the chunk table) and no behaviour change with both switches off. The chunk worker change only adds an evidence-first step before main's walk. When Ask is on, it spends on the gateway and Jev, gated by the flag, the rate limit and the one-in-flight rule.

korallis added 3 commits July 2, 2026 13:19
#1)

* feat(agents): verify scout reports and diagnose wedges before relaunch

Instruction-level edits from a research adoption review (least-to-most,
uncertainty-aware clarification, waves fan-out skill; mechanisms rejected,
verification discipline kept):

- scout reports open with status and coverage, tag per-finding confidence,
  and separate verified from inferred (fm-brief.sh scout DoD)
- scout relay carries confidence labels; expensive-to-reverse findings get
  a blind verifier scout before escalating (AGENTS.md section 7)
- stuck-crewmate ladder diagnoses spec-gap vs over-scoped vs execution
  wedges before relaunching the same brief (stuck-crewmate-recovery)
- needs-decision summaries carry concrete options plus a recommended
  default; explore the repo before escalating (fm-brief.sh rule 6)
- intake resolves scope ambiguity with the project-resolution asymmetry
  and states the partition remainder on multi-task splits (AGENTS.md)
- successor briefs name the predecessor's PR URL or report path (AGENTS.md)

* no-mistakes(review): Reorder rule 6 explore-first clause; make step 4 exit explicit
…llis fork (#2)

Restructure the README to answer why firstmate exists, what this fork
changes vs upstream (the PR #1 verification-discipline edits, with a
table), how the system works (lifecycle, ship vs scout, delivery modes,
secondmates, harnesses/backends), install steps for this fork including
upstream sync, worked usage examples, and guardrails. Every factual
claim was verified against AGENTS.md, docs/, and bin/ script headers.
…nd stow skill (#4)

* feat(stow): add operational memory capture (kunchenguid#197)

* feat(stow): add operational-memory learnings convention and /stow skill

Add data/learnings.md as the fleet-local operational-learnings home,
a knowledge-routing table in AGENTS.md, and a user-invocable /stow
skill that sweeps a session for uncaptured durable knowledge and
files it to the right disk home before a reset.

* no-mistakes(review): Fix stow backlog note command

* no-mistakes(document): Document stow memory routing

* fix(tests): protect herdr smoke cleanup from default sessions (kunchenguid#199)

* fix(tests): stop real-herdr smoke tests from ever killing the default session

Both fm-backend-herdr-smoke.test.sh and fm-backend-autodetect-smoke.test.sh
tore down their isolated throwaway HERDR_SESSION via a bare/inline-prefixed
`herdr server stop`, which is unscoped and resolves ambiently. On this herdr
client, that ambient resolution silently falls back to whatever server is
already running instead of the requested session - it killed the captain's
live default herdr server twice in production (2026-07-02), once from each
smoke test's cleanup trap.

Add tests/herdr-test-safety.sh with herdr_safe_stop_and_delete: it uses the
explicit-by-name `herdr session stop/delete <name>` form (never the ambient
`server stop`) and, before that, a read-only hard guard
(herdr_refuse_if_default) that re-queries `herdr session list --json` and
refuses outright if the target is literally "default", not found, or flagged
default:true. Fails closed on any ambiguity. Verified empirically against a
real isolated session: refuses on default/nonexistent/empty names without
ever calling stop, and correctly tears down a genuine isolated session while
leaving the default session's workspace state byte-identical before and
after.

* no-mistakes(review): guard herdr delete with fresh check

* no-mistakes(document): Document herdr smoke cleanup safety

* feat(bin): route herdr secondmates into per-home workspaces (kunchenguid#200)

* feat(bin): give each secondmate its own labeled herdr workspace

Give each secondmate its own labeled herdr workspace, and land crewmates
spawned from a secondmate home in that secondmate's own space, instead of
every firstmate home (primary and all secondmates) sharing one "firstmate"
workspace.

bin/backends/herdr.sh: replace the constant FM_BACKEND_HERDR_WORKSPACE_LABEL
with fm_backend_herdr_workspace_label(), resolved fresh from FM_HOME on every
call. The primary (no .fm-secondmate-home marker) still resolves to
"firstmate" - byte-identical to every pre-existing task's recorded label, no
forced migration. A secondmate home resolves to "firstmate-<secondmate-id>".
Every workspace-scoped path (find/ensure, tab create + duplicate check,
list-live recovery, pane-for-tab) uses this same resolution, so recovery and
duplicate checks stay scoped to each home's own space. Workspace and tab
create now pass --no-focus unconditionally (verified: neither focuses by
default once a workspace exists; --no-focus is defense in depth against the
one bootstrap edge case where the very first workspace in a session auto-
focuses).

Also fixes a session-targeting bug found while verifying this empirically:
HERDR_SESSION (env var, exported or inline-prefixed) is not reliably honored
by herdr 0.7.1 CLI subcommands once another herdr server is already running -
it silently falls back to whatever server IS running. fm_backend_herdr_cli
wraps every herdr invocation with both HERDR_SESSION and a trailing
--session <name> flag (verified to route correctly in every case tried),
fixing this for the whole adapter, not just the new label-scoped calls.

bin/fm-spawn.sh: a --secondmate spawn is launched BY the primary's own
process, whose FM_HOME still names the primary at that point. The herdr case
arm now shadows FM_HOME to the secondmate's own home (PROJ_ABS) for just the
two calls that resolve/create the workspace and tab, restored automatically
afterward (bash's temporary-assignment-before-a-command form works for shell
functions too). A crewmate/scout spawned FROM a secondmate's own fm-spawn.sh
process needs no such glue - its own FM_HOME already names it.

Tests: extended tests/fm-backend-herdr.test.sh (per-home label resolution,
--no-focus, --session flag, workspace-find/list-live scoping) and
tests/fm-backend-herdr-smoke.test.sh (a secondmate-shaped home's workspace
label, list-live scoping, restart stability in the multi-workspace shape).
Added tests/fm-backend-herdr-workspace-per-home-e2e.test.sh: the mandatory
isolated E2E, driving real bin/fm-spawn.sh/fm-teardown.sh - a primary-shaped
home into "firstmate", a --secondmate spawn into its own labeled space, a
crewmate spawned FROM that secondmate-shaped home landing in the same space
(this exact path had never run before), teardown closing only the right tab,
and list-live recovery seeing only each home's own tabs. All ten assertions
passed on the real binary; the default herdr session's own workspace state
was confirmed byte-identical before and after every real-herdr test run in
this change.

docs/herdr-backend.md: rewrote "Task container shape" for the workspace-per-
home design (label derivation, the --secondmate FM_HOME-shadow wrinkle, focus
behavior, label-collision/adopt-don't-duplicate semantics, no-forced-
migration), added "Session targeting: the --session flag, not HERDR_SESSION
alone", extended "ID stability" to the multi-workspace shape, and documented
the new E2E test.

* no-mistakes(review): Clarify herdr focus docs

* no-mistakes(review): Captain, clarify herdr server session docs

* no-mistakes(document): Document herdr per-home spaces

* fix(backends): rename Herdr secondmate workspace labels (kunchenguid#203)

* Rename herdr secondmate workspace prefix to 2ndmate-

The primary home keeps the firstmate label; secondmate homes now
resolve to 2ndmate-<id> so the herdr spaces sidebar is unambiguous.
Tests and docs updated; pre-rename workspaces can be aligned with
herdr workspace rename.

* no-mistakes(review): Clarify herdr workspace migration behavior

* no-mistakes(document): Herdr docs label alignment

* feat(bin): add unified session start digest (kunchenguid#201)

* feat(bin): collapse session start into one command

Add bin/fm-session-start.sh, composing fm-lock.sh, fm-bootstrap.sh, and
fm-wake-drain.sh into one ordered digest (lock, bootstrap diagnostics,
wake queue, context files, fleet state) instead of six-plus separate
turns. Lock now runs before bootstrap's mutating sweeps, closing a race
where a second concurrent session could mutate shared state before
discovering the lock was held. A lock refusal prints a loud read-only
banner, skips every mutating step via a new opt-in
FM_BOOTSTRAP_DETECT_ONLY flag on fm-bootstrap.sh, and still completes
the read-only-safe digest.

Add fm_backend_target_exists to fm-backend.sh as a shared, read-only,
never-side-effecting per-task endpoint-liveness primitive for both the
tmux and herdr backends.

Rewrite AGENTS.md sections 3 and 5 around the single command and add
tests/fm-session-start.test.sh.

* no-mistakes(review): Harden session-start read-only guidance

* no-mistakes(review): Suppress read-only tangle repair guidance

* no-mistakes(review): Include orphan status logs

* no-mistakes(review): Captain: make session-start test executable

* no-mistakes(review): Captain: clarify status tail guidance

* no-mistakes(document): Sync session-start docs

* no-mistakes(lint): Shell lint clean

* fix(tests): avoid shellcheck boolean chain

* fix(bin): corroborate herdr idle crew state (kunchenguid#207)

* fix(bin): corroborate herdr idle agent_status with the pane's own text

crew_pane_is_busy trusted a bare `idle` verdict from herdr's agent.get
outright, skipping the tail-regex corroboration unknown already gets.
agent.get reports generation state only (working while the model streams
a turn), so it reads idle for a crew blocked on its own long foreground
no-mistakes run - even though the pane still shows the busy banner the
whole time. Combined with the no-mistakes CLI's 10-run attribution cap,
this made a genuinely working herdr crew read as not provably working,
triggering an immediate stale wake instead of absorb-then-escalate.

* no-mistakes(document): Align herdr busy-state docs

* fix(backends): reuse the herdr firstmate workspace instead of leaking one per spawn (kunchenguid#202)

* fix(backends): reuse the herdr firstmate workspace instead of leaking one per spawn

Every herdr-backed crewmate left an orphaned `firstmate`-labelled workspace
behind, one per task, because `fm_backend_herdr_workspace_find` never matched
the existing workspace: its jq filter used `--arg label ... $label`, and
`label` is a reserved keyword in jq (label/break), so the filter was a compile
error. The error was swallowed by `2>/dev/null`, the find returned empty on
every call, and `workspace_ensure` took the create path each spawn, minting a
fresh workspace. The same collision silently disabled the create-task
duplicate-label check and the bare-selector tab lookup.

Rename the jq variable to `$want` in all three affected filters so reuse,
duplicate detection, and bare-selector lookup work. With reuse restored the
single `firstmate` workspace is persistent (like tmux's session) and teardown
correctly leaves it in place, closing only the task's pane/tab.

Also prune the default tab (label "1") herdr auto-creates inside a freshly
created workspace, best-effort, so the workspace holds only real task tabs.

Add stateful-fake-CLI tests that replay repeated spawn/teardown cycles and
assert one reused workspace, zero orphans, the default tab pruned, and
`workspace create` invoked exactly once. Verified against the real herdr binary
too: the pre-fix code failed the smoke idempotency check (minted wE then wF in
an isolated session); the fix passes it.

Document the workspace lifecycle, the jq-keyword pitfall, the default-tab
prune, and the project-labelled-workspace anomaly (not adapter-created) in
docs/herdr-backend.md.

* docs(herdr): trim workspace-lifecycle addition to current-state facts

The docs/herdr-backend.md convention documents current behavior, not
history - narrative belongs in the PR/commit message. Tightened the
workspace-leak and default-tab-prune write-up down to the operative
facts (the jq reserved-keyword guard, when pruning is safe, and the
persistence caveat), and corrected the CLI-facts table rows to match
the corrected prune timing.

* fix(backends): defer herdr default-tab prune until a real task tab exists

Closing a workspace's LAST tab deletes the whole workspace on real
herdr (verified). Pruning the auto-created default tab right after
workspace create closed the workspace's only tab at that point,
destroying the just-created workspace on every single spawn instead of
reusing it - the fake-CLI unit tests didn't model this real-herdr
behavior, so they passed while the real-herdr smoke test failed with
"container_ensure is not idempotent".

Move the prune into fm_backend_herdr_create_task, right after the
first real task tab is added to a freshly created workspace, when
closing the default tab alongside it is safe. Update the fake-CLI unit
test to match the corrected timing.

Also fix a smoke-test-only bug this surfaced: the test's second
create_task call reused a $CONTAINER captured before the first task
was killed, rather than re-running container_ensure like real
fm-spawn.sh always does immediately before every create_task call - so
once the workspace (correctly) disappeared after its last tab closed,
the stale reference no longer named a live workspace.

* test(backends): guard against jq --arg names colliding with jq keywords

Regression guard for the workspace-leak bug this PR fixes: a jq
--arg/--argjson variable named after a jq reserved keyword (e.g.
label) is a compile error on jq <= 1.6, and this adapter's
2>/dev/null silently turns that into an empty result instead of a
visible failure. Greps bin/ for the pattern so a future violation
fails loudly here instead of silently misbehaving on an older jq.

* docs(herdr): fix per-home staleness and drop contributor-specific example

The workspace-lifecycle write-up hardcoded "the firstmate workspace"
as if the label were always the fixed constant, stale against the
per-home labeling documented earlier in this file (primary: firstmate,
secondmate: 2ndmate-<id>). Rephrased per-home throughout, and pointed
the "workspace this adapter did not derive" case at the existing
Label-derivation section instead of a separate anomaly writeup.

Dropped the "Anomaly: a workspace labelled with a project name"
section - the python-teslemetry-stream example was a contributor's own
environment, not current adapter fact, and it repeated a now-incorrect
FM_BACKEND_HERDR_WORKSPACE_LABEL constant claim. Replaced with one
generic sentence already covered by the corrected wording above.

Also fixed the jq-reserved-keyword guard test's file reference, which
named tests/fm-backend.test.sh when the test actually lives in
tests/fm-backend-herdr.test.sh.

---------

Co-authored-by: kunchenguid <kun@kunchenguid.com>

* fix(backends): make Herdr default-tab pruning safe (kunchenguid#215)

* fix(backends): make the herdr default-tab prune provably safe

The default-tab prune could close a pane holding a LIVE agent: an
ADOPTED workspace (found pre-existing by label match) was pruned using
the same tab-count/label heuristic as a freshly created one, and herdr
derives a workspace's displayed label from its cwd basename when no
explicit --label is given. A captain launching herdr directly inside a
directory named "firstmate" produces a workspace that looks identical,
by label alone, to firstmate's own container - so the very next spawn
adopted the captain's own live workspace and closed their live pane
27ms after creating its task tab (2026-07-02 incident).

The fix is structural: fm_backend_herdr_workspace_ensure now captures
the seeded default tab's id straight from its own `workspace create`
response, only when it just created the workspace. That id threads
through fm_backend_herdr_container_ensure to fm_backend_herdr_create_task,
which is the only function allowed to prune it - an adopted workspace's
caller always passes an empty seeded-tab-id, so create_task never
re-derives "prunable" from a tab's label or count. Defense in depth:
the prune also refuses a tab whose pane reports a working agent.

Covered by new unit tests (adopted-never-prunes, created-prunes-exactly,
the exact label-collision incident shape) and a new isolated real-herdr
E2E test that reproduces the incident against the pre-fix code and shows
it fixed, plus the normal happy path.

* no-mistakes(document): Sync herdr prune docs

* no-mistakes: apply CI fixes

* no-mistakes(review): fix(backends): route fm_backend_target_exists herdr check through fm_backend_herdr_cli

* no-mistakes(document): No documentation changes needed; docs already fully synced with code

---------

Co-authored-by: Kun Chen <3233006+kunchenguid@users.noreply.github.com>
Co-authored-by: Brett Adams <Bre77@users.noreply.github.com>
Co-authored-by: kunchenguid <kun@kunchenguid.com>
@korallis korallis closed this Jul 4, 2026
fritznoff pushed a commit to fritznoff/starship that referenced this pull request Nov 2, 2026
…id#216)

Adds bin/fm-voice-idea.py: a spoken 'song name, then idea' glasses capture is filed into Atelier through its Inbox and importer, held under its capture id while Atelier is unreachable, and answered aloud with 'Filed to <song>', 'Saved, waiting for the desk' or an honest failure; fixture tests added.
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