Garry's Opinionated OpenClaw/Hermes Agent Brain
Plan: managed sync never stalls on one stuck preparation (#6278)
Thread: GBRA-59. Issue: https://github.com/garrytan/gbrain/issues/6278 (filed by garrytan-agents, 2026-10-08 03:07Z, v0.60.105.0, managed Postgres via Supavisor).
Related: #6188 (fence holds and repair, shipped in waves 10–11), #5984 (catch-up throughput, GBRA-45, PR capy/sync-feeder-fast-writes merging next), #5406 (writes stuck queued), #6176 (claim phase stamps).
The problem in one paragraph
A ~13.6k-entry managed catch-up (gbrain sync --source default --no-pull --no-embed) runs for 10–15 minutes, then one write sits in running / claim phase preparing for 700 s and growing. Its owner keeps renewing the 30 s claim lease every 10 s, so the lease never lapses, nothing behind it on the worktree root runs, and the non-TTY watchdog kills the process at 3600 s (sync_deadline_stop, rc 143). The next pass re-enters the same state. Four passes in a row, 153 of 13,627 entries in 3.3 h. The stall begins right after [persistence] phase=preparation reason=invalid_params lines from two fence errors (correlation, not proof). Separately, the global maintenance job's fence_repair and chronicle phases refuse with owner_unavailable, so the repair that should clear held fences never runs.
What the code says today (read on master 7aa2caa0, v0.60.106.0)
- No preparation deadline for sync or maintenance writes.
src/core/persistence/consumer.tsexecute()setsbounded = row.operation === 'remember' || ((put_page|edit_page) && !row.intent?.kind). Only those get the 30 spreparationMsbudget. Amanaged_sync_importmember, amanaged_maintenance_*request, and every other intent kind prepare with no deadline, whilestartClaimLeaserenews the claim every 10 s throughexecuteRawDirect(the session-mode direct pool). The group path (src/core/persistence/group-publish.tsexecuteClaimedGroup) prepares four members at a time under one group lease and has no deadline at all. This is exactly the shape the reporter sees:phase: preparing,resumes_on_its_own: false, "its owner is still renewing the claim". (amended: CEO) Two corrections. Only the single path renews throughexecuteRawDirect(consumer.ts:545-548); the group path renews withrenewGroupClaims, which runsengine.executeRawon the ordinary pool (journal.ts:321-325; GBRA-45 branchjournal.ts:343-347). And the existing 30 s deadline does not race the preparation: the timer only callsabort.abort()(consumer.ts:539-543) whileawait lease.whileHeld(preparation)(:552) still waits on the promise itself, so the deadline works only because the put_page/edit_page preparers honour the signal. The service dispatcher passes no signal to sync or maintenance preparers (service.ts:67-68;prepareManagedSyncMutation(engine,row,_config)atsync-prepare.ts:207), the group path never passes one (consumer.ts:615), and a lost claim keeps the root blocked until the abandoned preparation settles (#5373,consumer.ts:421-423,553-555).test/persistence-consumer-scheduling.test.ts:201-226pins the current behaviour that a preparation ignoring its signal staysrunningpast the deadline. - The stuck preparation has no step name.
#6176stampsclaim_phase(preparing|publishing) on every renewal (src/core/persistence/claim-phase.ts). Nothing records which step ofprepareManagedSyncMutation(src/core/persistence/sync-prepare.ts: authority, worktree binding, gitrev-parse, raw hash, origin checks, knowledge publication, import screen, link resolution) is in flight, or whether the step is waiting on a pooled connection, a Postgres lock, git, or the filesystem.health.tstherefore reportscause_unknowneven though the phase is known. (amended: CEO)syncGitis a synchronousexecFileSyncwith a 30 s timeout (sync-discovery.ts:50-52): it is bounded, and it blocks the event loop while it runs, so renewals that keep firing every 10 s prove the stuck await is asynchronous. Gitrev-parseis effectively ruled out as the unbounded wait. - Lease renewal and preparation use different pools. Renewals go through
executeRawDirect(direct session pool), preparation queries through the regular pool (max=GBRAIN_POOL_SIZE, default 10, postgres.js queues waiters forever). Up toconcurrencysingle preparations, lane groups publishing in long transactions (GBRA-45: up to six groups at once), the projection worker and the effects worker all share those 10 connections. A JS-level wait inside a transaction for a second pooled connection, or plain saturation, starves preparation while renewals keep succeeding. This is the leading hypothesis for why the preparation never finishes; it is unproven and must be proven or eliminated in Phase 0. (amended: CEO) Saturation is already partly guarded:pool-budget.ts:15-24caps long holds atmax-1,pool-capacity.ts:9-25caps publication concurrency, andresolveLanesclamps lanes to the long-hold capacity minus 3 (sync-group.ts:48-61; GBRA-45:62-71), so six lanes is the ceiling for a pool of ten, not a default. If the blocker is a group member, its renewals succeed on the same ordinary pool that would be starving it, which argues against total starvation.src/core/pool-gauge.ts:5-14states there are no public checkout counters, so the pool cannot today tell a queued checkout from a server-side lock wait. - Fence adoption writes are doomed before submission.
src/core/facts/unfenced-facts.tsfenceManaged()(called from theextract_factscycle phase and the v0.32.2 migration) renders a facts fence and submitsmanaged_maintenance_adopt_fact_fence.prepareFactFenceAdoption(src/core/persistence/prepared-maintenance.ts:290) re-parses the rendered fence and refuses withinvalid_params"The adopted fence row does not render its legacy fact." whencell.claim !== fact.value.factor visibility differs. That is an internal render→parse round-trip mismatch, not caller input. (amended: evidence, parent probe 2026-10-07) ArenderFactsTable→parseFactsFenceround trip over 24 claim shapes shows pipes, newlines, backslashes, backticks, 1200-char claims, unicode and emoji all round-trip; exactly four shapes do not: trailing whitespace ("x "→"x"), leading whitespace, whitespace-only (" "→"") and CRLF ("a\r\nb"→"a\nb"). The parser trims cells and normalizes line endings, the renderer does not, and the check compares the parsed cell with the rawfacts.factcolumn, so any legacy fact stored with surrounding whitespace or CRLF is refused on every replan. That matches the reporter's nine refusals per pass on the same pages. Nine such refusals per pass, each a terminalfailedwrite that consumes a claim, logs a preparation failure and teaches nothing: no hold, no repair candidate. (amended: CEO) Correction:failed_pagesdoes record the exception text (unfenced-facts.ts:256-257, surfaced as a warning bycycle/extract-facts.ts:487-492), but its advice ("report the request ID to the user") is not actionable. Both voices found more shapes the codec changes beyond the parent's four: a claim of the form~~x~~parses back inactive, a literal<br>parses back as a newline, a lone CR comes back as LF, and U+00A0 is stripped by JavaScripttrimbut not by Postgresbtrim(codec infence-shared.ts:30-54,76-101).planFencealso matches existing fence rows on the raw claim (unfenced-facts.ts:176-180), and each terminal refusal mints a fresh attempt id on the next run (prepared-maintenance.ts:262-266), which is why the same pages refuse on every pass. - A
repeated_markerfence defect in a timeline section fails a sync member instead of holding it.compileCanonicalProjections(src/core/persistence/canonical-projections.ts:297) throws the typedinvalid_fence(wireinvalid_params) for the first defect.#6218#6188 E10 (amended: CEO) made the sync hold such files (src/core/persistence/sync-holds.ts,src/commands/sync/holds.ts), but the reporter saw neither a hold nor afence_repaircandidate on 0.60.105.The hold is written by the sync process when it consumes the failed receipt; if the stall (1) lands first and the watchdog kills the process, the receipt is never consumed, and the next pass re-admits and re-fails the same page.(amended: CEO, refuted by both voices) A watchdog kill does not lose the hold:convertBlockedCursorre-holds the entry at the start of the next run (sync-run.ts:396-421). The real gap is that both hold paths,convertBlockedCursor(sync-run.ts:404) andholdFailedFenceRequest(sync-run.ts:445-450), refuse to write the hold while any request on the whole source isqueued/running/recovering, and returnpartial/writer_pendinginstead. A stuck preparation (1), or the steady stream ofextract_factsadoption writes on the same source, therefore blocks every fence hold indefinitely. GBRA-45 keeps the same source-wide wait (sync-run.ts:417,448-469). This links problems 1 and 2 of the report: the stall is what prevents the hold. Separately, the managed screen already holds residual fences before admission (sync-screen.ts:85sync-run.ts:317-321withsync-screen.ts:128-150;sync-screen.ts:85isprepareTimeFenceHold, the hold built from a failed receipt; amended: DX), so arepeated_markerrefusal at preparation means either stored-row-dependent fences (theprepare_timehold path) or a request that is not a sync member at all (an adoption or maintenance page write on a page whose stored body already has the defect); Phase 0.5 checks which. The sync hold work is #6188 (E10); the plan's "#6218" reference is unverified.repeated_markeris amanualtier reason (src/core/fence-repair/reasons.ts:66), so even a hold never self-repairs; the user is told to merge the two fences by hand. fence_repairrefuses withowner_unavailablefor a reason unrelated to the sync.src/core/fence-repair/repair-io.ts:85setsownerElsewherewhenbinding.owner_host_id !== localHostId() || binding.state !== 'active' || !binding.local_path. A running sync is reported assync_in_progress, notowner_unavailable.localHostId()is a UUID in<persistenceHome>/host.json, so a maintenance worker launched with a differentGBRAIN_HOME, user, or launchd environment than the sync CLI has a different host id and is "another host".The binding can also sit in(amended: CEO, refuted) A worktree binding goes torecoveringafter a SIGTERM mid-publication.recoveringonly during topology clone add/reclone (topology-clone.ts:139-143) and todrainingonly during writer transfer (ownership.ts:273); it is request rows that go torecoveringafter a kill (journal.ts:630).maintenancePreflight(prepared-maintenance.ts:78-83) refuses chronicle on a wider predicate than repair: missing binding, wrong source incarnation, missing coordination path, host mismatch, inactive state or missing local path. The function inrepair-io.tsisloadFenceSource, notsourceView, and the owner check runs before the sync check (repair/fences.ts:264-268).GBRAIN_HOMEresolves to<GBRAIN_HOME>/.gbrain(config.ts:1865-1881), so host.json lives at<GBRAIN_HOME>/.gbrain/persistence/host.json(identity.ts:37,55-59). The reporter's guess (sync holds the owner role) does not match the code; the cause is a host-id split, a wrong-incarnation or incomplete binding, or a genuinely different host, and Phase 0.1 decides which.
Goals
- G1. A catch-up never stops making progress because of one request. Any single write that cannot finish preparing is taken off the root within a bounded time and the rest of the root keeps moving. (amended: CEO) Stated as an invariant, not a budget table: while the database and control path work, no unpublished request keeps root execution past a hard ceiling. Preparation is cancelled (the signal reaches every preparer and its queries), the consumer races the preparation against the deadline on both the single and the group path, and a late result can never publish (the execution-token fence). An abandoned await that ignores cancellation is never silent: it is stamped, the request is held, and if the #5373 root block would otherwise keep the root waiting on it, the mechanism Eng chooses (isolate the zombie, or exit the sync with a distinct exit code so the zombie dies with the process) still guarantees the next pass moves past the entry. (amended: DX/Eng: settled in 1.9 — barrier to the ceiling, then isolation with a per-process cap; a CLI owner ends the drain
resumableand exits, a resident owner reportsrestart_required; no new exit number. The guarantee needs every owner process on the new version.) - G2.
gbrain sources writer status --jsonnames what a stuck preparation is doing (step, and what it waits on), so the next report carries evidence instead ofcause_unknown. (amended: CEO) The step is always named; the wait cause (git,fs,db,pool) is reported only when it is observed, otherwiseunknown. A truthfulunknownbeats a confident wrong repair command, so "never reportscause_unknown" is not a release gate. - G3. Fence problems never consume the write path: a fence that cannot be rendered or parsed becomes a hold with a reason and (where a tier applies) a
fence_repaircandidate, never a repeated terminal failure. (amended: CEO) The hold lands even while unrelated requests on the same source are still queued or running. For maintenance writes (fact-fence adoption, maintenance page writes) there is no manifest entry to hold: a row or page that cannot be written without a fence defect is not submitted at all, and is reported with its reason infailed_pagesand in doctor'sfence_integrity(and, for a fence defect already in the stored page, as afence_repaircandidate), so it never becomes a repeated terminal failure. - G4.
fence_repairandchroniclerun on the owner host while a sync is running, or say precisely why they cannot, with the exact command to fix it. (amended: CEO, restores the user's direction) The target is that repair actually runs during the sync for every candidate whose path is neither in flight nor still ahead in the sync's frozen manifest; the precise refusal is the fallback for a genuinely different host, not an alternative outcome. For the reporter's case the acceptance check is "the three held candidates repaired", not "the refusal is clearer". - G5.
The reporter's run (13.6k entries, Supavisor,(amended: CEO, the ≥300 figure has no source) The GBRA-45 bench measures 152.8 pages/min steady with six lanes at 57 ms (--no-embed) drains in one pass at the GBRA-45 throughput (≥300 pages/min steady) with zerosync_deadline_stop.docs/eval/managed-sync-catchup.mdon the GBRA-45 branch, "Parallel lanes" table), so 13.6k entries take about 90 minutes.longer than the 3600 s non-TTY watchdog.(amended: DX, refuted by both DX voices) The non-TTY deadline is progress-aware: it extends while pages commit and stops only after a stall window without progress (sync-reconcile.ts:161-206; live-sync.md), and the reporter's outertimeoutwas 14400 s. A healthy 90-minute catch-up can finish in one pass, so the one-pass goal stands. Goal: zero stalls caused by a single request; a stuck request costs at most its budget times the attempt limit; steady throughput within 20% of the bench on the same fixture and RTT; every pass checkpoints and the next pass resumes without re-stalling; (amended: DX) one pass drains the fixture, because budget × attempts (240 s) and the hard ceiling both stay inside the watchdog's no-progress window. The final report separates "processed every manifest entry" from "imported every page" (held, stale and missing counts), because holds deliberately leave content behind. - G6. (added: CEO) A systemic fault is not reported as a pile of file holds. When many entries in one run hit the preparation deadline (the existing
GIT_HOLD_ESCALATE_*thresholds,sync-holds.ts:48-52), the run stops with one systemic diagnostic naming the step and the evidence instead of holding every file and calling the pass complete.
Non-goals
- Throughput work beyond G5 (that is #5984 / GBRA-45).
- Automatic repair of
manual-tier fence reasons such asrepeated_markerby a model (spend policy is the user's call; #6188 settled it). - Changing the claim lease protocol or the direct/read pool split.
- (added: CEO) Phase 2.5 (merging repeated facts fences) is deferred to TODOS.md; a visible manual hold meets this incident.
- (added: CEO) Capturing
pg_stat_activityfor the blocker insidewriter status --probeis deferred to TODOS.md; Phase 0.1 asks the reporter for it by hand. - (added: CEO) An unproven pool concurrency cap (old 1.4) is out unless Phase 0 proves starvation.
Phase 0: prove the cause (1 day, Ubicloud)
Deliverable: a reproduction that stalls on master and a written root cause, before any fix is designed in detail. (amended: CEO) The one day is a time box on the investigation, not a promise of success, and it gates only the cause-specific fix (old 1.4). The containment work in Phase 1 does not depend on the cause and starts in parallel. If no natural reproduction appears within the day, record "cause unproven", ship containment proven by deterministic forced faults, and keep the investigation open on the issue; PR 1's step stamps make the reporter's next pass the capture.
- 0.1 Evidence from the reporter. Comment on #6278 asking the reporting agent for, during the next stall:
SELECT pid, state, wait_event_type, wait_event, xact_start, query_start, left(query, 200) FROM pg_stat_activity WHERE datname = current_database(), the sync process's Bun stack dump (kill -USR1/bun --inspectorgbrain sources writer status --probe --json),GBRAIN_POOL_SIZE,ls -la "${GBRAIN_HOME:-$HOME}/.gbrain/persistence/host.json"(amended: CEO, corrected path) from both the sync shell and the maintenance worker's environment, andgbrain sources writer status --source default --jsonfrom both. (amended: CEO) Also ask for the blocker row'soperation,intent->>'kind', publication group key andclaim_phase(SELECT request_id, operation, intent->>'kind', claim_phase FROM persistence_requests WHERE state='running'): that alone tells the single path from the group path, and a sync member from a maintenance write. (amended: Eng) Also capturegbrain config get sync.write_throughand which process submitted the adoption writes: adoptions that reached preparation passedmaintenancePreflight's owner check unless write-through is off (prepared-maintenance.ts:76-77), so a same-process host split cannot explain both the adoption refusals and theowner_unavailablerepair refusals. Send this comment now, not after the Ubicloud attempt. (Garry may instead let this thread read the Mac directly; that is his call.) - 0.2 Reproduce on a 16-vCPU Ubicloud VM (
UBI_OWNER=gbra59): Postgres behind PgBouncer in transaction mode (the CI gate already has one) withGBRAIN_POOL_SIZE=10, a 15k-page fixture worktree (amended: CEO) built with the GBRA-45 bench,scripts/bench/managed-sync-catchup.ts(it injects latency with toxiproxy; add PgBouncer in front), seeded with: (a) ~20 pages whose timeline section repeats a facts fence marker, (b) ~1k legacy unfenced facts whose text does not round-trip throughrenderFactsTable→parseFactsFence, seeded with exactly the four failing shapes (trailing whitespace, leading whitespace, whitespace-only, CRLF) plus round-tripping controls (pipes, newlines, backslashes) (amended: evidence), and theextract_factscycle phase enabled so adoption writes land mid-sync. Runtimeout 3600 gbrain sync --source default --no-pull --no-embedin a non-TTY. (amended: CEO) Run it on 0.60.105 and on the GBRA-45 head without the fix (the release target adds thepreparationReadsmemo and the vendored postgres.js pipelining patch), and later compare GBRA-45-without-fix against GBRA-45-with-fix on identical data and topology. Also exercise pool sizes 3 and 10, the shared and split direct routes, andSHOW statement_timeoutthrough the pooler. Capturewriter status --jsonevery 30 s andpg_stat_activityevery 30 s. - 0.3 Decide between the candidates with that capture: pool starvation (every pooled connection busy or idle-in-transaction while a preparation awaits a connection), a Postgres lock wait (
wait_event_type = Lock, whichstatement_timeout = 5minshould break unless Supavisor drops startup parameters: checkSHOW statement_timeoutthrough the pooler), a git or filesystem wait (syncGit,syncRawHash, link preparation), or a JS promise that never settles (transactionMemo,sharedSyncValidation,MaintenanceWriteWait). Write the finding and the forced probe that reproduces it into the plan's Review record, then the PR. (amended: CEO) The code already narrows the list: git is ruled out (synchronous and bounded, see claim 2); total pool starvation is unlikely if the blocker is a group member (claim 3). Remaining leads: a lock wait thatstatement_timeoutdoes not cover, a promise that never settles (transactionMemo,sharedSyncValidation,MaintenanceWriteWait, GBRA-45'spreparationReads), or a wait on the direct pool. - 0.4 Fence adoption mismatch. (amended: evidence) Done for the renderer/parser pair: the four failing shapes are surrounding whitespace (leading, trailing), whitespace-only and CRLF (probe script kept at
~/.capy/work/gbra59-autoplan/rt.ts). What remains is confirming those shapes exist in the reporter'sfacts.factrows and turning the probe into the 2.1 property test. (amended: CEO) Use the round trip itself as the oracle, run read-only in TypeScript over the reporter's unfenced rows, instead of a SQLbtrimcount: SQL undercounts (it misses~~x~~,<br>, lone CR and NBSP, which JavaScripttrimstrips andbtrimdoes not). - 0.5 (added: CEO) Which request failed with
repeated_marker. The managed screen holds residual fences before admission (sync-run.ts:317-321,sync-screen.ts:128-150; amended: DX), so read the two failed receipts'operationandintent->>'kind'. If they are adoption or maintenance page writes on pages whose stored body already has the defect, Phase 2 handles them as maintenance refusals; if they are sync members, theprepare_timehold path applies.
If 0.3 finds a cause outside this plan's radius (for example a Supavisor behaviour), the plan still ships Phases 1–3, because they make the stall bounded and visible regardless of cause, and files the external cause as its own issue.
Phase 1: bounded preparation for every write, hold instead of re-enter (PR 1)
(amended: CEO) Missing blast radius added to PR 1: src/core/persistence/service.ts (the preparer dispatcher, to thread the signal), sync-prepare.ts, page-prepare.ts, prepared-maintenance.ts (signal), fault-points.ts (new consumer:preparing point), sync-run.ts hold gate sites, sync-window.ts/sync-group.ts/sync-lanes.ts (ordering after a deadline release), switches.ts (kill switch), model.ts plus migration registration and fresh-install schema, core/config.ts and commands/config.ts (new keys; commands/config.ts:396-398 special-cases max_claim_ms validation), commands/doctor/checks/persistence-requests.ts (the check is persistence_write_stall, not persistence_stalled_claims), held-reads.ts, sources-retry-held.ts, doctor git-holds.ts, and src/core/behavior-change-notice.ts (new hold code). sync-waivers.ts and sync-run.ts also call the sync preparer outside the consumer; a consumer-only deadline does not bound them, so Eng must decide whether they need the same budget.
Files: src/core/persistence/consumer.ts, group-publish.ts, claim-phase.ts, claim-lease.ts, journal.ts, health.ts, diagnostics.ts, types.ts, sync-holds.ts, src/commands/sync/holds.ts, src/core/persistence/sync-run.ts, src/core/error-registry.ts, docs/ENGINES.md, docs/guides/write-refusals.md, docs/guides/repair.md.
1.1 Every preparation gets a deadline. (amended: CEO) The deadline must cancel, not only signal: thread the
AbortSignalfrom the consumer throughservice.tsinto every preparerand pass it to their queries ((amended: Eng, both voices: blanket query signals cost GBRA-45's throughput, because a signalled statement reserves a dedicated connection that the vendored driver never pipelines,executeRaw(sql, params, { signal }))vendor/postgres/src/index.js:262-266, andpreparationReadsskips its memo for signalled reads,group-publish.ts:155-158on GBRA-45; most preparation awaits are engine helpers with no signal parameter anyway. Cancellation is the consumer race plussignal.throwIfAborted()insideenterClaimStepat each step boundary; a signal goes only to unmemoized raw statements that can block on a lock or a pool reservation,postgres-engine.ts:2708-2744. Shared memos (preparationReads,groupReads,readWriteSwitches,preparationConfigView, the source-basename chain inlinks-preparation.ts) never take a member's signal: a member races its own signal against the shared promise, so an abort never rejects a sibling's read. Transactions, synchronous git/fs and PGLite WASM work cannot be interrupted; the race and the ceiling cover them. PR 1 is gated on the GBRA-45 bench within 20%.) race the preparation against the abort on both the single and the group path (today the group path never passes a signal), run the budget clock per member from that member's own start (a group holds up to 64 members prepared four at a time), and add an outer hard ceiling for any kind. The per-kind numbers below are provisional defaults chosen from preparation-tail measurements, not evidence. (amended: DX, both voices) Config keys form one family and none repurposes an existing key:persistence.sync_preparation_ms(default 120000),persistence.maintenance_preparation_ms(default300000120000, amended: Eng),persistence.preparation_ceiling_ms(the hard ceiling, default 600000, validated range 60000-3600000 and ≥ max(budgets) + 30 s grace, amended: Eng) andpersistence.max_preparation_attempts(default 2, range 1-10).persistence.max_claim_mskeeps its meaning (doctor's warning threshold); using it as a kill ceiling would turn a user's raised warning threshold into a day-long wait, or a lowered one into killed writes. Validation goes through the structured agent error renderer (today'smax_claim_mspath prints and callsprocess.exit(1),commands/config.ts:396-399). Writer status shows the effective budget, ceiling and switch state next tostep_age_ms. Eng decides what happens to an abandoned preparation that ignores cancellation, against the #5373 rule that a root waits for an abandoned preparation (see G1). (amended: CEO, spec review L1/L4/C3, provisional defaults for Eng to confirm) Hard ceiling default:persistence.max_claim_ms(600 s)persistence.preparation_ceiling_ms(600 s) (amended: DX). Abandoned await: keep the #5373 root block;once the ceiling passes the consumer finishes the request(amended: Eng, both voices; the request's claim was already released at the budget and may belong to another consumer, so the ceiling bounds the zombie, not the request — mechanism in 1.9) and the syncfailedwithpreparation_stalledthrough the direct route andexits with a distinct exit code and(amended: DX, no new exit number: the managed drain already has an exit contract,next_action(not 143)sync-drain.ts:23-26,330-358) endsoutcome: resumablewith a newstop_reason: preparation_abandoned, exit 0,next.safe_to_loop: true, printing the drain JSON before it exits, so the zombie dies with the process; (Eng: the owning consumer may live in a different process than the CLI,sync-persistence-delegate.ts, so exiting the CLI does not always end the owner's await; the mechanism must cover the actual owner); the next pass's claim-time counter and converters hold the entry. Group clock: when member k expires, members k and later are released in order and the abort is sent to their in-flight preparations; members before k that prepared keep their results and publish. Replace theboundedpredicate with a per-kind budget:remember/put_page/edit_pagekeep 30 s (preparationMs);managed_sync_*members getpersistence.sync_preparation_ms(default 120 s); maintenance and every other kind getmin(persistence.max_claim_ms, 300 s)persistence.maintenance_preparation_ms(amended: Eng, default lowered to 120 s: the adoption preparer is put_page-sized, and 300 s × 2 attempts × two poisoned writes on one serial root would pass the drain's 900 s progress window). The group path passes the same budget intoexecuteClaimedGroupand aborts the member'spreparewithpreparation_deadlinethrough an(amended: Eng, see 1.8). On expiry, the member is released withAbortSignalthe prepare functions already accept for put_pageblocked_reason = 'preparation_deadline'exactly as single put_page writes are today, and the group continues with the members that prepared (independent put_pages) or releases the later ones in order (sync groups, which must stay ordered).1.2 A second deadline on the same request holds it instead of requeueing it. (amended: CEO) The attempt counter must also count the kill case (exact rule below: a deadline release, or a reclaim of an expired claim whose
claim_phasewaspreparing), never only on release: in the reporter's loop the watchdog kills the process, nothing is released, and a release-time counter never reaches its limit.The hold is written by the consumer in the same transaction that finishes the request (not later by the sync), using theThe plan must specify the cursor transition: timed-out request → held manifest entry → valid predecessor for the next entry (reusesync-holds.tswriter that already takes atx, so it cannot be blocked by the source-wide gate (1.2b).advanceHeld), covering a first, middle and last group member, several admitted windows, lanes, delete, rename, restart before the cursor consumes the failure, and checkpoint finalization.sync.holds=failand company-brain sources keep failing instead of holding (sync-run.ts:432-437). The fix command isgbrain sources retry-held <id>followed by the same sync;gbrain sync --retry-helddoes not exist (commands/sync/args.ts:171-186). (amended: CEO, spec review) Counting rule: the counter increments on apreparation_deadlinerelease and on a reclaim of a request whose lease expired while itsclaim_phasewaspreparing(the kill case); it does not increment onconsumer_stoppingor a graceful shutdown release, and it resets when the request commits. The limit is checked at claim: a request already atpersistence.max_preparation_attempts(default 2) is finishedfailedwithpreparation_stalledwithout preparing again. A preparation timeout while the database is unreachable does not count; the probe is the claim renewal itself (direct route for single writes, ordinary pool for groups): if renewals fail the claim is lost (claim_lost), which never increments (amended: CEO, spec review N7). A request that hits the hard ceiling (1.1) has its counter set to the limit, because an overrun already proves the await ignored cancellation; the ceiling path therefore fails it on the first overrun (N2). For a group,the renewal stamp records which members were preparing at that moment(amended: Eng, outside voice: a renewal-only stamp misses a kill before the first renewal or between waves) each wave durably marks its dispatched members (their own token, start and step) before launching them, and the expired-claim transition charges only marked members, atomically, before it clears the token (consumer.ts:436-442on GBRA-45); undispatched followers are never charged (N5). PGLite reclaims throughreleaseAbandonedClaims(effect-journal.ts:193-195), which charges the same way (amended: Eng). An outage longer than the lease charges in-flight members at most once per outage (restated, amended: Eng: renewal failure cannot prove a later reclaim must not count); the breaker's systemic path keeps that ambiguity from becoming file holds. When a release brings the counter to the limit, the request is finishedfailedat that release; the claim-time check remains for the kill case. Hold kinds (amended: Eng): import members hold as today's entries; delete members get apreparation_stalleddelete hold (upstream_versionnull, cleared by retry-held, a version change or the file reappearing);managed_sync_checkpointnever holds (it fails, the run endsblocked, the next run retries it). Foreground and maintenance writes are counted too (a poisoned foreground write would otherwise be re-claimed ahead of the sync by foreground priority) and finish with a terminalpreparation_stalledreceipt to their waiting caller; that is a public contract change with its own behavior-change row and aput_page wait_mstest (Decision 59, Taste). (amended: CEO, spec review F1; supersedes "written by the consumer" above, see Decision 25) The failed receipt is the durable record; the sync converts it into a hold through the existing converters (holdFailedFenceRequestin-run,convertBlockedCursorat the start of the next run), which already build the fullHeldEntryand calladvanceHeld, now behind the narrowed gate (1.2b). The consumer does not know the manifest entry, run id or screen run, so it does not write holds. Both converters today accept only fence and content refusals (fenceReceiptLocation,isContentRefusal, the compactedinvalid_params/take_row_collisioncase,sync-run.ts:400-403); they gain apreparation_stalledbranch (amended: CEO, spec review N8). (amended: CEO, spec review N10)preparation_stalledreceipts are converted in-run as they fail, through the same path as fence refusals, so the cursor advances past them; the breaker (1.5) counts them as they arrive, and at the threshold-th receipt the run stops, flags the trip in its cursor, and converts neither that receipt nor any later one. (Eng design note, M1: the renewal probe does not see a partial outage that kills only the ordinary pool while direct renewals succeed; the breaker covers the mass case.) The cursor transition therefore reuses existing code; the PR 1 design note lists the cases above and passes an Eng design-review gate before implementation. Today apreparation_deadlinerelease puts the row back toqueuedwith no attempt counter, so the next tick re-claims it and the stall repeats. Addpreparation_attemptstopersistence_requests(migrationv220v221 or later (amended: Eng: v220 is taken by GBRA-39'scapy/cat40-hard-fix,v220-persistence-client-request-id.ts), the next free number at merge time)incremented on each(amended: CEO, counting rule below). Atpreparation_deadlinereleasepersistence.max_preparation_attempts(default 2) the consumer finishes the requestfailedwith a new registry codepreparation_stalled(class(amended: DX) classretryable, actorhost_adminserver,retryable: falsebecause a terminal request never republishes under the same request_id and a new attempt needs a new sync, registry default fix read-only (gbrain sources status {source_id} --json, the registry scanner requires read-only defaults,error-registry.ts:31-36), actoragentlocally andhost_adminon the remote render likebuildHoldReport), the receipt names the last recorded step (1.3), and for amanaged_sync_import/deletemember the sync writes a git hold with codepreparation_stalled(sameop_checkpointshold family asinvalid_frontmatterandinvalid_fence, cleared by the next successful import of that path) so the run keeps going. Sync's final report counts these underheld, andgbrain sources status <id>lists them withgbrain sync --source <id> --no-pull --retry-heldgbrain sources retry-held <id>(amended: CEO) as the fix.1.2b (added: CEO) Narrow the hold gate.
convertBlockedCursor(sync-run.ts:404) andholdFailedFenceRequest(sync-run.ts:445-450) wait until no request on the whole source is unfinished before they write a fence hold, so a stuck preparation or a stream of maintenance writes keeps every fence hold pending forever. Narrow the wait to requests that can still change the held entry's outcome (same worktree and earlier in sequence, or the same run), and write down the invariant the source-wide wait protected before removing it. (amended: CEO, spec review N9) Candidate invariant for the Eng design note: no entry after the held one publishes a change that depends on the held entry's outcome (same path, either side of a rename, a delete of the same slug), and the cursor never checkpoints past an entry whose request is still unfinished. The narrowed gate ships only with that invariant written and tested. (amended: Eng, both voices) Settled design: (1) first cancel the failed entry's obsolete admitted suffix (cancelWindow,sync-run.ts:842; lanecancelRowsvialaneFallback), so queued same-run successors cannot create a circular wait behind a blocked root; (2) then wait only for requests that are still active descendants of that suffix, plus unfinished or recovery-bearing requests that intersect the entry's source incarnation and page identity: slug,page_id, normalized path/sourcePath and both rename endpoints (reuse and extendUNFINISHED_PAGE_REQUEST_SQL,sync-waivers.ts:28-38on GBRA-45; index-backed bypersistence_requests_sync_run_open/_pending); unrelated maintenance and foreground writes on other pages no longer block; (3) evaluate that predicate atomically with the hold write and cursor CAS under the established page-key → cursor lock order (sync-waivers.ts:51-64,sync-run.ts:151-173), never by taking page locks after the cursor. A hold never turns a failed predecessor receipt into a committed one; the successors are refrozen with a fresh dependency chain. Tests cover both completion orders (the entry fails before the next starts; a later lane already applying aborts at its lane turn) for import, rename and delete, a same-page foreground write, and an unrelated maintenance write. This is the direct cause of "neither message produced a hold".1.3 Name the step. Extend
ClaimPhaseClockwithstep: string | nullandwaiting_on: ~~'pool' | 'lock' | 'git' | 'fs' | 'model' | null~~ 'git' | 'fs' | 'db' | 'pool' | 'unknown'(amended: CEO, spec review: one enum;lockis not observable without server correlation, deferred with E6);prepareManagedSyncMutation,preparePageMutation,prepareFactFenceAdoptionand the link resolver callenterClaimStep(clock, 'origin_check')etc. at each await boundary (about 12 call sites, no new statements: the renewal already stores the stamp).The pool wrapper marks(amended: CEO, refuted:waiting_on: 'pool'while a query waits for a connection (postgres.js exposes the queue;ConnectionManageralready counts it forwriter status --probe).src/core/pool-gauge.ts:5-14says there are no public checkout counters)waiting_onis set only from an observed boundary:git/fswhen that await is the current step,dbwhen a query is in flight,poolonly if the checkout start and acquisition are instrumented in gbrain's own wrapper, otherwiseunknown. The sync progress line showsstalled <N>s on <step>instead of an ETA that assumes no stall (the issue's ETA complaint). (amended: DX) Today the line prints only onpage_committed(sync-drain.ts:182-189), so this needs a timer in the drain that reads the head'sclaim_phase.claimStateOfreturnsstep,step_age_msandwaiting_on;(amended: DX, both voices;health.tsturns apreparingclaim older thanmax_claim_msintoreason: 'preparation_stalled'withwhyquoting the step, replacingcause_unknownfor this case.WRITE_HEALTH_REASONSis a wire enum that older clients validate strictly,persistence/types.ts:26,82-86, so a new value would make an older thin client reject whole pending receipts) The verdict goes on writer status's and doctor'sclaimobject asclaim.stall { reason: 'preparation_overdue', step, step_age_ms, waiting_on, budget_ms }; receipt diagnostics keep their enum.preparation_overduenames the running state;preparation_stallednames only the terminal give-up, so the two never share a name. Missingstep/waiting_onfrom an older owner's stamp read asnull/unknown, never inferred.writer status --jsonand doctor'spersistence_write_stallcheck (amended: CEO, corrected name) print it.1.4 Pool starvation guard (only if Phase 0 proves it). (amended: CEO) Conditional: it is in PR 1 only if Phase 0 proves a cause inside the one-day box; otherwise it leaves PR 1 and the investigation continues on the issue. Ships only with Phase 0 proof (Q3). The rationale below is refuted:
readWriteSwitchesreads four kill-switch config keys, not the pool's long-hold budget (GBRA-45switches.ts:13-22,52-58); that budget lives inpool-budget.ts. If starvation is proven, fix the specific acquisition that violates the budget instead of adding a second cap. If a preparation awaits a pooled connection while the consumer holds every pooled connection in its own transactions, the consumer caps concurrent lane publications plus single preparations atpool.max - 2and reportswaiting_on: 'pool';readWriteSwitcheson the GBRA-45 branch already reads the pool's long-hold budget, so this reuses that budget rather than adding one. If Phase 0 proves a different cause, this item becomes the specific fix for that cause (alock_timeouton the preparation statements, a git timeout, or a settle on the hanging promise), with the forced probe from 0.3 as its test.1.5 (added: CEO) Systemic breaker (G6). Count
preparation_stalledholdsreceipts per run (amended: CEO, spec review C2) in the sync, which owns the run context, and stop the run with one systemic diagnostic above theGIT_HOLD_ESCALATE_*thresholds before converting them to holds. (amended: CEO, spec review N4) The run records the trip in its cursor; the next run'sconvertBlockedCursorsees the flag and refreezes those entries as fresh requests with the counter at zero instead of holding them. A tripped run therefore durably holds no healthy file; a run below the thresholds can hold at most threshold−1 entries (49 or 5%), the same exposure every other hold type already accepts. (amended: DX) The breaker callsreadSyncHoldPolicy/holdsEscalated(sync-holds.ts:484-501, honouringsync.hold_escalate_count/_pct; the trip point is the existing "greater than" rule over the run's screened imports), not the raw constants; the escalation text (today "a generator or a gbrain upgrade is likely writing them wrong") is routed by code. The breaker stop isoutcome: blocked,stop_reason: preparation_systemic, exit 1, withnext.command= writer status. (amended: Eng) The count rule alone is slow (51 entries × 240 s on a serial root is about 3.4 h), so a second trip fires after 5 consecutivepreparation_stalledentries with no commit between them. The trip and the identities of processed stalled receipts are recorded durably with the cursor CAS, so a restart neither double-counts a receipt nor loses the trip marker; the "greater than" rule is preserved exactly (a count threshold of 50 trips at 51).preparation_stalledholds written before the trip carry the run id; the next run re-screens every such hold of the tripped run (version-conditional, so newer holds are untouched). Outside a trip, apreparation_stalledhold also re-screens when the gbrain version changes (holdRescreenDue,sync-holds.ts:307-311, gains the code); otherwise it waits forsources retry-held, and its why says so. The existingGIT_HOLD_CAP=500listing cap applies to the new code.1.7 (added: DX) Operator contract for the new surfaces.
- Hold routing. A
preparation_stalledhold must never be routed to frontmatter repair. Today every non-fence, non-concurrent hold falls through togbrain repair frontmatterinholdRepairSteps(sync-holds.ts:319-345),gitHoldFix's default branch (:394-397),buildHoldReport(:622),held-reads.ts:133,189,sources-retry-held.ts:74-79and doctorgit-holds.ts:36. Add astalledcount toHoldRepairRouteand thesync-hold-summarycounters, apreparation_stalledcase ingitHoldFixwhose argv is the read-onlygbrain sources writer status --source <id> --jsonand whosethenis retry-held plus the option-preserving sync,gitHoldDocs→write-refusals.md#preparation_stalled, and extendtest/held-files-walkthrough.test.tswith a source holding preparation, frontmatter and fence holds together. - Option-preserving retry.
sources retry-held's follow-up sync drops--no-embedand other processing options (sources-retry-held.ts:53-56,78); emit a machine-readable command built likesyncResumeCommand(sync-reconcile.ts:230-234). - Drain no-progress detector. The drain fingerprint keys on
updated_atandclaim_expires_at(sync-drain.ts:283-284), which every lease renewal bumps (journal.ts:322,452), sodrain_stalledcan never fire while a claim is renewed; that is a likely reason the reporter got the watchdog (rc 143) instead ofblockedwithnext. Key it on state,blocked_reason, head id/state andclaim_phasephase/step/since, and addstall.step/stall.waiting_onto the drain stall object. (amended: Eng, outside voice) The no-progress rule must then become claim-aware: today it stops after a stable head for 30 s and 3 passes (sync-drain.ts:71-72on GBRA-45), shorter than every new budget, so a healthy 60-second preparation would be cut off. A live preparation is allowed its effective budget plus the ceiling allowance; renewals never count as progress; a missing or dead owner and an overdue publication are detected separately. Test a healthy preparation longer than 30 s and shorter than its budget. - Writer status advice. The blocker's
next_actiontells the agent to inspect writer status from inside writer status (diagnostics.ts:93-97). AddWRITER_NEXT_ACTIONSentries forpreparation_deadlineandpreparation_stalled; addoperation,intent_kind, owner process kind (sync/serve/jobs), pid and build version (stamped on the live claim, amended: Eng: committed consumer versions inwriter-versions.tsdo not prove the stuck owner's build) to the blockers query, so doctor and troubleshooting stop telling users to restart agbrain servethat is not running, and future reports need no raw SQL (Phase 0.1). - Runbook. One "catch-up stuck / held N files" runbook in
docs/guides/troubleshooting.md, linked from writer status, hold fixes,gbrain errorsand the AGENTS.md held-file bullet, branching between preparation stall, manual fence defect and systemic stop, with complete commands. For the reporter's preparation case:gbrain sources status default --json, then (after the cause is fixed or gbrain upgraded)gbrain sources retry-held default --json, thengbrain sync --source default --no-pull --no-embed --json, thengbrain sources status default --jsonto verify. Fence repair previews first and uses the generated hash-bound apply command. - Docs and generated artifacts.
docs/guides/live-sync.md(outcome rows for the two new stop reasons, timing-knob rows for the four keys and the switch, what turning the switch off restores),docs/guides/write-refusals.md("Managed sync drain stops" table,#preparation_stalled,#fence_unrenderable),error-catalogue.tssync_drain_*entries andSTOP_DOCS,docs/guides/error-codes.mdregenerated withbun run build:error-codes, AGENTS.md,docs/architecture/key-files/*, a troubleshooting symptom row.docs/guides/exit-codes.mdneeds no change because no exit number is added. - Behavior-change rows (
src/core/behavior-change-notice.ts): deadlines and holds on sync and maintenance writes (held content stays out of the index until retry-held), the fact adoption writing normalized text back tofacts.fact(a data change), the four new keys, and the switch name. - Upgrade and mixed versions. Old claim/renewal SQL ignores the counter (
journal.ts:403-414,450-459) and old renewals overwrite the stamp with the old shape (claim-phase.ts:30-31); old converters do not knowpreparation_stalled(sync-run.ts:400-403). Specify: the migration's default (0) for existing rows; that every owner and worker must run the new version for the guarantee (writer status shows each owner's version so the operator can verify), with the release notes naming which processes to restart; what an older CLI shows for a new receipt or hold (the code with its read-only fix). (amended: Eng) No protocol bump:PERSISTENCE_PROTOCOL_PREDICATEonly sets the GUC the request-protocol guard checks (protocol.ts:24,35-48), and every new autocommit claim/renewal/release/expiry statement keeps it. Both new codes go into the registry and the write-error allowlist socoordinator.ts:128-148does not demote them tostorage_error. Old sync converters treatpreparation_stalledas a plain failure and old hold readers fall through to frontmatter advice, so the receipt and holdmessagetext itself carries the correct command. The column ispreparation_attempts integer NOT NULL DEFAULT 0 CHECK (preparation_attempts >= 0), added throughsrc/schema.sqlplusbun run build:schema(regeneratingschema-embedded.generated.tsandpglite-schema.generated.ts) and the catalog goldens, following ENGINES.md worked example 1, with an idempotent migration registered bybun run build:schema-migrations; tests cover fresh and upgraded Postgres and PGLite with queued, running, failed and compacted rows. Tests cover old queued/running requests, old failed fence receipts and existing holds across the upgrade.
- Hold routing. A
1.8 (added: Eng, both voices) Group and lane path. The clock starts when a member is dispatched, not when 64 followers are claimed. The lease renews a mutable held set: a released member leaves it before its release statement runs, because today
renewGroupClaims(...).size === rows.length(group-publish.ts:343master,:487GBRA-45) would read one release as a lost lease, release the whole group asclaim_lostand block the root on the stuck member again — #6278 on the default path. When member k expires: stop dispatching, abort the in-flight suffix, release k withpreparation_deadline(charged) and later members withgroup_member_waiting(not charged); publish the contiguous prepared prefix 0..k-1 throughpublishGroup(sequential path when the prefix is shorter than 2;publishGroupassumes every supplied row is prepared,group-publish.ts:185-186,514-547), with deliberate handling of the lane group key, which is the original last request (sync-lanes.ts:144-147). Independentbatch:groups release only k.laneFallback(group-publish.ts:398-411on GBRA-45) must keep the expired member'spreparation_deadlinereason instead of releasing everyone asgroup_member_waiting, or a stuck lane member is never counted. A deadline abort is classified beforefinishUnpublishedFailureon both paths: today the sequential group loop turns{error: AbortError}into a terminalstorage_erroron the first deadline (group-publish.ts:542), and a Postgres cancel (57014) becomes uncounteddatabase_contention(coordinator.ts:136-139).1.9 (added: Eng) Abandoned preparations (G1 mechanism; Decision 54, Taste). The budget releases the claim; the zombie keeps blocking its own root (the #5373 barrier,
consumer.ts:421-423,553-555) until it settles or the ceiling, measured from claim start, passes. At the ceiling the consumer drops that root block, sets the request's attempts to the limit (an overrun proves cancellation is ignored, so the next claim fails itpreparation_stalled), and keeps the zombie inoutlivedwith its step, reported instatus()and writer status. A per-process zombie cap (default 1) bounds the connections a zombie can pin: at the cap the consumer stops claiming and reportsrestart_required. A one-shot CLI owner then fails stop: the drain endsresumable/preparation_abandonedand the process exits, which ends the zombie;next.safe_to_loopis true only for that case. A resident owner (serve, the jobs worker, autopilot; and the PGLite resident lock holder a CLI delegates to,sync-persistence-delegate.ts:115-137, where exiting the client does not end the owner's await) reportsrestart_requiredin writer status and the drain endsblockedwith the restart command; where a supervisor exists (autopilot) the restart path is tested.stop()waits on abandoned preparations only for a short grace (5 s after aborting them) instead of forever (consumer.ts:716-724on GBRA-45); renewals and publications keep their existing bounded waits. With the switch off, today's behaviour is unchanged.1.10 (added: Eng, both voices) Preparation outside the consumer.
sameContentAtOrigin(sync-run.ts:524-535) andwouldWaiveEntry/unchangedSyncImport(sync-waivers.ts:173-190) run the full sync preparer on the feeder's event loop, where the consumer deadline cannot see a hang. Race each against the sync budget; on timeout return "cannot waive" / keep the origin refusal (both already fail open on errors) and propagate run cancellation. No request exists yet, so nothing is counted or held.graduation-drain.ts:110builds a consumer with the same preparer and inherits the deadlines; the ~12 registered preparers that take no signal (connectors, file imports) get the race and ceiling only, and theirpreparation_stalledhas no hold path (connectors keep their own hold store).1.6 (added: CEO) Kill switch. The new deadlines and the attempt counter sit behind a
WRITE_SWITCHESentry (switches.tspattern on GBRA-45) so a bad default can be turned off without a release.
Tests: a two-process E2E (test/e2e/persistence-preparation-deadline.e2e.test.ts) that injects a never-resolving fault point (fault-points.ts, consumer:preparing, (amended: CEO) a new point: today only consumer:prepared exists, fault-points.ts:17) into one sync member of a 200-page managed catch-up and asserts: the member is released at the budget, the root keeps publishing, the second attempt holds the path with preparation_stalled, the run checkpoints, writer status --json showed step and waiting_on, and sync --retry-heldgbrain sources retry-held default then a sync (amended: CEO) with the fault removed clears the hold. Unit tests for the budget table, the attempt counter, the stamp shape and the health.ts mapping. The existing consumer.test.ts deadline tests stay and still pass unchanged. (amended: CEO) Added cases: the fault in two variants, one that honours the signal and one that ignores it (the second is the reporter's case); a kill-and-restart loop (timeout on the sync) that reaches the hold within the attempt limit; a fence hold that lands while unrelated maintenance writes on the same source are queued; the breaker; a deadline on a first, middle and last group member and under lanes, with pause/release points for both completion orders; a zombie preparation that settles after its request was re-claimed and never publishes; (amended: CEO, spec review N6) the ceiling path: a signal-ignoring fault past the hard ceiling finishes the request preparation_stalled through the direct route, the drain ends resumable/preparation_abandoned (amended: DX), and the next pass holds the entry; a group kill that charges only the members that were preparing; a breaker trip followed by a run that refreezes instead of holding. test/persistence-consumer-scheduling.test.ts:201-226 pins today's "a preparation ignoring its signal stays running" behaviour, which this plan deliberately changes. (amended: Eng) The exact legacy test stays and runs with the switch off; with the switch on, the non-cooperative variant asserts queued, blocked_reason='preparation_deadline', preparation_attempts=1, the root still blocked (active_preparations===1, attempts===1), no publication after the late resolve and conservation; a third variant crosses the injected ceiling and asserts the root is freed, attempts are at the limit, the next claim fails preparation_stalled and nothing publishes. The #5373 takeover and shutdown tests (:548-628) stay. Added (amended: Eng): lease held-set shrink (persistence-claim-lease.test.ts, deadline on member 2 of 6), laneFallback reason preserved (lanes=2, deadline in the second lane group, managed-sync-lanes.test.ts), abort never reaching finishUnpublishedFailure, prefix publish, early-kill and wave-kill accounting, PGLite reclaim counting, one outage never failing a member, memo sibling safety, zombie cap → restart_required/preparation_abandoned, bounded stop(), waiver/origin budget fail-open, delete-member hold and checkpoint failure, a healthy preparation longer than the drain's 30 s window, breaker consecutive trip and replay after restart, and a foreground put_page receiving preparation_stalled. Time-based tests use injected short budgets and controllable faults, never wall-clock sleeps.
Phase 2: fence writes never fail the write path (PR 2, stacked on PR 1 PR 1, amended: CEO)
(amended: CEO) Phase 2 moves into PR 1 (2.1, 2.2, the shrunk 2.3 doctor count and the new 2.6 are small and cause-independent, and remove the nine refusals per pass that surround the stall; the doctor count is the surface for 2.1's diagnostic, so it ships with it); 2.4 is folded into 1.2; 2.5 is deferred to TODOS.md. Added blast radius: src/core/fence-shared.ts (the codec), the v0.32.2 migration caller of fenceManaged, and cycle/extract-facts.ts:496-535 (a page whose rows stay unfenced can block the source's destructive reconciliation).
Files: src/core/facts/unfenced-facts.ts, src/core/facts-fence.ts, src/core/persistence/prepared-maintenance.ts, src/core/cycle/extract-facts.ts, src/core/persistence/sync-holds.ts, src/core/fence-repair/{reasons,census,hold-fix}.ts, src/core/repair/fences.ts, src/commands/doctor/checks/fence-integrity.ts, docs as above.
- 2.1 Normalize, then round-trip check before submission. (amended: evidence)
planFencenormalizes each legacy claim the way the parser does (trim, CRLF/CR → LF) before rendering, renders the fence, parses it back, and compares every assigned row'sclaim,visibilityandactiveagainst the normalized claim. The adoption'sapplywrites the normalized text back intofacts.factin the same transaction as therow_numadoption (the canonical projection would re-derive it from the fence anywayamended: Eng, refuted: the projection'sexpireFactsexpires and detaches any row whose(row_num, fact, visibility)differs from the fence,canonical-projections.ts:378-384on GBRA-45, and inserts a new row, so the write-back is mandatory, in the sameUPDATEthat setsrow_num, beforeapplyPreservingTakeResolutions; a test asserts the fact id survives adoption), andprepareFactFenceAdoptioncompares against the normalized claim. A claim that normalizes to empty (whitespace-only) is dropped from the adoption and recorded asfence_unrenderableinfailed_pages; any other row that still fails the round trip is dropped the same way with the differing character class. The remaining rows still adopt. (amended: CEO) Use the parser as the oracle instead of re-implementing its normalization: the normalized claim isparseFactsFence(renderFactsTable([row])).facts[0]. Adopt the row (and write the parsed claim back tofacts.factin the adoption transaction) only when it comes back active, non-empty, with the same visibility and metadata, and differs from the stored claim only by whitespace and line endings (trim, CRLF/CR → LF, NBSP). Anything else (~~x~~parsing back inactive,<br>turning into a newline, empty) is not adopted; the legacy row stays as it is (never deleted or expired to get past a guard), with a durable diagnostic that does not depend on a receipt that was never created, and a dropped row must not block the source's destructive fact reconciliation (cycle/extract-facts.ts:496-535). (amended: Eng; Decision 57, Taste) Not by subtracting the rows from the source-wide count: reconciliation'slistExistingFactsForPageincludes activerow_num IS NULLrows (extract-facts.ts:294-308) and classifies them as stale (:731-738), so they would be expired. The guard narrows from source-wide to per page: pages that still hold unadopted legacy rows are excluded from the reconcile slug set and the phantom pass's touched canonicals, other pages reconcile,legacyRowsPendingand its warning stay. A mixed-page test runs adoption and then a full reconcile and asserts the rejected row stays active with its id, embedding and provenance while another page reconciles.planFence's reuse match (unfenced-facts.ts:176-180) compares the normalized claim too. (amended: CEO, spec review) The accepted normalization set is exactly: JavaScriptString.prototype.trim(Unicode whitespace, including NBSP) at both ends and CRLF/CR → LF inside; any other difference between the stored and parsed claim rejects the row.Two legacy rows that normalize to the same claim stay two rows with distinct(amended: Eng, outside voice:row_nums (fence rows may repeat a claim); nothing is merged or deleted.extract-from-fence.ts:83-93marks a later active row with the same claim and source as a duplicate and reconciliation then treats it as stale, so two adopted equal rows would lose one) A second legacy row whose normalized claim and source equal an already-adopted or planned row is not adopted; it stays a legacy row with aduplicate_claimdiagnostic and nothing is merged or deleted. Identity is claim plus visibility (what the projection compares); other metadata follows the fence representation (for example confidence is rendered to two decimals,facts-fence.ts:355-357) and the projection's field update writes it, which the behavior-change row states. The unmanaged writer (fenceFilePage,unfenced-facts.ts:297-302) writes the normalized text back the same way, and a page with no remaining assignments is not submitted. A test checks that a withdrawal still matches after normalization (facts_preserve_withdrawalfires onUPDATE OF fact, andgbrain_fact_fingerprint_v1is not trim-stable for a leading tab or NBSP). - 2.2 Reclassify the invariant.
prepareFactFenceAdoption's mismatch stays as a last-line defence but throws(amended: DX: there is nostorage_errorclassinternalinternalclass,agent-output.ts:34, andstorage_errormeans "reading or writing durable storage failed",error-registry.ts:329) a new registered codefence_unrenderable(classserver, modelled onparser_regression) withreasontelling the planner diagnostic from the last-line throw,whynaming the row, notinvalid_params, so the agent protocol stops telling callers to fix their input. - 2.3
(amended: CEO) Once 2.1 stops submitting rows that cannot round-trip there is nothing doomed to resubmit, and a one-day suppression would also delay a corrected page. Shrink to:extract_factsstops resubmitting doomed pages. The cycle phase skips pages whose last adoption failed withfence_unrenderable/storage_errorwithin the last day (persistence_requestsis the ledger; no new table), reports them in its verification block, anddoctor'sfence_integritycounts them asunrenderable_legacy_factswith the exactgbrain facts fence --page <slug> --dry-runcommand.doctor'sfence_integritycountsunrenderable_legacy_factsfrom the planner's read-only result and names the pages.gbrain facts fencedoes not exist (commands/facts.ts:11-18exposes onlyrelink), so the advice namesgbrain doctor --jsonand the page slug instead. (amended: DX) The planner result and doctor carry a typed per-row record (source, page, fact id, reason, never the claim text) instead of prose;failed_pagesgets a stable token (FACTS_FENCE_FAILED: <slug> (fence_unrenderable: N row(s), <class>)) in the cycle and v0.32.2 migration outputs. There is no safe automatic fix, so the finding says the rows stay active and searchable and nothing is lost, usesnext: report(not a loop back to doctor), and its verify counts those rows. It never suggestsforget_factto clear the guard. - 2.6 (added: CEO, spec review C1) Maintenance writes on a page with a fence defect are not submitted.
(amended: Eng, both voices: one choke point)planFence(and any maintenance page write built on a stored body) runssubmitMaintenanceruns, for every intent that carries page content, the samescanCanonicalFencescheckcompileCanonicalProjectionsuses, over the whole submitted body and timeline (replaceOrInsertFactsFencereplaces only the first fence outside code,facts-fence.ts:583-587, so a second timeline fence survives every adoption — the likely source of the tworepeated_markerrefusals); a repair whose postimage is clean passes; a defect skips the page with the fence reason infailed_pagesinstead of producing aninvalid_paramsrefusal at preparation, and the census already lists the stored defect as afence_repaircandidate. This covers therepeated_markerrefusals if Phase 0.5 shows they came from maintenance writes. - 2.4 (amended: CEO, superseded by Decision 25: the sync converts the failed receipt into a hold behind the narrowed gate 1.2b; the consumer writes no holds)
A sync member refused for a fence defect is held in the same tick, by the consumer, not later by the sync process. WhenfinishUnpublishedFailurerecords a typedinvalid_fencefor amanaged_sync_importmember, the consumer writes the git hold inside the samecompleteWritetransaction (the hold writer insync-holds.tsalready takes atx). The sync process's own hold write becomes idempotent on the existing record. A watchdog kill between failure and hold can no longer lose the hold, which closes the "neither message produced a hold" gap from the report. - 2.5 (amended: CEO, deferred to TODOS.md: disjoint row numbers do not prove two fences merge without changing section context, superseded references or protected rows,
fence-repair/types.ts:54-56,88-98; "no row numbers" needs allocation, not concatenation)repeated_markergets a deterministic Tier 1 fix when the fences are mergeable. Two facts fences in one section whose rows do not collide (row_numsets disjoint, or the second fence has no row numbers) merge into one fence by concatenation; themanualtier remains for colliding rows. This follows the #6188 tier rules (deterministic, no model) and the fixture in Phase 0 exercises both branches.
Tests: unit round-trip property test over the renderer/parser (random claim text with pipes, newlines, quotes, unicode, 1k cases); unfenced-facts.test.ts drop-and-continue; E2E: a sync over a worktree with a repeated-marker page and a mergeable pair asserts one invalid_fence hold with tier: manual, one normalized merge, no and the run completes. (amended: CEO) The receipt of the refused request stays failed requests,failed (coordinator.ts:141-148 finishes it that way; the hold sits beside it), so assert "one failed receipt converted to one hold", not "no failed requests". The property test checks every column (claim, visibility, kind, validity, source, active), not only the claim.
Phase 3: repair and chronicle run on the owner host during a sync (PR 2 or PR 3, depending on Phase 0.1 PR 2, amended: CEO)
Files: src/core/fence-repair/repair-io.ts, src/core/persistence/prepared-maintenance.ts, src/core/persistence/identity.ts, src/commands/doctor/checks/*owner*, src/core/fence-repair/reasons.ts, docs/guides/repair.md, docs/guides/troubleshooting.md.
- 3.1 Say which it is.
ownerElsewheresplits intoowner_host_mismatch(binding owner host id ≠ this process's host id;whyprints both ids' first 8 chars and bothhost.jsonpaths) andowner_not_active(binding statedraining/recovering, with the recovery command).maintenancePreflightuses the same split. (amended: CEO) The preflight has more conditions than repair (missing binding, wrong source incarnation, missing coordination path, host mismatch, inactive state, missing local path;prepared-maintenance.ts:78-83); each gets its own reason. A worktree inrecovering(topology clone) ordraining(writer transfer) names the operation in progress. Remote/MCP callers (remote=true) get the host ids but not localhost.jsonpaths, which contain usernames. (amended: DX, both voices) Keepowner_unavailableas the code, since the drain branches on it (sync-drain.ts:63BLOCKED_HEAD_REASONS), and add a registryreasonsvocabulary:host_mismatch,transfer_in_progress(draining),clone_in_progress(recovering),binding_missing,incarnation_changed,coordination_path_missing,local_path_missing. One matrix gives each reason its what/why, actor,fix.next(waitfor known in-progress work,tell_user_to_runfor a host admin decision) and a read-only verify;retryable: falseat the site forhost_mismatchso agents do not retry forever (the code's class isretryable). Never claim or transfer ownership just to run maintenance (prepared-maintenance.ts:81-83). Print only observed local paths:getWorktreeBindingreturns paths registered for the calling host (ownership.ts:48-54), not the owner's identity home. The repair candidate side adds the matchingFENCE_REASONSentries and the OWNER list inhold-fix.ts:80-103.FENCE_REASONSgains the two entries withactor: host_adminand exact fixes;owner_unavailablestays as the generic fallback for a missing binding. - 3.2 (amended: CEO) Conditional on Phase 0.1 showing a host split; autopilot already bakes
GBRAIN_HOMEinto its wrapper (commands/autopilot.ts:772) and forwards the environment to its worker, so change propagation only where 0.1 finds the gap; thehost_identity_splitcheck and service-file changes are unapproved until 0.1 returns. Same machine, same host id. If Phase 0.1 shows the maintenance worker'sGBRAIN_HOMEdiffers from the CLI's (launchd vs shell),gbrain doctorgains ahost_identity_splitcheck that lists everyhost.jsonunder the known homes for this user and names the service file to fix, andgbrain jobs work/the autopilot plist inheritGBRAIN_HOMEexplicitly. No automatic identity merge: two ids is a user decision. - 3.3 (amended: CEO) The busy set today holds only queued/running/recovering requests (
repair-io.ts:92-98), so a path still ahead in the sync's frozen 13.6k-entry manifest is "not busy"; repairing it changes its bytes and the sync later refuses that entry on its raw hash (sync-prepare.ts:254-257,337-343). Add the unfinished cursor's not-yet-admitted manifest paths tobusy(or define how a repair refreezes that entry); repair runs for everything else. (amended: CEO, spec review C4) Entries that are already held are not busy: the sync does not retry a held entry until its bytes change, and a repair that changes them is exactly what makes the next sync re-screen it. So the reporter's three held candidates are repairable during the sync. (amended: Eng, outside voice) The busy query fails closed (today a failed read becomes an empty busy set,repair-io.ts:94-98), includes terminal rows with an open recovery and both rename endpoints, loads manifest occupancy for every unfinished cursor of the current incarnation, and is rechecked at coordinated admission of the repair write (a new sync can freeze the candidate while repair waits on its model call), at both preview and apply (repair/fences.ts:265,408,418). Tests add a failed busy query, both admission orders, and a new sync starting during the model wait. Tests add a candidate far beyond the admitted window and a repair racing admission. Repairs while a sync runs.fences.tsalready distinguishessync_in_progressper candidate (busy paths). Keep that, but let candidates whose path is not busy repair during the sync (today a source with any unfinishedmanaged-synccursor skips every candidate viasyncUnfinished). The repair's write goes through the coordinator as a maintenance request, which Phase 1 bounds, and GBRA-45's foreground priority lets it jump the queue.
Tests: unit for the split reasons; E2E with two GBRAIN_HOMEs on one machine asserting the doctor check and the reason text; E2E running gbrain repair fences --source default --apply during a live catch-up and asserting the non-busy candidate repairs and the busy one is sync_in_progress.
Phase 4: prove it on the reporter's shape (gate before merge)
- 4.1 Run the Phase 0.2 fixture against the final branch on Ubicloud (16 vCPU, PgBouncer transaction mode, 57 ms injected latency as GBRA-45's bench does):
assert one pass drains 13.6k entries, zero(amended: CEO) assert the G5 criteria: no stall caused by one request, steady throughput within 20% of the GBRA-45 bench on the same fixture and RTT, every pass checkpoints and the next resumes (amended: DX: one pass drains the fixture), every seeded fence page is held or adopted with a reason,sync_deadline_stop, every seeded fence page is held or normalized with a reason,fence_repairin a concurrent maintenance job repairs the non-busy candidates, andwriter statusnever reportscause_unknown.fence_repairin a concurrent maintenance job repairs the candidates outside the busy set,writer statusnames the step of any preparation older than its budget, and foregroundput_pagep95 during the catch-up stays within the bench's foreground row. Add a second scenario with several poisoned entries and one with a database outage and recovery (the breaker, G6). (amended: CEO, spec review K6) PR 1's gate asserts the stall, hold, breaker, adoption and throughput criteria; the concurrentfence_repairassertions gate PR 2. (amended: DX) PR 1's gate also asserts time to hold ≤ budget × attempts + slack, that every hold surface's printed fix for apreparation_stalledhold is the writer-status/retry-held route (never frontmatter repair), that a stalled claim producesdrain_stalledwith the step instead of a watchdog stop, and a shell-wrapper contract test over synced, resumable (preparation_abandoned), blocked (preparation_systemic) and external timeout. The repository's full gate on current master still applies; this workload run does not replace it. - 4.2 Mirror the before/after table (pages/min, stalls, holds by reason, repair outcomes) into gbrain-evals as the measured verdict for this feature, per the project rule.
- 4.3 Ask the reporting agent to run the released build on the real brain and confirm on #6278; close when the pass completes.
Sequencing, ownership, versions
- Branch from
capy/sync-feeder-fast-writes(GBRA-45, merging next), because it rewritesconsumer.ts,group-publish.ts,journal.ts,sync-prepare.tsandsync-holds.ts; branching from master would conflict on the same hunks. Merge master in with merge commits after GBRA-45 lands. PR 1 (Phase 1 + Phase 0 probes) ships alone: it is the stall fix. PR 2 (Phases 2–3) stacks on it.(amended: CEO, see the two-PR split below) Versions: master's VERSION + one PATCH at merge time; migration number taken at merge time (highest on master and GBRA-45 is v219; v220 is claimed by GBRA-39, amended: Eng). Register with GBRA-40 for the queue.- Owner overlap to coordinate: GBRA-39 (
#6271, facts withdrawal and memory-prepare) touchesops/facts.ts, not the fence adoption path; GBRA-58 (#5575) planspersistence/effects.tsandops/facts.ts; neither touchesunfenced-facts.tsorrepair/fences.ts. Effort: Phase 0 one day; Phase 1 two days; Phase 2 two days; Phase 3 one day; Phase 4 half a day plus gate time. Serial, one thread with lanes for Phase 2 and 3 after PR 1's branch exists.- (amended: CEO) Two PRs, not three. PR 1 (containment, cause-independent): 1.1-1.3 with 1.2b, 1.5, 1.6, 1.7 (amended: DX), 1.8-1.10 (amended: Eng), Phase 2 (2.1, 2.2, 2.3 doctor count, 2.6), the Phase 0 probes, and 1.4/the cause-specific fix only if Phase 0 proves a cause within the day. PR 2 (repair during sync): Phase 3. PR 1 depends on GBRA-45 merging first (it branches from it and uses
WRITE_SWITCHES); if GBRA-45 slips, PR 1 waits rather than re-basing onto master, because both rewrite the same hunks. If PR 1's review load is too large, the fallback split is cancellation + counter + gate first, the adoption work second. The Phase 0.1 comment to the reporter goes out now. Revised effort:PR 1 about three days human / one day CC+gstack(amended: Eng) PR 1 about five days human / two days CC+gstack (four lanes: A persistence core, B sync-run/drain/holds after A's migration and claim stamp land, C facts/cycle/doctor in parallel, D docs last); PR 2 about two days human / half a day CC+gstack; plus gates.
Open questions for review
- Q1. (answered: CEO, both voices) Constant, config-settable per-member budget plus an outer hard ceiling; do not scale it with RTT (queue delay would inflate the budget exactly when containment is needed, and GBRA-45 adapts group size from publication apply time, not preparation tails). Stamp step age so headroom is visible. Default budgets: 120 s for a sync member and
300 s120 s (amended: Eng) for maintenance are guesses from the 57 ms bench (a group of four prepares in about 3 s there). The CEO/Eng review should decide whether the sync budget scales with the observed round-trip (GBRA-45 measures it) instead of a constant. - Q2. (answered: CEO, both voices) Both, at different layers: the receipt finishes
failedwithpreparation_stalledand the path is held so the cursor advances, but only with the counter (1.2), the sync-side conversion behind the narrowed gate (1.2b), and the breaker (G6). Hold vs fail: after two deadlines, hold the path (keeps the catch-up going, user sees aheldcount) or fail the request (the receipt is more visible but the run stalls until retried). The plan says hold, to match #6188's design. - Q3. (answered: CEO, both voices) No; the long-hold and lane caps already exist and the stated rationale is refuted. Should Phase 1.4's concurrency cap ship even if Phase 0 does not prove starvation? It is cheap, but an unproven guard is the kind of surface patch AGENTS.md warns against.
- Q4. (answered: CEO, both voices) Out of radius; deferred to TODOS.md. Phase 2.5's merge-on-no-collision is new deterministic repair logic. Is it in radius, or does it go to TODOS.md?
Review record
Run notes
- Driver: gstack
/autoplan(SKILL.md read from disk and followed by hand), run by a Capy subagent of GBRA-59 on 2026-10-07 against master 7aa2caa0 andorigin/capy/sync-feeder-fast-writes(GBRA-45, head d00f4d03). Restore copy of the original plan:~/.capy/work/gbra59-autoplan/restore-original.md. - Capy adaptations: no Skill tool, slash commands, AskUserQuestion or Claude hooks exist here.
gstack-skill-startran (SESSION_KIND interactive, PROTO 1) but its hooks (phase-publication guard, AUQ hooks) are not enforced on this host. Every question was auto-decided with the six principles; User Challenges are collected for the final gate instead of asked. The snapshot tool'sinit/create/amendsteps were not used because they require an## Implementation planheading the parent asked not to add; the methodology bundles were generated with itsmethodologycommand and given to the native voices. Amendments are marked inline with "(amended: PHASE)". - Outside voice: the Codex CLI is not installed on this machine (
command -v codexfails, CODEX_MODEnot_installed). In every phase the outside voice is anopenai/gpt-6.1-sol(reasoning high) subagent prompted with the skill's Codex filesystem-boundary prefix and the phase's review dimensions in the driver's words. It is recorded as "gpt-6.1-sol (Codex substitute)", not as Codex. - Native voice:
anthropic/claude-opus-5-5(reasoning high) subagent given the phase's methodology file and the plan. Both voices ran read-only on the shared machine and had to verify the "What the code says today" claims at file:line. - Design review (Phase 2): skipped. The plan has no UI scope (no screens, components or layouts; the user-facing surface is CLI/JSON output, which the DX phase covers).
- Parent evidence folded in before the CEO dispatch (marked "amended: evidence"): the 24-shape round-trip probe (
~/.capy/work/gbra59-autoplan/rt.ts).
Phase 1: CEO review (SELECTIVE EXPANSION)
Voices. Native (claude-opus-5-5): 6/10, "right problem, not ready to implement as written". Outside (gpt-6.1-sol, Codex substitute): 4/10, "revise before implementation: the plan treats a deadline as cancellation and a terminal receipt as forward progress". Full outputs: ~/.capy/work/gbra59-autoplan/ceo-native.md, ceo-outside.md.
CEO DUAL VOICES — CONSENSUS TABLE:
Dimension Claude Codex-sub Consensus
1. Premises valid? partly partly CONFIRMED partly (claims 1,3,5,6 need corrections)
2. Right problem to solve? yes yes CONFIRMED yes (root liveness + hold gate)
3. Scope calibration correct? partly partly CONFIRMED partly (cut 2.5/1.4; add cancel, counter, gate)
4. Alternatives sufficiently explored? partly no CONFIRMED gap (minimal containment never compared)
5. Operational risks covered? no partly CONFIRMED gap (zombies, kill loop, hold flood, manifest race)
6. 6-month trajectory sound? partly partly CONFIRMED partly (deadline without cancel breeds zombie bugs)
Outside voice is a gpt-6.1-sol stand-in for Codex; "CONFIRMED" here means both completed voices agree.
Code-claim verification (both voices, re-checked by the driver).
| Claim | Verdict | Evidence |
|---|---|---|
| 1 No deadline for sync/maintenance | PARTLY | Predicate verified consumer.ts:536-537; group path no deadline group-publish.ts:341-357. Refuted parts: group renewals use the ordinary pool (journal.ts:321-325); the deadline does not race the promise (consumer.ts:539-552); no signal reaches sync/maintenance preparers (service.ts:67-68, sync-prepare.ts:207, consumer.ts:615). |
| 2 Step not named | VERIFIED | claim-phase.ts:18-31, health.ts:17-25. Added: syncGit is sync execFileSync with 30 s timeout (sync-discovery.ts:50-52), so git is not the unbounded wait. |
| 3 Different pools | PARTLY | Single path only. Caps exist: pool-budget.ts:15-24, pool-capacity.ts:9-25, sync-group.ts:48-61. src/core/pool-gauge.ts:5-14: no checkout counters. |
| 4 Adoption doomed | VERIFIED, wider | prepared-maintenance.ts:291-293; 4/24 shapes reproduced by both voices; extra shapes ~~x~~→inactive, <br>→newline, lone CR, NBSP (fence-shared.ts:30-54,76-101). Refuted sub-claim: failed_pages does carry the text (unfenced-facts.ts:256-257). Fresh attempt id per pass: prepared-maintenance.ts:262-266. |
| 5 repeated_marker not held | PARTLY | canonical-projections.ts:295-297, reasons.ts:66 verified. Watchdog-loses-hold refuted (sync-run.ts:396-421 re-holds next run); real cause is the source-wide gate sync-run.ts:404,445-450 (GBRA-45 :417,448-469). Screen holds residual fences pre-admission (sync-screen.ts:85). "#6218" unverified; the work is #6188 E10. |
| 6 owner_unavailable | PARTLY | repair-io.ts:85 (function loadFenceSource), identity.ts:37,55-59, fences.ts:264-268 verified. Refuted: SIGTERM leaves binding recovering (only topology-clone.ts:139-143, ownership.ts:273; requests use journal.ts:630). Preflight has more conditions (prepared-maintenance.ts:78-83). host.json path is <GBRAIN_HOME>/.gbrain/persistence/host.json (config.ts:1865-1881). |
Also refuted in the plan body: gbrain sync --retry-held (does not exist, commands/sync/args.ts:171-186); gbrain facts fence (does not exist, commands/facts.ts:11-18); doctor check persistence_stalled_claims (is persistence_write_stall, doctor/checks/persistence-requests.ts:131-144); readWriteSwitches reads the long-hold budget (it reads kill switches, GBRA-45 switches.ts:13-22); fault point consumer:preparing (only consumer:prepared, fault-points.ts:17); G5 "≥300 pages/min" (bench: 152.8 at 57 ms, six lanes); fixture bench/sync-catchup (is scripts/bench/managed-sync-catchup.ts).
Step 0. 0A premise: the real problem is that one unfinished await stops a root with no sign, plus a hold mechanism that needs the whole source quiet; doing nothing costs the reporter about 0.8 pages/min. The plan attacked the symptom (a deadline) more than the mechanism (cancellation and the gate). 0B existing code: see "What already exists" below. 0C dream state: current, one await silently holds a root for an hour and fence failures loop; this plan (as amended), stalls are bounded, named and held, repair runs beside sync; 12-month ideal, every write-path await is cancellable and self-describing, bad input never reaches submission, repair runs through the coordinator with manifest awareness. 0D alternatives: A) plan as written (fails: deadline without cancel, release-time counter); B) minimal "bound + four-shape normalize" (fails: still no cancel, no hold under the gate, owner_unavailable untouched); C) containment invariant (cancel, claim-time counter, narrowed gate, parser oracle, step stamps, breaker) plus manifest-aware repair. C chosen (P1 completeness, smaller than A in new surface). 0E mode: SELECTIVE EXPANSION (auto-decided per autoplan override). 0G cherry-picks: E1-E9 in the scope table below. 0H spec review loop: see below. 0I temporal: hour 1 the implementer needs the #5373 root-block rule and which preparers honour a signal (only remember/put_page/edit_page); hours 2-3 ordering of a group member released at the deadline under lanes (laneFallback, cancel vs release); hours 4-5 the sync-run.ts gate, protocol predicate for the new column, GBRA-45's preparationReads memo; hour 6+ time-based test flakiness (inject budgets and faults, no sleeps).
| # | Proposal | Effort | Decision | Reasoning |
|---|---|---|---|---|
| E1 | Counter at claim / expired-claim reclaim | S | ACCEPTED (1.2) | Kill loop never releases |
| E2 | Narrow the hold gate | M | ACCEPTED (1.2b) | Direct cause of "no hold" |
| E3 | Parser-as-oracle normalization | S | ACCEPTED (2.1) | Codec changes >4 shapes |
| E4 | Cancel + race + isolate abandoned work | M | ACCEPTED (1.1, G1) | Signal alone frees nothing |
| E5 | Progress line names the stall | S | ACCEPTED (1.3) | Issue's ETA complaint |
| E6 | pg_stat_activity in writer status --probe |
M | DEFERRED (TODOS) | Reporter provides by hand |
| E7 | Systemic breaker | S | ACCEPTED (1.5, G6) | Outage must not read as success |
| E8 | Kill switch | S | ACCEPTED (1.6) | Reversible rollout |
| E9 | Manifest-aware repair busy set | M | ACCEPTED (3.3) | Keeps user's repair-during-sync direction safe |
| 2.5 | Repeated-marker merge | M | DEFERRED (TODOS) | No preservation proof |
| 1.4 | Unproven pool cap | S | SKIPPED unless proven | Rationale refuted |
Review sections (driver synthesis of both voices).
- Architecture: claimed request →
executeorexecuteClaimedGroup→prepare(no signal for sync/maintenance) →whileHeld→ on lease lossroot.untilwaits. New: per-member deadline, signal threaded to every preparer, claim-time counter, hold written in the failure transaction, breaker. Single point of failure: an await that ignores cancellation (G1 mechanism goes to Eng). New coupling consumer → sync-holds writer is justified (writer takes atx). Rollback: kill switch (1.6). - Error & Rescue: registry below; 4 GAPs found and closed by amendments.
- Security: low surface; new config keys are trusted-local. One Medium/Low: 3.1
whytext withhost.jsonpaths leaks usernames to remote callers; amended to omit paths forremote=true. - Data flow / edge cases: normalization paths (empty, whitespace-only, struck, CRLF, lone CR, NBSP,
<br>); async ordering for a member released at the deadline while a later lane is in its transaction; a zombie that settles after re-claim must not publish (token fence). Tests added to Phase 1. - Code quality: parser oracle removes duplicated normalization;
enterClaimStepat ~12 await boundaries is fine; no per-query wrapper just to mark pool waits. - Tests: matrix added to Phase 1 and Phase 2 (signal-ignoring fault, kill loop, busy-source hold, breaker, group positions, lane orders, zombie, all-column property test). 2am test: the reporter's
timeoutkill/restart loop against an injected hang ends with a hold and a completed pass. - Performance: step stamp rides the renewal; cancellation sends a Postgres cancel through postgres.js; no per-query overhead added.
- Observability: step in
writer statusandpersistence_write_stall; held counts by reason in the sync report andsources status; runbook inwrite-refusals.md; progress line names the stall. - Deployment: one additive column migration; older consumers ignore the counter (Eng checks the protocol predicate for mixed versions); kill switch; PR 1 is safe alone.
- Trajectory: reversibility 4/5 (switch + additive column). Regret scenarios: shipping 1.1 without cancellation (G1 quietly false), and an outage reported as a clean pass with thousands of holds (closed by G6).
- Design: skipped (no UI scope).
Error & Rescue registry.
| Codepath | Failure | Class | Rescued? | Action | User sees |
|---|---|---|---|---|---|
| Single prepare honouring signal | deadline | preparation_deadline |
Y | release; counter already +1 at claim | nothing until a hold |
| Prepare ignoring signal | never settles | none | was GAP, now Y (1.1/G1) | stamp, hold, isolate or exit distinctly | preparation_stalled with step |
| Group member | deadline | preparation_deadline |
Y (1.1) | release later members in order | partial progress |
| Process killed mid-prepare | no release | n/a | was GAP, now Y (1.2) | counter at claim | hold after N passes |
| attempts_max reached | — | preparation_stalled (retryable, host_admin) |
Y | fail receipt; sync converts it to a hold at end of run | held count + sources retry-held |
| Hold while source busy | gate waits | n/a | was GAP, now Y (1.2b) | narrowed gate | hold in the same run |
| Many stalls in one run | systemic | n/a | was GAP, now Y (1.5) | breaker | one systemic diagnostic |
| Adoption, non-roundtrip row | codec | fence_unrenderable / storage_error internal |
Y (2.1/2.2) | row not adopted, durable diagnostic | doctor count |
| Repair, host mismatch | — | owner_host_mismatch |
Y (3.1) | — | both host ids |
| Repair on manifest-tail path | later source_changed |
n/a | was GAP, now Y (3.3) | manifest-aware busy | sync_in_progress for that path |
Failure Modes registry.
CODEPATH | FAILURE MODE | RESCUED? | TEST? | USER SEES? | LOGGED?
----------------------------|---------------------------|----------|-------|-----------------------|--------
consumer.execute / group | await ignores cancel | Y (G1) | Y | preparation_stalled | Y
watchdog kill loop | counter never trips | Y (1.2) | Y | hold after N passes | Y
sync-run hold gate | hold blocked by busy src | Y (1.2b) | Y | hold same run | Y
hold flood | outage reads as success | Y (1.5) | Y | systemic diagnostic | Y
repair during sync | manifest-tail race | Y (3.3) | Y | sync_in_progress | Y
adoption codec | shapes beyond the four | Y (2.1) | Y | doctor count | Y
lane ordering after release | overtaking a held entry | Y (1.2) | Y | ordered progress | Y
host-id split | repair refused | Y (3.1) | Y | owner_host_mismatch | Y
No CRITICAL GAP remains after the amendments (every row was a gap in the original plan).
What already exists. Pool caps (pool-budget.ts, pool-capacity.ts, resolveLanes); claim-phase stamps (claim-phase.ts, #6176); stall threshold persistence.max_claim_ms (600 s); zombie tracking (keepUntilSettled/root.until, #5373); single-write deadline (put_page preparationMs); hold family (writeGitHold, op_checkpoints); hold escalation (GIT_HOLD_ESCALATE_*); hold re-screen (sources retry-held); fence normalization (fence-repair/normalize.ts); repair skip reasons (fences.ts sync_in_progress); lane order timeout (sync-lanes.ts, 60 s); bounded git (syncGit, 30 s); catch-up bench (scripts/bench/managed-sync-catchup.ts). The amended plan reuses each rather than adding a parallel mechanism.
NOT in scope. Deferred (TODOS): 2.5 repeated-marker merge; E6 pg_stat_activity capture. Rejected: unproven pool cap (1.4 without proof); one-day adoption suppression (old 2.3); model repair of manual-tier reasons; lease protocol or pool split changes; automatic identity merge.
Dream state delta. After this plan the writer bounds and names every stuck preparation and never lets one request or one fence stop a catch-up; what remains to the 12-month ideal is wait-cause evidence from the server (E6), cancellable awaits outside the consumer (sync-waivers.ts callers), and automatic merge of manual-tier fence defects.
Spec review loop (0H). Reviewer: claude-sonnet-5-5 subagent, both inputs (amended plan + ~/.capy/work/gbra59-autoplan/ceo-scope-summary.md). Three launches (the cap). Iteration 1: 6/10 FAIL, 25 issues (PR assignment contradictions, counter timing, consumer-written hold not buildable, breaker vs durable holds, maintenance-write fence case, busy set vs held candidates, enum drift). Iteration 2: 7.5/10 FAIL, 17 resolved, 9 new or partial (N1-N9). Iteration 3: 8.5/10 FAIL on one item (N10, conversion timing); N10 was then fixed as the reviewer prescribed (in-run conversion, breaker stops at threshold); not re-reviewed because the loop cap was reached. Remaining reviewer concerns: M1 (partial outage of the ordinary pool, noted for Eng) and the Taste rows 25 and 31. Metrics: iterations 3, issues found 35, fixed 34, remaining 1 (M1, accepted as an Eng note).
+====================================================================+
| MEGA PLAN REVIEW — COMPLETION SUMMARY (CEO) |
+====================================================================+
| Mode selected | SELECTIVE EXPANSION (autoplan override) |
| System Audit | 6 code claims: 1 verified, 1 verified-wider,|
| | 4 partly; 7 plan-body references refuted |
| Step 0 | Alternative C; 9 cherry-picks, 7 accepted |
| Section 1 (Arch) | 3 issues found |
| Section 2 (Errors) | 10 error paths mapped, 5 GAPS (all closed) |
| Section 3 (Security)| 1 issue found, 0 High severity |
| Section 4 (Data/UX) | 9 edge cases mapped, 0 unhandled after amend|
| Section 5 (Quality) | 1 issue found |
| Section 6 (Tests) | Diagram in registry, 8 gaps closed |
| Section 7 (Perf) | 0 issues found |
| Section 8 (Observ) | 2 gaps found (ETA, wait cause) |
| Section 9 (Deploy) | 2 risks flagged (protocol predicate, switch)|
| Section 10 (Future) | Reversibility: 4/5, debt items: 2 |
| Section 11 (Design) | SKIPPED (no UI scope) |
+--------------------------------------------------------------------+
| NOT in scope | written (7 items) |
| What already exists | written |
| Dream state delta | written |
| Error/rescue registry| 10 rows, 0 CRITICAL GAPS after amendments |
| Failure modes | 8 total, 0 CRITICAL GAPS after amendments |
| TODOS.md updates | 2 items proposed (not written; review pass) |
| Scope proposals | 11 proposed, 7 accepted |
| CEO plan | ~/.capy/work/gbra59-autoplan/ceo-scope-summary.md |
| Outside voice | gpt-6.1-sol (Codex substitute), completed |
| Lake Score | 4/4 recommendations chose complete option |
| Diagrams produced | consensus, error/rescue, failure modes |
| Stale diagrams found | 0 |
| Unresolved decisions | 1 taste (PR split), see Final gate |
+====================================================================+
- G1 is a liveness invariant: while the database works, no unpublished request keeps root execution past a hard ceiling; preparation is cancelled through a signal threaded to every preparer and its queries; the consumer races preparation against the deadline on the single and group paths; a late result never publishes; an abandoned await that ignores cancellation is stamped, held, and cannot keep the next pass from moving past its entry. Verify with a signal-honouring and a signal-ignoring
consumer:preparingfault on both paths. - The attempt counter increments at claim (or on expired-claim reclaim of a
preparingclaim), so the reporter's watchdog kill loop reaches the hold. Verify with a kill-and-restart E2E. - The failed
preparation_stalledreceipt is the durable record and the sync converts it into a hold with the existing converters (holdFailedFenceRequest,convertBlockedCursor→advanceHeld); the counter increments on deadline release and on reclaim of an expiredpreparingclaim, not on graceful release, resets on commit, and is checked at claim (default limit 2); the cursor transition is tested for first/middle/last group member, lanes, delete, rename, restart, checkpoint finalization;sync.holds=failand company-brain sources still fail. - The sync hold gate waits only for requests that can change the held entry's outcome, not every request on the source; verify a fence hold lands while unrelated maintenance writes are queued.
waiting_onreports only observed causes, elseunknown; the step is always named; the progress line saysstalled <N>s on <step>; doctor check namepersistence_write_stall.- A systemic breaker in the sync counts
preparation_stalledreceipts as they are converted in-run and, at theGIT_HOLD_ESCALATE_*threshold, stops with one diagnostic, flags the cursor and converts no more; the next run refreezes flagged entries with the counter at zero, so an outage holds at most threshold−1 healthy files; deadlines sit behind aWRITE_SWITCHESkill switch. Provisional defaults for Eng: hard ceiling =persistence.max_claim_ms; an abandoned await keeps the #5373 root block, the request is finishedpreparation_stalledat the ceiling and the sync exits with a distinct code; a group member expiring releases itself and later members in order. - Maintenance writes (adoption, maintenance page writes) run the canonical fence scan on the body before submission and skip a defective page with its reason (2.6).
- Fence adoption uses the parser as oracle: adopt (and write the parsed claim back to
facts.fact) only rows that come back active, non-empty, same visibility and metadata, differing only by whitespace/line endings; other rows are not adopted, never deleted, get a durable diagnostic, and do not block destructive reconciliation;prepareFactFenceAdoptionmismatch throwsstorage_errorclassinternal. Verify with an all-column property test seeded with the parent's four shapes plus~~x~~,<br>, lone CR, NBSP. - Repair during sync runs for every candidate outside a busy set that includes the unfinished cursor's not-yet-admitted manifest paths; owner refusals split per condition (host mismatch, incarnation, inactive state with the operation named, missing paths); remote callers do not get
host.jsonpaths. Verify a far-ahead manifest candidate and a repair racing admission. - Phase 0 is a one-day investigation time box gating only the cause-specific fix; the reporter comment (0.1, with blocker operation/kind/group key and the corrected host.json path) goes out now; 0.5 identifies which request failed
repeated_marker; repro compares GBRA-45 without and with the fix. - G5 acceptance: no stall caused by one request, throughput within 20% of the GBRA-45 bench (152.8 pages/min at 57 ms), every pass checkpoints and resumes, report separates processed from imported, foreground p95 within the bench row, plus multi-poison and outage scenarios; the full gate on current master still applies.
- Two PRs: PR 1 containment (Phase 1 with 1.2b, 1.5, 1.6; Phase 2: 2.1, 2.2, 2.3 doctor count, 2.6; Phase 0 probes; 1.4/cause-specific fix only if proven within the day); PR 2 repair during sync (Phase 3; 3.2 only if 0.1 shows a host split). Held entries are not in the repair busy set. 2.5 and the pg_stat_activity probe go to TODOS.md.
Phase 2: Design review
Skipped: no UI scope (the plan's surfaces are CLI text, JSON status and doctor checks; those are reviewed in DX). Not a completed review.
Phase 2.5: DX review (DX POLISH)
Scope trigger. The plan changes developer-facing CLI/MCP surfaces (writer status JSON, doctor checks, registry codes, config keys, hold reasons, sync stop outcomes) and gbrain's primary operator is an AI agent (AGENTS.md), so DX applies.
Voices. Native (claude-opus-5-5): 5/10 as written, about 8/10 with its checklist. Outside (gpt-6.1-sol, Codex substitute): 6/10, "revise the operator-contract and upgrade sections before coding". Both re-ran the codec probe (4/24) and confirmed the extra shapes. Both verified claims 1, 2, 4 and 6 and the amended claim 5 gate diagnosis; both refuted the CEO-phase G5 premise (the default non-TTY watchdog is progress-aware, sync-reconcile.ts:161-206) and the plan's sync-screen.ts:85 citation (that line is prepareTimeFenceHold; the pre-admission screen is sync-run.ts:317-321 with sync-screen.ts:128-150). Outside also corrected the lane default wording: GBRA-45's resolveLanes asks for 16 lanes and clamps to six on a pool of ten (sync-group.ts:53-71 there).
DX DUAL VOICES — CONSENSUS TABLE:
Dimension Claude Codex-sub Consensus
1. Getting started < 5 min? partly no CONFIRMED gap (hold in ~4 min, then misrouted fix)
2. API/CLI naming guessable? partly partly CONFIRMED partly (max_claim_ms repurposed; one name, two states)
3. Error messages actionable? partly partly CONFIRMED partly (frontmatter misroute, circular next_action, no `internal` class)
4. Docs findable & complete? partly partly CONFIRMED partly (live-sync, runbook, generated error codes missing)
5. Upgrade path safe? no partly CONFIRMED gap (wire enum, key meaning, mixed versions)
6. Dev environment friction-free? yes partly DISAGREE → resolved by M1 (writer status gains operation/kind/pid so no raw SQL)
Outside voice is a gpt-6.1-sol stand-in for Codex.
Single-voice findings verified by the driver. Drain no-progress detector defeated by renewals (native H2): the fingerprint key includes updated_at and claim_expires_at (sync-drain.ts:283-284), bumped by every renewal (journal.ts:322,452). Wire-enum break (native H4): isWriteDiagnostic rejects unknown reasons (persistence/types.ts:82-86). Breaker leaves pre-trip holds behind (outside 2): holdRescreenDue does not cover a new code (sync-holds.ts:307-311). ErrorClass has no internal (agent-output.ts:34); storage_error is class server (error-registry.ts:329). Drain exit contract (sync-drain.ts:23-26): outcomes synced | resumable | blocked.
Step 0. Product type: CLI + MCP developer tool whose primary operator is an AI agent. Persona: an agent running gbrain sync loops for its user on a managed Postgres brain; secondary, the host admin. Mode: DX POLISH. Competitive benchmark (patterns, not measured): Temporal separates heartbeat liveness from progress timeouts; Sidekiq retry then dead set with Retry/Delete; Kafka Connect errors.tolerance plus a dead-letter queue. The amended plan matches the Temporal split (renewal = heartbeat, step deadline = progress) and the Sidekiq dead-set shape (held entries plus retry-held). Magical moment: the sync's own holds_fix names the stuck file, the step it was stuck on and the three commands that clear it, with no digging. Lowest-effort vehicle: the existing hold report and writer status, not a new command.
Empathy narrative (native voice, condensed). "I start gbrain sync --source default --no-pull --json in my loop. Lines come, then stop, with a 22-hour ETA. Fifteen minutes later the watchdog kills the run and tells me to rerun; it stalls again. Writer status says cause_unknown and tells me to inspect writer status. Doctor tells me to restart gbrain serve, which isn't running. With the plan as first written the stall becomes a hold in four minutes, then holds_fix sends me to gbrain repair frontmatter, which finds nothing, and a version-behind client starts rejecting my pending receipts."
Developer journey map.
| Stage | Agent does | Friction (before DX amendments) | After DX amendments |
|---|---|---|---|
| 1 Discover | Watches [sync] N/M · ETA |
No line during a stall | Timer prints stalled Ns on <step> (1.3) |
| 2 Install/upgrade | gbrain upgrade |
Wire-enum break, max_claim_ms meaning, missing behavior rows |
claim.stall, new key family, rows, mixed-version section (1.3, 1.1, 1.7) |
| 3 First fix | Stall becomes a hold | Fix routed to frontmatter repair | preparation_stalled route in every hold surface (1.7) |
| 4 Real usage | until synced loop |
New exit number, drain_stalled dead |
resumable/blocked outcomes, fingerprint fixed (1.1, 1.7) |
| 5 Debug | writer status / doctor | Circular next_action, no operation, "restart serve" |
Next actions, operation/kind/pid (1.7) |
| 6 Roll back | kill switch | Undocumented effect | live-sync documents what off restores (1.7) |
TTHW (stall onset → right fix run). Today: never (3.3 h, four passes, no fix). Plan before DX: 10-15 min and six or more commands with a misroute. Target after DX: at most 5 min to a hold with the step named (budget 120 s × 2 attempts), then three commands (sources status, sources retry-held, the option-preserving sync), Competitive tier.
First-time confusion report. (1) preparation_stalled meant both "still stuck" and "gave up" → split into preparation_overdue/preparation_stalled. (2) max_claim_ms silently became a kill ceiling → separate keys. (3) A new exit number in a loop that already branches on drain outcomes → reuse outcomes. (4) failed_pages prose for unrenderable rows with a doctor loop → typed record, next: report. (5) Owner refusals as new codes would break the drain's owner_unavailable branch → reasons vocabulary.
DX scorecard.
| Pass | Before | After amendments | Main change |
|---|---|---|---|
| 1 Getting started | 4 | 8 | hold route + three-command runbook |
| 2 CLI/API design | 5 | 8 | key family, no new exit, one name per state |
| 3 Errors & debugging | 5 | 8 | read-only registry fixes, non-circular next actions, fence_unrenderable |
| 4 Docs | 5 | 8 | live-sync, runbook, generated error codes, AGENTS.md |
| 5 Upgrade | 4 | 7 | no wire-enum change, mixed-version section, behavior rows |
| 6 Dev env/tooling | 7 | 8 | fault points, writer status replaces raw SQL |
| 7 Community | 6 | 7 | evidence ask, gbrain-evals mirror, close-out |
| 8 Measurement | 5 | 8 | time-to-hold and printed-fix assertions, wrapper contract test |
| Overall | 5 | 8 |
DX implementation checklist (all accepted into 1.1, 1.3, 1.7, 2.2, 2.3, 3.1, 4.1):
-
preparation_stalledroute inHoldRepairRoute, summary counters,gitHoldFix,held-reads, retry-held text, doctorgit-holds, docs anchor; walkthrough test with mixed hold types - Option-preserving retry command from
sources retry-held - Drain fingerprint off lease columns;
stall.step/stall.waiting_on -
preparation_abandoned→resumable, exit 0,safe_to_loop;preparation_systemic→blocked, exit 1; catalogue,STOP_DOCS, write-refusals table; no new exit number -
claim.stall { reason: 'preparation_overdue', ... };WRITE_HEALTH_REASONSunchanged - One-pass gate restored
-
WRITER_NEXT_ACTIONS; blockers gain operation, intent kind, owner kind, pid -
fence_unrenderableregistered (server);preparation_stalledserver,retryable: false, read-only default fix, actor agent locally - Re-screen
preparation_stalledholds on version change and after a breaker trip - Separate key family with structured validation
- Breaker on
readSyncHoldPolicy/holdsEscalated, escalation text by code - Timer-driven stall line
- Docs: live-sync, write-refusals, troubleshooting runbook and symptom row, AGENTS.md, key-files,
build:error-codes - Behavior-change rows for deadlines/holds,
facts.factnormalization, keys, switch -
owner_unavailablereasons matrix,retryable: falseon host mismatch, observed paths only - Typed unrenderable-row record, stable
failed_pagestoken,next: report - Mixed-version section with restart guidance and tests
NOT in scope (DX). A new gbrain subcommand for stalls (the existing hold report and writer status carry it); automatic retry of preparation_stalled holds on a timer (version change and breaker trips only); changes to the v1 exit-code table.
What already exists (DX). Drain outcome contract and STOP_DOCS (sync-drain.ts), syncResumeCommand, holdRepairSteps/gitHoldFix, held-files-walkthrough test, readSyncHoldPolicy/holdsEscalated, WRITER_NEXT_ACTIONS, the registry reasons vocabulary pattern, build:error-codes, behavior-change-notice.ts.
User-direction flags raised by both DX voices (carried to the Final gate as User Challenges): maintenance writes are skipped with a typed diagnostic rather than held; "never stalls" holds while the database and control path work, and an await that ignores cancellation ends the run as resumable with the next pass holding the entry.
- Replaces the CEO block's "the sync exits with a distinct code": an abandoned preparation ends the drain
outcome: resumable,stop_reason: preparation_abandoned, exit 0,next.safe_to_loop: true, drain JSON printed first; the breaker endsoutcome: blocked,stop_reason: preparation_systemic, exit 1,next.command= writer status; no new exit number; both stop reasons get catalogue entries,STOP_DOCSand write-refusals rows; the mechanism covers the process that actually owns the consumer. Verify with a shell-wrapper contract test over synced, resumable, blocked and external timeout. - Replaces the CEO block's "hard ceiling =
persistence.max_claim_ms": new keyspersistence.sync_preparation_ms(120000),persistence.maintenance_preparation_ms(300000),persistence.preparation_ceiling_ms(600000, range 60000-3600000),persistence.max_preparation_attempts(2, range 1-10), validated through the structured error renderer;max_claim_mskeeps its doctor meaning; writer status shows effective budget, ceiling and switch state. - The running-overdue verdict lives on writer status and doctor
claim.stall { reason: 'preparation_overdue', step, step_age_ms, waiting_on, budget_ms };WRITE_HEALTH_REASONSand receipt diagnostics are unchanged; older stamps read as null/unknown. preparation_stalledis registered classserver,retryable: false, read-only default fixgbrain sources status {source_id} --json, actoragentlocally andhost_adminremotely;fence_unrenderableis registered classserverand used for both the planner diagnostic and the last-line throw (byreason); nointernalclass.- Every hold surface routes
preparation_stalledto writer status then retry-held plus an option-preserving sync, never to frontmatter repair;stalledcount inHoldRepairRouteand the summary; walkthrough test with preparation, frontmatter and fence holds together. - The drain fingerprint ignores lease columns and keys on state, blocked reason, head id/state and claim phase/step/since; a stalled claim produces
drain_stalledwith the step. Verify in the PR 1 gate. - Writer status
next_actionentries forpreparation_deadline/preparation_stalled; blockers report operation, intent kind, owner process kind and pid; the progress line is timer-driven and printsstalled <N>s on <step>. preparation_stalledholds re-screen on gbrain version change and, for holds written by a run that tripped the breaker, on the next run; otherwise they wait forsources retry-heldand their why says so. The breaker usesreadSyncHoldPolicy/holdsEscalatedand code-specific escalation text.- Owner refusals keep code
owner_unavailablewith reasonshost_mismatch,transfer_in_progress,clone_in_progress,binding_missing,incarnation_changed,coordination_path_missing,local_path_missing, each with what/why, actor,fix.nextand read-only verify;retryable: falseforhost_mismatch; only observed local paths printed;hold-fix.tsOWNER list updated. - Unrenderable legacy rows get a typed per-row record (source, page, fact id, reason, no claim text), a stable
failed_pagestoken,next: report, and a verify that counts them; neverforget_fact. - One troubleshooting runbook for "catch-up stuck / held N files" linked from writer status, hold fixes,
gbrain errorsand AGENTS.md; docs updated: live-sync (outcomes, knobs, switch semantics), write-refusals, error-codes regenerated, key-files, symptom row; behavior-change rows for deadlines/holds,facts.factnormalization, keys, switch. - A mixed-version section: migration default 0, every owner/worker must run the new version (writer status shows owner versions; release notes name the processes to restart), older CLIs show the code with its read-only fix; tests across the upgrade with old requests, receipts and holds.
- G5 one-pass goal restored: the PR 1 gate asserts one pass drains the fixture, time to hold ≤ budget × attempts + slack, and that the printed fix for a
preparation_stalledhold is the writer-status/retry-held route.
Phase 3: Eng review (runs last, reviews the CEO + DX amended plan)
Voices. Native (claude-opus-5-5): 6/10 as written, about 8.5/10 with its Critical/High fixes (architecture 6, code quality 7, tests 6, performance 5, security 8, errors 6, deploy 7). Outside (gpt-6.1-sol, Codex substitute): 6/10, "amend and re-review the owner ceiling, atomic hold transition and fact-preservation designs". Both re-grounded on GBRA-45 head 05c1aa5e (PR #6279). Full outputs: ~/.capy/work/gbra59-autoplan/eng-native.md, eng-outside.md.
ENG DUAL VOICES — CONSENSUS TABLE:
Dimension Claude Codex-sub Consensus
1. Architecture sound? partly partly CONFIRMED partly (group lease, ceiling model, owner lifecycle)
2. Test coverage sufficient? partly no CONFIRMED gap (14 gaps; kill accounting, drain timer, preservation)
3. Performance risks addressed? no partly CONFIRMED gap (blanket signals defeat GBRA-45 pipelining/memo)
4. Security threats covered? yes partly DISAGREE → resolved: busy set fails closed; diagnostics location-only
5. Error paths handled? partly partly CONFIRMED partly (abort → storage_error, lane reason loss, outage)
6. Deployment risk manageable? partly partly CONFIRMED partly (old owners keep stalling; v220 taken)
Outside voice is a gpt-6.1-sol stand-in for Codex.
Single-voice Critical findings, verified by the driver. Native C1 (group lease lost on a mid-group release): renewGroupClaims(...).size === rows.length at group-publish.ts:343 (master). Outside Critical (relaxed guard retires unadopted rows): listExistingFactsForPage selects active row_num IS NULL rows (cycle/extract-facts.ts:294-308) and the loop pushes every row without a matching fence row into stale (:731-738). Native H5 (write-back mandatory): GBRA-45 canonical-projections.ts:378-384 expires rows whose (row_num, fact, visibility) differ. Outside drain-timer finding: GBRA-45 sync-drain.ts:71-72 STALL_MS = 30_000, STALL_PASSES = 3. Outside stop() finding: GBRA-45 consumer.ts:724 loops on outlived forever. Native L2: origin/capy/cat40-hard-fix adds v220-persistence-client-request-id.ts.
Further code-claim corrections from Eng. Claim 3: a signalled executeRaw reservation is cancellable (postgres-engine.ts:2708-2744, cancellation.ts:17-41 on GBRA-45); transactions and begin are not. Claim 4: the projection does not re-derive the adopted row, it expires it (H5). Claim 6: adoption refusals that reached preparation imply the submitter passed the owner preflight unless sync.write_through is off (prepared-maintenance.ts:76-77). Claim 2 nuance: a released preparation_deadline row still reads cause_unknown on receipts (health.ts:13-24); only claim.stall fixes the running case.
Step 0 (scope challenge). The complexity gate trips (about 40 files, six or more new components). Not reduced (autoplan override: never reduce scope); every addition is in the blast radius of the files the plan already modifies and is required for G1/G3/G4 to hold. Sub-problems map to existing code: race → whileHeld; zombie tracking → keepUntilSettled/outlived; dispatch stamps → claim_phase (v217); hold conversion → holdFailedFenceRequest/convertBlockedCursor/advanceHeld; gate predicate → UNFINISHED_PAGE_REQUEST_SQL/NAMES_PAGE; breaker → readSyncHoldPolicy/holdsEscalated; switch → WRITE_SWITCHES; cancellable reads → reserveWithCancellation.
E1-E9 resolutions. E1 zombie: keep the barrier to the ceiling, then isolate with a per-process cap of 1; CLI owners fail-stop, resident owners report restart_required (Taste, Decision 54; outside wanted owner-level termination at the ceiling, which the cap + fail-stop delivers for CLIs). E2: race + step-boundary checks, signals only on unmemoized lock-prone raw statements, memos never take member signals, bench gate. E3: cancel the obsolete suffix, then an identity predicate checked atomically under page-key → cursor order. E4: per-member clocks from dispatch, mutable lease set, durable dispatch marks, prefix publish, reason-preserving laneFallback, abort classified before finishUnpublishedFailure. E5: same budget, fail open, nothing counted. E6: no protocol bump, additive column, allowlist entries, fix text in messages for old readers, build on the live claim. E7: legacy test kept for switch-off, rewritten variants for switch-on, plus a ceiling variant. E8: per-page guard (Taste, Decision 57). E9: plausible and likely: replaceOrInsertFactsFence replaces only the first fence, so a second timeline fence survives every adoption; 2.6 moves to submitMaintenance.
*Section 1, architecture (new components marked ).
service.ts dispatcher --(signal only to unmemoized lock-prone raw stmts)--> sync-prepare | prepared-maintenance(+adoption*) | page-prepare | link prep
consumer.execute --budget*(switches TTL snapshot*)--> claim-phase.enterClaimStep*(throwIfAborted, step, waiting_on)
| race(deadline*, claimLost) -> releaseUnpublishedClaim(reason, counter*)
| zombie registry* + ceiling* + cap* -> root.until drop / restart_required* ; bounded stop()*
| claim-time limit check* -> completeWrite(failed, preparation_stalled*)
+-> executeClaimedGroup: per-member clocks*, dispatch marks*(journal), held-set lease*(claim-lease),
prefix publishGroup*, laneFallback(reason-preserving*), abort classification*(coordinator)
expired_claims sweep (Postgres) / releaseAbandonedClaims (PGLite) --charge dispatched*--> preparation_attempts* (v221+)
sync-run converters --cancel suffix* -> identity gate* (page-key->cursor lock, CAS)--> preparationStalledHold*(sync-screen) -> advanceHeld -> sync-holds routing*
+-> breaker*(count + consecutive, durable trip) -> next-run refreeze / re-screen
sync-waivers / sameContentAtOrigin --budget race*, fail open-->
sync-drain: fingerprint*(state, claim_phase step) + claim-aware no-progress* -> stop reasons preparation_abandoned* / preparation_systemic*
unfenced-facts.planFence --parser oracle*--> submitMaintenance fence scan*(2.6) -> adoption apply (write-back in row_num UPDATE*)
extract-facts guard (per page*) ; doctor fence_integrity(unrenderable*) ; writer status claim.stall*, next actions*
[PR 2] repair-io busy set (fail closed*, manifest*, rename*, admission recheck*) ; owner_unavailable reasons*
Coupling added: consumer → journal dispatch marks (justified, crash accounting needs a durable boundary); sync-run → cancel helpers before conversion (existing helpers). Scaling: one extra statement per four-member wave (about 14 ms per page at 57 ms RTT, inside the bench's 20% gate). Rollback: WRITE_SWITCHES off restores today's behaviour, column stays (additive).
Section 2, code quality. One shared SQL constant for the gate predicate (no copies in both converters); enterClaimStep is the single cancellation and stamp point; memo rule stated once in group-publish.ts; no new class or service. Naming fixed in DX (preparation_overdue/preparation_stalled, key family).
Section 3, test review. The codepath → test map below; the full plan is on disk at ~/.gstack/projects/garrytan-gbrain/user-master-eng-review-test-plan-20261008-044354.md.
CODEPATH TYPE IN PLAN?
consumer single deadline race/release unit yes
non-coop ceiling isolation, attempts=limit unit added (E7 v3)
zombie cap -> restart_required / abandoned unit+E2E added
stop() bounded on zombie unit added
claim-time limit fail unit yes
group deadline first/mid/last unit+E2E yes
lease held-set shrink (C1) unit added
laneFallback reason preserved (H1) unit added
abort never -> finishUnpublishedFailure (H2) unit added
prefix publishGroup unit added
dispatch marks, only dispatched charged unit+E2E added
PGLite releaseAbandonedClaims counter unit added
outage charges once, never fails unit added
memo sibling safety unit added
signal threading throughput bench added (4.1 ±20%)
converters import/delete/checkpoint unit added (delete, checkpoint)
narrowed gate orders, same page, unrelated unit yes (same page added)
breaker count + consecutive + replay unit added (consecutive, replay)
waiver/origin budget fail-open unit added
drain fingerprint, claim-aware window unit added (window)
hold routing walkthrough unit yes (DX)
parser oracle property, all columns unit yes
adoption keeps fact id unit+pg added
duplicate normalized claim not adopted unit added
unmanaged writer write-back unit added
withdrawal fingerprint after normalize unit added
per-page reconcile guard keeps row active unit+pg added
2.6 second timeline fence skipped unit added
foreground put_page preparation_stalled unit added
mixed-version upgrade unit+pg yes (DX)
PR2 busy fail-closed, admission race, model wait unit+E2E added
Test pyramid holds (mostly unit, two E2E, one bench gate). Flakiness: injected clocks and fault barriers only. LLM/prompt changes: none, so no eval suite; the gbrain-evals mirror (4.2) is a measured-verdict record, not a model eval.
Section 4, performance. Blanket signal threading would defeat GBRA-45's pipelining and memo (H4) → limited to lock-prone raw statements, bench-gated. Budget reads fold into the switches.ts TTL snapshot (no per-claim config read). Dispatch marks add one statement per wave. Breaker consecutive rule cuts systemic detection from about 3.4 h to about 20 min. Maintenance budget lowered to 120 s keeps two poisoned writes inside the 900 s progress window.
Failure modes registry (after amendments).
| Path | Failure | Test | Handled | User sees | Critical gap? |
|---|---|---|---|---|---|
| Group lease after a member release | whole group lost, root blocked | added | 1.8 held set | progress | was CRITICAL, closed |
laneFallback |
stuck member never counted | added | 1.8 | hold after N | was CRITICAL, closed |
| Relaxed reconcile guard | unadopted rows expired | added | 1.2/2.1 per-page guard | rows stay active | was CRITICAL, closed |
| Write-back omitted | adopted row expired and re-inserted | added | 2.1 mandatory | stable ids | closed |
| Sequential group abort | healthy member failed storage_error |
added | 1.8 classification | correct code | closed |
| Memo with member signal | sibling aborted | added | 1.1 memo rule | none | closed |
| Drain timer vs budgets | healthy prep cut at 30 s | added | 1.7 claim-aware | none | closed |
| Zombie never settles | stop() hangs, pinned connection |
added | 1.9 cap + grace | restart_required | closed |
| Kill before first renewal | wrong members charged | added | 1.2 dispatch marks | correct hold | closed |
| PGLite reclaim | never counted | added | 1.2 | hold | closed |
| Delete member stall | no hold | added | 1.2 delete hold | hold | closed |
| Outage longer than lease | spurious charge | added | once per outage + breaker | none | bounded, accepted |
| Busy query error (PR 2) | repair on an admitted path | added | fail closed | sync_in_progress |
closed |
| Old resident owner | guarantee absent | upgrade test | restart guidance | writer status version | accepted (documented) |
NOT in scope (Eng). Publication-phase ceiling (TODOS "Ceiling for a stuck managed publication", wave 11); pg_stat_activity capture; repeated-marker merge (2.5); unproven pool cap; structural preservation of unadopted rows inside reconciliation (per-page guard chosen; TODO); Postgres claim-by-pid release.
What already exists (Eng). keepUntilSettled/root.until/outlived; claim_phase v217; releaseUnpublishedClaim; reserveWithCancellation; advanceHeld and both converters; NAMES_PAGE/UNFINISHED_PAGE_REQUEST_SQL; persistence_requests_sync_run_open index; readSyncHoldPolicy/holdsEscalated; WRITE_SWITCHES; cancelWindow/cancelRows; the scheduling, claim-loss, lanes and held-walkthrough tests. The existing TODO "Hard ceiling for a stuck managed write (W3.3b, #6176): reuse persistence.max_claim_ms … write_stalled after 3 releases" is superseded by this plan with two announced reversals: a separate ceiling key (DX) and code preparation_stalled after 2 attempts; PR 1 closes that TODO.
Worktree parallelization. Lane A persistence core (migration, claim-phase, consumer, group, journal, effect-journal, registry) → Lane B sync-run/drain/holds/waivers after A's migration and claim stamp land; Lane C facts/cycle/doctor fence in parallel with A; Lane D docs and behavior rows last. PR 2 starts after PR 1's branch exists.
Completion summary (Eng).
Step 0 scope challenge | scope kept (complexity gate tripped; all in blast radius)
Architecture | 6 issues (C1 lease, H3 ceiling, E1 owner lifecycle, E3 gate, E4 group, coupling ok)
Code quality | 4 issues (leftover keys/text, shared SQL constant, memo rule, naming)
Test review | diagram produced, 24 gaps added to the plan, test plan on disk
Performance | 4 issues (signal threading, budget snapshot, breaker latency, maintenance budget)
NOT in scope | written (6 items)
What already exists | written
Failure modes | 14 rows, 3 critical gaps found, 0 remaining
Outside voice | gpt-6.1-sol (Codex substitute), completed
Parallelization | 4 lanes, A+C parallel, B after A, D last
Unresolved decisions | 3 taste (54, 57, 59) to the gate
- Replaces the CEO block's "signal threaded to every preparer and its queries": cancellation is the consumer race plus
signal.throwIfAborted()inenterClaimStepat each step; a signal reaches only unmemoized raw statements that can block on a lock or pool reservation; shared memos (preparationReads,groupReads,readWriteSwitches,preparationConfigView, the basename chain) never take a member signal; PR 1 is gated on the GBRA-45 bench within 20%. - Replaces the CEO block's ceiling default: the ceiling bounds the zombie, not the request. Budget releases the claim; the zombie keeps its root block until it settles or the ceiling (from claim start) passes; then the root block drops, attempts are set to the limit, the zombie stays tracked; per-process zombie cap 1 → stop claiming,
restart_required; a CLI owner endsresumable/preparation_abandonedand exits (safe_to_looponly then); a resident owner (serve, jobs, autopilot, PGLite delegate) ends the drainblockedwith the restart command;stop()waits on abandoned preparations only 5 s after aborting them; switch off keeps today's behaviour. - Group path: per-member clocks from dispatch; the lease renews a mutable held set; member k expiring releases k charged and later members uncharged; the contiguous prepared prefix publishes;
batch:groups release only k;laneFallbackpreservespreparation_deadline; deadline aborts and Postgres cancels are classified beforefinishUnpublishedFailureon both paths. Verify with held-set, lanes=2 and abort-classification tests. - Each wave durably marks its dispatched members before launch; the expiry transition (Postgres sweep and PGLite
releaseAbandonedClaims) charges only marked members before clearing the token; an outage longer than the lease charges at most once; a release reaching the limit finishes the request there. - Hold kinds: import → hold, delete → delete hold (
upstream_versionnull), checkpoint → fail and endblocked; foreground and maintenance writes get a terminalpreparation_stalledreceipt with a behavior-change row and aput_page wait_mstest. - Hold gate: cancel the obsolete admitted suffix first; then wait only for active suffix descendants and unfinished or recovery-bearing requests intersecting the entry's incarnation, slug, page id, path/sourcePath and both rename endpoints (one shared SQL constant extending
UNFINISHED_PAGE_REQUEST_SQL); evaluate atomically with the hold write and cursor CAS under page-key → cursor lock order; never mark a failed predecessor committed. Verify both completion orders for import, rename and delete, a same-page foreground write and an unrelated maintenance write. - Breaker adds a consecutive trip (5 stalls with no commit between); the trip and processed receipt identities are durable with the cursor CAS; the "greater than" rule is kept exactly.
- The drain's no-progress rule is claim-aware: a live preparation is allowed its budget plus the ceiling allowance, renewals are never progress, dead owners and overdue publications are detected separately; verify a healthy 60 s preparation is not cut.
persistence.maintenance_preparation_msdefault 120000;persistence.preparation_ceiling_ms≥ max(budgets) + 30 s.- Waiver and origin-equivalence preparation outside the consumer races the sync budget and fails open, counting nothing; the ~12 signal-less preparers get the race and ceiling only.
- No protocol bump; every new autocommit statement keeps
PERSISTENCE_PROTOCOL_PREDICATE; both codes join the registry and write-error allowlist; receipt and hold messages carry the correct command for older readers; the live claim carries process kind, pid and build; migration v221 or later (preparation_attempts integer NOT NULL DEFAULT 0 CHECK (>= 0)) throughschema.sql+build:schema+ goldens +build:schema-migrations, tested fresh and upgraded on Postgres and PGLite. persistence-consumer-scheduling.test.ts:201-226stays verbatim under switch-off; switch-on variants assert queued/preparation_deadline/attempts=1/root blocked/no late publish/conservation, plus a ceiling variant; #5373 takeover and shutdown tests stay.- Adoption: the normalized claim is written in the same
UPDATEthat setsrow_num, beforeapplyPreservingTakeResolutions(the projection would otherwise expire the row); the fact id survives adoption; a duplicate normalized claim+source is not adopted (duplicate_claimdiagnostic); identity is claim+visibility and other metadata follows the fence representation; the unmanaged writer writes the normalized text too; a page with no assignments is not submitted; a withdrawal still matches after normalization. - The destructive reconcile guard narrows to per page: pages holding unadopted legacy rows are excluded from the reconcile slug set and phantom pass, other pages reconcile; verify a rejected row stays active with its id, embedding and provenance after adoption and a full reconcile.
- 2.6 runs in
submitMaintenancefor every content-carrying intent over the whole body and timeline; a clean repair postimage passes; verify a page with a second timeline fence is skipped before submission. - Phase 0.1 also captures
sync.write_throughand which process submitted the adoptions. - PR 2 busy set fails closed, includes open-recovery terminal rows and both rename endpoints, loads manifest occupancy for every unfinished cursor of the incarnation, and is rechecked at coordinated admission at both preview and apply; verify a failed busy query, both admission orders and a new sync starting during the model wait.
- PR 1 closes the TODOS entry "Hard ceiling for a stuck managed write (W3.3b, #6176)"; the publication-ceiling TODO stays open.
Decision Audit Trail
| # | Phase | Class | Question | Chosen option | Principle / reason |
|---|---|---|---|---|---|
| 1 | CEO | Mechanical | Review mode | SELECTIVE EXPANSION | autoplan override |
| 2 | CEO | Mechanical | Fold parent's round-trip evidence before dispatch | Yes, marked "amended: evidence" | P1; facts, not scope |
| 3 | CEO | Mechanical | Correct refuted code claims 1,3,4,5,6 and plan-body references | Correct inline with file:line | P5; both voices + driver re-check |
| 4 | CEO | Mechanical | Deadline semantics (1.1) | Cancel + race + per-member clock + hard ceiling; zombie mechanism to Eng | P1; both voices Critical |
| 5 | CEO | Mechanical | Attempt counter timing | At claim / expired-claim reclaim | P1; native C2, kill loop |
| 6 | CEO | Mechanical | Who writes the hold, and the source-wide gate | P1; both voices, sync-run.ts:404,445 |
|
| 7 | CEO | Mechanical | Q1 budgets | Constant per-member + hard ceiling, not RTT-scaled | both voices agree |
| 8 | CEO | Mechanical | Q2 hold vs fail | Both layers: failed receipt + hold | both voices agree |
| 9 | CEO | Mechanical | Q3 unproven pool cap | No | both voices; P4/P5 |
| 10 | CEO | Mechanical | Q4 repeated-marker merge | Defer to TODOS.md | both voices; P3 |
| 11 | CEO | Mechanical | waiting_on honesty, drop "never cause_unknown" gate |
Observed-only, else unknown |
P5; pool-gauge.ts:5-14 |
| 12 | CEO | Mechanical | Systemic breaker (G6) | Add, reuse GIT_HOLD_ESCALATE_* |
P1/P4; both voices High |
| 13 | CEO | Mechanical | Fence normalization method | Parser as oracle, lossless whitespace/EOL only | P4/P5; native H3, outside High |
| 14 | CEO | Mechanical | 2.3 one-day suppression | Cut to doctor count | P4; redundant after 2.1 |
| 15 | CEO | Mechanical | 3.3 repair during sync | Keep, add manifest-aware busy set | P1; keeps user's direction |
| 16 | CEO | Mechanical | G4 wording | Restore "repair actually runs" | user direction |
| 17 | CEO | Mechanical | G5 numbers | Bench-based (152.8/min), processed vs imported | P5; native M1 |
| 18 | CEO | Mechanical | Phase 0 gating | Time-box investigation; gate only cause-specific fix; send 0.1 now | P6; both voices |
| 19 | CEO | Mechanical | Kill switch | Add WRITE_SWITCHES entry |
P2 |
| 20 | CEO | Mechanical | Progress line names the stall (E5) | Add | P2, <1 day |
| 21 | CEO | Mechanical | pg_stat_activity probe (E6) | Defer to TODOS.md | P3 |
| 22 | CEO | Taste | PR split | Two PRs: containment (Phase 1 + 2.1/2.2) then repair (Phase 3 + 2.3) | voices differ: native wanted cause-specific deadline in a later PR, outside wanted one containment PR; chosen = outside's shape because containment does not need the cause |
| 23 | CEO | Mechanical | 3.1 host paths to remote callers | Omit paths when remote=true |
trust boundary in AGENTS.md |
| 24 | CEO | Mechanical | 0.5 identify which request failed repeated_marker |
Add | P1; driver finding (sync-screen.ts:85) |
| 25 | CEO | Taste | Who writes the preparation_stalled hold |
The sync, via existing converters behind the narrowed gate (reverses #6's "consumer writes it") | spec review F1: the consumer lacks the manifest entry, run id and screen run; native voice wanted the consumer to write it |
| 26 | CEO | Mechanical | Attempt counting rule and limit check point | Deadline release + expired-preparing reclaim; reset on commit; check at claim |
spec review C3 |
| 27 | CEO | Mechanical | Breaker vs durable holds | Sync converts in-run as receipts fail and counts them; at the threshold it stops, flags the cursor, converts no more; next run refreezes flagged entries | spec review C2, N4, N10 |
| 28 | CEO | Mechanical | Maintenance write on a defective page | Pre-submission fence scan, skip with reason (2.6) | spec review C1 |
| 29 | CEO | Mechanical | Held entries in repair busy set | Excluded | spec review C4 |
| 30 | CEO | Mechanical | Doctor count placement | PR 1 with 2.1 | spec review C5 |
| 31 | CEO | Taste | Abandoned-await default (G1 mechanism) | Keep #5373 root block, fail at ceiling, sync exits with distinct code | provisional; Eng confirms (outside voice preferred isolating the zombie) |
| 32 | CEO | Mechanical | waiting_on enum |
`git | fs |
| 33 | DX | Mechanical | preparation_stalled hold routing |
Own route in every hold surface | both voices; sync-holds.ts:319-397 |
| 34 | DX | Mechanical | Drain fingerprint on lease columns | Key on state/phase/step | native H2, driver-verified sync-drain.ts:283-284 |
| 35 | DX | Taste | Exit signalling for abandoned preparation | Reuse drain outcomes (resumable/blocked), no new exit number |
native: reuse; outside: reserve a new non-consent exit value; P4/P5 favour reuse and the reporter's loop already branches on outcomes |
| 36 | DX | Mechanical | Health reason on the wire enum | claim.stall, enum unchanged |
native H4, types.ts:82-86 |
| 37 | DX | Mechanical | G5 one-pass goal | Restore; CEO premise refuted | both voices, sync-reconcile.ts:161-206 |
| 38 | DX | Mechanical | Hard ceiling key | New key family, max_claim_ms unchanged |
both voices |
| 39 | DX | Mechanical | Code for the adoption invariant | Register fence_unrenderable (server) |
native M2; outside preferred storage_error server with a reason; P5 explicit, and storage_error's summary is wrong for it |
| 40 | DX | Mechanical | preparation_stalled class/retry |
server, retryable: false, read-only default fix, actor agent locally |
both voices |
| 41 | DX | Mechanical | Holds left by a transient cause | Re-screen on version change and after a breaker trip | both voices |
| 42 | DX | Mechanical | Running vs terminal naming | preparation_overdue / preparation_stalled |
native M6 |
| 43 | DX | Mechanical | Owner refusal codes | Keep owner_unavailable + reasons matrix |
native M11, outside 8; drain branches on the code |
| 44 | DX | Mechanical | Unrenderable rows journey | Typed record, next: report |
both voices |
| 45 | DX | Mechanical | Mixed-version section | Add, with restart guidance and tests | outside 4, native H4 |
| 46 | DX | Mechanical | Runbook and docs list | One runbook; docs and generated files listed | both voices |
| 47 | DX | Mechanical | Writer status fields and next actions | operation, intent kind, owner kind, pid; non-circular next actions | native M1 |
| 48 | DX | User Challenge | Maintenance writes: hold vs skip-with-diagnostic | Not auto-decided; plan text keeps skip-with-diagnostic pending Garry | both DX voices flag it as a narrowing of "hold instead of failing" |
| 49 | DX | User Challenge | "Never stalls" qualified (database reachable; ignored-cancel ends run as resumable) | Not auto-decided; plan keeps the qualification pending Garry | both DX voices and both CEO voices |
| 50 | Eng | Mechanical | Signal threading scope | Race + step checks; signals only on lock-prone raw statements; memo rule; bench gate | both voices; vendor/postgres/src/index.js:262-266, group-publish.ts:155-158 |
| 51 | Eng | Mechanical | Group lease on a mid-group release | Mutable held set | native C1, driver-verified group-publish.ts:343 |
| 52 | Eng | Mechanical | laneFallback reason and abort classification |
Preserve preparation_deadline; classify before finishUnpublishedFailure |
native H1/H2 |
| 53 | Eng | Mechanical | Crash accounting for groups | Durable dispatch marks per wave; charge at expiry | outside (renewal-only stamps miss early kills) |
| 54 | Eng | Taste | Abandoned-await mechanism (G1) | Barrier to ceiling, then isolate with cap 1; CLI fail-stop, resident restart_required; bounded stop() |
native: isolate with cap; outside: owner-level fail-stop at the ceiling; chosen mix gives fail-stop where it is cheap and safe |
| 55 | Eng | Mechanical | Narrowed gate design | Cancel suffix, identity predicate, atomic under page-key → cursor order | both voices (outside: circular wait and atomicity) |
| 56 | Eng | Mechanical | Adoption write-back | Mandatory, same UPDATE as row_num |
native H5, driver-verified projection expiry |
| 57 | Eng | Taste | Unadopted rows vs destructive reconcile | Per-page guard (exclude pages with unadopted rows) | native per-page skip (P5, small); outside preferred structural preservation in reconcile predicates (more complete, bigger); structural version deferred |
| 58 | Eng | Mechanical | Duplicate normalized claims | Second row not adopted, duplicate_claim diagnostic |
outside; reconcile dedup would expire it |
| 59 | Eng | Taste | Foreground writes after two deadlines | Terminal preparation_stalled with behavior row and test |
native M4; needed so foreground priority cannot re-stall the root; it is a public contract change Garry did not request |
| 60 | Eng | Mechanical | Drain window vs budgets | Claim-aware no-progress rule | outside, driver-verified sync-drain.ts:71-72 |
| 61 | Eng | Mechanical | Breaker latency and durability | Consecutive trip; durable trip and receipt ids | native M6, outside |
| 62 | Eng | Mechanical | Maintenance budget | 120 s; ceiling ≥ budgets + 30 s | native M5 |
| 63 | Eng | Mechanical | 2.6 placement | submitMaintenance, body + timeline |
both voices |
| 64 | Eng | Mechanical | Preparation outside the consumer | Budget race, fail open, no counter | both voices |
| 65 | Eng | Mechanical | Mixed versions / protocol | No bump; allowlist; messages carry fix; build on claim | both voices |
| 66 | Eng | Mechanical | Pinned scheduling test | Verbatim under switch-off; new switch-on variants | both voices |
| 67 | Eng | Mechanical | Migration number and schema path | v221+, schema.sql + build:schema + goldens |
native L2/L3, driver-verified v220 on GBRA-39 |
| 68 | Eng | Mechanical | PR 2 busy set | Fail closed, rename endpoints, manifest, admission recheck | outside |
| 69 | Eng | Mechanical | Metadata policy | Identity = claim+visibility; rest follows fence | outside (confidence rounding), projection behaviour |
| 70 | Eng | Mechanical | Existing TODO W3.3b | Superseded; PR 1 closes it; publication ceiling stays | native L4; announced reversal of its max_claim_ms/write_stalled design |
Final gate
Status: awaiting Garry's approval (autoplan does not approve its own output). Decisions: 70 audit rows (61 mechanical, 7 taste, 2 user challenges). Phase coverage:
| Phase | Native voice (opus-5-5) | Outside voice (gpt-6.1-sol, Codex substitute) | Consensus | Score before → after |
|---|---|---|---|---|
| CEO | completed, 6/10 | completed, 4/10 | 6/6 dimensions agree (mostly gaps); spec loop 3 launches, 8.5/10 | 5/10 → about 8/10 |
| Design | skipped (no UI scope) | skipped | — | — |
| DX | completed, 5/10 | completed, 6/10 | 5/6 agree, 1 resolved | 5/10 → 8/10 |
| Eng | completed, 6/10 | completed, 6/10 | 5/6 agree, 1 resolved | 6/10 → about 8.5/10 |
User Challenges (both models recommend a change to your stated direction; your direction stands unless you approve)
Challenge 1: maintenance writes are skipped with a diagnostic, not held (raised in DX, confirmed in Eng). You said: hold fence problems instead of failing writes. Both models recommend: for sync files, hold (as planned); for maintenance writes (fact-fence adoption, maintenance page writes), which have no manifest entry to hold, skip the write before submission with a typed diagnostic (fence_unrenderable, duplicate_claim, or the fence reason) in failed_pages and doctor, leave the legacy rows active and searchable, and keep those pages out of destructive reconciliation. Why: a hold is a sync-cursor object; inventing a durable "maintenance hold" store adds storage and a new repair surface for rows that lose nothing by staying legacy. What we might be missing: you may want one visible queue of "things gbrain could not write", across sync and maintenance, rather than two surfaces. If wrong: agents see unrenderable facts only in doctor and cycle warnings, and a page with such rows never gets destructive reconciliation until someone edits it.
Challenge 2: "the catch-up never stalls" is qualified (raised by both CEO voices, both DX voices and the Eng outside voice). You said: fix #6278 so the catch-up never stalls. Both models recommend stating the guarantee as: while the database and control path work, no single request holds a root past its budget (cooperative) or the hard ceiling (an await that ignores cancellation); an ignored-cancellation preparation ends a CLI run as resumable and the next pass holds the entry (so that case takes two passes, not one), a resident owner needs a restart, and a systemic fault stops the run with one diagnostic instead of holding every file. Why: an AbortSignal cannot interrupt transactions, synchronous git/fs or a promise that never settles, and freeing the root under a live zombie risks pinned connections; a database outage cannot be "progressed through". What we might be missing: if you want literal in-process continuation even for non-cancellable awaits, that needs a worker-process isolation design (bigger, not in this plan). If wrong: in the reporter's exact shape (if the stuck await ignores cancellation) one pass stops early and the next drains, which is still a large improvement on four failed passes. Feasibility risk flagged by both models: without every owner process upgraded, the guarantee does not hold.
Your choices (taste decisions, auto-decided with a recommendation)
- PR split (CEO, Decision 22). Recommend two PRs: PR 1 containment (Phases 1-2), PR 2 repair during sync (Phase 3), because containment does not depend on Phase 0's cause. Alternative (native CEO voice): PR 1 diagnostics and cause-independent pieces, PR 2 the deadline after Phase 0 names the await; delays the stall fix behind the investigation.
- Who writes the
preparation_stalledhold (CEO, Decision 25). Recommend the sync, via the existing converters behind the narrowed gate (the consumer lacks the manifest entry, run id and screen run). Alternative: the consumer writes it in the failure transaction; needs a partial hold record the sync reconciles later. - Exit signalling (DX, Decision 35). Recommend reusing the drain contract:
resumable/preparation_abandoned(exit 0,safe_to_loop) andblocked/preparation_systemic(exit 1); no new exit number. Alternative (outside voice): reserve a new non-consent exit value; clearer for shell scripts, but changes the v1 exit table and the reporter's loop. - Abandoned-await mechanism (CEO 31 → Eng 54). Recommend barrier to the ceiling, then isolation with a per-process cap of 1, CLI fail-stop, resident
restart_required, boundedstop(). Alternative (Eng outside voice): owner-level fail-stop at the ceiling for every owner, including resident ones; stronger resource guarantee, but restarts unrelated work inserve. - Unadopted legacy rows vs destructive reconcile (Eng 57). Recommend the per-page guard (pages with unadopted rows skip destructive reconcile). Alternative (Eng outside voice): structurally exclude active
row_num IS NULLrows from stale classification so every page reconciles; more complete, larger and riskier. - Foreground writes get a terminal
preparation_stalledafter two deadlines (Eng 59). Recommend yes, with a behavior-change row and a test, because foreground priority would otherwise keep re-claiming a poisoned foreground write ahead of the sync. Alternative: count only sync and maintenance kinds; leaves a foreground write able to stall the root. fence_unrenderableas its own code (DX 39, recorded mechanical; outside voice preferredstorage_errorclassserverwith a site reason). Low stakes; flagged for completeness.
Cross-phase themes
- A deadline is not cancellation (CEO both voices, DX, Eng both voices): every phase found that signalling an abort frees nothing unless the wait is raced and the root barrier is handled; this drove G1, 1.1, 1.8 and 1.9.
- The source-wide hold gate is the real "no hold" cause (CEO both voices, spec review, Eng both voices): it links the stall to the missing holds; 1.2b plus the Eng design closes it.
- Honest diagnostics over confident ones (CEO outside, DX both, Eng):
waiting_ononly when observed,claim.stallinstead of a wire-enum value, no fabricated host paths. - Holds must route to the right fix and recover from transient causes (DX both, Eng): frontmatter misroute, breaker recovery, version re-screen.
- Fact preservation through adoption and reconcile (CEO, Eng both): parser oracle, mandatory write-back, duplicate handling, per-page guard.
- Mixed-version owners defeat the guarantee (DX outside, Eng both): restart guidance and build on the live claim.
Deferred to TODOS.md (not written by this review pass; the implementing PR adds them)
- P3 — Repeated facts fences merge as a deterministic repair (old 2.5), with its own preservation proof and fixtures (section context, superseded references, protected rows).
- P3 —
writer status --probecapturespg_stat_activityfor the blocker's backend, sowaiting_oncan reportlockwith evidence. - P3 — Structural preservation of unadopted legacy rows inside destructive reconcile (alternative to the per-page guard, Decision 57).
- P3 — Worker-process isolation for non-cancellable preparation awaits (only if Challenge 2 is rejected).
- Existing: "Ceiling for a stuck managed publication (W3.3b, #6176)" stays open (publication phase, out of scope). Existing "Hard ceiling for a stuck managed write (W3.3b, #6176)" is closed by PR 1.
Implementation tasks (aggregated across phases)
The per-phase JSONL task files were not written (review-only pass, plan file is the only artifact besides the Eng test plan at ~/.gstack/projects/garrytan-gbrain/user-master-eng-review-test-plan-20261008-044354.md); the aggregated list below is synthesized from the three phases' accepted obligations.
Phase 0 (now, parallel to PR 1)
- T0 (P1, human ~1 h / CC ~10 min) — Comment on #6278 with the 0.1 evidence ask (blocker operation/kind/group key/claim_phase,
pg_stat_activity,sync.write_through, which process submitted adoptions, bothhost.jsonpaths at<GBRAIN_HOME>/.gbrain/persistence/host.json, writer status from both environments, failed receipts' kinds for 0.5). Needs posting by the owning thread, not this review. - T0b (P2, human ~1 d / CC ~3 h) — Ubicloud repro (
UBI_OWNER=gbra59): GBRA-45 head without and with the fix, PgBouncer transaction mode, pool 3/10, shared/split direct route, seeded fence shapes; time-boxed one day.
PR 1 — containment (about 5 days human / 2 days CC+gstack; base capy/sync-feeder-fast-writes)
- A1 (P1, 2 h / 15 min) — Migration v221+
preparation_attempts;src/schema.sql,bun run build:schema, goldens,build:schema-migrations. Verify: fresh + upgraded Postgres and PGLite tests. - A2 (P1, 4 h / 45 min) — Key family and kill switch:
switches.tsTTL snapshot,core/config.ts,commands/config.tsstructured validation. Verify: config validation tests. - A3 (P1, 3 h / 30 min) —
claim-phase.ts:step,waiting_on, dispatch state,enterClaimStep(clock, step, signal),claim.stall. Verify: stamp-shape unit tests. - A4 (P1, 1.5 d / 3 h) —
consumer.ts: race, reason-preserving release, claim-time limit, zombie registry, ceiling, cap,restart_required, boundedstop(), expiry charging,status(). Verify:persistence-consumer-scheduling.test.ts(legacy + switch-on variants), newtest/e2e/persistence-preparation-deadline.e2e.test.ts. - A5 (P1, 1.5 d / 3 h) —
group-publish.ts,claim-lease.ts,coordinator.ts: per-member clocks, held-set lease, prefix publish,laneFallbackreason, abort classification. Verify:persistence-claim-lease.test.ts,managed-sync-lanes.test.ts, group parity tests. - A6 (P1, 3 h / 30 min) —
journal.tsdispatch marks and release counter;effect-journal.tsPGLite charging. Verify: kill-accounting tests. - A7 (P1, 6 h / 1.5 h) —
service.ts,sync-prepare.ts,prepared-maintenance.ts,page-prepare.ts, link preparation: step stamps, limited signals, memo rule;fault-points.tsconsumer:preparing. Verify: memo sibling test, GBRA-45 bench within 20%. - A8 (P1, 3 h / 30 min) —
error-registry.ts+ write-error allowlist (preparation_stalled,fence_unrenderable),diagnostics.tsnext actions and blocker fields (operation, kind, owner kind, pid, build). Verify: registry scanner, writer status tests. - B1 (P1, 1 d / 2 h) —
sync-run.ts+sync-waivers.ts: cancel suffix, shared gate predicate under page-key → cursor order,preparation_stalledbranches, delete hold,sync-screen.tsbuilder. Verify: completion-order tests (import/rename/delete), same-page and unrelated-maintenance tests. - B2 (P1, 4 h / 1 h) — Breaker (count + consecutive, durable trip), refreeze,
holdRescreenDue. Verify: breaker replay tests. - B3 (P2, 2 h / 20 min) — Waiver/origin preparation budget, fail open. Verify: unit.
- B4 (P1, 4 h / 1 h) —
sync-drain.ts: fingerprint, claim-aware window, stop reasons, catalogue/STOP_DOCS, timer progress line;sync-wire.tsdelegated result. Verify: drain tests, wrapper contract test. - B5 (P1, 5 h / 1 h) — Hold routing in
sync-holds.ts,held-reads.ts,sources-retry-held.ts(option-preserving command), doctorgit-holds.ts,hold-fix.ts. Verify:held-files-walkthrough.test.tswith mixed holds. - C1 (P1, 5 h / 1 h) —
unfenced-facts.ts: parser oracle, normalized reuse, duplicate handling, typed records,FACTS_FENCE_FAILEDtoken; unmanaged write-back. Verify: 1k property test,unfenced-factstests,migrations-v0_32_2-managed.test.ts. - C2 (P1, 2 h / 30 min) — Adoption compare and write-back in the
row_numUPDATE. Verify: fact id survives adoption (unit + Postgres); withdrawal fingerprint test. - C3 (P1, 2 h / 30 min) — 2.6 scan in
submitMaintenance. Verify: second-timeline-fence fixture. - C4 (P1, 3 h / 30 min) — Per-page reconcile guard in
cycle/extract-facts.ts. Verify:extract-facts-unfenced-rows(+ Postgres) mixed-page test. - C5 (P2, 2 h / 30 min) — Doctor
fence_integrityunrenderable_legacy_factswithnext: report. Verify: doctor test. - D1 (P2, 5 h / 1 h) — Docs and generated artifacts: live-sync, write-refusals, troubleshooting runbook and symptom row, AGENTS.md, key-files,
bun run build:error-codes; behavior-change rows (deadlines/holds, foreground terminal receipt,facts.factnormalization, keys, switch); close TODO W3.3b (write ceiling). Verify: doc checks,ci:local:diff. - G1 (P1) — Gate: full Ubicloud gate on the exact head with current master; reporter-shape run (4.1); mirror the verdict into gbrain-evals (4.2).
PR 2 — repair and chronicle during a sync (about 2 days human / 0.5 day CC+gstack; stacked on PR 1)
- R1 (P1, 4 h / 1 h) —
owner_unavailablereasons matrix inprepared-maintenance.tspreflight andrepair-io.ts;FENCE_REASONSandhold-fix.tsOWNER entries;retryable:falseforhost_mismatch; remote render without paths. Verify:fence-repair-reasons.test.ts, preflight unit tests. - R2 (P1, 6 h / 1.5 h) —
repair/fences.tsat preview and apply: drop the blanketsyncUnfinishedskip; busy set fails closed, includes recovery rows, rename endpoints, manifest occupancy (held entries excluded); recheck at coordinated admission (file-repair.ts). Verify:repair-fences.test.ts, concurrent repair-during-catch-up E2E (non-busy repaired, busysync_in_progress, far-ahead busy, held repaired, failed busy query, admission race, sync starting during model wait). - R3 (P3, conditional on 0.1) —
host_identity_splitdoctor check and service-fileGBRAIN_HOMEpropagation; two-home E2E. - R4 (P2, 2 h / 30 min) — Docs: repair.md, troubleshooting.md. Gate: PR 2 assertions of 4.1.