Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
The strict door's index refresh survives crashes, and relative stored roots read as database-only
garrytan095f8f336594
diff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.mdindex 426e8a1168..eb119250ff 100644--- a/docs/architecture/key-files/agent-contract.md+++ b/docs/architecture/key-files/agent-contract.md@@ -31,7 +31,7 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md`; wire goldens: `test/fixtures/agent-- `src/mcp/initialize-context.ts` — per-initialize inputs for the generated instructions (`httpInstructionTools`: the tools/list filters with publish gates read on initialize; `instructionReadiness`: config plane + probed tier within 250 ms, HTTP view redacted) and `stdioCapabilityReadiness` (F2). Test: `test/mcp-capabilities-readiness.test.ts`.- `src/mcp/hidden-tool-hint.ts` + `src/core/ops/cli-equivalent.ts` — F6: on the owner's stdio pipe a real tool outside the surface/read-only access gets `unknown_tool` naming itself and its CLI equivalent (`cliEquivalent`: `cliOnly` argv, curated overrides, `cliHints.name`, else `gbrain call`). Where `request_tools` is callable and session widening is on, the fix is `request_tools {surface:'full'}` (`next: run`, argv kept); otherwise the CLI equivalent with actor `user` and a `user_message`; `why` names the lasting route (`GBRAIN_SURFACE=full` in the harness's per-server env, or a `--surface full` re-registration) and that an inherited `GBRAIN_SURFACE` overrides a pinned `--surface`. Read-only access never offers a widen. HTTP stays opaque. `scripts/generate-plugin-tree.ts` appends the same map as a per-skill note to generated starter-gap skills. Test: `test/hidden-tool-hint.test.ts`. D2: `hiddenToolRoute(op, ToolConnection)` is the one decision for every transport (`callable` | `widen {surface}` | `host {read_only|surface|grant}`): a widen is offered only when the widened connection could call the tool (read-only access, `GBRAIN_MCP_FORCE_SURFACE`, the grant's snapshot/scopes and an operator pin all hold); dispatch builds the connection with `toolConnection(opts)`. `hiddenToolNext` turns a route into the D2 fix (the call itself; request_tools; on HTTP the D4 grant repair; on stdio the CLI equivalent with the call's arguments as flags).- `Operation.cliOnly` + `cliOnlyRefusal` (`src/core/ops/callable.ts`) — F5: owner-only ops (they refuse every MCP caller) are never listed on MCP; a call gets `trusted_local_only` (error `permission_denied`) with the exact CLI command.-- `src/core/behavior-change-notice.ts` — the one-time `behavior_changes` safety notice: a live `chat_fallback_chain` (local view: entries, providers, refusal behavior, removal fix; HTTP view: only that a chain is configured), managed-brain lint repairs (`cycle.lint_fix`), smaller transcript parts re-embedded once (`TRANSCRIPT_REINGEST_MULTIPLIER`), a mention-linker rescan (v0.60.68.0), and fix wave 9's six upgrade-visible changes (v0.60.74.0). `BEHAVIOR_CHANGES` is the one table of disclosed changes, each with the release that introduced it (`FENCE_REPAIR_MEASURED` is the automatic fence repair row's measurement sentence, replaced by the Tier 3 eval's measured rates); `BEHAVIOR_NOTICE_SINCE` is the newest row's release (never `VERSION`), so the notice id `behavior_changes@<since>` moves only when a release appends rows. Content: the rows newer than the last notice release this brain × channel (× HTTP client) was shown, or than its baseline when never shown. Baseline: the brain's baseline under `GBRAIN_HOME/notices/behavior-changes/<brainKey>.baseline` (`gbrain init` stamps a database it creates; otherwise the first look records `0` when `upgrade-state.json` shows an upgrade from an older release or the oldest `sources.created_at` is past `FRESH_BRAIN_GRACE_MS`). Markers: CLI and stdio claim a `wx` file per notice × brain × channel (an unwritable home still delivers, once per process); the newest marker names the last release shown; HTTP keeps up to `HTTP_SHOWN_CAP` client ids, each with the release it was shown, in the `notices.behavior_changes.http` config row (a row from an older build counts its clients as shown its id's release) (no migration; a failed write still delivers). Delivery: `completeEngineStartup` in `src/cli.ts` (stderr; not `serve` or `doctor`), and `sessionSafetyNotices` in `src/mcp/dispatch.ts` on success and failure results. `gbrain doctor --only behavior_changes` reads every row newer than the baseline without writing. Pinned by `test/behavior-c... (line truncated to 2000 chars)+- `src/core/behavior-change-notice.ts` — the one-time `behavior_changes` safety notice: a live `chat_fallback_chain` (local view: entries, providers, refusal behavior, removal fix; HTTP view: only that a chain is configured), managed-brain lint repairs (`cycle.lint_fix`), smaller transcript parts re-embedded once (`TRANSCRIPT_REINGEST_MULTIPLIER`), a mention-linker rescan (v0.60.68.0), and fix wave 9's six upgrade-visible changes (v0.60.74.0). `BEHAVIOR_CHANGES` is the one table of disclosed changes, each with the release that introduced it (the notice lists releases oldest first whatever the table order) (`FENCE_REPAIR_MEASURED` is the automatic fence repair row's measurement sentence, replaced by the Tier 3 eval's measured rates); `BEHAVIOR_NOTICE_SINCE` is the newest row's release (never `VERSION`), so the notice id `behavior_changes@<since>` moves only when a release appends rows. Content: the rows newer than the last notice release this brain × channel (× HTTP client) was shown, or than its baseline when never shown. Baseline: the brain's baseline under `GBRAIN_HOME/notices/behavior-changes/<brainKey>.baseline` (`gbrain init` stamps a database it creates; otherwise the first look records `0` when `upgrade-state.json` shows an upgrade from an older release or the oldest `sources.created_at` is past `FRESH_BRAIN_GRACE_MS`). Markers: CLI and stdio claim a `wx` file per notice × brain × channel (an unwritable home still delivers, once per process); the newest marker names the last release shown; HTTP keeps up to `HTTP_SHOWN_CAP` client ids, each with the release it was shown, in the `notices.behavior_changes.http` config row (a row from an older build counts its clients as shown its id's release) (no migration; a failed write still delivers). Delivery: `completeEngineStartup` in `src/cli.ts` (stderr; not `serve` or `doctor`), and `sessionSafetyNotices` in `src/mcp/dispatch.ts` on success and failure results. `gbrain doctor --only behavior_changes` reads every row newer than the baseline without writing. Pinned by `test/behavior-c... (line truncated to 2000 chars)- `src/core/post-upgrade-notice.ts` — F7 `post_upgrade` safety notice (contract_version + behavior-table URL): `gbrain post-upgrade` writes it once; the first stdio MCP session per upgraded version gets it (persisted under GBRAIN_HOME). `src/cli/op-notices.ts` (also `retrievalIncompleteLine`, search/query's `Retrieval incomplete:` line: `projection_pending` only when `coverage` says some pending page could match, with the count, once per window across calls) renders op notices on the local CLI (`--json` objects gain `notices`; human output on stderr).- `src/core/ops/op-fix.ts` — Lane B builders for filled, surface-correct op errors (type-only agent-output import: ops sit in the snapshot-schema closure). `opTransport(ctx)` (cli/stdio/http from `remote`+`transport`), `paramUse(ctx, param, value?)` (`--no-pull` vs `no_pull: true`), `readFix` (diagnostic step, `mcp` + `argv`), `hostFix`/`hostOnlyError` (B6: host-only command, actor agent on CLI / user on stdio / host_admin on http with relay `user_message`), `invalidParam` (B2/B3: param, choices or type+description, one example; never echoes the raw value), `scopeDeniedError` (B5: `insufficient_scope`, frozen `error` via `legacy_error`, client id + current scopes in `why`, the exact `gbrain auth rescope`/`rescope-token` command, consent `credentials`). Test: `test/op-fix.test.ts`, `test/scope-denial-contract.test.ts`.- `src/core/persistence/page-identity.ts` — B4: `pageIdentityError(present, msg)` (a deleted page throws canonical `page_not_found` with the frozen wire/journal `error` `page_identity_changed`; a replaced page keeps `page_identity_changed`), `isMissingPageMessage` (replays recover the distinction from the stored message; no schema change), `yamlLocator` (content-free ` at line L, column C`). Replays (`writeResponse` in `persistence/service.ts`) set `OperationError.receiptFields` (never serialized); `toAgentError` fills the registry fix template (`{slug}`/`{source_id}`/`{request_id}`/`{operation}`, strict per-field patterns, unfillable → dropped) and applies the principal-aware receipt rule (CLI principal → `gbrain write-request`; same-principal MCP → `get_write_request` when callable; otherwise host inspection, actor host_admin). Test: `test/write-receipt-remediation.test.ts`.diff --git a/docs/architecture/key-files/core-minions-1.md b/docs/architecture/key-files/core-minions-1.mdindex e76d06733c..68338c7589 100644--- a/docs/architecture/key-files/core-minions-1.md+++ b/docs/architecture/key-files/core-minions-1.md@@ -4,7 +4,7 @@Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.- `src/core/minions/` — Minions job queue: BullMQ-inspired, Postgres-native (queue, worker, backoff, types, protected-names, quiet-hours, handlers/shell). Private dream-inline-* queues carry an explicit lifecycle: owner job id + owner token + a renewable lease (columns on minion_jobs; `queue.ts` `reconcilePrivateQueue` terminalizes one queue through the normal cancelJobs bookkeeping and stamps every cancellation with the machine-readable `private_queue_reconciled:` reason family; `renewPrivateQueueLease` is MONOTONIC — GREATEST — so a default-horizon renewal can never shrink a creation-time lease; `reconcileOrphanedPrivateQueues` cancels only provably-orphaned queues: no healthy child lock, owner terminal/missing or lease expired; legacy unowned rows are left to Doctor/retriage; `classifyPrivateQueueForRecovery` is PUBLIC so the doctor orphan check buckets through the same verdict). Recovery runs in `gbrain jobs work` after driver/selected-child readiness and `ensureSchema`, for bare AND supervised workers (including autopilot spawns/respawns); the standalone parent does not recover queues in `beforeSpawn`. `maybeRunWorkerStartupRecovery(queue, process.env, true)` keeps this worker-owned ordering even under `GBRAIN_SUPERVISED=1`. Dream-cycle start also recovers (cycle.ts, next to the cycle lock reap — the ONLY lane on PGLite, which inlines every child). `deriveWedgeSignal` is queue-aware: a dream-inline queue is never 'wedged' (no shared worker can claim it) — it reports `private_queue: true` so jobs stats / get_job_stats / doctor all point at reconciliation instead of the impossible worker restart.-- `src/core/minions/handlers/sync.ts` (and the other built-in job handler modules: `embed`, `lint`, `lint-fix`, `extract`, `extract-conversation-facts`, `chronicle-extract`, `loops-extract`, `enrich`, `integrity`, `integrity-auto`, `sync-retry-failed`, `import`, `backlinks`, `facts-absorb`, `autopilot-cycle`, `autopilot-global-maintenance`, `reindex`, `repair-jsonb`, `orphans`, `purge`, `cycle-phase`, `extract-atoms-drain`, `extract-ner`, `extract-takes-from-pages`, `extract-timeline-from-meetings`, `embed-catch-up`, `unify-types`, plus `job-pull.ts` and `job-progress.ts`) — one module per built-in handler body, each a `make<Name>Handler(engine)` factory (or a `MinionHandler` const when it needs no engine). Registered in a fixed order by `registerBuiltinHandlers` in `src/commands/jobs.ts`, which keeps the registration kind (plain vs gateway-refreshing) and wrappers such as `withFactsAbsorbHaltCooldown`; `cycle-phase.ts` serves the six phase wrappers. Command cores are imported lazily inside each handler. `resolveJobPull` and the facts-absorb retry predicates are re-exported from `jobs.ts`. `autopilot-global-maintenance` runs one `runCycle` call per maintenance phase and keeps its pass position in config `autopilot.global_maintenance.progress`: it stops starting a phase whose last measured duration would cross the job deadline (minus a 60 s reserve), the next job resumes at that phase, and a phase still marked running when an earlier job died is skipped for the rest of the pass; last_global_at is stamped only when a pass completes with no blocking phase. GBRA-130 A-10: each blocking phase keeps a streak in that row (`failures[phase]`, key `fail:<code>`, `budget`, `child:<outcome>` or `deferred`, counted once per pass); after three earlier `fail:` passes the pass stamps past it (`pass_completed_with_failing_phase`), `fail:`/`child:` streaks back off from their third pass, and the streak resets on a version change, a new key or `gbrain autopilot --retry-global` (rules in the module header). Phases run through an `ItemRun` (site `autopilot.global_maintenance`). Probe: `test/pathological/a10-global-maintenance-stamp.test.ts`. The deadline comes from `GBRAIN_GLOBAL_MAINTENANCE_TIMEOUT_MS` > `autopilot.global_maintenance_timeout_ms` > the autopilot default (`autopilot-fanout.ts:resolveGlobalMaintenanceTimeoutMs`); doctor `global_maintenance_timeouts` (`doctor/checks/global-maintenance-timeouts.ts`) warns after three consecutive deaths and names `gbrain dream --phase <name>` (`autopilot-global-maintenance-resume-4578.test.ts`). The `sync` handler runs performSync under `job.signal` composed with `job.shutdownSignal`: under a signal owner (`jobs work`, the supervisor) SIGTERM skips the cleanup pass and aborts only the worker's shutdown signal, so the sync and its `git pull` (async `pullRepo` on `bounded-child-exec.ts`) stop and the job is handed back without burning an attempt. A queued `autopilot_freshness` sync job re-reads its source when it runs and returns `{skipped:true, reason:'sync_disabled'}` when the source now has `syncEnabled:false`; explicit sync jobs still run and a failed lookup falls through to syncing (`sync-handler-sync-enabled.test.ts`). #6706: managed jobs drain via `sync-job-drain.ts`. Progress (`job-progress.ts` `reportJobProgress`, best-effort: a failed write never fails the job): `autopilot-cycle` passes `CycleOpts.onPhaseStart` and `autopilot-global-maintenance` writes before each phase's `runCycle`, both `{phase, phase_index, phase_count, started_at}`; the `sync` handler always passes `jobDrainProgress`'s `onProgress`, which writes a classic sync's phase (`resolve_repo`, `git_pull`, `full_import`, `import` with `banked_files`) on each change and at most every 10 s within one, beside the managed drain snapshot (`test/minion-job-progress-7241.test.ts`).+- `src/core/minions/handlers/sync.ts` (and the other built-in job handler modules: `embed`, `lint`, `lint-fix`, `extract`, `extract-conversation-facts`, `chronicle-extract`, `loops-extract`, `enrich`, `integrity`, `integrity-auto`, `sync-retry-failed`, `import`, `backlinks`, `facts-absorb`, `autopilot-cycle`, `autopilot-global-maintenance`, `reindex`, `repair-jsonb`, `orphans`, `purge`, `cycle-phase`, `extract-atoms-drain`, `extract-ner`, `extract-takes-from-pages`, `extract-timeline-from-meetings`, `embed-catch-up`, `unify-types`, plus `job-pull.ts` and `job-progress.ts`) — one module per built-in handler body, each a `make<Name>Handler(engine)` factory (or a `MinionHandler` const when it needs no engine). Registered in a fixed order by `registerBuiltinHandlers` in `src/commands/jobs.ts`, which keeps the registration kind (plain vs gateway-refreshing) and wrappers such as `withFactsAbsorbHaltCooldown`; `cycle-phase.ts` serves the six phase wrappers. Command cores are imported lazily inside each handler. `resolveJobPull` and the facts-absorb retry predicates are re-exported from `jobs.ts`. `autopilot-global-maintenance` runs one `runCycle` call per maintenance phase and keeps its pass position in config `autopilot.global_maintenance.progress`: it stops starting a phase whose last measured duration would cross the job deadline (minus a 60 s reserve), the next job resumes at that phase, and a phase still marked running when an earlier job died is skipped for the rest of the pass; last_global_at is stamped only when a pass completes with no blocking phase. GBRA-130 A-10: each blocking phase keeps a streak in that row (`failures[phase]`, key `fail:<code>`, `budget`, `child:<outcome>` or `deferred`, counted once per pass); after three earlier `fail:` passes the pass stamps past it (`pass_completed_with_failing_phase`), `fail:`/`child:` streaks back off from their third pass, and the streak resets on a version change, a new key or `gbrain autopilot --retry-global` (rules in the module header). Phases run through an `ItemRun` (site `autopilot.global_maintenance`). Probe: `test/pathological/a10-global-maintenance-stamp.test.ts`. The deadline comes from `GBRAIN_GLOBAL_MAINTENANCE_TIMEOUT_MS` > `autopilot.global_maintenance_timeout_ms` > the autopilot default (`autopilot-fanout.ts:resolveGlobalMaintenanceTimeoutMs`); doctor `global_maintenance_timeouts` (`doctor/checks/global-maintenance-timeouts.ts`) warns after three consecutive deaths and names `gbrain dream --phase <name>` (`autopilot-global-maintenance-resume-4578.test.ts`). The `sync` handler runs performSync under `job.signal` composed with `job.shutdownSignal`: under a signal owner (`jobs work`, the supervisor) SIGTERM skips the cleanup pass and aborts only the worker's shutdown signal, so the sync and its `git pull` (async `pullRepo` on `bounded-child-exec.ts`) stop and the job is handed back without burning an attempt. A queued `autopilot_freshness` sync job re-reads its source when it runs and returns `{skipped:true, reason:'sync_disabled'}` when the source now has `syncEnabled:false`; any sync job that `performSync` refuses `sync_not_applicable` or `sync_anchor_relative` completes as a skip (the latter carrying the refusal's `suggestion` and ask-the-user `fix`, no stored path), so it never uses up its attempts; explicit sync jobs still run and a failed lookup falls through to syncing (`sync-handler-sync-enabled.test.ts`). #6706: managed jobs drain via `sync-job-drain.ts`. Progress (`job-progress.ts` `reportJobProgress`, best-effort: a failed write never fails the job): `autopilot-cycle` passes `CycleOpts.onPhaseStart` and `autopilot-global-maintenance` writes before each phase's `runCycle`, both `{phase, phase_index, phase_count, started_at}`; the `sync` handler always passes `jobDrainProgress`'s `onProgress`, which writes a classic sync's phase (`resolve_repo`, `git_pull`, `full_import`, `import` with `banked_files`) on each change and at most every 10 s within one, beside the managed drain snapshot (`test/minion-job-progress-7241.test.ts`).- `src/core/minions/admission.ts` — submit-side queue admission control (the drain-side pool-starvation half is the job-isolation work; claim fairness is a filed TODO, deliberately out of scope). Three primitives resolved per name via `resolveAdmissionPolicy` (config `minions.*` > per-name defaults tables, 60s in-process cache per engine, fail-open with a once-per-process stderr warn; env kill-switch `GBRAIN_MINIONS_ADMISSION=0` disables all three): PARAM-COALESCING (`PARAM_COALESCE_DEFAULT` — on for `subagent`; `computeParamHash` = sha256 of stable-stringified payload excluding `__param_hash` itself and the `__submitter` display label — `__owner_client_id` is deliberately INCLUDED so owner lanes never cross; parentless + waiting-only + age-bounded to ttl/2), WAITING-TTL (`WAITING_TTL_DEFAULT_HOURS` — 48h for `subagent`; swept by `MinionQueue.handleWaitingTTL` through `cancelJobs(ids, {reason, rootStatuses:['waiting']})` so descendants cancel, child_done lands, aggregator parents resolve, and the reason stamps ROOT ids only; ≤500/tick oldest-first; warn-before-act is `runWaitingTtlTick` — first tick counts affected + stamps `TTL_NOTICE_SHOWN_KEY` with an ISO timestamp, sweeping starts only after `ttlNoticeGraceMs()` (1h default, env `GBRAIN_MINIONS_TTL_NOTICE_GRACE_MS`) elapses; `gbrain upgrade` prints the same one-shot notice and starts the same clock; legacy `'true'` flag values sweep immediately), and NAME-GLOBAL QUOTA (`QUOTA_MAX_WAITING_DEFAULT` EMPTY by operator decision — activates only via `minions.quota_max_waiting.<name>`; counts the name across ALL queues so per-run `dream-inline-*` fanout queues can't dodge it, EXACT under concurrency via a `minion_quota:<name>` advisory xact lock taken only when a quota is configured; throws typed `QueueQuotaExceededError`, checked everywhere via `isQueueQuotaExceededError` — dream submitters record a phase skip, synthesize rolls back the current transcript's fresh chunks, agent fanout cancels the whole tree, `submit_agent` maps to a structured `rate_limited` OperationError). `TTL_REASON_PREFIX` is the single source for the sweep's error_text prefix and the stats/doctor LIKE patterns; `safeConfigSegment` gates untrusted job names out of copy-pasteable config hints. Alerting rides `getStats` (`drained_completed/failed/dead/cancelled` keyed on finished_at + `waiting_now` + `oldest_waiting_minutes`), the `jobs stats` DIVERGENT-QUEUE / waiting-TTL screams (`GBRAIN_QUEUE_DIVERGENCE_RATIO`=2, `GBRAIN_QUEUE_DIVERGENCE_MIN_WAITING`=50; divergence compares intake vs COMPLETED so TTL-cancel storms can't masquerade as throughput) + `--json`, and doctor `checkQueueHealth`. Pinned by `test/minions-admission.test.ts` + `test/jobs-stats-divergence.serial.test.ts`.diff --git a/docs/architecture/key-files/core-persistence-git.md b/docs/architecture/key-files/core-persistence-git.mdindex ef00bdd9ed..f99c6f810c 100644--- a/docs/architecture/key-files/core-persistence-git.md+++ b/docs/architecture/key-files/core-persistence-git.md@@ -9,5 +9,5 @@ The managed Git writer (`gbrain sources refresh`), git-canonical memory (the git- `src/core/persistence/git-gap.ts` + `src/commands/sources-git-gap.ts` + `src/commands/doctor/checks/db-ahead-of-git.ts` — git-canonical memory, wave G1 (`docs/designs/GIT_CANONICAL_MEMORY.md#the-git-gap-census`), read-only. `declaredDatabaseOnly` is the one predicate for pages that may not have a tracked file, tested in order: a read-only mirror source, a private page (`isPrivatePage`), an alias-private page (`isDerivationPrivate`), lineage-private (computed in SQL from `privatePagesFilterFragment`), `database_only_reason`, a `storage.db_only` prefix (`isSourceDbOnlySlug`, refusing an invalid gbrain.yml), a never-filed derive-phase page (page-prepare.ts `isNeverFiledDerivedPage`: no `source_path`/`source_uri` under `DERIVE_PHASE_DB_ONLY_DEFAULTS`), a path the checkout's Git ignores (`ignoredPaths`: filter-free `check-ignore -z --stdin`, tracked files never reported, exit 1 = none, null when Git cannot answer). The equality contract compares a committed blob with the page's export view (`readExportPage`, withdrawals overlaid; the census reads a batch's views with `readExportPages`, the same snapshots in two statements, #7617): an inline blob parsed as reconcile parses a canonical file, aligned with the stored type, subtype and #6429 stamp and compared by `reconcileCanonical` digest; a segmented page by the Git blob id of its streamed export. HEAD is read with hardened plumbing only (`readHeadTree`: one `ls-tree -r -l -z --full-tree` under the source's directory; `readBlobs`: `cat-file --batch` in calls of at most 64 MiB) and the working tree by hashing raw bytes (`worktreeBlobOid`), never `git status`/`git diff`, so no repository filter, textconv or fsmonitor runs. `gbrain sources git-gap <id> [--sample n] [--json]` (trusted local CLI, not an MCP op) puts every live page in one state (`equal`, `database_ahead`, `git_ahead` when the sync import record's `blob_oid`/`disk_blob_oid` differs from HEAD, else folded into `database_ahead` and counted in `database_ahead_without_import_record`, split by content evidence in `direction_evidence`, `declared_database_only` per class, `undeclared_database_only`, `worktree_only`, `unparseable`, `unsafe_path`), reports the working tree separately, and counts rows with no Git home (unfenced active facts, fenced facts on a missing page or a page without a committed file, links whose `link_source` is not in `DERIVED_LINK_SOURCES`, timeline rows on pages without a file), open `sync-hold` records by code and parked effect targets by kind and code. Each 256-page batch reads in its own read-only transaction. Doctor `db_ahead_of_git` runs the census per non-archived source whose directory is a Git checkout (others are only counted) under `GBRAIN_DOCTOR_GIT_GAP_TIMEOUT_MS` (default 10 s) and the entry deadline; it is always `ok` (informational) and lists totals only with each source's `live_pages` (counted in SQL before the scan), a source the budget stopped or never reached as partial (`PARTIAL, <read> of <live> live page(s) read`). Tests: `test/git-gap-census.test.ts` (PGLite and Postgres).- `src/core/persistence/git-declared.ts` + `src/core/persistence/git-canonical-schema.ts` (migration `git_canonical_declared`) — git-canonical memory, wave G7a: the declared database-only classes of a strict source (`sources.config.canonical = "git"`, default off). `strictPageClass` judges a page by its slug and prior file (`declaredPathClass`: `db_only_prefix` for a `storage.db_only` dir, `derive_folder` for a never-filed derive-phase page; G3's indexer reads the same function) and then its rendered content (`privacyClass`: `private`, `alias_private`, or `lineage_private` from the same SQL remote reads use, `privatePagesFilterFragment`, over the page's own values). `page-prepare.ts` `prepareFileTarget` asks it before it builds a strict file target: a declared page gets no target (no file, no door commit, no Git effect), an untracked ignored target is `git_ignored`, a page turning private gets the removal of the file it still has in the worktree or at HEAD, and a path whose `filter` attribute is `lfs` passes `assertLfsTarget` only with `storage.git_lfs` and a checkout that configures the LFS filter (`git_lfs_not_enabled`). `preparePrivateTransition` (page-prepare.ts) is that removal for other writers (GBRA-60, connector imports #7971). In `publishMutation` and `publishGroup`, `assertNoPrivateCommit` refuses a file target carrying a private page's bytes before anything is written (`git_private_commit_refused`; a group rolls back whole), and `declareStrictPublication` (after apply, before the door commit) refuses a declared page's file or an undeclared file-less page (`git_home_required`), stamps `pages.database_only_reason` and, for a privacy class, clears `source_path`/`source_uri` in the transaction of the door commit that removed the file. A managed import builds its own file target, so it meets only these publication checks. `assertStrictGitHome` is the refusal for writers with no file form yet (G4, G5). The managed writer guard (`writer-guard-schema.ts`) refuses rows of a strict source unless the writer declares `gbrain.git_protocol` (`withCoordinatedWrite` does), behind the `git_canonical_brain.strict_sources` counter kept by `sources` triggers (`git_protocol_required`, mapped in `publication-failure.ts`). The guard reads its state as the writing role and fails closed: a hidden or missing `persistence_brain` or `git_canonical_brain` row, or a source or page row hidden by row-level security, raises `writer_coordinator_required` (`managed_writer_guard:unreadable_state`), and the counter refuses a recount under RLS on `sources` (`test/writer-fence-fail-closed-7636.test.ts`). The census (`git-gap.ts`) adds `database_only_source` (a source with no checkout) and maps the stamped reasons to their own classes. Tests: `test/git-canonical-declared-g7a.test.ts` (both engines).- `src/core/persistence/checkout-state.ts` (`readCheckoutState`) — Q1: a canonical checkout against its last fetched upstream, read-only and time-bounded (no fetch): ahead/behind, `diverged`, each commit the upstream lacks (sha, author, date, subject, paths; at most 20) and porcelain counts. `sources writer status` reports it as `checkouts`; doctor `git_convergence` adds the commits and counts for a managed checkout and warns at once on a diverged one.-- `src/core/persistence/git-door.ts`: G2, the door of git-canonical memory (Git is the source of truth, the database derives from it). A source with `sources.config.canonical = "git"` (strict, default off; set by `gbrain sources canonical <id> --to git --apply --expect <hash>`, `git-conversion.ts`) commits each published file before its database row. `publishMutation` (`coordinator.ts`) and `publishGroup` (`group-publish.ts`, one commit per group, after its lane turn) call `commitThroughDoor` under the writer lock, between the file rename and the transaction commit. It commits by plumbing without the checkout's index: `hash-object -w` per file, the trees along the changed paths rebuilt from HEAD (`cat-file tree`, `hash-object -w -t tree`), `commit-tree` with `commitGitTargets`' message, `update-ref` compare-and-swap (one rebuild if the branch moved, then a refusal), then `update-index --cacheinfo` for exactly the published paths (an entry someone staged during the write is left as it is, and the write says its commit landed). That refresh runs under Git's own index lock: `syncIndex` creates `<index>.lock` exclusively (an existing lock the #6932 proof finds abandoned is reclaimed under the caller's writer lock through `reclaimAbandonedIndexLock` in `effect-git.ts` and taken again; any other existing lock refuses with the landed failure, which says why it was not reclaimed), compares the entries, updates a hard-linked copy of the index through `GIT_INDEX_FILE`, and renames the copy onto the lock and the lock onto the index, so no writer that takes the lock can stage between the compare and the write; detached HEAD and unborn branches refuse typed. Each `DoorFile` carries its planned state (`planned`: the sha256 of the bytes the publication wrote, or null for a removal), and the door commits exactly that state or nothing: the file must hash to the plan before and after `hash-object -w` (else `git_target_changed`: nothing is committed and the edit stays on disk; the write is held in recovery as `unexpected_file_bytes` when the file holds neither its bytes nor the version before it, and fails with nothing held when the file holds the version before it), and each target's index entry must equal HEAD's (else `git_index_conflict`, index untouched). An entry that still holds the version its path's last commit replaced (an interrupted door refresh) counts as clean: the write restores it to HEAD and reports the paths as `outcome.persistence.git_index_restored` and the `git_index_restored` notice (`indexRestoredNotice`, emitted by `page-mutations.ts` `emitFenceNotice`). The step deadline is sized from one stat of the index (`gitStepTimeoutMs`), and `refuseIgnored` asks `check-ignore` only about new targets `ignore-rules.ts` cannot clear. Door commits are not coalesced across single writes (each holds its worktree lock exclusively and the consumer runs one per root); a batch commits once through publishGroup. The publication stamps the commit as `outcome.persistence.git_commit` (`git_state: committed`); a target Git refuses rolls the publication back. The Git effect carries `push_only` and joins the push without staging (`effects.ts`). The recovery record carries `door` (checkout and starting HEAD); `recoverPublication` keeps a file whose commit landed (`doorCommitLanded`) instead of restoring it, and the replay completes against it: `replayAfterDoorCommit` in `publishMutation` and the strict exceptions in `page-prepare.ts` (own bytes committed, or a removal HEAD already holds). Old binaries ignore `door`; strict stays off until conversion fences them. Tests: `test/git-door-strict-gbra133.test.ts` (both engines), `test/git-door-plumbing-gbra133.test.ts`, `test/git-door-planned-state.test.ts`, `test/git-door-write-cost.test.ts`, `test/git-door-index-lock-7742.test.ts` (both engines); per-write overhead bench `scripts/bench/door-write-overhead.ts` (opt-in, smoke `test/bench-door-write-overhead.test.ts`).+- `src/core/persistence/git-door.ts`: G2, the door of git-canonical memory. A source with `sources.config.canonical = "git"` (strict, default off; set by `gbrain sources canonical <id> --to git --apply --expect <hash>`, `git-conversion.ts`) commits each published file before its database row. `publishMutation` (`coordinator.ts`) and `publishGroup` (`group-publish.ts`, one commit per group, after its lane turn) call `commitThroughDoor` under the writer lock, between the file rename and the transaction commit. It commits by plumbing without the checkout's index: `hash-object -w` per file, the trees along the changed paths rebuilt from HEAD (`cat-file tree`, `hash-object -w -t tree`), `commit-tree` with `commitGitTargets`' message, `update-ref` compare-and-swap (one rebuild if the branch moved, then a refusal), then `update-index --cacheinfo` for exactly the published paths (an entry someone staged during the write is left as it is, and the write says its commit landed). That refresh runs under Git's own index lock: `syncIndex` creates `<index>.lock` exclusively (an existing lock the #6932 proof finds abandoned is reclaimed under the caller's writer lock through `reclaimAbandonedIndexLock` in `effect-git.ts` and taken again; any other existing lock refuses with the landed failure, which says why it was not reclaimed), compares the entries, updates a hard-linked copy of the index through `GIT_INDEX_FILE`, and renames the copy onto the lock and the lock onto the index, so no writer that takes the lock can stage between the compare and the write; it also sweeps dead processes' index copies (#7755), retries win32 renames (#7756); detached HEAD and unborn branches refuse typed. Each `DoorFile` carries its planned state (`planned`: the sha256 of the bytes the publication wrote, or null for a removal), and the door commits exactly that state or nothing: the file must hash to the plan before and after `hash-object -w` (else `git_target_changed`: nothing is committed and the edit stays on disk; the write is held in recovery as `unexpected_file_bytes` when the file holds neither its bytes nor the version before it, and fails with nothing held when the file holds the version before it), and each target's index entry must equal HEAD's (else `git_index_conflict`, index untouched). An entry that still holds the version its path's last commit replaced (an interrupted door refresh) counts as clean: the write restores it to HEAD and reports the paths as `outcome.persistence.git_index_restored` and the `git_index_restored` notice (`indexRestoredNotice`, emitted by `page-mutations.ts` `emitFenceNotice`). The step deadline is sized from one stat of the index (`gitStepTimeoutMs`), and `refuseIgnored` asks `check-ignore` only about new targets `ignore-rules.ts` cannot clear. Door commits are not coalesced across single writes (each holds its worktree lock exclusively and the consumer runs one per root); a batch commits once through publishGroup. The publication stamps the commit as `outcome.persistence.git_commit` (`git_state: committed`); a target Git refuses rolls the publication back. The Git effect carries `push_only` and joins the push without staging (`effects.ts`). The recovery record carries `door` (checkout and starting HEAD); `recoverPublication` keeps a file whose commit landed (`doorCommitLanded`) instead of restoring it, and the replay completes against it: `replayAfterDoorCommit` in `publishMutation` and the strict exceptions in `page-prepare.ts` (own bytes committed, or a removal HEAD already holds). Old binaries ignore `door`; strict stays off until conversion fences them. Tests: `test/git-door-strict-gbra133.test.ts` (both engines), `test/git-door-plumbing-gbra133.test.ts`, `test/git-door-planned-state.test.ts`, `test/git-door-write-cost.test.ts`, `test/git-door-index-lock-7742.test.ts` (both engines); per-write overhead bench `scripts/bench/door-write-overhead.ts` (opt-in, smoke `test/bench-door-write-overhead.test.ts`).- `src/core/persistence/ignore-rules.ts` — the ignore filter in front of `git check-ignore`; Git stays the only judge of an ignored path. `ignoreCandidates(root, paths)` returns every path some positive ignore rule could match, read from every `.gitignore` from the top level down to the path, `info/exclude` and `core.excludesFile`; a path it drops is one no rule could match. It over-approximates: negated rules are dropped, every wildcard matches any run of characters including `/`, directory-only rules match files, letters compare case-insensitively, each rule is tested against the path and every directory above it in its own and NFC spelling, and an unreadable or non-UTF-8 ignore file or a rule with a backslash or a character outside printable ASCII matches everything under its directory. Every path goes to Git on a sparse checkout or skip-worktree entry, a split or sparse index, an unresolvable `core.excludesFile` or include, a gitlink or symlink along the path, or a failed probe. The probe (rev-parse layout and the configuration with its origin files) is cached per checkout and taken again when a configuration file it read or could read, HEAD or the configuration environment changes; ignore files are re-read on every call and parsed once per content. Callers: `git-door.ts` `refuseIgnored` and `sync-origin-evidence.ts` `gitIgnoresUntracked`. Tests: `test/ignore-rules.test.ts`.diff --git a/docs/architecture/key-files/core-persistence-graduation.md b/docs/architecture/key-files/core-persistence-graduation.mdindex 4bb639911e..1666696efe 100644--- a/docs/architecture/key-files/core-persistence-graduation.md+++ b/docs/architecture/key-files/core-persistence-graduation.md@@ -17,7 +17,7 @@ Verified engine graduation, PGLite to Postgres ([operator guide](../../guides/mo- `src/commands/migrate-graduation.ts` — the `gbrain migrate` graduation CLI, routed before connect from `routeEngineFreeSubcommands` in `src/cli.ts` when `routesToGraduation` holds (run-scoped verbs and `--plan` always; a bare `--to postgres|supabase` on a durable PGLite config unless `migrate.graduation` is false or the host is Windows). Without `--yes --expect` it plans and returns the `confirmation_required` payload (effects egress and destructive, what moves and what stays, `plan_hash`, the `--plan` preview; no stdin prompt); `--plan`/`--dry-run` prints the plan; the run reports the receipt, retained copy, target doctor, `gbrain mcp expose` and the MCP restart note. Exit codes 0/1/2/3, 11 for a progressing drain stop (1 when a blocker needs a person), 75 for `graduation_in_progress`, 130 after SIGINT (stops at the next batch boundary). `--json` prints one document; progress goes to stderr per table and batch. Test: `test/migrate-graduation-cli.serial.test.ts`.- `src/commands/doctor/checks/engine-graduation.ts` — `graduationStateCheck`, emitted from the filesystem lane of `local-audits.ts`: `graduation_interrupted` fails when a manifest or marker is non-terminal with no live owner (fix `gbrain migrate --resume`, rollback named) or a stray brain sits at the old path, is `ok` while a live run owns it, exempts the run named by `GBRAIN_GRADUATION_RUN`, and emits nothing on a brain that never graduated. The retained `.graduated-*` copy is reported by `pglite_leftovers` (`src/core/pglite-leftovers-check.ts`), silent while a manifest is non-terminal.- `src/core/repair/missing-tables.ts` — `gbrain repair missing-tables` (#6911), explicit-only and preview-bound (`--apply --expect <hash>`), brain-wide, DDL only. The preview lists the missing rebuildable caches `readMissingTables` reports (`recreate`), plus `user_data_tables` and `other_tables` residuals it never recreates; the hash covers the brain id, `LATEST_VERSION` and the tables. Apply refuses when the brain schema is newer than the client, leaves a table that already exists alone (`already_present`, no DDL), runs `recreateStep` in one transaction per table under the migration statement and lock timeouts (`schemaLockBlockedError` on a lock timeout), maps 42501 to `schema_owner_required` (approval kept) and 23505/42P07 races to `already_present`, and retires the approved set with the last item. Tests: `test/purge-missing-cache-6911.test.ts`, `test/schema-missing-tables.test.ts`.-- `src/core/repair/url-clone-fences.ts` — `gbrain repair url-clone-fences` (#6946, GBRA-130 C-2): explicit-only, preview-bound, destructive consent; unmanaged brains only (a managed brain gets a warning naming `sources mirror-readonly`). The survey lists every tracked file of each owned clone in scope that differs from HEAD (`trackedChanges`) and proves per file (`proveFenceRowsOnly`) that HEAD's fence rows are an unchanged prefix of the working copy's and that re-rendering HEAD with the working fence matches byte for byte (`fence_rows_only`); anything else is listed as `non_fence_edit` / `unparsed_fence` / `staged_change` / `deleted` / `not_in_head` / `unreadable_checkout` and never touched; a file whose HEAD would not import (`headHold`, the import screen with `holdNoncanonicalPrivate`) is listed under the hold's code, and at apply its rows still go database-only and the file is restored (so the clone can pull) but HEAD is not imported; the import opts in too, and a held file reports `held` with the code instead of `restored` (#7897). The preview hash binds the approved set (preview-approval, keyed by the command string). The apply, per file under the source filesystem lock and page lock, rechecks both sides (`changed_since_preview`), backs the file up under `~/.gbrain/backups/url-clone-fences/`, clears `row_num`/`source_markdown_slug` on the appended rows in one `maintenanceTransaction` (inserting database-only any row the database lost), imports HEAD's bytes as the page through `importFromContent`, and only then restores the file from HEAD; each step is idempotent. Tests: `test/pathological/c2-url-clone-fences.test.ts`, `test/url-clone-fences-private-hold-7897.test.ts`.+- `src/core/repair/url-clone-fences.ts` — `gbrain repair url-clone-fences` (#6946, GBRA-130 C-2): explicit-only, preview-bound, destructive consent; unmanaged brains only (a managed brain gets a warning naming `sources mirror-readonly`). The survey lists every tracked file of each owned clone in scope that differs from HEAD (`trackedChanges`) and proves per file (`proveFenceRowsOnly`) that HEAD's fence rows are an unchanged prefix of the working copy's and that re-rendering HEAD with the working fence matches byte for byte (`fence_rows_only`); anything else is listed as `non_fence_edit` / `unparsed_fence` / `staged_change` / `deleted` / `not_in_head` / `unreadable_checkout` and never touched; a file whose HEAD would not import (`headHold`, the import screen with `holdNoncanonicalPrivate`) is listed under the hold's code, and at apply its rows still go database-only and the file is restored (so the clone can pull) but HEAD is not imported; the import opts in too, and a held file reports `held` with the code instead of `restored` (#7897), with `applied: true` (its rows moved and its file was restored), and is an apply item, never also a residual (#7910). The preview hash binds the approved set (preview-approval, keyed by the command string). The apply, per file under the source filesystem lock and page lock, rechecks both sides (`changed_since_preview`), backs the file up under `~/.gbrain/backups/url-clone-fences/`, clears `row_num`/`source_markdown_slug` on the appended rows in one `maintenanceTransaction` (inserting database-only any row the database lost), imports HEAD's bytes as the page through `importFromContent`, and only then restores the file from HEAD; each step is idempotent. Tests: `test/pathological/c2-url-clone-fences.test.ts`, `test/url-clone-fences-private-hold-7897.test.ts`.- `src/core/schema-missing-tables.ts` — #6911 expected-table check. `readMissingTables`: at head every graduation-inventory table for the engine, below head only the recreatable caches whose creating migration (`CREATED_BY`) already ran, `skipped` (`client_behind`) when the brain is newer; each missing table carries its inventory class and `loss_kind`. `recreateStep` (own-key lookup, rebuild class only) rebuilds `query_cache` (v055 DDL sized from the live `facts.embedding` shape, then the v056/v090/v091 statements) and `code_traversal_cache` (v059), then on Postgres enables RLS on the recreated table through v275's `protectTables` (a role that does not bypass RLS or own the table leaves it RLS-off and names it on stderr). `test/schema-missing-tables.test.ts` pins each recreated table's columns and indexes to the migrated brain's on both engines and checks that every inventory rebuild table is either in `RECREATABLE_TABLES` or defined by the base schema (so `init --migrate-only` recreates it). Doctor `schema_missing_tables` (`src/commands/doctor/checks/schema-health.ts`) renders it: warn for caches (repair preview fix) and tables without user data, fail for `user_data` tables.- `src/commands/doctor/checks/schema-function-bodies.ts` — `schema_function_bodies` (#7776, META, after `schema_version`): every function this binary's schema blob defines (`SCHEMA_SQL` or the PGLite template, parsed, never hand-listed; the writer-fence guards v197, v272 and v278 replace among them) must have its body installed, compared after whitespace and FTS-configuration normalization. Checked only at head (`skipped` with `client_behind` above it, `migrations_pending` below); a mismatch fails, names the functions and points at `gbrain init --migrate-only` after every gbrain on the database is upgraded. `test/doctor-schema-function-bodies.test.ts` pins that a fresh install matches.- `src/core/persistence/rebuildable-cache.ts` — #6911 purge-side skip: `isRebuildableCache` (inventory class `rebuild`), `relationExists` (`to_regclass` on the connection's search path), and `clearRebuildableCache(tx, table)`, which returns the rows deleted or null when the cache table is absent; the existence check runs first because a 42P01 aborts a Postgres transaction. Callers: page purge (`purge.missing_caches`) and fact purge.diff --git a/docs/architecture/key-files/core-persistence-request-indexes.md b/docs/architecture/key-files/core-persistence-request-indexes.mdindex 23bbbe56ec..b40de69fc4 100644--- a/docs/architecture/key-files/core-persistence-request-indexes.md+++ b/docs/architecture/key-files/core-persistence-request-indexes.md@@ -6,7 +6,7 @@ The online-built request-table indexes (the managed sync checkpoint pair, the pa- `src/core/persistence/checkpoint-validation.ts` — the managed sync checkpoint's incomplete-receipt validation (#5762): `INCOMPLETE_SYNC_RECEIPT_SQL` is three `LIMIT 1` probes (recovery; an open page receipt of the run; a non-committed page receipt with no committed sibling at its index) served by `persistence_requests_recovery`, `persistence_requests_sync_run_open` and `persistence_requests_sync_run_committed`, with the same result as the former single predicate. `findIncompleteSyncReceipt` returns the blocking receipt's request id and maps only this statement's 57014 statement timeout to the terminal, non-transient `checkpoint_validation_timeout`. `readRequestIndexStates` reads each index of `PERSISTENCE_REQUEST_ONLINE_INDEXES` (or the list passed) as valid, missing, INVALID or building (Postgres `pg_stat_progress_create_index`); `formatCheckpointTimeoutHint` / `checkpointTimeoutHint` is the one formatter for the three-state hint and the filled retry (`gbrain sync --source <id> --no-pull --retry-failed` plus the cursor-selecting options the checkpoint intent records in `syncOptions` and the saved processing flags), used by the sync summary and `get_write_request`. Tests: `test/persistence-sync-checkpoint-validation.test.ts`, `test/e2e/persistence-request-indexes-postgres.test.ts`.- `src/core/persistence/fault-points.ts` — named crash seams for the persistence gate. `faultPoint(point, detail)` is a no-op unless a gate worker installed a hook with `installFaultHook`; production never does. Seams: `publication:<boundary>` (the five `PublicationHooks.boundary` names, routed through `withFaultPoints` in `publishMutation`), `effect:<kind>:mid` for every `EffectKind` in `completeEffect` (after the side effect, before its completion is recorded; `EFFECT_FAULT_POINTS` is a `Record<EffectKind, FaultPoint>`), `effect_recovery:before_clear` (`effect-recovery.ts`), `large_file:stage_streaming` (after each piece `stageStreamedContent` writes to a stage's in-progress name), `effect_recovery:before_stage` / `effect_recovery:staged` (a streamed, version 2 withdrawal mirror: once its record is durable, before its file is streamed into the publication stage, and after that step, before the recovery transaction renames the stage), `publication_recovery:before_clear` (`recoverPublication`), `sync:mid_checkpoint` (after each committed cursor step in `sync-run.ts` `saveCursor`), `sync:after_freeze` (#6712 PR 0: at the end of `freezeEntry` for an import entry, after its bytes are read and before the request is admitted; detail carries `slug` and `path`), `consumer:prepared` (between preparing a claimed request and publishing it), `stuck_recovery:*` (between the steps of `recovery-resolve.ts`) and the purge lookups `purge:*` (page-purge.ts, intent-redaction.ts, facts/purge.ts; a hook throwing a 57014 models a statement timeout). Used by `scripts/persistence/crash-robot.ts`, the #6511 tests and `test/sync-convergence.serial.test.ts`, which installs it in real `serve`/`sync` processes through the `test/fixtures/convergence-fault-kill.ts` preload (one action registry: kill, uncommitted edit, stall until released, or throw a given SQLSTATE, at the nth hit).-- `src/core/persistence/recovery-resolve.ts` + `src/core/repair/stuck-recovery.ts` — `gbrain repair stuck-recovery [--source <id>] [--request-id <uuid>]` (#6650 §1.10; GBRA-130 C-1, C-4), explicit-only, preview-bound and destructive (registry `consentText`; `--apply --expect <hash> --keep prior|disk|withdrawn --yes`, a non-interactive apply without `--yes` exits 3; a `--keep` some approved record does not offer refuses `recovery_choice_refused` in the kind's plan before anything runs). `scanStuckRecoveries` (owner host only, else `owner_unavailable` for a named source) reads the source's queued head blocker (`readHeadBlockers`; its `request_recovery` ids select the records) and every non-terminal recovery record on the worktree blocked on `unexpected_file_bytes` or whose file matches neither recorded version: a page record (`target: 'page'`) or a v2 shared-skill bundle record (`target: 'skill_bundle'`, every file of the bundle; a file matches a recorded version only when `bundleFileHash` also accepts its mode and shape). A bundle record `recoveryFiles` cannot read is listed in `refused` as `recovery_bundle_unsupported` (residual `bundle_refused`; named with `--request-id` it throws with the same ask_user fix). Every withdrawal-mirror effect recovery on the worktree whose file is not a regular file holding its pre-withdrawal or withdrawn bytes is an item too (`target: 'withdrawal_mirror'`, id `effect:<id>`, `effect_id`, the forget's `request_id`; its file view adds `withdrawn`, the recorded post-withdrawal fingerprint, and its only choice is `withdrawn`); a record without usable withdrawn bytes, or bound to another owner epoch, root or incarnation, is listed in `refused` as `recovery_effect_unsupported` (residual `effect_recovery`) with `fix` `{ ask_user, argv: gbrain repair stuck-recovery --source <id> --request-id <request> }` and a `user_message`, and named with `--request-id` it throws with that fix; a blocked terminal request is listed in `refused` (residual `terminal_refused`; named with `--request-id` it refuses `recovery_choice_refused`, as does a choice the record cannot support), and unblocked terminal cleanups, staging-byte blocks and self-recovering records are residuals. Each item lists every file's prior (or absent) and disk (or deleted) fingerprints and what recovery sees; a local preview writes the prior (an effect's `withdrawn`), disk and unified-diff files 0600 under `~/.gbrain/backups/stuck-recovery/<request>/<digest>/` (a private directory outside every checkout) and prints the `diff -u` command. The item digest binds the recovery identity (attempt, owner epoch, path and published hash per file), the recorded prior hashes, each file's disk view and the page's `knowledge_revision`. `resolveStuckRecovery` runs under `acquireWorktree` with a bounded wait (10 s, then `writer_lock_unavailable`; so the resident recovery pass returns unchanged), re-verifies the digest (`preview_changed`) and journals in `op_checkpoints` op `stuck-recovery-resolution` keyed `<request row id>:<preview hash>` (exempt from the checkpoint purge; the finished row is the audit entry): `backed_up` (disk and prior bytes durable, always), then `written` (`--keep prior`: `upgradeRecoveryStaging` reserves an older record's restoration stage within the recovery budget, `queue_capacity` otherwise, then the prior bytes are published through `publishPersistenceFile` at that stage after `cleanupRecoveryStaging`, an absent prior unlinked) or `abandoned` (`--keep disk`, #6640's drop: `completeWrite` ends the live request `conflict` `source_changed`, or `finishUnpublishedFailure` with its recorded failure; the record is never rewritten, so its reserved bytes are released by the terminal path's `clearResolvedRecovery`), then `recoverPublication(…, alreadyLocked)` finishes by its unchanged rule and the journal records `done` with the result. A step refuses `unexpected_file_bytes` when the file changed again; a different `--keep` for the same hash refuses `idempotency_conflict`; an identical apply after `done` replays the result (also after the approved set aged out). A record the resident consumer (any version) or an earlier killed run already finished reports `finished_by: another_pass`. `--keep prior` on a request with no recorded failure requeues it (the accepted write publishes again). `--keep disk` hands off to `gbrain sources reconcile <source> <slug> --brain host --preview` and never reports the page repaired. A record whose prior file is over the single-string ceiling (`staging.before`) resolves the same way in bounded memory: the disk file and the staged copy are hashed in pieces (the copy's state, `verified`, `missing` or `mismatched`, is in the prior view and the digest), backups are kernel copies checked by streamed hash, the diff file is a summary (both fingerprints, the first differing byte, a window of at most 1 KiB; `cmp` reproduces it), `--keep prior` runs recovery's `restoreBeforeStage` after `cleanupRecoveryStaging(keepBefore)`, and `--keep disk` backs up a mismatched copy (`<index>.prior-stage`) and removes it before abandoning. `--keep prior` without a verified copy refuses `recovery_prior_stage_unavailable` (registry entry; its fix is the `--keep disk` apply under the same hash). An effect item resolves through `resolveEffectRecovery` under the same lock and journal (key `effect:<id>:<preview hash>`): `backed_up` (the edited bytes beside the withdrawn bytes and their diff), `written` (first `rebaseStaleEffectRecovery` (`effect-recovery.ts`): when a later withdrawal moved the page past the record, the record is rebased under its page lock on the latest snapshot's `mirrorContent` bytes (the rendering `mirrorPage` itself writes), its publication stage and reserved bytes following them, and the journal stores the rebased `identity` in the same transaction, so the recorded bytes never put a later-withdrawn fact back on disk and a rerun resumes; a page deleted, replaced or segmented meanwhile refuses `recovery_effect_unsupported` with nothing written; then `upgradeRecoveryStaging` `forward` and the record's `after` bytes published at its publication stage, mode restored), then `claimAndRecoverEffect` (`effects.ts`, the resident pass's own claim + `recoverEffectPublication` + failure recording) materializes the page, clears the record and advances the effect's cursor, and `trueUpRequests` settles the forget's receipt; `--keep disk`/`prior` on it refuse `recovery_choice_refused`, since keeping the edited or pre-withdrawal bytes would let the next sync re-import the forgotten fact. A bundle's `--keep prior` writes the prior bytes of its edited files and `recoverPublication` restores the rest; `--keep disk` keeps every file and abandons the publication; both back up every file first. Fault seams `stuck_recovery:{backed_up,written,abandoned,recovered}`. Tests: `test/repair-stuck-recovery.test.ts`, `test/e2e/repair-stuck-recovery-postgres.test.ts`, `test/pathological/c1-effect-stuck-recovery.test.ts` and `test/pathological/c4-bundle-stuck-recovery.test.ts` (both engines; the effect probe asserts the forgotten fact stays forgotten after the resolution, a commit and a sync).+- `src/core/persistence/recovery-resolve.ts` + `src/core/repair/stuck-recovery.ts` — `gbrain repair stuck-recovery [--source <id>] [--request-id <uuid>]` (#6650 §1.10; GBRA-130 C-1, C-4), explicit-only, preview-bound and destructive (registry `consentText`; `--apply --expect <hash> --keep prior|disk|withdrawn --yes`, a non-interactive apply without `--yes` exits 3; a `--keep` some approved record does not offer refuses `recovery_choice_refused` in the kind's plan before anything runs). `scanStuckRecoveries` (owner host only, else `owner_unavailable` for a named source) reads the source's queued head blocker (`readHeadBlockers`; its `request_recovery` ids select the records) and every non-terminal recovery record on the worktree blocked on `unexpected_file_bytes` or whose file matches neither recorded version: a page record (`target: 'page'`) or a v2 shared-skill bundle record (`target: 'skill_bundle'`, every file of the bundle; a file matches a recorded version only when `bundleFileHash` also accepts its mode and shape). A bundle record `recoveryFiles` cannot read is listed in `refused` as `recovery_bundle_unsupported` (residual `bundle_refused`; named with `--request-id` it throws with the same ask_user fix). Every withdrawal-mirror effect recovery on the worktree whose file is not a regular file holding its pre-withdrawal or withdrawn bytes is an item too (`target: 'withdrawal_mirror'`, id `effect:<id>`, `effect_id`, the forget's `request_id`; its file view adds `withdrawn`, the recorded post-withdrawal fingerprint, and its only choice is `withdrawn`); a record without usable withdrawn bytes, or bound to another owner epoch, root or incarnation, is listed in `refused` as `recovery_effect_unsupported` (residual `effect_recovery`) with `fix` `{ ask_user, argv: gbrain repair stuck-recovery --source <id> --request-id <request> }` and a `user_message`, and named with `--request-id` it throws with that fix; a blocked terminal request is listed in `refused` (residual `terminal_refused`; named with `--request-id` it refuses `recovery_choice_refused`, as does a choice the record cannot support), and unblocked terminal cleanups, staging-byte blocks and self-recovering records are residuals. Each item lists every file's prior (or absent) and disk (or deleted) fingerprints and what recovery sees; a local preview writes the prior (an effect's `withdrawn`), disk and unified-diff files 0600 under `~/.gbrain/backups/stuck-recovery/<request>/<digest>/` (a private directory outside every checkout) and prints the `diff -u` command. The item digest binds the recovery identity (attempt, owner epoch, path and published hash per file), the recorded prior hashes, each file's disk view and the page's `knowledge_revision`. `resolveStuckRecovery` runs under `acquireWorktree` with a bounded wait (10 s, then `writer_lock_unavailable`; so the resident recovery pass returns unchanged), re-verifies the digest (`preview_changed`) and journals in `op_checkpoints` op `stuck-recovery-resolution` keyed `<request row id>:<preview hash>` (exempt from the checkpoint purge; the finished row is the audit entry): `backed_up` (disk and prior bytes durable, always), then `written` (`--keep prior`: `upgradeRecoveryStaging` reserves an older record's restoration stage within the recovery budget, `queue_capacity` otherwise, then the prior bytes are published through `publishPersistenceFile` at that stage after `cleanupRecoveryStaging`, an absent prior unlinked) or `abandoned` (`--keep disk`, #6640's drop: `completeWrite` ends the live request `conflict` `source_changed`, or `finishUnpublishedFailure` with its recorded failure; the record is never rewritten, so its reserved bytes are released by the terminal path's `clearResolvedRecovery`), then `recoverPublication(…, alreadyLocked)` finishes by its unchanged rule and the journal records `done` with the result. A step refuses `unexpected_file_bytes` when the file changed again; a different `--keep` for the same hash refuses `idempotency_conflict`; an identical apply after `done` replays the result (also after the approved set aged out). A record the resident consumer (any version) or an earlier killed run already finished reports `finished_by: another_pass`. `--keep prior` on a request with no recorded failure requeues it (the accepted write publishes again). `--keep disk` hands off to `gbrain sources reconcile <source> <slug> --brain host --preview` and never reports the page repaired; on a git-canonical source (`binding.canonical_git`) a page's follow-up is commit (`gbrain git commit-push --path <checkout>`) or `git restore`, then sync, with an `ask_user` `fix` in the item detail (`strictKeptEdit`, #7715). A record whose prior file is over the single-string ceiling (`staging.before`) resolves the same way in bounded memory: the disk file and the staged copy are hashed in pieces (the copy's state, `verified`, `missing` or `mismatched`, is in the prior view and the digest), backups are kernel copies checked by streamed hash, the diff file is a summary (both fingerprints, the first differing byte, a window of at most 1 KiB; `cmp` reproduces it), `--keep prior` runs recovery's `restoreBeforeStage` after `cleanupRecoveryStaging(keepBefore)`, and `--keep disk` backs up a mismatched copy (`<index>.prior-stage`) and removes it before abandoning. `--keep prior` without a verified copy refuses `recovery_prior_stage_unavailable` (registry entry; its fix is the `--keep disk` apply under the same hash). An effect item resolves through `resolveEffectRecovery` under the same lock and journal (key `effect:<id>:<preview hash>`): `backed_up` (the edited bytes beside the withdrawn bytes and their diff), `written` (first `rebaseStaleEffectRecovery` (`effect-recovery.ts`): when a later withdrawal moved the page past the record, the record is rebased under its page lock on the latest snapshot's `mirrorContent` bytes (the rendering `mirrorPage` itself writes), its publication stage and reserved bytes following them, and the journal stores the rebased `identity` in the same transaction, so the recorded bytes never put a later-withdrawn fact back on disk and a rerun resumes; a page deleted, replaced or segmented meanwhile refuses `recovery_effect_unsupported` with nothing written; then `upgradeRecoveryStaging` `forward` and the record's `after` bytes published at its publication stage, mode restored), then `claimAndRecoverEffect` (`effects.ts`, the resident pass's own claim + `recoverEffectPublication` + failure recording) materializes the page, clears the record and advances the effect's cursor, and `trueUpRequests` settles the forget's receipt; `--keep disk`/`prior` on it refuse `recovery_choice_refused`, since keeping the edited or pre-withdrawal bytes would let the next sync re-import the forgotten fact. A bundle's `--keep prior` writes the prior bytes of its edited files and `recoverPublication` restores the rest; `--keep disk` keeps every file and abandons the publication; both back up every file first. Fault seams `stuck_recovery:{backed_up,written,abandoned,recovered}`. Tests: `test/repair-stuck-recovery.test.ts`, `test/e2e/repair-stuck-recovery-postgres.test.ts`, `test/pathological/c1-effect-stuck-recovery.test.ts` and `test/pathological/c4-bundle-stuck-recovery.test.ts` (both engines; the effect probe asserts the forgotten fact stays forgotten after the resolution, a commit and a sync).- `src/core/persistence/native-file-target.ts` — shared preparation/Git execution spelling resolution. Native directory-entry inode/device identity proves aliases; no global case folding or separator rewrite. Missing suffixes retain exact spelling, descendant symlinks and ambiguous aliases refuse, and physical root identity is rechecked. Exact POSIX case-distinct names and literal backslashes remain distinct. #5032: `isWindowsColonTarget(rel)` and `colonSlugWindowsRefusal(slug, sourceId)` name the one Windows-only refusal (`colon_slug_windows_write_through`: `:` names an NTFS alternate data stream); `submitPageMutation` raises it before admission when this host publishes the file, `prepareFileTarget` at publication, and managed (`fileRefusals`) and unmanaged (`failedFiles`) sync skip each such path by name (`test/colon-slug-windows-5032.test.ts`). A path segment over 255 bytes, or `ENAMETOOLONG` from the lookup, refuses `invalid_params` with detail `file_name_too_long` and a fix naming a slug whose segments fit 240 bytes (`test/pathological/b12-slug-segment-bytes.test.ts`).- `src/core/persistence/admission-retry.ts` — bounded retries for database-confirmed admission transaction aborts. Each retry reuses the UUID and normalized intent, rechecks guarded authority and reserves quota only on commitment. Standalone journal admission uses 100ms lock waits within the five-second retry budget to retain queue position behind short counter transactions; backoff occurs after rollback releases the connection so counter contention leaves pool capacity for reads. Ambiguous connection/commit errors are never classified as confirmed rollback. #6355: a session that drops under the attempt (`isConnectionLoss` in `retry-matcher.ts`: connection-class SQLSTATEs, postgres.js's connection codes, `57P01`/`57P02`/`57P03`, the socket errnos) re-runs the attempt after `CONNECTION_LOSS_RETRY_MS` (100/300/900 ms), which is safe because every attempt reads the retained request id first and replays an admitted row; when the session keeps dropping the caller gets `writeOutcomeUnknown` (`write_outcome_unknown`, `reason: connection_lost`, fix: read the request by id), never the raw socket error the crash robot's receipt oracle took for a refusal while the write committed (`test/persistence-admission-connection-loss.test.ts`, forced probes: a lost COMMIT acknowledgment; a dead lent transaction used once with the pool finishing the write). The optional `recover(error)` hook runs before each re-run; `admitWrite` uses it to rebuild the pool (`engine.reconnect`) and to move the re-run from a lent transaction (the consumer's lane, `onPersistenceLane`) to `engine.transaction`, since a dropped reservation fails every later use the same way ("Connection is no longer owned"). Real counter-lock, sustained-queue progress, read-capacity and after-insert rollback tests live in `test/persistence-journal.test.ts`. Withdrawal retries wrap its whole source-exclusive transaction with its existing lock policy; `admitWriteInTransaction` never backs off inside an existing unit of work. `test/persistence-withdrawal-retry.test.ts` verifies guard release, complete rollback and bounded contention. #6278 (B7): also the outstanding-request cap's `detail` format (`outstandingCapacityDetail`, `outstanding=N limit=M`, stamped by `journal.ts` `capacityError`) and its readers `isWriteCapacityWait` / `outstandingCapacityOf`, which the managed drain and `sync-run.ts`'s failure ledger use to tell a refusal that clears by itself from a cumulative cap. #8621: `waitOutRefreshFence` re-runs an interactive write's whole admission while a refresh fence refuses it (`worktree_refreshing`; 250 ms to 2 s backoff, `REFRESH_FENCE_WAIT_MS` = 10 s cap shared by every item of a `remember` batch via `withRefreshFenceBudget`, lowered by an explicit `wait_ms`); background writes and the managed sync are not waited for (`test/write-refusal-refresh-fence-8621.test.ts`).- `src/core/persistence/unbound-source.ts` — #5254 policy for a Postgres page write to a filesystem source (`local_path`, or `sync.repo_path` for `default`) with default write-through and no worktree binding. `submitPageMutation` refuses `owner_unavailable` with `detail: unbound_source`, a `docs` pointer to `write-refusals.md#unbound-sources-on-postgres`, and a hint naming the filled `sources writer status`/`writer claim ... --admin-intent writer_claim --expected-state <admin_state>` bind command (host path only for trusted local callers) and, for `put_page` to a page without `source_path`, `gbrain config set persistence.unbound_write database_only`. That key (`refuse` default, validated by `config set`; any other stored value refuses) lets such a `put_page` admit with `databaseOnlyReason: 'unbound_source'`. `decideUnboundWrite` is the one rule page writers and fact writers (`remember`, loop-fact retirement and relink through `fact-write-target.ts`, #6608) apply to a rooted source with no binding: connector → `connector_database`; PGLite not activation-listed database-only (#6449) → automatic claim; otherwise a page with a recorded canonical file, or the key unset, refuses and the rest is database-only. `remember` keeps its frozen `unavailable` code and carries the refusal's detail, docs and fix (`verb-errors.ts`). On a classic brain (managed persistence not activated) the hint leads with the classic write path: write `<checkout>/<slug>.md`, commit it, `gbrain sync --source <id>` (a remote caller is told to ask the user to). The refusal is `retryable: false` with a `fix` of `next: ask_user` and a `user_message` (classic or managed wording), because every way out is the user's choice (`test/unbound-source-hint.test.ts`). Publication rechecks inside its transaction, after `authorizeStoredRequest` share-locks the source row, that the source is still unbound and the page still has no `source_path` (else `owner_unavailable`/`unbound_source`, hint rebuilt from the persisted message by `writeResponse`), then stamps `pages.database_only_reason='unbound_source'` (migration 177). After binding, `prepareFileTarget` keeps a stamped page with no file database-only (receipt `write_through.skipped: unbound_source` with a warning) and managed sync refuses to import a file at its path (`source_changed`, diagnostic reason `unbound_source`). PGLite keeps auto-claiming. Tests: `test/e2e/unbound-source-postgres.test.ts`, `test/persistence-unbound-source.test.ts`. See [persistence stalls](persistence-stalls.md).diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.mdindex b7f65c7226..42b60470c7 100644--- a/docs/architecture/key-files/files-and-sync-1.md+++ b/docs/architecture/key-files/files-and-sync-1.md@@ -15,7 +15,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/data-frontmatter.ts` — shared data-only YAML/JSON parsing and serialization. Rejects unsupported language selectors before parsing, uses js-yaml safe schema (exported `FRONTMATTER_SCHEMA`) with existing scalar types (a calendar-invalid timestamp such as `2024-02-30` stays a string instead of rolling over to March 1), sanitizes parser errors, and keeps body text opaque. `loadBoundedYaml` is the only js-yaml `load` call for content gbrain did not write (frontmatter, recovery, brain-writer, skill and rename-identity readers): after load it sizes the value as if every alias were copied out, memoized and cycle-safe, and throws `YamlAliasBoundError` (js-yaml-shaped `reason` and `mark` at the first alias) past text length + `MAX_YAML_ALIAS_EXPANSION` (65,536), so an alias bomb is a YAML_PARSE / `invalid_frontmatter` refusal before anything serializes it. Used by markdown, capture, recipes, plugins, and greenfield ingestion. Independent fixtures: `test/data-frontmatter.test.ts`, `test/frontmatter-security.test.ts`, `test/pathological/s-47-yaml-alias-bomb.test.ts`.-- `src/core/default-source-path-check.ts` — pure `assessDefaultSourcePath(input)` verdict for the `default_source_local_path` doctor check (no DB/FS access — caller supplies gathered inputs, the npm-squat-check.ts shape). INVARIANT: `default.local_path: null` is the DESIGNED fallback topology (write-through nests under `sync.repo_path`), NOT an error — a null pointer warns ONLY when it provably breaks something: the fallback repo is another source's own working tree (the leak-guard collision: every unscoped default write-through silently skipped), or default has file-backed pages and no resolvable root. It also warns when a set `local_path`, or behind a null one `sync.repo_path`, is relative (neither POSIX- nor Windows-absolute): sync refuses it `sync_anchor_relative`. Everything else (no pages, resolvable fallback, deliberate DB-only brain) is ok. The repair it names is the non-destructive `gbrain sources set-path default <path>`.+- `src/core/default-source-path-check.ts` — pure `assessDefaultSourcePath(input)` verdict for the `default_source_local_path` doctor check (no DB/FS access — caller supplies gathered inputs, the npm-squat-check.ts shape). INVARIANT: `default.local_path: null` is the DESIGNED fallback topology (write-through nests under `sync.repo_path`), NOT an error — a null pointer warns ONLY when it provably breaks something: the fallback repo is another source's own working tree (the leak-guard collision: every unscoped default write-through silently skipped), or default has file-backed pages and no resolvable root. It also warns when a set `local_path`, or behind a null one `sync.repo_path`, is relative (not absolute on this host): sync refuses it `sync_anchor_relative`. Everything else (no pages, resolvable fallback, deliberate DB-only brain) is ok. The repair it names is the non-destructive `gbrain sources set-path default <path>`.- `src/core/disk-walk.ts` — `walkBrainRepo(repoPath)` returns `Map<slug, {size, mtimeMs}>` from one recursive `readdirSync`. Skips dot-dirs, `node_modules`, non-`.md` files. Used by `gbrain storage status` instead of per-page `existsSync + statSync` (~400K syscalls on 200K-page brains → tens).diff --git a/docs/architecture/key-files/files-and-sync-2.md b/docs/architecture/key-files/files-and-sync-2.mdindex f46059b51e..cf429ec24a 100644--- a/docs/architecture/key-files/files-and-sync-2.md+++ b/docs/architecture/key-files/files-and-sync-2.md@@ -12,7 +12,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/import-chunk-reuse.ts` — `reuseStoredChunkVectors`: A13 vector reuse for one markdown page import, shared by the inline import (before its transaction, to decide which chunks reach the provider) and every import's transaction (under the page lock, `importFromContent` in `import-file.ts`). It copies each stored vector the reuse gate admits onto its matching new chunk and maps the chunk to the stored row id when that row already holds exactly what the chunk would insert, so the import keeps it in place and deletes and writes only the rest; with `keepUnembedded` (the in-transaction pass) an identical never-embedded row stays under a new chunk that carries no vector either. Inline, `--no-embed` and prepared imports all keep rows; a prepared import reuses nothing from a page stored under per-chunk synopsis. With `requireRecordedInput` (set by `importFromContent` when the old or new body holds a protected fence, #6961) only a stored vector with a recorded embedding input is admitted, never the legacy raw-text match. Pinned by `test/fenced-embed-reuse-6961.test.ts`, `test/import-inline-chunk-keep.test.ts` (both engines) and `test/persistence-edit-embedding-reuse.test.ts`. `reuseSegmentChunkVectors` (Wave B) reads only the rows of the retired occurrences with their vectors and applies the same gate and `chunk_source\0chunk_text` plan, so an unchanged chunk inside a rewritten tail keeps its vector.- `src/core/sync-policy.ts` — `isSyncDisabledConfig(config)`: the one predicate for `config.syncEnabled === false` ("excluded from AUTOMATIC/bulk sync"), unwrapping PGLite's JSON-string config scalar via `parseSourceConfig`. Read by the `sync --all` fan-out filter (`src/commands/sync.ts`), autopilot's per-source freshness dispatcher (`src/commands/autopilot.ts`, skip before `queue.add('sync')`) and the full-cycle fan-out (`src/commands/autopilot-fanout.ts`, which drops the `sync` phase + pull from a disabled source's `autopilot-cycle` payload but keeps lint/backlinks/extract and the freshness stamp) and the `sync_enabled` column of `buildSyncStatusReport` (`src/core/sync-status-report.ts`, whose callers pass RAW `SELECT config` rows — a JSON string on PGLite — so a raw cast there contradicted the fan-out filter). Doctor's `checkSyncFreshness` also applies this predicate, including the legacy query fallback: disabled sources contribute neither warnings nor freshness counts; only boolean `false` disables, not the string `'false'`. `checkCycleFreshness` still monitors their maintenance cycles. Pinned by `test/doctor-sync-policy.test.ts` and `test/doctor-cycle-freshness.test.ts`. Deliberately does NOT gate `performSync()`: an explicit `gbrain sync --source <id>` still runs; `sync-cost-gate.ts` keeps its own inline check because it also feeds the explicit single-source cost preview. Pinned by `test/sync-policy.test.ts`, the `#4399` cases in `test/autopilot-fanout-wiring.test.ts` (source-text) and `test/autopilot-fanout.test.ts` (stubbed dispatch).-- `src/core/sync-applicability.ts` — agent-first operator wave E4. `syncContentDirectory(engine, {sourceId, repoPath})` resolves the sync root exactly as `performSync` does and returns it when it is a gbrain-owned content directory (under `<GBRAIN_HOME>/.gbrain/content/`, or an owned `--content-root` recorded in the shared-skills setup receipt) with no `.git` at the root; null otherwise (fail-open). `assertSyncAnchorAbsolute` refuses `sync_anchor_relative` (`syncAnchorRelativeError`: exit 3, an `ask_user` fix naming `gbrain sources set-path <id> <absolute-directory>`, or `gbrain config set sync.repo_path` with no source) when the stored anchor (`sources.local_path`, else `sync.repo_path`) is relative and no absolute or different `repoPath` was passed; single-source and `--all` CLI syncs refuse it before the cost gate walks the directory, and a cycle whose directory matches no source checks `default` and fails its sync phase with that code. A path absolute only on another operating system (a Windows drive path read on Linux or macOS) gets the same code with a `set-path`-only fix, since `--clear` refuses it. `src/core/sync-anchor.ts` never proves ownership from a relative anchor: `isAnchorOwnedSyncPath`, `ownsSourceSyncAnchor` and `sourceCommitAnchorAllowed` treat it as not owned, and for `default` the commit-anchor check skips a relative `sync.repo_path` and judges the row's `local_path`, so an explicit absolute `--repo` never advances the commit anchor of a source whose stored path is relative. `performSync` calls `assertSyncApplicable` first (the anchor check, then the content-directory check), so a content-directory source refuses with `sync_not_applicable` (reason `content_directory`, fix `gbrain import <dir> [--no-embed] --source <id>`, `git init` named only as an ask-the-user option) before the managed path or the legacy #2964 anchor self-heal could `git init` it. `sync --all` skips these sources with one line; the dream cycle's sync phase reports them `skipped` (`details.reason: sync_not_applicable`). The CLI `sync` record renders fix-carrying OperationErrors through `renderCliError` (`src/cli/commands/sync.ts`). Pinned by `test/sync-applicability.test.ts` and `test/sync-relative-anchor-refusal-7630.test.ts`.+- `src/core/sync-applicability.ts` — agent-first operator wave E4. `syncContentDirectory(engine, {sourceId, repoPath})` resolves the sync root exactly as `performSync` does and returns it when it is a gbrain-owned content directory (under `<GBRAIN_HOME>/.gbrain/content/`, or an owned `--content-root` recorded in the shared-skills setup receipt) with no `.git` at the root; null otherwise (fail-open). `assertSyncAnchorAbsolute` refuses `sync_anchor_relative` (`syncAnchorRelativeError`: exit 3, an `ask_user` fix naming `gbrain sources set-path <id> <absolute-directory>`, or `gbrain config set sync.repo_path` with no source) when the stored anchor (`sources.local_path`, else `sync.repo_path`) is not absolute on this host (`isHostAbsolutePath`: on win32 only a drive or UNC path) and no absolute `repoPath`, or relative one resolving elsewhere, was passed; `sync --all --json` puts the refusal's `code`, `why` and `fix` in the source's entry, and the `sync` Minion job completes as a skip carrying them; single-source and `--all` CLI syncs refuse it before the cost gate walks the directory, and a cycle whose directory matches no source checks `default` and fails its sync phase with that code. A path absolute only on another operating system (a Windows drive path read on Linux or macOS) gets the same code with a `set-path`-only fix, since `--clear` refuses it. `src/core/sync-anchor.ts` never proves ownership from a relative anchor: `isAnchorOwnedSyncPath`, `ownsSourceSyncAnchor` and `sourceCommitAnchorAllowed` treat it as not owned, and for `default` the commit-anchor check skips a relative `sync.repo_path` and judges the row's `local_path` (a null row falls back to that relative key and refuses), so an explicit absolute `--repo` never advances the commit anchor of a source whose stored path is relative. `performSync` calls `assertSyncApplicable` first (the anchor check, then the content-directory check), so a content-directory source refuses with `sync_not_applicable` (reason `content_directory`, fix `gbrain import <dir> [--no-embed] --source <id>`, `git init` named only as an ask-the-user option) before the managed path or the legacy #2964 anchor self-heal could `git init` it. `sync --all` skips these sources with one line; the dream cycle's sync phase reports them `skipped` (`details.reason: sync_not_applicable`). The CLI `sync` record renders fix-carrying OperationErrors through `renderCliError` (`src/cli/commands/sync.ts`). Pinned by `test/sync-applicability.test.ts` and `test/sync-relative-anchor-refusal-7630.test.ts`.- `src/core/sync-upstream.ts` — upstream observation for remote-tracking sources (#5255/#5176). `observeUpstream(root, syncedCommit)` reads the checkout's `@{upstream}` commit, the newer of the `FETCH_HEAD` and upstream-ref reflog mtimes (the last fetch, pull or push by any process) and `rev-list --count` of upstream commits the synced commit lacks; `recordUpstreamObservation` (called by `performSync` in `src/commands/sync/perform.ts` after every non-dry-run legacy or managed sync, best-effort) writes them to `sources.upstream_checked_at` / `upstream_commit` / `upstream_behind`, which `managed_writer_guard` does not protect. `upstreamFreshness` is doctor `sync_freshness`'s separate "upstream checked" verdict (a `remote_url` source with no observation or one at least 24 h old is upstream unknown; any observed upstream lead is behind), DB-only so remote doctor runs it. `managedPullWarning` / `UpstreamRefresh` back the cycle sync phase (`runPhaseSync` in `src/core/cycle.ts`), which runs a managed `pull: true` as no-pull and reports `details.upstream_refresh` (`pulled|failed|skipped_managed|not_requested`) plus a `managed_pull_skipped` warning when the checkout tracks an upstream. A managed brain's fix (the warning and doctor's behind/unknown verdict) is `gbrain sources refresh <source>`; an unmanaged one's is `gbrain sync --source <source>`. Tests: `test/managed-cycle-pull-upstream.test.ts`, the pull row of `test/managed-phase-matrix.test.ts`.- `src/core/sync-upstream-rewrite.ts` — classic sync's upstream watch for a source that syncs with pull (GBRA-133 S-58/S-59). `recordUpstreamBeforeFetch` (called by `src/commands/sync/preflight.ts` before every pull) stores in `sources.config.upstream_baseline` the upstream commit HEAD contains, only when HEAD contains it, so a rewritten upstream fetched earlier never replaces it; `settleUpstreamAfterPull` records the new baseline and clears `sources.config.upstream_divergence` after a pull that fast-forwarded or was up to date, and after a pull that failed with HEAD and `@{upstream}` diverged stores `upstream_rewritten` (baseline not an ancestor of the new upstream), `upstream_unknown` (no baseline or its object is gone) or `upstream_diverged` (baseline contained: plain local commits); nothing is classified while a rebase, merge, cherry-pick or revert marker (`GIT_OPERATION_MARKERS` in `src/core/git/commit-push.ts`) exists. Best effort: it never throws into the sync and never writes a sync-failure ledger row. `upstreamFix` is the typed next step (`ask_user` reset bound to the observed SHAs for rewritten/unknown, never a merge; `gbrain git commit-push --pull` for diverged; both `then` the sync). Read by `performSyncInner` (`result.upstream`), `buildSingleSyncJsonEnvelope`, `gbrain sources status --json` (`upstream`) and doctor `sync_failures` (`details.upstream`, warn, local fix; remote callers get counts only). Pinned by `test/pathological/s-58-upstream-rewrite.test.ts`.- `src/core/sync-attempt.ts` + `src/commands/doctor/sync-outcome.ts` — doctor `sync_freshness` for a source with no successful sync (`last_sync_at` NULL, #4960). `readLastSyncAttempt` reads, read-only, the newest `sync` Minions job of the source and, on a managed brain, `readSyncStatus` (holds, last error, cursor, its `next`); nothing found is `no_attempt`, an unreadable read is `no_attempt` with `unreadable`. A live first-sync lock inside the staleness ceiling is `warn` (`sync_first_run_in_progress`, fix `next: wait`); no lock is `fail` (`sync_no_successful_sync`) naming last attempt, result and held count, with a per-`reason` fix (`attempt_queued` wait, `holds_pending` the managed `next` or `sync status`, `last_attempt_unsuccessful` inspect the job then retry, `no_attempt` retry). Entries land in `details.no_successful_sync[]`; these sources stay in `stale_count`. Test: `test/doctor-sync-freshness-outcome-4960.test.ts`.@@ -31,4 +31,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/url-clone.ts` — gbrain-owned `sources add --url` clones (#6946, GBRA-130 C-2). `isOwnedClone` (config `managed_clone` or a `local_path` under the default clone dir) and `defaultCloneDir`; `urlCloneReadOnly` is the one predicate (owned clone on a brain without managed persistence) the fence writer (`fence-write.ts`, `databaseOnlyReason: 'url_clone'`), write-through (`skipped: 'url_clone'`), timeline write-through, unfenced-facts adoption, the empty-fence guard and `sourceMirrorReadOnly` consult, so nothing gbrain writes lands in a checkout it updates with `git pull --ff-only`. `urlClonePullBlock` reads the tracked changes of a clone whose pull failed and returns `pull_blocked_local_changes` with an `ask_user` fix naming the preview `gbrain repair url-clone-fences --source <id>`; `formatUrlClonePullBlock` renders it for sync's stderr (`sync/preflight.ts`) and `cycle.ts` puts it in the sync phase detail as `pull_blocked`. Test: `test/pathological/c2-url-clone-fences.test.ts`. gbrain itself never writes into an owned clone on an unmanaged brain, but local commits someone else makes there are published by `gbrain sources git-reconcile` (`src/commands/sources-git-reconcile.ts`, autopilot each tick: secret scan, rewritten-upstream refusal, repository-root check); `sources.refresh_publish_diverged false` or `gbrain sources set-sync <id> off` keeps them local.- `src/core/url-source-origin.ts`, `src/commands/sources-record-origin.ts` and `src/commands/doctor/checks/url-source-origin.ts` — who added a URL source (`sources.config.added_by_remote_caller`). Both add paths write it (`true` for a remote caller, `false` for the local operator); only an explicit `true` reads as remote. URL sources added before that record existed carry none, and nothing stored tells a remote caller's add from the local operator's (same row, same default clone directory); a clone outside `$GBRAIN_HOME/clones/<id>` (or a `clones/<id>` under an earlier home) proves a local add. A URL clone counts when `isOwnedClone` accepts it, so an unmarked clone at the default directory is listed too. `urlSourcesWithoutOrigin` (read-only) feeds the wave check `url_source_origin` (host-only, `resolution: 'operator'`, `warn` with an `ask_user` fix whose argv is the preview). `recordSourceOrigin(engine, ids, { origin, apply, remote })` backs `gbrain sources record-origin <id>... --remote|--local [--apply] [--json]`: it throws `trusted_local_only` unless `remote === false`, previews unless `apply`, writes `true` (`--remote`) or `false` (`--local`) in one transaction that re-reads the row `FOR UPDATE` and refuses `source_changed` if its path or URL moved; on a managed brain that transaction runs inside `withTopologyLocks` after `lockTopologyRows`, the locks a reclone takes (a held lock refuses the id `source_busy`), and `runManagedSourceClone` takes the config it clones with from its own locked admission read, so a record and a reclone never interleave. `--remote --apply` also writes `LFS_OFF_CLONE_CONFIG` into the repository's shared config (`--git-common-dir`; `git config --file`, not run in the checkout) before the row, reads the effective values back (`lockDownGaps`) and throws when a worktree-scoped or included setting overrides one, and locks down an already-remote source whose checkout lacks it (no git-lfs refusal for it unless Git cannot place the checkout, `lfs_unknown`); each key's existing values are removed before its one value is written, in a `config.lock` copy renamed over the config in one step; a throw is reported for its id as `write_failed` and the batch continues. It never removes a `true`, and refuses `--remote` for a checkout with any tracked `filter=lfs` path or a committed `.gitattributes` declaring `filter=lfs` outside a comment line (`lfs_tracked`, worded per case; read with `hardenedGitSync` `ls-files -- ':(attr:filter=lfs)'` plus every committed `.gitattributes` blob from `ls-tree -z` records split at their first tab, then `cat-file`, so clone-local attributes cannot hide one, and read again under the locks), or one it cannot inspect (`lfs_unknown`, whose reason names the cause: checkout missing, not its own repository's top level by a realpath comparison, owned by another user (`safe.directory`), or a Git read failed), because a lock-down reclone would not match the stored writer manifest there. An unborn HEAD with an empty index (a clone of an empty repository) has no committed attributes and passes. Without git-lfs files the tracked bytes are the same, so no manifest is written. Pinned by `test/url-source-origin.test.ts` (PGLite and Postgres).-- `src/core/write-through.ts` — shared atomic disk write-through for the canonical ingestion path. `resolvePageWriteTarget(engine, slug, sourceId, { includeDeleted? })` (active rows by default; `includeDeleted: true` resolves a tombstone's recorded `source_path` for the purge remediation retry) is the exported single source of truth for the ONE file a (source, slug) pair lives in on disk: a source with its own `local_path` writes at that tree's ROOT (never nested under `.sources/`); a source without one nests under the host repo (`sync.repo_path`, default at root, non-default under `.sources/<id>/`) unless that path is another source's own working tree (leak guard → `source_repo_belongs_to_other_source`; a live source whose `local_path` is relative counts as owning every tree, and a relative `local_path` or `sync.repo_path` target is `repo_not_found`); the page's recorded `source_path` (or a contained absolute `file://` `source_uri`; a relative or host-only `file://` names no local file and is read as absent) is preferred over a slug-derived name so writes land in the file of record instead of minting a twin; and `isWriteTargetContained` rejects hostile rows escaping the tree (`path_escapes_source_root`). The ok-result also carries `sourcePathToBind` — the target expressed in the file scanner's `source_path` convention for the source's pinned `slug_root_mode` (or the mode its first sync would pin, via `scannerSlugRootMode`): GIT-ROOT-relative under `git-root` when the scan root sits inside a git repo, scan-root-relative under `source-root` and for non-git or git-root scan roots, so a put-born page binds the same form managed sync and delete-reconcile key on. Every recorded-path reader (write targets, takes, reconcile, audit, export restore, doctor) decodes with the same mode (`resolveSourceLocalFilePath(..., slugRootMode)`): under `source-root` the scope prefix is removed only from the legacy Git-root form whose remainder names the page slug, and basename rows resolve under the unstripped slug directory. The resolver is shared by `writePageThrough`, the facts fence writer (`src/core/facts/fence-write.ts`), and fence forget (`src/core/facts/forget.ts`) — the fence appends to the page's file, so all writers MUST compute the identical path or the fence lands in a file sync never reads back and the next extract_facts reconcile deletes the fence-owned DB rows. `writePageThrough(engine, slug, {sourceId?, frontmatterOverrides?, inlineOnly?, logger?, expectedFileBytes?, deferCommit?})` resolves the target through it, re-reads the just-written DB row (`getPage`), renders an inline page via `serializePageToMarkdown`, and writes the `.md`. A page stored in segments is never rendered whole: its file is measured from its segments at the snapshot's revision (`unreadPageFile`; a page that moved since refuses `revision_conflict`), checked against `PUSH_SCAN_MAX_FILE_BYTES` before `source_path` is bound (a body already over the cap by `body_bytes` is refused without streaming), streamed through `stageStreamedContent` on the engine it was given (so a caller inside a transaction works) keeping the existing file's mode, and renamed over the target after the file-changed check; `frontmatterOverrides` on such a page return an error result, and `inlineOnly` (the derived writer) skips it as `segmented_page` so the brain has a committable artifact that round-trips through `gbrain sync`. Rendering from the row keeps the serialized content consistent at write time. The fsync-backed `atomicWriteFileSync` stages and renames the file after required source-path bookkeeping; lock/lease checks run before publication. `put_page` holds the root lock before importing and invokes write-through inside its database transaction, so ordinary filesystem rejection rolls back existing content, tags, chunks, and versions. A crash or database COMMIT failure after rename can still leave canonical Markdown ahead of the index; this is not distributed ACID or a durable queue. Never throws — returns `WriteThroughResult { written, path?, content? (the bytes written; inline pages only), skipped?: 'disabled_by_config' | 'url_clone' | 'no_repo_configured' | 'repo_not_found' | 'source_repo_belongs_to_other_source' | 'page_not_found_after_write' | 'path_escapes_source_root' | 'case_insensitive_collision' | 'file_changed' | 'over_push_scan_cap' | 'segmented_page', warning?, error? }` (`file_changed`: the caller's `expectedFileBytes` preimage, null for absent, no longer matches the file under the source filesystem lock, so the file is left untouched) so the caller decides messaging + exit codes. `withNoRepoWriteThroughWarning(result, sourceId)` decorates an unwritten `no_repo_configured` result with `warning` (the write landed only in the database; bind the token/server to a git-backed source or configure `local_path`/`sync.repo_path`); `put_page` applies it for untrusted callers only (`ctx.remote !== false`), so local CLI responses and the `disabled_by_config` operator opt-out stay silent. `isWriteThroughDisabled` (shared with the fence lane, ~30s per-engine cache) honors the `sync.write_through` opt-out. Trust gating (subagent sandbox, dry-run) stays at the CALLER. On a durability-hardened repo (`isDurabilityHardened` — the gbrain post-commit hook is installed, i.e. the user ran `gbrain sources harden`), a successful write is best-effort COMMITTED via `commitWriteThroughFile` (path-limited `git commit -- <file>`, never sweeps unrelated edits; the hook then background-pushes) unless the caller passes `deferCommit` (the derived write-through commits its batch itself, #8073; `deletePageThrough` takes it too) so write-through content reaches git instead of accumulating uncommitted forever; result carries `committed?: boolean`. Unhardened repos keep write-only behavior. `deletePageThrough(engine, slug, {sourceId?, target?, logger?})` is the delete-side sink (sole caller: the `delete_page` op): resolves the same target, unlinks the `.md`, and on a hardened repo best-effort commits the removal path-limited through the same helper with subject `gbrain: delete write-through <slug>`, reporting `committed?: boolean` on `DeleteThroughResult` (absent when unhardened or when the commit did not land — the unlink still stands; a never-committed page leaves nothing to commit, so no empty commit). Pinned by `test/delete-write-through-commit.test.ts`. Consumers: `put_page` op and `gbrain brainstorm/lsd --save` via `persistSavedIdea`. Pinned by `test/write-through.test.ts` + `test/write-through-commit.test.ts`. The `put_page` op is that deciding caller for direct writes: a skip outside the deliberate DB-only set (`no_repo_configured`/`disabled_by_config`/`subagent_sandbox`/`dry_run`) throws `storage_error` inside the import transaction, rolling back the page revision, tags, chunks and version snapshot instead of deleting a just-created row afterward. #6946: on a gbrain-owned `--url` clone of an unmanaged brain (`urlCloneReadOnly`), `writePageThrough` returns `skipped: 'url_clone'` and `deletePageThrough` returns `removed: false, skipped: 'url_clone'`; `timeline-write-through.ts` skips the same way.+- `src/core/write-through.ts` — shared atomic disk write-through for the canonical ingestion path. `resolvePageWriteTarget(engine, slug, sourceId, { includeDeleted? })` (active rows by default; `includeDeleted: true` resolves a tombstone's recorded `source_path` for the purge remediation retry) is the exported single source of truth for the ONE file a (source, slug) pair lives in on disk: a source with its own `local_path` writes at that tree's ROOT (never nested under `.sources/`); a source without one nests under the host repo (`sync.repo_path`, default at root, non-default under `.sources/<id>/`) unless that path is another source's own working tree (leak guard → `source_repo_belongs_to_other_source`; a live source whose `local_path` is relative counts as owning every tree, one absolute only on another OS does not, and a `local_path` or `sync.repo_path` target not absolute on this host (`isHostAbsolutePath`) is `repo_not_found`); the page's recorded `source_path` (or a contained absolute `file://` `source_uri`; a relative or host-only `file://` names no local file and is read as absent) is preferred over a slug-derived name so writes land in the file of record instead of minting a twin; and `isWriteTargetContained` rejects hostile rows escaping the tree (`path_escapes_source_root`). The ok-result also carries `sourcePathToBind` — the target expressed in the file scanner's `source_path` convention for the source's pinned `slug_root_mode` (or the mode its first sync would pin, via `scannerSlugRootMode`): GIT-ROOT-relative under `git-root` when the scan root sits inside a git repo, scan-root-relative under `source-root` and for non-git or git-root scan roots, so a put-born page binds the same form managed sync and delete-reconcile key on. Every recorded-path reader (write targets, takes, reconcile, audit, export restore, doctor) decodes with the same mode (`resolveSourceLocalFilePath(..., slugRootMode)`): under `source-root` the scope prefix is removed only from the legacy Git-root form whose remainder names the page slug, and basename rows resolve under the unstripped slug directory. The resolver is shared by `writePageThrough`, the facts fence writer (`src/core/facts/fence-write.ts`), and fence forget (`src/core/facts/forget.ts`) — the fence appends to the page's file, so all writers MUST compute the identical path or the fence lands in a file sync never reads back and the next extract_facts reconcile deletes the fence-owned DB rows. `writePageThrough(engine, slug, {sourceId?, frontmatterOverrides?, inlineOnly?, logger?, expectedFileBytes?, deferCommit?})` resolves the target through it, re-reads the just-written DB row (`getPage`), renders an inline page via `serializePageToMarkdown`, and writes the `.md`. A page stored in segments is never rendered whole: its file is measured from its segments at the snapshot's revision (`unreadPageFile`; a page that moved since refuses `revision_conflict`), checked against `PUSH_SCAN_MAX_FILE_BYTES` before `source_path` is bound (a body already over the cap by `body_bytes` is refused without streaming), streamed through `stageStreamedContent` on the engine it was given (so a caller inside a transaction works) keeping the existing file's mode, and renamed over the target after the file-changed check; `frontmatterOverrides` on such a page return an error result, and `inlineOnly` (the derived writer) skips it as `segmented_page` so the brain has a committable artifact that round-trips through `gbrain sync`. Rendering from the row keeps the serialized content consistent at write time. The fsync-backed `atomicWriteFileSync` stages and renames the file after required source-path bookkeeping; lock/lease checks run before publication. `put_page` holds the root lock before importing and invokes write-through inside its database transaction, so ordinary filesystem rejection rolls back existing content, tags, chunks, and versions. A crash or database COMMIT failure after rename can still leave canonical Markdown ahead of the index; this is not distributed ACID or a durable queue. Never throws — returns `WriteThroughResult { written, path?, content? (the bytes written; inline pages only), skipped?: 'disabled_by_config' | 'url_clone' | 'no_repo_configured' | 'repo_not_found' | 'source_repo_belongs_to_other_source' | 'page_not_found_after_write' | 'path_escapes_source_root' | 'case_insensitive_collision' | 'file_changed' | 'over_push_scan_cap' | 'segmented_page', warning?, error? }` (`file_changed`: the caller's `expectedFileBytes` preimage, null for absent, no longer matches the file under the source filesystem lock, so the file is left untouched) so the caller decides messaging + exit codes. `withNoRepoWriteThroughWarning(result, sourceId)` decorates an unwritten `no_repo_configured` result (and a `relative_root` one, naming `sources set-path`) with `warning` (the write landed only in the database; bind the token/server to a git-backed source or configure `local_path`/`sync.repo_path`); `put_page` applies it for untrusted callers only (`ctx.remote !== false`), so local CLI responses and the `disabled_by_config` operator opt-out stay silent. `isWriteThroughDisabled` (shared with the fence lane, ~30s per-engine cache) honors the `sync.write_through` opt-out. Trust gating (subagent sandbox, dry-run) stays at the CALLER. On a durability-hardened repo (`isDurabilityHardened` — the gbrain post-commit hook is installed, i.e. the user ran `gbrain sources harden`), a successful write is best-effort COMMITTED via `commitWriteThroughFile` (path-limited `git commit -- <file>`, never sweeps unrelated edits; the hook then background-pushes) unless the caller passes `deferCommit` (the derived write-through commits its batch itself, #8073; `deletePageThrough` takes it too) so write-through content reaches git instead of accumulating uncommitted forever; result carries `committed?: boolean`. Unhardened repos keep write-only behavior. `deletePageThrough(engine, slug, {sourceId?, target?, logger?})` is the delete-side sink (sole caller: the `delete_page` op): resolves the same target, unlinks the `.md`, and on a hardened repo best-effort commits the removal path-limited through the same helper with subject `gbrain: delete write-through <slug>`, reporting `committed?: boolean` on `DeleteThroughResult` (absent when unhardened or when the commit did not land — the unlink still stands; a never-committed page leaves nothing to commit, so no empty commit). Pinned by `test/delete-write-through-commit.test.ts`. Consumers: `put_page` op and `gbrain brainstorm/lsd --save` via `persistSavedIdea`. Pinned by `test/write-through.test.ts` + `test/write-through-commit.test.ts`. The `put_page` op is that deciding caller for direct writes: a skip outside the deliberate DB-only set (`no_repo_configured`/`disabled_by_config`/`subagent_sandbox`/`dry_run`) throws `storage_error` inside the import transaction, rolling back the page revision, tags, chunks and version snapshot instead of deleting a just-created row afterward. #6946: on a gbrain-owned `--url` clone of an unmanaged brain (`urlCloneReadOnly`), `writePageThrough` returns `skipped: 'url_clone'` and `deletePageThrough` returns `removed: false, skipped: 'url_clone'`; `timeline-write-through.ts` skips the same way.diff --git a/docs/architecture/key-files/managed-sync-bookkeeping.md b/docs/architecture/key-files/managed-sync-bookkeeping.mdindex 4a8073cf5b..30f639aa0d 100644--- a/docs/architecture/key-files/managed-sync-bookkeeping.md+++ b/docs/architecture/key-files/managed-sync-bookkeeping.md@@ -35,7 +35,7 @@ run, and the supersession of a checkpoint whose cursor another run replaced. The- `src/core/persistence/sync-cursor-moves.ts` — #6712 (L2, one page, one fate): the managed-sync cursor's pure transitions, peeled out of `sync-run.ts`; each returns the next cursor and writes nothing (sync-run.ts saves it with one compare-and-swap). `advanceHeld`/`settledPast` pass an entry without a commit (held, waived via `waivedCursor`, an idempotent deletion via `deletionSettled`) and add its index to the settled ranges the checkpoint skips; a deferred entry (`Cursor.deferred`, a `source_changed` file retried after the manifest end) leaves the deferred list instead of moving the index. `promoteWindow` makes the window's first group the cursor's group once the cursor reaches it, so requests admitted after a failed or held entry are read by their own receipts, never frozen again; `committedPast` does the same after a commit. `withHeldKeys` records a held entry's page keys (`dependencyKeys`) so a later entry of the run that shares one is held behind it (`blocked_on`).- `src/core/persistence/sync-stop-class.ts` — #6712 (L2; #6565): how the settle path in `sync-run.ts` classifies a page request that ended without committing. `receiptClass` reads the terminal classifier: `transport` (a dropped connection or a retryable refusal, re-frozen in place), `page` (held, deferred or blocked under the hold policy) or `systemic` (the run stops with the classifier's action). `resumableStop` is a systemic stop the fault table retries (an unrecognised P0001 or a 55000 surfacing as `storage_error`); `stopRecorded` says an earlier invocation already stopped this run (its failure ledger row carries the run id), so the next plain sync re-freezes every page that refusal failed, bounded by `STOPS_PER_ENTRY`. #6712 PR 3 (L7): `recordedStop` also returns the row's `gbrain_version`. `retryRecordedFailure` in `sync-run.ts` (what `--retry-failed`, now its deprecated alias, did on request) retries every recorded failure on the next plain sync, except a refusal nothing changed since the same version recorded it (`replaysUnchangedRefusal`: a content refusal while the file has its frozen bytes; a `source_changed` pinned import while HEAD is the run's target and the file still holds the working-tree bytes that refused, compared by hash rather than by mtime), a slug-mode refusal and a checkpoint whose source's `last_commit` moved (#6834), which wait for a changed file or `gbrain repair managed-sync-orphans`.- `src/core/persistence/sync-knock-on.ts` — #6643, shrunk by #6712 (one page, one fate): no producer is left. It keeps the legacy predicate over receipts older builds wrote (`error_detail` `{ origin: 'sync_knock_on', reason, root_request_id }`, or the pre-#6643 producers' exact messages, never an operator cancel): `isSyncKnockOn`/`syncKnockOnSql` (one predicate, never NULL) feed the terminal classifier, which renders such a receipt superseded, and `sync-run.ts` `refreezeInPlace`, which re-freezes the entry when a resumed cursor meets one (bounded by `STOPS_PER_ENTRY`, no config key). `cursorFenceCause` reads the two live causes of "cursor changed" (`run_replaced`, `outside_fence`; an older `window_dropped` still parses). `checkpoint-validation.ts` clause 3 skips converted receipts and the cursor's settled index ranges only; #6712 removed the knock-on exemption. `reviveCheckpoint` re-assesses a refused checkpoint at the cursor's end. `sync status` shows the cursor the recorded failure belongs to, `cursors`, and `checkpoint_blockers` (`listIncompleteSyncReceipts`, each with `knock_on`).-- `src/core/persistence/terminal-classify.ts` — #6650: `classifyTerminal` turns one terminal receipt (`failed` / `conflict` / `cancelled`, or any row still holding `recovery`) into a `TerminalVerdict` (category, code, origin, class, `safe_actions`, `needs_human`, `defect`, `historical`, `root_request_id`, one structured `action`) at read time; nothing is persisted. A recovery record outranks the code (`recovery_pending` / `recovery_blocked`); a knock-on is read through `isSyncKnockOn` (typed marker survives compaction) or the SQL twin `terminalKnockOnSql`; `storage_error` and `source_changed` route by their recorded origin or cause, and a row whose code and origin do not say what happened is `diagnosis_required` (read-only writer status, never a guessed fix). A `source_changed` whose canonical file is missing is `canonical_file_missing` (a ghost page; its exit is the `gbrain repair ghost-pages` preview, never a sync retry), and an origin-less `fence_unrenderable` adoption refusal is its own defect category. A retryable sync fault's `action` follows its operation (`faultOperation`: a `put_page` under a `canonical_reconcile` or `managed_*` intent kind reads as that kind): `submit_job` and a canonical reconcile keep the sync retry, a caller-submitted page or memory write (`RESUBMITTED_WRITES`) gets the read-only writer-status inspect and a resubmit with a new request_id, a `managed_*` write the inspect and a rerun of its command, any other operation the inspect alone. `TERMINAL_FIXED_IN` names the release that fixed a category; a row whose build (`error_detail.attempt.consumer_version`, else `admitter_version`) is older is historical. `legacy_publication_refusal` and `retired_operation` (a `revision_conflict` with origin `grandfather_retired` or a `managed_grandfather` intent, #7837) are historical whatever build wrote them, since only a request an older build admitted produces them. It also owns the supersession rule `repair/failed-writes.ts` reuses (`supersessionSql`, `supersessionOrderSql`, `dispositionOf`, `PAGE_REMOVAL_OPERATIONS`). Tests: `test/terminal-failures-6650.test.ts` (TS↔SQL twin parity included), `test/terminal-classify-6696.test.ts`.+- `src/core/persistence/terminal-classify.ts` — #6650: `classifyTerminal` turns one terminal receipt (`failed` / `conflict` / `cancelled`, or any row still holding `recovery`) into a `TerminalVerdict` (category, code, origin, class, `safe_actions`, `needs_human`, `defect`, `historical`, `root_request_id`, one structured `action`) at read time; nothing is persisted. A recovery record outranks the code (`recovery_pending` / `recovery_blocked`); a knock-on is read through `isSyncKnockOn` (typed marker survives compaction) or the SQL twin `terminalKnockOnSql`; `storage_error` and `source_changed` route by their recorded origin or cause, and a row whose code and origin do not say what happened is `diagnosis_required` (read-only writer status, never a guessed fix). A `source_changed` whose canonical file is missing is `canonical_file_missing` (a ghost page; its exit is the `gbrain repair ghost-pages` preview, never a sync retry), and an origin-less `fence_unrenderable` adoption refusal is its own defect category. A retryable sync fault's `action` follows its operation (`faultOperation`: a `put_page` under a `canonical_reconcile` or `managed_*` intent kind reads as that kind): `submit_job` and a canonical reconcile keep the sync retry, a caller-submitted page or memory write (`RESUBMITTED_WRITES`) gets the read-only writer-status inspect and a resubmit with a new request_id, a `managed_*` write the inspect and a rerun of its command, any other operation (and a compacted `put_page`, whose intent kind is gone) the inspect alone with `safe_actions: ['none']`. `TERMINAL_FIXED_IN` names the release that fixed a category; a row whose build (`error_detail.attempt.consumer_version`, else `admitter_version`) is older is historical. `legacy_publication_refusal` and `retired_operation` (a `revision_conflict` with origin `grandfather_retired` or a `managed_grandfather` intent, #7837) are historical whatever build wrote them, since only a request an older build admitted produces them. It also owns the supersession rule `repair/failed-writes.ts` reuses (`supersessionSql`, `supersessionOrderSql`, `dispositionOf`, `PAGE_REMOVAL_OPERATIONS`). Tests: `test/terminal-failures-6650.test.ts` (TS↔SQL twin parity included), `test/terminal-classify-6696.test.ts`.- `src/core/persistence/terminal-failures.ts` — #6650: the bounded readers over that classifier. `readTerminalFailureSummary` is one set-based aggregate (GROUPING SETS per source; `TERMINAL_STATEMENT_MS` 5 s statement and `TERMINAL_ACQUIRE_MS` 2 s connection deadlines; past either it returns `status: 'unknown'`, never an empty pile) splitting active blockers (recovery records plus the passed-in `checkpoint_blockers` of `sync-status.ts`, read by `readCheckpointBlockerMap`), unresolved rows (count, distinct slugs and intents, oldest age), historical rows (a later write superseded them, or older than `TERMINAL_FIXED_IN` via the SQL twin `TERMINAL_HISTORICAL_SQL`), 24 h and 7-day daily counts, categories and defect classes; archived sources are skipped. Thresholds `persistence.terminal_failures.window_days` (clamped to `persistence.receipt_retention_days`), `spike_factor`, `spike_min` (`readTerminalThresholds`, `validateTerminalConfigValue`, refused at `config set` by `commands/config/preparation-keys.ts`); `isSpike` against `sevenDayMedian`. `readTerminalFailures` is the drill-down (batches of 200, each selected before the supersession lateral join, which with the summary's probe tests the failed row's intent kind first so later large sync intents are not detoasted per row (#8729), at most 2,000 rows scanned per call, a sequence cursor, verdict filters, `--group-by category` groups, a `sync_fault` group also split by its operation, with an exact `drill_down` argv each; `--operation` filters on `faultOperation`). Consumers: doctor `persistence_terminal_failures` (`commands/doctor/checks/persistence-requests.ts`), `sync status` `terminal_failures` (`sync-status.ts`, `next` falls back to a recovery blocker's action), the `writer_failures` administration operation, and the admin `/metrics` gauges (`serve-http-metrics.ts` `renderTerminalFailureMetrics`, one aggregate per engine shared by scrapes for `TERMINAL_METRICS_TTL_MS` = 60 s via `cachedTerminalSummary`; never `/health`). Each source also reports `new_last_24h_older_builds` (rows and builds older than their class's fix), and doctor's spike message says an older write owner is producing them when they are most of the spike. Tests: `test/terminal-failures-6650.test.ts`, `test/sync-status-terminal-6650.test.ts`, `test/terminal-failure-metrics-6650.test.ts`, the CLI journey `test/agent-journey-terminal-failures-6650.test.ts`.- `src/commands/sources-writer-failures.ts` — #6650: output of `gbrain sources writer failures <source> [--state all] [--group-by category] [--since Nd] [--limit N] [--before <cursor>] [--category|--code|--origin|--operation] [--json]`, dispatched by `persistence-admin.ts` as `writer_failures` (validated in `administration.ts` `writerFailuresQuery`, locally or through the resident owner). A table by default, one JSON document with `--json`; row and group `fix` / `inspect` actions are rendered for the CLI; a full page prints `truncated` with the exact next command. The operation is advertised to clients in the owner's `administration_extensions` (`ipc.ts`, `admin-contract.ts` `PERSISTENCE_ADMIN_EXTENSIONS`), never in the `administration` list an older client validates strictly, and `local-client.ts` delegates it only to an owner that lists it (`ownerAdministers`). Tests: `test/writer-failures-cli-6650.test.ts`.- `src/core/persistence/public-category.ts` — #6712 PR 2 (L5): `publicCategory({ category?, code })`, the closed public vocabulary (`drift`, `conflict`, `content_refused`, `file_missing`, `permission`, `storage`, `config`, `superseded`, `transient`, `defect`) that sits beside the unchanged diagnosis `category`. `PUBLIC_BY_TERMINAL` maps every `TerminalCategory`, `PUBLIC_BY_CODE` every `SYNC_FAULT_TABLE` code (a new fault code needs a row: `test/public-category.test.ts`), and anything else goes by its registry class (unknown codes are `defect`). `classifyTerminal` carries it as `public_category`; `classifyRecordedFault` (terminal-classify.ts) reads a hold, a managed-sync failure row or a run stop as the failed receipt it stands for, so the receipt diagnosis, `managedWrite`, sync status holds and `last_error`, the terminal summary and doctor `sync_failures` (`details.failures`) render one verdict.diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.mdindex ea5f4c47ce..91773abd12 100644--- a/docs/architecture/key-files/persistence-stalls.md+++ b/docs/architecture/key-files/persistence-stalls.md@@ -22,7 +22,7 @@ owner (`owner_wedged_here`), movement surfaces (`data_moving`, doctor- `src/core/persistence/claim-phase.ts` — #6176 / #6278: the phase and step a running write request's claim is in. `startClaimPhase`/`enterClaimPhase` keep a per-claim `ClaimPhaseClock` in the consumer (single and group routes); `claimPhaseStamp` is the jsonb every claim, renewal and group dispatch mark stores in `persistence_requests.claim_phase` (v217): phase `preparing` or `publishing`, claim start, phase start, the execution token (so a later claim never reads an earlier claim's ages), the `step` in flight and when it began, `waiting_on` and the owning process (`owner`: command kind, pid, gbrain build; #6650 boot id, start). Preparers (`sync-prepare.ts`, `page-prepare.ts`, `prepared-maintenance.ts`, link resolution) call `enterClaimStep(clock, step, signal, waitingOn)` at each await boundary: it names the step, records what the await waits on (`git`, `fs`, `db`, `pool`, else `unknown`: set only where observed, never inferred) and throws the preparation's abort reason, so cancellation reaches a preparer between its queries even though the queries take no signal. `claimStateOf` reads a row back from the current claim's stamp only: `preparing`/`publishing` (live renewal), `publication_transaction` (claim lapsed while running, read on the database clock: a transaction holds the row or the owner is gone; requeued once it ends), `file_publication` (`publication_started`; recovery finishes it) or `unrecorded`, with claim and phase ages, `step`, `step_age_ms`, `waiting_on`, `owner`, `resumes_on_its_own` and a `why`. `claimStall` is the `preparation_overdue` verdict (`claim.stall`) for a preparing claim past its budget. `EXPIRED_PREPARING_CHARGE_SQL` is the one rule an expired-claim reclaim charges a preparation attempt by: only a claim stamped `preparing` under the token being reclaimed. `persistence.max_claim_ms` (default 600000, 60000 to 86400000; `validateMaxClaimConfigValue` is `config set`'s `invalid_params` refusal) is doctor `persistence_write_stall`'s threshold. Consumer and group-publish store the stamp on every renewal, so writer status (`diagnostics.ts`, `claim` on each running blocker, never the token) and doctor name a stuck phase and step without an extra statement per write. Tests: `test/persistence-write-stall.test.ts`, `test/persistence-claim-step.test.ts`.- `src/core/persistence/preparation-budget.ts` + `src/commands/config/preparation-keys.ts` — #6278: how long a claimed write may prepare and how many cut-offs it survives. `preparationKind` sorts a request into `foreground` (`remember`, and `put_page`/`edit_page` with no internal intent: the consumer's 30 s `preparationMs`), `sync` (`managed_sync_*` kinds: `persistence.sync_preparation_ms`, default 120000) or `maintenance` (every other kind: `persistence.maintenance_preparation_ms`, default 120000). `persistence.preparation_ceiling_ms` (default 600000, 60000 to 3600000, floored at the larger budget plus 30 s) is the hard ceiling for a preparation that ignores cancellation and `persistence.max_preparation_attempts` (default 2, 1 to 10) the cut-offs before a request finishes `preparation_stalled`; a missing or out-of-range value keeps its default (`resolvePreparationPolicy`). These keys and `persistence.max_transient_retries` (transient-retry.ts) ride the write-switch snapshot (`switches.ts`, one statement, 5 s TTL) together with the `preparation_deadlines` kill switch, so a claim never reads config on its own. `startPreparation` runs a preparer under its budget and the budget wins the race even when the preparer ignores its signal (the signal aborts with `{ code: 'preparation_deadline' }`; a result that lands after the budget on the clock still reads as a deadline; the late result is the caller's to drop); `racePreparation` is its outcome-only form for the sync's out-of-consumer preparations (`sync-waivers.ts`). `validatePreparationConfigValue` is `config set`'s structured refusal (each key's range, and the ceiling rule across the sibling keys; usage error exit 2, nothing written), wired in by `refuseInvalidPreparationValue`. `persistence.max_claim_ms` keeps its doctor meaning. Tests: `test/persistence-preparation-budget.test.ts`.- `src/core/persistence/bounded-reads.ts` — #6278 (plan item 1.4): a preparation read that can wait on a relation lock ends at the budget on the server. Phase 0 (`docs/eval/managed-sync-stall-repro.md`) showed that through a transaction-mode pooler gbrain's `statement_timeout` startup parameter is dropped, so a preparation read outside the publication transaction had no server-side bound; an `ACCESS EXCLUSIVE` lock on `pages` held elsewhere pinned the member's origin check and its connection until the lock lifted, and with the budget alone the released member's statement kept running as a zombie that blocked its root until the ceiling. `boundedReads(engine, clock)` is the engine view every preparer reads through (`prepareManagedSyncMutation` and its helpers, `preparePageMutation`, `prepareFactFenceAdoption`, the sync's out-of-consumer preparations): each unmemoized raw statement runs with `executeRaw`'s `timeoutMs` set to the clock's remaining budget (`ClaimPhaseClock.deadlineAt`, set by `startClaimPhase(now, signal, budgetMs)`) and the clock's signal, which ends only the wait for a free connection. On Postgres `timeoutMs` runs the statement on a reserved connection as `BEGIN; SET LOCAL statement_timeout; <statement>; COMMIT` in one pipelined round trip, so the bound holds through the pooler and `SET LOCAL` ends with it; inside a transaction and on PGLite the option is ignored. A statement the server ends (57014, or a 55P03 raised by a shorter session `lock_timeout`) surfaces as the member's own `preparation_deadline` (`PreparationDeadlineError`, or the signal's reason once it aborted), which `preparationAbortReason` classifies as the deadline: the consumer and the group route handle it as the deadline even inside the budget (charged release, `preparation_stalled` at the limit, the group cut like the timer), never as a `storage_error` receipt or an uncharged release. The memo rule holds: `preparationReads` answers a bounded read once with the member's bound and signal dropped. #6318: with `engineReads` (managed sync) other calls run under `withReadDeadline` (`read-deadline.ts`), so the engine's own reads (`readPageSnapshot`, the import pipeline) get `statement_timeout` at the time left. Tests: `test/persistence-bounded-reads.test.ts`, `test/e2e/persistence-preparation-lock-wait-postgres.test.ts` and `-engine-reads-lock-postgres` (a real lock held in another session), the server-ended cases in `test/persistence-consumer-scheduling.test.ts` and `test/e2e/persistence-group-deadline-postgres.test.ts`. GBRA-75 wave 9: `withBoundedReadSession` gives a waiver screen (`unchangedSyncImport`) one reserved ordinary-pool connection (a long-hold permit; none left, or PGLite, runs the screen as before) on which its bounded reads share one transaction: `BEGIN; SET LOCAL statement_timeout` once, `COMMIT` when the screen settles. The bound stays per statement on the server: it is set again in the read's pipeline once the bound in force differs from the read's own by more than `BOUNDED_SESSION_SLACK_MS` (25 ms). A waiver run (`waiveRun` in `sync-run.ts`) opens one session for all its screens, and a screen inside it joins it. Session reads are named prepared statements (`ReservedConnection.executeRaw` `prepare`, ANDed with the connection option as `runUnsafe` does). A failed read rolls back and the reads it aborted (25P02) run again in a new transaction; a read after the screen settled takes the per-read path. Test: `test/persistence-bounded-read-session.test.ts` (real lock wait and no remaining statement on Postgres).-- `src/core/persistence/owner-refusal.ts` — #6278: the `owner_unavailable` reasons matrix. `checkOwner(binding, incarnation, hostId)` names the first failing condition in a fixed order (`binding_missing`, `incarnation_changed`, `host_mismatch`, `transfer_in_progress` for a `draining` worktree, `clone_in_progress` for `recovering`, `local_path_missing`, `coordination_path_missing`) or returns the usable `ActiveOwnerBinding`; `ownerRefusal` gives each reason its message, `why`, actor, fix (always the read-only `gbrain sources writer status --source <id> --json`, with the same verify; `actor: provider` so the two in-progress reasons render `next: wait` with a 30 s delay, `host_admin` for the rest) and `retryable` (`host_mismatch` false at the site, carried by `OperationError.retryable`); `ownerUnavailableError` is the thrown form. `host_mismatch` prints both host ids' first 8 characters and, when `remote` is false, the `host.json` path this process read; nothing here claims or transfers ownership. Used by `maintenancePreflight`, `loadFenceSource` and `managedRepairRoot`; the registry's `owner_unavailable.reasons` and the `FENCE_REASONS` owner entries carry the same vocabulary. Tests: `test/owner-refusal.test.ts` (matrix, every preflight condition on a claimed worktree, the HTTP envelope without a local path), `test/fence-repair-reasons.test.ts`. `transfer_in_progress` is `wait` until the drain's `prepared_at` is `TRANSFER_STALE_MINUTES` (30) old, then `ask_user` naming the accept and the exact `transfer cancel` argv (a drain with no `prepared_at` keeps the wait).+- `src/core/persistence/owner-refusal.ts` — #6278: the `owner_unavailable` reasons matrix. `checkOwner(binding, incarnation, hostId)` names the first failing condition in a fixed order (`binding_missing`, `incarnation_changed`, `host_mismatch`, `transfer_in_progress` for a `draining` worktree, `clone_in_progress` for `recovering`, `local_path_missing`, `coordination_path_missing`) or returns the usable `ActiveOwnerBinding`; `ownerRefusal` gives each reason its message, `why`, actor, fix (always the read-only `gbrain sources writer status --source <id> --json`, with the same verify; `actor: provider` so the two in-progress reasons render `next: wait` with a 30 s delay, `host_admin` for the rest) and `retryable` (`host_mismatch` false at the site, carried by `OperationError.retryable`); `ownerUnavailableError` is the thrown form. `syncOwnerBinding` (#7956): the managed sync context's owner gate; the conversion checks its root only past it. `host_mismatch` prints both host ids' first 8 characters and, when `remote` is false, the `host.json` path this process read; nothing here claims or transfers ownership. Used by `maintenancePreflight`, `loadFenceSource` and `managedRepairRoot`; the registry's `owner_unavailable.reasons` and the `FENCE_REASONS` owner entries carry the same vocabulary. Tests: `test/owner-refusal.test.ts` (matrix, every preflight condition on a claimed worktree, the HTTP envelope without a local path), `test/fence-repair-reasons.test.ts`. `transfer_in_progress` is `wait` until the drain's `prepared_at` is `TRANSFER_STALE_MINUTES` (30) old, then `ask_user` naming the accept and the exact `transfer cancel` argv (a drain with no `prepared_at` keeps the wait).- `src/core/persistence/repair-busy.ts` — #6278: the busy set a repair must not write while a managed sync runs. `loadRepairBusySet(engine, sourceId, incarnation)` returns the paths and slugs named by queued, running and recovering requests and terminal rows with an open recovery (both rename endpoints included) plus, for every unfinished `managed-sync` cursor of the incarnation, the entries of its frozen `managed-sync-manifest` from the cursor's index on (a path with a `sync-hold` record is left out: the sync retries a held file only when its bytes change); it never throws and fails closed (`unknown` set, so `repairBusy` answers true for everything) when a query fails or a cursor's manifest is missing. `repairBusyMessage` is the hold text, `repairBusyError` the `sync_in_progress` refusal (`reason` `candidate_in_flight` or `busy_set_unreadable`) `submitManagedFileRepair` raises at admission. Tests: `test/repair-busy.test.ts`, `test/repair-fences.test.ts`, `test/repair-fences-during-catchup.test.ts` (Postgres: `test/e2e/repair-fences-during-catchup-postgres.test.ts`).- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement, + the 5 s #6650 dead-owner scan, mirroring the claim, recovery, expired-claim, effect, projection (inline rows windowed by `projection-window.ts`) and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. #5984: `awaitWrite` (`waitForWrite` is its row-only form) receives a request this consumer publishes through the `onSettled` handoff with no request read, and skips polls while `holds(id)` says the consumer has it claimed; otherwise it polls the narrow `WRITE_PROGRESS_SQL` (first poll after min(200 ms, half the wait), then 50 ms backing off to 250 ms) and reads the full row once when terminal. Its own cancelled reads are not failures; a database read failure ends the wait as a classified `read_failed` (auth/permission failures at once), and a pending head with an intervention `blocked_reason` ends as `blocked`. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection from the ordinary pool, never the direct/session route (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. The rate-limited stderr line names the phase, the SQLSTATE or write-error code, a redacted one-line message of at most 200 characters, connection-wait evidence (`first_conn_ms`, or `checkout=not_observed conn_wait_ms`, attributed to the phase through AsyncLocalStorage over the engine's `onCheckout` seam) plus `loop_lag_ms`, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`); the trusted status `phase` carries the same fields. Every claimed write has a preparation budget (`preparation-budget.ts`): `execute` races the preparation against it (`startPreparation`), so the claim is released with `blocked_reason` `preparation_deadline` and one counted attempt at the budget even when the preparer ignores its signal, and a late result never publishes (the execution-token fence). A request already at `persistence.max_preparation_attempts` is finished `failed` with `preparation_stalled` at claim without preparing again, and the release that reaches the limit finishes it there (`coordinator.ts` `finishPreparationStalled`; a waiting `awaitWrite` caller gets the terminal receipt, foreground writes included); a preparer's rejection on the consumer's own abort (its reason, an `AbortError` or a cancelled statement, `preparationAbortReason`) is a release, never a receipt. The expired-claim sweep (Postgres, and PGLite's `releaseAbandonedClaims`) charges one attempt for a claim stamped `preparing` (a process killed mid-preparation); `claim_lost`, `consumer_stopping` and `group_member_waiting` never charge, and a commit resets the counter. A statement the database ended with 57014 (statement timeout or cancel: `coordinator.ts` `writeInterruption`) is charged too, in `finishUnpublishedFailure` and in `publishMutation`'s recovery route, and at the limit ends the request `failed` with `write_interrupted` instead of a `database_contention` release; contention with other transactions (55P03, 40001, 40P01), a dropped connection or a restarting database is never charged (`test/persistence-write-interrupted.test.ts`). The #5373 root barrier for an abandoned preparation ends at `persistence.preparation_ceiling_ms` measured from the claim: the root is freed, the counter is pinned at the limit (an overrun proves cancellation is ignored, so the next claim fails the request `preparation_stalled`) and the zombie stays in `status().outlived_ceiling`; at the per-process cap (`zombieCap`, default 1) the consumer claims nothing more and `status().restart_required` is true. `stop()` gives abandoned preparations `ABANDONED_STOP_GRACE_MS` (5 s) after aborting them instead of waiting forever. The fault point `consumer:preparing` sits inside the budget, `status()` reports `preparation_policy` and `abandoned_preparations`, and the stderr line carries `phase=preparation reason=deadline_exceeded | preparation_stalled | ceiling_exceeded`. With the `preparation_deadlines` switch off only `remember` and intent-less `put_page`/`edit_page` keep the 30 s budget, the old unbounded wait applies and no attempt is counted. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `claimableWriteSql` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (PGLite, 1,000 pages: ~9.5 ms mean, ~18 ms p99 per page). On PGLite the first full tick releases claims last written before this process started (`releaseAbandonedClaims` in `effect-journal.ts`: running effects and unpublished requests without a recovery record), since the datastore admits one process and those owners have exited; Postgres keeps lease expiry (requests 30 s, effects 2 minutes); a provably dead owner's claim goes in 5 s (#6650). On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-consumer-log.test.ts`, `projection-drain.test.ts` (injected clock and per-page cost), `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`. With `requestsOnly` (engine graduation's drain) the effect, projection, topology and maintenance workers never start; claim, recovery, expired-claim and publication run as usual and `stop()` remains the barrier. Both the single route and the grouped/lane route (`executeClaimedGroup` in `group-publish.ts`) prepare under a claim lease (`claim-lease.ts`: a renewal every `renewalIntervalMs`, default 10 s, each bounded by `phaseMs`); the claim is lost the first time a renewal says it is gone, throws or overruns, and `whileHeld` stops waiting on the preparation at that moment (the single route also aborts it). The claims still ours are released unpublished with `claim_lost` (token-fenced, so a consumer that took one over keeps it); the abandoned preparation is never published and keeps its root or lane slot until it settles or the ceiling passes, while the consumer slot frees at once. Renewals are never awaited on the way out: `stop()` drains in-flight renewals and gives abandoned preparations their grace before engine close. Tests: `test/persistence-claim-lease.test.ts`, `test/e2e/persistence-consumer-claim-loss.test.ts`, `test/persistence-preparation-kill-accounting.test.ts`, `test/e2e/persistence-preparation-deadline.e2e.test.ts`. #6355: `onLane` lends its warm lane's transaction through a wrapper that notes a connection loss (`isConnectionLoss`); in `finally` a lost lane is released and `idleLaneRetryAt` set a minute out, whatever `run` returned or threw (admission turns the loss into `write_outcome_unknown` or succeeds on the pool, so the catch alone never saw it), because the dead reservation answers every later statement with "Connection is no longer owned" (`test/persistence-consumer-lane-loss.test.ts`). #7106: `publishSingle` passes `projectionPending` (coordinator.ts `PublicationHooks`): a committed write that created its page (no page at its slug before the publication, and no additional page key such as a rename's) and whose outcome says `projection: 'pending'` (a new segmented page over SEGMENTED_CREATE_SEAL_MAX_BYTES, quarantined or not: `segmentedOutcome` in searchable.ts, recorded by the managed import, sync and put_page preparers) settles its waiter at commit, and its `afterCommit` projection goes to `detachBuild`, which runs at most `DETACHED_PROJECTION_BUILDS` (1) at a time, queued builds in order, each tracked in `outlived` so stop() waits for queued and running builds; it holds neither the reply nor the root. An edit (a deferred retirement included) and a publication without the hook await afterCommit as before (`test/large-pages/managed-import-projection-pending.test.ts`).- **`src/core/persistence/sync-group.ts`** + **`group-publish.ts`** — #5984 bulk publication for draining managed Postgres syncs. `sync-group.ts` resolves bulk settings (`--no-bulk` > `GBRAIN_SYNC_BULK` > `sync.bulk` > on; `sync.bulk_size` 16, `sync.bulk_max_txn_ms` 15 s; PGLite off), sizes the next group from the last group's admission-to-commit time per member, freezes followers (four at a time, stopping at a rename, company plan, overtaken or waived entry, or #6712 a slug or page id shared with a member in flight or held, `dependencyKeys`) and admits a group in one transaction (`admitWriteGroupInTransaction`, which keeps one request row, ID and digest per page and replays priors). `sync-run.ts` keeps the head in `pending` and all members in the cursor's `group` (members carry `intent.group` = the head's request ID), waits for the last member and advances over the committed prefix; a terminal failure becomes the pending entry (settled by fault class; later members stay in the window, #6712), a still-pending member returns `writer_pending`. Any caller finishes an existing group; only a drain forms one. #6075: when another owner loop already admitted the group's head on the single path with the head's pre-group intent (the intent minus the `group`/`lane` keys `formGroup` adds, `groupedIntent`/`ungroupedIntent`), `groupStep` drops the group and the single path takes that request, and the never-admitted followers are frozen again; a different intent under the head's request ID still refuses `idempotency_conflict`. The single path's ENG-A7 admission guard compares the stored pending intent as well as its request ID, so a pass that read the head before a drain grouped it re-reads the cursor instead of admitting the stale intent, and an `idempotency_conflict` against a head the group admitted first re-reads the cursor too (`test/managed-sync-stale-group-head.test.ts`). The consumer claims a head's directly following queued members (`claimGroupFollowers`, never past an unfinished non-member) and `executeClaimedGroup` prepares four at a time, then `publishGroup` publishes them in one transaction: one worktree lock, ownership guard and coordinated write (each member set as the attributed actor with `setMemberAttribution`), per-member authorization, preimage read, sync validation (its source-wide part shared per transaction), apply (which reads the postimage the receipt and effects use), effects and receipt; `completeGroup` then reads every member's effect bytes, and pipelines the counter lock with one `UPDATE ... FROM unnest(...) RETURNING` that checks each member's claim and terminal reservation and releases the counters (a short `RETURNING` throws, so the single path reports each member's own code). #6712: each member keeps its own fate (sync groups keep claim 64, width four, ordered release, `syncGroup`): a failed preparation settles before the rest publish as a group; a sync member its lane group's transaction refused settles alone, the rest requeue (`settleCulprit`); other failures roll back and members publish singly. Sync validation accepts a group member through the cursor's `group`. #6007: the pages of one `put_pages` batch (`intent.page_batch.id`; the group key is `journal.ts` `publicationGroupKey`) and the files of one managed import batch (`intent.import_batch`, key `import:`, grouped on PGLite too; `independentGroup` names both) also publish as groups of at most `PAGE_BATCH_GROUP_MAX` (8) pages, prepared all at once, files included: one transaction records every member's recovery record (`prepareRecoveries`) before any file is touched, the publication transaction marks the members `publication_started`, publishes each member's file before its apply and re-arms the batch's mention links once after every member completes (`reconcileFinishedBatch`), and one transaction clears the records after commit (`clearResolvedRecoveries`). A single foreground page write publishes here too, as a group of one (core-persistence-continued.md, `switches.ts` entry). Within that transaction the source's local path, the owner's host binding and config values are read once per group (source membership and the writer registration are already memoized per transaction by `transactionMemo`). On failure every file the group published is restored by `recoverPublication`, which requeues those claims; the fallback claims them back in order (`reclaimReleasedWrite`) and publishes the members singly. Each member has its own preparation budget (#6278): `executeClaimedGroup` marks a wave durably (`markDispatched`) and starts each member's clock when the wave dispatches it, so a follower waiting behind four others is never charged; the lease renews the mutable set of members still held (`renewGroupClaims` stamps each member's own phase), so releasing one member never reads as a lost group lease. When member k's budget passes, nothing later is dispatched, the in-flight suffix is aborted, k is released `preparation_deadline` (charged; finished `preparation_stalled` when that reaches the limit) and the later members `group_member_waiting` (not charged), and the contiguous prepared prefix 0..k-1 publishes (singly when shorter than two; under lanes in the original group's key order). A `put_pages` batch group releases only k, `laneFallback` keeps the expired member's reason, and an abandoned member's preparation goes to the consumer with its clock, so the root waits for it until it settles or the ceiling. A member's signal reaches its preparer through its clock (`enterClaimStep`), never as a blanket statement signal: `preparationReads` and `groupReads` answer one read for every member (GBRA-75 wave 10: `preparationReads` answers `getConfig` from one `getAllConfig` per group; an import group's members also read their own `{ sourceId, includeDeleted: true }` snapshot from one batch and coalesce `findDuplicatePage` into one `findDuplicatePages` statement through `import-reads.ts`, and the group's preparation runs inside `withScreeningPaths`; publication's `validate`/`checkPaths` run after it, unmemoized) and skip their memo for a signalled statement, so a member that must give up on a shared read races its own signal against the shared promise (pinned by `test/persistence-preparation-memo-rule.test.ts`). A commit resets `preparation_attempts` (`completeGroup`). Tests: `test/managed-sync-bulk.test.ts`, `test/e2e/put-pages-group-postgres.test.ts`, `test/e2e/persistence-group-deadline-postgres.test.ts`.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 2e27a2a319..0edde162ac 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -1910,7 +1910,7 @@ More: [docs/guides/write-refusals.md#file_too_large](../../docs/guides/write-ref| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| Sync held one file because it is not a readable regular file inside the source root (a symlink, a non-regular file or a permission error); the rest of the source synced. | Sync reads only regular files inside the source root and never follows a symlink, which can point anywhere on the host. The file waits in the hold store instead of failing the run, so it never blocks the source, and classic sync re-screens it on every run. | Replace the symlink with the regular file (or delete it), make the file readable to the account gbrain runs as, or leave it out with sync.exclude; the next gbrain sync --source <source> --no-pull re-screens it. | agent | `repeat the read that failed` | 1 | no |+| Sync held one file because it is not a readable regular file inside the source root (a symlink, a non-regular file or a permission error); the rest of the source synced. | Sync reads only regular files inside the source root and never follows a symlink, which can point anywhere on the host. The file waits in the hold store instead of failing the run, so it never blocks the source, and classic sync re-screens it on every run. | Replace the symlink with the regular file (or delete it), make the file readable to the account that runs gbrain, or leave it out with sync.exclude; the next gbrain sync --source <source> --no-pull re-screens it. | agent | `repeat the read that failed` | 1 | no |Reasons: `symlink_in_repo`, `symlink_outside_root`, `symlink_dangling`, `symlink_loop`, `permission_denied`, `not_regular_file`.@@ -2096,7 +2096,7 @@ More: [docs/guides/git-canonical.md#approval-across-time](../../docs/guides/git-| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| A git-canonical conversion stopped because its strict pass did not finish, or finished with work left after the flag was set. | The conversion runs a full strict-equivalent pass before it sets canonical: git, and one genuine strict pass after, then up to three closing strict passes while only door commits a live writer landed meanwhile are left (Git ahead of the database). A pass that ends partial, blocked or deferred stops the conversion where it is: before the flag the source stays as it was, after it the source stays strict (Git wins) and the plan lists what is left. | Wait until gbrain sync status --source <id> --json shows the source idle, then preview again with gbrain sources canonical <id> --to git --dry-run and apply the new hash. | agent | `repeat the read that failed` | 1 | yes |+| A git-canonical conversion stopped because its strict pass did not finish, finished with work left after the flag was set, or found the flag removed (a --to mixed apply) while it ran. | The conversion runs a full strict-equivalent pass before it sets canonical: git, and one genuine strict pass after, then up to three closing strict passes while only door commits a live writer landed meanwhile are left (Git ahead of the database). A pass that ends partial, blocked or deferred stops the conversion where it is: before the flag the source stays as it was, after it the source stays strict (Git wins) and the plan lists what is left. | Wait until gbrain sync status --source <id> --json shows the source idle, then preview again with gbrain sources canonical <id> --to git --dry-run and apply the new hash. | agent | `repeat the read that failed` | 1 | yes |More: [docs/designs/GIT_CANONICAL_MEMORY.md#conversion](../../docs/designs/GIT_CANONICAL_MEMORY.md#conversion)@@ -2222,7 +2222,7 @@ More: [docs/guides/write-refusals.md#git_protocol_required](../../docs/guides/wr| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| A strict (canonical: git) write's file changed on disk while it was being committed, so nothing was committed and the write was not published. | The door commits exactly the bytes the write published, and checks the file's hash against them before and after Git stores it. An edit landing in between would otherwise be committed while the database records other content; recovery leaves the changed file as it is. | When the file holds neither the write's bytes nor the version before it, the write is held in recovery (blocked reason unexpected_file_bytes) and the source's later writes wait behind it; when it holds the version before the write, nothing is held and the write failed, so read the page before resubmitting it with a new request_id. To resolve a held write, preview with gbrain repair stuck-recovery --source <id> --json, ask the user which version to keep, then run gbrain repair stuck-recovery --source <id> --keep disk\|prior --apply --expect <preview_hash> --yes (disk keeps the edit). Run: gbrain sources writer status --json | user | `repeat the read that failed` | 1 | no |+| A strict (canonical: git) write's file changed on disk while it was being committed, so nothing was committed and the write was not published. | The door commits exactly the bytes the write published, and checks the file's hash against them before and after Git stores it. An edit landing in between would otherwise be committed while the database records other content; recovery leaves the changed file as it is. | When the file holds neither the write's bytes nor the version before it, the write is held in recovery (blocked reason unexpected_file_bytes) and the source's later writes wait behind it; when it holds the version before the write, nothing is held and the write failed; when it holds the write's own bytes again by the time recovery runs, recovery restores the version before the write and the write failed, with nothing held. After a failure, read the page before resubmitting it with a new request_id. To resolve a held write, preview with gbrain repair stuck-recovery --source <id> --json, ask the user which version to keep, then run gbrain repair stuck-recovery --source <id> --keep disk\|prior --apply --expect <preview_hash> --yes (disk keeps the edit). Run: gbrain sources writer status --json | user | `repeat the read that failed` | 1 | no |### git_target_ignored@@ -5064,6 +5064,16 @@ More: [docs/guides/write-refusals.md#slug_page_mismatch](../../docs/guides/write|---|---|---|---|---|---|---|| Multiple active sources alias this canonical skill root; resolve ownership before publishing. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |+### source_root_unreadable++<a id="source_root_unreadable"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The source's registered root on its owner host cannot be read as a directory (gone, unmounted, not a directory, no permission or a symlink loop), so `gbrain sources canonical` planned and wrote nothing. | Converting a source reads its whole checkout; a root that cannot be listed would otherwise surface as a raw filesystem or Git error, or as a missing-checkout refusal whose fix creates an empty repository there. | Restore or remount the directory on the brain host (or make it readable to the account that runs gbrain), compare it with the root gbrain sources writer status --source <source> --json names, then preview again. | host_admin | `gbrain doctor --json` | 1 | no |++Reasons: `missing`, `not_directory`, `permission_denied`, `symlink_loop`, `unreadable`.+### source_writeback_required<a id="source_writeback_required"></a>diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex f79d2e6128..2266cc6d73 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -1224,7 +1224,13 @@ The preview lists a terminal request as `refused` with the reason and offersno choice for it. After `--keep disk` the database page still holds thecontent from before the write, so the page shows as file/database drift untilyou reconcile it: `gbrain sources reconcile <source> <slug> --brain host---preview`. The command never reports the page as repaired.+--preview`. On a git-canonical (strict) source Git is the parent, so the kept+bytes are an uncommitted edit instead: publish it with+`gbrain git commit-push --path <checkout> -m "<message>" -- <path>`, or discard+it with `git -C <checkout> restore -- <path>`, then run+`gbrain sync --source <source> --no-pull`; `git status --porcelain -- <path>`+and `gbrain sync status --source <source> --json` verify it. The item's `fix`+asks the user which (#7715). The command never reports the page as repaired.The apply runs under the worktree lock, so the resident recovery pass cannotinterleave. Each step is journaled (`op_checkpoints`, op@@ -3128,8 +3134,10 @@ again. A file whose HEAD bytes would not import as its page is listed under thehold's code (`visibility_noncanonical` for a `Visibility: private` that page privacydoes not read): apply keeps its rows database-only and restores the file fromHEAD so the clone can pull the upstream fix, but does not import HEAD, reports-`held` with the code and leaves the page at its last imported version; sync-holds the file until upstream fixes it (#7897). Each restored file is first backed up under+`held` with the code and leaves the page at its last imported version. The+restored file equals HEAD, so sync does not screen it again and records no+hold; the page changes once an upstream fix is pulled and synced (#7897). Such+a file is an apply item, not a residual (#7910). Each restored file is first backed up under`~/.gbrain/backups/url-clone-fences/`. Its rows stay active and recallable asdatabase-only facts, HEAD's bytes are imported as the page (as sync wouldimport them, except for a held file above), and only then is the file restored; each step is idempotent, sodiff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex 915098bc7c..c267071b8c 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -901,13 +901,20 @@ A path that is absolute only on another operating system (a Windows drive pathsuch as `C:\brain-example`, set by another host sharing the brain, read on Linuxor macOS) is refused the same way, as not an absolute path on this host. Use`set-path` with this host's directory (or `gbrain config set sync.repo_path` for-the legacy key); `--clear` refuses such a path. An explicit absolute `--repo`+the legacy key); `--clear` refuses such a path. If the other host owns the+source, leave the path and sync it there. Doctor warns about such a path on the+`default` source and leaves another source's to the host that set it.+On Windows, a root-relative path (`\brain` or `/brain`) names a folder on+whatever drive gbrain runs from, so it counts as relative. An explicit absolute `--repo`passes the refusal, but it never advances the sync position of a source whose-stored path is relative.+stored path is relative, or of a `default` source with no path behind a relative+`sync.repo_path`. A queued `sync` job for such a source completes as a skip+(`reason: sync_anchor_relative`) carrying the same ask-the-user fix, and+`gbrain sync --all --json` gives the source's entry its `code` and `fix`.Until the path is absolute, the main readers do not treat the folder gbrainruns from as the source either: page and fact writes skip the file and stay in-the database (`repo_not_found`, `no_repo_configured`), a captured file keeps+the database (`repo_not_found`, `no_repo_configured`, `relative_root`), a captured file keepsno origin path, matching a folder to its source ignores the path, fence repairedits stored pages, managed activation refuses it (`source_changed`, detail`source_path_missing`), the dream, autopilot, per-phase and globaldiff --git a/llms-full.txt b/llms-full.txtindex ffc6215362..9cc122beb0 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -10197,13 +10197,20 @@ A path that is absolute only on another operating system (a Windows drive pathsuch as `C:\brain-example`, set by another host sharing the brain, read on Linuxor macOS) is refused the same way, as not an absolute path on this host. Use`set-path` with this host's directory (or `gbrain config set sync.repo_path` for-the legacy key); `--clear` refuses such a path. An explicit absolute `--repo`+the legacy key); `--clear` refuses such a path. If the other host owns the+source, leave the path and sync it there. Doctor warns about such a path on the+`default` source and leaves another source's to the host that set it.+On Windows, a root-relative path (`\brain` or `/brain`) names a folder on+whatever drive gbrain runs from, so it counts as relative. An explicit absolute `--repo`passes the refusal, but it never advances the sync position of a source whose-stored path is relative.+stored path is relative, or of a `default` source with no path behind a relative+`sync.repo_path`. A queued `sync` job for such a source completes as a skip+(`reason: sync_anchor_relative`) carrying the same ask-the-user fix, and+`gbrain sync --all --json` gives the source's entry its `code` and `fix`.Until the path is absolute, the main readers do not treat the folder gbrainruns from as the source either: page and fact writes skip the file and stay in-the database (`repo_not_found`, `no_repo_configured`), a captured file keeps+the database (`repo_not_found`, `no_repo_configured`, `relative_root`), a captured file keepsno origin path, matching a folder to its source ignores the path, fence repairedits stored pages, managed activation refuses it (`source_changed`, detail`source_path_missing`), the dream, autopilot, per-phase and globaldiff --git a/src/cli/commands/append.ts b/src/cli/commands/append.tsindex 1317f06f38..b33fbeb6d8 100644--- a/src/cli/commands/append.ts+++ b/src/cli/commands/append.ts@@ -456,7 +456,8 @@ async function streamLocalPage(connect: () => Promise<BrainEngine>, path: stringassertPageRevision(await engine.readPageSnapshot(slug, { sourceId, includeDeleted: true }), engineMutationPrecondition(parseMutationPrecondition(params)));const result = await importStreamedMarkdownFile(engine, resolve(path), relativePath, { sourceId, inferFrontmatter: false, content }, stat, policy);if (result.status === 'skipped' && result.error) {- throw opError(result.refusal?.code === 'invalid_frontmatter' ? 'invalid_frontmatter' : result.refusal?.code === 'visibility_noncanonical' ? 'visibility_not_applied' : 'invalid_params', result.error,+ if (result.refusal?.code === 'visibility_noncanonical') throw (await import('../../core/persistence/visibility-request.ts')).privateRequestRefusal({ slug, source_id: sourceId }, undefined);+ throw opError(result.refusal?.code === 'invalid_frontmatter' ? 'invalid_frontmatter' : 'invalid_params', result.error,`${path} was not written as ${slug}: fix what the message names (or split the file into smaller pages) and run the command again.`);}return result;diff --git a/src/commands/doctor/checks/default-source-path.ts b/src/commands/doctor/checks/default-source-path.tsindex ef448abf32..8ea95b6a5e 100644--- a/src/commands/doctor/checks/default-source-path.ts+++ b/src/commands/doctor/checks/default-source-path.ts@@ -8,19 +8,47 @@* under sync.repo_path), so the check only warns when the fallback* demonstrably fails — see the helper's doc comment for the exact gates.* #7630: it also warns on a relative default local_path or sync.repo_path and- * for every other source whose local_path is relative.+ * for every other source whose local_path is relative (a path absolute only on+ * another OS belongs to the host that set it, so it is not listed). #7646:+ * that scan runs on its own, so a failed read leaves the rest of the check, and+ * the database-only note names every live source with no local_path whose+ * pages a relative sibling keeps out of sync.repo_path.** Lives in the doctor module dir per the peeled-façade rule — new code goes* here, not back into doctor.ts. Returns null for the 'skip' verdict when no- * source has a relative local_path, so the caller pushes nothing.+ * other source needs a note, so the caller pushes nothing.*/import { existsSync, statSync } from 'fs';-import { isAbsolute, posix, win32 } from 'path';import type { BrainEngine } from '../../../core/engine.ts';import type { Check } from '../../doctor.ts';import { assessDefaultSourcePath } from '../../../core/default-source-path-check.ts';+import { isForeignAbsolutePath, isHostAbsolutePath } from '../../../core/path-confine.ts';import { otherSourceOwning } from '../../../core/write-through.ts';+type PathRow = { id: string; local_path: string };++/** Every other live source whose local_path is relative on this host (not absolute here or on another OS). */+async function relativeSources(engine: BrainEngine): Promise<PathRow[]> {+ return (await engine.executeRaw<PathRow>(+ `SELECT id, local_path FROM sources WHERE id <> 'default' AND local_path IS NOT NULL AND local_path <> '' AND archived IS NOT TRUE ORDER BY id`,+ )).filter(row => !isHostAbsolutePath(row.local_path) && !isForeignAbsolutePath(row.local_path));+}++function siblingNote(relative: PathRow[], pathless: string[]): string {+ const parts: string[] = [];+ if (relative.length > 0) {+ parts.push(`${relative.map(row => `source "${row.id}" has the relative local_path "${row.local_path}"`).join('; ')}, which names whatever directory ` ++ 'gbrain runs from, so sync refuses it (sync_anchor_relative). Ask the user which directory holds its files, then run ' ++ '`gbrain sources set-path <id> <absolute-directory>`, or clear the pointer with `gbrain sources set-path <id> --clear`.');+ }+ if (pathless.length > 0) {+ parts.push(pathless.includes('default')+ ? 'Until then, pages of every source with no local_path (the default source and any `.sources/<id>` source) are saved to the database only, not written under sync.repo_path.'+ : `Until then, pages of ${pathless.map(id => `"${id}"`).join(', ')} (no local_path) are saved to the database only, not written under sync.repo_path.`);+ }+ return parts.join(' ');+}+export async function defaultSourceLocalPathCheck(engine: BrainEngine): Promise<Check | null> {const [defaultSource] = await engine.executeRaw<{ local_path: string | null }>(`SELECT local_path FROM sources WHERE id = 'default'`,@@ -31,12 +59,14 @@ export async function defaultSourceLocalPathCheck(engine: BrainEngine): Promise<let repoPath: string | null = null;let repoPathIsDir = false;let collidingSourceId: string | null = null;- let blockedByRelative = false;let sharedPages = 0;- // #7630: any other source with a relative local_path is refused by sync the same way, so name it here too.- const relative = (await engine.executeRaw<{ id: string; local_path: string }>(- `SELECT id, local_path FROM sources WHERE id <> 'default' AND local_path IS NOT NULL AND local_path <> '' AND archived IS NOT TRUE ORDER BY id`,- )).filter(row => !posix.isAbsolute(row.local_path) && !win32.isAbsolute(row.local_path));+ let relative: PathRow[] = [];+ let scanFailed: string | null = null;+ try {+ relative = await relativeSources(engine);+ } catch (error) {+ scanFailed = error instanceof Error ? error.message : String(error);+ }// Only gather the fallback-topology inputs when the pointer is actually// null — the set case resolves from the row alone.if (defaultSource && !defaultSource.local_path) {@@ -49,7 +79,7 @@ export async function defaultSourceLocalPathCheck(engine: BrainEngine): Promise<livePages = Number(counts?.live ?? 0);fileBackedPages = Number(counts?.file_backed ?? 0);repoPath = (await engine.getConfig('sync.repo_path')) || null;- if (repoPath && isAbsolute(repoPath)) {+ if (repoPath && isHostAbsolutePath(repoPath)) {try {repoPathIsDir = existsSync(repoPath) && statSync(repoPath).isDirectory();} catch {@@ -57,7 +87,6 @@ export async function defaultSourceLocalPathCheck(engine: BrainEngine): Promise<}// Mirror resolvePageWriteTarget's #2018 leak guard: sync.repo_path// being another source's own working tree silently skips the write.- blockedByRelative = relative.length > 0;collidingSourceId = await otherSourceOwning(engine, 'default', repoPath, false);if (collidingSourceId) {const [shared] = await engine.executeRaw<{ n: number }>(@@ -70,6 +99,17 @@ export async function defaultSourceLocalPathCheck(engine: BrainEngine): Promise<}}}+ // A live relative sibling makes the leak guard refuse every write under sync.repo_path, so pages of any live source+ // with no local_path go database-only, whether or not default has a path of its own.+ let pathless: string[] = [];+ if (relative.length > 0) {+ const globalRepo = repoPath ?? ((await engine.getConfig('sync.repo_path')) || null);+ if (globalRepo && isHostAbsolutePath(globalRepo)) {+ pathless = (await engine.executeRaw<{ id: string }>(+ `SELECT id FROM sources WHERE (local_path IS NULL OR local_path = '') AND archived IS NOT TRUE ORDER BY id`,+ )).map(row => row.id);+ }+ }const assessment = assessDefaultSourcePath({defaultSource,@@ -80,15 +120,11 @@ export async function defaultSourceLocalPathCheck(engine: BrainEngine): Promise<collidingSourceId,sharedPages,});- if (assessment.status === 'skip' && relative.length === 0) return null;- const relativeNote = relative.length === 0 ? '' :- `${relative.map(row => `source "${row.id}" has the relative local_path "${row.local_path}"`).join('; ')}, which names whatever directory ` +- 'gbrain runs from, so sync refuses it (sync_anchor_relative). Ask the user which directory holds its files, then run ' +- '`gbrain sources set-path <id> <absolute-directory>`, or clear the pointer with `gbrain sources set-path <id> --clear`.' +- (blockedByRelative ? ' Until then, pages of every source with no local_path (the default source and any `.sources/<id>` source) are saved to the database only, not written under sync.repo_path.' : '');- return {- name: 'default_source_local_path',- status: relative.length > 0 || assessment.status === 'skip' ? 'warn' : assessment.status,- message: relativeNote ? [relativeNote, blockedByRelative && assessment.status === 'ok' ? '' : assessment.message].filter(Boolean).map(part => /[.!?]$/.test(part) ? part : `${part}.`).join(' ') : assessment.message,- };+ const note = siblingNote(relative, pathless);+ const failedNote = scanFailed === null ? '' : `Other sources' local_path values could not be read, so they were not checked (${scanFailed}).`;+ if (assessment.status === 'skip' && !note && !failedNote) return null;+ if (!note && !failedNote) return { name: 'default_source_local_path', status: assessment.status === 'ok' ? 'ok' : 'warn', message: assessment.message };+ const hidesFallback = pathless.includes('default') && assessment.status === 'ok';+ const message = [note, hidesFallback ? '' : assessment.message, failedNote].filter(Boolean).map(part => /[.!?]$/.test(part) ? part : `${part}.`).join(' ');+ return { name: 'default_source_local_path', status: 'warn', message };}diff --git a/src/commands/dream.ts b/src/commands/dream.tsindex fb5eda5a52..680156f97d 100644--- a/src/commands/dream.ts+++ b/src/commands/dream.ts@@ -915,16 +915,21 @@ export async function runDream(engine: BrainEngine | null, args: string[]): Prom// 'partial' cycles still exit 0.const failedPhases = report.phases.filter(p => p.status === 'fail' || p.details?.contained === true).map(p => p.phase);const failed = report.status === 'failed' || failedPhases.length > 0;+ // #7646: a phase that needs the user (sync_anchor_relative) fails again on every rerun; its ask_user fix leads instead.+ const askPhase = report.phases.find(p => failedPhases.includes(p.phase) && p.fix?.next === 'ask_user');if (!opts.json) printHuman(report);else if (!failed || !jsonGuardActive()) await writeJsonDocument(JSON.stringify(report, null, 2));else {// D2: under the --json guard a failed cycle is one envelope leading with the CycleReport keys.writeCliError(opError('cycle_failed', `The dream cycle ${report.status === 'failed' ? 'failed' : 'had failing phases'}${failedPhases.length ? ` (${failedPhases.join(', ')})` : ''}.`,- `Read phases[].error for the cause, fix it, then rerun the phase: gbrain dream --phase ${failedPhases[0] ?? '<phase>'}`),- 'dream', { json: true, stderr: false, legacy: { ...report } });+ askPhase ? `The ${askPhase.phase} phase needs the user: ${askPhase.summary} Follow phases[].fix before rerunning.`+ : `Read phases[].error for the cause, fix it, then rerun the phase: gbrain dream --phase ${failedPhases[0] ?? '<phase>'}`),+ 'dream', { json: true, stderr: false, legacy: { ...report }, ...(askPhase ? { extra: { fix: askPhase.fix } } : {}) });}if (failed && !opts.json && failedPhases.length > 0) {- console.error(`Dream failed: ${failedPhases.length} phase(s) failed (${failedPhases.join(', ')}); see the phase errors above. After fixing the cause, re-run one with: gbrain dream --phase ${failedPhases[0]}`);+ console.error(askPhase+ ? `Dream failed: the ${askPhase.phase} phase needs the user before it can run: ${askPhase.fix?.user_message ?? askPhase.summary}`+ : `Dream failed: ${failedPhases.length} phase(s) failed (${failedPhases.join(', ')}); see the phase errors above. After fixing the cause, re-run one with: gbrain dream --phase ${failedPhases[0]}`);}if (failed) process.exit(1);diff --git a/src/commands/sources-canonical.ts b/src/commands/sources-canonical.tsindex b6bbd912e5..8f57aab7c6 100644--- a/src/commands/sources-canonical.ts+++ b/src/commands/sources-canonical.ts@@ -76,7 +76,8 @@ export function describeGitPreview(p: GitConversionPreview): string {function describeResult(r: GitConversionResult): string {if (r.status === 'delta') return [`Source ${r.source_id} is still mixed: ${r.committed.pages} unchanged approved page(s) committed in ${r.committed.groups} door commit(s), ${r.withheld.pages} withheld; ${r.delta!.count} item(s) left unapplied (${counts(r.delta!.by)}).`,...r.delta!.items.slice(0, 20).map(item => ` ${item.reason}: ${item.item}`), 'Relay this list to the owner; after their decision preview again with --approval-out and apply the new approval.'].join('\n');- const lines = [`Source ${r.source_id} ${r.status === 'converted' ? 'is git-canonical' : 'is git-canonical, with work left'}: ${r.committed.pages} page(s) committed in ${r.committed.groups} door commit(s), ${r.withheld.pages} private page(s) withheld (${r.withheld.commits.length} removal commit(s)), ${r.holds_cleared} hold(s) cleared, ${r.parked.retried} parked effect(s) retried and ${r.parked.reclassified} reclassified.`];+ const state = r.status === 'converted' ? 'is git-canonical' : r.after.strict ? 'is git-canonical, with work left' : 'is mixed again (canonical: git was removed while the conversion ran)';+ const lines = [`Source ${r.source_id} ${state}: ${r.committed.pages} page(s) committed in ${r.committed.groups} door commit(s), ${r.withheld.pages} private page(s) withheld (${r.withheld.commits.length} removal commit(s)), ${r.holds_cleared} hold(s) cleared, ${r.parked.retried} parked effect(s) retried and ${r.parked.reclassified} reclassified.`];if (r.push.state === 'pending') lines.push(`Push pending (${r.push.code}): ${r.push.notice}`);if (r.reclassified.length) lines.push(`Held instead of overwritten (the page moved since the plan): ${r.reclassified.length} (${r.reclassified.slice(0, 20).join(', ')}).`);if (r.status === 'incomplete') lines.push(describeGitPreview(r.after));@@ -190,9 +191,13 @@ export async function runSourcesCanonical(engine: BrainEngine, args: string[]):}if (result.status === 'incomplete') {const closing = result.closing_passes ? ` and ${result.closing_passes} closing pass(es), with Git still ahead at ${result.after.git_wins.count} path(s)` : '';- const error = opError('git_conversion_incomplete', `Source ${parsed.sourceId} is git-canonical, and ${result.after.remaining} item(s) were still open after its strict passes${closing}.`,- `Writes landed during the conversion. Git wins on the source now; preview again with gbrain sources canonical ${parsed.sourceId} --to git --dry-run and apply the new hash.`,- { docs: DOCS, detail: 'work_left', fix: conversionIncompleteFix(parsed.sourceId) });+ const error = result.after.strict+ ? opError('git_conversion_incomplete', `Source ${parsed.sourceId} is git-canonical, and ${result.after.remaining} item(s) were still open after its strict passes${closing}.`,+ `Writes landed during the conversion. Git wins on the source now; preview again with gbrain sources canonical ${parsed.sourceId} --to git --dry-run and apply the new hash.`,+ { docs: DOCS, detail: 'work_left', fix: conversionIncompleteFix(parsed.sourceId) })+ : opError('git_conversion_incomplete', `Source ${parsed.sourceId} is mixed: its canonical: git flag was removed (a --to mixed apply) while the conversion ran, so it did not convert.`,+ `Nothing is undone: the door commits stay in Git and the source syncs as a mixed source. If it should be git-canonical, preview again with gbrain sources canonical ${parsed.sourceId} --to git --dry-run and apply the new hash.`,+ { docs: DOCS, detail: 'flag_removed', fix: conversionIncompleteFix(parsed.sourceId) });print({ status: 'incomplete', result, ...toAgentError(error, { transport: 'cli', command: 'sources canonical', render: cliRenderContext() }) }, describeResult(result));setCliExitVerdict(1);return;diff --git a/src/commands/sync/run.ts b/src/commands/sync/run.tsindex 73b9bb0da0..783e709ca6 100644--- a/src/commands/sync/run.ts+++ b/src/commands/sync/run.ts@@ -1,10 +1,9 @@/** `gbrain sync` CLI body (`runSyncInner`): flag parsing, --all fan-out, watch mode. */import { existsSync } from 'fs';-import { isAbsolute } from 'path';import { getCompanyBrainProfile } from '../../core/company-brain/profile.ts';import { slog, withSourcePrefix } from '../../core/console-prefix.ts';import type { BrainEngine } from '../../core/engine.ts';-import { msysToNativePath } from '../../core/path-confine.ts';+import { isHostAbsolutePath, msysToNativePath } from '../../core/path-confine.ts';import { syncFailureJsonFields, readManagedSyncFailures } from '../../core/persistence/sync-failures.ts';import { syncHoldJsonFields } from '../../core/persistence/sync-holds.ts';import { printHoldNotes } from '../sync-diagnostics.ts';@@ -48,7 +47,7 @@ import { cliRenderContext, renderNotice, type Notice } from '../../core/agent-ouconst emitJson = (text: string): void => { void writeJsonDocument(text); };/** #7630: a stored root that is not absolute names the cwd, so post-sync .gitignore upkeep skips it. */-const absoluteStoredPath = (path: string | null): string | null => path && isAbsolute(path) ? path : null;+const absoluteStoredPath = (path: string | null): string | null => path && isHostAbsolutePath(path) ? path : null;type SyncAllSourceRow = { id: string; name: string; local_path: string | null; config: Record<string, unknown>; last_commit: string | null; chunker_version: string | null };@@ -59,6 +58,8 @@ type PerSourceResult = {status: 'ok' | 'error' | 'skipped_missing_path';result?: SyncResult;error?: string;+ /** #7646: a refusal's agent contract (code, why, fix), so an --all consumer gets what a single-source sync exits 3 with. */+ contract?: Record<string, unknown>;localPath?: string;};@@ -66,6 +67,11 @@ type PerSourceResult = {function runNotices(result: SyncResult): Notice[] {return [...(result.tail?.notice ? [result.tail.notice] : []), ...(result.reason_notices ?? []), ...(result.privacy_label_notice ? [result.privacy_label_notice] : [])];}+const failureContract = (error: unknown): Record<string, unknown> | undefined => {+ if (!(error instanceof Error) || error.name !== 'OperationError') return undefined;+ const { code, suggestion, why, fix } = (error as Error & { toJSON(): Record<string, unknown> }).toJSON();+ return { code, ...(suggestion ? { suggestion } : {}), ...(why ? { why } : {}), ...(fix ? { fix } : {}) };+};/*** #6696 (A4): a sync receipt carries the capacity notices (60 s snapshot, at most once an hour per process per@@ -482,7 +488,7 @@ async function runSyncAll(const policyFailures = new Map<string, unknown>();for (const source of runnableSources) {// #7630: a relative local_path fails its source before the cost gate walks the directory.- if (source.local_path && !isAbsolute(msysToNativePath(source.local_path))) { policyFailures.set(source.id, syncAnchorRelativeError(source.id, source.local_path)); continue; }+ if (source.local_path && !isHostAbsolutePath(source.local_path)) { policyFailures.set(source.id, syncAnchorRelativeError(source.id, source.local_path)); continue; }try { companyPolicies.set(source.id, await getCompanyBrainProfile(engine, source.id)); }catch (error) { policyFailures.set(source.id, error); }}@@ -722,6 +728,7 @@ export async function dispatchSyncAll(input: {sourceName: src.name,status: 'error',error: msg,+ contract: failureContract(r.reason),});}}@@ -746,6 +753,7 @@ export async function dispatchSyncAll(input: {sourceName: src.name,status: 'error',error: msg,+ contract: failureContract(e),});}}@@ -798,6 +806,7 @@ function emitSyncAllEnvelope(input: {...(r.result.type_warnings ? { type_warnings: r.result.type_warnings } : {}),} : {}),...(r.error ? { error: r.error } : {}),+ ...r.contract,...(embedBackfillBySource.has(r.sourceId)? { embed_backfill: embedBackfillBySource.get(r.sourceId) }: {}),@@ -874,7 +883,7 @@ async function runSingleSourceSync(if (gateRows.length > 0) {const gate = await resolveSingleSyncEmbedPlan(engine, {sourceId,- local_path: (gateRows[0].local_path && isAbsolute(gateRows[0].local_path) ? gateRows[0].local_path : null) ?? repoPath ?? null,+ local_path: absoluteStoredPath(gateRows[0].local_path) ?? repoPath ?? null,config: gateRows[0].config ?? {},last_commit: gateRows[0].last_commit,chunker_version: gateRows[0].chunker_version,diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex ba88dee396..6dcbc69d6c 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1578,6 +1578,16 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.529.0', id: 'owner_repair_file_restore_7960', text: 'On an unmanaged repository brain, `gbrain repair provenance --apply` or `gbrain trust backfill --repair-unknown-markers` whose database write fails after the page file was written now puts the file\'s previous bytes back, and when the write had been committed on a hardened checkout, commits that restore (`gbrain: restore write-through <slug>`), so a failed apply leaves the file, Git and the database unchanged (#7960).' },// GBRA-261 lane F (#7777, #7780).{ since: '0.60.529.0', id: 'protocol_guard_refusal_typed_7777', text: 'A write refused during publication by a persistence protocol guard (SQLSTATE 42501) now fails with the guard\'s own code on its receipt, `writer_upgrade_required`, `writer_not_quiesced`, `unsupported_mutation_protocol` or `writer_coordinator_required` (relationship `unreadable_state` when the database role cannot read the writer state), with `write_error_detail` naming the guard and a suggestion for that refusal, instead of `storage_error` for an unexpected owner exception. `gbrain sources writer status` gives the same step in `recent_failures[].next_action`. Any other permission error is unchanged, and so is the same refusal outside publication (write admission, protocol activation), which still reports `permission_denied`. Every `unreadable_state` refusal (#7780) now reads "writer state this database role cannot fully read (row-level security hides it or applies to the role, or a singleton row is missing)", its receipt suggests running gbrain as a role that can read that state instead of upgrading, and `gbrain sources writer status` shows the table in `recent_failures[].error_detail.state`.' },+ // #7717 items 9 and 13, #7755, #7756 (strict door). `since` is stamped at the merge slot.+ { since: '0.60.529.0', id: 'door_index_refresh_7717', text: 'On a source with `canonical: git`, a page committed with a legacy file mode (100664) no longer gets a mode-only commit when a write leaves its bytes unchanged, and with `core.fileMode=false` a write of it commits the page as 100644 (before, Git refused the rebuilt tree and the write failed `git_unavailable`). A write replayed after its commit landed and refused `git_index_conflict` because someone staged the page meanwhile now says HEAD already holds its bytes, instead of that it committed nothing. The index refresh after a door commit removes the index copies (`index.gbrain-<pid>-*` in the git directory) a killed gbrain process left behind, and on Windows retries a briefly refused rename of the index before it reports that the commit landed but the index was not updated.' },+ // GBRA-261 lane E (#7646 stored-root follow-ups).+ { since: '0.60.529.0', id: 'stored_root_predicate_7646', text: 'Stored paths (`sources.local_path`, `sync.repo_path`) are judged absolute by one rule in sync, `config set sync.repo_path`, write-through, `gbrain sources set-path --clear` and doctor. On Windows only a drive path (`C:\\...`) or a UNC share counts: a root-relative `\\brain` or `/brain`, which names a folder on whatever drive gbrain runs from, is refused by sync (`sync_anchor_relative`) and cleared by `--clear` like `.`. Doctor\'s `default_source_local_path` now warns when the `default` source\'s own path is absolute only on another operating system (a Windows drive path read on Linux or macOS), where it reported ok. A page or fact write whose stored root is not absolute on this host records the database-only reason `relative_root` (it was `no_repo_configured` or none).' },+ { since: '0.60.529.0', id: 'sync_anchor_relative_jobs_7646', text: 'A queued `sync` job for a source whose stored path is not absolute on this host completes as a skip (`reason: sync_anchor_relative`, with the ask-the-user fix) instead of failing and using up its attempts. `gbrain sync --all --json` gives such a source\'s entry `code`, `why` and `fix` beside `error`. With a stored `.`, `gbrain sync --repo ./` is refused like `--repo .`. A relative `sync.repo_path` behind a `default` source with no path no longer lets an explicit `--repo` advance default\'s last synced commit. `gbrain dream --json` puts a failed phase\'s ask-the-user fix in its `cycle_failed` envelope.' },+ // GBRA-261 lane B (#7956, #7715, #7910, #7881).+ { since: '0.60.529.0', id: 'conversion_root_owner_7956', text: '`gbrain sources canonical <id> --to git` refuses a registered root it cannot read (gone, unmounted, a file, no permission or a symlink loop) with `source_root_unreadable` (reason and fix) instead of a raw filesystem or Git error, and an archived or re-registered source refuses `owner_unavailable` before the Git checkout check instead of `git_checkout_required`. An apply whose source was returned to mixed (`--to mixed`) while it ran reports `incomplete` with a message that the source is mixed, never `converted` (#7956).' },+ { since: '0.60.529.0', id: 'stuck_recovery_strict_followup_7715', text: 'On a git-canonical (strict) source, `gbrain repair stuck-recovery --keep disk` now says the kept bytes are an uncommitted edit at the file\'s path and hands off to commit then sync (`gbrain git commit-push --path <checkout> -m "<message>" -- <path>`, or `git -C <checkout> restore -- <path>` to discard, then `gbrain sync --source <id> --no-pull`; verify with `git status --porcelain` then `gbrain sync status --source <id> --json`), with an ask-the-user `fix` in the item detail, instead of a database-side `sources reconcile`. Mixed sources keep the reconcile follow-up (#7715).' },+ { since: '0.60.529.0', id: 'url_clone_fences_held_preview_7910', text: '`gbrain repair url-clone-fences` lists a held file (for example `visibility_noncanonical`) once, as an apply item, and no longer also counts it as a residual; its preview says the restored file equals HEAD, so sync does not screen it again and the page changes once an upstream fix is pulled and synced (it no longer claims sync holds the file) (#7910).' },+ { since: '0.60.529.0', id: 'streamed_put_visibility_wording_7881', text: 'On a brain without managed persistence, `gbrain put --file` and `gbrain capture --file` of a page over the single-string ceiling that asks for `visibility: private` in a spelling page privacy does not read refuse `visibility_not_applied` with the page-write message a smaller put gives (nothing was written; write `visibility: private` on its own frontmatter line), not the import hold\'s "sync or import the file again" (#7881).' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */@@ -1615,10 +1625,12 @@ export function behaviorChangesNotice(chain: ChainDisclosure | null, opts: { rembyRelease.set(change.since, [...(byRelease.get(change.since) ?? []), text]);}if (byRelease.size === 0) return null;- const count = [...byRelease.values()].reduce((n, texts) => n + texts.length, 0);+ // #7646: rows sit in table order, which is not always release order; the disclosure lists releases oldest first.+ const releases = [...byRelease].sort(([a], [b]) => compareReleases(a, b));+ const count = releases.reduce((n, [, texts]) => n + texts.length, 0);let n = 0;- const why = `gbrain ${releaseSpan([...byRelease.keys()])} changed ${count} behavior${count === 1 ? '' : 's'} on this brain. All stay on; this is a one-time disclosure, not a request for consent. ` +- [...byRelease].map(([since, texts]) => (byRelease.size > 1 ? `v${since}: ` : '') + texts.map(t => `(${++n}) ${t}`).join(' ')).join(' ') ++ const why = `gbrain ${releaseSpan(releases.map(([since]) => since))} changed ${count} behavior${count === 1 ? '' : 's'} on this brain. All stay on; this is a one-time disclosure, not a request for consent. ` ++ releases.map(([since, texts]) => (releases.length > 1 ? `v${since}: ` : '') + texts.map(t => `(${++n}) ${t}`).join(' ')).join(' ') +' gbrain doctor --only behavior_changes shows this again.';const fix: Action = chain && namesChain && !opts.remote? chatFallbackRemovalFix(chain.plane, chain.filePath)diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex f75c16fec6..a1d5bdec63 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -78,7 +78,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--request-id', '--source', '--type'],'hook': ['--allow-unverified-remote', '--auto', '--batch-check', '--brain', '--branch', '--cached', '--catalog', '--count', '--diff-filter', '--dir', '--enable', '--end-of-options', '--env', '--force-with-lease', '--gbrain-bin', '--get', '--harness', '--heads', '--help', '--instructions', '--instructions-only', '--is-ancestor', '--jq', '--json', '--limit', '--name-only', '--no-follow-tags', '--no-instructions', '--no-tags', '--only', '--others', '--pat-file', '--path', '--porcelain', '--print', '--pure', '--quiet', '--recurse-submodules', '--remove', '--scope', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--source-ids', '--verify', '--workspace', '--yes'],'import': ['--accept-pending', '--access-policy', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--as', '--background', '--batch-check', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--url', '--verify', '--wait', '--workers', '--yes'],- 'init': ['--abandon', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--access', '--access-policy', '--acknowledge-managed', '--adopt', '--advertise', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--allow-without-owner', '--anchor', '--applied', '--apply', '--approval-out', '--approved', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto', '--auto-additive', '--background', '--base', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--catch-up', '--channel', '--chat-model', '--check', '--check-downgrade', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--conversation', '--cursor', '--db-only', '--deadline', '--decisions', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--federated', '--file', '--filter', '--first-parent', '--fix', '--force', '--force-all', '--force-retry', '--force-schema', '--format', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--git', '--grammar', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-covered', '--include-cross-entity', '--include-failures', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--input', '--install', '--instructions-only', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--label-lowerings', '--lanes', '--legacy-lock', '--limit', '--link', '--list', '--list-out', '--local', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--may-act-for', '--mcp-only', '--mcp-url', '--member', '--members', '--members-file', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-git', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-stdio-member', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--of', '--older-than', '--once', '--only', '--operation', '--output', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--qm', '--query', '--question', '--quiet', '--readers', '--reason', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remote', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retire', '--retry-failed', '--retry-parked', '--runtime', '--safe', '--save', '--scan-secrets', '--scan-timeout', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--serves', '--session', '--session-id', '--shared-skills', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--slugs-file', '--source', '--source-id', '--sources', '--squash', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--take', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--types', '--uninstall', '--unsettle', '--untrack', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],+ 'init': ['--abandon', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--access', '--access-policy', '--acknowledge-managed', '--adopt', '--advertise', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--allow-without-owner', '--anchor', '--applied', '--apply', '--approval-out', '--approved', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto', '--auto-additive', '--background', '--base', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--catch-up', '--channel', '--chat-model', '--check', '--check-downgrade', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--conversation', '--cursor', '--db-only', '--deadline', '--decisions', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--federated', '--file', '--filter', '--first-parent', '--fix', '--force', '--force-all', '--force-retry', '--force-schema', '--format', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--git', '--grammar', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-covered', '--include-cross-entity', '--include-failures', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--input', '--install', '--instructions-only', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--label-lowerings', '--lanes', '--legacy-lock', '--limit', '--link', '--list', '--list-out', '--local', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--may-act-for', '--mcp-only', '--mcp-url', '--member', '--members', '--members-file', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-git', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-stdio-member', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--of', '--older-than', '--once', '--only', '--operation', '--output', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--qm', '--query', '--question', '--quiet', '--readers', '--reason', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remote', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retire', '--retry-failed', '--retry-parked', '--runtime', '--safe', '--save', '--scan-secrets', '--scan-timeout', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--serves', '--session', '--session-id', '--shared-skills', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--slugs-file', '--source', '--source-id', '--sources', '--squash', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--take', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--types', '--uninstall', '--unsettle', '--untrack', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--as', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--timings', '--type', '--wait'],'jobs': ['--abbrev-ref', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--agent', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--approval-out', '--approved', '--as', '--asof', '--assign-corpus', '--attest-actor', '--attest-ops', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--base', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--bundled', '--by-mention', '--cached', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--clear', '--cli-path', '--client', '--close', '--cluster-errors', '--code', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--decisions', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-catalog', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filter', '--filters', '--finished-since', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--format', '--fresh', '--from-index', '--from-json', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include', '--include-ambiguous', '--include-content', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--input-json', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--members', '--members-file', '--migrate-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-assume-unchanged', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-skip-worktree', '--no-verify', '--no-worker', '--non-interactive', '--now', '--of', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--qm', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--readers', '--reason', '--reason-scan-limit', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--restart-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--routing', '--row', '--save', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--serves', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skill-loading', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stdio-member', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--text', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--token-env', '--trust', '--type', '--types', '--uninstall', '--untrack', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],diff --git a/src/core/default-source-path-check.ts b/src/core/default-source-path-check.tsindex 64fd39363d..e47871d93a 100644--- a/src/core/default-source-path-check.ts+++ b/src/core/default-source-path-check.ts@@ -22,8 +22,9 @@* write-through, fence writes, and delete-reconcile cannot find them.** - RELATIVE PATH (#7630): a set `local_path`, or with a null one a- * `sync.repo_path`, that is not absolute (a legacy "."). It names whatever- * directory gbrain runs from, and sync refuses it `sync_anchor_relative`.+ * `sync.repo_path`, that is not absolute on this host (a legacy ".", or a+ * path absolute only on another OS). Sync refuses it `sync_anchor_relative`+ * by the same predicate (`isHostAbsolutePath`).** Everything else (no pages yet, resolvable repo fallback, deliberate* DB-only brain) reports ok. The repair for a genuinely broken pointer is@@ -34,7 +35,7 @@* npm-squat-check.ts / pglite-leftovers-check.ts. The gathering wrapper* lives on the doctor surface (doctor/checks/default-source-path.ts).*/-import { posix, win32 } from 'path';+import { isForeignAbsolutePath, isHostAbsolutePath } from './path-confine.ts';export interface DefaultSourcePathInput {/** The `default` sources row, or undefined when no such row exists. */@@ -68,7 +69,17 @@ export function assessDefaultSourcePath(// integrity.return { status: 'skip', message: '' };}- if (defaultSource.local_path && !posix.isAbsolute(defaultSource.local_path) && !win32.isAbsolute(defaultSource.local_path)) {+ if (defaultSource.local_path && isForeignAbsolutePath(defaultSource.local_path)) {+ return {+ status: 'warn',+ message:+ `default source local_path "${defaultSource.local_path}" is not an absolute path on this host (another host sharing this ` ++ 'brain may have set it), so sync here refuses it (sync_anchor_relative). If that host owns the brain, sync from there and ' ++ 'leave the path alone; otherwise ask the user which directory on this host holds the brain, then run ' ++ '`gbrain sources set-path default <absolute-directory>`.',+ };+ }+ if (defaultSource.local_path && !isHostAbsolutePath(defaultSource.local_path)) {return {status: 'warn',message:@@ -84,7 +95,17 @@ export function assessDefaultSourcePath(message: `default source local_path is set: ${defaultSource.local_path}`,};}- if (repoPath && !posix.isAbsolute(repoPath) && !win32.isAbsolute(repoPath)) {+ if (repoPath && isForeignAbsolutePath(repoPath)) {+ return {+ status: 'warn',+ message:+ `default source has no local_path and sync.repo_path "${repoPath}" is not an absolute path on this host (another host ` ++ 'sharing this brain may have set it), so default-source page writes here skip the repository and sync refuses it. If ' ++ 'that host owns the brain, sync from there and leave the path alone; otherwise ask the user which directory on this ' ++ 'host holds the brain, then run `gbrain sources set-path default <absolute-directory>`.',+ };+ }+ if (repoPath && !isHostAbsolutePath(repoPath)) {return {status: 'warn',message:diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex e5e61a8b93..7947c3ff1d 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -351,7 +351,7 @@ export const CODES = {file_drift_mixed_selection: { class: 'caller', summary: "gbrain repair file-drift --held selected held pages of more than one Decision (side, or deleted state), so nothing was previewed: one --prefer must not resolve differently shaped drift in bulk.", why: "Each side and deleted state is its own Decision with its own meaning of --prefer file and --prefer database; resolving them together would apply one choice to questions the user answered differently, or not at all.", docs: 'docs/guides/repair.md#file-drift', suggestion: 'Preview one Decision at a time with the narrower commands the message names (--held --side <side>, plus --state <state> for --side deleted), or narrow with --only / --skip.', fix: { argv: ['gbrain', 'sources', 'status', '{source_id}', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists the held files of the source with their side and state.', requires_exclusive: false } },file_drift_state_required: { class: 'caller', summary: "gbrain repair file-drift --held for deleted-side drift needs --state (tombstone_edited, purged_differs or file_gone); nothing was previewed.", why: "In each deleted state --prefer file and --prefer database do opposite things (tombstone_edited: restore and import, or keep the deletion and remove the file; purged_differs: import as a new page, or remove the file; file_gone: soft-delete the page, or recreate the file), so the state is always named explicitly.", docs: 'docs/guides/repair.md#file-drift', suggestion: 'Rerun the preview with --side deleted --state <state>, choosing the state gbrain sources status <source> --json lists for the held files.', fix: { argv: ['gbrain', 'sources', 'status', '{source_id}', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists the held files of the source with their side and state.', requires_exclusive: false } },file_removed_during_scan: { class: 'retryable', summary: "A file lint listed was removed before lint read it, so it was not linted.", why: "Another process deleted or renamed the file during the run; lint reports it and continues with the remaining files.", docs: 'docs/guides/repair.md#file-removed-during-scan', suggestion: "Re-run gbrain lint on the same target; it lints the files present now." },- file_unreadable: { class: 'caller', retryable: false, reasons: ['symlink_in_repo', 'symlink_outside_root', 'symlink_dangling', 'symlink_loop', 'permission_denied', 'not_regular_file'], summary: "Sync held one file because it is not a readable regular file inside the source root (a symlink, a non-regular file or a permission error); the rest of the source synced.", why: "Sync reads only regular files inside the source root and never follows a symlink, which can point anywhere on the host. The file waits in the hold store instead of failing the run, so it never blocks the source, and classic sync re-screens it on every run.", docs: 'docs/guides/write-refusals.md#file_unreadable', suggestion: 'Replace the symlink with the regular file (or delete it), make the file readable to the account gbrain runs as, or leave it out with sync.exclude; the next gbrain sync --source <source> --no-pull re-screens it.' },+ file_unreadable: { class: 'caller', retryable: false, reasons: ['symlink_in_repo', 'symlink_outside_root', 'symlink_dangling', 'symlink_loop', 'permission_denied', 'not_regular_file'], summary: "Sync held one file because it is not a readable regular file inside the source root (a symlink, a non-regular file or a permission error); the rest of the source synced.", why: "Sync reads only regular files inside the source root and never follows a symlink, which can point anywhere on the host. The file waits in the hold store instead of failing the run, so it never blocks the source, and classic sync re-screens it on every run.", docs: 'docs/guides/write-refusals.md#file_unreadable', suggestion: 'Replace the symlink with the regular file (or delete it), make the file readable to the account that runs gbrain, or leave it out with sync.exclude; the next gbrain sync --source <source> --no-pull re-screens it.' },file_wins_rewrite: { class: 'caller', retryable: false, actor: 'user', summary: "gbrain repair file-drift --prefer file refused a page because keeping its file would need a full re-render of the file, not only appended protected parts; nothing was written.", why: "File wins keeps the canonical file's bytes and adds only what reconcile's protections keep from the database: protected frontmatter keys the file lacks and database-only timeline rows, appended. A result that also changes a value, a tag, the title or the body would re-render the whole file (keys reordered, lists re-emitted, rules and headings rewritten), which is not the file winning.", docs: 'docs/guides/write-refusals.md#file_wins_rewrite', suggestion: 'Show the user the page\'s exceptions in the preview. Commit the database-only differences into the file through the door (`gbrain git commit-push`) and preview again, or preview `--prefer database` if the database copy should win.' },file_too_large: { class: 'caller', summary: "The file is over the page size limit (24 MiB for a Markdown page, 5 MB for a code file), so it was not imported.", why: "Every page under the limit is stored, chunked and searchable whatever its size; the limit bounds what one page may hold in this release. The same bytes refuse on every retry. A smaller page refused by an MCP or HTTP transport is a different refusal.", docs: 'docs/guides/write-refusals.md#file_too_large', suggestion: 'Leave the file out of the source (sync.exclude), or, if it must be in the brain, split it into files under the limit; then sync or import again. Never split a page under the limit.' },follow_approval_required: { class: 'caller', summary: "Following a brain's shared skills needs the user's explicit follow approval.", docs: 'docs/guides/shared-brain-skills.md#approve-publication-following-and-editing-separately' },@@ -384,7 +384,7 @@ export const CODES = {git_target_pending: { class: 'retryable', summary: "Git still lists a removed canonical file in the index; the removal was not committed yet." },git_operation_in_progress: { class: 'caller', summary: "A rebase, merge, cherry-pick or revert is in progress in the checkout, so gbrain will not commit or move it.", docs: 'docs/guides/shared-checkout-git.md#stuck-rebase' },git_push_unavailable: { class: 'retryable', summary: "The canonical commit is durable locally; its push will retry." },- git_target_changed: { class: 'caller', actor: 'user', summary: "A strict (canonical: git) write's file changed on disk while it was being committed, so nothing was committed and the write was not published.", why: "The door commits exactly the bytes the write published, and checks the file's hash against them before and after Git stores it. An edit landing in between would otherwise be committed while the database records other content; recovery leaves the changed file as it is.", suggestion: "When the file holds neither the write's bytes nor the version before it, the write is held in recovery (blocked reason unexpected_file_bytes) and the source's later writes wait behind it; when it holds the version before the write, nothing is held and the write failed, so read the page before resubmitting it with a new request_id. To resolve a held write, preview with gbrain repair stuck-recovery --source <id> --json, ask the user which version to keep, then run gbrain repair stuck-recovery --source <id> --keep disk|prior --apply --expect <preview_hash> --yes (disk keeps the edit).", fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists the held request, its source and its blocked reason.', requires_exclusive: false } },+ git_target_changed: { class: 'caller', actor: 'user', summary: "A strict (canonical: git) write's file changed on disk while it was being committed, so nothing was committed and the write was not published.", why: "The door commits exactly the bytes the write published, and checks the file's hash against them before and after Git stores it. An edit landing in between would otherwise be committed while the database records other content; recovery leaves the changed file as it is.", suggestion: "When the file holds neither the write's bytes nor the version before it, the write is held in recovery (blocked reason unexpected_file_bytes) and the source's later writes wait behind it; when it holds the version before the write, nothing is held and the write failed; when it holds the write's own bytes again by the time recovery runs, recovery restores the version before the write and the write failed, with nothing held. After a failure, read the page before resubmitting it with a new request_id. To resolve a held write, preview with gbrain repair stuck-recovery --source <id> --json, ask the user which version to keep, then run gbrain repair stuck-recovery --source <id> --keep disk|prior --apply --expect <preview_hash> --yes (disk keeps the edit).", fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists the held request, its source and its blocked reason.', requires_exclusive: false } },git_target_ignored: { class: 'caller', summary: "A .gitignore rule excludes the canonical file, so its Git effect cannot commit it; the effect parks at once.", suggestion: 'Remove or narrow the rule and commit that change, then run gbrain sources writer retry-effects <source> --parked-code git_target_ignored; or keep the file out of Git and leave the effect parked.' },git_target_unsafe: { class: 'caller', summary: "Git cannot identify the existing canonical file by its native spelling." },git_unavailable: { class: 'retryable', summary: "A git command did not complete." },@@ -392,7 +392,7 @@ export const CODES = {git_conversion_blocked: { class: 'consent', actor: 'user', summary: "Converting a source to git-canonical would discard database content or cannot place it, so the apply wrote nothing.", reasons: ['both_moved', 'held_drift_both', 'held_drift_unknown_differs', 'deleted_in_git', 'uncommitted_edit', 'ignored_target', 'unparseable', 'unsafe_path', 'segmented_page', 'export_mismatch', 'git_overwrites_database', 'ignore_status_unknown', 'no_record_both_moved', 'no_record_no_evidence'], why: "gbrain sources canonical --to git applies only when every database row will be in Git or in a declared database-only class afterwards. The preview counts what would be lost or cannot be placed by category (detail lists them): both_moved and held_drift_both, a page Git and the database both changed; no_record_both_moved and no_record_no_evidence, a page with no import record whose content history shows both sides moved, or shows nothing, until the owner's --decisions file decides it; deleted_in_git, a page Git deleted that the database edited since; uncommitted_edit, a working-tree edit the adoption would overwrite; ignored_target, a page whose file Git ignores without a declared class; unparseable and unsafe_path, a committed file or path sync cannot read; segmented_page, a segmented page conversion does not adopt yet; export_mismatch, a page whose export does not read back equal; git_overwrites_database, a page version a strict pass would replace that nothing accepted; ignore_status_unknown, a target whose ignore status Git cannot read (beyond a symlink, outside the checkout, a timed-out check). There is no override.", docs: 'docs/designs/GIT_CANONICAL_MEMORY.md#conversion', suggestion: 'Relay the categories and their paths (the --dry-run preview lists them) and ask the user how each should be resolved; preview again afterwards.' },git_conversion_delta: { class: 'consent', actor: 'user', summary: "An approved conversion found pages that changed since the approval, or decisions it did not approve, so only the unchanged pages were applied and the source stays mixed.", why: "gbrain sources canonical --to git --apply --approved applies only the pages whose slug, revision, committed blob, evidence and action are the ones the owner approved. A page that changed since, a new page, a database edit the plan would now discard, and any decision the approval did not hold stay unapplied and are listed (delta) with counts; nothing outside the approved set is applied without a new decision.", docs: 'docs/guides/git-canonical.md#approval-across-time', suggestion: 'Relay the delta list and its counts to the owner; once they decide, preview again with --approval-out and apply the new approval.' },conversion_file_in_source_root: { class: 'caller', summary: "A conversion review list, decisions file or approval was refused because its path is inside a source's checkout.", why: "Those files name pages and paths. Written or read only outside every registered source root and the Git working tree holding it (mode 0600), they can never be synced, imported or committed.", docs: 'docs/guides/git-canonical.md#review-list-and-decisions', suggestion: 'Pass a path outside every source checkout, e.g. under ~/.gbrain.' },- git_conversion_incomplete: { class: 'retryable', summary: "A git-canonical conversion stopped because its strict pass did not finish, or finished with work left after the flag was set.", why: "The conversion runs a full strict-equivalent pass before it sets canonical: git, and one genuine strict pass after, then up to three closing strict passes while only door commits a live writer landed meanwhile are left (Git ahead of the database). A pass that ends partial, blocked or deferred stops the conversion where it is: before the flag the source stays as it was, after it the source stays strict (Git wins) and the plan lists what is left.", docs: 'docs/designs/GIT_CANONICAL_MEMORY.md#conversion', suggestion: 'Wait until gbrain sync status --source <id> --json shows the source idle, then preview again with gbrain sources canonical <id> --to git --dry-run and apply the new hash.' },+ git_conversion_incomplete: { class: 'retryable', summary: "A git-canonical conversion stopped because its strict pass did not finish, finished with work left after the flag was set, or found the flag removed (a --to mixed apply) while it ran.", why: "The conversion runs a full strict-equivalent pass before it sets canonical: git, and one genuine strict pass after, then up to three closing strict passes while only door commits a live writer landed meanwhile are left (Git ahead of the database). A pass that ends partial, blocked or deferred stops the conversion where it is: before the flag the source stays as it was, after it the source stays strict (Git wins) and the plan lists what is left.", docs: 'docs/designs/GIT_CANONICAL_MEMORY.md#conversion', suggestion: 'Wait until gbrain sync status --source <id> --json shows the source idle, then preview again with gbrain sources canonical <id> --to git --dry-run and apply the new hash.' },git_home_required: { class: 'caller', summary: "A git-canonical source would store content in the database without a file in Git; nothing was written.", reasons: ['no_file_form', 'declared_target', 'facts_lane'], why: "On a source with canonical: git, page content reaches the database only after Git commits its file. The declared database-only classes (private, alias-private and lineage-private pages, storage.db_only directories, never-filed derive-phase pages, paths Git ignores, detached pages and origin twins) are the only exceptions. no_file_form: the write has no file and is in no declared class; declared_target: a publication would commit a file for a declared page; facts_lane: a writer with no file form yet.", docs: 'docs/guides/write-refusals.md#git_home_required', suggestion: 'Ask the user which git home to configure (a path Git tracks, or a storage.db_only directory in gbrain.yml), then submit the write again with a new request_id.' },git_private_commit_refused: { class: 'caller', summary: "A git-canonical source refused to commit the file of a private, alias-private or lineage-private page; nothing was written and HEAD is unchanged.", reasons: ['private', 'alias_private', 'lineage_private'], why: "Private pages of a source with canonical: git are database-only: their bytes never enter Git history. A page turning private is published as the door commit that removes its file, never as a commit of its bytes.", docs: 'docs/guides/write-refusals.md#git_private_commit_refused', suggestion: 'The page stays database-only. Write it through put_page (which publishes a private page without a file), or remove visibility: private if it belongs in Git, then submit again with a new request_id.' },git_protocol_required: { class: 'host_only', summary: "A write reached a git-canonical source from a process that does not declare the git-canonical protocol (an older gbrain, or gbrain.write_sources set by hand); nothing was written.", docs: 'docs/guides/write-refusals.md#git_protocol_required', suggestion: 'Upgrade or stop the gbrain process that wrote it (gbrain upgrade on its host), then retry with a new request_id.' },@@ -797,6 +797,7 @@ export const CODES = {source_referenced: { class: 'caller', summary: "OAuth clients still reference this source." },source_retire_superseded: { class: 'caller', summary: "A retried source remove or purge was superseded: its source has since been removed, replaced or changed by another lifecycle operation; nothing was changed.", why: "A remove or purge records the source incarnation it was admitted against before it deletes its first page, so a retry of its request id can never delete the pages of a source re-added under the same ID, and a later lifecycle change to the source (such as a restore) abandons the request. A request refused this way stays refused.", suggestion: "Do not retry this request id. Read the source's current state; removing the current source is a new decision for the user, made with a new request id.", fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Read-only: shows the source's current incarnation, binding, pending work and its stopped or superseded remove and purge requests (topology_requests).", requires_exclusive: false } },source_root_conflict: { class: 'caller', summary: "Multiple active sources alias this canonical skill root; resolve ownership before publishing." },+ source_root_unreadable: { class: 'host_only', retryable: false, reasons: ['missing', 'not_directory', 'permission_denied', 'symlink_loop', 'unreadable'], summary: "The source's registered root on its owner host cannot be read as a directory (gone, unmounted, not a directory, no permission or a symlink loop), so `gbrain sources canonical` planned and wrote nothing.", why: "Converting a source reads its whole checkout; a root that cannot be listed would otherwise surface as a raw filesystem or Git error, or as a missing-checkout refusal whose fix creates an empty repository there.", suggestion: 'Restore or remount the directory on the brain host (or make it readable to the account that runs gbrain), compare it with the root gbrain sources writer status --source <source> --json names, then preview again.' },source_writeback_required: { class: 'host_only', summary: "Canonical preparation requires a source-content correction; this profile never writes repository files." },sources_not_readable: { class: 'host_only', retryable: false, summary: "An unscoped search, query, recall or list_pages came back empty and was refused: every source this connection can read (the default source and federated sources) holds no page (for recall and query, no world fact either), while other sources on the brain hold pages it cannot read (not federated, and no source grant).", why: "Answering would return an empty result that reads like a clean miss. The refusal names the host command that federates a source or grants this connection the sources it should read; it never names a hidden source and never widens access. A scope that holds pages but matched nothing, a granted token, an OAuth client, a bound connection and a read that names a source are never refused.", docs: 'docs/guides/multi-source-brains.md#an-unscoped-connection-whose-sources-hold-no-pages', suggestion: 'Ask the user which source these connections should read; the brain host runs `gbrain sources federate <source>`, or grants the token its sources with `gbrain auth rescope --token <name> --sources <ids>`.' },split_bad_ratio: { class: 'caller', summary: "Split bad ratio." },diff --git a/src/core/minions/handlers/sync.ts b/src/core/minions/handlers/sync.tsindex d068925e92..184c002f1f 100644--- a/src/core/minions/handlers/sync.ts+++ b/src/core/minions/handlers/sync.ts@@ -152,6 +152,14 @@ export function makeSyncHandler(engine: BrainEngine): MinionHandler {console.error(`[sync] skipped: sync does not apply to ${sourceId ?? 'default'} (gbrain-owned content directory, not a Git checkout).`);return { skipped: true, reason: 'sync_not_applicable', source_id: sourceId ?? 'default' };}+ // #7646: a relative stored anchor refuses the same way on every retry, so the job completes as a skip carrying the+ // ask-the-user fix instead of using up its attempts. The result is readable remotely (get_job): no stored path in it.+ if ((err as { code?: unknown } | null)?.code === 'sync_anchor_relative') {+ const refusal = err as { suggestion?: string; fix?: { argv?: string[]; actor?: string; ask_user?: boolean; inputs?: unknown } };+ console.error(`[sync] skipped: ${refusal.suggestion ?? 'the stored sync path is not absolute on this host'}`);+ return { skipped: true, reason: 'sync_anchor_relative', source_id: sourceId ?? 'default', suggestion: refusal.suggestion,+ fix: { argv: refusal.fix?.argv, actor: refusal.fix?.actor, ask_user: refusal.fix?.ask_user, inputs: refusal.fix?.inputs } };+ }throw err;}diff --git a/src/core/path-confine.ts b/src/core/path-confine.tsindex 904a5b5f6c..d9b63ddb51 100644--- a/src/core/path-confine.ts+++ b/src/core/path-confine.ts@@ -21,7 +21,7 @@import { realpathSync, existsSync, type Stats } from 'fs';import { realpath as realpathAsync } from 'fs/promises';-import { resolve as resolvePath, relative, isAbsolute, dirname, basename, join, sep } from 'path';+import { resolve as resolvePath, relative, isAbsolute, dirname, basename, join, sep, posix } from 'path';/*** Symlink-safe path confinement: realpath BOTH sides, then a separator-aware@@ -140,6 +140,27 @@ export function msysToNativePath(return `${drive}:${rest || '\\'}`;}+/** The platform the loaded `path` module resolves for: the stored-root verdict follows the module that resolves the root. */+const PATH_PLATFORM: NodeJS.Platform = sep === '\\' ? 'win32' : 'linux';++/**+ * #7646: is a stored root (`sources.local_path`, `sync.repo_path`) absolute on THIS host? The one predicate sync,+ * `config set`, write-through, `sources set-path --clear` and doctor share. On win32 only a drive path (`C:\\x`, or a+ * Git Bash `/c/x`, healed by `msysToNativePath`) or a UNC share counts: `path.win32.isAbsolute` also accepts the+ * root-relative `\\brain` and `/brain`, which resolve against whatever drive gbrain runs from. On POSIX it is+ * `path.posix.isAbsolute`, so a Windows drive path another host stored is not absolute here.+ */+export function isHostAbsolutePath(p: string, platform: NodeJS.Platform = PATH_PLATFORM): boolean {+ if (platform !== 'win32') return posix.isAbsolute(p);+ return /^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/])/.test(msysToNativePath(p, platform));+}++/** #7646: a stored root absolute only on another operating system (a Windows drive or UNC path on POSIX, a POSIX path on win32). */+export function isForeignAbsolutePath(p: string, platform: NodeJS.Platform = PATH_PLATFORM): boolean {+ if (isHostAbsolutePath(p, platform)) return false;+ return platform === 'win32' ? posix.isAbsolute(p) && !/^[\\/]{2}/.test(p) : isHostAbsolutePath(p, 'win32');+}+/*** Async twin of `realpathOrResolve` — same fallback contract, but backed by* `fs.promises.realpath` instead of `realpathSync`. Exists so a callerdiff --git a/src/core/persistence/connector-path.ts b/src/core/persistence/connector-path.tsindex 5ce9746619..5407e09bd5 100644--- a/src/core/persistence/connector-path.ts+++ b/src/core/persistence/connector-path.ts@@ -1,4 +1,4 @@-import { posix, win32 } from 'node:path';+import { isHostAbsolutePath, isForeignAbsolutePath } from '../path-confine.ts';import type { BrainEngine } from '../engine.ts';import { OperationError } from '../ops/contract.ts';import { isConnectorSourceKind } from './connector-identity.ts';@@ -24,7 +24,7 @@ export async function clearConnectorLocalPath(engine: BrainEngine, sourceId: str"SELECT local_path, config->>'kind' AS kind, incarnation FROM sources WHERE id=$1 FOR UPDATE", [sourceId]);if (!source) throw new OperationError('not_found', `Source "${sourceId}" not found.`, "Run 'gbrain sources list' to see registered sources.");const connector = isConnectorSourceKind(source.kind);- if (!connector && source.local_path !== null && (posix.isAbsolute(source.local_path) || win32.isAbsolute(source.local_path))) {+ if (!connector && source.local_path !== null && (isHostAbsolutePath(source.local_path) || isForeignAbsolutePath(source.local_path))) {throw new OperationError('invalid_params', `--clear applies only to connector sources (google, github) and to a relative local_path; "${sourceId}" is a filesystem source whose path is its canonical checkout.`,`Point it at its checkout with gbrain sources set-path ${sourceId} <path>, or remove it with gbrain sources remove ${sourceId}.`);}diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex b41040f1ed..bb96d512f7 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -431,7 +431,7 @@ export function decoratePublicationOutcome(row: WriteRequest, prepared: Preparedoutcome.write_through = fileCount ? { written: !prepared.noop, ...(row.authority.heldFor ? { held_for: row.authority.heldFor } : {}) }: { written: false, skipped: prepared.databaseOnlyReason ?? row.authority.databaseOnlyReason ?? 'no_repo_configured' };if (prepared.databaseOnlyReason === 'mirror_read_only') outcome.storage = 'database_only';- if ((row.operation === 'put_page' || row.operation === 'edit_page' || row.operation === 'append_page') && row.authority.remote && row.authority.databaseOnlyReason === 'no_repo_configured') outcome.write_through = withNoRepoWriteThroughWarning(outcome.write_through as { written: boolean; skipped?: string }, row.source_id, row.operation);+ if ((row.operation === 'put_page' || row.operation === 'edit_page' || row.operation === 'append_page') && row.authority.remote && (row.authority.databaseOnlyReason === 'no_repo_configured' || row.authority.databaseOnlyReason === 'relative_root')) outcome.write_through = withNoRepoWriteThroughWarning(outcome.write_through as { written: boolean; skipped?: string }, row.source_id, row.operation);if ((outcome.write_through as { skipped?: string }).skipped === 'unbound_source') {outcome.write_through = { ...outcome.write_through as object, warning: unboundWriteWarning(row.operation, row.source_id, row.authority.databaseOnlyReason === 'unbound_source') };}diff --git a/src/core/persistence/fact-write-target.ts b/src/core/persistence/fact-write-target.tsindex 5edf236ea7..eb6b1ff6fe 100644--- a/src/core/persistence/fact-write-target.ts+++ b/src/core/persistence/fact-write-target.ts@@ -1,4 +1,4 @@-import { isAbsolute } from 'node:path';+import { isHostAbsolutePath } from '../path-confine.ts';import type { BrainEngine } from '../engine.ts';import { getWorktreeBinding, type WorktreeBinding } from './ownership.ts';import { decideUnboundWrite } from './unbound-source.ts';@@ -12,7 +12,8 @@ import type { WriteAuthority } from './model.ts';* automatically while maintenance writers (relink) refuse rather than claim;* an unbound Postgres source writes a page without a canonical file* database-only under `persistence.unbound_write=database_only` and refuses- * otherwise. `fileBacked` is whether the target page records a canonical file;+ * otherwise. A stored root that is not absolute on this host (#7646) publishes+ * database-only with `relative_root`. `fileBacked` is whether the target page records a canonical file;* the refusal names the checkout only to trusted local (`remote: false`) callers.*/export type FactWriteTarget =@@ -28,7 +29,8 @@ export async function resolveFactWriteTarget(engine: BrainEngine, sourceId: striif (!writeThrough) return { kind: 'publish', binding: null, databaseOnlyReason: reason };const binding = await getWorktreeBinding(engine, sourceId);const root = source.local_path || (sourceId === 'default' ? await engine.getConfig('sync.repo_path') : null);- if (!root || !isAbsolute(root) || binding) return { kind: 'publish', binding };+ if (!root || binding) return { kind: 'publish', binding };+ if (!isHostAbsolutePath(root)) return { kind: 'publish', binding: null, databaseOnlyReason: 'relative_root' };const decision = await decideUnboundWrite(engine, { sourceId, sourceKind: source.kind, fileBacked: opts.fileBacked, path: opts.remote ? null : root });return decision.kind === 'claim' ? { kind: 'unbound', root } : { kind: 'publish', binding: null, databaseOnlyReason: decision.reason };}diff --git a/src/core/persistence/git-conversion.ts b/src/core/persistence/git-conversion.tsindex 76e8cd1626..2814cb9393 100644--- a/src/core/persistence/git-conversion.ts+++ b/src/core/persistence/git-conversion.ts@@ -39,7 +39,7 @@* only a plan with no work left is a completed conversion; otherwise the source stays strict (Git wins) and the* remaining categories are reported. `--to mixed` removes the flag and changes nothing else.*/-import { chmodSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';+import { accessSync, chmodSync, constants, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';import type { BrainEngine } from '../engine.ts';import type { SyncOpts, SyncResult } from '../../commands/sync.ts';@@ -59,10 +59,11 @@ import { commitThroughDoor } from './git-door.ts';import { gitRootAhead, pushGitRoot } from './effect-git.ts';import { DURABILITY_NOT_ENABLED_REASON, gitDurabilityPolicy } from './git-durability-policy.ts';import { currentVerifiedLocalWriter, hostIdFor } from './identity.ts';-import { acquireWorktree, getWorktreeBinding, readManagedMode } from './ownership.ts';+import { acquireWorktree, readManagedMode } from './ownership.ts';import { inspectDurabilityCheckout } from './git-durability-administration.ts';import { classifyGitCheckout } from '../git-checkout.ts';-import { resolveManagedSyncContext, type ManagedSyncContext } from './sync-discovery.ts';+import { readManagedSyncRows, resolveManagedSyncContext, type ManagedSyncContext } from './sync-discovery.ts';+import { syncOwnerBinding } from './owner-refusal.ts';import { readShadowLevel, type ConversionBinding } from './sync-pass.ts';import { isPrivacyClass, type PrivacyClass } from './git-declared.ts';import { classifySyncPath } from './sync-classify.ts';@@ -311,12 +312,34 @@ export async function assertConversionCaller(engine: BrainEngine, sourceId: striuser_message: `Source ${sourceId} can only become git-canonical on a brain with managed writes, and this brain is not managed. Should it move to managed writes first?` } });}+type UnreadableRootReason = 'missing' | 'not_directory' | 'permission_denied' | 'symlink_loop' | 'unreadable';+const ROOT_ERRNO: Record<string, UnreadableRootReason> = { ENOENT: 'missing', ENOTDIR: 'not_directory', EACCES: 'permission_denied', EPERM: 'permission_denied', ELOOP: 'symlink_loop' };+const ROOT_STATE: Record<UnreadableRootReason, string> = { missing: 'does not exist (it was moved, deleted or unmounted)', not_directory: 'is not a directory',+ permission_denied: 'cannot be read by the account that runs gbrain', symlink_loop: 'is a symlink loop', unreadable: 'cannot be read' };++/** #7956: why the registered root cannot be listed as a directory, or null when it can. */+function unreadableRoot(root: string): UnreadableRootReason | null {+ try {+ if (!statSync(root).isDirectory()) return 'not_directory';+ accessSync(root, constants.R_OK | constants.X_OK);+ return null;+ } catch (error) { return ROOT_ERRNO[(error as NodeJS.ErrnoException).code ?? ''] ?? 'unreadable'; }+}+/*** #7885: a root with no Git checkout, or one whose branch has no commit yet, has nothing to convert into. The plan refuses- * before it reads anything, and the source keeps working as it is (the database is its record). A root it cannot read- * (gone, unmounted, not a directory) is left to the context resolution, which owns those refusals.+ * before it reads anything, and the source keeps working as it is (the database is its record). #7956: a root it cannot+ * read (gone, unmounted, not a directory, no permission, a symlink loop) refuses source_root_unreadable, never a raw+ * filesystem or Git error and never a checkout refusal whose fix would create a repository there.*/async function assertConversionCheckout(sourceId: string, root: string): Promise<void> {+ const unreadable = unreadableRoot(root);+ if (unreadable) {+ throw opError('source_root_unreadable', `Source ${sourceId}'s registered root ${root} ${ROOT_STATE[unreadable]}, so nothing was read or written.`,+ `Restore or remount the directory on the brain host (or make it readable to the account that runs gbrain), compare it with the root gbrain sources writer status --source ${sourceId} --json names, then preview again.`,+ { reason: unreadable, docs: DOCS, retryable: false, fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'], consent: [], actor: 'agent', requires_exclusive: false,+ why: 'Shows the root the owner registered, to compare with the directory on disk; read-only.', verify: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] } } });+ }if (classifyGitCheckout(root) === 'unknown') return;let code: 'git_checkout_required' | 'git_branch_unborn';try { await inspectDurabilityCheckout(root); return; }@@ -346,8 +369,9 @@ const strictContext = (context: ManagedSyncContext): ManagedSyncContext => ({ ..* committed blob and evidence kind, and its digest is bound into the preview hash.*/export async function planGitConversion(engine: BrainEngine, sourceId: string, opts: { decisions?: ConversionDecision[] } = {}): Promise<GitConversionPlan> {- const binding = await getWorktreeBinding(engine, sourceId);- if (binding?.local_path && binding.owner_host_id === hostIdFor(engine) && binding.state === 'active') await assertConversionCheckout(sourceId, resolve(binding.local_path, binding.relative_path));+ const [source, binding] = await readManagedSyncRows(engine, sourceId);+ const owned = syncOwnerBinding(source, binding, hostIdFor(engine));+ if (owned) await assertConversionCheckout(sourceId, resolve(owned.local_path, owned.relative_path));const context = await resolveManagedSyncContext(engine, { sourceId, noPull: true, dryRun: true });const pages: GitGapPage[] = [];const equal = new Map<string, PageRevision>();@@ -865,7 +889,7 @@ async function runConversion(engine: BrainEngine, plan: GitConversionPlan, expecpassOrThrow(sourceId, 'strict_pass_closing', await pass('strict_pass_closing', after.git_wins.count), progress);after = (await planGitConversion(engine, sourceId)).preview;}- return { status: after.remaining === 0 && !binding.reclassified.size ? 'converted' : 'incomplete', source_id: sourceId, head: after.head, committed, withheld, holds_cleared: holdsCleared, parked, push,+ return { status: after.strict && after.remaining === 0 && !binding.reclassified.size ? 'converted' : 'incomplete', source_id: sourceId, head: after.head, committed, withheld, holds_cleared: holdsCleared, parked, push,closing_passes: closing, after, reclassified: [...binding.reclassified].sort() };} catch (error) { throw await withRecovery(engine, sourceId, error, recovery, progress); }}diff --git a/src/core/persistence/git-door.ts b/src/core/persistence/git-door.tsindex 0814675a23..e4d879c7b6 100644--- a/src/core/persistence/git-door.ts+++ b/src/core/persistence/git-door.ts@@ -39,8 +39,8 @@* once through publishGroup.*/import { createHash, randomBytes } from 'node:crypto';-import { closeSync, copyFileSync, existsSync, linkSync, lstatSync, mkdirSync, mkdtempSync, openSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';-import { join, relative, resolve, sep } from 'node:path';+import { closeSync, copyFileSync, existsSync, linkSync, lstatSync, mkdirSync, mkdtempSync, openSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { basename, dirname, join, relative, resolve, sep } from 'node:path';import type { Notice } from '../agent-output.ts';import { literalPathspecs } from '../git-env.ts';import { OperationError, opError } from '../ops/contract.ts';@@ -74,8 +74,16 @@ export function strictChanged(sourceId: string): OperationError {'Retry the write with a new request_id.');}-/** Test seam: runs after a door commit is written and before the compare-and-swap that moves the branch to it. */-export const doorSeams: { beforeUpdateRef?: (root: string, attempt: number) => Promise<void> | void } = {};+/**+ * Test seams: `beforeUpdateRef` runs after a door commit is written and before the compare-and-swap that moves the branch to it;+ * `indexLockHeld` runs while the index refresh holds `index.lock` open, after the index copy is updated and before it is renamed.+ */+export const doorSeams: { beforeUpdateRef?: (root: string, attempt: number) => Promise<void> | void; indexLockHeld?: (lock: string) => Promise<void> | void } = {};++/** Test seam: the descriptor close and renames that commit a refreshed index, and the platform that decides whether a rename is retried. */+export const indexCommitIo: { close: (fd: number) => void; rename: (from: string, to: string) => void; platform: NodeJS.Platform } = {+ close: closeSync, rename: renameSync, platform: process.platform,+};const doorTurns = new Map<string, Promise<void>>();/** Refusals that keep their own code: the checkout's state, not the commit, stopped the write. */@@ -267,11 +275,11 @@ async function doorCommit(session: GitSession, root: string, files: DoorFile[],target.head = before && before.mode !== TREE_MODE ? `${indexMode} ${before.oid.toString('hex')}` : undefined;if (target.oid) {if (!before || before.mode === TREE_MODE) fresh.push(target);- if (before && /^100[0-7]{3}$/.test(before.mode) && target.mode !== before.mode) {+ if (before && /^100[0-7]{3}$/.test(before.mode) && target.mode !== indexMode) {fileModeTrusted ??= (await git(session, ['config', '--type=bool', '--default=true', 'core.fileMode'])).stdout.trim() !== 'false';- if (!fileModeTrusted) target.mode = before.mode;+ if (!fileModeTrusted) target.mode = indexMode;}- if (before && before.mode === target.mode && before.oid.toString('hex') === target.oid) continue;+ if (before && indexMode === target.mode && before.oid.toString('hex') === target.oid) continue;dir.edits.set(target.name, { mode: target.mode!, oid: Buffer.from(target.oid, 'hex') });} else {if (!before || before.mode === TREE_MODE) continue;@@ -285,7 +293,7 @@ async function doorCommit(session: GitSession, root: string, files: DoorFile[],if (staged.length) {const replaced = await replacedEntries(session, head, staged);const foreign = staged.filter(target => indexed.entries.get(target.rel) !== replaced.get(target.rel));- if (foreign.length) throw indexConflict(root, foreign);+ if (foreign.length) throw indexConflict(root, foreign, !changed.length);}const restored = () => { if (staged.length) onIndexRestored?.(staged.map(target => target.rel)); };if (!changed.length) {@@ -367,18 +375,25 @@ function refuseChanged(root: string, targets: Iterable<Target>): void {const moved = [...targets].filter(target => { try { return hashFile(join(root, target.rel)) !== target.planned; } catch { return true; } }).map(target => target.rel);if (!moved.length) return;throw opError('git_target_changed', `${moved.join(', ')} in ${root} no longer holds the bytes this write published, so nothing was committed and the write was not published.`,- 'Another process changed the file during the write. If the file now holds neither this write\'s bytes nor the version before it, recovery leaves it as it is and holds the write, so the source\'s later writes wait: preview with gbrain repair stuck-recovery --json, ask the user which version to keep, then apply that choice with the --keep, --expect and --apply --yes flags the preview lists (--keep disk keeps the edit). If it holds the version before the write, nothing is held and the write failed; read the page before resubmitting it with a new request_id.', { detail: moved.join(',') });+ 'Another process changed the file during the write. If the file now holds neither this write\'s bytes nor the version before it, recovery leaves it as it is and holds the write, so the source\'s later writes wait: preview with gbrain repair stuck-recovery --json (--source with the write\'s source lists only its held writes), ask the user which version to keep, then apply that choice with the --keep, --expect and --apply --yes flags the preview lists (--keep disk keeps the edit). If it holds the version before the write, nothing is held and the write failed. If it holds this write\'s bytes again by the time recovery runs, recovery restores the version before it and the write failed, with nothing held. After a failure, read the page before resubmitting it with a new request_id.', { detail: moved.join(',') });}-/** Targets whose index entry differs from HEAD's and from the version their path's last commit replaced (a staged change, or a merge conflict) refuse as `git_index_conflict`. */-function indexConflict(root: string, staged: Target[]): OperationError {+/**+ * Targets whose index entry differs from HEAD's and from the version their path's last commit replaced (a staged change, or a merge conflict) refuse as+ * `git_index_conflict`. `atHead`: HEAD already holds every target in its planned state (a replay after its own commit landed), so the refusal says so.+ */+function indexConflict(root: string, staged: Target[], atHead: boolean): OperationError {const paths = staged.map(target => target.rel);- return opError('git_index_conflict', `${paths.join(', ')} in ${root} has a staged change that is not committed, so this write committed nothing and the index was left as it was.`,- 'Commit the staged change, or unstage it (git restore --staged -- <path> keeps the file on disk), then retry the write with a new request_id.', {+ return opError('git_index_conflict', atHead+ ? `${paths.join(', ')} in ${root} has a staged change that is not committed. HEAD already holds this write's bytes (committed earlier), so there was nothing to commit and the index was left as it was.`+ : `${paths.join(', ')} in ${root} has a staged change that is not committed, so this write committed nothing and the index was left as it was.`,+ atHead ? 'Git holds the write; the source\'s next sync imports it into the page. Commit the staged change, or unstage it (git restore --staged -- <path> keeps the file on disk).'+ : 'Commit the staged change, or unstage it (git restore --staged -- <path> keeps the file on disk), then retry the write with a new request_id.', {detail: paths.join(','),fix: { ask_user: true, argv: ['git', '-C', root, 'restore', '--staged', '--', ...literalPathspecs(paths)], consent: [], actor: 'user', requires_exclusive: false,why: 'The door commits a path only while its index entry equals HEAD\'s, so a staged change is never overwritten or committed under a gbrain commit. Unstaging keeps the file on disk; committing it publishes that change.',- user_message: `${paths.join(', ')} in ${root} has a staged change that is not committed, so gbrain did not commit its write there. Commit the staged change, or unstage it (its bytes stay on disk), then retry the write?`,+ user_message: atHead ? `${paths.join(', ')} in ${root} has a staged change that is not committed; gbrain's write is already in HEAD. Commit the staged change, or unstage it (its bytes stay on disk)?`+ : `${paths.join(', ')} in ${root} has a staged change that is not committed, so gbrain did not commit its write there. Commit the staged change, or unstage it (its bytes stay on disk), then retry the write?`,verify: { argv: ['git', '-C', root, 'diff', '--cached', '--name-only', '--', ...literalPathspecs(paths)] } },});}@@ -451,6 +466,7 @@ async function syncIndex(session: GitSession, root: string, prefix: string, indeheld = fd !== null;if (!held) failure = `Unable to create '${lock}': File exists; another git process holds the index lock${reclaimed === true ? '' : ` (not reclaimed: ${reclaimed})`}`;if (held) {+ sweepIndexCopies(index);const moved = indexSignature(index) !== seen.signature;// Git never rewrites an index in place (it writes <file>.lock and renames it), so a hard link is a safe copy.if (existsSync(index)) try { linkSync(index, copy); } catch { copyFileSync(index, copy); }@@ -464,13 +480,22 @@ async function syncIndex(session: GitSession, root: string, prefix: string, indeconst updated = await git({ ...session, indexFile: copy }, ['update-index', '--add', '--force-write-index', ...kept.flatMap(target => ['--cacheinfo', `${target.mode},${target.oid},${prefix}${target.rel}`]),...(removed.length ? ['--force-remove', '--', ...removed.map(target => target.rel)] : [])]);if (updated.code !== 0) failure = updated.stderr.trim().slice(0, 300) || `exit ${updated.code}`;- else { closeSync(fd!); fd = null; renameSync(copy, lock); renameSync(lock, index); held = false; }+ else {+ await doorSeams.indexLockHeld?.(lock);+ const open = fd!;+ fd = null;+ indexCommitIo.close(open);+ await renameIndex(copy, lock);+ await renameIndex(lock, index);+ held = false;+ }}}} catch (error) { failure = error instanceof Error ? error.message : String(error); }finally {- if (fd !== null) closeSync(fd);+ if (fd !== null) try { closeSync(fd); } catch { /* the descriptor is released whether or not close reports an error */ }rmSync(copy, { force: true });+ rmSync(`${copy}.lock`, { force: true });if (held) rmSync(lock, { force: true });}if (!failure && !restaged.length) return;@@ -483,6 +508,40 @@ async function syncIndex(session: GitSession, root: string, prefix: string, indethrow error;}+const RENAME_RETRY_MS = [1, 10, 20, 40, 100];+const SHARING_VIOLATIONS = new Set(['EPERM', 'EBUSY', 'EACCES']);++/**+ * Renames a refreshed index into place. On win32 a sharing violation (an indexer, antivirus or a reader holding the file for a moment) is+ * retried with a short backoff, as Git for Windows retries its own index rename (#7756); elsewhere the first failure stands.+ */+async function renameIndex(from: string, to: string): Promise<void> {+ for (let attempt = 0; ; attempt++) {+ try { indexCommitIo.rename(from, to); return; } catch (error) {+ if (indexCommitIo.platform !== 'win32' || attempt >= RENAME_RETRY_MS.length || !SHARING_VIOLATIONS.has((error as NodeJS.ErrnoException).code ?? '')) throw error;+ }+ await new Promise(done => setTimeout(done, RENAME_RETRY_MS[attempt]));+ }+}++const processGone = (pid: number) => {+ try { process.kill(pid, 0); return false; } catch (error) { return (error as NodeJS.ErrnoException).code === 'ESRCH'; }+};++/**+ * Removes the index copies (`<index>.gbrain-<pid>-<random>`, and the Git lock of one) a refresh left when its process was killed before its+ * cleanup (#7755), once that process is gone. Runs while the caller holds `index.lock`, which every refresh holds while its copy exists.+ */+function sweepIndexCopies(index: string): void {+ const dir = dirname(index), stem = `${basename(index)}.gbrain-`;+ let names: string[];+ try { names = readdirSync(dir); } catch { return; }+ for (const name of names) {+ const pid = name.startsWith(stem) ? /^(\d+)-[0-9a-f]{12}(?:\.lock)?$/.exec(name.slice(stem.length))?.[1] : undefined;+ if (pid && processGone(Number(pid))) try { rmSync(join(dir, name), { force: true }); } catch { /* best effort: a leftover never fails the refresh */ }+ }+}+/** Whether the working tree and HEAD both hold the record's published state at its path (its bytes, or no entry for a removal). */export async function holdsCommittedAfter(record: FileRecoveryRecord & { door: NonNullable<FileRecoveryRecord['door']> }): Promise<boolean> {if (record.afterHash === null) return hashFile(record.path) === null && await headBlob(record.door.root, record.path) === null;diff --git a/src/core/persistence/model.ts b/src/core/persistence/model.tsindex 00bfbf2697..e6d5f521eb 100644--- a/src/core/persistence/model.ts+++ b/src/core/persistence/model.ts@@ -38,7 +38,7 @@ export interface WriteAuthority {* holding page, which is gbrain's own companion to it.*/heldFor?: string;- databaseOnlyReason?: 'subagent_sandbox' | 'disabled_by_config' | 'no_repo_configured' | 'connector_database' | 'unbound_source' | 'overwrite_restore' | 'detached' | 'entity_page_missing';+ databaseOnlyReason?: 'subagent_sandbox' | 'disabled_by_config' | 'no_repo_configured' | 'relative_root' | 'connector_database' | 'unbound_source' | 'overwrite_restore' | 'detached' | 'entity_page_missing';autoLinkTrusted?: boolean;restrictedNamespace?: boolean;sourceId: string;diff --git a/src/core/persistence/owner-refusal.ts b/src/core/persistence/owner-refusal.tsindex 3c4c727ad4..d142f7ae21 100644--- a/src/core/persistence/owner-refusal.ts+++ b/src/core/persistence/owner-refusal.ts@@ -69,6 +69,19 @@ export function checkOwner(binding: WorktreeBinding | null, incarnation: string,return { reason: null, binding: binding as ActiveOwnerBinding };}+/**+ * #7956: the binding a managed sync of the source runs on from host `hostId`, or null: the source exists and is not+ * archived, and its binding belongs to that incarnation, is owned by the host, is active and has a local path.+ * `resolveManagedSyncContext` (sync-discovery.ts) refuses `owner_unavailable` past the same conditions; the conversion+ * checks its root only on a binding this returns.+ */+export function syncOwnerBinding(source: { archived: boolean; incarnation: string } | undefined, binding: WorktreeBinding | null,+ hostId: string): (WorktreeBinding & { local_path: string }) | null {+ if (!source || source.archived || !binding || binding.source_incarnation !== source.incarnation || binding.owner_host_id !== hostId+ || binding.state !== 'active' || !binding.local_path) return null;+ return binding as WorktreeBinding & { local_path: string };+}+/** The reason alone; null when the binding is usable. */export function ownerUnavailableReason(binding: WorktreeBinding | null, incarnation: string, hostId: string): OwnerUnavailableReason | null {return checkOwner(binding, incarnation, hostId).reason;diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex 1ec79103d5..cd862486e0 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -5,6 +5,7 @@ import { fenceNormalizedNotice, type FencesNormalized } from '../fence-repair/reimport { parseFenceRepairReceipt } from '../fence-repair/receipt.ts';import { realpathSync } from 'node:fs';import { isAbsolute, join, relative, resolve, sep } from 'node:path';+import { isHostAbsolutePath } from '../path-confine.ts';import type { OperationContext } from '../ops/contract.ts';import { OperationError } from '../ops/contract.ts';import { admitChangeReason, CHANGE_REASON_OPERATIONS } from './change-reason.ts';@@ -171,7 +172,7 @@ async function resolveCaptureFile(ctx: OperationContext, sourceId: string, p: Reconst binding = await getWorktreeBinding(ctx.engine, sourceId);let root = binding ? binding.owner_host_id === hostIdFor(ctx.engine) && binding.local_path ? join(binding.local_path, binding.relative_path) : null: source?.local_path || (sourceId === 'default' ? await ctx.engine.getConfig('sync.repo_path') : null);- if (root && !isAbsolute(root)) root = null;+ if (root && !isHostAbsolutePath(root)) root = null;let origin: string | null = null;try { if (root) origin = relative(realpathSync(root), realpathSync(file)); } catch { /* unreadable or absent root */ }if (!root || !origin || isAbsolute(origin) || origin === '..' || origin.startsWith(`..${sep}`) || !/\.mdx?$/i.test(origin)) {@@ -511,7 +512,7 @@ export async function preparePageAdmission(ctx: OperationContext,const sandbox = ctx.viaSubagent === true && !(ctx.allowedSlugPrefixes?.length);const configuredWriteThrough = !/^(false|0|off|no)$/i.test(writeThroughSetting ?? 'true');const configuredRoot = source.local_path || repoPath;- const root = configuredRoot && isAbsolute(configuredRoot) ? configuredRoot : null;+ const root = configuredRoot && isHostAbsolutePath(configuredRoot) ? configuredRoot : null;// Checkout paths belong to a host binding; sources.local_path may name// another host's original checkout after a verified ownership transfer.const localRoot = binding ? binding.owner_host_id === hostIdFor(ctx.engine) && binding.local_path@@ -524,7 +525,7 @@ export async function preparePageAdmission(ctx: OperationContext,if (sandbox) authority.databaseOnlyReason = 'subagent_sandbox';else if (databaseOnly) authority.databaseOnlyReason = databaseOnly;else if (!configuredWriteThrough) authority.databaseOnlyReason = 'disabled_by_config';- else if (!root && !binding) authority.databaseOnlyReason = 'no_repo_configured';+ else if (!root && !binding) authority.databaseOnlyReason = configuredRoot ? 'relative_root' : 'no_repo_configured';if (p.local_dir !== undefined) {let matches = false;if (ctx.remote === false && typeof p.local_dir === 'string' && localRoot) {diff --git a/src/core/persistence/recovery-resolve.ts b/src/core/persistence/recovery-resolve.tsindex e5decc8b62..75dc35e1c6 100644--- a/src/core/persistence/recovery-resolve.ts+++ b/src/core/persistence/recovery-resolve.ts@@ -146,6 +146,8 @@ interface Journal {export interface ResolutionResult {outcome: 'resolved' | 'still_blocked'; keep: KeepChoice; request_state: string; blocked_reason: string | null;finished_by: 'this_run' | 'another_pass'; backup_dir: string; next: string;+ /** #7715: a strict source's `--keep disk` page: commit the kept edit (the user decides: publish or discard), then sync. */+ fix?: Action;}interface EffectRow { id: string; request_ref: string; request_id: string | null; kind: string; state: string; error_code: string | null; worktree_id: string;recovery: EffectRecovery | null }@@ -649,6 +651,29 @@ const sameIdentity = (row: WriteRequest | null, item: StuckRecovery) => {return !!files && digest(identityOf(files, row!.recovery!)) === digest(item.identity);};+/**+ * #7715: on a strict (git-canonical) source the kept bytes are an ordinary uncommitted edit and Git is the parent, so the+ * follow-up is to commit it (or restore it) and then sync, never a database-side reconcile of content Git does not hold.+ */+function strictKeptEdit(item: StuckRecovery, request: WriteRequest, checkout: string): { next: string; fix: Action } {+ const paths = item.files.map(file => file.relative);+ const sync = ['gbrain', 'sync', '--source', item.source_id, '--no-pull'];+ const shown = paths.join(' ');+ const next = `The bytes on disk are kept and the write's publication was abandoned (request ${request.state}). Source ${item.source_id} is git-canonical, so Git is the parent: `+ + `the kept bytes are an uncommitted edit at ${shown} in ${checkout}, and the page keeps its committed version until Git holds the edit. This command does not mark the page repaired. `+ + `To publish the edit: gbrain git commit-push --path ${checkout} -m "<message>" -- ${shown}, then ${sync.join(' ')}. `+ + `To discard it: git -C ${checkout} restore -- ${shown}, then ${sync.join(' ')}. `+ + `Verify with git -C ${checkout} status --porcelain -- ${shown} (empty once it is committed or restored), then gbrain sync status --source ${item.source_id} --json.`;+ return { next, fix: { ask_user: true, argv: ['gbrain', 'git', 'commit-push', '--path', checkout, '-m', '<MESSAGE>', '--', ...paths],+ inputs: [{ name: 'MESSAGE', how: `A one-line commit message for the kept edit, once the user chooses to publish it. To discard it instead: git -C ${checkout} restore -- ${shown}, then ${sync.join(' ')}.` }],+ consent: [], actor: 'agent', requires_exclusive: false,+ why: 'Commits the kept edit, so Git holds it and the next sync imports it; whether to publish or discard it is the user\'s call.',+ user_message: `The edit to ${item.slug} in source ${item.source_id} is kept on disk but is not in Git yet. Publish it (commit it, then sync) or discard it (restore the committed version, then sync)?`,+ verify: { argv: ['git', '-C', checkout, 'status', '--porcelain', '--', ...paths] },+ then: { argv: sync, consent: [], actor: 'agent', requires_exclusive: false, why: 'Imports the committed edit, or settles the restored file, so the writes waiting on the source resume.',+ verify: { argv: ['gbrain', 'sync', 'status', '--source', item.source_id, '--json'] } } } };+}+function nextStep(item: StuckRecovery, keep: KeepChoice, request: WriteRequest): string {const state = request.state;const sync = `gbrain sync --source ${item.source_id} --no-pull`;@@ -766,7 +791,8 @@ Promise<ResolutionResult & { replayed: boolean }> {const result: ResolutionResult = { outcome: blocked ? 'still_blocked' : 'resolved', keep: opts.keep, request_state: recovered.state,blocked_reason: blocked ? recovered.blocked_reason ?? null : null, finished_by: ours ? 'this_run' : 'another_pass', backup_dir: journal.backup_dir,next: blocked ? `The recovery is still blocked (${recovered.blocked_reason ?? 'recovering'}); rerun the same apply, or inspect it with gbrain sources writer status --source ${item.source_id} --json.`- : nextStep(item, opts.keep, recovered) };+ : nextStep(item, opts.keep, recovered),+ ...(!blocked && opts.keep === 'disk' && item.target === 'page' && binding.canonical_git && binding.local_path ? strictKeptEdit(item, recovered, binding.local_path) : {}) };if (!blocked) await writeJournal(engine, key, { ...journal, phase: 'done', result });return { ...result, replayed: false };} finally { await lock.release(); }diff --git a/src/core/persistence/resolve-paths.ts b/src/core/persistence/resolve-paths.tsindex 7aa313fa22..25938b1271 100644--- a/src/core/persistence/resolve-paths.ts+++ b/src/core/persistence/resolve-paths.ts@@ -28,7 +28,7 @@ import type { BrainEngine } from '../engine.ts';import type { Action } from '../agent-output.ts';import { literalPathspecs } from '../git-env.ts';import { existsSync, realpathSync } from 'node:fs';-import { isAbsolute } from 'node:path';+import { isHostAbsolutePath } from '../path-confine.ts';import { opError } from '../ops/contract.ts';import { resolveSlugForPath, unsyncableReason, type SyncableReason } from '../sync.ts';import { parseMarkdownHead } from '../markdown.ts';@@ -116,7 +116,7 @@ export async function resolveSourcePaths(engine: BrainEngine, sourceId: string,const status = ['gbrain', 'sources', 'status', sourceId, '--json'];if (!source || source.archived) throw opError('not_found', `Source ${sourceId} is not registered or is archived.`, 'List the registered sources and pass one of their ids.',{ fix: readFix('Lists the registered sources.', ['gbrain', 'sources', 'list', '--json'], ['gbrain', 'sources', 'list', '--json']) });- if (source.local_path && !isAbsolute(source.local_path)) throw opError('sync_anchor_relative', `Source ${sourceId} has a relative local_path, which names no fixed directory, so its paths cannot be resolved.`,+ if (source.local_path && !isHostAbsolutePath(source.local_path)) throw opError('sync_anchor_relative', `Source ${sourceId} has a relative local_path, which names no fixed directory, so its paths cannot be resolved.`,'Ask the user which directory holds the checkout, then run gbrain sources set-path on the host that holds it.',{ fix: { argv: ['gbrain', 'sources', 'set-path', sourceId, '<dir>'], consent: [], actor: 'user', ask_user: true, requires_exclusive: false,inputs: [{ name: 'dir', how: "The absolute path of the directory that holds this source's checkout, from the user; never the current directory by default." }],diff --git a/src/core/persistence/terminal-classify.ts b/src/core/persistence/terminal-classify.tsindex 70ac798a1a..04e4b66b23 100644--- a/src/core/persistence/terminal-classify.ts+++ b/src/core/persistence/terminal-classify.ts@@ -309,7 +309,11 @@ function route(input: TerminalInput): Partial_ {verify: { argv: failuresArgv(source) } } };}if (code === 'owner_marker_missing') return fromTable('sync_fault', code, origin, ownerMarkerRestoreFix(source));- if (FAULT_CODES.has(code)) return fromTable('sync_fault', code, origin, faultAction(code, input), null, input.error_message);+ if (FAULT_CODES.has(code)) {+ const verdict = fromTable('sync_fault', code, origin, faultAction(code, input), null, input.error_message);+ // #7646: a fault no sync and no caller retries offers only the read-only inspect, so its safe actions say so too.+ return inspectOnlyFault(code, input) ? { ...verdict, safe_actions: ['none'] } : verdict;+ }const entry = (CODES as Record<string, { class: string } | undefined>)[code];if (!entry) return diagnosis(input, code, origin, `The write ended with code ${code}, which this build does not know.`);if (entry.class === 'server') {@@ -353,7 +357,8 @@ function schemaMissingVerdict(input: TerminalInput, code: string, origin: string/** #7630: the caller-submitted page and memory writes a caller resubmits; no sync replays them. */const RESUBMITTED_WRITES = new Set(['put_page', 'put_pages', 'capture', 'delete_page', 'restore_page', 'revert_version', 'edit_page', 'append_page', 'remember', 'forget', 'forget_fact',- 'add_tag', 'remove_tag', 'add_link', 'remove_link', 'add_timeline_entry', 'takes_add', 'takes_update', 'takes_supersede', 'takes_resolve', 'takes_remove']);+ 'add_tag', 'remove_tag', 'add_link', 'remove_link', 'add_timeline_entry', 'takes_add', 'takes_update', 'takes_supersede', 'takes_resolve', 'takes_remove',+ 'loops_close', 'decide_proposal', 'trust_owner_page', 'trust_release', 'relink_facts']);/*** #7630: the operation a fault's fix depends on. A reconcile or managed write (import, repair, quarantine clear,@@ -363,6 +368,21 @@ export function faultOperation(operation: string, intentKind: string | null | unreturn operation === 'put_page' && intentKind && (intentKind === 'canonical_reconcile' || intentKind.startsWith('managed_')) ? intentKind : operation;}+/**+ * #7646: a caller resubmits its own write. A compacted `put_page` lost its intent kind, so it may be a reconcile or a+ * managed write stored as one: it gets the read-only inspect, never the resubmit advice.+ */+function resubmitted(input: TerminalInput): boolean {+ return RESUBMITTED_WRITES.has(input.operation) && !(input.operation === 'put_page' && input.compacted && !input.intent_kind);+}++/** #7646: a retryable fault on a write that is neither a sync, a reconcile, a managed write nor a caller's resubmittable write. */+function inspectOnlyFault(code: string, input: TerminalInput): boolean {+ const operation = faultOperation(input.operation, input.intent_kind);+ return classifySyncFault({ code }).safe_actions[0] === 'retry' && input.operation !== 'submit_job' && !operation.startsWith('managed_')+ && operation !== 'canonical_reconcile' && !resubmitted(input);+}+/*** #7630: a sync write, a maintenance job and a recorded sync fault (read as one) are stored as `submit_job`; their* retry is the sync. A foreground write (`remember`, `put_page`, ...) is resubmitted by its caller, and a managed write@@ -379,7 +399,7 @@ function faultAction(code: string, input: TerminalInput): Action {if (v.safe_actions[0] === 'retry' && operation === 'canonical_reconcile') {return syncRetry(input.source_id, `The canonical reconcile recorded ${code} (${v.class}); the next sync re-admits a keep_db reconcile, and a \`gbrain sources reconcile\` run is retried by running it again.`);}- if (v.safe_actions[0] === 'retry' && input.operation !== 'submit_job' && !RESUBMITTED_WRITES.has(input.operation)) {+ if (inspectOnlyFault(code, input)) {return inspect(input.source_id, `The ${input.operation} operation ended ${code}; it was not part of a sync, so a sync does not retry it. Writer status names what holds it, read-only.`, v.human_reason);}if (v.safe_actions[0] === 'retry' && input.operation !== 'submit_job') {diff --git a/src/core/persistence/terminal-failures.ts b/src/core/persistence/terminal-failures.tsindex eb5e2c410a..80b30dd0d5 100644--- a/src/core/persistence/terminal-failures.ts+++ b/src/core/persistence/terminal-failures.ts@@ -380,7 +380,7 @@ export async function readTerminalFailures(engine: BrainEngine, q: TerminalFailuconst key = `${row.code}\0${row.origin ?? ''}\0${row.category}${operation === undefined ? '' : `\0${operation}`}`;let g = groups.get(key);if (!g) {- const filter = { code: row.code, origin: row.origin, category: row.category, ...(operation === undefined ? {} : { operation }) };+ const filter = { code: row.code, origin: row.origin, category: row.category, ...(operation ?? q.operation ? { operation: operation ?? q.operation } : {}) };groups.set(key, g = { code: row.code, origin: row.origin, category: row.category, ...(operation === undefined ? {} : { operation }), public_category: row.public_category, rows: 0, class: row.class, needs_human: row.needs_human,...(row.human_reason ? { human_reason: row.human_reason } : {}), filter, fix: row.fix, samples: [],drill_down: terminalFailuresArgv({ sourceId: q.sourceId, state: q.state, sinceDays: q.sinceDays, category: row.category, code: row.code, origin: row.origin ?? NO_ORIGIN, operation: operation ?? q.operation }) });diff --git a/src/core/repair/stuck-recovery.ts b/src/core/repair/stuck-recovery.tsindex 12bd7609c5..c677e1a152 100644--- a/src/core/repair/stuck-recovery.ts+++ b/src/core/repair/stuck-recovery.ts@@ -126,7 +126,7 @@ export const stuckRecoveryRepair: RepairHandler = {return { applied: result.outcome === 'resolved' && !result.replayed, outcome: result.replayed ? 'replayed' : result.outcome,...(result.blocked_reason ? { reason: result.blocked_reason } : {}),detail: { request_id: recovery.request_id, ...(recovery.effect_id ? { effect_id: recovery.effect_id } : {}), keep, request_state: result.request_state,- finished_by: result.finished_by, backup_dir: result.backup_dir, next: result.next } };+ finished_by: result.finished_by, backup_dir: result.backup_dir, next: result.next, ...(result.fix ? { fix: result.fix } : {}) } };},render(details) {const recoveries = (details.recoveries ?? []) as StuckRecovery[];diff --git a/src/core/repair/url-clone-fences.ts b/src/core/repair/url-clone-fences.tsindex 019502940c..e099e91dd3 100644--- a/src/core/repair/url-clone-fences.ts+++ b/src/core/repair/url-clone-fences.ts@@ -150,7 +150,7 @@ async function survey(engine: BrainEngine, sourceIds: string[]): Promise<{ filesfiles.push({ source_id: source.id, incarnation: source.incarnation, root, path, slug, page_id, head_sha256: sha256(head!), work_sha256: sha256(work!),rows: proof.added.map(row => row.rowNum), selection: sourceIds });listing.push(hold- ? { item, class: hold.code, detail: `${proof.added.length} fence row(s) gbrain appended to ${slug}: kept database-only, then the file is restored from HEAD so the clone can pull again, but HEAD's bytes are not imported as the page: ${hold.message} The page keeps its last imported version and sync holds the file until it is fixed upstream.` }+ ? { item, class: hold.code, detail: `${proof.added.length} fence row(s) gbrain appended to ${slug}: kept database-only, then the file is restored from HEAD so the clone can pull again, but HEAD's bytes are not imported as the page: ${hold.message} The page keeps its last imported version: the restored file equals HEAD, so sync does not screen it again and records no hold; the page changes once a commit that fixes the file upstream is pulled and synced.` }: { item, class: 'fence_rows_only', detail: `${proof.added.length} fence row(s) gbrain appended to ${slug}: kept database-only, then the file is restored from HEAD` });}}@@ -228,7 +228,8 @@ export const urlCloneFencesRepair: RepairHandler = {}const { files, listing } = await survey(engine, scope.source_ids);const residuals: Record<string, number> = {};- for (const entry of listing) if (entry.class !== 'fence_rows_only') residuals[entry.class] = (residuals[entry.class] ?? 0) + 1;+ const planned = new Set(files.map(file => `${file.source_id}:${file.path}`));+ for (const entry of listing) if (!planned.has(entry.item)) residuals[entry.class] = (residuals[entry.class] ?? 0) + 1;const hash = previewHash({ kind: 'url-clone-fences-v2', brain_id: scope.brain_id, selection: scope.source_ids,files: files.map(f => [f.source_id, f.incarnation, f.root, f.path, f.slug, f.page_id, f.head_sha256, f.work_sha256, f.rows]) });if (files.length) await saveApprovedSet<ClonedFile>(engine, { ...APPROVAL, hash }, files);diff --git a/src/core/sources-ops.ts b/src/core/sources-ops.tsindex afcc59530c..10494e0aed 100644--- a/src/core/sources-ops.ts+++ b/src/core/sources-ops.ts@@ -40,7 +40,7 @@ import { managedPersistenceEnabled } from './persistence/ownership.ts';import { existsSync, mkdirSync, renameSync, rmSync, lstatSync, realpathSync } from 'fs';import { join, dirname, basename, isAbsolute, resolve as resolvePath } from 'path';-import { isPathContained, msysToNativePath } from './path-confine.ts';+import { isHostAbsolutePath, isPathContained, msysToNativePath } from './path-confine.ts';import { mkdirPrivate } from './atomic-write.ts';import { randomBytes } from 'crypto';import type { BrainEngine } from './engine.ts';@@ -926,6 +926,8 @@ export interface RemoveResult {pages_deleted: number;clone_removed: boolean;clone_path: string | null;+ /** #7646: why a gbrain-managed clone was left on disk (`relative_path`: its stored path names no fixed directory). */+ clone_skipped_reason?: 'relative_path';dryRun: boolean;}@@ -1001,9 +1003,13 @@ export async function removeSource(const gManaged = ghCfg.kind === 'google' && ghCfg.g_managed === true;const cloneRoot = gbrainPath('clones');let cloneRemoved = false;- if (!opts.keepStorage && src.local_path && (remoteUrl || ghManaged || gManaged) && !isAbsolute(src.local_path)) {+ let cloneSkippedReason: RemoveResult['clone_skipped_reason'];+ if (!opts.keepStorage && src.local_path && (remoteUrl || ghManaged || gManaged) && !isHostAbsolutePath(src.local_path)) {+ cloneSkippedReason = 'relative_path';+ const cloneDir = defaultCloneDir(opts.id);console.error(- `[gbrain] WARN: clone cleanup skipped for "${opts.id}": its stored local_path "${src.local_path}" is relative, so it would name the current directory. Delete the clone by hand if you still want it gone.`,+ `[gbrain] WARN: clone cleanup skipped for "${opts.id}": its stored local_path "${src.local_path}" is not absolute on this host, so it would name the current directory. ` ++ (existsSync(cloneDir) ? `gbrain's clone directory for this source is ${cloneDir}; delete it by hand if you still want it gone (a later sources add ${opts.id} --url refuses while it holds files).` : 'Delete the clone by hand if you still want it gone.'),);} else if (!opts.keepStorage &&@@ -1041,6 +1047,7 @@ export async function removeSource(pages_deleted: pageCount,clone_removed: cloneRemoved,clone_path: src.local_path,+ ...(cloneSkippedReason ? { clone_skipped_reason: cloneSkippedReason } : {}),dryRun: false,};}@@ -1129,7 +1136,7 @@ export async function recloneIfMissing(}const remoteUrl = getRemoteUrl(src.config);if (!remoteUrl || !src.local_path) return false;- if (!isAbsolute(src.local_path)) {+ if (!isHostAbsolutePath(src.local_path)) {throw new SourceOpError('unmanaged_path',`Refusing to re-clone "${id}": its stored local_path "${src.local_path}" is relative, so it would name the current directory. Run gbrain sources set-path ${id} <absolute-directory>, then retry.`);}diff --git a/src/core/sync-anchor.ts b/src/core/sync-anchor.tsindex d7a1a03c5f..1a0a9ebc58 100644--- a/src/core/sync-anchor.ts+++ b/src/core/sync-anchor.ts@@ -6,7 +6,8 @@ import { withCompanyBrainSource } from './company-brain/profile.ts';*/import { realpathSync } from 'fs';import { syncDispatchRow } from './sync-dispatch-read.ts';-import { isAbsolute, resolve as pathResolve } from 'path';+import { resolve as pathResolve } from 'path';+import { isHostAbsolutePath } from './path-confine.ts';import type { BrainEngine } from './engine.ts';import type { SyncOpts } from '../commands/sync.ts';import { ownsGlobalSyncAnchor, sameRepoDir } from './sync.ts';@@ -91,7 +92,7 @@ export async function isAnchorOwnedSyncPath(if (opts.srcSubpath) return false;if (opts.sourceId && opts.sourceId !== 'default') return false;const anchor = await readSyncAnchor(engine, opts.sourceId, 'repo_path');- if (anchor === null || !isAbsolute(anchor)) return false;+ if (anchor === null || !isHostAbsolutePath(anchor)) return false;try {return realpathSync(anchor) === realpathSync(repoPath);} catch {@@ -143,7 +144,7 @@ export async function ownsSourceSyncAnchor();const configured = rows[0]?.local_path ?? null;if (configured === null) return { owns: true, configured: null };- if (!isAbsolute(configured)) return { owns: false, configured };+ if (!isHostAbsolutePath(configured)) return { owns: false, configured };return { owns: sameRepoDir(configured, dir), configured };} catch {return { owns: true, configured: null };@@ -195,8 +196,10 @@ function sameOrNestedRepoDir(a: string, b: string): boolean {* Identity resolution mirrors `ownsGlobalSyncAnchor` for `'default'` (global* `sync.repo_path` key first, else the row's `local_path`); other ids use the* row's `local_path`. A null identity bootstraps (first sync of a- * freshly-registered source). Best-effort: a failed read fails OPEN — a- * guard bug must never block anchor writes.+ * freshly-registered source); #7646: a relative `sync.repo_path` behind a null+ * `default` row is a stored identity that proves nothing, so it refuses rather+ * than bootstraps. Best-effort: a failed read fails OPEN — a guard bug must+ * never block anchor writes.*/export async function sourceCommitAnchorAllowed(engine: BrainEngine,@@ -205,19 +208,21 @@ export async function sourceCommitAnchorAllowed(): Promise<SourceAnchorOwnership> {try {let configured: string | null = null;+ let relativeGlobal: string | null = null;if (sourceId === 'default') {const globalPath = (await engine.getConfig('sync.repo_path')) || null;- configured = globalPath && isAbsolute(globalPath) ? globalPath : null;+ if (globalPath && isHostAbsolutePath(globalPath)) configured = globalPath;+ else relativeGlobal = globalPath;}if (configured === null) {const rows = await engine.executeRaw<{ local_path: string | null }>(`SELECT local_path FROM sources WHERE id = $1`,[sourceId],);- configured = rows[0]?.local_path ?? null;+ configured = rows[0]?.local_path ?? relativeGlobal;}if (configured === null) return { owns: true, configured: null };- if (!isAbsolute(configured)) return { owns: false, configured };+ if (!isHostAbsolutePath(configured)) return { owns: false, configured };return { owns: sameOrNestedRepoDir(configured, repoDir), configured };} catch {return { owns: true, configured: null };@@ -258,11 +263,14 @@ export async function writeSyncAnchor(if (repoDir !== undefined) {const { owns, configured } = await sourceCommitAnchorAllowed(engine, sourceId, repoDir);if (!owns) {- serr(- `[sync] sources.last_commit for "${sourceId}" not advanced — syncing repo ` +- `"${repoDir}" is neither the registered directory ${configured ?? '(unset)'} nor ` +- `within the same tree. Sync from the registered directory, or re-register the ` +- `source to move it intentionally.`,+ serr(configured !== null && !isHostAbsolutePath(configured)+ ? `[sync] sources.last_commit for "${sourceId}" not advanced — its stored path "${configured}" is not an ` ++ `absolute directory on this host, so it cannot prove "${repoDir}" is its tree. Ask the user which directory ` ++ `holds it, then run: gbrain sources set-path ${sourceId} <absolute-directory>`+ : `[sync] sources.last_commit for "${sourceId}" not advanced — syncing repo ` ++ `"${repoDir}" is neither the registered directory ${configured ?? '(unset)'} nor ` ++ `within the same tree. Sync from the registered directory, or re-register the ` ++ `source to move it intentionally.`,);return;}diff --git a/src/core/sync-applicability.ts b/src/core/sync-applicability.tsindex 7c02cf4e4e..2171f70f9f 100644--- a/src/core/sync-applicability.ts+++ b/src/core/sync-applicability.ts@@ -15,12 +15,13 @@* whatever directory gbrain runs from.*/import { existsSync, realpathSync } from 'node:fs';-import { isAbsolute, join, posix, relative, resolve, win32 } from 'node:path';+import { isAbsolute, join, relative, resolve } from 'node:path';import type { BrainEngine } from './engine.ts';import { gbrainPath, loadConfig } from './config.ts';import { opError, type OperationError } from './ops/contract.ts';import { readSyncAnchor } from './sync-anchor.ts';import { contentSetupKey } from './shared-skills/setup.ts';+import { isForeignAbsolutePath, isHostAbsolutePath } from './path-confine.ts';/** A source whose sync root is a gbrain-owned content directory with no Git checkout. */export interface SyncContentDirectory {@@ -93,7 +94,7 @@ export function syncNotApplicableError(dir: SyncContentDirectory): OperationErro* everything in it, an import of its markdown). Refused before any Git probe, cost estimate or import.*/export function syncAnchorRelativeError(sourceId: string | undefined, anchor: string): OperationError {- const foreign = posix.isAbsolute(anchor) || win32.isAbsolute(anchor);+ const foreign = isForeignAbsolutePath(anchor);const why = foreign? `The path is absolute only on another operating system (another host sharing this brain may have set it); on this host it would name a folder inside whatever directory gbrain runs from, so sync cannot use it here. Nothing was changed.`: `A relative path names whatever directory gbrain runs from, not a fixed folder, so it cannot prove which folder is the brain; syncing it from an unrelated folder would Git-initialize that folder, commit everything in it and import its markdown. Nothing was changed.`;@@ -124,11 +125,15 @@ export function syncAnchorRelativeError(sourceId: string | undefined, anchor: stverify: { argv: ['gbrain', 'sources', 'status', sourceId, '--json'] } } });}-/** #7630: refuse a sync whose root would be a relative stored anchor (an explicit absolute or different `repoPath` passes). */+/**+ * #7630: refuse a sync whose root would be a relative stored anchor. An explicit absolute `repoPath` passes, and so does a+ * relative one naming another directory; #7646: a relative `repoPath` is compared with the anchor after resolving both, so+ * `--repo ./` is refused like `--repo .`.+ */export async function assertSyncAnchorAbsolute(engine: BrainEngine, opts: { sourceId?: string; repoPath?: string }): Promise<void> {- if (opts.repoPath && isAbsolute(opts.repoPath)) return;+ if (opts.repoPath && isHostAbsolutePath(opts.repoPath)) return;const anchor = await readSyncAnchor(engine, opts.sourceId, 'repo_path');- if (!anchor || isAbsolute(anchor) || (opts.repoPath && opts.repoPath !== anchor)) return;+ if (!anchor || isHostAbsolutePath(anchor) || (opts.repoPath && resolve(opts.repoPath) !== resolve(anchor))) return;throw syncAnchorRelativeError(opts.sourceId, anchor);}diff --git a/src/core/sync-config-keys.ts b/src/core/sync-config-keys.tsindex 9635e801e8..81c3361a81 100644--- a/src/core/sync-config-keys.ts+++ b/src/core/sync-config-keys.ts@@ -10,7 +10,7 @@* `config get` prints the value in effect and where it comes from, and doctor (`sync_config_keys`) reports a value* stored before the upgrade as unapplied.*/-import { isAbsolute } from 'node:path';+import { isHostAbsolutePath } from './path-confine.ts';import { CONFIG_ROLLBACK_WINDOWS, type ConfigRollbackWindow } from './wire-skew.ts';import type { BrainEngine } from './engine.ts';@@ -129,7 +129,7 @@ export function syncKeySetNotice(key: string): { writes: boolean; lines: string[/** #7630: the `config set sync.repo_path` refusal for a relative value, or null when it may be stored. */export function syncRepoPathRefusal(value: string): string | null {- if (isAbsolute(value)) return null;+ if (isHostAbsolutePath(value)) return null;return `sync.repo_path must be an absolute directory (got '${value}'): a relative path names whatever directory gbrain runs from, and sync refuses it (sync_anchor_relative). Nothing was written.`;}diff --git a/src/core/write-through.ts b/src/core/write-through.tsindex 9401416cff..8fbf9b6d1e 100644--- a/src/core/write-through.ts+++ b/src/core/write-through.ts@@ -23,14 +23,14 @@ import { hasSourceFilesystemLock, withSourceFilesystemLock, assertSourceFilesyst*/import { existsSync, statSync, mkdirSync, unlinkSync, readdirSync, readFileSync, renameSync, rmSync } from 'fs';-import { basename, dirname, isAbsolute, join, posix, relative, resolve, sep, win32 } from 'path';+import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'path';import { atomicStagingPath, atomicWriteFileSync } from './atomic-write.ts';import { flushDirectory } from './fs-durable.ts';import { isSegmentedPage } from './page-body/page-shape.ts';import type { BrainEngine } from './engine.ts';import type { StreamedFileContent } from './persistence/large-file.ts';import { isRelativeFileUri, serializePageToMarkdown, resolvePageFilePath, resolveSourceLocalFilePath } from './markdown.ts';-import { isWriteTargetContained, msysToNativePath } from './path-confine.ts';+import { isForeignAbsolutePath, isHostAbsolutePath, isWriteTargetContained, msysToNativePath } from './path-confine.ts';import { readSlugRootMode, resolveSlugRootMode, type SlugRootMode } from './sync-anchor.ts';import { resolveSlugForPath } from './sync.ts';import { PUSH_SCAN_MAX_FILE_BYTES } from './page-size-policy.ts';@@ -131,6 +131,14 @@ export interface WritePageThroughOpts {}export function withNoRepoWriteThroughWarning<T extends { written: boolean; skipped?: string; warning?: string }>(result: T, sourceId: string, operation = 'put_page'): T {+ if (!result.written && result.skipped === 'relative_root') {+ return {+ ...result,+ warning:+ `${operation} wrote only to the database for source '${sourceId}': its stored repo path is not an absolute directory on this host, so no durable markdown file was created. ` ++ `Ask the operator to run gbrain sources set-path ${sourceId} <absolute-directory> before relying on the write.`,+ } as T;+ }if (result.written || result.skipped !== 'no_repo_configured') return result;return {...result,@@ -307,9 +315,8 @@ export async function otherSourceOwning(engine: BrainEngine, sourceId: string, pconst target = identity(path);return rows.find(row => {// #7630: a live source's relative local_path names no known tree, so like any unresolvable spelling it counts as a match.- // An absolute path written by another OS (C:\ on POSIX) is not relative, the same reading doctor and --clear use.- const native = msysToNativePath(row.local_path);- if (!posix.isAbsolute(native) && !win32.isAbsolute(native)) return relativeOwns && !row.archived;+ // An absolute path written by another OS (C:\ on POSIX) is not relative, the same reading sync, doctor and --clear use.+ if (!isHostAbsolutePath(row.local_path) && !isForeignAbsolutePath(row.local_path)) return relativeOwns && !row.archived;const other = identity(row.local_path);if (target === null || other === null) return true;const rel = relative(other, target);@@ -389,7 +396,7 @@ export async function resolvePageWriteTarget(if (sourceLocalPath) {// #7630: a relative local_path (a legacy ".") names whatever directory gbrain runs from, never the source's tree.- if (!isAbsolute(sourceLocalPath) || !existsSync(sourceLocalPath) || !statSync(sourceLocalPath).isDirectory()) {+ if (!isHostAbsolutePath(sourceLocalPath) || !existsSync(sourceLocalPath) || !statSync(sourceLocalPath).isDirectory()) {return { ok: false, skipped: 'repo_not_found' };}filePath = recordedPath@@ -403,7 +410,7 @@ export async function resolvePageWriteTarget(if (!repoPath) {return { ok: false, skipped: 'no_repo_configured' };}- if (!isAbsolute(repoPath) || !existsSync(repoPath) || !statSync(repoPath).isDirectory()) {+ if (!isHostAbsolutePath(repoPath) || !existsSync(repoPath) || !statSync(repoPath).isDirectory()) {return { ok: false, skipped: 'repo_not_found' };}const pageRoot = sourceId === 'default' ? repoPath : join(repoPath, '.sources', sourceId);diff --git a/test/behavior-change-notice.test.ts b/test/behavior-change-notice.test.tsindex e13f582638..5d72de3101 100644--- a/test/behavior-change-notice.test.ts+++ b/test/behavior-change-notice.test.ts@@ -325,6 +325,17 @@ describe('per-release content', () => {expect(all.why).toContain(noticeHeader('0', true));expect(all.fix?.argv).toEqual(['unset', 'GBRAIN_CHAT_FALLBACK_CHAIN']);});++ // #7646: table order is not release order (rows land out of order across merges), so the notice sorts releases itself.+ test('the disclosure lists releases oldest first, whatever the table order', () => {+ const listed = (why: string) => [...why.matchAll(/(?:^| )v(\d+\.\d+\.\d+\.\d+): \(/g)].map(m => m[1]!);+ const sinces = [...new Set(BEHAVIOR_CHANGES.map(c => c.since))].sort(compareReleases);+ for (const after of ['0', sinces.at(-6)!, sinces.at(-3)!]) {+ const shown = listed(behaviorChangesNotice(null, { after })!.why);+ expect(shown.length).toBeGreaterThan(1);+ expect(shown).toEqual([...shown].sort(compareReleases));+ }+ });});describe('concurrent initializations', () => {diff --git a/test/cli-page-writes.test.ts b/test/cli-page-writes.test.tsindex 1e2147caed..c784959537 100644--- a/test/cli-page-writes.test.ts+++ b/test/cli-page-writes.test.ts@@ -227,6 +227,8 @@ for (const backend of testBackends()) {const put = await cli(['put', 'notes/huge-private', '--file', file('huge-private.md', `---\nVisibility: Private\n---\n${hugeBody('Huge private')}`)]);expect(put.code).not.toBe(0);expect(put.stderr).toContain('visibility_not_applied');+ expect(put.stderr).toContain('page notes/huge-private would stay world-readable, so nothing was written');+ expect(put.stderr).not.toContain('import the file again');expect(await sql<{ n: number }>('SELECT count(*)::int AS n FROM pages WHERE slug = $1', ['notes/huge-private'])).toEqual([{ n: 0 }]);}, 600_000);diff --git a/test/e2e/stored-root-followups-7646-postgres.test.ts b/test/e2e/stored-root-followups-7646-postgres.test.tsnew file mode 100644index 0000000000..b05ec26104--- /dev/null+++ b/test/e2e/stored-root-followups-7646-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../stored-root-followups-7646.test.ts'));diff --git a/test/git-canonical-conversion-owner-root-7956.test.ts b/test/git-canonical-conversion-owner-root-7956.test.tsnew file mode 100644index 0000000000..dafdefd665--- /dev/null+++ b/test/git-canonical-conversion-owner-root-7956.test.ts@@ -0,0 +1,150 @@+/**+ * #7956: `sources canonical --to git` judges the source's owner the way the managed sync context does before it looks at+ * the root, refuses a root it cannot read with a typed refusal, and reports `converted` only for a source that is still+ * git-canonical when the apply ends.+ *+ * Protects:+ * - a registered root that is gone, a file, a symlink loop or unreadable refuses `source_root_unreadable` (reason, fix)+ * instead of a raw ENOENT or Git error, and never `git_checkout_required`, whose fix would create a repository there;+ * - an archived or re-registered source, a checkout another host owns and a draining worktree refuse `owner_unavailable`+ * before the checkout check, so a checkout-less root on such a source is not refused as missing a checkout;+ * - a source returned to mixed (`--to mixed`) while the apply ran gets no closing strict pass and is reported+ * `incomplete` with a message that says it is mixed, never `converted`.+ */+import { describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { chmodSync, mkdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { applyGitConversion, applyMixedConversion, planGitConversion, planMixedConversion, type ConversionProgress } from '../src/core/persistence/git-conversion.ts';+import { runSourcesCanonical } from '../src/commands/sources-canonical.ts';+import { _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';+import { acquireCommitLockAsync } from '../src/core/git/commit-push.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';++const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, '-c', 'commit.gpgsign=false', ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const note = (body: string) => `---\ntype: concept\ntitle: note\n---\n\n${body}\n`;+const plain = ({ root }: { root: string }) => { mkdirSync(join(root, 'notes'), { recursive: true }); writeFileSync(join(root, 'notes/a.md'), note('A plain file.')); };+const committed = ({ root }: { root: string }) => {+ plain({ root });+ git(root, 'init', '-q'); git(root, 'config', 'user.name', 'Example Writer'); git(root, 'config', 'user.email', '[email protected]');+ for (const name of ['b', 'c']) writeFileSync(join(root, `notes/${name}.md`), note(`Committed ${name}.`));+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 'notes');+};++/** Runs the CLI and returns its last stdout line as JSON; `events` collects the --json progress lines on stderr. */+async function cli(engine: BrainEngine, args: string[], events: ConversionProgress[] = []): Promise<Record<string, any>> {+ const out: string[] = [];+ const log = console.log, write = process.stderr.write, priorExitCode = process.exitCode;+ console.log = (line: unknown) => { out.push(String(line)); };+ process.stderr.write = ((chunk: string | Uint8Array) => {+ for (const line of String(chunk).split('\n')) if (line.startsWith('{')) { const event = JSON.parse(line) as ConversionProgress; if (event.phase) events.push(event); }+ return true;+ }) as typeof process.stderr.write;+ try { await runSourcesCanonical(engine, args); }+ finally { console.log = log; process.stderr.write = write; _resetCliExitVerdictForTests(); process.exitCode = priorExitCode ?? 0; }+ return JSON.parse(out.at(-1)!);+}+const isStrict = async (engine: BrainEngine) => (await engine.executeRaw("SELECT 1 FROM sources WHERE id='default' AND config->>'canonical'='git'")).length === 1;+const worktree = "(SELECT worktree_id FROM persistence_source_bindings WHERE source_id='default')";++for (const backend of testBackends()) describe(`[${backend}] #7956: owner, root and status of a git-canonical conversion`, () => {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;+ const preview = ['default', '--to', 'git', '--dry-run', '--json'];++ const broken: Array<[string, (root: string) => void, string]> = [+ ['is gone', root => rmSync(root, { recursive: true, force: true }), 'missing'],+ ['is a file', root => { rmSync(root, { recursive: true, force: true }); writeFileSync(root, 'not a directory\n'); }, 'not_directory'],+ ['is a symlink loop', root => { rmSync(root, { recursive: true, force: true }); symlinkSync(root, root); }, 'symlink_loop'],+ ];+ for (const [name, breakRoot, reason] of broken) {+ // Value: protects=an unreadable owned root refuses typed with a fix instead of a raw error, and never as a missing checkout; fails_when=the plan reaches realpathSync or git rev-parse on it, or maps it to git_checkout_required; why_new=#7885's test only asserted it was not git_checkout_required; seam=none; no_claim=what sync itself says about such a root+ test(`a root that ${name} refuses source_root_unreadable (${reason}) with a fix, and writes nothing`, () => managedBrain(async ({ engine, root }) => {+ breakRoot(root);+ try {+ await expect(planGitConversion(engine, 'default')).rejects.toMatchObject({ code: 'source_root_unreadable' });+ const refused = await cli(engine, preview);+ expect(refused).toMatchObject({ status: 'refused', code: 'source_root_unreadable', reason, retryable: false,+ fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', 'default', '--json'] } });+ expect(String(refused.message)).toContain(root);+ expect(await isStrict(engine)).toBe(false);+ } finally { rmSync(root, { recursive: true, force: true }); mkdirSync(root, { recursive: true }); }+ }, { databaseUrl, setup: committed }), 120_000);+ }++ // Value: protects=a root the account cannot list refuses typed (permission_denied); fails_when=EACCES surfaces raw; why_new=the cases above cover the other errno classes; seam=none; no_claim=root, who bypasses permissions (skipped)+ test.skipIf(process.getuid?.() === 0)('a root without read permission refuses source_root_unreadable (permission_denied)', () => managedBrain(async ({ engine, root }) => {+ chmodSync(root, 0o000);+ try {+ expect(await cli(engine, preview)).toMatchObject({ status: 'refused', code: 'source_root_unreadable', reason: 'permission_denied' });+ } finally { chmodSync(root, 0o755); }+ }, { databaseUrl, setup: committed }), 120_000);++ const unowned: Array<[string, string, string | undefined]> = [+ ['an archived source', "UPDATE sources SET archived=true WHERE id='default'", undefined],+ ['a re-registered source', "UPDATE persistence_source_bindings SET source_incarnation=gen_random_uuid() WHERE source_id='default'", 'incarnation_changed'],+ ['a checkout another host owns', `UPDATE persistence_worktrees SET owner_host_id=gen_random_uuid() WHERE id=${worktree}`, 'host_mismatch'],+ ['a draining worktree', `UPDATE persistence_worktrees SET state='draining' WHERE id=${worktree}`, 'transfer_in_progress'],+ ];+ for (const [name, sql, reason] of unowned) {+ // Value: protects=the owner gate runs before the checkout check with the context's own conditions, so a checkout-less root on a source this host may not sync is refused as unowned, not as missing a checkout (whose fix is git init there); fails_when=the checkout check gates on a narrower predicate than resolveManagedSyncContext; why_new=no test set an unowned binding over a checkout-less root; seam=none; no_claim=the owner_unavailable message itself+ test(`${name} over a checkout-less root refuses owner_unavailable, not git_checkout_required`, () => managedBrain(async ({ engine }) => {+ await engine.transaction(async tx => { await tx.executeRaw("SELECT set_config('gbrain.topology_change', 'on', true)"); await tx.executeRaw(sql); });+ expect(await cli(engine, preview)).toMatchObject({ status: 'refused', code: 'owner_unavailable', ...(reason ? { reason } : {}) });+ expect(await isStrict(engine)).toBe(false);+ }, { databaseUrl, setup: plain }), 120_000);+ }++ /** Runs `run` once, when strict pass 2 has read its level; returns whether it ran. */+ const afterStrictPass2 = (seen: ConversionProgress[], run: () => Promise<void>) => {+ let done = false;+ installFaultHook(async point => {+ if (done || point !== 'sync:level_read' || seen.at(-1)?.phase !== 'strict_pass_2') return;+ done = true;+ await run();+ });+ return () => done;+ };+ const toMixed = async (engine: BrainEngine) => { await applyMixedConversion(engine, 'default', (await planMixedConversion(engine, 'default')).preview_hash); };++ // Value: protects=an apply whose source was returned to mixed during strict pass 2 reports incomplete with after.strict false, never converted; fails_when=status reads after.remaining alone; why_new=every converted test keeps the flag; seam=fault hook at sync:level_read; no_claim=a --to mixed racing the flag flip itself+ test('a --to mixed apply during strict pass 2 leaves the apply incomplete, not converted', () => managedBrain(async ({ engine }) => {+ expect((await performManagedSync(engine, { sourceId: 'default', noPull: true, noExtract: true })).status).toBe('first_sync');+ const seen: ConversionProgress[] = [];+ const fired = afterStrictPass2(seen, () => toMixed(engine));+ let result: Awaited<ReturnType<typeof applyGitConversion>>;+ try {+ const { preview: plan } = await planGitConversion(engine, 'default');+ result = await applyGitConversion(engine, 'default', plan.preview_hash, { noExtract: true, onProgress: progress => seen.push(progress) });+ } finally { installFaultHook(undefined); }+ expect(fired()).toBe(true);+ expect(result).toMatchObject({ status: 'incomplete', closing_passes: 0, after: { strict: false } });+ expect(await isStrict(engine)).toBe(false);+ }, { databaseUrl, setup: committed }), 300_000);++ // Value: protects=closing passes run only on a source that is still git-canonical: Git ahead on a source returned to mixed gets no closing pass, and the CLI says the source is mixed; fails_when=the closing loop drops its after.strict guard, or the refusal says git-canonical; why_new=the live-writer tests keep the flag; seam=fault hook at sync:level_read; no_claim=what a later mixed sync imports+ test('Git ahead on a source returned to mixed gets no closing pass, and the refusal says the source is mixed', () => managedBrain(async ({ engine, root }) => {+ expect((await performManagedSync(engine, { sourceId: 'default', noPull: true, noExtract: true })).status).toBe('first_sync');+ const seen: ConversionProgress[] = [];+ const fired = afterStrictPass2(seen, async () => {+ await toMixed(engine);+ writeFileSync(join(root, 'notes/b.md'), note('Committed by a live writer after strict pass 2.'));+ const lock = await acquireCommitLockAsync(root, 10_000);+ try { git(root, 'add', '--', 'notes/b.md'); git(root, 'commit', '-qm', 'live writer'); } finally { await lock.release(); }+ });+ let out: Record<string, any>;+ try {+ const { preview: plan } = await planGitConversion(engine, 'default');+ out = await cli(engine, ['default', '--to', 'git', '--apply', '--expect', plan.preview_hash, '--no-extract', '--json'], seen);+ } finally { installFaultHook(undefined); }+ expect(fired()).toBe(true);+ expect(out).toMatchObject({ status: 'incomplete', code: 'git_conversion_incomplete', result: { status: 'incomplete', closing_passes: 0, after: { strict: false } } });+ expect(out.result.after.git_wins.count).toBeGreaterThan(0);+ expect(out.message).toContain('is mixed');+ expect(out.message).not.toContain('is git-canonical');+ expect(await isStrict(engine)).toBe(false);+ }, { databaseUrl, setup: committed }), 300_000);+});diff --git a/test/git-door-index-lock-7742.test.ts b/test/git-door-index-lock-7742.test.tsindex 3ef923b541..dacaa3fed8 100644--- a/test/git-door-index-lock-7742.test.ts+++ b/test/git-door-index-lock-7742.test.ts@@ -14,11 +14,11 @@* cannot create for a reason other than an existing lock still reports the landed commit and names that cause.*/import { afterEach, describe, expect, test } from 'bun:test';-import { execFileSync } from 'node:child_process';+import { execFileSync, spawnSync } from 'node:child_process';import { randomUUID } from 'node:crypto';-import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, utimesSync, writeFileSync } from 'node:fs';+import { chmodSync, closeSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, utimesSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';-import { join } from 'node:path';+import { basename, join } from 'node:path';import type { BrainEngine } from '../src/core/engine.ts';import { gitChildEnv } from '../src/core/git-env.ts';import { operations, type OperationContext } from '../src/core/operations.ts';@@ -26,9 +26,9 @@ import { submissionAuthority } from '../src/core/persistence/authority.ts';import { publishMutation, type PublicationHooks } from '../src/core/persistence/coordinator.ts';import { sha256 } from '../src/core/persistence/digest.ts';import { INDEX_LOCK_GRACE_FOR_TESTS } from '../src/core/persistence/effect-git.ts';-import { commitThroughDoor, doorSeams } from '../src/core/persistence/git-door.ts';+import { commitThroughDoor, doorSeams, indexCommitIo } from '../src/core/persistence/git-door.ts';import { localHostId } from '../src/core/persistence/identity.ts';-import { proveIndexLockAbandoned } from '../src/core/persistence/index-lock-reclaim.ts';+import { processTableBlind, proveIndexLockAbandoned, readIndexLockReclaims, type IndexLockVerdict } from '../src/core/persistence/index-lock-reclaim.ts';import { admitWrite, claimNextWrite } from '../src/core/persistence/journal.ts';import { tryAcquireNativeLock } from '../src/core/persistence/native-lock.ts';import { getWorktreeBinding } from '../src/core/persistence/ownership.ts';@@ -50,7 +50,11 @@ const page = (title: string) => `---\ntype: note\ntitle: ${title}\n---\n\nA smalconst setup = ({ root }: { root: string }) => { writeFileSync(join(root, '.gitignore'), '\n'); durableGitRepo(root, ['.gitignore']); };const putPage = operations.find(op => op.name === 'put_page')!;const dirs: string[] = [];-afterEach(() => { delete doorSeams.beforeUpdateRef; for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });+const io = { ...indexCommitIo };+afterEach(() => {+ delete doorSeams.beforeUpdateRef; delete doorSeams.indexLockHeld; Object.assign(indexCommitIo, io);+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });+});/*** A git on PATH that hands every call to the real git. Once armed, the first call whose arguments contain ` <trigger> `@@ -107,6 +111,8 @@ const armAfterPublication = (root: string, shim: { dir: string; arm(): void }):/** Index locks and door index copies left in the checkout's git directory. */const leftovers = (root: string) => readdirSync(join(root, '.git')).filter(name => name === 'index.lock' || name.startsWith('index.gbrain-'));+/** Why the #6932 proof may keep a lock on a host it cannot fully see: another user's git, or one that stayed unreadable while it exited. */+const HOST_DOUBT = /not reclaimed: git process \d+ \(.*\) (belongs to another user|could not be inspected|is this user's, but it stayed unreadable)/;for (const backend of testBackends()) describe(`[${backend}] the door's index refresh holds the index lock`, () => {const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;@@ -278,7 +284,8 @@ describe('door plumbing: the index lock', () => {// Value: protects=the door, holding the writer lock, reclaims an index.lock no live process holds (#6932) and finishes its refresh,// as it did when update-index ran through effect-git; fails_when=the door's own exclusive create answers any existing lock with the// landed failure; why_new=the held-lock test uses a fresh lock no proof accepts; seam=none; no_claim=hosts where the proof cannot see- // every process, where the lock must stay and the landed failure stands (the oracle is the same proof the door runs)+ // every process, or another user's git runs, where the lock must stay and the landed failure stands. The oracle is the door's own+ // verdict (its receipt, or the reason its refusal names), never a second proof that a git starting in between could flip (#7758)test('an abandoned index.lock is reclaimed under the writer lock and the refresh completes', async () => {const root = seeded(), lock = join(root, '.git', 'index.lock');const home = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-door-home-')));@@ -290,18 +297,112 @@ describe('door plumbing: the index lock', () => {await withEnv({ GBRAIN_HOME: home }, async () => {const writer = (await tryAcquireNativeLock(join(home, 'writer.lock')))!;try {- const provable = proveIndexLockAbandoned(lock, root, INDEX_LOCK_GRACE_FOR_TESTS).abandoned;const error = await refusal(commitThroughDoor(root, [{ path: join(root, 'notes/a.md'), planned: sha256('door\n') }], writer));expect(git(root, 'show', 'HEAD:notes/a.md')).toBe('door');- if (!provable) {- expect(error).toMatchObject({ code: 'git_unavailable', message: expect.stringContaining('landed, but the index') });+ const reclaims = readIndexLockReclaims().filter(receipt => receipt.lock === lock);+ if (error) {+ const blind = processTableBlind();+ expect(error).toMatchObject({ code: 'git_unavailable', message: expect.stringContaining('landed, but the index'),+ suggestion: blind ? expect.stringContaining(`not reclaimed: ${blind}`) : expect.stringMatching(HOST_DOUBT) });expect(existsSync(lock)).toBe(true);+ expect(reclaims).toEqual([]);return;}- expect(error).toBeNull();+ expect(reclaims).toHaveLength(1);+ expect(existsSync(lock)).toBe(false);expect(git(root, 'rev-parse', ':notes/a.md')).toBe(git(root, 'rev-parse', 'HEAD:notes/a.md'));expect(leftovers(root)).toEqual([]);} finally { await writer.release(); }});});+ // Value: protects=index copies a refresh killed before its cleanup left in the git directory (and their Git locks) are removed by the next+ // refresh while it holds index.lock, once their process is gone, while a live process's copy stays (#7755); fails_when=nothing sweeps+ // index.gbrain-*, so each crash leaves an index-sized file; why_new=no test plants a stale copy; seam=none; no_claim=a reused pid+ test('index copies a killed refresh left are removed under the lock once their process is gone; a live process\'s copy stays', async () => {+ const root = seeded(), gitDir = join(root, '.git');+ const dead = spawnSync('true').pid;+ expect(() => process.kill(dead, 0)).toThrow();+ const stale = [`index.gbrain-${dead}-0123456789ab`, `index.gbrain-${dead}-0123456789ab.lock`], live = `index.gbrain-${process.ppid}-ba9876543210`;+ for (const name of [...stale, live]) writeFileSync(join(gitDir, name), 'a copy of the index');+ writeFileSync(join(root, 'notes/a.md'), 'door\n');+ expect(await commitThroughDoor(root, [{ path: join(root, 'notes/a.md'), planned: sha256('door\n') }])).toBe(git(root, 'rev-parse', 'HEAD'));+ expect(git(root, 'rev-parse', ':notes/a.md')).toBe(git(root, 'rev-parse', 'HEAD:notes/a.md'));+ expect(leftovers(root)).toEqual([live]);+ });++ // Value: protects=a dead process's leftover the sweep cannot remove (a directory here; EBUSY or EPERM on Windows) never fails the refresh+ // of a commit that landed (#7755 review); fails_when=the sweep's removal error ends the write with the landed git_unavailable failure and+ // leaves the index behind HEAD on every later write; why_new=the sweep test plants only removable files; seam=none; no_claim=a real EBUSY+ test('a stale index copy the sweep cannot remove is left in place and the refresh still completes', async () => {+ const root = seeded(), gitDir = join(root, '.git');+ const dead = spawnSync('true').pid;+ const stuck = `index.gbrain-${dead}-0123456789ab`;+ mkdirSync(join(gitDir, stuck));+ writeFileSync(join(gitDir, stuck, 'x'), 'x');+ writeFileSync(join(root, 'notes/a.md'), 'door\n');+ expect(await commitThroughDoor(root, [{ path: join(root, 'notes/a.md'), planned: sha256('door\n') }])).toBe(git(root, 'rev-parse', 'HEAD'));+ expect(git(root, 'rev-parse', ':notes/a.md')).toBe(git(root, 'rev-parse', 'HEAD:notes/a.md'));+ expect(leftovers(root)).toEqual([stuck]);+ });++ // Value: protects=on win32 a transient sharing violation (EPERM, EBUSY, EACCES) on the renames that commit the refreshed index is retried,+ // as Git for Windows retries its own, while other platforms fail at once as before (#7756); fails_when=one refused rename ends the write+ // with the landed failure on Windows, or a retry runs elsewhere; why_new=no Windows path was tested; seam=indexCommitIo (rename, platform);+ // no_claim=a real Windows sharing violation+ for (const platform of ['win32', 'linux'] as const) test(`a transiently refused index rename is retried on win32 only (${platform})`, async () => {+ const root = seeded(), before = git(root, 'rev-parse', ':notes/a.md');+ const renames: string[] = [];+ let refused = 0;+ Object.assign(indexCommitIo, { platform, rename: (from: string, to: string) => {+ renames.push(basename(to));+ if (refused++ < 2) throw Object.assign(new Error(`EPERM: operation not permitted, rename '${from}' -> '${to}'`), { code: 'EPERM' });+ renameSync(from, to);+ } });+ writeFileSync(join(root, 'notes/a.md'), 'door\n');+ const error = await refusal(commitThroughDoor(root, [{ path: join(root, 'notes/a.md'), planned: sha256('door\n') }]));+ expect(git(root, 'show', 'HEAD:notes/a.md')).toBe('door');+ if (platform === 'win32') {+ expect(error).toBeNull();+ expect(renames).toEqual(['index.lock', 'index.lock', 'index.lock', 'index']);+ expect(git(root, 'rev-parse', ':notes/a.md')).toBe(git(root, 'rev-parse', 'HEAD:notes/a.md'));+ } else {+ expect(error).toMatchObject({ code: 'git_unavailable', message: expect.stringContaining('landed, but the index'), suggestion: expect.stringContaining('EPERM') });+ expect(renames).toEqual(['index.lock']);+ expect(git(root, 'rev-parse', ':notes/a.md')).toBe(before);+ }+ expect(leftovers(root)).toEqual([]);+ });++ // Value: protects=the door keeps its index.lock descriptor open while it refreshes the index, so the #6932 abandoned-lock proof run at that+ // moment (an aged, empty lock, no git child running) names this process as the holder and never counts the lock abandoned (#7757);+ // fails_when=the descriptor is closed right after the create; why_new=every other door test passes with it closed early;+ // seam=doorSeams.indexLockHeld; no_claim=hosts where the proof cannot see every process (the test skips there)+ test.skipIf(processTableBlind() !== null)('the door holds its index.lock open during the refresh, so the abandoned-lock proof finds it held', async () => {+ const root = seeded(), lock = join(root, '.git', 'index.lock');+ let verdict: IndexLockVerdict | undefined;+ doorSeams.indexLockHeld = held => {+ const old = new Date(Date.now() - 60_000);+ utimesSync(held, old, old);+ verdict = proveIndexLockAbandoned(held, root, INDEX_LOCK_GRACE_FOR_TESTS);+ };+ writeFileSync(join(root, 'notes/a.md'), 'door\n');+ expect(await commitThroughDoor(root, [{ path: join(root, 'notes/a.md'), planned: sha256('door\n') }])).toBe(git(root, 'rev-parse', 'HEAD'));+ expect(verdict).toEqual({ abandoned: false, reason: expect.stringMatching(new RegExp(`^process ${process.pid} \\(.*\\) has the lock open$`)) });+ expect(existsSync(lock)).toBe(false);+ expect(git(root, 'rev-parse', ':notes/a.md')).toBe(git(root, 'rev-parse', 'HEAD:notes/a.md'));+ });++ // Value: protects=a close of the held index.lock that fails (EIO on a network filesystem) still ends in the landed failure and removes the+ // lock and the index copy (#7758); fails_when=the finally closes the released descriptor again, its EBADF escapes the landed failure and+ // skips the cleanup; why_new=no close failure was tested; seam=indexCommitIo.close; no_claim=a real EIO+ test('a failed close of the held index.lock still reports the landed commit and leaves no lock or index copy', async () => {+ const root = seeded(), before = git(root, 'rev-parse', ':notes/a.md');+ indexCommitIo.close = (fd: number) => { closeSync(fd); throw Object.assign(new Error('EIO: i/o error, close'), { code: 'EIO' }); };+ writeFileSync(join(root, 'notes/a.md'), 'door\n');+ const error = await refusal(commitThroughDoor(root, [{ path: join(root, 'notes/a.md'), planned: sha256('door\n') }]));+ expect(error).toMatchObject({ code: 'git_unavailable', message: expect.stringContaining('landed, but the index'), suggestion: expect.stringContaining('EIO') });+ expect(git(root, 'show', 'HEAD:notes/a.md')).toBe('door');+ expect(git(root, 'rev-parse', ':notes/a.md')).toBe(before);+ expect(leftovers(root)).toEqual([]);+ });});diff --git a/test/git-door-planned-state.test.ts b/test/git-door-planned-state.test.tsindex 3c1fea5125..660cb40b7b 100644--- a/test/git-door-planned-state.test.ts+++ b/test/git-door-planned-state.test.ts@@ -224,6 +224,42 @@ for (const backend of testBackends()) describe(`[${backend}] the door commits onexpect(git(root, 'rev-parse', `HEAD:${FILE}`)).toBe(git(root, 'hash-object', '--', FILE));expect(git(root, 'status', '--porcelain')).toBe('');}, { databaseUrl, setup }), 120_000);+ // Value: protects=a disk revert to the version before the write, landing during its publication, ends the write failed git_target_changed+ // with nothing committed, nothing held and no head blocker, so the source's later writes still commit (gbrain#7717 item 11);+ // fails_when=recovery holds a file that already holds its prior bytes, or the door commits the reverted bytes; why_new=D4 covers only an+ // edit that holds neither version; seam=none; no_claim=a revert landing after the door's second hash+ test('D4 variant: a disk revert to the prior bytes during the publication ends failed git_target_changed, holds nothing, and a later write commits', () => managedBrain(async ({ engine, ctx, root }) => {+ await committedPage(engine, ctx);+ const head = git(root, 'rev-parse', 'HEAD'), committed = git(root, 'rev-parse', `HEAD:${FILE}`), prior = readFileSync(join(root, FILE));+ const reverted = await publish(engine, ctx, page('Second'), { boundary: async name => { if (name === 'after_publication') writeFileSync(join(root, FILE), prior); } });+ expect(reverted).toMatchObject({ state: 'failed', error_code: 'git_target_changed' });+ expect(await getWriteRequestById(engine, reverted.id)).toMatchObject({ state: 'failed', error_code: 'git_target_changed', recovery: null, blocked_reason: null });+ expect(await standing(engine, root)).toEqual({ row: 'First', head: 'First', disk: 'First', index: committed });+ expect(git(root, 'rev-parse', 'HEAD')).toBe(head);+ expect(git(root, 'status', '--porcelain')).toBe('');+ expect(await publish(engine, ctx, page('Third'))).toMatchObject({ state: 'committed' });+ expect(await standing(engine, root)).toEqual({ row: 'Third', head: 'Third', disk: 'Third', index: git(root, 'rev-parse', `HEAD:${FILE}`) });+ }, { databaseUrl, setup }), 120_000);++ // Value: protects=a replay after a landed door commit, refused because someone staged the page meanwhile, says HEAD already holds its bytes+ // instead of claiming it committed nothing (gbrain#7717 item 9); fails_when=the refusal reads as if Git lacks the write; why_new=only the+ // plumbing half was tested; seam=publication boundary before_commit throws a dropped connection; no_claim=a replay whose blob HEAD lacks+ test('a replay after a landed commit, refused on a change staged meanwhile, says HEAD already holds its bytes', () => managedBrain(async ({ engine, ctx, root }) => {+ await committedPage(engine, ctx);+ let staged = '';+ const interrupted = await publish(engine, ctx, page('Second'), { boundary: async name => {+ if (name !== 'before_commit' || staged) return;+ staged = execFileSync('git', ['-C', root, 'hash-object', '-w', '--stdin'], { input: page('USER STAGED EDIT'), encoding: 'utf8', env }).trim();+ git(root, 'update-index', '--cacheinfo', `100644,${staged},${FILE}`);+ throw Object.assign(new Error('database interruption'), { code: 'CONNECTION_CLOSED' });+ } });+ expect(interrupted).toMatchObject({ state: 'queued' });+ const replay = await publishNext(engine, ctx);+ expect(replay).toMatchObject({ state: 'failed', error_code: 'git_index_conflict', error_message: expect.stringContaining('HEAD already holds this write\'s bytes') });+ expect(String(replay.error_message)).not.toContain('committed nothing');+ expect(await standing(engine, root)).toEqual({ row: 'First', head: 'Second', disk: 'Second', index: staged });+ }, { databaseUrl, setup }), 120_000);+// Generated by /ship Step 7 coverage audit (gstack), test-only.// Value: protects=a group publication puts git_index_restored on the receipt of the member whose stale entry it restored, and on no other;// fails_when=group-publish.ts drops onIndexRestored or maps the restored path to the wrong member; why_new=the stale-entry test above runs the@@ -276,7 +312,8 @@ describe('door plumbing: the planned state', () => {put(root, 'notes/a.md', 'someone else\n');put(root, 'notes/new.md', 'someone else\n');for (const [path, planned] of [['notes/a.md', sha256('planned\n')], ['notes/new.md', sha256('planned\n')], ['notes/a.md', null]] as const) {- expect(await refusal(commitThroughDoor(root, [{ path: join(root, path), planned }]))).toMatchObject({ code: 'git_target_changed', message: expect.stringContaining(path) });+ expect(await refusal(commitThroughDoor(root, [{ path: join(root, path), planned }]))).toMatchObject({ code: 'git_target_changed', message: expect.stringContaining(path),+ suggestion: expect.stringMatching(/stuck-recovery --json \(--source [^]*holds this write's bytes again by the time recovery runs, recovery restores the version before it/) });}expect(git(root, 'rev-parse', 'HEAD')).toBe(head);expect(git(root, 'diff', '--cached', '--name-only')).toBe('');@@ -312,6 +349,26 @@ describe('door plumbing: the planned state', () => {expect(git(root, 'status', '--porcelain')).toBe('');});+ // Value: protects=a path committed with a legacy mode (100664) gets no mode-only commit for its own bytes and no new tree entry with that mode,+ // which git fsck --strict flags badFilemode (gbrain#7717 item 13); fails_when=the edit skip or the core.fileMode=false fallback reads the raw+ // tree mode instead of its index form; why_new=the test above covers only the staged check; seam=none; no_claim=modes other than 100664+ for (const fileMode of ['true', 'false']) test(`a legacy-mode (100664) path makes no mode-only commit and keeps no 100664 entry, core.fileMode=${fileMode}`, async () => {+ const root = repo({ 'notes/a.md': 'a\n' });+ git(root, 'config', 'core.fileMode', fileMode);+ const blob = execFileSync('git', ['-C', root, 'hash-object', '-w', '--stdin'], { input: 'legacy\n', env, encoding: 'utf8' }).trim();+ const tree = execFileSync('git', ['-C', root, 'hash-object', '-t', 'tree', '--literally', '-w', '--stdin'],+ { input: Buffer.concat([Buffer.from('100664 legacy.md\0'), Buffer.from(blob, 'hex')]), env, encoding: 'utf8' }).trim();+ git(root, 'update-ref', 'refs/heads/main', git(root, 'commit-tree', tree, '-p', 'HEAD', '-m', 'legacy mode'));+ git(root, 'reset', '-q', '--hard');+ const head = git(root, 'rev-parse', 'HEAD');+ expect(await publishAt(root, 'legacy.md', 'legacy\n')).toBe(head);+ expect(git(root, 'rev-parse', 'HEAD')).toBe(head);+ expect(await publishAt(root, 'legacy.md', 'door\n')).toBe(git(root, 'rev-parse', 'HEAD'));+ expect(git(root, 'ls-tree', 'HEAD', '--', 'legacy.md')).toStartWith('100644 blob ');+ expect(git(root, 'show', 'HEAD:legacy.md')).toBe('door');+ expect(git(root, 'status', '--porcelain')).toBe('');+ });+test('a change staged after the check and before the index refresh is left staged; the refusal says the commit landed', async () => {const root = repo({ 'notes/a.md': 'a\n', 'notes/b.md': 'b\n' });let staged = '';diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex d09aaeca55..e454634a7b 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -133,6 +133,7 @@ test/ghost-pages-git-canonical-7967.test.tstest/git-canonical-conversion-g8a.test.tstest/git-canonical-conversion-live-writer.test.tstest/git-canonical-conversion-no-checkout-7885.test.ts+test/git-canonical-conversion-owner-root-7956.test.tstest/git-canonical-conversion-progress.test.tstest/git-canonical-conversion-strict-pass-7866.test.tstest/git-canonical-declared-g7a.test.tsdiff --git a/test/repair-stuck-recovery.test.ts b/test/repair-stuck-recovery.test.tsindex 3f101d1c77..0d95e5cb49 100644--- a/test/repair-stuck-recovery.test.ts+++ b/test/repair-stuck-recovery.test.ts@@ -164,6 +164,36 @@ describe('gbrain repair stuck-recovery', () => {expect(next.indexOf('--auto-additive')).toBeLessThan(next.indexOf(`gbrain sync --source ${s.sourceId} --no-pull`));}));+ for (const strict of [true, false]) {+ // Value: protects=on a git-canonical source the --keep disk follow-up says commit (or restore) then sync, with an ask_user fix whose verify is git status then sync status, and never sends the operator to a database-side reconcile; a mixed source keeps the reconcile follow-up and no fix; fails_when=nextStep ignores the source's mode; why_new=every --keep disk test ran on a mixed source; seam=none; no_claim=that the commit then imports (the door and sync tests cover it)+ test(`#7715: --keep disk on a ${strict ? 'strict (git-canonical)' : 'mixed'} source ${strict ? 'hands off to commit-then-sync, not reconcile' : 'keeps the reconcile follow-up'}`, () => run(async () => {+ const s = await stuck({ prior: PRIOR, after: AFTER, disk: EDITED });+ if (strict) await engine.executeRaw(`UPDATE sources SET config = config || '{"canonical":"git"}'::jsonb WHERE id=$1`, [s.sourceId]);+ const checkout = (await getWorktreeBinding(engine, s.sourceId, localHostId()))!.local_path!;+ const preview = await repair(s.sourceId);+ const result = await repair(s.sourceId, { apply: true, expect: preview.preview_hash, keep: 'disk' });+ expect(result.outcomes).toEqual({ resolved: 1 });+ expect(readFileSync(s.path, 'utf8')).toBe(EDITED);+ const detail = result.outcome_items![0]!.detail!;+ const next = String(detail.next);+ if (!strict) {+ expect(next).toContain(`gbrain sources reconcile ${s.sourceId} page --brain host --preview --auto-additive`);+ expect(detail.fix).toBeUndefined();+ return;+ }+ expect(next).not.toContain('sources reconcile');+ expect(next).toContain('the kept bytes are an uncommitted edit at page.md');+ expect(next).toContain(`gbrain git commit-push --path ${checkout} -m "<message>" -- page.md, then gbrain sync --source ${s.sourceId} --no-pull`);+ expect(next).toContain(`git -C ${checkout} restore -- page.md, then gbrain sync --source ${s.sourceId} --no-pull`);+ expect(next).toContain(`git -C ${checkout} status --porcelain -- page.md`);+ expect(next.indexOf('status --porcelain')).toBeLessThan(next.indexOf(`gbrain sync status --source ${s.sourceId} --json`));+ expect(detail.fix).toMatchObject({ ask_user: true, argv: ['gbrain', 'git', 'commit-push', '--path', checkout, '-m', '<MESSAGE>', '--', 'page.md'],+ inputs: [{ name: 'MESSAGE' }], verify: { argv: ['git', '-C', checkout, 'status', '--porcelain', '--', 'page.md'] },+ then: { argv: ['gbrain', 'sync', '--source', s.sourceId, '--no-pull'], verify: { argv: ['gbrain', 'sync', 'status', '--source', s.sourceId, '--json'] } } });+ expect(String((detail.fix as { user_message: string }).user_message)).toContain('Publish it');+ }));+ }+test('absent prior (the write was a create): the preview says so, and --keep prior unlinks the edited file after backing it up', () => run(async () => {const s = await stuck({ prior: null, after: AFTER, disk: EDITED });const out = await cli(['stuck-recovery', '--source', s.sourceId]);diff --git a/test/sources-ops.test.ts b/test/sources-ops.test.tsindex 2a91ef26a7..b430ead763 100644--- a/test/sources-ops.test.ts+++ b/test/sources-ops.test.ts@@ -4,7 +4,7 @@* coverage lives in test/e2e/sources-remote-mcp.test.ts.*/-import { test, expect, describe, beforeAll, afterAll, beforeEach } from 'bun:test';+import { test, expect, describe, beforeAll, afterAll, beforeEach, spyOn } from 'bun:test';import {mkdirSync,writeFileSync,@@ -1345,4 +1345,22 @@ describe('#7630 — a relative clone local_path never names the current directorexpect(readdirSync(dir)).toEqual(['KEEP_ME.md']);});});++ // #7646: the skipped cleanup is reported in the result (remote sources_remove sees only that) and the warning names gbrain's+ // own clone directory, which a later sources add <id> --url refuses while it holds files.+ test('removeSource reports clone_skipped_reason and names the clone directory it left', async () => {+ await insideRelativeClone('rel-orphan', { remote_url: 'https://github.com/example/repo', managed_clone: true }, async dir => {+ const cloneDir = defaultCloneDir('rel-orphan');+ mkdirSync(cloneDir, { recursive: true });+ writeFileSync(join(cloneDir, 'README.md'), 'the clone gbrain made');+ const errors: string[] = [];+ const spy = spyOn(console, 'error').mockImplementation((...a: unknown[]) => { errors.push(a.map(String).join(' ')); });+ let result: Awaited<ReturnType<typeof removeSource>>;+ try { result = await removeSource(engine, { id: 'rel-orphan', confirmDestructive: true }); } finally { spy.mockRestore(); }+ expect(result).toMatchObject({ clone_removed: false, clone_skipped_reason: 'relative_path' });+ expect(errors.join('\n')).toContain(`gbrain's clone directory for this source is ${cloneDir}`);+ expect(existsSync(join(cloneDir, 'README.md'))).toBe(true);+ expect(existsSync(join(dir, 'KEEP_ME.md'))).toBe(true);+ });+ });});diff --git a/test/stored-root-followups-7646.test.ts b/test/stored-root-followups-7646.test.tsnew file mode 100644index 0000000000..27ec57a6f0--- /dev/null+++ b/test/stored-root-followups-7646.test.ts@@ -0,0 +1,328 @@+/**+ * #7646: follow-ups to the #7630 relative stored-anchor refusal (#7640).+ *+ * Protects:+ * - a relative sync.repo_path behind a default row with no path never lets an explicit foreign --repo advance default's+ * last_commit (the commit-anchor guard refuses instead of bootstrapping), and the refusal names sources set-path;+ * - with a stored ".", sync --repo ./ is refused like --repo . (the relative --repo is compared after resolving);+ * - sync, sources set-path --clear and doctor read one "absolute on this host" predicate, so a Windows drive path on+ * POSIX and a root-relative path get the same verdict from all three;+ * - doctor's default_source_local_path survives a failed sibling scan and names every pathless source the relative+ * sibling keeps database-only;+ * - sync --all --json carries the refusal's code and fix per source, prices no relative source in the cost gate with+ * embedding on, and refuses a foreign-OS path the same way;+ * - a queued sync job on a relative anchor completes as a skip carrying the ask-the-user fix (no stored path);+ * - page and fact writes record the database-only reason relative_root;+ * - gbrain dream names the failed phase's ask-the-user fix instead of a rerun that refuses again.+ *+ * PGLite always; Postgres when DATABASE_URL is set (test/e2e/stored-root-followups-7646-postgres.test.ts).+ */+import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test';+import { execSync } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { isForeignAbsolutePath, isHostAbsolutePath } from '../src/core/path-confine.ts';+import { clearConnectorLocalPath } from '../src/core/persistence/connector-path.ts';+import { defaultSourceLocalPathCheck } from '../src/commands/doctor/checks/default-source-path.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++const SYNC = { noPull: true, noEmbed: true, noExtract: true, full: true };+const WINDOWS_PATH = 'C:\\brain-example';++describe('#7646: one absolute-path predicate per host', () => {+ const cells: Array<[string, NodeJS.Platform, boolean, boolean]> = [+ ['/srv/brain-example', 'linux', true, false],+ [WINDOWS_PATH, 'linux', false, true],+ ['\\\\server-example\\share', 'linux', false, true],+ ['.', 'linux', false, false],+ ['\\brain-example', 'linux', false, false],+ [WINDOWS_PATH, 'win32', true, false],+ ['C:/brain-example', 'win32', true, false],+ ['/c/brain-example', 'win32', true, false],+ ['\\\\server-example\\share', 'win32', true, false],+ ['\\brain-example', 'win32', false, false],+ ['/brain-example', 'win32', false, true],+ ['C:brain-example', 'win32', false, false],+ ['.', 'win32', false, false],+ ];+ for (const [path, platform, host, foreign] of cells) {+ test(`${JSON.stringify(path)} on ${platform}: absolute=${host}, foreign=${foreign}`, () => {+ expect(isHostAbsolutePath(path, platform)).toBe(host);+ expect(isForeignAbsolutePath(path, platform)).toBe(foreign);+ });+ }+});++for (const backend of testBackends()) {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;++ describe(`#7646 [${backend}]: stored-root follow-ups`, () => {+ let engine: BrainEngine, close: () => Promise<void>, home: string, folder: string, previousCwd: string;++ beforeEach(async () => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-7646-home-'));+ folder = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-7646-unrelated-')));+ writeFileSync(join(folder, 'notes.md'), '---\ntype: note\ntitle: Notes\n---\n\nA note that is not part of any brain.\n');+ ({ engine, close } = await isolatedSharedSkillsEngine(databaseUrl));+ previousCwd = process.cwd();+ process.chdir(folder);+ }, 120_000);++ afterEach(async () => {+ process.chdir(previousCwd);+ await close();+ rmSync(folder, { recursive: true, force: true });+ rmSync(home, { recursive: true, force: true });+ });++ const gitRepo = (prefix: string) => {+ const repo = realpathSync(mkdtempSync(join(tmpdir(), prefix)));+ execSync('git init -q && git config user.email [email protected] && git config user.name T', { cwd: repo, stdio: 'pipe' });+ writeFileSync(join(repo, 'kept.md'), '---\ntype: note\ntitle: Kept\n---\n\nA page of an absolute source.\n');+ execSync('git add -A && git commit -q -m initial', { cwd: repo, stdio: 'pipe' });+ return repo;+ };+ const sync = async (opts: Record<string, unknown>) => withEnv({ GBRAIN_HOME: home }, async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ return performSync(engine, { ...SYNC, ...opts }).then(() => null, (error: unknown) => error as { code?: string; message?: string; suggestion?: string; fix?: { argv?: string[] } });+ });+ const cli = async (run: () => Promise<unknown>) => {+ const lines: string[] = [];+ let exit: number | undefined;+ let refused: { code?: string } | undefined;+ const push = (...a: unknown[]) => { lines.push(a.map(x => (typeof x === 'string' ? x : JSON.stringify(x))).join(' ')); };+ const spies = [spyOn(console, 'log').mockImplementation(push), spyOn(console, 'error').mockImplementation(push),+ spyOn(process.stderr, 'write').mockImplementation(((chunk: unknown) => { lines.push(String(chunk)); return true; }) as never),+ spyOn(process, 'exit').mockImplementation(((code?: number) => { exit = code; throw new Error(`__exit__${code}`); }) as never)];+ try {+ await withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_SOURCE: undefined, GBRAIN_ALLOW_DEFAULT_WRITE: undefined }, run);+ } catch (error) {+ if (!String(error).includes('__exit__')) refused = error as { code?: string };+ } finally {+ for (const spy of spies) spy.mockRestore();+ }+ return { lines, exit, refused };+ };+ const runSync = (args: string[]) => cli(async () => { const { runSync } = await import('../src/commands/sync.ts'); await runSync(engine, args); });+ const envelopeOf = (lines: string[]) => JSON.parse(lines.find(line => line.startsWith('{"schema_version"'))!) as+ { sources: Array<{ source_id: string; status: string; error?: string; code?: string; fix?: { argv?: string[] } }>; error_count: number };++ // Value: protects=an explicit foreign --repo never advances default's last_commit when the only stored path is a relative+ // sync.repo_path; fails_when=sourceCommitAnchorAllowed treats the relative key as no identity and bootstraps;+ // why_new=the #7630 commit-anchor cases always store an absolute or relative default row; seam=none; no_claim=the repo_path repoint+ test('a relative sync.repo_path behind a pathless default row refuses the commit anchor and names set-path', async () => {+ const foreign = gitRepo('gbrain-7646-foreign-');+ try {+ await engine.setConfig('sync.repo_path', '.');+ expect((await engine.executeRaw<{ local_path: string | null }>("SELECT local_path FROM sources WHERE id='default'"))[0]!.local_path).toBeNull();+ const { sourceCommitAnchorAllowed, writeSyncAnchor } = await import('../src/core/sync-anchor.ts');+ expect(await sourceCommitAnchorAllowed(engine, 'default', foreign)).toEqual({ owns: false, configured: '.' });+ const { lines } = await cli(() => writeSyncAnchor(engine, 'default', 'last_commit', 'f'.repeat(40), undefined, foreign));+ expect((await engine.executeRaw<{ last_commit: string | null }>("SELECT last_commit FROM sources WHERE id='default'"))[0]!.last_commit).toBeNull();+ expect(lines.join('\n')).toContain('gbrain sources set-path default <absolute-directory>');+ } finally {+ rmSync(foreign, { recursive: true, force: true });+ }+ }, 120_000);++ // Value: protects=with a stored ".", --repo ./ is refused like --repo . (no .git, no import of the cwd);+ // fails_when=the explicit-repo exemption compares spellings, so ./ passes and the cwd is synced; why_new=the #7630 case passes+ // only "."; seam=none; no_claim=an absolute --repo (the explicit exemption, unchanged)+ test('sync --repo ./ with a stored "." is refused sync_anchor_relative like --repo .', async () => {+ await engine.executeRaw("UPDATE sources SET local_path='.' WHERE id='default'");+ for (const spelling of ['./', '.']) {+ const result = await runSync(['--repo', spelling, '--no-pull', '--no-embed', '--json']);+ expect(result.refused?.code).toBe('sync_anchor_relative');+ }+ expect(existsSync(join(folder, '.git'))).toBe(false);+ expect((await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM pages WHERE source_id='default'"))[0]!.n).toBe(0);+ }, 120_000);++ // Value: protects=sync, set-path --clear and doctor agree that a root-relative path is relative, and sync refuses a path absolute+ // only on Windows while --clear and doctor leave it to the host that set it (the #7630 verdict);+ // fails_when=--clear, doctor and sync disagree on "\brain", or a Windows drive path reads as relative;+ // why_new=#7630 pinned each reader separately; seam=none; no_claim=a Windows host (cells above cover the predicate there)+ test.skipIf(process.platform === 'win32')('a root-relative path gets one verdict from sync, --clear and doctor; a Windows drive path stays the other host\'s', async () => {+ await engine.executeRaw("UPDATE sources SET local_path=$1 WHERE id='default'", [folder]);+ await engine.executeRaw("INSERT INTO sources (id, name, local_path) VALUES ('win-host', 'win-host', $1), ('root-rel', 'root-rel', $2)", [WINDOWS_PATH, '\brain-example']);+ const foreign = await sync({ sourceId: 'win-host' });+ expect(foreign?.code).toBe('sync_anchor_relative');+ expect(foreign?.message).toContain('not an absolute path on this host');+ expect(await clearConnectorLocalPath(engine, 'win-host').then(() => 'cleared', (error: { code?: string }) => error.code)).toBe('invalid_params');+ const rootRelative = await sync({ sourceId: 'root-rel' });+ expect(rootRelative?.code).toBe('sync_anchor_relative');+ const check = await defaultSourceLocalPathCheck(engine);+ expect(check?.status).toBe('warn');+ expect(check?.message).not.toContain('win-host');+ expect(check?.message).toContain('source "root-rel" has the relative local_path "\brain-example"');+ expect(await clearConnectorLocalPath(engine, 'root-rel')).toEqual({ prior: '\brain-example', connector: false });+ }, 120_000);++ // Value: protects=doctor still reports default_source_local_path when the other-source scan fails; fails_when=the scan error+ // propagates and doctor's bare catch hides the whole check; why_new=no case injects a failing scan; seam=executeRaw throws+ // for the scan's SQL only; no_claim=a failure of the default row read itself (still best-effort in local-audits)+ test('doctor default_source_local_path survives a failed sibling scan and says it was not checked', async () => {+ await engine.executeRaw("UPDATE sources SET local_path='.' WHERE id='default'");+ const original = engine.executeRaw.bind(engine);+ const failing = new Proxy(engine, { get(target, key) {+ if (key === 'executeRaw') return async (sql: string, params?: unknown[]) => {+ if (sql.includes("id <> 'default' AND local_path IS NOT NULL")) throw new Error('scan failed in test');+ return original(sql, params);+ };+ return Reflect.get(target, key);+ } }) as BrainEngine;+ const check = await defaultSourceLocalPathCheck(failing);+ expect(check?.status).toBe('warn');+ expect(check?.message).toContain('default source local_path is the relative path "."');+ expect(check?.message).toContain("could not be read, so they were not checked (scan failed in test)");+ }, 120_000);++ // Value: protects=doctor names a pathless sibling as database-only when default has its own path and a relative sibling makes+ // the leak guard refuse every write under sync.repo_path; fails_when=the note is computed only when default has no path;+ // why_new=the #7630 case has a pathless default; seam=none; no_claim=the write path itself (write-through's leak guard)+ test('doctor names every live pathless source a relative sibling keeps database-only, not only default', async () => {+ const repo = gitRepo('gbrain-7646-repo-');+ const own = gitRepo('gbrain-7646-default-');+ try {+ await engine.executeRaw("UPDATE sources SET local_path=$1 WHERE id='default'", [own]);+ await engine.setConfig('sync.repo_path', repo);+ await engine.executeRaw("INSERT INTO sources (id, name, local_path) VALUES ('notes-a', 'notes-a', '.'), ('notes-c', 'notes-c', NULL)");+ const { otherSourceOwning } = await import('../src/core/write-through.ts');+ expect(await otherSourceOwning(engine, 'notes-c', join(repo, '.sources', 'notes-c', 'x.md'))).toBe('notes-a');+ const check = await defaultSourceLocalPathCheck(engine);+ expect(check?.status).toBe('warn');+ expect(check?.message).toContain('Until then, pages of "notes-c" (no local_path) are saved to the database only');+ } finally {+ rmSync(repo, { recursive: true, force: true });+ rmSync(own, { recursive: true, force: true });+ }+ }, 120_000);++ // Value: protects=sync --all --json gives a refused source its code and ask-the-user fix (single-source parity), for a "."+ // and for a Windows drive path on POSIX; fails_when=the per-source entry carries only free text; why_new=the #7630 --all+ // case asserts only the error text and seeds only "."; seam=none; no_claim=parallel import workers (--workers 1)+ test.skipIf(process.platform === 'win32')('sync --all --json carries code and fix for a relative and a Windows-absolute source', async () => {+ const repo = gitRepo('gbrain-7646-all-');+ try {+ await engine.executeRaw("UPDATE sources SET local_path='.' WHERE id='default'");+ await engine.executeRaw("INSERT INTO sources (id, name, local_path) VALUES ('notes-a', 'notes-a', $1), ('win-host', 'win-host', $2)", [repo, WINDOWS_PATH]);+ const { lines, exit } = await runSync(['--all', '--no-pull', '--no-embed', '--json', '--workers', '1']);+ const bySource = Object.fromEntries(envelopeOf(lines).sources.map(s => [s.source_id, s]));+ expect(bySource.default).toMatchObject({ status: 'error', code: 'sync_anchor_relative' });+ expect(bySource.default?.fix?.argv).toEqual(['gbrain', 'sources', 'set-path', 'default', '<dir>']);+ expect(bySource['win-host']).toMatchObject({ status: 'error', code: 'sync_anchor_relative' });+ expect(bySource['win-host']?.error).toContain('not an absolute path on this host');+ expect(bySource['win-host']?.fix?.argv).toEqual(['gbrain', 'sources', 'set-path', 'win-host', '<dir>']);+ expect(bySource['notes-a']?.status).not.toBe('error');+ expect(exit).toBe(1);+ expect(existsSync(join(folder, '.git'))).toBe(false);+ } finally {+ rmSync(repo, { recursive: true, force: true });+ }+ }, 120_000);++ // Value: protects=sync --all with embedding on never hands a relative source to the cost gate, which would walk and price the+ // cwd; fails_when=the --all fan-out guard (run.ts) is removed or moved after the gate; why_new=the #7630 --all case runs+ // --no-embed; seam=resolveSyncAllEmbedPlan spied to record its sources and stop; no_claim=what the estimate would cost+ test('sync --all with embedding on prices only the absolute source in the cost gate', async () => {+ const repo = gitRepo('gbrain-7646-gate-');+ try {+ await engine.executeRaw("UPDATE sources SET local_path='.' WHERE id='default'");+ await engine.executeRaw("INSERT INTO sources (id, name, local_path) VALUES ('notes-a', 'notes-a', $1)", [repo]);+ for (let i = 0; i < 5; i++) writeFileSync(join(folder, `page-${i}.md`), `---\ntype: note\ntitle: Page ${i}\n---\n\n${'word '.repeat(200)}\n`);+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'sk-test-7646' } });+ const fetchSpy = spyOn(globalThis, 'fetch').mockImplementation((async () => { throw new Error('#7646 test: no provider call'); }) as never);+ const embedBackfill = await import('../src/core/sync-embed-backfill.ts');+ const priced: string[][] = [];+ const gate = spyOn(embedBackfill, 'resolveSyncAllEmbedPlan').mockImplementation(async (_e, sources) => {+ priced.push(sources.map(s => s.id));+ return { stop: true } as never;+ });+ let fetchCalls: number;+ try {+ await runSync(['--all', '--no-pull', '--json', '--workers', '1']);+ } finally {+ fetchCalls = fetchSpy.mock.calls.length;+ gate.mockRestore();+ fetchSpy.mockRestore();+ resetGateway();+ }+ expect(priced).toEqual([['notes-a']]);+ expect(fetchCalls).toBe(0);+ expect(existsSync(join(folder, '.git'))).toBe(false);+ } finally {+ rmSync(repo, { recursive: true, force: true });+ }+ }, 120_000);++ // Value: protects=a queued sync job on a relative (or foreign-OS) anchor completes as a skip carrying the ask-the-user fix and no+ // stored path, so it does not fail and use up its attempts; fails_when=the handler rethrows sync_anchor_relative;+ // why_new=only sync_not_applicable had the skip; seam=none; no_claim=the dispatcher pre-skip (automaticSyncSkip)+ test.skipIf(process.platform === 'win32')('a sync job on a relative or foreign-OS anchor completes as a skip with the fix', async () => {+ const { makeSyncHandler } = await import('../src/core/minions/handlers/sync.ts');+ const job = (data: Record<string, unknown>) => ({ id: 1, name: 'sync', data, signal: new AbortController().signal }) as never;+ await engine.executeRaw("UPDATE sources SET local_path='.' WHERE id='default'");+ const relative = await cli(async () => {+ const result = await withEnv({ GBRAIN_HOME: home }, () => makeSyncHandler(engine)(job({ sourceId: 'default', pull: false, auto_embed_backfill: false })));+ expect(result).toMatchObject({ skipped: true, reason: 'sync_anchor_relative', source_id: 'default',+ fix: { argv: ['gbrain', 'sources', 'set-path', 'default', '<dir>'], ask_user: true } });+ });+ expect(relative.refused).toBeUndefined();+ await engine.executeRaw("INSERT INTO sources (id, name, local_path) VALUES ('win-host', 'win-host', $1)", [WINDOWS_PATH]);+ const foreign = await cli(async () => {+ const result = await withEnv({ GBRAIN_HOME: home }, () => makeSyncHandler(engine)(job({ sourceId: 'win-host', pull: false, auto_embed_backfill: false })));+ expect(result).toMatchObject({ skipped: true, reason: 'sync_anchor_relative', source_id: 'win-host' });+ expect(JSON.stringify(result)).not.toContain('brain-example');+ });+ expect(foreign.refused).toBeUndefined();+ expect(existsSync(join(folder, '.git'))).toBe(false);+ }, 120_000);++ // Value: protects=a page or fact write whose stored root is relative names that cause (relative_root), not "no repo+ // configured", and a remote write's warning points at set-path; fails_when=page admission files it under no_repo_configured+ // and the fact target sets no reason; why_new=#7630 asserted only that nothing was written to the cwd; seam=none;+ // no_claim=the managed (bound) path, which publishes through its binding+ test('page and fact writes on a relative root record the database-only reason relative_root', async () => {+ await engine.executeRaw("UPDATE sources SET local_path='.' WHERE id='default'");+ const { resolveFactWriteTarget } = await import('../src/core/persistence/fact-write-target.ts');+ expect(await resolveFactWriteTarget(engine, 'default', { local_path: '.', kind: null }, { fileBacked: false, remote: false }))+ .toEqual({ kind: 'publish', binding: null, databaseOnlyReason: 'relative_root' });+ await withEnv({ GBRAIN_HOME: home, GBRAIN_SOURCE: undefined }, async () => {+ const { operations } = await import('../src/core/operations.ts');+ const put = operations.find(o => o.name === 'put_page')!;+ const local = { engine, config: { engine: backend }, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: false, sourceId: 'default', deferEmbeds: true };+ const result = await put.handler(local as never, { slug: 'notes/kept-in-db', content: '---\ntype: note\ntitle: Kept\n---\n\nA page with no folder of its own.\n' }) as { write_through?: { skipped?: string } };+ expect(result.write_through?.skipped).toBe('relative_root');+ });+ expect(existsSync(join(folder, 'notes'))).toBe(false);+ const { withNoRepoWriteThroughWarning } = await import('../src/core/write-through.ts');+ expect(withNoRepoWriteThroughWarning<{ written: boolean; skipped?: string; warning?: string }>({ written: false, skipped: 'relative_root' }, 'default').warning).toContain('gbrain sources set-path default <absolute-directory>');+ }, 120_000);++ // Value: protects=gbrain dream on a relative default row names the sync phase's ask-the-user step instead of telling the user to+ // rerun the phase, which refuses again; fails_when=the cycle_failed line keeps the generic rerun advice; why_new=#7630 pinned+ // the phase result only; seam=none; no_claim=the --json envelope (needs the CLI's JSON guard; same askPhase lookup)+ test('gbrain dream names the failed sync phase\'s ask-the-user fix', async () => {+ const repo = gitRepo('gbrain-7646-dream-');+ try {+ await engine.executeRaw("UPDATE sources SET local_path='.' WHERE id='default'");+ await engine.setConfig('sync.repo_path', repo);+ process.chdir(repo);+ const { lines, exit } = await cli(async () => { const { runDream } = await import('../src/commands/dream.ts'); await runDream(engine, ['--dir', repo, '--phase', 'sync']); });+ expect(exit).toBe(1);+ const text = lines.join('\n');+ expect(text).toContain('the sync phase needs the user before it can run');+ expect(text).toContain('gbrain sources set-path default <absolute-directory>');+ expect(text).not.toContain('re-run one with: gbrain dream --phase sync');+ } finally {+ process.chdir(folder);+ rmSync(repo, { recursive: true, force: true });+ }+ }, 120_000);+ });+}diff --git a/test/terminal-failures-6650.test.ts b/test/terminal-failures-6650.test.tsindex a2779033a9..1143d03ef4 100644--- a/test/terminal-failures-6650.test.ts+++ b/test/terminal-failures-6650.test.ts@@ -38,6 +38,31 @@ const base: TerminalInput = { source_id: 'src', slug: 'notes/a', operation: 'putblocked_reason: null, compacted: false };describe('classifyTerminal', () => {+ // #7646: a fault no sync and no caller retries must not advertise a retry; a compacted put_page (intent kind gone, so it may be+ // a reconcile or managed write) gets the inspect, never the resubmit advice.+ test('safe_actions follow the fix on non-sync faults, and a compacted put_page gets the inspect only', () => {+ const stalled = { ...base, error_code: 'preparation_stalled' };+ const live = classifyTerminal(stalled)!;+ expect(live.safe_actions).toEqual(['retry', 'upgrade']);+ expect(live.action.why).toContain('resubmit the same put_page with a new request_id');+ const compacted = classifyTerminal({ ...stalled, compacted: true, intent_kind: null })!;+ expect(compacted.action.argv).toEqual(['gbrain', 'sources', 'writer', 'status', '--source', 'src', '--json']);+ expect(compacted.action.why).not.toContain('resubmit');+ expect(compacted.safe_actions).toEqual(['none']);+ const facts = classifyTerminal({ ...stalled, operation: 'extract_facts' })!;+ expect(facts.action.why).toContain('it was not part of a sync');+ expect(facts.safe_actions).toEqual(['none']);+ expect(classifyTerminal({ ...stalled, operation: 'submit_job' })!.safe_actions).toEqual(['retry', 'upgrade']);+ });++ test('a retryable fault on a caller-submitted loop, proposal, trust or relink write keeps its resubmit advice', () => {+ for (const operation of ['loops_close', 'decide_proposal', 'trust_owner_page', 'trust_release', 'relink_facts']) {+ const verdict = classifyTerminal({ ...base, error_code: 'preparation_stalled', operation })!;+ expect(verdict.action.why).toContain(`resubmit the same ${operation} with a new request_id`);+ expect(verdict.safe_actions).toEqual(['retry', 'upgrade']);+ }+ });+test('routes storage_error by origin, and an origin-less compacted one is diagnosis_required', () => {expect(classifyTerminal({ ...base, error_code: 'storage_error', error_detail: { origin: 'owner_exception', error_class: 'TypeError' } })).toMatchObject({ category: 'owner_exception', defect: true, needs_human: true });@@ -470,6 +495,8 @@ for (const kind of testBackends()) describe(`the aggregate, doctor and the drillif (rows.status !== 'ok') throw new Error('unknown');expect(rows.rows!.length).toBe(g.rows);expect(rows.rows!.map(r => r.operation)).toEqual(['put_page']);+ // #7646: a consumer that re-queries with the group's filter object gets the same rows as its drill-down.+ expect(g.filter).toMatchObject({ operation: 'put_page' });}});diff --git a/test/url-clone-fences-private-hold-7897.test.ts b/test/url-clone-fences-private-hold-7897.test.tsindex 5b93d149ce..372ef8cd63 100644--- a/test/url-clone-fences-private-hold-7897.test.ts+++ b/test/url-clone-fences-private-hold-7897.test.ts@@ -127,6 +127,17 @@ for (const { backend, databaseUrl } of arms) describe(`[${backend}] repair url-c});}, 180_000);+ // Value: protects=a held file is an apply item, not also a residual, and its preview says sync will not re-screen the restored file (no hold appears); fails_when=residuals count every non-fence_rows_only class, or the detail promises a sync hold; why_new=#7910; seam=none; no_claim=the apply (covered above)+ test('#7910: a held file is listed once, as an apply item and not a residual, and its preview says the restored file is not re-screened', async () => {+ await withClone(databaseUrl, 'Visibility: private\n', async c => {+ const preview = await repair(c.engine, { apply: false });+ expect({ affected: preview.affected, residuals: preview.residuals }).toEqual({ affected: 1, residuals: {} });+ const detail = preview.listing![0]!.detail!;+ expect(detail).toContain('sync does not screen it again and records no hold');+ expect(detail).not.toContain('sync holds the file');+ });+ }, 180_000);+test('an approval saved before the fix applies as held: the file is restored and its row kept database-only, HEAD is not imported', async () => {await withClone(databaseUrl, 'visibility: Private\n', async c => {const page = await c.page();