Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge #9035 head d9065aba91 into the persistence train

garrytana79de8a6fc44
diff --cc CHANGELOG.md
index 2c9e35f42a,31c19c13f1..9a3b90cdb3
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -10,501 -10,52 +10,547 @@@ credits are retained; no result has bee
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+ ## [Unreleased]
+
+ **Persistence, sync and job fixes, most from community bug reports and each reproduced on master: sync timeouts stop cleanly, held and deleted files release, Postgres pools and deadline reads stop leaking or hanging, derived effects stop reporting false recoveries, and fix commands print what a retry needs.** `gbrain sync --timeout N` now stops as a partial run with exit 0 instead of being killed by its own watchdog, a held deleted file whose page was soft-deleted no longer stays `needs_human`, and `gbrain git commit-push` publishes a staged deletion under a wildcard-ignored folder. A Postgres pool that finishes opening after a reconnect is closed instead of leaking, a managed-sync preparation read gives up at its deadline instead of waiting on a saturated pool, and the sync cost check no longer scans every chunk when nothing has drifted. A `links` or `facts-backstop` effect that meets another write's publication in flight waits as `writer_busy` and retries within a second, instead of reporting `recovery_required` and waiting 30 s. A refused edit's fix command now prints the revision the retry needs, keyless init suggests an import that runs, cancelling a finished job changes nothing, and particle-1 on OpenRouter stops truncating.
+
+ ### Itemized changes
+
+ #### Sync timeout partials, deletion holds, ignored-dir deletions, git effect parking, snapshot generations (#8976)
+
+ - `src/core/sync-reconcile.ts`, `src/commands/sync-delegate.ts`, `src/commands/sync/plain-directory.ts`: the `--timeout N` hard-deadline backstop arms one grace window after N, so the in-band stop always lands first; a delegated job keeps its own bound at N; a plain-directory source stopped by the timeout reports `Sync PARTIAL` (`reason=timeout`) with exit 0 instead of `internal_error: import aborted`. Reported and first fixed by @zkiihne (supersedes #7819).
+ - `src/core/persistence/sync-pass.ts`: a `concurrent_write` hold whose file is gone joins the deletion candidates, so the existing no-live-page check (by id and slug) releases it; a hold whose page is still live stays held. Reported and first fixed by @Masashi-Ono0611 (#8751, supersedes #8753).
+ - `src/core/git/commit-push.ts`: named paths that cover index entries stage with `add -u`, visible untracked paths with `add -A`, and a path already staged as deleted counts as staged; only the named paths are committed, a mistyped or ignored-only path still refuses, and a refusal restores the index. Reported and first fixed by @Masashi-Ono0611 (#7984, supersedes #7987).
+ - `src/core/persistence/effects.ts`: a grouped Git completion failure is recorded against its effect's target, so per-target failures accumulate to the parking threshold instead of resetting to 1. Reported and first fixed by @Masashi-Ono0611 (#8606, supersedes #8631).
+ - `src/core/page-body/ingest.ts`, `src/core/persistence/segmented-apply.ts`: `materializedSnapshot` reads the snapshot's own body generation; when that generation's rows are gone it refuses `page_body_rows_unreadable` instead of returning a newer body. Reported and first fixed by @javieraldape (#8492, supersedes #8501).
+ - `src/core/persistence/types.ts`, `src/core/persistence/verb-errors.ts`: `page_body_rows_unreadable` is a write error code with its own non-retryable diagnostic instead of `storage_error`. Reported and first fixed by @babyspectrum (#8522, supersedes #8551).
+ - Docs: `docs/guides/shared-checkout-git.md`, `docs/guides/write-refusals.md`, key-files entries.
+ - Tests: `test/sync-timeout-watchdog-order.test.ts`, `test/sync-concurrent-write-deleted-hold-8751.test.ts` (PGLite and Postgres), `test/commit-push-ignored-deletion-7984.test.ts`, `test/persistence-effect-git-group-failure-8606.test.ts`, `test/large-pages/snapshot-body-generation-8492.test.ts`, `test/memory-write-rows-unreadable-8522.test.ts`; pinned deadline expectations in `test/sync-hard-deadline.test.ts` and `test/sync-timeout-cli-dispatch.test.ts` move by the grace window.
+
+ #### Late pool leak, preparation deadlines, type cache churn, stale-chunk scan, adoption recovery, timeline batches, export and init retries (#8980)
+
+ - `src/core/connection-manager.ts`: `disconnect()` and `retire()` bump an epoch; a direct or session-fallback pool that finishes initializing after either is ended (bounded) and its waiters get `CONNECTION_ENDED`, and a late failure starts no retry. Reported and first fixed by @javieraldape (#8478, supersedes #8569).
+ - `src/core/postgres-engine/bounded-statement.ts`, `src/core/read-deadline.ts`, `src/core/persistence/bounded-reads.ts`: a deadline read refuses once expired, reserves with an abort signal at the deadline, and discards a connection whose COMMIT is still pending; the refusal surfaces as `preparation_deadline`. Reported and first fixed by @javieraldape (#8651, supersedes #8698).
+ - `src/core/pg-type-cache.ts`: re-describing a statement with the same parameter types no longer marks the cache dirty. Reported and first fixed by @Masashi-Ono0611 (#8647, supersedes #8657).
+ - `src/core/engine-sql/chunks.ts`: with a signature, `sumStaleChunkChars` sums disjoint unembedded and drifted arms through UNION ALL, so the partial stale index serves the common case (measured 100 ms to 12 ms on a 200k-chunk fixture with no drift); totals are unchanged. Reported and first fixed by @Masashi-Ono0611 (#8811, supersedes #8813).
+ - `src/core/persistence/coordinator.ts`, `src/core/persistence/local-edit-adoption.ts`: adoption recovery gathers its landed-commit proof before the recovery transaction and rechecks HEAD and the request's pin under the row lock, staying `recovery_required` on any change. Reported and first fixed by @javieraldape (#8869, supersedes #8914).
+ - `src/commands/extract.ts`: sync's inline timeline extraction writes each page's rows through one batch projection (same trust gate and dedup), falls back to row-by-row only when the batch fails, and counts rows actually inserted. A missing or soft-deleted page still fails its slug with `PageMissingError`, checked under a page lock inside the batch transaction. Reported and first fixed by @troyhoffman-oss (supersedes #6805).
+ - `src/core/shared-skills/migration-export.ts`: an exported or inventory-stage checkpoint with no bound source and no started topology claim can move to a new root, restarting at inventory with a fresh request; a bound or claimed checkpoint still refuses. A root refused for sitting inside a Git worktree is now checked before anything is staged, so no copy of the export is left in the repository; an earlier staging directory is removed only when it holds exactly the export's own files, and an earlier filled root is listed in the receipt (`earlier_roots`) and the printed next steps. Reported and first fixed by @Masashi-Ono0611 (#8528, supersedes #8628).
+ - `src/core/shared-skills/setup.ts`: `installPackagedSharedSkills` resumes the caller's open or committed default-pack publication in the same source incarnation instead of submitting a second one. Reported and first fixed by @javieraldape (#8453, supersedes #8493).
+ - Docs: key-files entries. `scripts/structural-suites.tsv` regenerated.
+ - Tests: `test/connection-manager.serial.test.ts`, `test/e2e/engine-open-postgres.test.ts`, `test/postgres-deadline-read.test.ts`, `test/e2e/persistence-preparation-pool-wait-postgres.test.ts`, `test/pg-type-cache.test.ts`, `test/sum-stale-chunk-chars-8811.test.ts` (PGLite and Postgres), `test/adopt-local-edit.test.ts`, `test/extract-timeline-for-slugs-batch.test.ts`, `test/shared-skills-export.serial.test.ts`, `test/shared-skills-packaged-key-7734.test.ts`.
+
+ #### Derived effects wait as `writer_busy` behind a publication in flight (#8754)
+
+ - `src/core/persistence/effects.ts`: the effect guard tells a publication in flight (its request `running` with a live claim, or already terminal with its record not yet cleared) from one that needs recovery. An effect that does not hold the worktree lock and meets only publications in flight is requeued `writer_busy` with the existing busy backoff (250 ms doubling, at most 60 s, never parked). A record whose publisher's claim lapsed, or a request in `recovering`, still requeues it `recovery_required`, and an effect that holds the lock (Git, withdrawal mirror) is unchanged. An `embedding` effect in the same wait records `writer_busy` too, on its unchanged retry schedule. Nothing was lost before (the next effect pass after the 30 s delay derived the links), but the receipt said a recovery was needed when none was.
+ - `test/persistence-derived-effect-publication-race.test.ts` (PGLite, and PostgreSQL through `test/e2e/persistence-derived-effect-publication-race-postgres.test.ts`): drives a real put_page publication to its `prepared` and `after_commit` boundaries between a links effect's claim and its guard, and checks the effect waits as `writer_busy` with a delay under 5 s, then commits its link on the next pass; with the publisher's claim lapsed it stays `recovery_required` and still links once the record settles.
+
+ #### Fix commands print the revision a retry needs, keyless init hint, finished job trees, particle-1 headroom (#8909)
+
+ - `src/core/error-registry.ts`, `src/cli/page-render.ts`: the fix for `revision_required`, `revision_conflict` and `page_identity_changed` is now `gbrain get --include-content ...`, and that read prints `[gbrain] revision <rev>: put or delete this page with --expected-revision <rev>.` on stderr; before, the suggested `gbrain get -- <slug>` printed only frontmatter and body. `docs/guides/error-codes.md` follows.
+ - `src/commands/init.ts`: `gbrain init --pglite --no-embedding` now suggests `gbrain import <dir> --no-embed`, which runs on that brain, instead of an import that refuses because embeddings are off.
+ - `src/core/minions/worker.ts`: a quiet-hours skip no longer rewrites an already-cancelled job's reason to `skipped_quiet_hours`.
+ - `src/core/minions/queue.ts`: cancelling a job that already finished refuses and changes nothing (it used to cancel the job's still-live children while reporting that it could not cancel); submitting a child under a parent that already completed, failed, died or was cancelled refuses; both `fail_parent` updates clear the parent's lock. A behavior-notice row discloses the cancel and submit changes.
+ - `src/core/pglite-engine/code-edges.ts`: `getEdgesByChunk` on PGLite binds the edge-type filter on every arm with one `LIMIT` per table, matching Postgres.
+ - `src/core/ai/recipes/openrouter.ts`: `particle-ai/` models get thinking headroom on OpenRouter, so `thinking: 'off'` calls no longer truncate at 2,048 tokens. No default model changes.
+ - `src/core/behavior-change-notice.ts`, `docs/guides/write-refusals.md`: the `refresh_replan_own_commits_8828` notice and the `refresh_source_changed` row now match the code (text only; the row's `since` is unchanged).
+ - Tests: `test/revision-fix-command-shows-revision.test.ts`, `test/init-keyless-import-hint.test.ts`, `test/worker-quiet-hours-skip-keeps-cancelled.test.ts`, `test/code-edges.test.ts`, `test/ai/recipe-openrouter.test.ts`, `test/minion-cancel-failed-parent.test.ts`, `test/minion-child-of-finished-parent.test.ts`, `test/minion-fail-parent-clears-lock.test.ts`, `test/write-receipt-remediation.test.ts`.
+
+## [0.60.657.0] - 2026-11-11
+
+**A running `gbrain serve`, worker or autopilot no longer fails writes after another process changes a table's columns (GST-2260).** When `gbrain apply-migrations` or an upgrade in another process added, renamed or dropped a column, every pooled connection that had already prepared a `SELECT *` or `RETURNING *` on that table failed its next run with "cached plan must not change result type". Outside a transaction the driver quietly prepared the statement again, but inside one the error had already aborted the transaction, so the caller saw it. A `put_page` came back `internal_error`, or was accepted and then failed at publication, once for each statement on each pooled connection. Version 0.60.646.0 made the write paths re-run the transaction it aborted. Now the first such error also makes every connection in the process prepare its statements again before its next query, and an OAuth token grant whose client read meets it and a minion job's completion or failure record are re-run too. Pools that do not prepare statements (transaction-mode pooler URLs, `prepare: false`) and PGLite are unchanged.
+
+### Itemized changes
+
+- `vendor/postgres` (`patches/[email protected]`): the first `RevalidateCachedQuery` error on a statement a connection had cached starts a process-wide plan generation; each connection drops its prepared statements before it builds its next query, and a statement described under an older generation is not cached in the new one.
+- `src/core/retry-matcher.ts`: `retryOnStalePlan`, one more run, on 0.60.646.0's `isStalePlanError`, for a transaction that does only database work.
+- `src/core/oauth-grants.ts`: the client-locked OAuth grant transaction runs once more when a stale plan fails its opening client read, before the callback writes anything.
+- `src/core/minions/queue.ts`: `completeJob` and `failJob`, whose transactions do only database work, run once more after a stale plan.
+- Tests: `test/stale-plan-heal.test.ts` (Postgres; listed in `test/postgres-unit-arms.txt`).
+
+## [0.60.656.0] - 2026-11-11
+
+**`gbrain upgrade` finishes on hosts where autopilot runs outside launchd and systemd, instead of refusing every time.**
+
+The upgrade restarted autopilot only through an installed launchd or systemd service, and refused (`restart_refused`, exit 3) for any other autopilot. That included gbrain's own Linux cron install (`gbrain autopilot --install` on a host without a user systemd bus), so a scheduled stable upgrade on such a host failed on every run. An autopilot whose launcher starts it again is now handed to that launcher. The upgrade stops it (only while `ps` still shows the same process; SIGTERM drains it) and waits up to six minutes for the launcher to start the installed build.
+
+| Situation | Before | Now |
+|---|---|---|
+| Autopilot started by this brain's gbrain cron line | `restart_refused` | handed to the cron line and verified back on the new build |
+| Autopilot started by your own cron entry or wrapper | `restart_refused`, fix `kill <pid>` | still refuses, naming `gbrain autopilot --install` or `gbrain config set self_upgrade.autopilot_launcher external` (declare it only when the launcher starts autopilot again within 5 minutes); declared, it is handed over like the cron line |
+| doctor `self_upgrade_health` | silent until an upgrade failed | runs the same pre-swap plan read-only: warns while `gbrain upgrade` would refuse, naming each process and its step (autopilot outside gbrain's service, a process from another install), and names a hand-off or a second Bun global install the upgrade replaces itself; a harness MCP server does not warn (`--stop-mcp` stops it), and a held or failed auto-upgrade is reported first |
+
+On a host whose autopilot runs from gbrain's cron line, the old binary still refuses with `restart_refused` on the way to this release, because it checks the restart before it installs. Run `gbrain upgrade --no-restart`, then `gbrain upgrade --restart-only`, so the new build does the hand-off.
+
+**The daily stable check no longer sticks on a rolled-back release.** A release that was stable before (its `stable-v<version>` record tag exists) or that `stable.json` lists in `known_bad` is skipped and logged, so the newest release gets its soak instead of a refused promotion on every scheduled run (#8792).
+
+**A release can be marked not promotable when it soaked clean but is known bad from outside evidence.** Dispatch `promote-stable.yml` for the current stable with `not_promotable`, `not_promotable_reason` and `not_promotable_fixed_in`. The stable record gains a `not_promotable` list, and no tag moves. The daily check never soaks or promotes a release on it, on the important path and the weekly floor alike, and a manual promotion of one is refused. Clients ignore the list, so unlike `withdraw` it moves no install to another release. `not_promotable_remove` takes a release off the list. A reason over 500 characters is refused, and so is a record larger than clients accept; nothing is pushed in either case.
+
+## [0.60.655.0] - 2026-11-10
+
+**QM, the AI helper that uses gbrain as one of its memories, can now read a person's own brain safely, read shared rooms only as the room's audience, and suggest edits that wait for the brain owner's yes.** This lands the QM internal-provider chain (#8475, #8480, #8557, #8477, #8483, #8479, #8466) as one release. Nothing changes for a brain with no attested (`x-qm-actor`) client: unattested calls and member-bound credentials behave as before, and every new table is database state, so a repo-less brain works the same.
+
+### What changed
+
+| Area | Before | Now |
+|---|---|---|
+| Direct page writes from QM | an attested call could run `add_timeline_entry`, `add_link`, `put_page` and `edit_page` | refused (`actor_not_attested`, reason `op_not_attested`); `--attest-ops` refuses a list that names one, and a queued attested write of one fails when it publishes |
+| Reads that name sources | only `memory_recall` read named sources as their audience | `get_page`, `entity`, `whois`, `get_backlinks`, `get_timeline`, `find_experts`, `volunteer_context` and `query` do too: restricted pages and member pages read as missing, and `__all__` or `all_sources` is refused; an agent job submitted for the person reads the same way, and `context_pack` naming sources is refused on a client that reads them as the scope |
+| How a client reads named sources | always as the audience | `gbrain auth rescope --attest-read person\|scope\|none`; `scope` also refuses any call that names no person; `gbrain doctor` warns (`attest_read_shared_scope`) when a person client reads a source a scope client reads |
+| A person's own DM sources | every attested caller with the grant read every DM source in it | `gbrain access member source add\|remove\|list` binds a source to its member; an attested call reads its grant minus other members' personal sources, and a scope read reads no personal source at all |
+| QM contract | v1 and v2 | v3 (`docs/contracts/qm-memory-provider/v3.json`) adds the person's own-DM tools with frozen result shapes, `structuredContent` on attested personal reads (re-measured against the result cap), an `arm` (`own`/`ranked`) on each `memory_recall` fact, and an opt-in `memory_recall` `query_keep` (`head`/`tail`) that adds `query_truncated`; v1 is byte-identical, and v2 changes only its `deferred_ops` list and its `unknown_arguments` wording |
+| Suggested edits | none | `memory_propose` holds one timeline entry or one link for the owner; `gbrain memory-proposals list\|show\|approve\|deny` on the brain host decides it, and approval publishes through the normal writer door with the member's id in its provenance |
+| Members | id and name | an operator-declared email (`gbrain access member add\|set --email`), and `gbrain access member link --email <addr> --qm <id>` |
+| Remote owner administration | a shell on the brain host | `gbrain mcp admin attest`, `member-add\|member-set\|member-disable\|member-enable\|members` and `link\|unlink\|links` over the owner-session routes `/admin/api/access/attest`, `/members` and `/member-links`; no OAuth token or MCP tool reaches them |
+
+### Itemized changes
+
+- `src/core/access/actor-model.ts`: the four page writes join `ACTOR_DEFERRED_OPS`; `docs/contracts/qm-memory-provider/v2.json` lists them in `deferred_ops` (a published-contract amendment).
+- `src/core/access/scope-read.ts` (new), `src/mcp/dispatch.ts`: `SCOPE_READ_ACCESS`, `SCOPE_READ_OPS`, `attestedReadMode`, also applied to agent job tool calls (`src/core/minions/tools/brain-allowlist.ts`); `attest_read` on `access_tokens` and `oauth_clients` (migration v298).
+- `src/core/access/member-sources.ts` (new): `access_member_sources` (migration v299) and `attestedReadScope`, also applied to agent jobs submitted for an attested actor.
+- `scripts/build-qm-memory-contract.ts`: v2 and v3 `transport.unknown_arguments` now say what every MCP read has done since v0.60.635.0: an undeclared argument named like a source scope or a filter (`source` for `source_id`) is refused with `invalid_params` and nothing is read, and any other undeclared read argument is only reported in `_meta.warnings`. Wording only; `test/qm-memory-contract.test.ts` pins it against the refusal check.
+- `src/core/ops/qm-memory.ts`, `scripts/build-qm-memory-contract.ts`: contract v3, `qmMemoryToolResult` for personal tools, recall arms, `query_keep`, and `boundRecallChars` trimming `facts_groups` and `entity_unspecified` to the facts it delivers.
+- `src/core/persistence/memory-proposals.ts` (new), `src/commands/memory-proposals.ts` (new): `memory_proposals` (migration v300), owner review, TTL and retention; a proposal's request id is scoped to its credential and member, and a proposed link re-checks its target and the approved page revision when it publishes.
+- `src/core/access/members.ts`, `src/core/access/actor.ts`, `src/commands/access.ts`, `src/commands/serve-http-access.ts`, `src/commands/mcp-admin.ts`: member email (migration v301), `linkMemberByEmail`, and the owner HTTP routes with an `access_admin` request-log row per applied change.
+- Inventories: `access_member_sources`, `memory_proposals` and the email column join the deletion and graduation inventories.
+- Docs: `docs/guides/qm.md` (reads that name sources, each person's own sources, proposed writes), `docs/mcp/ADMIN.md`, `docs/architecture/key-files/access.md`.
+- Tests: `test/qm-scope-read.test.ts`, `test/qm-personal-sources.test.ts`, `test/qm-personal-tools.test.ts`, `test/qm-memory-propose.test.ts`, `test/access-members.test.ts`, `test/serve-http-access.test.ts`, `test/mcp-admin-cli.serial.test.ts` (PGLite and Postgres where they touch the database).
+
+## [0.60.654.0] - 2026-11-10
+
+**A managed sync no longer fetches Git objects in a partial clone (`git clone --filter`).** Every Git read a managed sync makes now runs with Git's transports and lazy fetching switched off. A file whose blob the clone never fetched is imported from your checkout when the checkout holds exactly that blob, and otherwise held alone as `git_object_missing`, with a message that names the partial clone and the `git cat-file -p <blob>` that fetches it. A blobless clone with a normal checkout syncs every file as before; an older object it never fetched (an earlier version of a renamed file or of the folder rules) is read only once you fetch it. A treeless clone (`--filter=tree:0`) that lacks a tree of the commit being synced stops the run with `git_object_missing`, naming the partial clone and the `git ls-tree -r -d <commit>` that fetches the trees; nothing is synced or deleted until then. The folder rules in `.gbrain/access.yml` are read the same way. A rule file or rule history the clone has not fetched makes the source read as nobody to remote members, as a shallow checkout already does, with a message that names the exact `git` command that fetches it. Run that command in the checkout and the next sync applies the rules and clears the mark.
+
+### Itemized changes
+
+- `src/core/hardened-git.ts`: `NO_LAZY_FETCH_ENV` is what a managed-sync read that runs under `gitChildEnv` adds beside `HARDENED_GIT_ARGS`: `GIT_NO_LAZY_FETCH=1` (Git 2.45+) and an empty `GIT_ALLOW_PROTOCOL`, which allows no transport on any Git version.
+- `syncGit` and `syncGitAsync` (`sync-discovery.ts`), every read in `sync-blobs.ts` (`ls-tree`, `cat-file --batch`), the `git show` fallback, the delta and working-tree diff (`sync-delta.ts`), the rename-identity `cat-file` stream, the metafile head reads, the origin-evidence history walk and ignore check, the held-deletion read, the unindexed-file listing and the pending-import checks now run with both.
+- `src/core/persistence/sync-entry-fault.ts`: in a partial clone the `git_object_missing` hold names the partial clone and its fix is `git cat-file -p <blob>`; in any other checkout it still names `git fsck --connectivity-only`.
+- A partial clone with no checkout (`--no-checkout`) holds every committed file `git_object_missing`. When rename detection needs an older blob the partial clone lacks, the sync compares the whole tree instead, so the new path imports as a new page and the old page is deleted, and that rename does not keep its page.
+- `src/core/access/policy-git.ts`: the folder-rule reads every managed pass makes (`git show` and `git log` of `.gbrain/access.yml` and `.gbrain/access.approved`, and a rebuild's history replay) now run under `HARDENED_GIT_ARGS` and `NO_LAZY_FETCH_ENV` too; before, they were a managed-sync read that could still fetch in a partial clone. A policy file the commit names that the clone never fetched, or a history the replay cannot read, makes the source read as nobody, as a shallow checkout already does; the next sync that can read it clears that.
+- `src/core/persistence/sync-discovery.ts`: `syncPartialClone` and `partialCloneTreeRefusal`. The full tree walk and the reconcile level read (`sync-pass-run.ts`) stop with `git_object_missing` when a partial clone lacks a tree of the synced commit; any other listing failure is unchanged.
+- Git 2.40 to 2.44 ignore `GIT_NO_LAZY_FETCH`. There the empty `GIT_ALLOW_PROTOCOL` refuses the fetch instead, so a missing object reads as missing and nothing is fetched, the same outcome as on 2.45 and newer.
+- Tests: `test/sync-partial-clone-2331.test.ts` on PGLite and Postgres, with a marker on the partial clone's object fetches and a check that it never ran: a blobless clone that syncs a second commit after a pull, both blob read paths with and without `GIT_NO_LAZY_FETCH` (also with the file transport allowed in the environment), two treeless clones, the history walk that dates deletions, and folder rules whose committed file or history the clone lacks, which read as nobody until the command the problem names runs and then clear on the next plain sync.
+
+## [0.60.653.0] - 2026-11-10
+
+**Postgres connections to a database that isn't on your machine now use TLS unless the URL opts out.** Before this release gbrain's Postgres driver connected in plaintext whenever the database URL had no `sslmode`, so the password and every page crossed the network unencrypted, even to a hosted database that supports TLS. Now every connection pool requires TLS (`sslmode=require`) for any host other than `localhost`, `127.0.0.0/8`, `::1` or a Unix socket; private addresses and Docker service names count as remote. An sslmode in the URL is always honored, so `?sslmode=disable` keeps a plaintext connection on a network you trust. A server that has no TLS no longer connects silently: it fails with `postgres_tls_required`, which says to turn TLS on at the server or add `sslmode=disable`. `sslmode=require` encrypts but does not verify the server certificate; `sslmode=verify-full`, with the provider's CA in `NODE_EXTRA_CA_CERTS`, verifies it too. A new doctor check, `postgres_tls`, warns when a brain on a remote host is connected without TLS. PGLite has no network connection and is unchanged.
+
+**If you self-host Postgres without TLS on another machine:** after upgrading, gbrain refuses to connect with `postgres_tls_required`. Either enable TLS on the server (`ssl = on` with a certificate), or add `?sslmode=disable` (or `&sslmode=disable`) to your database URL in `~/.gbrain/config.json` or `GBRAIN_DATABASE_URL`/`DATABASE_URL`.
+
+### Itemized changes
+
+- `src/core/pg-tls.ts` (new): `resolvePgTls` / `withPgTls`, the one TLS resolver every `postgres()` call site in `src/` uses (the module pool in `db.ts`, worker instance pools in `postgres-engine.ts`, the read and direct pools in `connection-manager.ts`, the graduation target probe and the schema-lock diagnostic connection). An `ssl` option, `sslmode` / `ssl` / `sslrootcert=system` in the URL, or the driver's `PGSSL` variable is explicit and left alone; a loopback host or socket keeps the driver default; anything else gets `ssl: 'require'`. After a failed default-required connect, `tlsRequiredDefaultError` sends the protocol's SSLRequest to the server and turns a "no" into `postgres_tls_required` (DNS, refused and timeout failures are not probed).
+- `src/core/error-registry.ts`: new code `postgres_tls_required` (host_only, actor user; fix asks the user, reads `gbrain engine status --probe --json`, verifies with `gbrain doctor --only postgres_tls --json`). `docs/guides/error-codes.md` regenerated.
+- `src/core/pg-access-classify.ts`: new reason `tls_required_default` (manual tier in `gbrain db-repair`, which never removes TLS on its own; fatal for persistence reads).
+- `src/commands/doctor/checks/postgres-tls.ts` (new): `postgres_tls` (ops) judges TLS from the client side, from the mode the driver used for the URL the engine connected with. It warns on `sslmode=disable` and on a `sslmode=prefer` connection that fell back or may have fallen back to plaintext (it never certifies prefer as encrypted), and is ok for a TLS client behind a pooler. The session's `pg_stat_ssl` row, which behind a pooler describes the pooler's hop, is detail only. It emits nothing on PGLite.
+- `src/core/behavior-change-notice.ts`: one row (`postgres_tls_default`) disclosing the new default and the opt-out.
+- `gbrain init` prints the Supabase URL format with `?sslmode=require`; `docs/ENGINES.md#tls-for-postgres-connections` documents the modes, `verify-full` with Supabase's CA, and the opt-out; the personal-brain tutorial and the other documented Postgres URLs carry `?sslmode=require`.
+- `scripts/ci-local.sh`, `scripts/run-e2e.sh`: the Docker CI gate reaches its untrusted-by-name service hosts (`postgres-N`, `pgbouncer`) with an explicit `sslmode=disable`, and the derived PgBouncer E2E URL keeps the base URL's query.
+- Tests: `test/pg-tls.test.ts` (loopback, remote, explicit modes, opt-out, a guard that every `postgres()` pool in `src/` goes through `withPgTls`), `test/pg-tls-default-refusal.test.ts` (a fake server without TLS on a non-loopback interface gets the coded error; `sslmode=disable` and a TLS-capable server do not), `test/doctor-postgres-tls.test.ts`, `test/e2e/pg-tls-postgres.test.ts` (real servers: a TLS server through a non-loopback address connects with `pg_stat_ssl.ssl = true` on both pool kinds; an `ssl=off` server refuses, then connects with `sslmode=disable` and doctor warns; `sslmode=prefer` falls back and doctor says so; an opt-in TLS-client pooler with a plaintext upstream reads ok).
+- `bun.lock`: moves `fast-xml-parser` to 5.12.0 and `fast-xml-builder` to 1.3.1 (the minimum 5.12.0 declares) for a Low advisory in the parser's non-default `stopNodes` option, which gbrain's code does not reach; package.json ranges are unchanged.
+
+## [0.60.652.0] - 2026-11-10
+
+**The private-labels preview finishes on large sources.** On a source with a few hundred thousand pages, `gbrain repair private-labels` ran past its 120-second statement bound while counting the pages a window of clears would expose, so the preview failed, and so did every `--apply --expect`, which repeats the check. The count used to pair every page with every cleared page. It now reads each page's references once and joins them to the cleared pages, so it returns the same pages and the same exposure map well inside the bound, which is unchanged. On a synthetic brain (`scripts/bench/private-labels-dependents.ts`: 300,000 pages in the window's source, 100,000 in another, 8 links per page) with a 1,000-page window, master hit the 120-second bound and this release took 0.33 to 1.06 seconds across the four shapes.
+
+### Itemized changes
+
+- The dependents statement in `src/core/repair/private-labels.ts` lists each page's `source_slug`, `event.depth` and `derived_from` slugs (with `.md` removed) in one pass, matches them to the cleared pages with equality joins, and applies the post-clear privacy rules only to the candidate pages. It runs with JIT off and is planned for its real parameters. No migration and no new index.
+- New equivalence tests on PGLite and Postgres run the old statement, kept verbatim in a test helper, next to the new one and require identical rows: a fixture with every kind of tie, each cleared page alone, a generated source and privacy aliases turned off.
+- A Postgres scale test requires a 50,000-page source with a 1,000-page window to finish inside 20 seconds. The old statement fails it.
+- `scripts/bench/private-labels-dependents.ts` builds the synthetic brain and times the preview, with `--lineage` for common `derived_from` chains and `--class alias-and-visibility`.
+
+## [0.60.651.0] - 2026-11-10
+
+**CI wastes fewer reruns: the macOS type check stops running out of memory, and a worktree test stops stalling for two minutes.** The macOS type check now runs on GitHub's 14 GB Intel runner. On the 7 GB arm64 runner, a check that couldn't reuse a recent saved state ran short of memory, took 7 to 15 minutes and sometimes hit its 15-minute limit. On Intel a check with no saved state takes about 4 minutes. The stale-plan worktree test no longer waits out a 2-minute lease on PGLite: its wait for commits now lets timers run, so the background writer finishes its pass.
+
+### Itemized changes
+
+- The `typecheck` job in `macos-validation.yml` runs on `macos-26-intel`. It still fails on a real type error: a forced probe failed with `TS2322` and exit code 2.
+- `test/persistence-stale-plan-retry.test.ts` pauses for timers after every pass of its commit wait, and a new probe pins that a timer-parked pass resumes during the wait. No assertion changed. The stall was test timing, and every page was committed.
+- actionlint moves from v1.7.11 to v1.7.12, which knows the `macos-26-intel` runner label.
+- The advisory harness check runs against harness-evals 7e8d872edb (v0.0.136). A hand run at that pin against this branch passed with 0 cross-scope pages, 36 assertions passed and 0 failed.
+- The shard weight maps for unit, serial and E2E tests are refreshed from the latest nightly runs.
+
+## [0.60.650.0] - 2026-11-10
+
+**Private-labels windows publish together and finish past declined pages.** `gbrain repair private-labels --apply --expect <hash>` on a brain with managed persistence now admits a window's pages together and publishes them in groups, instead of one page and one wait at a time. On a 1,000-page window with Git commits and a second queue consumer (`scripts/bench/private-labels-apply.ts`), it went from 181.4 to 1365.3 pages a minute with no added database latency, and from 19.9 to 37.1 pages a minute with 20 ms added to each database round trip. Git commits for the window dropped from 990 to 22. The preview no longer claims a re-embed for every page: only pages stored under per-chunk synopsis, or with a chunk that has no vector yet, count.
+
+### Itemized changes
+
+A page whose own state declines the write (its file changed outside gbrain, `source_changed`, or its body is stored in segments) fails alone and the rest of its group lands. A preview-bound apply of any repair kind that completes with only such declines now exits 0 and counts them under `declined`. The next private-labels preview lists pages an earlier apply tried and that did not change after every page not tried yet, and such a page declining again no longer counts toward the `item_failures_systemic` stop, so windows that carry declines forward keep finishing; pages not tried yet that all fail the same way still stop the run. A page that declined under a release before 0.60.649.0 has no ledger line, because those releases recorded only writes that landed, so the first apply after upgrading stops once with `item_failures_systemic` when five or more such pages head its window; that run leaves intent lines for its batch, so the next preview lists them last. The apply result names its ledger (`details.ledger`, `details.ledger_rows_written`).
+
+A preview-bound repair apply now waits out a `gbrain sources refresh` for up to 10 minutes per step instead of 10 seconds. A refresh that runs longer ends the apply with `worktree_refreshing`, naming the refresh and how long it has run; rerunning the same apply resumes it (GBRA-443).
+
+## [0.60.649.0] - 2026-11-10
+
+**Access and privacy fixes.** A member-bound credential now sees its own readable pages on every read surface, the brain owner's remote credentials get private facts on every fact surface, `gbrain sources federate` names the member-written pages it makes readable to everyone, and seven community-reported bugs in access, privacy, purge, repair and secret scanning are fixed.
+
+### Community-reported access, privacy, purge, repair and secret-scan fixes
+
+**Seven community-reported bugs in access, privacy, purge, repair and secret scanning are fixed.** A member-bound caller now gets its own readable pages in core memory, entity lookups, reflex pointers and pull briefs, the same pages `get_page` returns. `gbrain access who-can-read` names the members a folder rule admits instead of saying everyone. Purging a page removes its name from the retrieval feedback tables and captured eval candidates. S3 and MinIO file URLs are signed for one hour, so a private bucket's file opens from another machine. The secret scanner now also catches a key right after a written `\e[` terminal colour code. `gbrain repair visibility` now stamps a synthesized concept that has no visibility and no inputs, so the doctor warning about it can clear.
+
+| What you did | Before | Now |
+|---|---|---|
+| A member-bound credential reads core memory or resolves its own `readable_by` page | the page was hidden | the page is there, as in `get_page` |
+| `gbrain access who-can-read team-b/profile` under a folder rule | "every caller entitled to the source" | the members the rule admits |
+| `delete_page purge:true`, or the expired-tombstone purge | the slug stayed in `retrieval_*` and `eval_candidates` | removed, and the receipt checks each store |
+| `gbrain files signed-url` with S3 or MinIO storage | an unsigned URL, 403 on a private bucket | a presigned GET that expires in an hour |
+| `gbrain repair visibility` on a concept with no visibility and no inputs | planned nothing, and doctor kept warning | stamped `private`, and the warning clears |
+| A browser MCP client sends `X-Gbrain-Client` from an allowlisted origin | the preflight blocked the call | allowed on both HTTP transports |
+| Transcript text with a key right after a written `\e[32m` colour code | the key was kept | redacted |
+
+After upgrading, `gbrain doctor` asks for a fresh `gbrain transcripts audit-secrets` run (read-only) if your brain has imported transcripts, because the detectors changed.
+
+#### Itemized changes
+
+- `src/core/core-memory.ts`, `src/core/entities/resolve.ts`, `src/core/context/retrieval-reflex.ts`, `src/core/context/proactive-brief.ts`: these reads filter with `privatePagesFilterForCaller` (and `privateTimelineEventFilterForCaller` for brief edits), the caller's member access plus the privacy rule with its grant and opt-out. Entity resolution and core memory take it only when asked (`forCaller`: the remote `remember` path, `get_brain_context` and the remote core budget message), so fence repair, subject inference and local core readers (`compile-context --include-core`, `gbrain core`, the session hook) keep the plain privacy fragment. Retrieval pointers and brief arms take the same `forCaller` option, which only the remote `context_pack` pull brief sets, so the per-turn hook, the OpenClaw context engine and `gbrain watch` keep the plain fragment even with the remote read hatch open. Reported by @javieraldape (#8442).
+- `src/commands/access.ts`: `whoCanRead` asks the read path's own predicate (`accessAllowedSql` with each member's satisfied folder rules) per enabled member, and the note names folder rules. Reported by @Masashi-Ono0611 (#8743).
+- `src/core/feedback/store.ts`: `scrubPurgedSlugs` deletes the source's `retrieval_event_pages`, `retrieval_event_links`, `retrieval_feedback` and `retrieval_weights` rows naming the slug (a page key or either end of a `from|type|to` edge key) and drops it from `eval_candidates.retrieved_slugs` where the results came from that source. Called in the purge transaction by `purgePageInTransaction`, the belief-ledger tombstone expiry and the bulk `purgeDeletedPages`. A federated capture keeps a slug that another of its sources still has a page for. The feedback writers insert rows only for pages that still exist, checked under a key-share lock on the page row, and the page purge scrubs after it deletes the page, so a write that races the purge on Postgres cannot bring the slug back. `src/core/deletion-inventory.ts` moves the four tables to `swept`; `verifyPagePurge` reports each store. A restore that replays a page purge (`restorePgliteBackup`, `beliefs replay-purges`) runs the same scrub on the restored brain (`src/core/belief/purge-mirror.ts`). Reported by @Masashi-Ono0611 (#8822) and @alanshurafa (#8823).
+- `src/core/storage/s3.ts`: `getUrl` returns a SigV4 presigned GET with a 3600 s expiry. New dependency `@aws-sdk/s3-request-presigner` 3.1028.0 (the `client-s3` release), with `@aws-sdk/util-format-url` pinned to 3.972.9 from the same release. Reported by @liuwenyong1985 (#8793).
+- `src/core/repair/visibility.ts`: `planLineage` stamps `private` on a concept with no recoverable lineage and no visibility; an explicit value stays, and both still count in `concepts_without_lineage`. Reported by @Masashi-Ono0611 (#8856).
+- `src/mcp/http-transport.ts`, `src/commands/serve-http-oauth.ts`: `X-Gbrain-Client` joins the CORS allowed headers. Reported by @dajiaohuang (#8691).
+- `src/core/secret-scan.ts`: the escape boundary also accepts a written `\e[…m` colour code, next to the forms #8266 added. `TRANSCRIPT_SECRET_AUDIT_VERSION` is 4. Reported by @javieraldape (#8764).
+- Tests: `test/caller-aux-page-reads.test.ts`, `test/access-who-can-read-folder-rules.test.ts`, `test/purge-retrieval-feedback-8821.test.ts`, `test/storage-s3-signed-url.test.ts`, `test/mcp-cors-client-header.test.ts`, a `\e[32m` case in `test/secret-scan-encoded-boundary-8266.test.ts`, a new case in `test/derived-visibility-repair.test.ts`; `test/storage-s3.test.ts` checks the same URL bases on a presigned URL.
+
+### The brain owner's private facts, and a crash-safe private-labels repair
+
+The brain owner's remote credentials (`gbrain access owner set <member>`) now get private facts beyond list-style `recall`: in the `query` facts arm, `think` trajectories, hot memory (`_meta.brain_hot_memory`), `delta` and `context_pack` hot facts. Facts taken from a page the owner cannot read (`readable_by`, folder rules) and facts in sources its grant does not read stay hidden, and the owner speaking for a shared-room audience gets world-only facts. Other members, unbound and public callers are unchanged, and the hot-memory cache keeps the owner's entries apart from every other caller's.
+
+The owner's `recall` with a `question` now returns its private facts, as `recall` by entity or session already did. Before, ranking a question dropped them.
+
+`gbrain repair private-labels` now writes its undo ledger ahead of each page. Every cleared or restored page gets an `intent` line before the page write and a `committed` line after it, so a run that stops between the two can still be undone with `--class restore`. When the ledger can't take the intent line, the apply refuses with `storage_error` and changes nothing (GST-2092).
+
+`--class restore` treats ledger lines as untrusted input. It re-adds only `access` (a string) and `visibility: private`. A line with any other key, a non-string value or a page id that isn't an integer is counted as unreadable instead of failing the preview (GST-2092, GST-2128).
+
+The private-labels preview now counts the pages each window would expose along with its own: `derived_from` pages, atoms whose origin is a listed page, synthesized concepts built from such atoms, and life-chronicle events extracted from a listed page or from a page whose only privacy is a `derived_from` naming one, each judged by the rules remote reads use. It reports them by category (`details.dependents`, no slugs) and warns when the count isn't zero. The preview hash covers the pages it counted, so an apply that would expose a page added since the preview refuses `preview_changed` (GST-2093). A ledger line a crash cut off no longer swallows the next one.
+
+On a brain without managed persistence, a page whose file sits in its source's checkout is no longer cleared in the database only, because the next sync or re-import would put the label back from the file. The apply holds it with outcome `file_backed` and names the file to edit. Repo-less pages clear as before (GST-2128).
+
+An apply that ends with a failure, a stop or a pending write keeps its approved preview, so rerunning the same `--apply --expect <hash>` resumes it instead of asking for a new preview (GST-2128).
+
+Restore no longer lists a page whose label was removed by hand after a restore landed. The preview counts it as `removed_after_restore` and says so (GST-2128).
+
+### Federating a source names the member pages it exposes
+
+**`gbrain sources federate` now names the pages it makes readable to everyone that a member's credential wrote.** A token or OAuth client bound to a member and granted its own source (the documented `--sources private-<member>,default` shape) writes there without `readable_by`, which is right while that source is not federated: only credentials granted it read it. Federating the source adds it to what every connection with no source grant reads, so each such page became readable by every unbound token and agent connection, and nothing said so. `sources federate <id>` still federates exactly as before, with the same exit code, and then prints on stderr how many pages in the source a remote token or OAuth client wrote that name no readers and no folder rule, up to five slugs with the member each credential is bound to now, `gbrain access who-can-read <slug> --source <id>` to check one, and `gbrain access rule add --prefix <folder/> --readers <member> --source <id>` (which previews before `--yes`) to keep a folder to its member; every command is shell-quoted. No record keeps which member a credential was bound to when it wrote, so pages from a credential unbound, rebound or deleted since then are listed too. A page whose remote author was followed only by a tag change (which moves the revision attribution without a version snapshot) is not listed. `sources federate --json` prints one object (`id`, `federated`, and `pages_exposed` when there are such pages) and moves the human lines to stderr. `sources restore`, which re-federates by default, prints the same list, and a managed restore returns it as `pages_exposed`. The pages are read from the database's write attribution after the change commits, so a repo-less brain reports them the same way. Writes made through an attested actor (`x-qm-actor`) carry the attesting system's credential and are listed under it.
+
+#### Itemized changes
+
+- `src/core/access/federation-exposure.ts`: `remotePagesFederationExposes` reads the live pages of a source with no readers and no folder rule whose live revision or any earlier version a token or OAuth client wrote; `remotePagesFederationExposesOrWarn` runs it only for a change that federated the source and reports a failed read as a warning without changing the federation.
+- `src/commands/sources.ts`: `sources federate` (and `--json`) and the unmanaged `sources restore` print the list on stderr after the change commits.
+- `src/core/persistence/administration.ts`: a managed `source_lifecycle` restore that re-federates adds `pages_exposed` to its result.
+- Docs: `docs/guides/multi-source-brains.md`.
+- Tests: `test/sources-federate-member-pages.test.ts` (repo-less PGLite: a member-bound token's remote `put_page` into an unfederated source, then `sources federate` names that page and its member and not a page with readers or an operator page, and an unbound token then reads it; `--json`; a credential unbound or deleted since it wrote and a slug holding `$(...)`, quoted in the commands; unmanaged `restore` and `--no-federate`; the managed restore result). It fails on master with an empty stderr.
+
+## [0.60.648.0] - 2026-11-10
+
+**A managed sync no longer imports a file that Git stores through a filter, such as a git-crypt encrypted note, as if its stored bytes were the page.** The file alone is held `content_filter_owned` with a message that says gbrain does not run a repository's filter programs during sync (and names git-crypt when the file starts with its header), and the rest of the source imports and moves on. Reported by @JustinTSmith (#9024) and first fixed by @Masashi-Ono0611 (#9026).
+
+### Itemized changes
+
+- `src/core/persistence/sync-blobs.ts`: `readFilterDrivers` reads the `filter` attribute of many paths at the synced commit in one `git check-attr -z --stdin --source=<commit>` (git 2.40 or newer), or from a temporary index of that commit with `check-attr --cached` on an older git. Every Git call it makes runs with the hardened arguments (fsmonitor, hooks and every transport off) and `GIT_NO_LAZY_FETCH=1`, so reading the attribute runs no repository program and fetches nothing. The module's other reads also switch off `core.fsmonitor` and hooks.
+- `src/core/persistence/sync-entry-fault.ts`: `filterOwnedRefusal` refuses a blob that starts with git-crypt's header, or a committed blob whose path names a filter driver other than Git LFS, whether or not this checkout configures it (LFS pointers keep their own handling). For a plain-text file under an attribute nobody uses, a held file's message says to remove the attribute and run `gbrain sources retry-held`. `missingAttributesRefusal` holds a file `git_object_missing` when a partial clone lacks a `.gitattributes` that applies to it.
+- `src/core/persistence/sync-screen.ts`, `sync-run.ts`: the freeze screen and the `sync.holds=fail` path check committed imports with it before the NUL check, so a git-crypt file gets the clear hold instead of `content_null_bytes`. Working-tree reads are unaffected. A company-brain source checks its approved revision and stops with `content_filter_owned`.
+- New hold and error code `content_filter_owned` (error registry, fault class, public category, docs/guides/write-refusals.md, the sync unblock runbook).
+- Tests: `test/sync-filter-owned-9024.test.ts` and `test/sync-filter-owned-company-9024.test.ts` on PGLite and Postgres, with a clean/smudge filter, an `fsmonitor` and an `upload-pack` marker in the test repository, and a check that none of them ran.
+
+## [0.60.647.0] - 2026-11-10
+
+**A team member's `remember` can now share a fact with the team, and every `remember` reply says where the fact went.** A member credential still saves privately by default, on its own page `memory/members/<member>`, so only that member recalls it. Passing `share: true` saves the fact on its subject's page instead, where everyone who reads the source recalls it, as every other caller's `remember` already does. The tool description tells agents to share facts about the team's work and keep facts about a person private. Before this, a member's `visibility: "world"` was quietly saved as private; it is now refused with `member_share_required` and nothing is saved, so no one believes they shared a fact the team cannot see. For the same reason, `share: true` onto a page whose facts are kept private (a page with readers named, or a brain whose fact default is private) is refused with `share_target_restricted`. A shared fact belongs to the team: only the brain host can withdraw it. Nothing already saved moves.
+
+### Itemized changes
+
+- `src/core/verbs.ts`: `remember` takes a `share` boolean on every MCP surface, starter included. A non-boolean `share`, `share: true` with `visibility: "private"`, and a member's `visibility: "world"` (`member_share_required`) are refused with `invalid_params` before anything is saved, so one such item refuses a whole batch.
+- `src/core/persistence/memory-mutations.ts`: a member's `share: true` saves on the entity page with world visibility; when that page's facts would be private (whatever `visibility` the call passed), the save is refused (`share_target_restricted`), and preparation refuses it again if the page turned restricted after admission. In a batch, items saved before a refused item stay saved, as with other save-time refusals. New and replayed replies carry `page` and `visibility`.
+- `src/core/facts/writeback-instructions.ts`, `writeback-config.ts`, `src/mcp/instructions.ts`, the HTTP serves, the stdio serve bound through `mcp.stdio_member` and `memory_conversation_mode`: with ambient writeback on, a member caller is told to omit `visibility` and to pass `share: true` only for facts about the team's work, instead of the brain-wide "pass visibility: world" line its saves would now be refused for. A credential that may name a member per call (`x-qm-actor` on `remember`, as QM's service does) is told both: the member rule on calls made for a member, `visibility: "world"` on the rest. The `member_share_required` refusal names the exact retry.
+- `src/core/remember-batch.ts`: `share` is accepted per item and as a shared top-level key, and each item's receipt carries `page` and `visibility`.
+- `test/mcp-schema-budget.test.ts`: the starter tool-list ceilings and the `remember` budget grow by what `share` costs (+144 characters, 200 headroom kept).
+- QM's `memory_write` and its per-person contract (`docs/contracts/qm-memory-provider/v1.json`) are unchanged.
+- `src/core/behavior-change-notice.ts`: one row for the changed `remember` behavior.
+- Docs: `docs/tutorials/company-brain.md`, `docs/mcp/ADMIN.md`, `docs/TOOL_CATALOG.md` (regenerated).
+- Tests: `test/remember-share-gst2243.test.ts` (a shared fact is recalled by another member and an unbound reader, an unshared one is not; all three refusals; replayed and non-member replies; batch `share`; `memory_write` still saves on the member page); `test/access-member-facts.test.ts` drops the `visibility: "world"` an attested member save no longer accepts.
+
+## [0.60.646.0] - 2026-11-10
+
+**A migration that adds a column under a running server no longer fails writes on direct Postgres.** On a direct Postgres connection the driver reuses each connection's prepared statements. When a migration adds a column to a table that a `SELECT *` reads, the next run of that statement inside a transaction fails with SQLSTATE 0A000, "cached plan must not change result type", once per pooled connection. Outside a transaction the driver quietly prepares it again; inside one, the transaction is already aborted and the error reaches the write. Two places lost writes this way. A legacy-token write whose authority reads `access_tokens` failed with `storage_error` and committed nothing; a retry worked. Worse, after a migration added a column to `persistence_requests`, an accepted write could end `failed`/`storage_error` at publication and was never retried, so a caller that left on `write_pending` lost it unless it polled the receipt; other submissions were refused at admission with `internal_error`. Four of the last 50 migrations (v254, v261, v292, v294) changed that table. Now the two `access_tokens` reads name their columns, so a new column leaves their result unchanged; the stale-plan error counts as a transient interruption of the write (cause `stale_plan`), so the request is claimed again after the usual backoff and stays bounded by `persistence.max_transient_retries`; and admission re-runs on it like a serialization failure. Only the stale-plan error matches (the server's plan-revalidation routine, in any locale, or that English message): every other 0A000 stays a refusal. Both reads also keep working on a schema behind the build (a brain whose migrations could not be applied): an accepted legacy-token write still replays, a new one is refused `migrations_pending`, and shared-skill membership still works. A transaction-mode pooler (`prepare=false`) and PGLite were never affected. Writes that already failed this way stay failed; `gbrain doctor`'s terminal-failures check lists them, and each needs a resubmit with a new `request_id`.
+
+### Itemized changes
+
+- `src/core/retry-matcher.ts`: `isStalePlanError` matches SQLSTATE 0A000 with the server routine `RevalidateCachedQuery`, or, when no routine is reported, the "cached plan must not change result type" message.
+- `src/core/persistence/transient-retry.ts`: `transientInterruption` returns `{ cause: 'stale_plan', sqlstate: '0A000' }` for it, so `finishUnpublishedFailure`, the recovery route and grouped publication charge it against `persistence.max_transient_retries` and release the claim with backoff; past the limit the write ends `write_interrupted`. `src/core/persistence/coordinator.ts` words that receipt for the new cause.
+- `src/core/persistence/admission-retry.ts`: `retryWriteAdmission` re-runs an admission that hit it, within its existing time budget.
+- `src/core/persistence/coordinator.ts`: `transientDatabaseFailure` also accepts the stale-plan error, so with `persistence.preparation_deadlines false` it is released uncounted as database contention, as a 57014 is; the effect worker, the consumer's release paths and the recovery resolver share that predicate.
+- `src/core/grants/model.ts`: `TOKEN_GRANT_ROW_COLUMNS` lists the columns `grantFromTokenRow` reads, and the async `tokenGrantRowSelect(engine)` selects the ones the table has; `src/core/persistence/authority.ts` (publication authority, `FOR SHARE`) and `src/core/shared-skills/membership-authority.ts` use it instead of `*`, at the cost of one catalog read per legacy-token call.
+- Docs: `docs/guides/write-refusals.md` and `docs/guides/error-codes.md` (`write_interrupted`), `docs/architecture/key-files/persistence-stalls.md`.
+- Tests: `test/persistence-stale-plan-retry.test.ts` adds a `persistence_requests` column under a pool of 3 and requires all 9 later `put_page` calls to commit with no request past the retry limit (on the previous code 3 to 9 of the 9 failed; without the admission retry or without the publication classification it still fails). `test/access-token-grant-columns.test.ts` runs both `access_tokens` reads on every pooled connection before and after an added column, plus a legacy-token `put_page` (all three failed on the previous code). Its worktree-backed case does the same on a git checkout and requires each page's file once with one Git commit (on the previous code 5 and 6 writes failed). `test/access-token-grant-columns.test.ts` also drops `private_pages` to stand in for an older schema: both reads still work, an accepted request replays and a new one is refused `migrations_pending` (42703 or `unavailable` on the previous code). `test/stale-plan-classification-gst2314.test.ts` covers the routine match, a non-English message and that other 0A000 errors stay refusals. `test/publication-failure-owner-exception.test.ts` now uses a different 0A000 as its sample owner exception, since the stale-plan one retries. `test/access-ungranted-member-writes.test.ts` resets its connections after the column-rename case, which left stale plans for the next test; no assertion changed.
+
+## [0.60.645.0] - 2026-11-10
+
+**A GitHub (or other API) connector source no longer stops for good when one of its items is a page stored in segments.** A long issue (a body plus hundreds of comments) grows past 1 MiB and is stored in segments. Before, that item could never import, and once such a page existed, every later sweep of a bound source stopped on `page_body_segmented` with no item named, so nothing after it imported and the cursor never moved. Now an item up to 24 MiB imports and re-renders like any other, and one the sweep cannot read whole (over 24 MiB) fails on its own from the first sweep, and is held after three (`gbrain sources status`), while the rest of the run imports and the cursor moves; a new comment on it re-tries only that item. Reported and first diagnosed in #9062.
+
+### Itemized changes
+
+- `src/core/persistence/connector-sync.ts`: the connector publication reads a segmented page back as strings (up to 24 MiB) before it carries its timeline and fences into the re-render, seals a segmented body through its import (never the inline text seal, which read the whole timeline), and runs the import's after-commit step, so a segmented page left unsealed is chunked. The freshness read (`page()`) reads a segmented page back the same way.
+- `src/core/github-source.ts`: a stored page the sweep cannot read fails that item (a content hold after three runs), not the run.
+- `src/core/connectors/connector-hold-session.ts`: on a bound source, `page_body_segmented` raised before any write request is counted against the item instead of aborting the run, as invalid connector text already was.
+- Tests: `test/connector-segmented-page-9062.test.ts` (PGLite) and its PostgreSQL arm `test/e2e/connector-segmented-page-9062.test.ts`.
+
+## [0.60.644.0] - 2026-11-10
+
+**`gbrain doctor` now ends on its `--budget-ms` deadline when `git` hangs in an OpenClaw workspace.** The bootstrap entry checks push health by running `git status`, `git branch` and `git rev-list` on the install receipt's workspace, and on a workspace whose last push failed. Those calls ran synchronously with a 10-second limit each. While one hung, nothing else in the process could run, so the run overran its budget and every later check, the cheap incident checks included, started with no time left. They now run asynchronously, like the home-dir probes since #8979. Each call is killed with SIGKILL, together with its process group, at 10 seconds or at the entry's deadline, whichever comes first, and a call that fails or is cut short reads as unverified, as before. Every local probe's output is also capped at 1 MiB again: a probe that prints more than that is killed and reads as absent, which is what `execFile`'s buffer limit did before #8979.
+
+**The Postgres crash robot no longer fails a full run when a race makes one fewer slot than its count run saw.** The robot first runs each schedule to count the seams it reaches, then crashes one run at a counted slot. In `sync_and_connector_race_direct_write`, the connector republish races a direct write, and the race legally settles two ways: one makes 5 publications, the other 6, with the git effects, preparations and commits following. A crash planned at the 6th publication was never reached by a run that took the 5-publication outcome, and the job failed with `fault_not_reached` (#8078). A run that misses its fault now reports how many slots of that seam it made. If it was exactly one short of the count run, it runs once more at its last slot, and the manifest records `retargeted` on the run and lists it under `faults_retargeted`. A run that found violations, made no slot, fell two or more short, or misses again still fails as `fault_not_reached`.
+
+### Itemized changes
+
+- `src/commands/doctor/local-probe.ts`: `localProbe` moved here from `checks/local-audits.ts`. It takes `ownTimeoutMs` (default 5 s) and `windowsShell` (git runs without cmd.exe on Windows), and it kills a probe and returns null once its stdout passes `LOCAL_PROBE_MAX_OUTPUT_BYTES` (1 MiB).
+- `src/commands/doctor/bootstrap-checks.ts`: `bootstrapDoctorChecks(engine, entryDeadlineAt)` runs every git call through `localProbe` with a 10 s bound. `commitsAheadOfOrigin`, `treeMatchesOrigin` and `recordedPushFailureCheck` are async.
+- Tests: `test/doctor-bootstrap-git-deadline-8990.test.ts`. A `git` stand-in that ignores SIGTERM and waits on a 6 s child is killed within a 1000 ms budget, on both the workspace probe and the recorded-failure probe, and neither it nor its child survives (each fails on the previous code, at 18 s and 12 s). A probe that floods stdout is killed within 1.5 s and reads as absent, one that prints 2 MiB and exits reads as absent, and one under the cap returns its whole output (the first two fail without the cap).
+- `scripts/persistence/crash-robot.ts`: the run role's fault hook reports `reached`, the slots of its seam it made. `scripts/persistence/robot-driver.ts`: a planned crash carries `counted` (the count run's slots), and `retargetable` reruns a run once when it found no violations, `counted` is set and `0 < reached`, `counted - 1 <= reached < nth`.
+- Tests: `test/persistence-crash-robot.test.ts`. A run one slot short crashes at its last slot and passes; a short run with violations, a run two short, a run short again after the retarget, a run with no slot and a run with no counted plan still fail. The failed #9071 manifest entry, given the `counted: 6` its count run saw, failed 4 of 4 on Postgres before the fix and passed 3 of 3 after it, crashing at the 5th publication.
+
+## [0.60.643.0] - 2026-11-10
+
+**Retrying an interrupted `gbrain sources remove` or `purge` can no longer delete a re-added source's pages.** A managed remove or purge deletes a large source's pages in batches, and a run that stops partway can be finished by rerunning it with the same `--request-id`. Until now nothing tied that request id to the source it was started against: if the source was removed and added again under the same ID in between, the rerun deleted the new source's pages. The first batch now records which incarnation of the source the request was admitted against, in the same transaction as its first deletion. A rerun against the same incarnation still resumes and finishes; a rerun after the source was replaced refuses with `source_retire_superseded` and changes nothing. Restoring, archiving or otherwise changing the source after a run stopped abandons that run the same way, so a purge stopped before a restore can't hold up `deactivate` or graduation for good, and both ask the user before a stopped run is finished, since finishing deletes the rest of the source's pages. A stopped automatic expired-archive purge is left to the next automatic run instead of being handed to a person, and `gbrain sources writer status --source <id> --json` now lists a source's stopped and superseded remove and purge requests.
+
+### Itemized changes
+
+- `src/core/persistence/topology-receipts.ts`: `admitTopologyRetire` records a retire admission (a `persistence_topology_changes` row in state `recovering` with no recovery record, bound to the source incarnation, holding one lifetime ID and a full receipt reservation after the same quota check `assertTopologyChangeCapacity` made); `recordTopologyChange` settles a request's own admission `committed` and trues up its receipt bytes; `supersedeTopologyRetires` settles other requests' admissions `failed` when a remove or purge deletes their incarnation, or when any other lifecycle operation (archive, restore, rebind, claim) commits a change to it; it skips only the caller's own (principal, request id) pair, so a retry under a replaced CLI registration settles the old registration's admission too.
+- `src/core/persistence/source-lifecycle.ts`: a request id whose admission names another incarnation than the source registered now refuses `source_retire_superseded` before any lock or deletion (a dry run too) and settles the admission `failed`, so a later retry refuses the same way; the batches and the final transaction resume past their own admission (#8984).
+- `src/core/persistence/source-lifecycle.ts`: a remove or purge retry also refuses `source_retire_superseded` when another CLI registration (one replaced since) admitted the same request id against a different incarnation of the source, and settles that admission `failed`; idempotency is per registration, so before this the retry ran as a new request and deleted the re-added source's pages. An admission bound to the current incarnation still resumes under the new registration (#8984).
+- `src/core/error-registry.ts`: new caller code `source_retire_superseded`, with a read-only writer-status fix; `sources writer status --json` gains `topology_requests` (recovering admissions and superseded requests).
+- `src/core/persistence/deactivation.ts`, `graduation-drain.ts`: an unfinished retire is listed as a blocker that names its request id and asks the user whether to finish it (rerun the same command with its request id) or keep what is left (another lifecycle change abandons it); graduation marks it `needsUser`. A stopped automatic expired-archive purge (its admission records `expired_only`) instead says the next automatic run finishes it, with `needsUser: false`.
+- Tests: `test/source-retire-incarnation.test.ts` (PGLite) and `test/e2e/source-retire-incarnation-postgres.test.ts`: a retry after the final transaction failed, and a retry after committed batches already deleted part of the source, both refuse once the source was replaced and keep the new source's pages (both resolved `committed` on master); a same-incarnation retry resumes and settles; a restore after an interrupted purge abandons it, so its retry refuses and no blocker stays. `test/source-retire-batched.test.ts` and its Postgres twin now expect the interrupted run's admission row.
+
+## [0.60.642.0] - 2026-11-10
+
+**A purged page's facts no longer come back.** When the 72-hour retention purge removed a soft-deleted page's row, it left the page's facts active, because facts have no foreign key to pages. Once the tombstone was gone, those facts showed up again for every reader, local and remote, and a new page written at the same slug picked them up. The purge now expires those facts in the same transaction as the page delete: the facts filed on the page, and the facts about it that no page holds. The rows are kept, expired, never deleted. A fact another page holds about the slug stays active, even when that page is soft-deleted, so restoring it brings the fact back. An ontology observation about a live entity that was sourced from the purged page also stays active.
+
+### Itemized changes
+
+- `src/core/facts/gone-page-facts.ts`: `expireGonePageFacts`, the facts a purged page takes with it, as two updates that each use their slug index.
+- `src/core/engine-sql/pages.ts` (`purgeDeletedPages`, the bulk purge) and `src/core/persistence/purge-deleted.ts` (`expireRecordedTombstones`, the belief-ledger purge of a recorded source) call it in the purge transaction. The managed purge already sweeps the facts filed on the page.
+- Tests: `test/purge-expires-page-facts.test.ts` (PGLite and Postgres), which fails before the fix on the bulk and recorded purges.
+
+
+## [0.60.641.0] - 2026-11-10
+
+**Facts, timeline entries, tags and ontology observations now follow the page they are about, so a remote caller who cannot read a page learns nothing about it from fact reads, and a deleted page's facts, timeline and tags stay hidden from everyone until it is restored.** Before this, a fact saved on an open page about a page with `readable_by` or `visibility: private` still reached remote callers through recall, ontology_get, volunteer_chronicle, delta, find_trajectory, hot memory and the entity card, and a soft-deleted page's facts, timeline rows and tags kept answering every reader. Recorded-time reads (get_page and get_versions with known_as_of), plain get_versions with include_body, and delta's belief changes now also keep a quarantined page's bodies and claims from remote callers, including a page quarantined only by a later write and a version history that spans several sources. Nothing is deleted or expired, so restore_page brings every row back as it was. A new page written at a deleted page's slug still shows the deleted page's facts, and a purged page's facts still come back, as before; both are follow-up work.
+
+### Itemized changes
+
+- `src/core/search/private-visibility.ts`: `privateFactFilterForCaller` and `privateEntityFilterForCaller` add the entity-page read gate to the provenance-page gate; recall, the entity card, contested claims, attribution, saved-fact matching, entity facts and the proactive brief use it.
+- `src/core/eligibility/sql.ts`: `deletedPageProjectionHiddenSql` hides facts on or about a soft-deleted page, and that page's takes and timeline rows, in every projection read; fact list reads, ontology reads and the unattributed-facts review list apply it even without a read policy.
+- `src/core/ops/tags.ts`: `get_tags` reads live pages only, for local callers too.
+- `src/core/ops/get-page-projection.ts`, `admin.ts`, `known-as-of.ts`: `historyQuarantine` gives each stored version the quarantine view of its own page (quarantined now or in that version), so a remote caller gets no body for it.
+- `src/core/belief/history.ts`, `changes.ts`: a quarantined page's fact and take events and fence claims stay out of a remote caller's belief history and delta.
+- `src/core/persistence/page-prepare.ts`: a put over a soft-deleted page takes its tags from its own content and does not write the deleted page's database-only timeline rows into the new page's first version.
+- Tests: `test/fact-reads-page-access.test.ts` (new), `test/recorded-read-gate.test.ts` (new cases 4 to 7), `test/get-tags-remote-privacy.test.ts`, on PGLite and Postgres.
+
+## [0.60.640.0] - 2026-11-10
+
+**The skill resolver's hook lane is faster and safer at its 50 ms deadline, offers skills again after a Codex compaction, supports Pi and Cursor, and takes per-harness settings.** The hook starts its worker first and skips the CLI dispatcher, so the worker bundle drops from 172 KB to 62 KB and the lane's p90 drops from 58.9 ms to 38.1 ms on a 2-CPU machine (0 of 40 turns over 50 ms, was 7). A turn the deadline ends mid-commit now removes its session temp file and releases the session lease. The resolver stays off by default, lexical-only and fail-open.
+
+### Itemized changes
+
+- Lane speed: the hook fast path (`src/core/skills/resolver/hook-lane.ts`, `hook-worker.ts`, `lane-worker.ts`) starts the worker before reading settings and never loads the CLI dispatcher. That hook process no longer prints the update heartbeat or the backup nag; `GBRAIN_HOOKS=0` and the CLI preflight still apply. A worker that exits before answering is logged as `skill_resolver_internal` at once instead of waiting out the deadline.
+- Deadline: the session commit holds a release handle, so a deadline exit removes the temp file and the `.json.lock` lease it took.
+- Codex compaction: `gbrain setup codex --skill-loading resolve` also writes a `SessionStart` hook (with its trust entry), and a `SessionStart` with `source: "compact"` resets the session's offered skills. An existing install gets the hook on its next setup run.
+- Harnesses: `pi` and `cursor` join the path harnesses (each suggestion carries its SKILL.md path). The turn-input and build-receipt schemas list them.
+- Resolve: `min_match_strength` (`--min-match`) drops weaker suggestions before the cut to `top_k`; exclude lists take up to 1,024 ids (`EXCLUDE_MAX`); `skill_catalog_mismatch` carries `catalog_hash`; a skill the turn names keeps its line after the budget is spent; with no catalog word in the message, `previous_user_message` is ranked instead. `RESOLVER_FEATURES` and `MATCH_STRENGTHS` are exported from `gbrain/skill-resolver`.
+- Config: `skills.resolver.top_k`, `skills.resolver.min_match`, `skills.resolver.pinned` and `skills.resolver.per_harness.<harness>.{top_k,min_match}`, validated by `gbrain config set` (which refuses `per_harness.constructor`). With nothing set, Claude Code and Codex keep 5 suggestions and no floor.
+- Logs: `skill-index/logs/lane-<UTC day>.jsonl` and `resolver-<UTC day>.log`, kept 14 days and capped at 2 MB a day; the old undated file is removed and doctor reads today and yesterday.
+- Library bundle: `gbrain-skill-resolver.mjs` is built with whitespace minification, so the CLI build and the release build have one sha256 whatever the working directory.
+- Bench: `scripts/bench-skill-resolver.ts` runs a discarded warm-up round, then judges the median of nine rounds of 100 cold turns; the bars stay 10 ms at 1,000 skills and 40 ms at 7,500.
+- Tests: `test/skill-resolver-hook-lane.test.ts` (deadline stalls during the lease and after the temp write, Codex compaction, fast path), `test/skill-resolver.test.ts`, `test/skill-resolver-contract.test.ts`, `test/setup-skill-resolver.test.ts`, `test/skill-resolver-packaging.test.ts` (two-directory sha256), `test/skill-resolver-cli.test.ts` and `test/cli-fast-path.test.ts`.
+
+## [0.60.639.0] - 2026-11-10
+
+**Access hardening: job results, write receipts, the status snapshot and graph edges stay inside the caller's grant; a forgotten fact stays forgotten; transcript redaction, `.env` handling and test databases are tighter.** An agent job, its result and its progress now answer only a caller acting for the same audience the job was submitted with, and write receipts follow the same rule. `get_status_snapshot` lists only the sources a remote caller's grant reads. Link reads, graph walks, entity cards and context packs leave out edges whose authoring page is deleted or, for a source-scoped caller, lives outside the caller's sources. A forgotten fact stays forgotten when the default visibility narrows or extraction runs again, while an explicit `remember` of the same claim still saves it. Transcript redaction also catches credentials assigned to names that end in a `key` word (`STRIPE_KEY=`), a `.env` file in the working directory can no longer set `GBRAIN_SURFACE`, the stale-editor-save check works on any Postgres encoding, and the throwaway test databases publish on loopback only.
+
+### Itemized changes
+
+- Jobs: `jobActorSql` (`src/core/minions/types.ts`) matches the job's stored audience as well as its attested actor, so `get_agent_job`, `get_job`, `wait_job`, `get_job_progress`, `list_jobs` (both paging modes) and `cancel_job` answer only the audience the job was submitted for; a job with no audience answers only callers that name none.
+- Write receipts: `sameAttestedActor` (`src/core/access/member-facts.ts`) compares a stored audience the same way, so `get_write_request`, `list_write_requests`, `cancel_write_request` and `request_id` replay stay with the audience the write was made for.
+- `get_status_snapshot` (`src/core/ops/skills-catalog.ts`) confines its sources to the `sourceScopeOpts` ladder `sources_list` and `get_health` use; the local CLI keeps every source.
+- Links (`src/core/engine-sql/links.ts`, `src/core/verbs/entity-card.ts`): every arm of `getLinks`/`getBacklinks`, traversal, `listLinkSources` and the entity card drop an edge whose origin page is soft-deleted, and, under a source grant, one whose origin page is outside it. For remote callers, `find_orphans` counts only links whose other endpoint and origin page are inside the caller's sources; the local operator's count stays brain-wide.
+- Facts (`src/core/facts/withdrawal.ts`, `backstop.ts`, `fence-write.ts`, `src/core/persistence/facts-prepare.ts`, `facts-maintenance.ts`): every automatic admission path (extraction, the refused-window retry, the withdrawal retry and the moved-facts follow-up) checks the withdrawal ledger under the lock at any visibility, so narrowing `facts.default_visibility` or extracting again never brings a forgotten claim back. `remember` with `content-origin user_said` still saves it.
+- Redaction (`src/core/secret-scan-assignment.ts`): the `high_entropy_assignment` key also accepts an identifier whose last word is `key` (`SUPABASE_SERVICE_ROLE_KEY=`, `deploy-key:`); `MONKEY=`, a bare `KEY=` and short or low-entropy values stay as written.
+- `.env` (`src/core/env-trust.ts`): `GBRAIN_SURFACE` joins `CWD_DOTENV_PROTECTED_KEYS`. A shell export still sets the stdio surface; a repository's `.env` cannot widen it.
+- Local-edit adoption (`src/core/persistence/local-edit-adoption.ts`): the stale-editor-save comparison trims and compares revisions in TypeScript, so it works on SQL_ASCII and LATIN1 databases. New doctor check `database_encoding` warns when a Postgres brain's `server_encoding` is not UTF8.
+- Test databases: `docker-compose.ci.yml`, `docker-compose.test.yml` and every documented `docker run -p` publish on `127.0.0.1` only.
+- Skills: `skills/conventions/untrusted-content.md` and the ingest skills describe the controls that ship (remote-read quoting in `transcript-quote.ts`, `TURN_CONTEXT_ENVELOPE`) and drop flag and fence names no code reads; text an agent ingests itself is stored at owner tier, unquoted.
+- Tests: `test/access-on-behalf-of.test.ts`, `test/status-snapshot-source-scope.test.ts`, `test/link-origin-scope.test.ts`, `test/transcript-redaction-key-names.test.ts`, `test/env-trust.test.ts`, `test/test-db-loopback-ports.test.ts`, `test/adopt-local-edit.test.ts`, `test/doctor-database-encoding.test.ts`, `test/managed-sweep-refused-window-retry.test.ts`, `test/managed-facts-withdrawal-recovery-6506.test.ts`, `test/managed-facts-withdrawn-skip-6506.test.ts`, `test/facts-entity-moved-7602.test.ts`, `test/untrusted-content-convention.test.ts` (PGLite and Postgres where an engine is involved).
+
+## [0.60.638.0] - 2026-11-10
+
+**Atoms extracted from a world page never carry a fence row the page shows only to its owner, and `gbrain repair atom-fence-rows` finds and narrows atoms stored before.** A world page's facts table can hold rows marked `visibility: private`, and its takes table is never part of what a remote caller reads. Atom extraction, take proposals and the patterns phase read a page as a world reader sees it, so what they produce holds only world rows. Atoms an earlier version stored may still hold such a row: doctor `atom_fence_rows` counts them and names the read-only preview, and only `gbrain repair atom-fence-rows --apply --expect <hash>` makes the previewed atoms private. Nothing runs on upgrade.
+
+### Itemized changes
+
+- `src/core/cycle/extract-atoms-input.ts`: a page's extraction input is its `publicBody` (facts rows other than world and the takes fence removed); the cap, the watermark and quote verification apply to that text, on the cycle phase and the managed path alike.
+- `src/core/cycle/propose-takes.ts`: the extractor receives the page's `publicBody`, and a proposal that restates a take held by someone other than `world` is dropped before it is filed; the content hash, fence skip and dedup rows still read the stored body.
+- `src/core/cycle/patterns.ts`: reflection excerpts in the subagent prompt and the quote-grounding sources are the reflection's `publicBody`.
+- `src/core/repair/atom-fence-rows.ts` (new, registered in `repair/core.ts`, `repair/registry.ts`, `persistence/preview-approval.ts`): explicit-only, preview-bound kind; the preview lists each world atom with its source page and the row kinds and numbers it carries (never the row text) and changes nothing; the apply sets `visibility: private` on exactly the previewed set through a revision-bound put_page.
+- `src/commands/doctor/checks/atom-fence-rows.ts` (new, a host-only `WAVE_CHECKS` entry, BRAIN category): `atom_fence_rows` warns with the count per source and the preview command.
+- Docs: `docs/guides/repair.md#atom-fence-rows` (what is listed, the apply, cost), `skills/RESOLVER.md`, key-files rows in `core-cycle.md`, `hindsight.md`, `core-cycle-patterns.md` and `memory-purge.md`.
+- Tests (PGLite and Postgres): `test/extract-atoms-world-fence-rows.test.ts` (cycle phase and managed brain: prompt, atoms and a remote read of each atom hold only world rows), `test/cycle-world-fence-rows.test.ts` (propose_takes input and proposals, patterns prompt and quote grounding), `test/repair-atom-fence-rows.test.ts` (doctor finding, preview changes nothing, apply without `--expect` refuses, apply narrows exactly the previewed atoms, unmanaged and managed).
+
+## [0.60.637.0] - 2026-11-10
+
+**A file Git puts back after sync deleted its page brings the page back, and the retention purge never deletes a committed file.** On a managed brain, a commit that removed a Markdown file made sync soft-delete its page. When the same file came back (a `git revert`, switching to a branch and back, a collaborator's delete-then-restore, a file missing from disk for one working-tree sync), sync settled the path as "deleted, file unchanged" and left the page out of get, search and recall while `gbrain sync status` said synced. `gbrain pages purge-deleted --yes` then deleted the restored file from the checkout. Sync now tells a tombstone it made from a missing file apart from a person's delete and imports the file over it, so the same page comes back; a brain an older version left in that state heals on its next sync. The purge leaves a file committed at the source's last synced commit or at HEAD alone, unless a person's delete of the page never removed the file (for example because another page shared it). A page purge also stops leaving timeline text in the write journal.
+
+### Itemized changes
+
+- `src/core/persistence/sync-pass.ts`, `sync-classify.ts`: the level read marks a tombstone a managed sync deletion made (its open `sync-delete-tombstone` record or uncompacted `managed_sync_delete` receipt); once its file is back with clean committed bytes it classifies `import` (the import revives the same page row), and a `file_drift` hold an older version raised over it re-runs. A person's tombstone keeps `deleted_same` / `deleted_edited`.
+- `src/core/persistence/sync-pass-run.ts`: the selection fingerprint carries `sync_deleted_restore`, so the first sync after the upgrade reads the whole source once and brings back pages left deleted beside their file.
+- `src/core/persistence/page-prepare.ts`, `sync-markers.ts`: a retention purge of a tombstone whose file is committed at the source's `last_commit` or HEAD removes no file: a sync-made tombstone defers (`revision_conflict`) to the sync that restores it; any other is purged database-only (`write_through.skipped: committed_file`), except a person's delete that made the tombstone and never removed its file (`write_through.written: false`, for example because another live page shared it), which still has the purge finish that removal. Publication re-checks, so a file committed while the purge was prepared is kept too. A sync-made tombstone defers only while its file is on disk; off disk (working-tree mode) it is purged database-only without a deletion marker, so the file's later return imports it. An unreadable checkout counts as committed; a checkout with no commit yet does not. Repo-less sources are unchanged.
+- `src/core/persistence/page-purge.ts`: a page purge redacts the `entry` summary and source and the `bullet` text of the page's `add_timeline_entry` receipts, compacted ones included (up to 10,000 per page; past that `journal_sweep.complete` is false).
+- Tests: `test/sync-restored-file-purge.test.ts` (PGLite and Postgres), `test/sync-classify-6712.test.ts`, `test/purge-eval-fixes.test.ts`.
+
+## [0.60.636.0] - 2026-11-10
+
+**A fact or take no longer disappears when gbrain re-creates a `## Facts` or takes section that a page rewrite dropped.** When an agent rewrote a page without its facts or takes section, gbrain correctly kept those rows live until the user decided. But the next `remember`, `takes add`, fact extraction, `gbrain facts relink` or dream-cycle merge of a duplicate stub page into that page built a new section holding only its own row, and the write after that (a tag, a timeline entry, an append, or a get and put round trip) read the new section as the user's answer: the remembered facts expired and the takes were deleted, on repo-less and Git-backed brains alike. Those writers now render the held rows back into the section they create, so nothing is lost; a fact the user forgot, a take they removed, and rows retired by an explicit empty section stay withdrawn. `gbrain repair lost-fence-rows` previews the rows an older gbrain already lost this way and, after `--apply --expect <hash> --yes`, puts exactly those rows back from page history.
+
+### Itemized changes
+
+- `src/core/facts/unfenced-facts.ts`: `heldFenceFactRows` lists the live rows a facts fence of the page held; `withHeldFactsFence` renders them into a new facts section when the page has none. Used by `remember` (`fence-fact-append.ts`), managed fact extraction (`persistence/facts-prepare.ts`, which also serves Google loops and the put backstop), `facts relink` (`relink-publish.ts`), unmanaged `writeFactsToFence` (`fence-write.ts`), cycle fact adoption (`planFence`) and the dream cycle's phantom redirect (`cycle/phantom-redirect.ts`, `cycle/phantom-redirect-managed.ts`).
+- `src/core/persistence/takes-prepare.ts`: `heldTakeRows` reads the stored takes while the take fence is held `fence_absent`; a takes write that creates the fence renders them first (covers `takes add`, `takes propose --accept` and consolidation).
+- `src/core/repair/lost-fence-rows.ts`: new explicit-only, preview-bound repair kind `lost-fence-rows`, registered in `repair/core.ts` and `repair/registry.ts`; `persistence/preview-approval.ts` accepts its approvals.
+- Docs: `docs/guides/repair.md#lost-fence-rows`.
+- Tests: `test/fence-absent-append-keeps-rows.test.ts` (remember, takes add, managed extraction and relink, each followed by a tag, timeline entry, append or round trip; forget, takes remove and an empty section stay withdrawn; a managed phantom redirect into the page keeps the held fact; repo-less and Git), `test/repair-lost-fence-rows.test.ts` (preview writes nothing, apply restores exactly the listed rows, deliberate removals and empty sections are not listed, a changed page is skipped).
+
+## [0.60.635.0] - 2026-11-10
+
+**A connected agent can no longer change, or learn about, a page it is not allowed to read.** A remote write token that could not read a `visibility: private` page could still overwrite that page's stored raw data, add links to or from it and remove its links, and `extract_entities` would link new entity stubs to a source page the caller could not read, or add a timeline line to an existing person page it could not read. Each of those answers also differed from the answer for a page that does not exist, so a caller could tell which hidden pages exist. They now answer exactly as for a missing page and change nothing. `ontology_propose` refuses an entity page its caller cannot read and stores an observation no wider than that page. `get_ingest_log` no longer names pages its remote caller cannot read or the host's checkout path, and `get_health` no longer lists such a page among the most connected. An MCP read that names a source or filter parameter with a slip (`source` for `source_id`, `type` for `types`) now gets an error naming the right parameter instead of an answer drawn from every source the token can read. `gbrain serve --http` now applies the `/mcp` rate limits and body cap when `GBRAIN_HTTP_RATE_LIMIT_IP`, `GBRAIN_HTTP_RATE_LIMIT_TOKEN` or `GBRAIN_HTTP_MAX_BODY_BYTES` is set; before, only the legacy transport read them. Trusted local CLI calls are unchanged.
+
+### Itemized changes
+
+- `src/core/persistence/page-visibility.ts`: `remoteTargetHidden` tests the caller's whole read policy (member access, then privacy with its grant and hatch), the policy `get_page` applies, instead of the member-access part alone; `remotePageAccess` and `remoteReadPolicySql` give the same test to a batch of slugs. `requireWritablePage` (so `put_raw_data`, `add_link` on either endpoint and the managed `add_timeline_entry` preflight) and `remove_link` use it; a delegated subagent write keeps its own privacy refusal.
+- `src/core/ops/extraction.ts`, `src/core/enrichment-service.ts`, `src/core/trust/taint.ts`: `extract_entities` treats a source page its remote caller cannot read as missing (no backlink, no trust read from it), skips an entity whose page the caller cannot read (`skipped_reason: page_not_found`, under the slug its name maps to, nothing written) and carries on with the rest of the batch, follows a retired entity page's redirect only through pages the caller can read, and counts mentions only on pages the caller can read.
+- `src/core/ops/chronicle.ts`: `ontology_propose` from a remote caller requires a readable entity page when one exists (a hidden one answers like `put_page`'s create on it) and tightens the observation's visibility to that page, as `remember` and `extract_facts` do.
+- `src/core/ops/ingest-log.ts`: for remote callers, `get_ingest_log` shows a row only when every page it names (in `pages_updated`, or in `source_ref` for rows that name one page there) is a live page the caller can read, and shows `source_ref` without host paths (a sync row keeps only its commit, an import row reads `<local path>`).
+- `src/core/ops/admin.ts`: `get_health`'s `most_connected` lists, for a remote caller, only pages its `get_page` would show.
+- `src/mcp/validate-params.ts`, `src/mcp/dispatch.ts`: `narrowingUnknownParams`; a read rejects an unknown scope or filter parameter in warn mode too (`mcp.strict_params` keeps its default), and `source`, `sourceId`, `sources` and `sourceIds` suggest `source_id` / `source_ids`.
+- `src/commands/serve-http-mcp.ts`: POST `/mcp` runs the IP bucket before the token lookup and the token bucket after it, each only while its env var is set, and passes `GBRAIN_HTTP_MAX_BODY_BYTES` (default the SDK's 4 MiB) to the transport; a value that is not a positive whole number is ignored with a warning. `SECURITY.md`, `docs/guides/memory-boundaries.md`, `docs/guides/remote-mcp.md` state the real defaults.
+- Tests: `test/access-hidden-page-writes.test.ts` (PGLite and Postgres; repo-less and managed), `test/serve-http-mcp-limits.test.ts` (a live server), `test/validate-params.test.ts`.
+- Also in this release (#9060): the chronicle long-conversation tests no longer fail when they run across midnight UTC, and the architecture file index describes the chronicle judged-input digest and the duplicate-events doctor check.
+
+## [0.60.634.0] - 2026-11-09
+
+**Privacy, trust and access checks written in SQL now give the same answer as their TypeScript versions, so remote callers can't see a page through one path that another path hides.** Several rules are evaluated twice: once in TypeScript on a page already read, and once in SQL for list, search, backlink and scan queries. Postgres `btrim(x)` strips only spaces, while JavaScript's `trim()` strips every Unicode edge whitespace character, and Postgres `lower()` follows the database collation. A page marked private through the `access` or `confidentiality` field, with other whitespace around the value (a YAML block scalar keeps a trailing newline), was hidden from remote `get_page` but not from remote list and search. The fast page filters also skipped the full check for `type: question` pages and pages with a `pinned_question` key, which the full check treats as private.
+
+### Itemized changes
+
+- `src/core/edge-whitespace.ts` (new): `EDGE_WHITESPACE`, exactly what JavaScript's `trim()` strips, `edgeTrimSql()`, and an ASCII-only lowercase for TypeScript and SQL. The generated SQL is plain ASCII, so it also runs on a Postgres database whose encoding is not UTF8; there the SQL side trims ASCII whitespace only.
+- `src/core/search/private-visibility.ts`: `privacyAliasSql` trims and lowercases like the row-side check; `privatePagesFilterFragmentFast` and the caller fast path send question and `pinned_question` pages to the full check.
+- `src/core/persistence/git-declared.ts`: `privacyClass` runs the lineage check for question pages too, so a question page built from a private input stays out of Git, as remote reads already hide it.
+- `src/core/trust/channel.ts`, `src/core/trust/backfill.ts`: the frontmatter trust caps and the backfill's extractor marker trim the same whitespace as the TypeScript caps; the transcript-harness cap lowercases ASCII on both sides.
+- `src/core/access/caller.ts` (local stdio member binding), `src/core/persistence/unbound-pages.ts` (database-only pages), `src/core/persistence/effect-journal.ts` (the `auto_link` / `mcp.remote_auto_links` gate), `src/core/repair/private-labels.ts` and `src/core/persistence/local-edit-adoption.ts` use the shared set.
+- Behaviour: a page whose alias value carries such whitespace, or a question or pinned-question page without `visibility`, is now hidden from remote list, search and backlink reads as well as from `get_page`. Doctor and repair counts that use these checks may move to match. Nothing rewrites stored pages.
+- Tests: `test/edge-whitespace-twins.test.ts` (PGLite and Postgres) holds each SQL check equal to its TypeScript side on generated inputs and checks remote list and search; `test/trust-claim.test.ts`, `test/trust-backfill.test.ts` and `test/remote-graph-freshness.test.ts` gain edge-whitespace cases.
+
+## [0.60.633.0] - 2026-11-09
+
+### Added
+
+- `gbrain skills index build|status|remove` and `gbrain skills resolve`: an engine-free skill resolver that ranks a harness's skill catalog against one user turn and prints a short `<relevant_skills>` block (at most 5 suggestions, at most 400 tokens), so an agent with hundreds of skills sees the few that fit. Off by default; nothing changes until you build a catalog and call it. Works with no brain, on thin clients and while `gbrain serve` holds the PGLite lock. Word matching only (the BM25F ranker frozen by the Step 1 offline eval); nothing leaves the machine. Sessions never repeat a suggestion and share a 2,000-token budget (`skills.resolver.session_token_budget`). JSON contract in `docs/schemas/skill-resolver.v1.*.json`; library as `gbrain/skill-resolver` and, for Node, one dependency-free module built from the same source: `gbrain skills library` writes it to `GBRAIN_HOME/lib/gbrain-skill-resolver.mjs` and prints its sha256, and each release attaches `gbrain-skill-resolver.mjs` with a `.sha256`. Each suggestion carries `match_strength` (`named`, `name`, `triggers`, `routing`, `description` or `body`) so an adapter can drop weak matches. Guide: `docs/guides/skill-resolver.md`.
+- `gbrain setup claude-code|codex --skill-loading resolve`: a per-turn hook lane (`GBRAIN_HOOK_LANE=skill-resolver`) that adds the resolver's block to every prompt, with the harness's own load line. Setup builds the user catalog first and writes the `skills.resolver.*` keys and the hook only when it found at least one skill (`skill_resolver_setup_incomplete` otherwise); `--skill-loading off` and `setup --remove` undo all of it. The lane runs in the hook process with no brain and no serve, exits within 50 ms with nothing printed when it cannot deliver, drops a block over `skills.resolver.lane_payload_chars` whole, and lets exactly one wiring deliver. Claude Code project skills get their own catalog, built in the background. `gbrain doctor` reports it as `skill_resolver`. Off by default; with it off, hook output and setup's files are unchanged. A `config.json` that holds only `skills.resolver` settings no longer reads as a Postgres brain. Release binaries are now built with the lane's worker as a second entrypoint.
+
+## [0.60.632.0] - 2026-11-09
+
+**A page write that git could not commit because the file is flagged assume-unchanged or skip-worktree now stays in the write-through pending ledger.** gbrain's own page writes and `gbrain git commit-push --pending` asked `git status` which pending files were still uncommitted, and status does not show a flagged entry, so the write was left uncommitted, dropped from the ledger (doctor `dirty_age` never reported it and no later write retried it), and `--pending` answered `nothing_to_commit` with exit 0. A flagged file whose bytes differ from HEAD now counts as uncommitted.
+
+| Situation | Before | After |
+| --- | --- | --- |
+| A page write to a flagged file | not committed, not in the ledger | not committed, kept in the ledger (the write itself fails `commit_paths_skipped`, as in 0.60.630.0); doctor reports it as `dirty_age` after 30 minutes |
+| A later page write while a flagged file is in the ledger | the entry was settled away | the entry is committed beside the new write when git picks it up, and otherwise stays |
+| `gbrain git commit-push --pending` with a flagged pending file | `nothing_to_commit`, exit 0 | `commit_paths_skipped` naming the file, exit 1; the ledger keeps it |
+| A page write or `gbrain git commit-push` naming a modified skip-worktree file that is on disk | `git add` refused it: `commit_paths_invalid`, nothing committed, and a page write dropped the file from the ledger | the other paths are committed; the file is reported as skipped (`commit_paths_skipped`, reason `skip_worktree`, exit 1 from `commit-push`) and a page write keeps it in the ledger |
+
+### Itemized changes
+
+- `src/core/git/commit-push.ts`: the pending-ledger check (`dirtyPaths`, used by the write-through commit, `--pending`, ledger settling and doctor `dirty_age`) also counts flagged entries whose bytes differ from HEAD, using the same check as the GST-2116 skipped-path detection (`flaggedChanges`), where an entry git cannot hash counts as changed instead of failing the check and a flagged gitlink is left out; `commitPaths` no longer hands `git add` a named skip-worktree file that is on disk (git refuses it and failed every named path), and reports it as skipped; the write-through commit notes its own flagged files that git left out in the ledger, and ledger settling keeps every entry when the check fails.
+- Docs: `docs/guides/shared-checkout-git.md` (pending write-through section).
+- Tests: `test/pending-ledger-flagged-gst2118.test.ts` (real git and the real CLI: a flagged write-through file stays in the ledger and doctor's dirty check sees it, a later write commits an older flagged entry instead of settling it away, `--pending` on a flagged file fails and keeps the entry, and a flagged entry git cannot hash is kept while a later write still commits, a write to a named skip-worktree file beside another page commits the other page and keeps the file for `--pending` to report, and an ordinary pending file as the control). Five of its six cases fail without the fix; the control passes.
+
+## [0.60.631.0] - 2026-11-09
+
+**A long conversation that keeps growing is no longer re-extracted, and re-paid for, on every new message.** Automatic event extraction reads a page's title, date, attendees and the first 12,000 characters of its body. On a conversation longer than that, each new message recorded a new revision, and each revision paid for another extraction call on exactly the same text. The model words each event a little differently every time, event pages are named after that wording, and an extraction of a page longer than 12,000 characters never retired the previous one, so every run added a fresh copy of every event. One page could collect dozens of paid calls and hundreds of duplicate events. Now a revision that changes nothing extraction reads (text, title, date, attendees, privacy) makes no call and writes nothing (it records `judge_input_unchanged`); a window the judge keeps failing on (its answer cut off, unreadable, malformed or over the per-page spend cap) is paid for at most the page's attempt limit across all revisions, retries included, then records `judge_input_failed` until the text changes, a release changes the extractor, or a backfill asks again (a run a newer revision replaced, or a missing provider or price, never counts toward that limit); and a re-extraction that re-read all the text the page's live events came from (for example after a title change, or the first time a conversation grows past 12,000 characters) replaces those events instead of adding to them. An extraction that dropped proposals over `chronicle.max_events_per_page` is asked again when that setting or the timezone changes, and one that dropped proposals dated after the page's last day is asked again, once, when that day moves. A page whose opening text was edited still keeps its earlier events, as before. Text past the first 12,000 characters is still not extracted; incremental coverage of the tail is tracked in #9013. Reported by @andreineacsu.
+
+**Doctor counts the duplicates earlier releases left.** The new `chronicle_duplicate_events` check (info) reports how many pages hold live events from earlier extraction runs beside their newest run's, and how many such events. It changes nothing; a preview-first repair that retires them is tracked in #9012.
+
+### Itemized changes
+
+- `src/core/chronicle/execute.ts`: before the daily reservation, a row whose judge input digest equals that of the page's latest decided extracted generation (no ineligible revision or chronicle retirement since) finishes `skipped` / `judge_input_unchanged` with no call; an automatic row whose input already used the attempt limit without publishing finishes `failed` / `judge_input_failed` (a refused input stays `judge_refused`), with no call, summing `judge_input_failures` over every row of the page with that digest, the current revision's retries included (only a `judge_truncated`, `judge_parse_failed`, `malformed_proposal`, `budget_exhausted` or `judge_refused` attempt increments it); a truncated generation replaces the previous one only when every live chronicle event of the page is recorded by a ledger row whose judged window the new window starts with. Ended-invite projections and held results never count as judged, and each finish that judged writes the judged input outright, so a held retry clears what a failed attempt recorded (a row a newer revision replaced before its retry keeps it); a generation that dropped future-dated proposals records `cutoffInputHash` (the digest keyed to the screen's cutoff day).
+- `src/core/chronicle/extract-events.ts`: `chronicleJudgedInput` (digest of the judge input with the body cut to `JUDGE_BODY_CHARS`, the extractor version, the depth page's visibility and source incarnation, the timezone and `chronicle.max_events_per_page`; the window and its sha256) and `cutoffInputHash`.
+- Migration `v297` `chronicle_judge_window`: `chronicle_page_state.judge_input_hash`, `judge_window_chars`, `judge_window_hash` (nullable) and `judge_input_failures` (`NOT NULL DEFAULT 0`); no backfill, so existing rows start at no judged input and zero counted failures. A row recorded before it has no window, so that page's next revision is judged once more and stays additive.
+- `src/core/chronicle/reasons.ts`, `src/core/error-registry.ts`: reason codes `judge_input_unchanged` and `judge_input_failed`.
+- `src/core/chronicle/ledger-stats.ts`, `src/commands/doctor/checks/auto-chronicle.ts`: `readChronicleDuplicateEvents` and the `chronicle_duplicate_events` doctor check.
+- Docs: `docs/guides/life-chronicle.md`, `docs/guides/error-codes.md`.
+- Tests: `test/chronicle-long-conversation-8972.test.ts` with its Postgres arm `test/e2e/chronicle-long-conversation-8972-postgres.test.ts`; schema, migration and doctor goldens regenerated for the new columns and check.
+
+## [0.60.630.0] - 2026-11-09
+
+**`gbrain git commit-push` and `scripts/brain-commit-push.sh` no longer report success when git left a named path uncommitted.** `git add` stages nothing and still exits 0 for a modified file flagged assume-unchanged or skip-worktree and for a file inside a nested Git repository, so the helper answered "nothing to commit" (or pushed the other paths) with exit 0, and the write sat uncommitted with nothing in any log. Now the other named paths are still committed (and, on a classic checkout, pushed), and the run exits 1 naming each skipped path and its reason: `writer_coordinator_required` for a page in a managed canonical worktree, which belongs to the persistence owner (save it through `put_page`), and the new `commit_paths_skipped` for anything else. The helper's own managed-checkout refusal now prints the operator contract (code, why, fix, next) instead of one line.
+
+| Situation | Before | After |
+| --- | --- | --- |
+| A named file is flagged assume-unchanged (or skip-worktree under a named directory) and modified | `nothing to commit`, exit 0; the edit stays uncommitted | `commit_paths_skipped` (reason `assume_unchanged` / `skip_worktree`), exit 1; fix (ask the user): `git update-index --no-assume-unchanged -- <paths>`, and a separate `git update-index --no-skip-worktree -- <paths>` (given both flags, git clears only the first) |
+| A named file sits inside an untracked nested repository | exit 0 with nothing committed; beside other paths, `git_unavailable` and nothing committed | the other paths are committed, then `commit_paths_skipped` (reason `not_staged`), exit 1 |
+| The same on a managed canonical worktree, for a page | `nothing to commit; not pushed`, exit 0 | `writer_coordinator_required`, exit 1, naming each page; fix (ask the user): save it through `put_page` with the managed source (`gbrain put --source-id <source> <slug>`, `source_id` over MCP) |
+| The push fails after a path was skipped | the push error alone | `commit_paths_skipped` still names each skipped path, with the push error beside it, exit 1 (the CLI; the helper without gbrain exits 4) |
+| A gbrain write-through commit (`commitPathsLocked`) that git leaves a named path out of | the commit returned as saved | `commit_paths_skipped` after the rest is committed |
+| `scripts/brain-commit-push.sh` without gbrain on the machine | `nothing to commit`, push, exit 0 | the push still runs, then `Error [commit_paths_skipped]` with each path, exit 1 |
+| `scripts/brain-commit-push.sh` on a checkout marked managed | one line, `writer_coordinator_required: submit managed changes through persistence`, exit 1 | `Error [writer_coordinator_required]` with `Why:`, `Fix:` (put_page; `gbrain git commit-push` for files that are not pages) and `Next: ask_user`, exit 1 |
+
+A skip-worktree file absent from disk (a sparse checkout), a flagged gitlink (its commit lives in the nested repository) and ignored files under a named directory are not reported; a named ignored file was already refused by `git add` (`commit_paths_invalid`). Existing brains get the new helper on the next `gbrain sources harden`.
+
+### Itemized changes
+
+- `src/core/git/commit-push.ts`: after the commit step, `commitPaths` reads which named paths HEAD still lacks (flagged entries whose bytes on disk differ from HEAD, named files git did not index, and status entries with unstaged changes) and leaves an unindexed file out of `commit --only`, so it no longer fails the other paths. The check runs after the commit's index-restore block, so a failure there never stages a reversal of a commit that already landed. The managed `put_page` fix carries the managed source in its CLI argv and MCP arguments, so following it cannot write a same-slug page in another source. `commitAndPush` (classic, managed and remoteless) throws `commit_paths_skipped` or, for a page in a managed worktree, `writer_coordinator_required`, after committing and publishing the rest; `detail` carries the skipped paths, the commit and the pushed head.
+- `src/core/brain-repo-durability.ts`: the rendered `scripts/brain-commit-push.sh` prints the operator contract on its managed refusal, and its fallback (no gbrain) runs the same check after its commit (NUL-separated listings, so a non-ASCII or quoted name is read exactly; a symlink is compared by its link text), leaves a file git did not index out of `commit --only`, and exits 1 with `commit_paths_skipped` after the push.
+- `src/commands/git.ts`: when the run fails after the other paths were pushed, the push log still records that push.
+- `src/core/error-registry.ts`: new code `commit_paths_skipped` (reasons `assume_unchanged`, `skip_worktree`, `not_staged`).
+- Docs: `docs/guides/shared-checkout-git.md` (the `commit_paths_skipped` row, the `writer_coordinator_required` row, the fallback paragraph), `docs/guides/error-codes.md` (regenerated).
+- Tests: `test/git-commit-push-skipped-paths-gst2116.test.ts` (the real CLI and the rendered helper against temp repositories, a bare remote and a managed-root registry: an assume-unchanged page, a nested-repository page beside a committable one, a skip-worktree entry under a named directory, a managed page and a managed non-page file, a remoteless checkout, a named directory inside a nested repository, a run with both flags, the helper's fallback (a non-ASCII path, a nested-repository file beside a committable page, a clean flagged symlink), the helper handing over to gbrain on a managed root, its managed refusal; a named directory beside a sparse entry and an ignored draft still commits with exit 0). Also: the write-through door, a push that fails after a skipped path (CLI and helper), a named assume-unchanged gitlink beside a committed page (the commit stands and no reversal is staged), and the managed fix's source. Sixteen of its eighteen cases fail on master; the two that pass there are the sparse-entry control and the gitlink case, which guards this change's own post-commit path.
+
+## [0.60.629.0] - 2026-11-09
+
+**`gbrain repair file-drift` now agrees with sync on a held origin-twin page.** A legacy page left as an origin twin with no recorded file (no import record) could be held `file_drift` by sync while `repair file-drift --slug <slug>` reported `no_drift`. The hold's own suggested fix couldn't clear it, and scripts that use the preview as a drift check passed falsely. The preview now reads such a twin against its slug-path file, the same way sync imports it, and lists it with an apply command.
+
+### Itemized changes
+
+- `src/core/persistence/drift-conflicts.ts`: `liveFileDrift` reads an adoptable origin twin with no recorded file against its slug-path file. A twin in a read-only mirror source, whose slug path no file can import as, whose slug-path file sync doesn't admit (outside its scope or under `sync.exclude`), or whose slug-path file another page records as its source path keeps `database_only`. A slug path several files import as keeps the earlier reading instead of reporting `slug_path_ambiguous`. A twin under a declared db_only path, which sync holds but no repair can adopt, reads `unknown` (`db_only_slug_path`) instead of passing as `no_drift`, and so does a slug-path file another page names only by file URI (`shared_origin`), since sync still imports it into the twin.
+- `src/core/persistence/reconcile-state.ts`: the slug-path adoption check moves into one exported `adoptableSlugOrigin`, which reconcile and the drift preview now share. Reconcile's behaviour is unchanged.
+- Applying either side to such a twin binds the slug-path file as its `source_path` and clears `origin_twin`. Maintenance writes to a twin whose slug-path file differs are now refused as drift, like any drifted page.
+- Tests: `test/repair-file-drift-origin-twin-gbra108.test.ts` (PGLite, managed source, real git): a legacy page with no import record held by sync, previewed and applied for both `--prefer database` and `--prefer file`, after which a re-sync clears the hold; also mirror-read-only, db_only, non-importable slug path, missing file, shared-origin, excluded slug path, URI-only claimant and ambiguous slug path cases.
+
+## [0.60.628.0] - 2026-11-09
+
+**A page a member-bound credential creates in a federated source is now readable only by that member.** A token or OAuth client bound to a member (`gbrain auth rescope --member <id>`) and granted `--sources <id>` for a federated source wrote its pages there with no readers. Every credential without a source grant reads `default` plus every federated source, so another member's no-grant token and an unbound token read those pages over `get_page`, `search`, `query`, `recall` and `list_pages`. Such a page is now written with `readable_by: [member:<id>]`, as a page the credential writes to `default` already was, and `POST /ingest` refuses the credential. A write source that is not federated keeps the audience its grants give it. Pages written before the upgrade keep their readers, and `gbrain access who-can-read <slug>` shows who reads one.
+
+### Itemized changes
+
+- `src/core/source-resolver.ts`: `noGrantFloorReads` says whether a caller with no source grant reads a source unqualified: `default`, or a source in the federated set `noGrantFederatedScope` threads for that floor. It throws when the sources cannot be read.
+- `src/core/persistence/page-visibility.ts`: `defaultSourceMemberWriter` keys on `noGrantFloorReads` instead of the literal `default`, so a member-bound write to a federated source is stamped too. A source table it cannot read refuses the write instead of publishing the page shared.
+- `src/commands/serve-http-webhooks.ts`: the `POST /ingest` refusal names the credential's write source.
+- Docs: `docs/guides/multi-source-brains.md`, `docs/tutorials/company-brain.md` (Model C), `docs/mcp/ADMIN.md`.
+- Tests: `test/access-federated-member-writes.test.ts` (PGLite, and Postgres with `DATABASE_URL`): a member-bound token or OAuth client granted a federated source creates a page that another member and an unbound token, reading the federated set as the HTTP transports do, cannot read; with `default` isolated the floor is `default` alone and nothing is stamped; a streamed upload over the 24 MiB ceiling is kept to its member too; a write whose source config cannot be read is refused, not published unstamped; a non-federated source stays unstamped and out of unbound reads; a member-bound write cannot leave its granted source; `POST /ingest` refuses with nothing queued.
+
+## [0.60.627.0] - 2026-11-09
+
+**A webhook capture can no longer drop a page's readers (GST-2112).** `POST /ingest` wrote through a trusted local path whose only check was that the sender could read the page, so a member-bound token granted a source could replace a page whose `readable_by` named it with a body that named no readers, and every caller could then read the page. The route and the `ingest_capture` job now apply the remote `put_page` readers rule: a body that drops `readable_by` from a page that names readers, or names readers that leave out the sender, is refused `readable_by_invalid` (403 at the route, nothing queued; at write time for a job already queued). The job binds its write to the revision it checked, so readers added between the check and the write refuse the write with `revision_conflict` and the retry refuses `readable_by_invalid`. A capture already queued from a member-bound credential whose write source is `default` is refused `permission_denied` at write time, as the route refuses it before queueing. Bodies that keep the readers, and pages without readers, import as before.
+
+### Itemized changes
+
+- `src/commands/serve-http-webhooks.ts`: the route applies the remote readers rule to the capture body before anything is queued.
+- `src/core/minions/handlers/ingest-capture.ts`, `src/core/import-file.ts`: the job reads the page snapshot before the visibility check, applies the same rule at write time, binds its write to the checked revision (`revision_conflict` when it moved; a page that did not exist stays a create), and refuses a member-bound `default` writer `permission_denied`.
+- `src/core/behavior-change-notice.ts`: one row for the changed capture behavior.
+- Docs: `docs/guides/write-refusals.md`.
+- Tests: `test/ingest-capture-keeps-readers.test.ts` (PGLite and Postgres).
+
## [0.60.626.0] - 2026-11-09
**`gbrain sources record-origin --remote` now locks down the existing checkout too, and on a managed brain it can no longer report success while a reclone still clones with git-lfs on.** On a managed brain the record took only the source row lock, so a reclone that had already read the source, or held its worktree locks, could clone with git-lfs downloads and hooks on after the command said the source was recorded. The record now takes the worktree locks and rows a reclone takes (refusing the id `source_busy` while one runs), and the reclone reads the record under its own locks. `--remote --apply` now also turns git-lfs downloads and hooks off in the existing checkout's `.git/config`, because a reclone only happens when a checkout is lost or replaced, and until then doctor read green while the checkout still fetched git-lfs objects and ran hooks. The git-lfs check now reads a committed `.gitattributes` under a directory whose name holds a tab (it was cut at the tab and skipped), ignores commented-out `filter=lfs` lines, says "declares a git-lfs filter" when a rule only declares one, and records a clone of an empty repository instead of telling the operator to restore an intact checkout. A failed write is reported for its own id instead of ending the run without saying which ids were recorded.
diff --cc docs/architecture/key-files/security.md
index bdb23df5f0,6578597237..c781a8a551
--- a/docs/architecture/key-files/security.md
+++ b/docs/architecture/key-files/security.md
@@@ -31,8 -29,8 +31,8 @@@ Current behavior and load-bearing invar
- `src/core/ssrf-validate.ts` — DNS-rebinding-defended URL validation. `validateAndResolveUrl(url)` resolves the hostname via `dns.lookup({all: true, family: 0})`, checks EVERY A and AAAA record against the internal-IP deny list, and returns the resolved IP so callers fetch by IP (validation IP === fetch IP defeats DNS rebinding). `fetchWithSSRFGuard(url, opts)` does redirect-aware fetching with per-hop re-validation (max 3 hops by default). Reusable across all URL-fetching features. Test seam `__setDnsLookupForTests` for hermetic tests.
- `src/core/trust/` — memory trust tiers (#5575). `tier.ts`: the six tiers in filter order (`user_confirmed` > `operator_curated` > `tool_observed` > `agent_written` > `unknown` > `external_untrusted`), `TRUST_TIER_LABELS` (the fixed user-facing labels; enums only in JSON), `USER_SAID_TRUST_LABEL` (the label of an `agent_written` row whose `write_origin.content_origin` is `user_said`; the tier never rises, the eval harness reads the constant), `minTrust`/`maxTrust`/`admitsTrust`/`tiersAtOrAbove`, `contentOriginTier` (`tool_output` lowers to external), `storedMinTrust` (a damaged token floor fails closed to the strictest), and `effectiveWriteTrust`, which computes a write's tier once (derived writes capped at `agent_written` and their least trusted input; `write_origin.taint_inputs` keeps the 32 least trusted with `taint_inputs_truncated`/`taint_input_count`). `schema.ts` (migration only, like attribution): `trust_tier` + `write_origin` on facts, takes, timeline_entries and pages, the page_versions snapshot, `min_trust` on oauth_clients/access_tokens, `trust_proposals`, and the BEFORE ROW `trust_tier_stamp` trigger (fires last: INSERT gets the writer's tier from `gbrain.write_trust_tier` or `unknown`; a `TRUST_CONTENT_COLUMNS` change restamps for an owner-tier writer and takes min(prior, writer) otherwise; an unchanged row keeps its tier; a raise needs `gbrain.write_trust_promotion` covering it, or `gbrain.write_trust_backfill` from `unknown` to below `user_confirmed`, else `trust_raise_refused`). Writers declare through `WriteAttribution.trust`, `withWriteTrust` and `maintenanceTransaction(…, trust)` (`persistence/context.ts`; nested declarations combine as min, a group member resets). `confirm.ts`: `requireOwnerConfirmation` (a remote caller needs `memory_confirm`; the local CLI needs a TTY where the user types the target token; `--yes` never confirms), `tierRaiseFix`, `trustRaiseRefusal`, test seam `__setConfirmationIoForTests`. `min-trust.ts`: the local-only floor writes behind `gbrain auth create --min-trust` and `gbrain auth set-min-trust`. `backfill.ts`: `gbrain trust backfill` (deterministic signals, read-only dry run that works before the migration, resumable batches inside `withCoordinatedWrite` on managed brains) and the doctor `trust_tiers` counts. Tests: `test/trust-tier.test.ts`, `test/trust-tier-schema.test.ts` and `test/trust-backfill.test.ts` (PGLite and Postgres), `test/trust-confirm-scope.test.ts`. Write side (lane L1a): `channel.ts` computes the tier once per write from the channel (`requestChannelTrust`: agent verbs agent_written, `content_origin: tool_output` external_untrusted, connector jobs external_untrusted; owner sync/import `ownerImportTrust`: operator_curated or the `sources set-trust` default, lowered by frontmatter markers `frontmatterTrustCaps`) and `stampTrustMarker` (the lower-only `trust_tier` marker, CEO-21); `page-write.ts` wires it into page-prepare (marker stamp, fence edits keep the page tier via `withTrustKeep`, `lower_page` proposals on agent rewrites, the page gate tier; on an unclassified page `stampPageTrustMarker` also caps the marker by the stored frontmatter's own lowering markers, so a write that removes one cannot raise the page, #7873; a derived `submit_job` page with a derivation declaration stamps the marker too, #7905); `proposals.ts` is the `trust_proposals` store and handler dispatch (`decide.ts` loads every handler); `supersede-handlers.ts` is guarded supersession (`supersessionGuarded`, contested fact/take/ontology proposals, remote `forget_requires_owner`, the trust store for the checked decide_proposals supersede); `fence-guard.ts` guards the facts-fence re-projection and gates new fence rows, and holds take and timeline rows a lower-tier write would delete, replace or deactivate (`guardFenceTakes`, `heldRows`, `contestHeldRows`; projection, `takes_remove`, takes reconcile, timeline orphan prune; W1 #6783 §12 (a)); `held-removals.ts` is the owner's accept of those `forget` proposals (the page's text rules the row; a refused `takes_remove` reruns as an owner `takes_remove` bound by a nonce); `propagation.ts` lowers rows derived from a lowered input through `derivation_inputs` and never promotes (`propagateTierLowering`, §12 (b)); tests `test/trust-held-removals.test.ts` (PGLite and Postgres); `gate-outcomes.ts` is the DX-1 `gate` field and the held-write verb error. Owner actions: owner actions (#5575 lane L1a-owner: A4, CEO-2, CEO-9, CEO-12, DX-2, DX-7, DX-10, DX-13, DX-14, DX-15, ENG-15). `owner-actions.ts`: `previewOwnerAction` / `applyOwnerAction` for confirm, drop, release, revert, allow, allow_remove, disable and enable: the preview names the summary, the typed token (the ref, or a hash8 for page refs), the exact command, whether the action raises trust and a `binding` of the target's exact state (row content and tier, page revision, proposal status); apply re-previews, refuses a moved binding with `preview_changed` and a raising action without a confirmation with `confirmation_required` (`ownerActionFix` is the DX-3 `tell_user_to_run` fix). Fact and take confirms are tier-only updates under `withTrustPromotion` (inside `withCoordinatedWrite` on a managed brain); the hold store is an isolated adapter over `write_gate_holds` (`__setHoldStoreForTests`, `TODO(L2a-merge)`); on a managed brain its `publish` (`release-publish.ts`) releases a held fact whose page exists as a journaled `trust_release` request: `prepareTrustReleaseMutation` appends the fact to its entity page's facts fence with `prepareFenceFactAppend` (or, for a hold naming `payload.row_num`, indexes the row its file already holds), flips the hold and writes the row at user_confirmed (origin `trust_release`, ledger cause `{hold}`) in one publication, locks and rechecks the hold in validate (`preview_changed`), previews and binds an index-existing release's cell fields and refuses `preview_changed` when the cell no longer matches (`releaseCell`, `releaseCellFields`, origin `fields_previewed`; #7656; doctor `trust_release_unpreviewed_fields` lists earlier releases without it), while the database-only fallback re-checks the binding on the locked hold (#7657), keys the request id on the hold and its approved state, and refuses a deleted or private page with the fact still held; a hold with no entity slug or no page keeps the database-only release; `disable --all` writes `write_gate.external_mode=off`, `write_gate.agent_mode=off`, `trust.agent_activation=allow` with the `trust.kill_switch` receipt that `--undo` restores from. `page-handlers.ts`: `confirmPage` (removes the CEO-21 `trust_tier` marker through a journaled `trust_owner_page` mutation on a managed brain, `importFromContent` otherwise; tier only when no marker), `revertPageToVersion` (the version's content and its snapshot tier, `unknown` for legacy versions), the coordinator preparer `prepareTrustOwnerPageMutation` (dispatched from `persistence/service.ts`; re-checks the approved revision and refuses a remote request without `memory_confirm`), and the `lower_page` handler (accept = confirm, reject = dismiss, `revertLoweredPage` = restore the prior owner version). `refs.ts`: typed refs `f<id>`, `t<id>`, `h<id>`, `tp<id>`, `a<id>`, `p:<source>/<slug>`, bare slugs resolved by `--source` or a single source (ambiguity refuses). `review.ts`: `buildTrustReview` (pending proposals, lowered pages, unconfirmed standing preferences, holds, allow rules, kill-switch state, grouped by day and page, complete argv) and `explainTrust`. `allow-rules.ts`: the `trust_allow_rules` table (migration v229, receipted, removal keeps the row) and the pure `matchTrustAllowRule` over server-stamped fields. `owner-ipc.ts`: the `trust_read` / `trust_preview` / `trust_apply` administration handlers a resident owner serves over its 0600 socket to the verified local CLI only. Tests: `test/trust-owner-actions.test.ts` (PGLite and Postgres), `test/trust-release-fence.test.ts` (PGLite and Postgres), `test/trust-owner-ipc.test.ts`, `test/trust-cli.test.ts`. Derived-row taint (`taint.ts`, `derived-gate.ts`, `timeline-projection.ts`): see [security](security.md).
-- `src/core/eligibility/{policy,sql,labels,registry,stamp,activation,scan,explain}.ts` — the one reversible read eligibility policy for memory trust (#5575 A6, A7, CEO-18, CEO-20, DX-6, DX-10, ENG-8, ENG-14). `policy.ts`: `resolveReadEligibility` returns the effective floor (the strictest of `AuthInfo.minTrust`, the caller's `min_trust` and `trust.read_policy=filter`'s own `unknown` floor; label mode adds nothing, so ordering is byte-identical) and, for proactive reads, `suppressFlagged` unless `trust.agent_activation=allow`. `sql.ts`: vetted predicates over a caller alias (closed vocabularies only): `trustFloorSql`, `pageEligibleSql` (spliced by `buildVisibilityClause` and `pageReadFilter`, so every search arm filters before LIMIT; a chunk's tier is its page's), `projectionEligibleSql` (facts, takes and timeline reads: a quarantined page's projections and `needs_rederive` rows are hidden, never expired) and `activationSuppressedSql` (tier at or below `agent_written` plus an instruction-family `write_gate_receipts` flag). `labels.ts`: `trust_tier` + a short server-stamped `origin` (`trustFields` appends `:user_said` for a relayed user statement, which `trustLabelWords` reads as `USER_SAID_TRUST_LABEL` unless the row is flagged unconfirmed); compact per-item text labels with the fixed words, `unknown` as a short origin line, and the `<external-data>` envelope only below `unknown`. `registry.ts`: `OP_READ_TRUST` classifies every read-scope op `filtered | labeled | text_free` (the dispatcher refuses a `labeled` op for a floored token) and `PROACTIVE_SURFACES` lists the injecting surfaces, each calling `proactiveEligibility(ctx, id)`; drift-tested by `test/eligibility-registry.test.ts`. `stamp.ts` labels rows after ranking and backstops the floor for rows a stage adds by slug; explicit reads mark flagged rows `unconfirmed`. `activation.ts` partitions proactive candidates (`partitionForActivation`, `pageActivationVerdicts`) and builds the `memory_suppressed` notice (count + `gbrain trust review`, never content). `scan.ts` (`gbrain trust scan`, doctor `trust_scan`) records flag receipts for agent-written-or-lower rows written before the gate, in resumable keyset batches bounded by the id ceiling of its first run (later rows are gated by their writers; a detector bump rescans). `explain.ts` is the `gbrain trust explain` data API: tier, origin, receipts and the per-surface decision for a typed ref. Tests: `test/eligibility-{policy,registry,reads}.test.ts`.
+- `src/core/eligibility/{policy,sql,labels,registry,stamp,activation,scan,explain}.ts` — the one reversible read eligibility policy for memory trust (#5575 A6, A7, CEO-18, CEO-20, DX-6, DX-10, ENG-8, ENG-14). `policy.ts`: `resolveReadEligibility` returns the effective floor (the strictest of `AuthInfo.minTrust`, the caller's `min_trust` and `trust.read_policy=filter`'s own `unknown` floor; label mode adds nothing, so ordering is byte-identical) and, for proactive reads, `suppressFlagged` unless `trust.agent_activation=allow`. `sql.ts`: vetted predicates over a caller alias (closed vocabularies only): `trustFloorSql`, `pageEligibleSql` (spliced by `buildVisibilityClause` and `pageReadFilter`, so every search arm filters before LIMIT; a chunk's tier is its page's), `projectionEligibleSql` (facts, takes and timeline reads: a soft-deleted page's projections (`deletedPageProjectionHiddenSql`: a fact on or about the page, by `source_markdown_slug` or `entity_slug` in its own source, and the page's takes and timeline rows, back on `restore_page`), a quarantined page's projections and `needs_rederive` rows are hidden, never expired) and `activationSuppressedSql` (tier at or below `agent_written` plus an instruction-family `write_gate_receipts` flag). `labels.ts`: `trust_tier` + a short server-stamped `origin` (`trustFields` appends `:user_said` for a relayed user statement, which `trustLabelWords` reads as `USER_SAID_TRUST_LABEL` unless the row is flagged unconfirmed); compact per-item text labels with the fixed words, `unknown` as a short origin line, and the `<external-data>` envelope only below `unknown`. `registry.ts`: `OP_READ_TRUST` classifies every read-scope op `filtered | labeled | text_free` (the dispatcher refuses a `labeled` op for a floored token) and `PROACTIVE_SURFACES` lists the injecting surfaces, each calling `proactiveEligibility(ctx, id)`; drift-tested by `test/eligibility-registry.test.ts`. `stamp.ts` labels rows after ranking and backstops the floor for rows a stage adds by slug; explicit reads mark flagged rows `unconfirmed`. `activation.ts` partitions proactive candidates (`partitionForActivation`, `pageActivationVerdicts`) and builds the `memory_suppressed` notice (count + `gbrain trust review`, never content). `scan.ts` (`gbrain trust scan`, doctor `trust_scan`) records flag receipts for agent-written-or-lower rows written before the gate, in resumable keyset batches bounded by the id ceiling of its first run (later rows are gated by their writers; a detector bump rescans). `explain.ts` is the `gbrain trust explain` data API: tier, origin, receipts and the per-surface decision for a typed ref. Tests: `test/eligibility-{policy,registry,reads}.test.ts`.
- - `src/core/trust/taint.ts`, `derived-gate.ts`, `timeline-projection.ts` (#5575 derived rows; the rest of `src/core/trust/` is above): `taint.ts` (I2, ENG-3/ENG-7): `readTaintInputs`/`deriveTrust` read the stored tiers of every row a deriver placed in its prompt (a vanished input reads `unknown`); `derivedWriteTrust` caps model output at `agent_written` and a deterministic projection (fence or timeline parse) at `operator_curated`; `recordTaintEdges` writes the complete `derivation_inputs` edges; `lowerToDerivedTier`/`lowerDerivedPage` (and `lowerDerivedPageIn`, the same inside a caller's coordinated transaction) lower a derived row whose republish changed no content column; `derivedMaintenanceTransaction` is the unmanaged deriver seam; `declareDerivation`/`declaredWriteTrust` carry a derivation in a maintenance or facts intent (the preparer stamps it, never above `agent_written`); `readDerivedTaintShare` is the doctor CEO-24 diagnostic. `derived-gate.ts`: the derivers' row-level write gate at the declared tier (`derivedGateConfig`, `applyGateDecision`: insert + flag receipt, hold, or skip a reject; `recordTimelineFlag`). `timeline-projection.ts`: `gbrain extract` timeline walks stamped per page tier and gated. Tests: `test/trust-taint.test.ts`, `test/trust-taint-origin.test.ts` (PGLite and Postgres), `test/trust-taint-dream.test.ts`.
+ - `src/core/trust/taint.ts`, `derived-gate.ts`, `timeline-projection.ts` (#5575 derived rows; the rest of `src/core/trust/` is above): `taint.ts` (I2, ENG-3/ENG-7): `readTaintInputs`/`deriveTrust` read the stored tiers of every row a deriver placed in its prompt (a vanished input reads `unknown`); `derivedWriteTrust` caps model output at `agent_written` and a deterministic projection (fence or timeline parse) at `operator_curated`; `recordTaintEdges` writes the complete `derivation_inputs` edges; `lowerToDerivedTier`/`lowerDerivedPage` (and `lowerDerivedPageIn`, the same inside a caller's coordinated transaction) lower a derived row whose republish changed no content column; `derivedMaintenanceTransaction` is the unmanaged deriver seam; `declareDerivation`/`declaredWriteTrust` carry a derivation in a maintenance or facts intent (the preparer stamps it, never above `agent_written`); `readDerivedTaintShare` is the doctor CEO-24 diagnostic. `derived-gate.ts`: the derivers' row-level write gate at the declared tier (`derivedGateConfig`, `applyGateDecision`: insert + flag receipt, hold, or skip a reject; `recordTimelineFlag`). `timeline-projection.ts`: `gbrain extract` timeline walks stamped per page tier and gated; `addProjectedPageTimeline` writes one page's own timeline as one batch that holds the live page FOR SHARE and refuses a missing one (`requirePages`), falling back row by row when the database refuses the batch (#6805). Tests: `test/trust-taint.test.ts`, `test/trust-taint-origin.test.ts` (PGLite and Postgres), `test/trust-taint-dream.test.ts`.
- `src/core/trust/claim.ts` + `claim-state.ts` + `claim-notice.ts`, `src/commands/trust-claim.ts`: #5575 legacy content. `gbrain trust claim-sources` (local CLI; typed source id on a TTY, `--yes` never counts, non-TTY refuses `confirmation_required` with a tell_user_to_run fix) records a claim in `sources.config` (`trust_tier: operator_curated`, `trust_claimed_at`, `trust_claim_lifted_at`) and lifts the source's legacy `unknown` rows (ids at or below `write_gate.scan_baseline`) through `trust/backfill.ts` scoped to the claimed sources (own cursor, `write_origin.channel` `trust_claim`), lowered by `frontmatterTrustCapsSql` (channel.ts, pinned to `frontmatterTrustCaps`) and every backfill signal, never above operator_curated; connector sources refuse. Doctor `trust_sources_unclaimed`, `gbrain post-upgrade` and the behavior-change notice name the claim (`actor: user`, tell_user_to_run); doctor `trust_scan`'s fix is the user's to run; the scan refuses while a lift is pending; explain and review show pending rows as owner tier. `claim-sources --relower [--dry-run]` (`relowerClaimedRows`, backfill.ts) is the lower-only #6533 repair: `trust_claim` rows whose page rule now ranks below their stored tier (legacy `extracted_by: extract_atoms-*` atoms) drop to it, pages first with child rows following through the relower-mode page taint, receipt `write_origin.channel` `trust_relower`; the dry run reports the same rows; doctor `trust_sources_unclaimed` names it. Guide: `docs/guides/memory-trust.md`. Tests: `test/trust-claim.test.ts`, `test/trust-claim-relower.test.ts`.
- `src/core/trust/marker-repair.ts`: #6550 `gbrain trust backfill --repair-unknown-markers` (local CLI, `src/cli/commands/trust.ts`). `previewMarkerRepair` lists live pages whose frontmatter `trust_tier` is `unknown` while the row is higher, with evidence (first `page_versions` snapshot showing the marker vs the fixed release `UNKNOWN_MARKER_FIX_RELEASE`: its commit time bounds the first run, `upgrade-state.json` can name it; whether the oldest kept version had the marker), an `assessment` (`consistent_with_6550` only when a pre-fix snapshot shows it and the first import did not, else `ambiguous`), pages already lowered through the marker (with their revert command), a `preview_hash` and the apply argv naming only the consistent pages. `applyMarkerRepair` refuses `preview_changed` unless the fresh preview hashes to `--expect`, then calls `page-handlers.ts` `repairPageMarker` per named slug: the `trust_owner_page` mode `repair_marker` (refused for remote requests) rewrites the marker to `repairedMarker(stored tier)` (none at owner tiers) at the previewed revision and keeps the tier. `review.ts` adds a `repair` command to `lower_page` items an `unknown` marker caused. Pinned by `test/trust-channel-writes.test.ts` (#6550 repair) and `test/trust-cli.test.ts`.
- `src/core/trust/provenance-drift.ts`, `src/core/repair/provenance.ts`, `src/commands/doctor/checks/provenance-stamp-drift.ts`: #7891 / #7918. `analyzePageDrift` (pure) walks a page's `page_versions` plus its live row; each transition's writer is the older snapshot's `archived_write_request_id` (joined to `persistence_requests.id` for `authority.remote`, else the principal kind; none: `unattributed`). Verdicts: `remote`, `ambiguous`, `local`, `needs_review` (a later local write changed the same stamp) and `restamp` (a classified page whose live caps rank above its stored tier). A restore puts each stamp back to the server-written column or the value before the first non-local change, and stamps min(lost cap, live caps, stored tier) with `stampTrustMarker`, so it only lowers. `scanProvenanceDrift` is bounded (`DRIFT_SCAN_LIMIT` per source) and degrades to `pre_trust` / `pre_attribution`. The doctor check is read-only; the repair kind is explicit-only and preview-bound (`provenance-v1` hash, approved set) and writes through `trust_owner_page` mode `restore_provenance` (`restorePageProvenance` in `page-handlers.ts`, local CLI only, re-checked against `plannedDigest`, files `lower_page` with proposer `provenance_repair`) or `repair_marker` for `restamp`. A page sync holds is listed `held` by the preview and skipped `held` by the apply, both through `pageHolds` (#8009), so the apply writes what the preview counted. Both repair modes render the page to its file on a classic checkout (`writePageThrough` with the preimage bytes). #7917: `recordAgentPageLowering` also files for derived publications and for callers that name a proposer; `prepareMaintenanceMutation` and `derivedMaintenanceTransaction` (rows carrying `prior`) call it. #7918: `derivationWriteTrust` rates a present but unreadable declaration `unknown`.
diff --cc docs/architecture/key-files/workspace-push-and-backup.md
index 26d30db2e1,0d9fecf950..ad502c3f77
--- a/docs/architecture/key-files/workspace-push-and-backup.md
+++ b/docs/architecture/key-files/workspace-push-and-backup.md
@@@ -12,7 -12,7 +12,7 @@@ Key files
## Shared-checkout git writer
- - `src/core/git/commit-push.ts` + `src/core/git/commit-guard.ts` — writer safety in a shared checkout (#7381). `integrate` replaces the tip 3-way merge when any local commit is patch-equivalent to an upstream one (`rev-list --cherry-mark`): it replays the local commits onto the remote tip in memory (`merge-tree --merge-base` on git 2.40+, a 3-way `read-tree` otherwise), leaving out the equivalent ones and clean merges, so a copy the remote edited never conflicts and one it reverted is never re-applied; the merge message lists what it left out. `supersededPaths` resolves a content conflict to ours when the remote's blob is one the same path held earlier in ours' history (last 200 commits touching it) and a different blob replaced it there; the push reports them as `superseded_remote_paths`, and `integrate_conflict` lists only the rest (`detail.superseded` names them). `commitPaths` refuses a path outside the source roots (`configuredSourceRoots`, git config `gbrain.sourceRoot`, recorded by `sources harden`'s `recordSourceRoot`) and a file another writer staged under a named directory (`commit_prestaged_paths`), and restores the exact index entries (`update-index --index-info`) when git refuses the commit. After the commit step (and its index restore) `commitPaths` returns the named paths HEAD still lacks (`unstagedPaths`: a modified entry flagged assume-unchanged or skip-worktree, a named file git did not index such as one inside a nested repository, and unstaged status entries under a named directory; a skip-worktree entry absent from disk, a flagged gitlink and ignored files under a named directory are left out) and keeps an unindexed file out of `commit --only`; `commitAndPush` (classic, managed and remoteless) and `commitPathsLocked` then throw `commit_paths_skipped`, or `writer_coordinator_required` for a page in a managed worktree (its `put_page` fix names the managed source), once the rest is committed and, on a classic checkout, pushed (`detail`: `skipped`, `committed`, `pushed`, `branch`, and `publish` when the push failed too). Every commit gbrain makes carries `GBRAIN_COMMIT_VIA=<lock path>`. Every pathspec it passes goes through `literalPathspecs` (`git-env.ts`), never `git --literal-pathspecs`, so the commit's hooks keep Git's normal pathspec rules: a pre-commit guard that selects files by glob still sees and can refuse them (`git_unavailable`, paths unstaged). `commitPathsLocked` (write-through) never commits without the lock: a busy lock or refused commit notes the file in `brain-writethrough-pending.log` (git dir, O_APPEND lines), which the next locked write-through and `commit-push --pending` commit and `settlePending` prunes. `notePending` is exported: the derived and dream write-through (`cycle/derived-write-through.ts`, #8073) records each file it writes before its batch commit, so a crash in between leaves the file for that sweep. A publish refuses local non-merge commits outside the roots (`commit_outside_source_root`; `--allow-outside-source-root` lifts both refusals, and `sources harden` passes it for its root scaffolding). With git config `gbrain.quarantine` (opt-in) a content conflict publishes the remote's version of each conflicted file plus every other local change, names the local commit under `refs/gbrain/quarantine/<time>-<sha>` and appends it to `brain-quarantine.log` (`readQuarantine` lists entries whose ref still exists); structural conflicts still refuse. `commit-guard.ts` installs the opt-in `prepare-commit-msg` guard (`gbrain git guard`), which admits only commits naming a held commit lock, passes merges and in-progress operations, and honors `GBRAIN_COMMIT_GUARD=off`. The helper's no-gbrain fallback (`renderCommitPushHelper`) marks children with the absolute lock path and releases the commit lock before pushing under `brain-publish.lock`; it runs the same skipped-path check after its commit and reports `commit_paths_skipped` after the push (exit 1, or 4 when the push failed). The CLI (`src/commands/git.ts`) refuses `checkout_not_a_source` before staging when this brain home's managed-root registry records source checkouts and the resolved checkout is none of them and has no `gbrain.sourceRoot` (#8662); a registered checkout must contain the resolved one, or be a subdirectory its HEAD tracks, so a repository that only encloses one is refused, and a registry that cannot be listed refuses `writer_coordinator_required` (GST-1623). Tests: `test/git-writer-safety-7381.serial.test.ts`, `test/git-literal-pathspec-hooks-7759.test.ts`, `test/git-commit-push-not-a-source-8662.test.ts`, `test/git-commit-push-skipped-paths-gst2116.test.ts`.
-- `src/core/git/commit-push.ts` + `src/core/git/commit-guard.ts` — writer safety in a shared checkout (#7381). `integrate` replaces the tip 3-way merge when any local commit is patch-equivalent to an upstream one (`rev-list --cherry-mark`): it replays the local commits onto the remote tip in memory (`merge-tree --merge-base` on git 2.40+, a 3-way `read-tree` otherwise), leaving out the equivalent ones and clean merges, so a copy the remote edited never conflicts and one it reverted is never re-applied; the merge message lists what it left out. `supersededPaths` resolves a content conflict to ours when the remote's blob is one the same path held earlier in ours' history (last 200 commits touching it) and a different blob replaced it there; the push reports them as `superseded_remote_paths`, and `integrate_conflict` lists only the rest (`detail.superseded` names them). `commitPaths` refuses a path outside the source roots (`configuredSourceRoots`, git config `gbrain.sourceRoot`, recorded by `sources harden`'s `recordSourceRoot`) and a file another writer staged under a named directory (`commit_prestaged_paths`), stages named tracked paths with `add -u` and visible untracked ones with `add -A` (a tracked deletion under an ignored directory commits, #7984; any other path keeps git's `commit_paths_invalid`), and restores the exact index entries (`update-index --index-info`) when git refuses the commit. Every commit gbrain makes carries `GBRAIN_COMMIT_VIA=<lock path>`. Every pathspec it passes goes through `literalPathspecs` (`git-env.ts`), never `git --literal-pathspecs`, so the commit's hooks keep Git's normal pathspec rules: a pre-commit guard that selects files by glob still sees and can refuse them (`git_unavailable`, paths unstaged). `commitPathsLocked` (write-through) never commits without the lock: a busy lock or refused commit notes the file in `brain-writethrough-pending.log` (git dir, O_APPEND lines), which the next locked write-through and `commit-push --pending` commit and `settlePending` prunes. `notePending` is exported: the derived and dream write-through (`cycle/derived-write-through.ts`, #8073) records each file it writes before its batch commit, so a crash in between leaves the file for that sweep. A publish refuses local non-merge commits outside the roots (`commit_outside_source_root`; `--allow-outside-source-root` lifts both refusals, and `sources harden` passes it for its root scaffolding). With git config `gbrain.quarantine` (opt-in) a content conflict publishes the remote's version of each conflicted file plus every other local change, names the local commit under `refs/gbrain/quarantine/<time>-<sha>` and appends it to `brain-quarantine.log` (`readQuarantine` lists entries whose ref still exists); structural conflicts still refuse. `commit-guard.ts` installs the opt-in `prepare-commit-msg` guard (`gbrain git guard`), which admits only commits naming a held commit lock, passes merges and in-progress operations, and honors `GBRAIN_COMMIT_GUARD=off`. The helper's no-gbrain fallback (`renderCommitPushHelper`) marks children with the absolute lock path and releases the commit lock before pushing under `brain-publish.lock`. The CLI (`src/commands/git.ts`) refuses `checkout_not_a_source` before staging when this brain home's managed-root registry records source checkouts and the resolved checkout is none of them and has no `gbrain.sourceRoot` (#8662); a registered checkout must contain the resolved one, or be a subdirectory its HEAD tracks, so a repository that only encloses one is refused, and a registry that cannot be listed refuses `writer_coordinator_required` (GST-1623). Tests: `test/git-writer-safety-7381.serial.test.ts`, `test/git-literal-pathspec-hooks-7759.test.ts`, `test/git-commit-push-not-a-source-8662.test.ts`.
++- `src/core/git/commit-push.ts` + `src/core/git/commit-guard.ts` — writer safety in a shared checkout (#7381). `integrate` replaces the tip 3-way merge when any local commit is patch-equivalent to an upstream one (`rev-list --cherry-mark`): it replays the local commits onto the remote tip in memory (`merge-tree --merge-base` on git 2.40+, a 3-way `read-tree` otherwise), leaving out the equivalent ones and clean merges, so a copy the remote edited never conflicts and one it reverted is never re-applied; the merge message lists what it left out. `supersededPaths` resolves a content conflict to ours when the remote's blob is one the same path held earlier in ours' history (last 200 commits touching it) and a different blob replaced it there; the push reports them as `superseded_remote_paths`, and `integrate_conflict` lists only the rest (`detail.superseded` names them). `commitPaths` refuses a path outside the source roots (`configuredSourceRoots`, git config `gbrain.sourceRoot`, recorded by `sources harden`'s `recordSourceRoot`) and a file another writer staged under a named directory (`commit_prestaged_paths`), stages named tracked paths with `add -u` and visible untracked ones with `add -A` (a tracked deletion under an ignored directory commits, #7984; any other path keeps git's `commit_paths_invalid`), and restores the exact index entries (`update-index --index-info`) when git refuses the commit. After the commit step (and its index restore) `commitPaths` returns the named paths HEAD still lacks (`unstagedPaths`: a modified entry flagged assume-unchanged or skip-worktree, a named file git did not index such as one inside a nested repository, and unstaged status entries under a named directory; a skip-worktree entry absent from disk, a flagged gitlink and ignored files under a named directory are left out) and keeps an unindexed file out of `commit --only`; `commitAndPush` (classic, managed and remoteless) and `commitPathsLocked` then throw `commit_paths_skipped`, or `writer_coordinator_required` for a page in a managed worktree (its `put_page` fix names the managed source), once the rest is committed and, on a classic checkout, pushed (`detail`: `skipped`, `committed`, `pushed`, `branch`, and `publish` when the push failed too). Every commit gbrain makes carries `GBRAIN_COMMIT_VIA=<lock path>`. Every pathspec it passes goes through `literalPathspecs` (`git-env.ts`), never `git --literal-pathspecs`, so the commit's hooks keep Git's normal pathspec rules: a pre-commit guard that selects files by glob still sees and can refuse them (`git_unavailable`, paths unstaged). `commitPathsLocked` (write-through) never commits without the lock: a busy lock or refused commit notes the file in `brain-writethrough-pending.log` (git dir, O_APPEND lines), which the next locked write-through and `commit-push --pending` commit and `settlePending` prunes. `notePending` is exported: the derived and dream write-through (`cycle/derived-write-through.ts`, #8073) records each file it writes before its batch commit, so a crash in between leaves the file for that sweep. A publish refuses local non-merge commits outside the roots (`commit_outside_source_root`; `--allow-outside-source-root` lifts both refusals, and `sources harden` passes it for its root scaffolding). With git config `gbrain.quarantine` (opt-in) a content conflict publishes the remote's version of each conflicted file plus every other local change, names the local commit under `refs/gbrain/quarantine/<time>-<sha>` and appends it to `brain-quarantine.log` (`readQuarantine` lists entries whose ref still exists); structural conflicts still refuse. `commit-guard.ts` installs the opt-in `prepare-commit-msg` guard (`gbrain git guard`), which admits only commits naming a held commit lock, passes merges and in-progress operations, and honors `GBRAIN_COMMIT_GUARD=off`. The helper's no-gbrain fallback (`renderCommitPushHelper`) marks children with the absolute lock path and releases the commit lock before pushing under `brain-publish.lock`; it runs the same skipped-path check after its commit and reports `commit_paths_skipped` after the push (exit 1, or 4 when the push failed). The CLI (`src/commands/git.ts`) refuses `checkout_not_a_source` before staging when this brain home's managed-root registry records source checkouts and the resolved checkout is none of them and has no `gbrain.sourceRoot` (#8662); a registered checkout must contain the resolved one, or be a subdirectory its HEAD tracks, so a repository that only encloses one is refused, and a registry that cannot be listed refuses `writer_coordinator_required` (GST-1623). Tests: `test/git-writer-safety-7381.serial.test.ts`, `test/git-literal-pathspec-hooks-7759.test.ts`, `test/git-commit-push-not-a-source-8662.test.ts`, `test/git-commit-push-skipped-paths-gst2116.test.ts`.
- `src/core/git/range-secret-scan.ts` — `scanRange(root, from, to)`, the secret gate for automatic publishes: `gbrain git commit-push --push-only --scan-secrets` (the child `gbrain sources refresh` runs to publish a diverged managed checkout) scans `trackingRef..target` under the publish lock, right before the push. Plumbing only (`rev-list`, `cat-file commit`, one streamed `diff-tree --stdin -p --root --cc`), so log, diff and attribute settings never change what is scanned. Commit messages, added lines and merge resolutions go through `scanText` with the `.gbrain-scan-allow` allowlist; a finding, added text over the scan cap or a change to `.gbrain-scan-allow`/`.gitattributes` refuses `publish_secret_found` (file, line, rule, commit, never the value), and a range it cannot read in full (git failure, unrecognised output, 300 s budget) refuses `publish_scan_unreadable`.
- `src/commands/doctor/checks/git-writer.ts` — `checkout_lagging`, `dirty_age`, `commits_outside_source_root`, `quarantined_changes` (#7381, brain category, after `git_convergence`): over the unmanaged source checkouts with an upstream (`sourceRoots` from git-convergence, grouped by toplevel with each source's toplevel-relative root), never fetching, every git call bounded at 5 s. Lagging warns when `HEAD..@{u}` holds a commit over an hour old (fix: `gbrain git commit-push --pull --path <top>`, agent). Dirty age warns on pending write-through files older than 30 minutes (`pendingWriteThroughStillDirty`; fix: `commit-push --pending`, agent) and on files staged that long (ask_user: unstage or commit by name). Outside-root warns on unpushed non-merge commits that change files outside the DB source roots plus `gbrain.sourceRoot` (`localCommitsOutsideRoots`; ask_user fix with `--allow-outside-source-root`), and says when the checkout has no root recorded. Test: `test/doctor-git-writer-7381.test.ts`.
- `src/core/git/commit-ledger.ts` — the commit ledger (PR B, docs/designs/REFRESH_WRITE_BARRIER.md part 3): `<git common dir>/gbrain/commit-ledger.jsonl`, one O_APPEND JSON line under 1 KiB per record, under its own flock `commit-ledger.lock` (start line, append, 4 MiB rotation to `commit-ledger.1.jsonl`). `recordCommit`/`recordCommitAsync` take the sha and writer kind (`commit_push`, `door`, `merge`, `replay`, `effect`, `sync_init`, `workspace_push`, `bootstrap`, `hosted_repo`); porcelain sites call `recordIntent` (head_before, `messageDigest` of the message) before `git commit`, plumbing sites record the `commit-tree` sha before the ref moves. A failed append never fails the commit (logged once); a directory outside git records nothing. `readLedger` reads both files; only a missing file reads as empty, any other read error throws (GST-1623). Tests: `test/commit-ledger.test.ts`.
diff --cc scripts/module-size-limits.tsv
index 918445738f,03f4d2c13b..fcb4ecc5f3
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@@ -21,10 -21,10 +21,10 @@@ src/core/import-file.ts 2091 ratchet +
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
src/core/operations.ts 249 ratchet +1 #7168: graphRankOperations import (ops/graph-rank.ts; spread shares the orphans line); peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row; lowered GBRA-75 W11 cold start: OP_AREAS + finalize step moved to operation-load.ts (shared with the CLI per-op loader); +1 C4 pinned questions: questionsOperations import and spread (ops/questions.ts; its areas live in operation-load.ts OP_AREAS); +1 Wave B append: pageAppendOperations import (spread shares the pages line); +1 Wave B upload sessions: pageUploadOperations import (spread shares the pages line); +1 #7191: search-exact import; +1 GBRA-156: whois import (ops/whois.ts; spread shares the chunks line); +1 GST-359 D: qmMemoryOperations import (ops/qm-memory.ts; spread shares the memory line); re-summed at the train R merge with v0.60.574.0: 246 + 1; re-summed at the memory train #8481 merge with v0.60.576.0 (248 measured); +1 Wakeshift PR 1: wakeshiftOperations import (ops/wakeshift.ts; its spread shares the jobs line)
src/core/pglite-engine.ts 3103 ratchet +9 #7191: findPages/countPagesBy delegates and imports (SQL in engine-sql/page-lookup.ts); +4 GBRA-283 B1 (#8455): initSchema seeds an engine opened from settings with settings.embedding and refuses a mismatch, and its open skips the snapshot fast path (logic in embedded-engine.ts; engine methods cannot move); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts); +2 GBRA-76: transaction/transactionDirect take TransactionOptions and refuse an already-aborted signal before BEGIN; +2 #4772 (W14 PR3): entityTypes HealthDeps delegate + import (policy in schema-pack/entity-types.ts, SQL in engine-sql/health.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3023 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates (SQL in engine-sql/pages.ts); +6 large pages Wave A sub-a: getChunkPage delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +7 LHF wave 2 item 5: request config snapshot delegate lines in getConfig/getAllConfig/setConfig/unsetConfig (logic in config-snapshot.ts); +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3072 + 3; +5 PR2 fix lane X: keywordBoundedRead runs the read on the engine itself (engine methods cannot move): 3075 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3080 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3085); +2 #7159: the frontmatter where clause in searchKeyword and its import (SQL in search/frontmatter-where.ts; engine methods cannot move); +2 GBRA-156 keyword OR rarity: the import and the searchKeyword OR retry through rankOrFallbackByRarity with an orFallback rank parameter like Postgres (logic in search/keyword-or-rarity.ts; engine methods cannot move); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); re-summed at the Wave B PR 4 merge with v0.60.452.0 (3097 measured); +2 GBRA-283 Wave A (#8460): the ENGINE_ROOT import and field (engine identity for per-engine caches; class fields cannot move)
-src/core/postgres-engine.ts 3178 ratchet +9 #7191: findPages/countPagesBy scoped-read delegates and imports (SQL in engine-sql/page-lookup.ts); +6 GBRA-283 B1 (#8455): an engine opened from settings routes its direct URL and statement-description cache from its settings, and initSchema seeds settings.embedding and refuses a mismatch (logic in embedded-engine.ts; engine methods cannot move); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +3 wave 18b lane 2 (#6495): keywordTimeouts negative-cache field and the searchKeyword runner wrap (logic in postgres-engine/keyword-timeout-cache.ts); integrated at wave 18b: master 3082 + 3; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3085 + 3; +3 PR2 fix lane E (E1): getChunks/getChunkPage/getChunkWindows run the manifest privilege probe in their scoped transaction (chunkManifestReads in search/safe-chunks.ts); integrated at the lane E merge onto b75a69a6d: 3088 + 3; +6 PR2 fix lane X: searchVector, explainVectorSearch, the hasMore witness and runVectorAttempt pick the chunk-manifest statement form inside each bounded attempt transaction, so its statement_timeout bounds the probe (form memo vectorStatementForms in search/vector-statement.ts; engine methods cannot move): 3091 + 6; +5 PR2 fix lane X: keywordBoundedRead runs the read in withScopedReadTransaction under the keyword statement timeout setting (engine methods cannot move): 3097 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3102 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3107); +3 #7159: the frontmatter where clause in the two keyword typesClause sites and its import (SQL in search/frontmatter-where.ts; engine methods cannot move); GBRA-156 retrieval wave (#7201) composed with #7194 at the merge: re-summed (3114 measured); +2 warm CLI socket (#7218): connectedDatabaseUrl getter (the URL the engine connected with, bound into the socket identity), composed over the GBRA-156 retrieval wave (3116 measured); +1 GBRA-133 PR 2b: transactionOn hands the outermost transaction its commit checks (page-state/transactions.ts withCommitChecks), composed with the warm CLI socket at the merge (3117 measured); +18 GBRA-156: the private readTransaction helper behind withScopedReadTransaction and jitOffRead answers a top-level read before its COMMIT settles (engine methods cannot move; 3135 measured); +1 GBRA-156: transactionOn and runUnsafe hold a per-search connection slot (import of search/connection-budget.ts; 3136 measured); +2 GBRA-156: transactionOn passes TransactionOptions.pipelineFirst to the pool begin as { first } (driver gate in vendor/postgres index.js begin); an engine method cannot move; composed with the warm CLI socket and GBRA-133 PR 2b at the master v0.60.344.0 merge (3119 measured); GBRA-151 #7183/#7187/#7188 re-summed at the v0.60.402.0 merge (3135 measured); +2 #7183 (GBRA-151) at the v0.60.412.0 merge: read-write-transactions import and transactionOn wraps its connection in readWriteTransactions (logic in postgres-engine/read-write-transactions.ts; engine methods cannot move): 3135 + 2; +7 GBRA-156: transactionOn opens readOnly transactions as BEGIN READ ONLY and a top-level read inherits its request signal, runUnsafe refuses an aborted request (logic in request-signal.ts; engine methods cannot move): 3137 + 7; +3 GBRA-156 keyword OR rarity: the import and the searchKeyword OR retry through rankOrFallbackByRarity (logic in search/keyword-or-rarity.ts; engine methods cannot move); +2 wave-b PR 4 merged with #7218 (both sides added imports); re-summed at the Wave B PR 4 merge with v0.60.452.0 (3155 measured); +2 GBRA-283 Wave A (#8460): the ENGINE_ROOT import and field (engine identity for per-engine caches; class fields cannot move); +7 GBRA-283 B1 review: the instance pool passes settings connection fields explicitly, initSchema reads the embedding identity again under the schema lock, and reconnect ends the superseded manager (engine methods cannot move); re-summed at the train R merge with v0.60.574.0: 3170 + 4; +4 #6318: withScopedReadTransaction runs a bounded preparation's read under its deadline (read-deadline.ts; reserved-connection envelope runDeadlineRead in postgres-engine/bounded-statement.ts) and adds statement_timeout to the transaction settings (engine methods cannot move): re-summed at the 0.60.583.0 merge: 3174 + 4
+src/core/postgres-engine.ts 3180 ratchet +9 #7191: findPages/countPagesBy scoped-read delegates and imports (SQL in engine-sql/page-lookup.ts); +6 GBRA-283 B1 (#8455): an engine opened from settings routes its direct URL and statement-description cache from its settings, and initSchema seeds settings.embedding and refuses a mismatch (logic in embedded-engine.ts; engine methods cannot move); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +3 wave 18b lane 2 (#6495): keywordTimeouts negative-cache field and the searchKeyword runner wrap (logic in postgres-engine/keyword-timeout-cache.ts); integrated at wave 18b: master 3082 + 3; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3085 + 3; +3 PR2 fix lane E (E1): getChunks/getChunkPage/getChunkWindows run the manifest privilege probe in their scoped transaction (chunkManifestReads in search/safe-chunks.ts); integrated at the lane E merge onto b75a69a6d: 3088 + 3; +6 PR2 fix lane X: searchVector, explainVectorSearch, the hasMore witness and runVectorAttempt pick the chunk-manifest statement form inside each bounded attempt transaction, so its statement_timeout bounds the probe (form memo vectorStatementForms in search/vector-statement.ts; engine methods cannot move): 3091 + 6; +5 PR2 fix lane X: keywordBoundedRead runs the read in withScopedReadTransaction under the keyword statement timeout setting (engine methods cannot move): 3097 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3102 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3107); +3 #7159: the frontmatter where clause in the two keyword typesClause sites and its import (SQL in search/frontmatter-where.ts; engine methods cannot move); GBRA-156 retrieval wave (#7201) composed with #7194 at the merge: re-summed (3114 measured); +2 warm CLI socket (#7218): connectedDatabaseUrl getter (the URL the engine connected with, bound into the socket identity), composed over the GBRA-156 retrieval wave (3116 measured); +1 GBRA-133 PR 2b: transactionOn hands the outermost transaction its commit checks (page-state/transactions.ts withCommitChecks), composed with the warm CLI socket at the merge (3117 measured); +18 GBRA-156: the private readTransaction helper behind withScopedReadTransaction and jitOffRead answers a top-level read before its COMMIT settles (engine methods cannot move; 3135 measured); +1 GBRA-156: transactionOn and runUnsafe hold a per-search connection slot (import of search/connection-budget.ts; 3136 measured); +2 GBRA-156: transactionOn passes TransactionOptions.pipelineFirst to the pool begin as { first } (driver gate in vendor/postgres index.js begin); an engine method cannot move; composed with the warm CLI socket and GBRA-133 PR 2b at the master v0.60.344.0 merge (3119 measured); GBRA-151 #7183/#7187/#7188 re-summed at the v0.60.402.0 merge (3135 measured); +2 #7183 (GBRA-151) at the v0.60.412.0 merge: read-write-transactions import and transactionOn wraps its connection in readWriteTransactions (logic in postgres-engine/read-write-transactions.ts; engine methods cannot move): 3135 + 2; +7 GBRA-156: transactionOn opens readOnly transactions as BEGIN READ ONLY and a top-level read inherits its request signal, runUnsafe refuses an aborted request (logic in request-signal.ts; engine methods cannot move): 3137 + 7; +3 GBRA-156 keyword OR rarity: the import and the searchKeyword OR retry through rankOrFallbackByRarity (logic in search/keyword-or-rarity.ts; engine methods cannot move); +2 wave-b PR 4 merged with #7218 (both sides added imports); re-summed at the Wave B PR 4 merge with v0.60.452.0 (3155 measured); +2 GBRA-283 Wave A (#8460): the ENGINE_ROOT import and field (engine identity for per-engine caches; class fields cannot move); +7 GBRA-283 B1 review: the instance pool passes settings connection fields explicitly, initSchema reads the embedding identity again under the schema lock, and reconnect ends the superseded manager (engine methods cannot move); re-summed at the train R merge with v0.60.574.0: 3170 + 4; +4 #6318: withScopedReadTransaction runs a bounded preparation's read under its deadline (read-deadline.ts; reserved-connection envelope runDeadlineRead in postgres-engine/bounded-statement.ts) and adds statement_timeout to the transaction settings (engine methods cannot move): re-summed at the 0.60.583.0 merge: 3174 + 4; +2 TLS default: the pg-tls import and the instance pool builds its options through withPgTls and turns a no-TLS refusal into postgres_tls_required (logic in pg-tls.ts; engine methods cannot move): 3178 + 2
src/core/search/hybrid.ts 1562 ratchet +5 GBRA-81 item 5 per-stage search timings: HybridSearchOpts._timings (interface field) and the timer bindings and import in hybridSearch/hybridSearchCached (collector logic in search/stage-timings.ts); +2 W5 page-unit ranking cut: HybridSearchOpts.pageRankCut (logic in search/page-rank-cut.ts); +9 W3 confidence-gated reranking: HybridSearchOpts.rerankGate and the gate/lookup threading through rerankAndPin and sizeReturnPool (logic in search/hybrid/rerank-gate.ts, crag.ts gradePreRerank); re-summed at the W3 merge onto master v0.60.168.0 (1641 measured); +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts; +14 fix wave 13 P4.8 #6400: lazyQueryEmbedDeadline (the query-embed deadline starts when the embed starts) and the _queryEmbedDeadline getter; +1 query facts arm: HybridSearchOpts.onQueryEmbedding (interface field; its one-line call is paid inside the ceiling) after the vector arms, so the facts arm reuses the query embedding without a second model call; re-summed at the master a08578ca5 merge (1591 master lines + 3 integration lines: the onQueryEmbedding hook); lowered to 1562: LHF wave 2 item 3 peeled cosineReScore into search/cosine-rescore.ts
src/core/types.ts 2357 ratchet +2 #8664 agent label: WriteAttributionView.agent_label (+ its doc line; the header, record and read live in persistence/attribution.ts and ops/attribution.ts) +3 train R: #7491 SearchOpts identifier-probe field and #7175 keywordPhrase option (interface fields); +2 GBRA-154 #7175: SearchOpts.keywordPhrase (opt-in phrase factor); +4 Wave B PR 1 (1c): Page.body_storage/body_bytes (interface fields; guard logic in page-body/page-shape.ts); +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); re-summed at the W3 merge onto master v0.60.168.0 (2279 measured); +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons; +12 fix wave 15 P2.1 (#6500): PageFilters.slugAfter (single-source slug keyset, interface field + doc) and the updated_desc tiebreaker comment (the keyset walk lives in facts/conversation-enumeration.ts); +2 wave 16 G5.1 (#6495): EngineConfig.keyword_statement_timeout_ms (interface field + doc); +2 GBRA-92: EngineConfig.pglite_shared_buffers (interface field + doc); +11 large pages (Wave A): Chunk/ChunkInput projected_byte_start/end interface fields (span logic in chunkers/recursive.ts, page-window/document.ts); +4 wave 18b lane 2 (#6495): SearchOpts.keywordTimeoutCache, the skipped_after_timeout degraded reason and the useCache doc line; integrated at wave 18b: master 2319 + 4; +2 LHF wave 2 item 3: retrieval meta cosine_rescore field (js_fallback disclosure; logic in search/cosine-rescore.ts); +14 GBRA-154 ranking wave (#4612 #7153 #7156 #7162 #7164): SearchResult collapsed/redirect_to/image_page/rank_prior/rank_score/fused_score stamps and HybridSearchMeta.collapse (interface fields; logic in search/collapse.ts, rank-priors.ts, score-contract.ts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (2343 measured); GBRA-156 retrieval wave (#7201) composed with #7194 at the merge: re-summed (2345 measured); GBRA-151 #7147 follow-up re-summed at the v0.60.338.0 merge (2347 measured); +2 GBRA-95 G7a follow-up: Page.withheld_source_path field; +2 #7600: SearchResult.quoted (interface field; logic in search/transcript-quote.ts); +1 #8377: ChronicleTimelineRow.trust_tier (interface field; chronicle reads quote rows by tier); re-summed at the train R merge with v0.60.574.0: 2354 + 1
- src/core/minions/queue.ts 2548 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts); +5 GBRA-130 A-30: claim excludeWatchdogSuspects option (signature, doc and the mark parameter), the releaseWatchdogClaim delegate, and the co-runner stall call site in handleStalled (logic in minions/watchdog-attribution.ts); +5 GBRA-158 #7239/#7240: failJob result parameter (the #7216 hunk), jsonbSafeJson import and its call in add (sanitizer in text-safe.ts); +2 #7242 lane reservation: claim excludeNames option (doc line and the bound array; policy in minions/lanes.ts); +1 #7241 submitter label import (job-insight.ts) + 1 queue-families type import; #7252 x #7249 merge: both sides grew the file, re-summed (2544 measured); +3 GBRA-133: the stall sweep deletes a drain-lease holder record whose lease lock is gone or expired; +1 GST-2260: retryOnStalePlan import for completeJob/failJob (helper in retry-matcher.ts)
-src/core/minions/queue.ts 2548 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts); +5 GBRA-130 A-30: claim excludeWatchdogSuspects option (signature, doc and the mark parameter), the releaseWatchdogClaim delegate, and the co-runner stall call site in handleStalled (logic in minions/watchdog-attribution.ts); +5 GBRA-158 #7239/#7240: failJob result parameter (the #7216 hunk), jsonbSafeJson import and its call in add (sanitizer in text-safe.ts); +2 #7242 lane reservation: claim excludeNames option (doc line and the bound array; policy in minions/lanes.ts); +1 #7241 submitter label import (job-insight.ts) + 1 queue-families type import; #7252 x #7249 merge: both sides grew the file, re-summed (2544 measured); +3 GBRA-133: the stall sweep deletes a drain-lease holder record whose lease lock is gone or expired; +1: add refuses a child under a finished parent
++src/core/minions/queue.ts 2549 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts); +5 GBRA-130 A-30: claim excludeWatchdogSuspects option (signature, doc and the mark parameter), the releaseWatchdogClaim delegate, and the co-runner stall call site in handleStalled (logic in minions/watchdog-attribution.ts); +5 GBRA-158 #7239/#7240: failJob result parameter (the #7216 hunk), jsonbSafeJson import and its call in add (sanitizer in text-safe.ts); +2 #7242 lane reservation: claim excludeNames option (doc line and the bound array; policy in minions/lanes.ts); +1 #7241 submitter label import (job-insight.ts) + 1 queue-families type import; #7252 x #7249 merge: both sides grew the file, re-summed (2544 measured); +3 GBRA-133: the stall sweep deletes a drain-lease holder record whose lease lock is gone or expired; +1 GST-2260: retryOnStalePlan import for completeJob/failJob (helper in retry-matcher.ts); +1 persistence train: add refuses a child under a finished parent (#8909)
src/commands/init.ts 1892 ratchet +2 fix wave 9 lane F #5253: leaving deferred setup also clears the DB-plane embedding_disabled row (both init branches); grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle); +5 agent operator follow-up Item 2: --surface flag (value flag, parse, help line, module-level registration surface, type import) for the printed harness registration; +2 fix wave lane B3: both engine paths stamp a database init created as a fresh install for the behavior_changes notice (core/behavior-change-notice.ts); +4 GBRA-81 item 1: --search-mode value flag, its parse line, module-level choice, help line (picker logic lives in init-mode-picker.ts); +2 D8 funnel: a fresh init counts one clean_install when the opt-in funnel is on (core/funnel.ts); +1 GBRA-199: --surface help line names the default verbs listing; +7 GBRA-248 W0b: the implicit-keyless marker on both zero-key fallbacks, the deferred-hint gate on both engine paths and the kept-identity call in both (logic in commands/init-embedding-plane.ts)
src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)
src/core/minions/handlers/subagent.ts 1925 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch; +7 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms read once and passed to the oneshot and gateway-loop paths (resolver lives in minions/handler-timeouts.ts)
@@@ -45,7 -45,6 +45,7 @@@ src/core/search/mode.ts 1730 ratchet +1
src/commands/eval-longmemeval.ts 1545 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts); +13 GBRA-81 lane A: --via-operation query|search (flags, per-call expansion pin, the run's expectExpansion, the op branch in runOneQuestion, row field, via_operation_summary and its FAIL line; logic in eval/longmemeval/via-operation.ts); +12 --call-plan FILE / --call-plan-gate CMD: two LME_FLAGS entries (CLI help lines), two ParsedArgs fields, the parseArgs pairing check and the header invariant (planner lives in eval/longmemeval/call-plan.ts; runEvalLongMemEval is one line shorter); +1 #7619: parseArgs refuses a value on a switch (--judge=false turned the paid judge on)
src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: links_extraction_lag held bucket and its retry fix (logic in core/extraction-lag.ts heldExtractionReport); +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.ts; +20 wave 18b lane 1: links_extraction_lag names the columns its pre-migration degrade reads (#6599 strict predicate), sync_freshness separates sync outcome from freshness for a source with no successful sync (#4960; verdict text, fixes and the attempt read live in doctor/sync-outcome.ts and core/sync-attempt.ts) and exempts read-only skill-pack catalogs (#6076; core/shared-skills/adopted-packs.ts); -51 #6803 (D1): links_extraction_lag reads its counts and verdict from core/extraction-lag.ts (shared with the sync nudge); +1 #7145: content_hash_duplicates reads one group past its list to report a floor ("at least 50")
src/core/search/evidence-delivery.ts 1759 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned); +4 GST-687: page evidence and the extractive fallback quote below-owner-tier text for untrusted readers (untrusted flag; logic in search/transcript-quote.ts)
-src/commands/config.ts 1526 ratchet +1 GBRA-216: recall.* config set value refusal (facts/recall-config.ts); +1 GBRA-216: config set refuses a dream.claim_conflicts.mode other than propose|off (refusal in facts/claim-conflicts.ts); new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal)
+src/commands/config.ts 1530 ratchet +1 GBRA-216: recall.* config set value refusal (facts/recall-config.ts); +1 GBRA-216: config set refuses a dream.claim_conflicts.mode other than propose|off (refusal in facts/claim-conflicts.ts); new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal); +4 GBRA-377 PR B: skills.resolver.* file-plane routing (doc line, the one-line router and its two dispatch lines; logic in core/setup/skill-resolver-config.ts)
src/commands/mcp-expose.ts 1519 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts)
- src/core/behavior-change-notice.ts 1713 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 GST-2051 ungranted_member_writes_gst2051 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-731 think_window_trajectory_gst731 row and +1 GST-1602 purge_cancels_deferred_write_gst1602 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8915 v0.60.621.0: 1688 + 2; +1 GST-2059: owner_reads_private row; +1 #8888: the record-origin checkout lock-down row (re-summed at the Q6 stack on #8934 v0.60.625.0: 1691 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 E1/F3/F4 rows (since TBD until the merge slot), re-summed at the master merge; +1 GBRA-284 personal_sources_gbra284 row (since TBD until the merge slot) (re-summed at the QM wave merge onto master v0.60.626.0: 1692 + 3); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 v3: the qm_personal_structured_gst1158 row (since TBD until the merge slot); +1 #8477 GST-1158 F2 personal-tools row at the QM wave merge (1695 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 #8483 memory_propose row at the QM wave merge (1696 + 1); +1 GST-1094 gap 4: the qm_admin_http_gst1094 row (since TBD until the merge slot); +1 GST-1158: the member_email_link_gst1158 row (since TBD until the merge slot); +2 #8479 member-email rows at the QM wave merge (1697 + 2); +1 GST-2112: ingest_keeps_readers_gst2112 row (re-summed at the Q7 v0.60.627.0 merge: 1692 + 1); +1 #8982 federated_member_writes_8982 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-2116 commit_push_skipped_paths_gst2116 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q10 slot on #9009 ee0f4a78: 1694 + 1; +1 GST-2118 pending_ledger_flagged_gst2118 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q12 slot on #9016 afb49de5: 1695 + 1; +1 GBRA-431: read_scope_params_gbra431 row (rows are data and cannot move), re-summed at the #9032 stack merge: 1697 measured; +2 GST-2201 sync_restored_file_gst2201 and purge_keeps_committed_file_gst2201 rows (since is the current VERSION until the merge slot; +1 GST-2243 remember_share_gst2243 row (re-summed at the #9098 stack merge: 1699 + 1); +1 GST-2312 #9024 sync_filter_owned_hold_9024 row (re-summed at the #9064 stack merge: 1700 + 1; rows are data and cannot move); +2 access-privacy wave (0.60.649.0): the owner_private_facts_gst2089 and private_labels_write_ahead_gst2092 rows; +1 GBRA-443 private_labels_batch_exit_gbra443 row (rows are data and cannot move), re-summed at the 0.60.650.0 slot on #9038: 1703 + 1; +1 postgres_tls_default row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.651.0 merge: 1704 + 1; +1 GST-2331 sync_reads_fetch_nothing_gst2331 row (rows are data and cannot move), re-summed at the 0.60.654.0 stack on #9045 6ff5540d: 1705 + 1; +7 QM wave (#9037) rows: attest_scope_read_ops_gst1158, attest_direct_page_writes_deferred_gst1158, personal_sources_gbra284, qm_personal_structured_gst1158, memory_propose_held_writes_gst1158, member_email_link_gst1158, qm_admin_http_gst1094 (re-summed at the 0.60.655.0 stack on #9110 f9b2072e: 1706 + 7)
-src/core/behavior-change-notice.ts 1694 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 GST-2051 ungranted_member_writes_gst2051 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-731 think_window_trajectory_gst731 row and +1 GST-1602 purge_cancels_deferred_write_gst1602 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8915 v0.60.621.0: 1688 + 2; +1 GST-2059: owner_reads_private row; +1 #8888: the record-origin checkout lock-down row (re-summed at the Q6 stack on #8934 v0.60.625.0: 1691 + 1); +1 GST-1644 derived_effect_publication_busy_gst1644 row (since TBD until the merge slot; rows are data and cannot move) (re-summed at the persistence wave merge: 1693 measured); +1 job_tree_finished_parent_guards row (re-summed at the persistence wave merge: 1694 measured)
++src/core/behavior-change-notice.ts 1715 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 GST-2051 ungranted_member_writes_gst2051 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-731 think_window_trajectory_gst731 row and +1 GST-1602 purge_cancels_deferred_write_gst1602 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8915 v0.60.621.0: 1688 + 2; +1 GST-2059: owner_reads_private row; +1 #8888: the record-origin checkout lock-down row (re-summed at the Q6 stack on #8934 v0.60.625.0: 1691 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 E1/F3/F4 rows (since TBD until the merge slot), re-summed at the master merge; +1 GBRA-284 personal_sources_gbra284 row (since TBD until the merge slot) (re-summed at the QM wave merge onto master v0.60.626.0: 1692 + 3); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 v3: the qm_personal_structured_gst1158 row (since TBD until the merge slot); +1 #8477 GST-1158 F2 personal-tools row at the QM wave merge (1695 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 #8483 memory_propose row at the QM wave merge (1696 + 1); +1 GST-1094 gap 4: the qm_admin_http_gst1094 row (since TBD until the merge slot); +1 GST-1158: the member_email_link_gst1158 row (since TBD until the merge slot); +2 #8479 member-email rows at the QM wave merge (1697 + 2); +1 GST-2112: ingest_keeps_readers_gst2112 row (re-summed at the Q7 v0.60.627.0 merge: 1692 + 1); +1 #8982 federated_member_writes_8982 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-2116 commit_push_skipped_paths_gst2116 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q10 slot on #9009 ee0f4a78: 1694 + 1; +1 GST-2118 pending_ledger_flagged_gst2118 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q12 slot on #9016 afb49de5: 1695 + 1; +1 GBRA-431: read_scope_params_gbra431 row (rows are data and cannot move), re-summed at the #9032 stack merge: 1697 measured; +2 GST-2201 sync_restored_file_gst2201 and purge_keeps_committed_file_gst2201 rows (since is the current VERSION until the merge slot; +1 GST-2243 remember_share_gst2243 row (re-summed at the #9098 stack merge: 1699 + 1); +1 GST-2312 #9024 sync_filter_owned_hold_9024 row (re-summed at the #9064 stack merge: 1700 + 1; rows are data and cannot move); +2 access-privacy wave (0.60.649.0): the owner_private_facts_gst2089 and private_labels_write_ahead_gst2092 rows; +1 GBRA-443 private_labels_batch_exit_gbra443 row (rows are data and cannot move), re-summed at the 0.60.650.0 slot on #9038: 1703 + 1; +1 postgres_tls_default row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.651.0 merge: 1704 + 1; +1 GST-2331 sync_reads_fetch_nothing_gst2331 row (rows are data and cannot move), re-summed at the 0.60.654.0 stack on #9045 6ff5540d: 1705 + 1; +7 QM wave (#9037) rows: attest_scope_read_ops_gst1158, attest_direct_page_writes_deferred_gst1158, personal_sources_gbra284, qm_personal_structured_gst1158, memory_propose_held_writes_gst1158, member_email_link_gst1158, qm_admin_http_gst1094 (re-summed at the 0.60.655.0 stack on #9110 f9b2072e: 1706 + 7); +2 persistence train 13: derived_effect_publication_busy_gst1644 and job_tree_finished_parent_guards rows (since TBD until the merge slot)
+src/commands/auth.ts 1503 ratchet new row: crossed the 1500 unlisted cap at the v0.60.595.0 merge: GST-1113 --attest-sources help lines plus GST-1158 F3 --attest-read help lines (3); CLI help lines cannot move
diff --cc src/core/behavior-change-notice.ts
index 977f74bb21,8188b34cde..0d7fc4952f
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@@ -1494,27 -1494,8 +1494,29 @@@ export const BEHAVIOR_CHANGES: Readonly
{ since: '0.60.622.0', id: 'purge_cancels_deferred_write_gst1602', text: 'With `persistence.refresh_barrier` on, `gbrain forget <id> --purge` no longer refuses `purge_blocked_pending_recovery` while a write deferred behind a refresh holds the claim in its staged body: the deferred write was never claimed, so the purge cancels it with `purged_content`, as it does a queued one, and removes the content at once instead of up to 15 minutes later.' },
{ since: '0.60.623.0', id: 'owner_reads_private_gst2059', text: 'A brain can now name its owner: `gbrain access owner set <member>` (config `access.owner_member`, an enabled member). Every remote credential or stdio server bound to that member reads the whole brain, `visibility: private` pages, privacy-alias pages (`access: private`, ...), derived and pinned-question pages included, through `get_page`, `search`, `query`, `recall` and the other page reads in the sources its grant reads, and `recall` returns its private facts. `readable_by` and folder rules still bind it, and it is not relaxed when it speaks for a shared-room audience. A page the owner\'s credential creates in `default` through `put_page` is not kept to the owner (no `readable_by: [member:<id>]`). Other members, unbound and public callers are unchanged. `_meta.access.relaxation` reads `owner` for such a call, and `gbrain access check --token <name>` reports it. `gbrain repair private-labels` (named runs only) previews the `access: private` labels stamped on ordinary pages with counts per category, keeps real restrictions, and clears the rest in reviewed batches (`--apply --expect <hash>`), recording each change so `--class restore` can put it back. The bulk-ingestion page template no longer writes an `access:` line; what each designation means is in docs/guides/access-designations.md.' },
{ since: '0.60.626.0', id: 'record_origin_checkout_lockdown_8888', text: '`gbrain sources record-origin <id>... --remote --apply` now also turns git-lfs downloads and hooks off in each recorded source\'s existing checkout (its `.git/config`: `lfs.fetchexclude=*`, `core.hooksPath=/dev/null`, `lfs.locksverify=false`), not only on later reclones, in the repository\'s shared config, and refuses `write_failed` naming the key when a worktree-scoped or included setting still overrides one; a source already recorded as remote gets the lock-down on the next `--remote --apply` when its checkout lacks it, even when its files now use git-lfs, and a key that holds several values in that config is replaced by the one clone-time value. On a managed brain it takes the same worktree locks a reclone takes, refusing the id `source_busy` while a reclone, refresh or write holds them, and a reclone reads the record under its own locks. A write that fails is reported for its own id (`write_failed`) instead of ending the run. The git-lfs check reads a committed `.gitattributes` under a directory whose name holds a tab, ignores commented-out `filter=lfs` lines, says when a committed rule only declares an LFS filter, records a clone of an empty repository instead of refusing it, and names the cause of an `lfs_unknown` refusal.' },
+ { since: '0.60.627.0', id: 'ingest_keeps_readers_gst2112', text: 'A webhook capture (`POST /ingest` with `X-Gbrain-Slug` and its `ingest_capture` job) is now refused `readable_by_invalid` when its body drops `readable_by` from a page that names readers, or names readers that leave out the sending token or client: the route answers 403 and queues nothing, and a job already queued refuses at write time. Before, such a capture replaced the page and its readers, and every caller could read it. Bodies that keep the readers, and pages without readers, import as before.' },
+ { since: '0.60.628.0', id: 'federated_member_writes_8982', text: 'A token or OAuth client bound to a member whose write source is a federated source (`gbrain sources federate <id>`) now writes the pages it creates with `readable_by: [member:<id>]`, as one writing to `default` does, because every credential without a source grant reads federated sources too; `POST /ingest` refuses such a credential. Before this, other members\' no-grant tokens and unbound tokens read those pages. A write source that is not federated is unchanged, and pages written before the upgrade keep their readers (`gbrain access who-can-read <slug>`).' },
+ { since: '0.60.630.0', id: 'commit_push_skipped_paths_gst2116', text: '`gbrain git commit-push` and `scripts/brain-commit-push.sh` now exit 1 when git left a named path out of the commit, instead of exiting 0: a modified file flagged assume-unchanged or skip-worktree, or a file inside a nested Git repository. The other named paths are still committed (and pushed on a classic checkout); the error names each skipped path and its reason: `writer_coordinator_required` for a page in a managed canonical worktree (save it through put_page), `commit_paths_skipped` otherwise. The helper\'s managed-checkout refusal now prints the operator contract (code, why, fix, next). Existing brains get the new helper on the next `gbrain sources harden`.' },
+ { since: '0.60.632.0', id: 'pending_ledger_flagged_gst2118', text: 'A page write that git could not commit because the file is flagged assume-unchanged or skip-worktree now stays in the write-through pending ledger, so `gbrain doctor` reports it as `dirty_age`, and `gbrain git commit-push --pending` exits 1 with `commit_paths_skipped` naming it instead of exiting 0 with nothing_to_commit. `gbrain git commit-push` naming a modified skip-worktree file now commits the other paths and fails `commit_paths_skipped` (reason `skip_worktree`) instead of `commit_paths_invalid` with nothing committed.' },
+ { since: '0.60.635.0', id: 'read_scope_params_gbra431', text: 'An MCP read now refuses an unknown parameter whose name is, or is nearest to, a source scope or a filter (`source` for `source_id`, `sources` for `source_ids`, `type` for `types`, `tag`, `since`, `entity`, `visibility`, `min_trust`) with `invalid_params` naming the declared parameter, whatever `mcp.strict_params` says; it used to ignore it and answer unnarrowed. Other unknown read parameters keep the warn grace period. `gbrain serve --http` now applies `GBRAIN_HTTP_RATE_LIMIT_IP`, `GBRAIN_HTTP_RATE_LIMIT_TOKEN` and `GBRAIN_HTTP_MAX_BODY_BYTES` to `/mcp` when they are set (429 with Retry-After, 413); unset, it keeps no rate limit and a 4 MiB body cap.' },
+ { since: '0.60.637.0', id: 'sync_restored_file_gst2201', text: 'On a managed source, a page sync deleted because its file was gone comes back on the next sync once the file returns (a `git revert`, a branch or detached checkout and back, a later commit that re-adds it with the same or edited bytes, a file missing from disk for one working-tree sync). It used to stay deleted (`deleted_same`, or a `file_drift` hold whose suggested fix removed the file) while `gbrain sync status` said synced. The first sync after the upgrade reads the whole source once, so pages an older version left deleted beside their file come back and such holds clear without a manual step. A page a person deleted keeps its deletion.' },
+ { since: '0.60.637.0', id: 'purge_keeps_committed_file_gst2201', text: 'The retention purge (the autopilot purge phase, the `purge` job and `gbrain pages purge-deleted`) never removes a soft-deleted page\'s file that is committed at its source\'s last synced commit or at HEAD. A page sync deleted whose file is back is left for the sync that restores it (counted as deferred); any other such page is removed database-only (receipt `write_through.skipped: committed_file`) and its file stays. A page whose file is gone, or a person\'s delete that never removed its file (for example because another page shared it), purges as before. A page purge (`gbrain delete <slug> --purge` and the retention purge) now also redacts the timeline text the page\'s `add_timeline_entry` receipts kept (the entry\'s summary and source, `bullet`), compacted ones included.' },
+ { since: '0.60.647.0', id: 'remember_share_gst2243', text: 'A member credential\'s `remember` still saves privately on `memory/members/<member>` by default, and can now pass `share: true` to save the fact on its subject\'s page for everyone who reads the source, as every non-member caller does. A member\'s explicit `visibility: "world"`, which used to be saved as private without a word, is now refused (`invalid_params`, reason `member_share_required`) and nothing is saved; `share: true` with `visibility: "private"`, or onto a page whose facts are kept private, is refused too (`share_target_restricted` for the page). Only the brain host can withdraw a shared fact. With ambient writeback on, a member credential\'s instructions say to omit `visibility` and use `share: true` for team facts, and a credential that may name a member through `x-qm-actor` is told to do so on those calls and pass `visibility: "world"` on the rest. Every `remember` reply, for any caller, now names the `page` the fact went to and its `visibility`. QM\'s `memory_write` is unchanged.' },
+ { since: '0.60.648.0', id: 'sync_filter_owned_hold_9024', text: 'A managed sync now holds a committed file that Git stores through a filter (a path whose `filter` attribute at the synced commit names a driver other than Git LFS, whether or not this checkout configures that driver, or a file starting with git-crypt\'s header) as `content_filter_owned`, and the rest of the source syncs. Before, such a file imported its stored bytes (git-crypt ciphertext, for one) as the page text, or a git-crypt file was held `content_null_bytes`. gbrain still never runs a repository\'s filter programs (or `core.fsmonitor`) during sync, and reading the filter attribute fetches nothing, so a partial clone that lacks a `.gitattributes` that applies to the file holds it `git_object_missing`; the hold names git-crypt when the header matches and says to leave the file out with `sync.exclude` or commit it without the filter, and for a plain-text file under a filter attribute nobody uses, to remove the attribute and run `gbrain sources retry-held`. A page an older version already imported from such a file is left as it is until the file changes; then the file is held. With `sync.holds=fail`, and on a company-brain source (which never holds), the run stops with `content_filter_owned`. Classic (unmanaged) sync is unchanged.' },
+ { since: '0.60.649.0', id: 'owner_private_facts_gst2089', text: 'The brain owner\'s remote credentials now get private facts in the `query` facts arm, `think` trajectories, hot memory, `delta` and `context_pack` hot facts, and from `recall` with a `question`, under the same rule as its private pages: no audience, or an audience of the owner alone. Facts taken from a page the owner cannot read and facts outside its source grant stay hidden. Facts on `entity` and `context_pack` cards stay world-only. Every other remote caller is unchanged.' },
+ { since: '0.60.649.0', id: 'private_labels_write_ahead_gst2092', text: '`gbrain repair private-labels` writes its undo ledger ahead of each page: an `intent` line before the write and a `committed` line after it, so a run that stops between them can still be undone with `--class restore`, and a ledger that cannot take the intent line refuses the apply (`storage_error`) before anything changes. Restore re-adds only `access` and `visibility: private` from well-formed ledger lines (others are counted unreadable) and no longer lists a page whose label was removed after a restore landed (`removed_after_restore`). The preview counts the derived_from pages and life-chronicle events each window would expose along with its pages; on a brain without managed persistence a page whose file sits in its source\'s checkout is held (`file_backed`) instead of being cleared in the database only; and an apply that ends with a failure keeps its approved preview, so the same `--apply --expect` resumes it.' },
+ { since: '0.60.650.0', id: 'private_labels_batch_exit_gbra443', text: '`gbrain repair private-labels --apply --expect` on a brain with managed persistence admits a window\'s pages together and publishes them in groups instead of one page and one wait at a time; a page whose write is declined fails alone. `gbrain repair <kind> --apply --expect <hash>` (every preview-bound kind) now exits 0 when the run is complete, nothing stopped, and every failed item is its page declining the write (`source_changed`, `page_body_segmented`); the result counts them in `declined` by reason, and any other failure or a stop still exits 1. An apply bound to no preview keeps exit 1 for them. The private-labels preview lists pages an earlier apply tried and that did not change after every page not tried yet (`details.window.tried_before`), no longer claims a re-embed for every page (only pages stored under per-chunk synopsis, or with a chunk that has no vector yet, count), and an apply result carries `details.ledger`, `details.ledger_rows_written` and `details.ledger_rows`. A page an earlier apply tried that declines again no longer counts toward `item_failures_systemic`, so a window of carried declines completes; pages not tried yet still trip it. A preview-bound repair apply waits out a `gbrain sources refresh` for up to 10 minutes per step instead of 10 s, and past that ends with `worktree_refreshing` (exit 1) naming the refresh and its running time; rerunning the same apply resumes. Other interactive writes keep 10 s.' },
+ { since: '0.60.653.0', id: 'postgres_tls_default', text: 'Postgres connections to a host that is not on this machine now require TLS (sslmode=require) unless the database URL names an sslmode; localhost, 127.0.0.0/8, ::1 and Unix sockets are unchanged. A private address or a Docker service name counts as not on this machine. A database server without TLS now fails to connect with `postgres_tls_required` instead of connecting in plaintext: turn TLS on at the server, or add `sslmode=disable` to the database URL to keep the old plaintext connection on a network you trust. `sslmode=require` encrypts but does not verify the server certificate; `sslmode=verify-full` (with the provider CA in `NODE_EXTRA_CA_CERTS`) verifies it too. `gbrain doctor --only postgres_tls` shows whether this brain\'s connection is encrypted.' },
+ { since: '0.60.654.0', id: 'sync_reads_fetch_nothing_gst2331', text: 'A managed sync now makes no object fetches in a partial clone (`git clone --filter`): every Git read it makes runs with Git\'s transports and lazy fetching switched off. A committed file whose blob the partial clone never fetched imports from the working tree when those bytes are the committed blob, and is otherwise held `git_object_missing` with a message that names the partial clone and the `git cat-file -p <blob>` that fetches it; a partial clone with no checkout holds every committed file this way. A blobless clone with a normal checkout syncs its files as before, but an older object it never fetched is read only once it is fetched: when rename detection needs an older blob the partial clone lacks, the sync compares the whole tree instead (the new path imports as a new page and the old page is deleted, so that rename does not keep its page), and folder rules wait as below. A treeless clone (`--filter=tree:0`) that lacks a tree of the synced commit stops the run with `git_object_missing`, naming the partial clone and the `git ls-tree -r -d <commit>` that fetches the trees, and syncs or deletes nothing until then. A source whose commit names a folder-rule file (`.gbrain/access.yml`, `.gbrain/access.approved`) this clone has not fetched, or whose rule history a rebuild cannot read (a first sync replays every earlier version of `access.yml`), reads as nobody to remote members until the objects are fetched, the same as the shallow-checkout rule; its problem names the exact command that fetches them (`git -C <root> cat-file -p <rev>:./<path>` for a file, `git -C <root> log --first-parent -p <rev> -- .gbrain/access.yml` for the history), and the next sync after that command applies the rules and clears the mark with no other step. Before, the sync fetched a missing object from the partial clone\'s remote.' },
+ { since: '0.60.655.0', id: 'attest_scope_read_ops_gst1158', text: 'An attested call (`x-qm-actor`) to `get_page`, `entity`, `whois`, `get_backlinks`, `get_timeline`, `find_experts`, `volunteer_context` or `query` that names `source_id` or `source_ids` now reads as those sources\' audience, as `memory_recall` already did: the person\'s pages restricted to named readers and their member page `memory/members/<member>` read as missing, a source outside the credential\'s read grant is refused, and `__all__` or `all_sources` beside a named source is refused (`invalid_params`). `get_timeline` gains `source_id` and `source_ids`, `find_experts` and `volunteer_context` gain `source_ids`, and `volunteer_context` refuses `stats: true` under that read. `gbrain auth rescope --attest-read person|scope|none` sets how an attest credential reads named sources: `person` narrows to them but reads as the person; `scope` reads them as their audience and refuses every call that names no person (`actor_not_attested` reason `actor_required`), reading nothing; unset (the default) keeps the scope read and still serves calls that name no person. `gbrain doctor` warns (`attest_read_shared_scope`) when a person credential reads a source another attest credential reads as the scope.' },
+ { since: '0.60.655.0', id: 'attest_direct_page_writes_deferred_gst1158', text: 'An attested call (`x-qm-actor`) may no longer run `add_timeline_entry`, `add_link`, `put_page` or `edit_page`: they write pages every reader of the page sees, so they wait for owner-approved proposals. `gbrain auth rescope --attest-ops` refuses a list that names one, a credential whose list already names one is refused for it on every attested call (`actor_not_attested`, reason `op_not_attested`), and a queued attested write of one fails when it publishes. Unattested calls and member-bound credentials are unchanged.' },
+ { since: '0.60.655.0', id: 'personal_sources_gbra284', text: 'An operator can bind a source to the member it belongs to (`gbrain access member source add <member> <source>`, migration v299); a bound source is personal. An attested call (`x-qm-actor`) now reads its credential\'s grant minus every personal source bound to another member, and a read that names sources as their audience (the scope read) reads no personal source at all, not even the speaker\'s own. A hidden personal source named in `source_id` or `source_ids` is refused exactly like a source outside the grant (`permission_denied`); an unnamed read skips it. The rule only hides inside the grant and never makes a source readable, so it is within the existing trust posture (gate_rev 6). On an existing install nothing changes until an operator binds a source; after that, a credential whose grant already includes the bound source stops showing it to attested callers for anyone else. Unattested calls and member-bound credentials are unchanged.' },
+ { since: '0.60.655.0', id: 'qm_personal_structured_gst1158', text: 'An attested call (`x-qm-actor`) to `query`, `get_page`, `get_timeline`, `get_backlinks`, `find_experts`, `whois`, `entity`, `context_pack`, `volunteer_context`, `get_write_request` or `forget_fact` now also answers with its result in `structuredContent` (a list as `structuredContent.results`) and its refusals with `structuredContent.error`; `content` keeps the JSON, except `context_pack`, whose `content` is now its rendered text alone. A personal read whose answer, counted with `structuredContent`, is over the result cap is refused whole (`result_too_large`). Each `memory_recall` fact in `structuredContent.facts` gains `arm` (`own` or `ranked`). The same tools without `x-qm-actor` are unchanged, and none of them joined the default attested operations.' },
+ { since: '0.60.655.0', id: 'memory_propose_held_writes_gst1158', text: 'New attested operation `memory_propose` (add it to `--attest-ops`): QM proposes one timeline entry or link on a shared page for the person it serves, and nothing is written until the brain owner runs `gbrain memory-proposals approve <request_id>` (`list`, `show`, `deny --reason`). `get_write_request` and `cancel_write_request` read and withdraw the proposal; an approved one becomes an ordinary write under the same request id. Held text stays in the `memory_proposals` table, out of git, export, search and recall. Proposals expire after `proposals.ttl_hours` (168), at most 10 wait per person and 50 per credential, and closed ones are deleted after `proposals.retention_days` (30). `gbrain doctor` (`memory_proposals_pending`) and `gbrain status` show the queue.' },
+ { since: '0.60.655.0', id: 'member_email_link_gst1158', text: 'A member can carry an operator-declared email: `gbrain access member add <id> --email <addr>` or `gbrain access member set <id> --email <addr>|none`, shown by `member list`, stored lower-case and unique per brain, and cleared when the member is removed. `gbrain access member link --email <addr> --qm <id>` (and `gbrain mcp admin link --email`, `member-add --email`, `member-set` over the owner session) links the one member that declares it, exactly as linking by member id does; an unknown email is `not_found` and creates nothing. No OAuth token, attested call or MCP tool can set an email or make a link.' },
+ { since: '0.60.655.0', id: 'qm_admin_http_gst1094', text: 'The brain owner can now manage the attest right, members and canonical-id links over the running server: `gbrain mcp admin attest <client> --attest-actor qm|none [--attest-ops <list>]`, `member-add`, `member-disable`, `member-enable`, `members`, `link <member> --qm <id>`, `unlink --qm <id>` and `links`, backed by `/admin/api/access/attest`, `/admin/api/access/members` and `/admin/api/access/member-links`. These routes take the owner session only (never an OAuth token or an MCP tool), refuse what the local `gbrain auth rescope` and `gbrain access member` commands refuse, preview with `--dry-run` where those do, and log each applied change as `access_admin`. Removing a member stays a brain-host command.' },
+ { since: 'TBD', id: 'derived_effect_publication_busy_gst1644', text: 'A `links` or `facts-backstop` effect that meets another write\'s publication in flight in the same worktree (its claim live, or committed with its recovery record not yet cleared) now waits as `writer_busy` with the busy backoff (250 ms doubling, at most 60 s) instead of `recovery_required` with a fixed 30 s retry, so a write receipt no longer reports `recovery_required` for that routine wait. A recovery record whose publisher\'s claim lapsed, or a request in `recovering`, still holds the effect as `recovery_required`. Neither wait parks a links or facts-backstop effect, and no derived link is lost: the next effect pass after it is due derives it. An `embedding` effect in the same wait now records `writer_busy` too; its retry schedule is unchanged.' },
+ { since: 'TBD', id: 'job_tree_finished_parent_guards', text: '`gbrain jobs cancel <id>` (and the `cancel_job` tool) on a job that already finished now refuses and changes nothing; it used to cancel that job\'s still-live children while reporting that it could not cancel. Cancel a live child by its own id. Submitting a child under a parent that already completed, failed, died or was cancelled now refuses instead of queueing work nothing waits for. A parent failed by a `fail_parent` child no longer keeps the lock it held while active.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --cc src/core/cli-flag-registry.generated.ts
index 25377b4e16,61bdeaef93..a4cc79e32d
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@@ -48,11 -48,11 +48,11 @@@ export const CLI_FLAG_REGISTRY: Record<
'connectors': ['--accept-pending', '--all', '--as', '--background', '--brain', '--channels', '--cookie', '--deadline', '--dry-run', '--embed', '--explain', '--follow', '--force', '--full', '--help', '--install', '--json', '--kind', '--limit', '--max-requests', '--no-accept-pending', '--no-browser', '--probe', '--progress-interval', '--progress-json', '--provider', '--quiet', '--source', '--timeout', '--timings', '--token', '--try-oauth', '--wait', '--window-days', '--workers', '--yes'],
'conversation-parser': ['--brain', '--help', '--json', '--source'],
'core': ['--apply', '--brain', '--fail-fast', '--help', '--include-core', '--json', '--priority', '--revision', '--slug', '--source', '--tools-json'],
- 'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--search-mode', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],
+ 'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embed', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--search-mode', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],
'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--as', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--timings', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--claims', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],
- 'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--follow', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--restart-only', '--reverse', '--row', '--scopes', '--session', '--side', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--surface', '--to', '--updated-after', '--url', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--approval-out', '--approved', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--attest-sources', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--base', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--cherry-mark', '--claims', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--confidence', '--confirm', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--db-url', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--images', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--of', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preset', '--preview', '--principal', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--readers', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--rules', '--run', '--runtime', '--sample', '--save', '--scan-secrets', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--source-ids', '--sources', '--squash', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--types', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--worktree', '--write-tree', '--yes'],
+ 'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--filter', '--follow', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--restart-only', '--reverse', '--row', '--scopes', '--session', '--side', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--surface', '--to', '--updated-after', '--url', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--approval-out', '--approved', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--base', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--bundled', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--cherry-mark', '--claims', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--confidence', '--config', '--confirm', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--db-url', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--env-file', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--filter', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-json', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--generation', '--get', '--get-all', '--get-regexp', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--images', '--import', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-assume-unchanged', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-optional-locks', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-skip-worktree', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--of', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preload', '--preset', '--preview', '--principal', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--readers', '--reason', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--reset-session', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--routing', '--rules', '--run', '--runtime', '--sample', '--save', '--scan-secrets', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--source-ids', '--sources', '--squash', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--tags', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--tsconfig-override', '--type', '--types', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--worktree', '--write-tree', '--yes'],
++ 'doctor': ['--abandon', '--abbrev-ref', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--approval-out', '--approved', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--base', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--bundled', '--by-mention', '--cached', '--call-site', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--claims', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--confidence', '--config', '--confirm', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--db-url', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--env-file', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--filter', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-json', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--generation', '--get', '--get-all', '--get-regexp', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--images', '--import', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-assume-unchanged', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-migrate', '--no-optional-locks', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-skip-worktree', '--no-tags', '--no-verify', '--no-walk', '--non-interactive', '--now', '--of', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preload', '--preset', '--preview', '--principal', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--readers', '--reason', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--reset-session', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--root', '--routing', '--rules', '--run', '--runtime', '--sample', '--save', '--scan-secrets', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--source-ids', '--sources', '--squash', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--tags', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--tsconfig-override', '--type', '--types', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--worktree', '--write-tree', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--phase', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
@@@ -73,21 -73,20 +73,21 @@@
'founder': ['--brain', '--help', '--json', '--mcp-only', '--request-id', '--since', '--source', '--until'],
'friction': ['--agent', '--base', '--brain', '--compare', '--help', '--hint', '--json', '--kind', '--message', '--no-redact', '--phase', '--run-id', '--severity', '--source', '--transcript-path', '--transcripts'],
'frontmatter': ['--allow-catch-all', '--batch', '--brain', '--cached', '--diff-filter', '--dry-run', '--exclude-standard', '--fix', '--force', '--full-name', '--get', '--git-common-dir', '--help', '--importable', '--include-ambiguous', '--include-catch-all', '--json', '--literal-pathspecs', '--local', '--name-only', '--no-verify', '--others', '--path', '--show-prefix', '--show-toplevel', '--source', '--stage', '--staged', '--stdin', '--type', '--uninstall'],
- 'git': ['--abbrev-ref', '--absolute-git-dir', '--add', '--aggressive', '--all', '--allow-outside-source-root', '--autostash', '--base', '--batch-check', '--brain', '--branch', '--cached', '--cacheinfo', '--cherry-mark', '--count', '--dry-run', '--enable', '--error-unmatch', '--exit-code', '--expect-remote', '--ff-only', '--file', '--force', '--force-remove', '--force-with-lease', '--format', '--get', '--get-all', '--get-regexp', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--hard', '--help', '--index-info', '--install', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-checkout', '--local', '--local-env-vars', '--max-count', '--merge-base', '--message', '--mode', '--name-only', '--name-status', '--no-assume-unchanged', '--no-autostash', '--no-commit-id', '--no-cron', '--no-gpg-sign', '--no-merges', '--no-optional-locks', '--no-recurse-submodules', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-verify', '--no-write-fetch-head', '--not', '--only', '--parents', '--pat-file', '--path', '--path-format', '--pending', '--porcelain', '--pull', '--push', '--push-only', '--quiet', '--rebase', '--repo', '--require-clean', '--resolve', '--reverse', '--right-only', '--root', '--scan-secrets', '--short', '--show-toplevel', '--source', '--source-id', '--staged', '--stat', '--stdin', '--topo-order', '--type', '--uninstall', '--unset', '--unset-all', '--untracked-files', '--verify', '--worktree', '--write-tree'],
- 'google': ['--access', '--account', '--allow-create-db', '--allow-docker', '--brain', '--calendar-id', '--chat-model', '--client-id', '--client-json', '--client-secret', '--code', '--consent-state', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--history-days', '--http', '--issuer-url', '--json', '--key', '--kind', '--limit', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-browser', '--no-embedding', '--no-git', '--no-probe', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--paste', '--path', '--pglite', '--plan', '--port', '--prefer-postgres', '--probe', '--provenance', '--purge-client', '--query', '--reauth', '--retry-failed', '--schema-pack', '--scopes', '--search-mode', '--services', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--sync-budget-ms', '--timeout-ms', '--to', '--token-command', '--url', '--version', '--via', '--yes'],
- 'git': ['--abbrev-ref', '--absolute-git-dir', '--add', '--aggressive', '--all', '--allow-outside-source-root', '--autostash', '--base', '--batch-check', '--brain', '--branch', '--cached', '--cacheinfo', '--cherry-mark', '--count', '--diff-filter', '--dry-run', '--enable', '--exclude-standard', '--exit-code', '--expect-remote', '--ff-only', '--file', '--force', '--force-remove', '--force-with-lease', '--format', '--get', '--get-all', '--get-regexp', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--hard', '--help', '--index-info', '--install', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-checkout', '--local', '--local-env-vars', '--max-count', '--merge-base', '--message', '--mode', '--name-only', '--name-status', '--no-autostash', '--no-commit-id', '--no-cron', '--no-gpg-sign', '--no-merges', '--no-recurse-submodules', '--no-renames', '--no-tags', '--no-verify', '--no-write-fetch-head', '--not', '--only', '--others', '--parents', '--pat-file', '--path', '--path-format', '--pending', '--porcelain', '--pull', '--push', '--push-only', '--quiet', '--rebase', '--repo', '--require-clean', '--resolve', '--reverse', '--right-only', '--root', '--scan-secrets', '--short', '--show-toplevel', '--source', '--staged', '--stat', '--topo-order', '--type', '--uninstall', '--unset', '--unset-all', '--untracked-files', '--verify', '--worktree', '--write-tree'],
++ 'git': ['--abbrev-ref', '--absolute-git-dir', '--add', '--allow-outside-source-root', '--autostash', '--base', '--brain', '--branch', '--cached', '--diff-filter', '--dry-run', '--enable', '--error-unmatch', '--exclude-standard', '--expect-remote', '--ff-only', '--file', '--force', '--get', '--get-all', '--get-regexp', '--git-common-dir', '--git-dir', '--git-path', '--hard', '--help', '--index-info', '--install', '--is-inside-work-tree', '--json', '--keep-checkout', '--local', '--local-env-vars', '--message', '--mode', '--name-only', '--name-status', '--no-assume-unchanged', '--no-autostash', '--no-cron', '--no-optional-locks', '--no-recurse-submodules', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-verify', '--only', '--others', '--pat-file', '--path', '--path-format', '--pending', '--porcelain', '--pull', '--push-only', '--quiet', '--rebase', '--repo', '--require-clean', '--resolve', '--scan-secrets', '--short', '--show-toplevel', '--source', '--source-id', '--stdin', '--type', '--uninstall', '--unset', '--unset-all', '--untracked-files', '--verify', '--worktree', '--write-tree'],
+ 'google': ['--access', '--account', '--allow-create-db', '--allow-docker', '--brain', '--calendar-id', '--chat-model', '--client-id', '--client-json', '--client-secret', '--code', '--consent-state', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--history-days', '--http', '--issuer-url', '--json', '--key', '--kind', '--limit', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-browser', '--no-embed', '--no-embedding', '--no-git', '--no-probe', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--paste', '--path', '--pglite', '--plan', '--port', '--prefer-postgres', '--probe', '--provenance', '--purge-client', '--query', '--reauth', '--retry-failed', '--schema-pack', '--scopes', '--search-mode', '--services', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--sync-budget-ms', '--timeout-ms', '--to', '--token-command', '--url', '--version', '--via', '--yes'],
'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', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--gbrain-bin', '--get', '--harness', '--help', '--instructions', '--instructions-only', '--jq', '--json', '--limit', '--name-only', '--no-instructions', '--only', '--others', '--pat-file', '--path', '--porcelain', '--print', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--source-ids', '--verify', '--workspace', '--yes'],
+ 'hook': ['--allow-unverified-remote', '--auto', '--batch-check', '--brain', '--branch', '--cached', '--catalog', '--count', '--diff-filter', '--dir', '--enable', '--end-of-options', '--env', '--gbrain-bin', '--get', '--harness', '--help', '--instructions', '--instructions-only', '--jq', '--json', '--limit', '--name-only', '--no-instructions', '--only', '--others', '--pat-file', '--path', '--porcelain', '--print', '--pure', '--quiet', '--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', '--literal-pathspecs', '--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'],
- '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', '--applied', '--apply', '--approval-out', '--approved', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--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', '--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', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--federated', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grammar', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-cross-entity', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--input', '--install', '--instructions-only', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--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', '--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-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', '--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', '--save', '--scan-secrets', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--session', '--session-id', '--shared-skills', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--sources', '--squash', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--types', '--uninstall', '--unsettle', '--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', '--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', '--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-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grammar', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-cross-entity', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--input', '--install', '--instructions-only', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--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', '--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-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', '--save', '--scan-secrets', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--session', '--session-id', '--shared-skills', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--sources', '--squash', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--types', '--uninstall', '--unsettle', '--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', '--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-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', '--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', '--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', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skill-loading', '--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', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--text', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--token-env', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
- 'jobs': ['--abbrev-ref', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--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', '--by-mention', '--cached', '--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-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--finished-since', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--format', '--fresh', '--from-index', '--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', '--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', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--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-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', '--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', '--row', '--save', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--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', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--token-env', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
- 'lint': ['--abbrev-ref', '--accept-pending', '--add', '--admin-intent', '--adopt-slug-path', '--as', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--get-all', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--older-than', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--timeout', '--timings', '--unset-all', '--wait', '--yes'],
++ 'jobs': ['--abbrev-ref', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--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', '--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', '--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', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skill-loading', '--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', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--text', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--token-env', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
+ 'lint': ['--abbrev-ref', '--accept-pending', '--add', '--admin-intent', '--adopt-slug-path', '--as', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--get-all', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-assume-unchanged', '--no-autostash', '--no-cron', '--no-pull', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-verify', '--older-than', '--only', '--pat-file', '--path', '--porcelain', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--stdin', '--timeout', '--timings', '--unset-all', '--untracked-files', '--verify', '--wait', '--yes'],
'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
- 'maintain': ['--absolute-git-dir', '--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check-only', '--class', '--clear', '--client', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cwd', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--ignore-missing', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-instructions', '--no-pull', '--no-renames', '--no-walk', '--once', '--only', '--operations', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--session', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--supabase', '--surface', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--untracked-files', '--url-env', '--verbose', '--verify', '--version', '--window', '--workers', '--workspace', '--yes'],
- 'mcp': ['--admin-token-file', '--advertise', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],
+ 'maintain': ['--absolute-git-dir', '--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--attest-read', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check-only', '--class', '--clear', '--client', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cwd', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--ignore-missing', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-instructions', '--no-pull', '--no-renames', '--no-walk', '--once', '--only', '--operations', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--session', '--show-current', '--show-toplevel', '--since', '--skill-loading', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--supabase', '--surface', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--untracked-files', '--url-env', '--verbose', '--verify', '--version', '--window', '--workers', '--workspace', '--yes'],
+ 'mcp': ['--admin-token-file', '--advertise', '--agent', '--all', '--arg', '--attest-actor', '--attest-ops', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--email', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--groups', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--member', '--name', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--qm', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],
+ 'memory-proposals': ['--all', '--brain', '--dry-run', '--help', '--json', '--limit', '--reason', '--replace', '--source'],
'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--as', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--harness', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--statement-timeout', '--status', '--timeout', '--timings', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],
'models': ['--batch', '--brain', '--concurrent', '--cycles', '--dim', '--dimensions', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--limit', '--max-tokens', '--max-usd', '--output', '--receipt-dir', '--skip', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--source', '--status', '--task', '--to', '--yes'],
'mounts': ['--alias', '--brain', '--database-path', '--database-url', '--db-path', '--db-url', '--engine', '--help', '--id', '--json', '--mcp-url', '--path', '--skills-dir', '--source'],
diff --cc src/core/git/commit-push.ts
index 6147b50f93,f5347dc9f5..5fbaa5d111
--- a/src/core/git/commit-push.ts
+++ b/src/core/git/commit-push.ts
@@@ -587,889 -462,859 +587,607 @@@ function commitPaths(root: string, rel
const swept = stagedPaths(root).filter(p => !rel.includes(p) && rel.some(spec => covers(spec, p)));
if (swept.length) {
const list = `${swept.slice(0, 10).join(', ')}${swept.length > 10 ? ', ...' : ''}`;
-- throw opError('commit_prestaged_paths', `${swept.length} file(s) under the named path(s) were already staged by another writer: ${list}.`,
-- 'Nothing was staged or committed. If they are yours, name each file explicitly; otherwise leave them to the writer that staged them, or unstage them with the user\'s agreement (git restore --staged -- <file>; the working tree keeps its bytes).',
-- { detail: JSON.stringify({ paths: swept }), fix: { ask_user: true, consent: [], actor: 'user', requires_exclusive: false,
-- argv: ['git', '-C', root, 'restore', '--staged', '--', ...swept],
-- why: 'Another writer staged these files; committing them would publish whatever that writer had in progress, and unstaging them drops its staging.',
-- user_message: `Files already staged by another writer sit under the path you asked to commit (${list}). Commit only the files you name, or unstage those (their bytes stay on disk)?`,
-- docs: 'docs/guides/shared-checkout-git.md#outcomes' } });
-- }
-- const before = indexEntries(root, rel);
- // GST-2118: git add refuses a named skip-worktree file that is on disk; it is left to the skipped-path check, so the other paths still commit.
++ throw opError('commit_prestaged_paths', `${swept.length} file(s) under the named path(s) were already staged by another writer: ${list}.` // GST-2118: git add refuses a named skip-worktree file that is on disk; it is left to the skipped-path check, so the other paths still commit.
+ const sparse = new Set(gitOk(root, ['ls-files', '-v', '-z', '--', ...literalPathspecs(rel)], 'ls-files -v').split('\0')
+ .filter(entry => /^[sS] /.test(entry) && rel.includes(entry.slice(2)) && existsSync(join(root, entry.slice(2)))).map(entry => entry.slice(2)));
- const add = rel.some(p => !sparse.has(p)) ? withIndexRetry(root, ['add', '-A', '--', ...literalPathspecs(rel.filter(p => !sparse.has(p)))], 'git add') : { code: 0, stdout: '', stderr: '' };
- if (add.code !== 0) {
- throw opError('commit_paths_invalid', 'git add refused the given paths.', add.stderr.trim().slice(0, 300) || 'Check the paths exist or are tracked.');
- }
++ const live = rel.filter(p => !sparse.has(p));
+ // #7984: a tracked path stages with `add -u`, because `add -A` refuses a deletion whose only match left is an ignored
+ // path; visible untracked files stage with `add -A`; a path already staged as deleted is staged. Any other path keeps
+ // git's own refusal (missing, or only an ignored untracked file).
- const listed = (args: string[]) => git(root, [...args, '-z', '--', ...literalPathspecs(rel)]).stdout.split('\0').filter(Boolean);
++ const listed = (args: string[]) => live.length ? git(root, [...args, '-z', '--', ...literalPathspecs(live)]).stdout.split('\0').filter(Boolean) : [];
+ const tracked = before.map(line => line.slice(line.indexOf('\t') + 1));
+ const untracked = listed(['ls-files', '--others', '--exclude-standard']);
+ const deleted = listed(['diff', '--cached', '--no-renames', '--name-only', '--diff-filter=D']);
- const matching = (paths: string[]) => rel.filter(spec => paths.some(p => covers(spec, p)));
++ const matching = (paths: string[]) => live.filter(spec => paths.some(p => covers(spec, p)));
+ const matched = new Set(matching([...tracked, ...untracked, ...deleted]));
- const unmatched = rel.filter(spec => !matched.has(spec));
- try {
- for (const [mode, specs] of [['-u', matching(tracked)], ['-A', matching(untracked)], ['-A', unmatched]] as const) {
- if (!specs.length) continue;
- const add = withIndexRetry(root, ['add', mode, '--', ...literalPathspecs(specs)], 'git add');
- if (add.code !== 0) throw opError('commit_paths_invalid', 'git add refused the given paths.', add.stderr.trim().slice(0, 300) || 'Check the paths exist or are tracked.');
- }
- const paths = withRenamePartners(root, rel);
- const partners = paths.filter(p => !insideSourceRoots(p, scope.roots));
- if (partners.length) throw outsideRootError(root, scope.roots, partners, 'A staged rename would commit');
- if (git(root, ['diff', '--cached', '--quiet', '--', ...literalPathspecs(paths)]).code === 0) return null;
- const env = { [COMMIT_VIA_ENV]: scope.lockPath, ...(scope.markHeld ? { [COMMIT_LOCK_ENV]: scope.lockPath } : {}) };
- // #7759: literal per path, never git's global --literal-pathspecs: Git exports that to the commit's hooks, where a
- // guard's glob pathspec ('*.json') then matches nothing and lets the commit through.
- recordIntent(root, { writer: 'commit_push', head_before: git(root, ['rev-parse', '--verify', '--quiet', 'HEAD']).stdout.trim() || null, message });
- const commit = withIndexRetry(root, ['commit', '--only', '-m', message, '--', ...literalPathspecs(paths)], 'git commit', env);
- if (commit.code !== 0) {
- throw opError('git_unavailable', `git commit failed in ${root}; the paths were unstaged again and keep their bytes.`,
- `${commit.stderr.trim().slice(0, 300)} A missing git identity (user.name, user.email) or a refusing pre-commit hook are common causes.`);
- }
- const sha = gitOk(root, ['rev-parse', 'HEAD'], 'rev-parse HEAD');
- recordCommit(root, { sha, writer: 'commit_push' });
- return sha;
- } catch (e) {
- try { restoreIndex(root, rel, before); } catch { /* the index lock outlasted the retries; the error below still stands */ }
- throw e;
- }
-}
++ const unmatched = live.filter(spec => !matched.has(spec));
+ let landed: { committed: boolean; paths: string[]; listed: string[] };
- try {
- const paths = withRenamePartners(root, rel);
- const partners = paths.filter(p => !insideSourceRoots(p, scope.roots));
- if (partners.length) throw outsideRootError(root, scope.roots, partners, 'A staged rename would commit');
- // A file git did not index would fail `commit --only` for every path; it is left out here and reported as skipped.
- const listed = gitOk(root, ['ls-files', '-v', '-z', '--', ...literalPathspecs(paths)], 'ls-files -v').split('\0').filter(Boolean);
- const unindexed = new Set(unindexedFiles(root, paths, listed));
- const staged = paths.filter(p => !unindexed.has(p) && !sparse.has(p));
- if (!staged.length || git(root, ['diff', '--cached', '--quiet', '--', ...literalPathspecs(staged)]).code === 0) {
- landed = { committed: false, paths, listed };
- } else {
- const env = { [COMMIT_VIA_ENV]: scope.lockPath, ...(scope.markHeld ? { [COMMIT_LOCK_ENV]: scope.lockPath } : {}) };
- // #7759: literal per path, never git's global --literal-pathspecs: Git exports that to the commit's hooks, where a
- // guard's glob pathspec ('*.json') then matches nothing and lets the commit through.
- recordIntent(root, { writer: 'commit_push', head_before: git(root, ['rev-parse', '--verify', '--quiet', 'HEAD']).stdout.trim() || null, message });
- const commit = withIndexRetry(root, ['commit', '--only', '-m', message, '--', ...literalPathspecs(staged)], 'git commit', env);
- if (commit.code !== 0) {
- throw opError('git_unavailable', `git commit failed in ${root}; the paths were unstaged again and keep their bytes.`,
- `${commit.stderr.trim().slice(0, 300)} A missing git identity (user.name, user.email) or a refusing pre-commit hook are common causes.`);
- }
- landed = { committed: true, paths, listed };
- }
- } catch (e) {
- try { restoreIndex(root, rel, before); } catch { /* the index lock outlasted the retries; the error below still stands */ }
- throw e;
- }
- // GST-2116: after the try, so a failure from here on never restores the index under a commit that landed.
- const sha = landed.committed ? gitOk(root, ['rev-parse', 'HEAD'], 'rev-parse HEAD') : null;
- if (sha) recordCommit(root, { sha, writer: 'commit_push' });
- return { sha, skipped: unstagedPaths(root, landed.paths, landed.listed) };
++l for classic (unmanaged) brain
++ * repos (#6530). Many writers (agents, crons, hooks, gbrain's own
++ * write-through) commit to ONE checkout, so nothing here rebases, stashes or
++ * resets the working tree:
++ *
++ * 1. two locks per checkout: the short commit lock (`git rev-parse --git-path
++ * brain-commit.lock`, the same flock a bash `flock -x` takes) for local
++ * index/HEAD changes only, and the publish lock (brain-publish.lock) for
++ * the network push; a publisher takes the commit lock only to advance, and
++ * an unattended publisher that finds the publish lock busy leaves a request
++ * the holder honors after it releases (so no commit is stranded);
++ * 2. commits carry only the caller's paths (`commit --only -- <paths>`);
++ * 3. a rejected push is integrated IN MEMORY (`merge-tree --write-tree`, or a
++ * 3-way `read-tree` into a temporary index on git < 2.38) into a merge
++ * commit built with `commit-tree`; no working tree is touched;
++ * 4. the shared checkout advances only by `merge --ff-only`, which refuses
++ * (and changes nothing) when HEAD moved or a file it must change is dirty.
++ *
++ * Managed canonical worktrees are refused: the persistence owner is their
++ * only writer. The one exception is a keep-checkout publish (`keepCheckout`,
++ * `--push-only --keep-checkout`): it pushes HEAD, merging a moved remote in
++ * memory, but never moves the checkout and skips its pre-push hook, so `gbrain sources
++ * refresh` stays the only importer of remote files into a managed worktree
++ * (#7010; the owner's Git effects publish this way). CLI-only; never exposed
++ * over MCP (it pushes with host credentials).
++ */
++import { appendFileSync, existsSync, lstatSync, mkdtempSync, readFileSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
++import { tmpdir } from 'node:os';
++import { scanRange } from './range-secret-scan.ts';
++import { isAbsolute, join, relative, resolve } from 'node:path';
++import { execFileSync } from '../spawn.ts';
++import { gitChildEnv, literalPathspecs } from '../git-env.ts';
++import { GIT_ENV, GIT_ENV_AUTH, GIT_SSRF_SUBCOMMAND_FLAGS, durableSsrfFlags } from '../git-transport.ts';
++import { assertManagedFilesystemWrite, hasFilesystemPublication, managedFilesystemRootFor, type ManagedFilesystemRoot } from '../persistence/filesystem-guard.ts';
++import { acquireNativeLock, acquireNativeLockSync, type NativeLockSyncHandle } from '../persistence/native-lock.ts';
++import { recordCommit, recordIntent } from './commit-ledger.ts';
++import { OperationError, opError } from '../ops/contract.ts';
++import { shellQuote, type Action } from '../agent-output.ts';
++import { isSyncable } from '../sync.ts';
+
-// ── Pending write-through ───────────────────────────────────────────────────
++export const COMMIT_LOCK_NAME = 'brain-commit.lock';
++/** Taken by pre-#6530 helpers and hooks; held too so they still exclude us during the mixed-version window. */
++export const LEGACY_PUSH_LOCK_NAME = 'gbrain-push.lock';
++export const COMMIT_LOCK_ENV = 'BRAIN_COMMIT_LOCK_HELD';
++export const PUBLISH_LOCK_NAME = 'brain-publish.lock';
++const PUBLISH_REQUEST_NAME = 'brain-publish.requested';
++const CONFLICT_STATE_NAME = 'brain-integrate-conflict.json';
++/** Write-through files gbrain wrote but could not commit (lock busy past the short budget, or a refused commit): one `<iso>\t<json path>` line each. */
++const PENDING_NAME = 'brain-writethrough-pending.log';
++/** Toplevel-relative source root(s) of this checkout, one value each (`gbrain sources harden` writes them); unset means the whole checkout. */
++export const SOURCE_ROOT_CONFIG = 'gbrain.sourceRoot';
++/** Set to the commit lock path on every commit gbrain makes under that lock; the opt-in commit guard admits only these. */
++export const COMMIT_VIA_ENV = 'GBRAIN_COMMIT_VIA';
++const MAX_PUSH_ATTEMPTS = 8;
++const sleeper = new Int32Array(new SharedArrayBuffer(4));
++const INDEX_LOCK_RETRIES = 5;
+
-export interface PendingWriteThrough { path: string; since: string }
++export type CheckoutState = 'advanced' | 'unchanged' | 'lagging';
+
-const PENDING_NOTED = new Set(['commit_lock_busy', 'git_index_locked', 'git_index_stale', 'git_unavailable', 'git_operation_in_progress']);
++export interface CommitPushResult {
++ /**
++ * `push_deferred`: an unattended publish found another publish running and left it a request to publish HEAD too.
++ * `committed_local`: a managed canonical worktree, or a checkout with no Git remote (`no_remote`), where commit-push only commits the named paths and never pushes.
++ */
++ outcome: 'pushed' | 'nothing_to_commit' | 'pushed_checkout_lagging' | 'push_deferred' | 'committed_local';
++ /** The commit now on the remote branch (the caller's commit or the merge built over it). */
++ sha: string | null;
++ committed: string | null;
++ branch: string;
++ remote: string;
++ paths: string[];
++ /** Remote commits merged in to publish. */
++ integrated: number;
++ /** `remote`: a push reported failure but every push destination already holds the commit (a lost acknowledgement or a concurrent pusher). */
++ confirmed?: 'push' | 'remote';
++ checkout: CheckoutState;
++ lagging_reason?: string;
++ /** Opt-in quarantine (git config gbrain.quarantine): the local versions of conflicting files, parked under a ref; the remote's version was published. */
++ quarantined?: QuarantineEntry;
++ /** The checkout has no Git remote: the paths were committed locally (or were already committed) and nothing was pushed. */
++ no_remote?: true;
++ /** Conflicted files where the remote held a version this checkout had already replaced: this checkout's version was published. */
++ superseded_remote_paths?: string[];
++ /** A managed canonical worktree: the named paths were committed (or had no change) and nothing was pushed. */
++ managed?: true;
++ /** Managed only: commits on the branch its upstream lacks as last fetched; null when no fetched upstream can be read. */
++ unpublished?: number | null;
++ /** Managed only: the branch's configured upstream (`origin/main`); null when it names none. */
++ upstream?: string | null;
+}
- // ── Pending write-through ───────────────────────────────────────────────────
-function readPendingFile(file: string, into: Map<string, string>): void {
- let text: string;
- try { text = readFileSync(file, 'utf8'); } catch { return; }
- for (const line of text.split('\n')) {
- const tab = line.indexOf('\t');
- if (tab === -1) continue;
- let path: unknown;
- try { path = JSON.parse(line.slice(tab + 1)); } catch { continue; }
- const since = line.slice(0, tab);
- if (typeof path === 'string' && path && (!into.has(path) || since < into.get(path)!)) into.set(path, since);
- }
++export interface PullResult {
++ status: 'up_to_date' | 'advanced' | 'ahead' | 'skipped_dirty' | 'lagging';
++ from?: string;
++ to?: string;
++ merged?: boolean;
++ /** Why the checkout could not advance (dirty must-change file, HEAD moved). */
++ reason?: string;
+ }
- export interface PendingWriteThrough { path: string; since: string }
-/** Write-through files gbrain wrote in this checkout but could not commit, oldest first. A path committed since stays listed until the next locked commit settles the ledger. */
-export function readPendingWriteThrough(repo: string): PendingWriteThrough[] {
- try {
- const file = absGitPath(checkoutRoot(repo), PENDING_NAME);
- const entries = new Map<string, string>();
- readPendingFile(file, entries);
- readPendingFile(`${file}.settle`, entries);
- return [...entries].map(([path, since]) => ({ path, since })).sort((a, b) => a.since.localeCompare(b.since));
- } catch {
- return [];
- }
++export interface CommitPushOptions {
++ repo: string;
++ /** Paths to commit, absolute or relative to `cwd`. Ignored with pushOnly. */
++ paths?: string[];
++ message?: string;
++ pushOnly?: boolean;
++ cwd?: string;
++ lockWaitMs?: number;
++ /** `--resolve`: blob choice per conflicted path for the in-memory merge. */
++ resolutions?: Map<string, Resolution>;
++ /**
++ * `--expect-remote`: the remote commit the resolutions were chosen against (required with resolutions). Without
++ * resolutions it binds the publish (#7686): HEAD is merged with that commit, pushed with a lease on it, and a remote that
++ * moved anywhere else refuses, so a rewrite made after the caller checked the remote is never merged back.
++ */
++ expectRemote?: string;
++ /** How long a foreground publish waits for another publish to finish. */
++ publishWaitMs?: number;
++ /** Unattended callers (the post-commit hook): publish, but advance the checkout only when it has no local edit. */
++ advanceOnlyWhenClean?: boolean;
++ /** Push-only: publish HEAD to this remote branch instead of the checked-out branch's upstream (the helper's `--push-only <branch>`). */
++ branch?: string;
++ /** Push-only: never advance the checkout and skip its pre-push hook (a managed canonical worktree; see the header). */
++ keepCheckout?: boolean;
++ /** Before pushing, scan what the commits the upstream lacks add (messages, added lines, merge resolutions) and refuse `publish_secret_found` on a finding: the gate for automatic publishes of commits gbrain did not write. */
++ scanSecrets?: boolean;
++ /** Commit the pending write-through files (`--pending`) instead of named paths. */
++ pending?: boolean;
++ /** Commit and publish files outside the configured source root(s): the user's explicit choice, or gbrain's own scaffolding at the checkout root. */
++ allowOutsideSourceRoot?: boolean;
++ /** `--base <path>=<blob>`: the blob (or `absent`) each named path had at HEAD when the writer read it; a moved one refuses `commit_base_moved`. */
++ bases?: Map<string, string>;
+ }
- const PENDING_NOTED = new Set(['commit_lock_busy', 'git_index_locked', 'git_index_stale', 'git_unavailable', 'git_operation_in_progress']);
-/** The pending ledger's files that still differ from HEAD (doctor's `dirty_age`); the others were committed since. */
-export function pendingWriteThroughStillDirty(repo: string): PendingWriteThrough[] {
- const pending = readPendingWriteThrough(repo);
- if (!pending.length) return [];
- const dirty = dirtyPaths(checkoutRoot(repo), pending.map(e => e.path));
- return pending.filter(e => dirty.has(e.path));
++export type Resolution = { kind: 'ours' } | { kind: 'theirs' } | { kind: 'file'; path: string };
+
- function readPendingFile(file: string, into: Map<string, string>): void {
- let text: string;
- try { text = readFileSync(file, 'utf8'); } catch { return; }
- for (const line of text.split('\n')) {
- const tab = line.indexOf('\t');
- if (tab === -1) continue;
- let path: unknown;
- try { path = JSON.parse(line.slice(tab + 1)); } catch { continue; }
- const since = line.slice(0, tab);
- if (typeof path === 'string' && path && (!into.has(path) || since < into.get(path)!)) into.set(path, since);
- }
++interface Ctx {
++ root: string;
++ branch: string;
++ remote: string;
++ mergeRef: string;
++ trackingRef: string;
++ keepCheckout?: boolean;
}
- /** Write-through files gbrain wrote in this checkout but could not commit, oldest first. A path committed since stays listed until the next locked commit settles the ledger. */
- export function readPendingWriteThrough(repo: string): PendingWriteThrough[] {
-/**
- * Appends without the lock (O_APPEND), so a writer that could not get it still records its file. `root` is the checkout
- * root and `paths` are relative to it (`scopePaths`). The derived write-through also records each file right after writing
- * it (#8073), so a crash before its commit leaves the file for the next locked commit to sweep.
- */
-export function notePending(root: string, paths: string[]): void {
- try { appendFileSync(absGitPath(root, PENDING_NAME), paths.map(p => `${new Date().toISOString()}\t${JSON.stringify(p)}\n`).join('')); } catch { /* best-effort */ }
-}
-
-/** Which of `paths` differ from HEAD in the index or the working tree. */
-function dirtyPaths(root: string, paths: string[]): Set<string> {
- const out = new Set<string>();
- for (let i = 0; i < paths.length; i += 500) {
- const entries = git(root, ['status', '--porcelain', '-z', '--untracked-files=all', '--', ...literalPathspecs(paths.slice(i, i + 500))]).stdout.split('\0');
- for (let j = 0; j < entries.length; j++) {
- if (entries[j].length < 4) continue;
- out.add(entries[j].slice(3));
- if (/^[RC]/.test(entries[j])) j++;
- }
++interface GitRun { code: number; stdout: string; stderr: string }
++
++function git(root: string, args: string[], opts: { auth?: boolean; timeoutMs?: number; env?: NodeJS.ProcessEnv; input?: string; maxBuffer?: number } = {}): GitRun {
++ const base = opts.auth ? { ...GIT_ENV_AUTH } : { ...GIT_ENV };
+ try {
- const file = absGitPath(checkoutRoot(repo), PENDING_NAME);
- const entries = new Map<string, string>();
- readPendingFile(file, entries);
- readPendingFile(`${file}.settle`, entries);
- return [...entries].map(([path, since]) => ({ path, since })).sort((a, b) => a.since.localeCompare(b.since));
- } catch {
- return [];
++ const stdout = execFileSync('git', ['-C', root, ...args], {
++ stdio: ['pipe', 'pipe', 'pipe'],
++ input: opts.input ?? '',
++ timeout: opts.timeoutMs ?? 60_000,
++ ...(opts.maxBuffer ? { maxBuffer: opts.maxBuffer } : {}),
++ env: gitChildEnv({ ...base, LC_ALL: 'C', LANGUAGE: 'C', ...opts.env }),
++ }).toString();
++ return { code: 0, stdout, stderr: '' };
++ } catch (e) {
++ const err = e as { status?: number | null; stdout?: Buffer | string; stderr?: Buffer | string; message?: string };
++ return {
++ code: typeof err.status === 'number' ? err.status : -1,
++ stdout: String(err.stdout ?? ''),
++ stderr: String(err.stderr ?? err.message ?? ''),
++ };
}
- return out;
}
- /** The pending ledger's files that still differ from HEAD (doctor's `dirty_age`); the others were committed since. */
- export function pendingWriteThroughStillDirty(repo: string): PendingWriteThrough[] {
- const pending = readPendingWriteThrough(repo);
- if (!pending.length) return [];
- const dirty = dirtyPaths(checkoutRoot(repo), pending.map(e => e.path));
- return pending.filter(e => dirty.has(e.path));
-/** Drop ledger entries whose file no longer differs from HEAD (the caller holds the commit lock). New lines appended meanwhile go to a fresh ledger file. */
-function settlePending(root: string): void {
- try {
- const file = absGitPath(root, PENDING_NAME);
- const settle = `${file}.settle`;
- const moved = `${file}.${process.pid}.tmp`;
- if (existsSync(file)) renameSync(file, moved);
- const entries = new Map<string, string>();
- readPendingFile(settle, entries);
- readPendingFile(moved, entries);
- const dirty = dirtyPaths(root, [...entries.keys()]);
- const keep = [...entries].filter(([path]) => dirty.has(path)).map(([path, since]) => `${since}\t${JSON.stringify(path)}\n`);
- if (keep.length) { writeFileSync(`${settle}.tmp`, keep.join('')); renameSync(`${settle}.tmp`, settle); }
- else rmSync(settle, { force: true });
- rmSync(moved, { force: true });
- } catch { /* best-effort: the ledger only feeds retries and doctor */ }
++function gitOk(root: string, args: string[], what: string, opts: Parameters<typeof git>[2] = {}): string {
++ const r = git(root, args, opts);
++ if (r.code !== 0) {
++ throw opError('git_unavailable', `git ${what} failed in ${root}: ${r.stderr.trim().slice(0, 300) || `exit ${r.code}`}`,
++ `Run git status in ${root}, fix what git reports, then rerun the same gbrain git commit-push command.`);
++ }
++ return r.stdout.trim();
}
/**
- * Appends without the lock (O_APPEND), so a writer that could not get it still records its file. `root` is the checkout
- * root and `paths` are relative to it (`scopePaths`). The derived write-through also records each file right after writing
- * it (#8073), so a crash before its commit leaves the file for the next locked commit to sweep.
- * Commit-only entry for gbrain's own write paths (write-through pages, facts
- * fences, takes, timeline, lint fixes), always under the commit lock. A writer
- * holding the lock past `lockWaitMs` makes this fail `commit_lock_busy` (the
- * file write itself stands) and the file goes into the pending ledger, which
- * the next locked write-through or `gbrain git commit-push --pending` commits and
- * doctor's `dirty_age` reports. It never commits without the lock: that races
- * other writers on the shared index. Paths must sit under `repo` (the source
- * root). No marker is set, so the post-commit hook publishes. Returns the new
- * commit, or null when the paths had no change.
++ * Transport flags for this checkout's OWN configured remotes: no redirects, no
++ * external helpers, no submodule fetch surface. The file protocol keeps git's
++ * default (`user`): a bare repo on the same host is a supported brain topology
++ * (the pre-#6530 helper pushed to it with plain git), and the URL is the
++ * operator's own config, not remote-supplied input. GBRAIN_GIT_ALLOW_FILE_TRANSPORT
++ * still forces `always` for tests.
*/
- export function notePending(root: string, paths: string[]): void {
- try { appendFileSync(absGitPath(root, PENDING_NAME), paths.map(p => `${new Date().toISOString()}\t${JSON.stringify(p)}\n`).join('')); } catch { /* best-effort */ }
- }
-
- /** Which of `paths` differ from HEAD in the index or the working tree. */
- function dirtyPaths(root: string, paths: string[]): Set<string> {
- const out = new Set<string>();
- for (let i = 0; i < paths.length; i += 500) {
- const specs = literalPathspecs(paths.slice(i, i + 500));
- // GST-2118: status is blind to an assume-unchanged or skip-worktree entry, so a flagged edit is read from HEAD.
- for (const { path } of flaggedChanges(root, git(root, ['ls-files', '-v', '-z', '--', ...specs]).stdout.split('\0').filter(Boolean))) out.add(path);
- const entries = git(root, ['status', '--porcelain', '-z', '--untracked-files=all', '--', ...specs]).stdout.split('\0');
- for (let j = 0; j < entries.length; j++) {
- if (entries[j].length < 4) continue;
- out.add(entries[j].slice(3));
- if (/^[RC]/.test(entries[j])) j++;
-export function commitPathsLocked(repo: string, rel: string[], message: string, opts: { lockWaitMs: number }): string | null {
- const root = checkoutRoot(repo);
- assertManagedFilesystemWrite(root);
- assertNoOperationInProgress(root);
- const paths = scopePaths(root, rel, root);
- const own = relative(realpathSync(root), realpathSync(repo)).split('\\').join('/');
- const roots = [own.startsWith('..') ? '' : own];
- let lock: CommitLock;
- try { lock = acquireCommitLock(root, opts.lockWaitMs); } catch (e) {
- if (PENDING_NOTED.has((e as { code?: string }).code ?? '')) notePending(root, paths);
- throw e;
- }
- try {
- const pending = [...dirtyPaths(root, readPendingWriteThrough(root).map(e => e.path).filter(p => !paths.includes(p) && insideSourceRoots(p, roots)))];
- const scope = { roots, lockPath: lock.lockPath, markHeld: false };
- let sha: string | null;
- try {
- sha = commitPaths(root, [...paths, ...pending], pending.length ? `${message} (+${pending.length} pending write-through file(s))` : message, scope);
- } catch (e) {
- if (!pending.length) throw e;
- sha = commitPaths(root, paths, message, scope);
-- }
- settlePending(root);
- return sha;
- } catch (e) {
- if (PENDING_NOTED.has((e as { code?: string }).code ?? '')) notePending(root, paths);
- throw e;
- } finally {
- lock.release();
-- }
- return out;
++function transportFlags(): string[] {
++ return durableSsrfFlags().flatMap((flag, i, all) =>
++ all[i - 1] === '-c' && flag.startsWith('protocol.file.allow=') && process.env.GBRAIN_GIT_ALLOW_FILE_TRANSPORT !== '1'
++ ? ['protocol.file.allow=user'] : [flag]);
}
- /** Drop ledger entries whose file no longer differs from HEAD (the caller holds the commit lock). New lines appended meanwhile go to a fresh ledger file. */
- function settlePending(root: string): void {
- try {
- const file = absGitPath(root, PENDING_NAME);
- const settle = `${file}.settle`;
- const moved = `${file}.${process.pid}.tmp`;
- if (existsSync(file)) renameSync(file, moved);
- const entries = new Map<string, string>();
- readPendingFile(settle, entries);
- readPendingFile(moved, entries);
- const dirty = (() => { try { return dirtyPaths(root, [...entries.keys()]); } catch { return null; } })();
- const keep = [...entries].filter(([path]) => !dirty || dirty.has(path)).map(([path, since]) => `${since}\t${JSON.stringify(path)}\n`);
- if (keep.length) { writeFileSync(`${settle}.tmp`, keep.join('')); renameSync(`${settle}.tmp`, settle); }
- else rmSync(settle, { force: true });
- rmSync(moved, { force: true });
- } catch { /* best-effort: the ledger only feeds retries and doctor */ }
-// ── In-memory integrate ─────────────────────────────────────────────────────
-
-interface MergeTree {
- /** The merged tree; with conflicts, a placeholder every conflicted path must be resolved over. */
- tree: string | null;
- /** Raw repo-relative paths (NUL-delimited from git, never C-quoted). */
- conflicts: string[];
- /** Conflicts that are not one path's content (file/directory, renames): never resolvable by a blob choice. */
- structural: string[];
++/** Remote operations: transport hardening on every call, credentials allowed, no prompt. */
++function remoteGit(root: string, sub: 'fetch' | 'push', args: string[], timeoutMs = 120_000): GitRun {
++ return git(root, [...transportFlags(), sub, ...GIT_SSRF_SUBCOMMAND_FLAGS, ...args], { auth: true, timeoutMs });
}
- /**
- * Commit-only entry for gbrain's own write paths (write-through pages, facts
- * fences, takes, timeline, lint fixes), always under the commit lock. A writer
- * holding the lock past `lockWaitMs` makes this fail `commit_lock_busy` (the
- * file write itself stands) and the file goes into the pending ledger, which
- * the next locked write-through or `gbrain git commit-push --pending` commits and
- * doctor's `dirty_age` reports. It never commits without the lock: that races
- * other writers on the shared index. Paths must sit under `repo` (the source
- * root). No marker is set, so the post-commit hook publishes. Returns the new
- * commit, or null when the paths had no change. A named path git left out fails
- * `commit_paths_skipped` after the rest is committed (GST-2116).
- */
- export function commitPathsLocked(repo: string, rel: string[], message: string, opts: { lockWaitMs: number }): string | null {
- const root = checkoutRoot(repo);
- assertManagedFilesystemWrite(root);
- assertNoOperationInProgress(root);
- const paths = scopePaths(root, rel, root);
- const own = relative(realpathSync(root), realpathSync(repo)).split('\\').join('/');
- const roots = [own.startsWith('..') ? '' : own];
- let lock: CommitLock;
- try { lock = acquireCommitLock(root, opts.lockWaitMs); } catch (e) {
- if (PENDING_NOTED.has((e as { code?: string }).code ?? '')) notePending(root, paths);
- throw e;
- }
- try {
- const pending = [...dirtyPaths(root, readPendingWriteThrough(root).map(e => e.path).filter(p => !paths.includes(p) && insideSourceRoots(p, roots)))];
- const scope = { roots, lockPath: lock.lockPath, markHeld: false };
- let commit: ReturnType<typeof commitPaths>;
- try {
- commit = commitPaths(root, [...paths, ...pending], pending.length ? `${message} (+${pending.length} pending write-through file(s))` : message, scope);
- } catch (e) {
- if (!pending.length) throw e;
- commit = commitPaths(root, paths, message, scope);
- }
- // GST-2118: a file git left out stays in the ledger, so doctor dirty_age reports it and --pending retries it loudly.
- const ownSkipped = commit.skipped.filter(s => paths.includes(s.path));
- if (ownSkipped.length) notePending(root, ownSkipped.map(s => s.path));
- settlePending(root);
- if (ownSkipped.length) {
- const branch = git(root, ['symbolic-ref', '--quiet', '--short', 'HEAD']).stdout.trim();
- throw skippedPathsError(root, ownSkipped, { outcome: commit.sha ? 'committed_local' : 'nothing_to_commit', sha: commit.sha, committed: commit.sha, branch, remote: '', paths, integrated: 0, checkout: 'unchanged' });
- }
- return commit.sha;
- } catch (e) {
- if (PENDING_NOTED.has((e as { code?: string }).code ?? '')) notePending(root, paths);
- throw e;
- } finally {
- lock.release();
- }
-/** merge-tree conflict types a per-path blob choice fully resolves; anything else is structural. */
-const RESOLVABLE_CONFLICTS = new Set(['CONFLICT (contents)', 'CONFLICT (add/add)', 'CONFLICT (modify/delete)', 'CONFLICT (binary)']);
++export function gitVersion(root: string): [number, number] {
++ const m = /git version (\d+)\.(\d+)/.exec(gitOk(root, ['version'], 'version'));
++ return m ? [Number(m[1]), Number(m[2])] : [0, 0];
+}
- // ── In-memory integrate ─────────────────────────────────────────────────────
-const versions = new Map<string, [number, number]>();
-function cachedGitVersion(root: string): [number, number] {
- let v = versions.get(root);
- if (!v) { v = gitVersion(root); versions.set(root, v); }
- return v;
++function absGitPath(root: string, rel: string): string {
++ const p = gitOk(root, ['rev-parse', '--git-path', rel], 'rev-parse --git-path');
++ if (!p) throw opError('git_unavailable', `git rev-parse --git-path ${rel} printed nothing in ${root}.`, 'Check that git works in this checkout (git status).');
++ return isAbsolute(p) ? p : resolve(root, p);
+ }
- interface MergeTree {
- /** The merged tree; with conflicts, a placeholder every conflicted path must be resolved over. */
- tree: string | null;
- /** Raw repo-relative paths (NUL-delimited from git, never C-quoted). */
- conflicts: string[];
- /** Conflicts that are not one path's content (file/directory, renames): never resolvable by a blob choice. */
- structural: string[];
-/** `--no-write-fetch-head` exists from git 2.29; older git just writes FETCH_HEAD. */
-function fetchFlags(root: string): string[] {
- const [maj, min] = cachedGitVersion(root);
- return ['--no-tags', ...(maj > 2 || (maj === 2 && min >= 29) ? ['--no-write-fetch-head'] : [])];
++/** The checkout's toplevel; throws `commit_paths_invalid` outside a work tree. */
++/** The operator step that commits and pushes only `paths` (relative to `root`) with one -m per message paragraph: the fix text doctor and repair print instead of a bare git add/commit. */
++export function commitPushCommand(root: string, paths: readonly string[], messages: readonly string[]): string {
++ return shellQuote(['gbrain', 'git', 'commit-push', '--path', root, ...messages.flatMap(m => ['-m', m]), '--', ...paths]);
}
- /** merge-tree conflict types a per-path blob choice fully resolves; anything else is structural. */
- const RESOLVABLE_CONFLICTS = new Set(['CONFLICT (contents)', 'CONFLICT (add/add)', 'CONFLICT (modify/delete)', 'CONFLICT (binary)']);
-/**
- * merge-tree --write-tree on git >= 2.38; else (or with the GBRAIN_GIT_NO_MERGE_TREE=1 test seam) a 3-way read-tree
- * that treats any same-path change on both sides as a conflict. `base` replaces the merge base (a replayed commit's
- * parent); merge-tree takes it from git 2.40.
- */
-function mergeTrees(root: string, ours: string, theirs: string, base?: string): MergeTree {
- const [maj, min] = cachedGitVersion(root);
- if ((maj > 2 || (maj === 2 && min >= (base ? 40 : 38))) && process.env.GBRAIN_GIT_NO_MERGE_TREE !== '1') {
- const r = git(root, ['merge-tree', '--write-tree', '--name-only', '-z', ...(base ? [`--merge-base=${base}`] : []), ours, theirs]);
- if (r.code !== 0 && r.code !== 1) throw opError('git_unavailable', 'git merge-tree failed.', r.stderr.trim().slice(0, 300));
- const f = r.stdout.split('\0');
- const tree = f[0] || null;
- if (r.code === 0) return { tree, conflicts: [], structural: [] };
- let i = 1;
- const conflicts = new Set<string>();
- while (i < f.length && f[i] !== '') conflicts.add(f[i++]);
- i++;
- const structural = new Set<string>();
- while (i < f.length && f[i] !== '') {
- const n = Number(f[i++]);
- if (!Number.isInteger(n) || n < 1) break;
- const paths = f.slice(i, i + n);
- const type = f[i + n] ?? '';
- i += n + 2;
- if (type.startsWith('CONFLICT') && !RESOLVABLE_CONFLICTS.has(type)) for (const p of paths) structural.add(p);
- }
- return { tree, conflicts: [...conflicts], structural: [...conflicts].filter(p => structural.has(p)) };
- }
- const mergeBase = base ?? git(root, ['merge-base', ours, theirs]).stdout.trim();
- if (!mergeBase) throw opError('integrate_conflict', 'The local and remote branches share no history.', 'Reconcile the branches by hand.');
- const dir = mkdtempSync(join(tmpdir(), 'gbrain-integrate-'));
- try {
- const env = { GIT_INDEX_FILE: join(dir, 'index') };
- const read = git(root, ['read-tree', '-m', '-i', '--aggressive', mergeBase, ours, theirs], { env });
- if (read.code !== 0) throw opError('git_unavailable', 'git read-tree failed.', read.stderr.trim().slice(0, 300));
- const unmerged = git(root, ['ls-files', '-u', '-z'], { env }).stdout.split('\0').filter(Boolean);
- if (!unmerged.length) return { tree: gitOk(root, ['write-tree'], 'write-tree', { env }), conflicts: [], structural: [] };
- const conflicts = [...new Set(unmerged.map(l => l.slice(l.indexOf('\t') + 1)))];
- const structural: string[] = [];
- for (const path of conflicts) {
- gitOk(root, ['update-index', '--force-remove', '--', path], 'update-index', { env });
- const mine = unmerged.find(l => l.slice(l.indexOf('\t') + 1) === path && l.split('\t')[0].split(' ')[2] === '2');
- if (!mine) continue;
- const [mode, sha] = mine.split('\t')[0].split(' ');
- if (git(root, ['update-index', '--add', '--cacheinfo', `${mode},${sha},${path}`], { env }).code !== 0) structural.push(path);
- }
- return { tree: gitOk(root, ['write-tree'], 'write-tree', { env }), conflicts, structural };
- } finally {
- rmSync(dir, { recursive: true, force: true });
++export function checkoutRoot(dir: string): string {
++ const r = git(dir, ['rev-parse', '--show-toplevel']);
++ if (r.code !== 0 || !r.stdout.trim()) {
++ throw opError('commit_paths_invalid', `${dir} is not inside a git checkout.`,
++ 'Run the command inside the brain checkout or pass --path <checkout>.');
+ }
++ return r.stdout.trim();
+ }
- const versions = new Map<string, [number, number]>();
- function cachedGitVersion(root: string): [number, number] {
- let v = versions.get(root);
- if (!v) { v = gitVersion(root); versions.set(root, v); }
- return v;
-const treeOf = (root: string, commit: string) => gitOk(root, ['rev-parse', `${commit}^{tree}`], 'rev-parse tree');
-
-interface Integration extends MergeTree {
- /** Local commits left out because an upstream commit already carries the same patch (`git patch-id`). */
- skipped: string[];
++function resolveCtx(root: string): Ctx {
++ const sym = git(root, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
++ if (sym.code !== 0) {
++ throw opError('git_detached_head', `${root} is on a detached HEAD, so there is no branch to publish.`,
++ 'Check out the branch the remote tracks (git switch <branch>), then rerun.');
++ }
++ const branch = sym.stdout.trim();
++ if (git(root, ['rev-parse', '--verify', '--quiet', 'HEAD']).code !== 0) {
++ throw opError('git_detached_head', `Branch ${branch} in ${root} has no commit yet.`,
++ 'Make the first commit on this branch with git, then rerun.', { reason: 'unborn' });
++ }
++ const remote = git(root, ['config', '--get', `branch.${branch}.remote`]).stdout.trim() || 'origin';
++ const mergeRef = git(root, ['config', '--get', `branch.${branch}.merge`]).stdout.trim() || `refs/heads/${branch}`;
++ if (remote === '.' || git(root, ['remote', 'get-url', '--', remote]).code !== 0) {
++ throw opError('git_unavailable', `Branch ${branch} in ${root} has no usable remote (${remote}); nothing was committed.`,
++ `Add the remote (git remote add ${remote} <url>) or set the branch upstream, then rerun.`);
++ }
++ const short = mergeRef.replace(/^refs\/heads\//, '');
++ return { root, branch, remote, mergeRef, trackingRef: `refs/remotes/${remote}/${short}` };
}
- /** `--no-write-fetch-head` exists from git 2.29; older git just writes FETCH_HEAD. */
- function fetchFlags(root: string): string[] {
- const [maj, min] = cachedGitVersion(root);
- return ['--no-tags', ...(maj > 2 || (maj === 2 && min >= 29) ? ['--no-write-fetch-head'] : [])];
-const MAX_REPLAY = 500;
-
-/**
- * The tree a publish of `local` over `remote` should carry. A 3-way merge of the two tips
- * counts a local commit whose patch already reached the remote (cherry-picked or rebased there) as a new
- * change again: a remote that edited those lines since conflicts forever, and a remote that reverted it gets
- * the change back silently. So when any local commit is patch-equivalent to an upstream one, the local
- * commits are replayed in memory onto the remote tip instead, oldest first, leaving out the equivalent ones
- * and the clean merges (their content is their parents'). A merge that carries its own resolution, a root
- * commit, or more than MAX_REPLAY commits fall back to the tip merge.
- */
-function integrate(root: string, local: string, remote: string): Integration {
- const commits = git(root, ['rev-list', '--reverse', '--topo-order', '--cherry-mark', '--right-only', '--parents', `${remote}...${local}`])
- .stdout.split('\n').filter(Boolean).map(line => {
- const [head, ...parents] = line.split(' ');
- return { sha: head.slice(1), equivalent: head.startsWith('='), parents };
- });
- const tipMerge = (): Integration => ({ ...mergeTrees(root, local, remote), skipped: [] });
- if (!commits.some(c => c.equivalent) || commits.length > MAX_REPLAY) return tipMerge();
- let acc = remote;
- const conflicts = new Set<string>();
- const structural = new Set<string>();
- const skipped: string[] = [];
- for (const c of commits) {
- if (c.equivalent) { skipped.push(c.sha); continue; }
- if (c.parents.length !== 1) {
- if (c.parents.length !== 2) return tipMerge();
- const own = mergeTrees(root, c.parents[0], c.parents[1]);
- if (own.conflicts.length || own.tree !== treeOf(root, c.sha)) return tipMerge();
- continue;
- }
- const step = mergeTrees(root, acc, c.sha, c.parents[0]);
- for (const p of step.conflicts) conflicts.add(p);
- for (const p of step.structural) structural.add(p);
- acc = gitOk(root, ['commit-tree', '--no-gpg-sign', step.tree!, '-p', acc, '-m', 'gbrain: replay'], 'commit-tree');
- recordCommit(root, { sha: acc, writer: 'replay', ref: null });
++/** `--push-only <branch>`: publish to an explicit remote branch (validated as one exact ref, never a pattern). */
++function withBranch(ctx: Ctx, branch: string | undefined): Ctx {
++ if (!branch) return ctx;
++ const short = branch.replace(/^refs\/heads\//, '');
++ if (!short || git(ctx.root, ['check-ref-format', `refs/heads/${short}`]).code !== 0) {
++ throw opError('commit_paths_invalid', `${branch} is not a valid branch name.`, 'Pass one exact branch name, e.g. --branch main.', { detail: branch });
+ }
- return { tree: treeOf(root, acc), conflicts: [...conflicts], structural: [...structural], skipped };
++ return { ...ctx, mergeRef: `refs/heads/${short}`, trackingRef: `refs/remotes/${ctx.remote}/${short}` };
}
- /**
- * merge-tree --write-tree on git >= 2.38; else (or with the GBRAIN_GIT_NO_MERGE_TREE=1 test seam) a 3-way read-tree
- * that treats any same-path change on both sides as a conflict. `base` replaces the merge base (a replayed commit's
- * parent); merge-tree takes it from git 2.40.
- */
- function mergeTrees(root: string, ours: string, theirs: string, base?: string): MergeTree {
- const [maj, min] = cachedGitVersion(root);
- if ((maj > 2 || (maj === 2 && min >= (base ? 40 : 38))) && process.env.GBRAIN_GIT_NO_MERGE_TREE !== '1') {
- const r = git(root, ['merge-tree', '--write-tree', '--name-only', '-z', ...(base ? [`--merge-base=${base}`] : []), ours, theirs]);
- if (r.code !== 0 && r.code !== 1) throw opError('git_unavailable', 'git merge-tree failed.', r.stderr.trim().slice(0, 300));
- const f = r.stdout.split('\0');
- const tree = f[0] || null;
- if (r.code === 0) return { tree, conflicts: [], structural: [] };
- let i = 1;
- const conflicts = new Set<string>();
- while (i < f.length && f[i] !== '') conflicts.add(f[i++]);
- i++;
- const structural = new Set<string>();
- while (i < f.length && f[i] !== '') {
- const n = Number(f[i++]);
- if (!Number.isInteger(n) || n < 1) break;
- const paths = f.slice(i, i + n);
- const type = f[i + n] ?? '';
- i += n + 2;
- if (type.startsWith('CONFLICT') && !RESOLVABLE_CONFLICTS.has(type)) for (const p of paths) structural.add(p);
-interface TreeEntry { mode: string; type: string; sha: string }
++/** The git-dir entries a rebase, merge, cherry-pick or revert leaves while it is in progress. */
++export const GIT_OPERATION_MARKERS = ['rebase-merge', 'rebase-apply', 'MERGE_HEAD', 'CHERRY_PICK_HEAD', 'REVERT_HEAD', 'sequencer'] as const;
+
-function treeEntry(root: string, commit: string, path: string): TreeEntry | null {
- for (const line of git(root, ['ls-tree', '-z', commit, '--', ...literalPathspecs([path])]).stdout.split('\0')) {
- const tab = line.indexOf('\t');
- if (tab === -1 || line.slice(tab + 1) !== path) continue;
- const [mode, type, sha] = line.slice(0, tab).split(' ');
- return { mode, type, sha };
++/** Refuse while another git operation is mid-flight; never abort it for the user. */
++export function assertNoOperationInProgress(root: string): void {
++ for (const marker of GIT_OPERATION_MARKERS) {
++ if (existsSync(absGitPath(root, marker))) {
++ throw opError('git_operation_in_progress', `A git ${marker.startsWith('rebase') ? 'rebase' : marker.toLowerCase().replace(/_head$/, '')} is in progress in ${root}.`,
++ `Finish or abort it first. A stuck rebase may hold another writer's autostash: save it with git stash store <sha from .git/${marker}/autostash> before deleting anything. See docs/guides/shared-checkout-git.md#stuck-rebase.`,
++ { detail: marker });
+ }
- return { tree, conflicts: [...conflicts], structural: [...conflicts].filter(p => structural.has(p)) };
}
- const mergeBase = base ?? git(root, ['merge-base', ours, theirs]).stdout.trim();
- if (!mergeBase) throw opError('integrate_conflict', 'The local and remote branches share no history.', 'Reconcile the branches by hand.');
- const dir = mkdtempSync(join(tmpdir(), 'gbrain-integrate-'));
- try {
- const env = { GIT_INDEX_FILE: join(dir, 'index') };
- const read = git(root, ['read-tree', '-m', '-i', '--aggressive', mergeBase, ours, theirs], { env });
- if (read.code !== 0) throw opError('git_unavailable', 'git read-tree failed.', read.stderr.trim().slice(0, 300));
- const unmerged = git(root, ['ls-files', '-u', '-z'], { env }).stdout.split('\0').filter(Boolean);
- if (!unmerged.length) return { tree: gitOk(root, ['write-tree'], 'write-tree', { env }), conflicts: [], structural: [] };
- const conflicts = [...new Set(unmerged.map(l => l.slice(l.indexOf('\t') + 1)))];
- const structural: string[] = [];
- for (const path of conflicts) {
- gitOk(root, ['update-index', '--force-remove', '--', path], 'update-index', { env });
- const mine = unmerged.find(l => l.slice(l.indexOf('\t') + 1) === path && l.split('\t')[0].split(' ')[2] === '2');
- if (!mine) continue;
- const [mode, sha] = mine.split('\t')[0].split(' ');
- if (git(root, ['update-index', '--add', '--cacheinfo', `${mode},${sha},${path}`], { env }).code !== 0) structural.push(path);
- }
- return { tree: gitOk(root, ['write-tree'], 'write-tree', { env }), conflicts, structural };
- } finally {
- rmSync(dir, { recursive: true, force: true });
- return null;
+ }
+
-/** One path's content conflict: a blob (or absent) on every side, no side has it as a directory or under a file. */
-function blobConflict(root: string, base: string, ours: string, theirs: string, path: string): boolean {
- const sides = [base, ours, theirs].map(c => (c ? treeEntry(root, c, path) : null));
- if (sides.every(e => !e) || sides.some(e => e && e.type !== 'blob')) return false;
- const parts = path.split('/');
- for (let k = 1; k < parts.length; k++) {
- const prefix = parts.slice(0, k).join('/');
- if ([ours, theirs].some(c => treeEntry(root, c, prefix)?.type === 'blob')) return false;
- }
- return true;
-}
++// ── Lock ────────────────────────────────────────────────────────────────────
+
-const MAX_SUPERSEDED_HISTORY = 200;
++export interface CommitLock { release(): void; lockPath: string; reentrant: boolean }
+
+ /**
- * Content conflicts where the remote's blob is one this checkout held at the same path and then replaced with
- * another blob (a stale clone or writer brought an old copy back): the remote's version is history this side
- * already moved past, so these resolve to ours. Reads the last MAX_SUPERSEDED_HISTORY commits of `ours` that touch
- * the path. A blob ours never held there, a remote deletion, a structural conflict and a path the caller resolves
- * explicitly stay conflicts.
++ * Take this checkout's commit lock (and the legacy push lock). Re-entrant only
++ * when BRAIN_COMMIT_LOCK_HELD names this exact lock AND the lock is really
++ * held: a stale, spoofed or generic (`1`) marker cannot bypass a lock.
+ */
-function supersededPaths(root: string, ours: string, theirs: string, merged: MergeTree, explicit?: Map<string, Resolution>): string[] {
- const base = git(root, ['merge-base', ours, theirs]).stdout.trim();
- return merged.conflicts.filter(path => {
- if (explicit?.has(path) || merged.structural.includes(path) || path.includes('\n') || !blobConflict(root, base, ours, theirs, path)) return false;
- const remote = treeEntry(root, theirs, path);
- if (!remote) return false;
- const commits = git(root, ['log', '--format=%H', '-n', String(MAX_SUPERSEDED_HISTORY), ours, '--', ...literalPathspecs([path])]).stdout.split('\n').filter(Boolean);
- const blobs = git(root, ['cat-file', '--batch-check=%(objectname) %(objecttype)'], { input: commits.map(c => `${c}:${path}\n`).join('') })
- .stdout.split('\n').slice(0, commits.length).map(line => (line.endsWith(' blob') ? line.split(' ')[0] : null));
- const held = [treeEntry(root, ours, path)?.sha ?? null, ...blobs];
- const at = held.indexOf(remote.sha);
- return at > 0 && held.slice(0, at).some(sha => sha && sha !== remote.sha);
- });
-}
-
-/** Apply `--resolve` choices on top of the merge's placeholder tree; structural conflicts are refused. */
-function resolvedTree(ctx: Ctx, ours: string, theirs: string, merged: MergeTree, resolutions: Map<string, Resolution>, cwd: string): string {
- if (merged.conflicts.some(p => !resolutions.has(p))) throw conflictError(ctx, ours, theirs, merged);
- const base = git(ctx.root, ['merge-base', ours, theirs]).stdout.trim();
- const structural = merged.conflicts.filter(p => merged.structural.includes(p) || !blobConflict(ctx.root, base, ours, theirs, p));
- if (structural.length) throw conflictError(ctx, ours, theirs, { ...merged, structural });
- const dir = mkdtempSync(join(tmpdir(), 'gbrain-resolve-'));
- try {
- const env = { GIT_INDEX_FILE: join(dir, 'index') };
- gitOk(ctx.root, ['read-tree', merged.tree!], 'read-tree', { env });
- for (const path of merged.conflicts) {
- const choice = resolutions.get(path)!;
- if (choice.kind === 'file') {
- const blob = gitOk(ctx.root, ['hash-object', '-w', '--', resolve(cwd, choice.path)], 'hash-object');
- gitOk(ctx.root, ['update-index', '--add', '--cacheinfo', `${treeEntry(ctx.root, ours, path)?.mode ?? '100644'},${blob},${path}`], 'update-index', { env });
- continue;
- }
- const entry = treeEntry(ctx.root, choice.kind === 'ours' ? ours : theirs, path);
- if (entry) gitOk(ctx.root, ['update-index', '--add', '--cacheinfo', `${entry.mode},${entry.sha},${path}`], 'update-index', { env });
- else gitOk(ctx.root, ['update-index', '--force-remove', '--', path], 'update-index', { env });
- }
- return gitOk(ctx.root, ['write-tree'], 'write-tree', { env });
- } finally {
- rmSync(dir, { recursive: true, force: true });
++export function acquireCommitLock(root: string, waitMs = defaultLockWaitMs()): CommitLock {
++ const lockPath = absGitPath(root, COMMIT_LOCK_NAME);
++ const legacyPath = absGitPath(root, LEGACY_PUSH_LOCK_NAME);
++ const marker = process.env[COMMIT_LOCK_ENV];
++ if (marker && marker !== '1' && resolve(marker) === lockPath) {
++ const probe = acquireNativeLockSync(lockPath, { timeoutMs: 0 });
++ if (!probe) return { release() {}, lockPath, reentrant: true };
++ return withLegacy(root, probe, lockPath, legacyPath, waitMs);
}
++ const handle = acquireNativeLockSync(lockPath, { timeoutMs: waitMs });
++ if (!handle) throw lockBusy(lockPath, waitMs);
++ return withLegacy(root, handle, lockPath, legacyPath, waitMs);
+ }
+
-function shellWord(v: string): string {
- return /^[A-Za-z0-9._\/@%+:-]+$/.test(v) ? v : `'${v.replace(/'/g, `'\\''`)}'`;
++function withLegacy(root: string, handle: NativeLockSyncHandle, lockPath: string, legacyPath: string, waitMs: number): CommitLock {
++ let legacy: NativeLockSyncHandle | null;
++ try { legacy = acquireNativeLockSync(legacyPath, { timeoutMs: waitMs }); }
++ catch (e) { handle.release(); throw e; }
++ if (!legacy) { handle.release(); throw lockBusy(legacyPath, waitMs, root); }
++ return { lockPath, reentrant: false, release() { legacy!.release(); handle.release(); } };
+ }
+
-function conflictError(ctx: Ctx, ours: string, theirs: string, merged: MergeTree & { superseded?: string[] }, preface = ''): OperationError {
- const paths = merged.conflicts;
- const local = ours.slice(0, 12);
- const remote = theirs.slice(0, 12);
- const compare = `Compare the two versions (this machine's: git show ${local}:<path>; the remote's: git show ${remote}:<path>)`;
- const fix = merged.structural.length
- ? `${preface}The local commit ${local} stays local and the checkout is unchanged. ${merged.structural.map(shellWord).join(', ')} ${merged.structural.length === 1 ? 'is' : 'are'} a file/directory or rename conflict that a per-file choice cannot resolve. ${compare}, then move or remove the local path in a new commit (gbrain git commit-push -m "<msg>" -- <paths>) and rerun gbrain git commit-push --push-only. See docs/guides/shared-checkout-git.md#conflicts.`
- : `${preface}The local commit ${local} stays local and the checkout is unchanged. ${compare}, then run gbrain git commit-push --push-only${ctx.keepCheckout ? ' --keep-checkout' : ''} --expect-remote ${remote} ${paths.map(p => `--resolve ${shellWord(p)}=ours|theirs`).join(' ')} (ours = this machine's version, theirs = the remote's, or =file:<path> with a merged copy). Until then every push from this checkout reports this conflict. See docs/guides/shared-checkout-git.md#conflicts.`;
- return opError('integrate_conflict', `Local and remote commits both changed ${paths.length} file(s) on ${ctx.branch}; nothing was merged.`, fix,
- { detail: JSON.stringify({ local: ours, remote: theirs, paths, structural: merged.structural, ...(merged.superseded?.length ? { superseded: merged.superseded } : {}) }),
- fix: { ask_user: true, consent: [], actor: 'user', requires_exclusive: false,
- why: 'Choosing which version of a file wins discards the other side; ask the user before resolving.',
- user_message: `Both this machine and the remote changed ${paths.join(', ')}. Which version should win, or should they be merged by hand?`,
- ...(merged.structural.length ? {} : { argv: ['gbrain', 'git', 'commit-push', '--push-only', ...(ctx.keepCheckout ? ['--keep-checkout'] : []), '--path', ctx.root, '--expect-remote', theirs, ...paths.flatMap(p => ['--resolve', `${p}=<ours|theirs>`])] }),
- docs: 'docs/guides/shared-checkout-git.md#conflicts' } });
++/** The same locks for async callers (`gbrain sync`'s pull), without blocking the event loop while waiting. */
++export async function acquireCommitLockAsync(root: string, waitMs = defaultLockWaitMs(), signal?: AbortSignal): Promise<{ release(): Promise<void> }> {
++ const lockPath = absGitPath(root, COMMIT_LOCK_NAME);
++ const legacyPath = absGitPath(root, LEGACY_PUSH_LOCK_NAME);
++ const handle = await acquireNativeLock(lockPath, { timeoutMs: waitMs, signal });
++ if (!handle) throw lockBusy(lockPath, waitMs, root);
++ let legacy;
++ try { legacy = await acquireNativeLock(legacyPath, { timeoutMs: waitMs, signal }); }
++ catch (e) { await handle.release(); throw e; }
++ if (!legacy) { await handle.release(); throw lockBusy(legacyPath, waitMs, root); }
++ return { async release() { await legacy.release(); await handle.release(); } };
}
- const treeOf = (root: string, commit: string) => gitOk(root, ['rev-parse', `${commit}^{tree}`], 'rev-parse tree');
-/** Honors the user's commit signing config, like the `git pull` it replaces. */
-function buildMerge(ctx: Ctx, ours: string, theirs: string, tree: string, skipped: string[] = [], extra: string[] = []): string {
- const remote = `${ctx.remote}/${ctx.mergeRef.replace(/^refs\/heads\//, '')}`;
- const note = skipped.length
- ? ['-m', `Left out ${skipped.length} local commit(s) whose patch ${remote} already has: ${skipped.slice(0, 20).map(s => s.slice(0, 12)).join(' ')}${skipped.length > 20 ? ' ...' : ''}`] : [];
- const sha = gitOk(ctx.root, ['commit-tree', tree, '-p', ours, '-p', theirs, '-m', `gbrain: merge ${remote} into ${ctx.branch}`, ...note, ...extra.flatMap(m => ['-m', m])], 'commit-tree');
- recordCommit(ctx.root, { sha, writer: 'merge', ref: null });
- return sha;
++function defaultLockWaitMs(): number {
++ const raw = process.env.GBRAIN_COMMIT_LOCK_WAIT_SECONDS ?? process.env.GBRAIN_PUSH_LOCK_WAIT_SECONDS;
++ const secs = raw === undefined ? 60 : Number(raw);
++ return Number.isFinite(secs) && secs >= 0 ? secs * 1000 : 60_000;
+ }
- interface Integration extends MergeTree {
- /** Local commits left out because an upstream commit already carries the same patch (`git patch-id`). */
- skipped: string[];
-function fetchTracking(ctx: Ctx): string | null {
- const r = remoteGit(ctx.root, 'fetch', [...fetchFlags(ctx.root), '--', ctx.remote, `+${ctx.mergeRef}:${ctx.trackingRef}`]);
- if (r.code !== 0) return null;
- return git(ctx.root, ['rev-parse', '--verify', '--quiet', ctx.trackingRef]).stdout.trim() || null;
++function lockBusy(lockPath: string, waitMs: number, root?: string): OperationError {
++ return opError('commit_lock_busy', `Another writer held this checkout's commit lock for ${Math.round(waitMs / 1000)}s.`,
++ `Another commit or push is running in ${root ?? 'this checkout'} (lock ${lockPath}). Retry once it finishes; nothing was committed.`,
++ { detail: lockPath, retryable: true });
}
- const MAX_REPLAY = 500;
-function isAncestor(root: string, a: string, b: string): boolean {
- return git(root, ['merge-base', '--is-ancestor', a, b]).code === 0;
-}
++// ── Paths ───────────────────────────────────────────────────────────────────
--/**
- * The tree a publish of `local` over `remote` should carry. A 3-way merge of the two tips
- * counts a local commit whose patch already reached the remote (cherry-picked or rebased there) as a new
- * change again: a remote that edited those lines since conflicts forever, and a remote that reverted it gets
- * the change back silently. So when any local commit is patch-equivalent to an upstream one, the local
- * commits are replayed in memory onto the remote tip instead, oldest first, leaving out the equivalent ones
- * and the clean merges (their content is their parents'). A merge that carries its own resolution, a root
- * commit, or more than MAX_REPLAY commits fall back to the tip merge.
- * #5138: true only when EVERY effective push destination (pushurl and
- * pushInsteadOf expanded) has `sha` on the exact target branch. A URL that git
- * would resolve as another remote alias fails closed, and remote evidence is
- * read live (ls-remote), never from a stale tracking ref or the fetch repo.
-- */
- function integrate(root: string, local: string, remote: string): Integration {
- const commits = git(root, ['rev-list', '--reverse', '--topo-order', '--cherry-mark', '--right-only', '--parents', `${remote}...${local}`])
- .stdout.split('\n').filter(Boolean).map(line => {
- const [head, ...parents] = line.split(' ');
- return { sha: head.slice(1), equivalent: head.startsWith('='), parents };
- });
- const tipMerge = (): Integration => ({ ...mergeTrees(root, local, remote), skipped: [] });
- if (!commits.some(c => c.equivalent) || commits.length > MAX_REPLAY) return tipMerge();
- let acc = remote;
- const conflicts = new Set<string>();
- const structural = new Set<string>();
- const skipped: string[] = [];
- for (const c of commits) {
- if (c.equivalent) { skipped.push(c.sha); continue; }
- if (c.parents.length !== 1) {
- if (c.parents.length !== 2) return tipMerge();
- const own = mergeTrees(root, c.parents[0], c.parents[1]);
- if (own.conflicts.length || own.tree !== treeOf(root, c.sha)) return tipMerge();
- continue;
-function remoteContains(ctx: Ctx, sha: string): boolean {
- const branchRef = ctx.mergeRef;
- if (git(ctx.root, ['check-ref-format', branchRef]).code !== 0) return false;
- const urls = git(ctx.root, ['remote', 'get-url', '--push', '--all', '--', ctx.remote]).stdout.split('\n').map(u => u.trim()).filter(Boolean);
- if (urls.length === 0) return false;
- for (const url of urls) {
- if (git(ctx.root, ['ls-remote', '--get-url', '--', url]).stdout.trim() !== url) return false;
- const listed = git(ctx.root, [...transportFlags(), 'ls-remote', '--exit-code', '--', url, branchRef], { auth: true, timeoutMs: 60_000 });
- if (listed.code !== 0) return false;
- const tip = listed.stdout.split(/\s/)[0];
- if (!/^[0-9a-f]{40,64}$/.test(tip)) return false;
- if (git(ctx.root, ['cat-file', '-e', `${tip}^{commit}`]).code !== 0) {
- const got = git(ctx.root, [...transportFlags(), 'fetch', '--quiet', ...fetchFlags(ctx.root), ...GIT_SSRF_SUBCOMMAND_FLAGS, '--', url, tip], { auth: true, timeoutMs: 120_000 });
- if (got.code !== 0) return false;
++/** Repo-relative paths; refuses the root itself, `.git` and anything outside the checkout. */
++export function scopePaths(root: string, paths: string[], cwd: string): string[] {
++ if (paths.length === 0) {
++ throw opError('commit_paths_invalid', 'No paths to commit.',
++ 'Pass the explicit file(s) you wrote; a repo-wide commit would sweep up other writers\' files.');
++ }
++ const out: string[] = [];
++ for (const p of paths) {
++ const abs = resolve(cwd, p);
++ const rel = relative(root, abs);
++ if (rel === '' || rel === '.' || rel.startsWith('..') || isAbsolute(rel)) {
++ throw opError('commit_paths_invalid', `Path ${p} is ${rel === '' || rel === '.' ? 'the whole checkout' : 'outside the checkout'}.`,
++ 'Pass the explicit file(s) you wrote inside the checkout; a repo-wide commit would sweep up other writers\' files.', { detail: p });
}
- const step = mergeTrees(root, acc, c.sha, c.parents[0]);
- for (const p of step.conflicts) conflicts.add(p);
- for (const p of step.structural) structural.add(p);
- acc = gitOk(root, ['commit-tree', '--no-gpg-sign', step.tree!, '-p', acc, '-m', 'gbrain: replay'], 'commit-tree');
- recordCommit(root, { sha: acc, writer: 'replay', ref: null });
- if (!isAncestor(ctx.root, sha, tip)) return false;
++ if (rel.split(/[\\/]/)[0] === '.git') {
++ throw opError('commit_paths_invalid', `Path ${p} is inside .git.`, 'Pass files in the working tree.', { detail: p });
++ }
++ out.push(rel.split('\\').join('/'));
}
- return { tree: treeOf(root, acc), conflicts: [...conflicts], structural: [...structural], skipped };
- return true;
++ return [...new Set(out)];
}
- interface TreeEntry { mode: string; type: string; sha: string }
-interface Published { sha: string; integrated: number; confirmed: 'push' | 'remote'; quarantined?: QuarantineEntry; superseded?: string[] }
--
- function treeEntry(root: string, commit: string, path: string): TreeEntry | null {
- for (const line of git(root, ['ls-tree', '-z', commit, '--', ...literalPathspecs([path])]).stdout.split('\0')) {
- const tab = line.indexOf('\t');
- if (tab === -1 || line.slice(tab + 1) !== path) continue;
- const [mode, type, sha] = line.slice(0, tab).split(' ');
- return { mode, type, sha };
-// ── Quarantine (opt-in) ─────────────────────────────────────────────────────
-
-const QUARANTINE_LEDGER_NAME = 'brain-quarantine.log';
-export const QUARANTINE_REF_PREFIX = 'refs/gbrain/quarantine/';
-
-export interface QuarantineEntry { ref: string; local: string; remote: string; paths: string[]; at: string }
++/** The checkout's configured source roots (`gbrain.sourceRoot`, toplevel-relative); [''] (the whole checkout) when none is set. */
++export function configuredSourceRoots(root: string): string[] {
++ const roots: string[] = [];
++ for (const raw of git(root, ['config', '--get-all', SOURCE_ROOT_CONFIG]).stdout.split('\n').map(v => v.trim()).filter(Boolean)) {
++ const rel = (isAbsolute(raw) ? relative(root, raw) : raw).split('\\').join('/').replace(/^(\.\/)+/, '').replace(/\/+$/, '');
++ if (rel === '' || rel === '.') return [''];
++ if (!rel.startsWith('..')) roots.push(rel);
+ }
- return null;
++ return roots.length ? [...new Set(roots)] : [''];
+}
- /** One path's content conflict: a blob (or absent) on every side, no side has it as a directory or under a file. */
- function blobConflict(root: string, base: string, ours: string, theirs: string, path: string): boolean {
- const sides = [base, ours, theirs].map(c => (c ? treeEntry(root, c, path) : null));
- if (sides.every(e => !e) || sides.some(e => e && e.type !== 'blob')) return false;
- const parts = path.split('/');
- for (let k = 1; k < parts.length; k++) {
- const prefix = parts.slice(0, k).join('/');
- if ([ours, theirs].some(c => treeEntry(root, c, prefix)?.type === 'blob')) return false;
- }
- return true;
-const quarantineEnabled = (root: string) => git(root, ['config', '--type=bool', '--get', 'gbrain.quarantine']).stdout.trim() === 'true';
++const covers = (spec: string, path: string) => spec === '' || path === spec || path.startsWith(`${spec}/`);
++export const insideSourceRoots = (path: string, roots: string[]) => roots.some(r => covers(r, path));
+
-/** Name the local commit under refs/gbrain/quarantine/ and note which files it parks; the ref keeps it even if history is later rewritten. */
-function parkLocalVersion(root: string, local: string, remote: string, paths: string[]): QuarantineEntry {
- const at = new Date().toISOString();
- const ref = `${QUARANTINE_REF_PREFIX}${at.replace(/[-:]/g, '').replace(/\.\d+Z$/, 'Z')}-${local.slice(0, 12)}`;
- gitOk(root, ['update-ref', ref, local], 'update-ref quarantine');
- const entry = { ref, local, remote, paths, at };
- appendFileSync(absGitPath(root, QUARANTINE_LEDGER_NAME), `${JSON.stringify(entry)}\n`);
- return entry;
++function outsideRootError(root: string, roots: string[], paths: string[], what: string): OperationError {
++ return opError('commit_outside_source_root', `${what} ${paths.slice(0, 10).join(', ')}${paths.length > 10 ? ', ...' : ''}, outside this brain's source root (${roots.join(', ')}).`,
++ `Commit only files under the source root. Files elsewhere in ${root} belong to other projects or writers; commit those with their own tools. Nothing was staged or committed.`,
++ { detail: JSON.stringify({ roots, paths }) });
}
- const MAX_SUPERSEDED_HISTORY = 200;
-/** Parked local versions whose ref still exists (deleting the ref is how the user says they are done with it). */
-export function readQuarantine(repo: string): QuarantineEntry[] {
- try {
- const root = checkoutRoot(repo);
- const p = absGitPath(root, QUARANTINE_LEDGER_NAME);
- if (!existsSync(p)) return [];
- const live = new Set(git(root, ['for-each-ref', '--format=%(refname)', QUARANTINE_REF_PREFIX]).stdout.split('\n').filter(Boolean));
- return readFileSync(p, 'utf8').split('\n').flatMap(line => {
- try { const e = JSON.parse(line) as QuarantineEntry; return live.has(e.ref) ? [e] : []; } catch { return []; }
- });
- } catch {
- return [];
- }
++// ── Commit ──────────────────────────────────────────────────────────────────
+
- /**
- * Content conflicts where the remote's blob is one this checkout held at the same path and then replaced with
- * another blob (a stale clone or writer brought an old copy back): the remote's version is history this side
- * already moved past, so these resolve to ours. Reads the last MAX_SUPERSEDED_HISTORY commits of `ours` that touch
- * the path. A blob ours never held there, a remote deletion, a structural conflict and a path the caller resolves
- * explicitly stay conflicts.
- */
- function supersededPaths(root: string, ours: string, theirs: string, merged: MergeTree, explicit?: Map<string, Resolution>): string[] {
- const base = git(root, ['merge-base', ours, theirs]).stdout.trim();
- return merged.conflicts.filter(path => {
- if (explicit?.has(path) || merged.structural.includes(path) || path.includes('\n') || !blobConflict(root, base, ours, theirs, path)) return false;
- const remote = treeEntry(root, theirs, path);
- if (!remote) return false;
- const commits = git(root, ['log', '--format=%H', '-n', String(MAX_SUPERSEDED_HISTORY), ours, '--', ...literalPathspecs([path])]).stdout.split('\n').filter(Boolean);
- const blobs = git(root, ['cat-file', '--batch-check=%(objectname) %(objecttype)'], { input: commits.map(c => `${c}:${path}\n`).join('') })
- .stdout.split('\n').slice(0, commits.length).map(line => (line.endsWith(' blob') ? line.split(' ')[0] : null));
- const held = [treeEntry(root, ours, path)?.sha ?? null, ...blobs];
- const at = held.indexOf(remote.sha);
- return at > 0 && held.slice(0, at).some(sha => sha && sha !== remote.sha);
- });
++function indexLocked(r: GitRun): boolean {
++ return /index\.lock': File exists|Unable to create '.*index\.lock'/.test(r.stderr);
}
- /** Apply `--resolve` choices on top of the merge's placeholder tree; structural conflicts are refused. */
- function resolvedTree(ctx: Ctx, ours: string, theirs: string, merged: MergeTree, resolutions: Map<string, Resolution>, cwd: string): string {
- if (merged.conflicts.some(p => !resolutions.has(p))) throw conflictError(ctx, ours, theirs, merged);
- const base = git(ctx.root, ['merge-base', ours, theirs]).stdout.trim();
- const structural = merged.conflicts.filter(p => merged.structural.includes(p) || !blobConflict(ctx.root, base, ours, theirs, p));
- if (structural.length) throw conflictError(ctx, ours, theirs, { ...merged, structural });
- const dir = mkdtempSync(join(tmpdir(), 'gbrain-resolve-'));
- try {
- const env = { GIT_INDEX_FILE: join(dir, 'index') };
- gitOk(ctx.root, ['read-tree', merged.tree!], 'read-tree', { env });
- for (const path of merged.conflicts) {
- const choice = resolutions.get(path)!;
- if (choice.kind === 'file') {
- const blob = gitOk(ctx.root, ['hash-object', '-w', '--', resolve(cwd, choice.path)], 'hash-object');
- gitOk(ctx.root, ['update-index', '--add', '--cacheinfo', `${treeEntry(ctx.root, ours, path)?.mode ?? '100644'},${blob},${path}`], 'update-index', { env });
-/**
- * Push `start` (an immutable sha), merging remote commits in memory as needed.
- * When the remote already holds the candidate, the published tip (which may be
- * a merge built over it earlier) is returned so a lagging checkout catches up.
- */
-function publish(ctx: Ctx, start: string, resolutions: Map<string, Resolution> | undefined, expectRemote: string | undefined, cwd: string): Published {
- const bound = expectRemote && !resolutions?.size ? gitOk(ctx.root, ['rev-parse', '--verify', `${expectRemote}^{commit}`], 'rev-parse --expect-remote') : undefined;
- let candidate = start;
- let integrated = 0;
- let lastError = '';
- let stalled = 0;
- let quarantined: QuarantineEntry | undefined;
- const superseded = new Set<string>();
- const notes = () => ({ ...(quarantined ? { quarantined } : {}), ...(superseded.size ? { superseded: [...superseded] } : {}) });
- const onRemote = (): Published => {
- const tip = fetchTracking(ctx);
- return { sha: tip && isAncestor(ctx.root, candidate, tip) ? tip : candidate, integrated, confirmed: 'remote', ...notes() };
- };
- for (let attempt = 0; attempt < MAX_PUSH_ATTEMPTS; attempt++) {
- if (attempt) Atomics.wait(sleeper, 0, 0, Math.min(2000, 50 * 2 ** attempt) + Math.floor(Math.random() * 100));
- let remoteTip = bound && !isAncestor(ctx.root, bound, candidate) ? bound : null;
- if (!remoteTip) {
- const push = remoteGit(ctx.root, 'push', [...(ctx.keepCheckout ? ['--no-verify'] : []), ...(bound ? [`--force-with-lease=${ctx.mergeRef}:${bound}`] : []), '--', ctx.remote, `${candidate}:${ctx.mergeRef}`]);
- if (push.code === 0) return { sha: candidate, integrated, confirmed: 'push', ...notes() };
- lastError = push.stderr.trim();
- if (remoteContains(ctx, candidate)) return onRemote();
- remoteTip = fetchTracking(ctx);
- if (!remoteTip) break;
- if (bound && remoteTip !== bound) {
- throw opError('push_unconfirmed', `The remote moved to ${remoteTip.slice(0, 12)} after --expect-remote ${bound.slice(0, 12)} was checked, so nothing was pushed: publishing now could merge back commits a rewrite removed.`,
- 'Check the remote history first (gbrain sources refresh checks it for a force-push), then rerun.', { detail: candidate, retryable: true });
- }
- if (isAncestor(ctx.root, remoteTip, candidate)) {
- if (++stalled > 1) break;
-- continue;
- }
- }
- const raw = integrate(ctx.root, candidate, remoteTip);
- const kept = supersededPaths(ctx.root, candidate, remoteTip, raw, resolutions);
- const merged = kept.length
- ? { ...raw, superseded: kept, conflicts: raw.conflicts.filter(p => !kept.includes(p)),
- tree: resolvedTree(ctx, candidate, remoteTip, { ...raw, conflicts: kept }, new Map(kept.map(p => [p, { kind: 'ours' } as Resolution])), cwd) }
- : raw;
- let tree = merged.tree!;
- let mergeNotes: string[] = kept.length
- ? [`Kept this machine's version of ${kept.length} file(s) where the remote held a version this checkout had already replaced: ${kept.slice(0, 20).join(', ')}${kept.length > 20 ? ', ...' : ''}`] : [];
- if (merged.conflicts.length && !resolutions?.size && !merged.structural.length && quarantineEnabled(ctx.root)) {
- tree = resolvedTree(ctx, candidate, remoteTip, merged, new Map(merged.conflicts.map(p => [p, { kind: 'theirs' } as Resolution])), cwd);
- quarantined = parkLocalVersion(ctx.root, candidate, remoteTip, merged.conflicts);
- mergeNotes = [...mergeNotes, `Quarantined this machine's version of ${merged.conflicts.length} conflicting file(s) under ${quarantined.ref}: ${merged.conflicts.slice(0, 20).join(', ')}`];
- } else if (merged.conflicts.length) {
- if (!resolutions?.size) throw conflictError(ctx, candidate, remoteTip, merged);
- if (!expectRemote || !remoteTip.startsWith(expectRemote.toLowerCase())) {
- throw conflictError(ctx, candidate, remoteTip, merged,
- `The remote moved to ${remoteTip.slice(0, 12)}${expectRemote ? ` after the choice was made against ${expectRemote.slice(0, 12)}` : ''}; review the remote's current version before choosing. `);
++/** Run an index-writing git command; a lockless git holding index.lock gets a bounded, jittered retry. */
++function withIndexRetry(root: string, args: string[], what: string, env?: NodeJS.ProcessEnv, input?: string): GitRun {
++ for (let attempt = 0; ; attempt++) {
++ const r = git(root, args, { env, timeoutMs: 120_000, input });
++ if (r.code === 0 || !indexLocked(r)) return r;
++ if (attempt >= INDEX_LOCK_RETRIES) {
++ const lock = absGitPath(root, 'index.lock');
++ let ageMs = 0;
++ try { ageMs = Date.now() - statSync(lock).mtimeMs; } catch { /* gone */ }
++ if (ageMs > 10 * 60_000) {
++ throw opError('git_index_stale', `A Git index lock older than 10 minutes blocks ${root}: ${lock}.`,
++ `If no git command is running in that checkout, remove ${lock}, then rerun. Nothing was committed.`, { detail: lock });
}
- const entry = treeEntry(ctx.root, choice.kind === 'ours' ? ours : theirs, path);
- if (entry) gitOk(ctx.root, ['update-index', '--add', '--cacheinfo', `${entry.mode},${entry.sha},${path}`], 'update-index', { env });
- else gitOk(ctx.root, ['update-index', '--force-remove', '--', path], 'update-index', { env });
- tree = resolvedTree(ctx, candidate, remoteTip, merged, resolutions, cwd);
++ throw opError('git_index_locked', `Another git process kept ${root}'s index locked during ${what}.`,
++ 'A git command that does not take the commit lock is running in this checkout. Retry shortly; nothing was committed.', { detail: lock, retryable: true });
}
- return gitOk(ctx.root, ['write-tree'], 'write-tree', { env });
- } finally {
- rmSync(dir, { recursive: true, force: true });
- integrated += Number(git(ctx.root, ['rev-list', '--count', `${candidate}..${remoteTip}`]).stdout.trim() || 0);
- candidate = buildMerge(ctx, candidate, remoteTip, tree, merged.skipped, mergeNotes);
- for (const p of kept) superseded.add(p);
- }
- if (remoteContains(ctx, candidate)) return onRemote();
- throw opError('push_unconfirmed', `The commit is durable locally but no push to ${ctx.remote}/${ctx.mergeRef.replace(/^refs\/heads\//, '')} was confirmed.`,
- `git push failed (network, credentials, branch protection, or a remote that kept moving): ${lastError.slice(0, 500) || 'no detail'}. Rerun gbrain git commit-push --push-only once the remote is reachable; never git pull --rebase in this checkout.`,
- { detail: candidate, retryable: true });
-}
-
-/** Non-merge commits in `target` but not in `upstream` (at most 200) that change files outside `roots`; null when git cannot list them. */
-export function localCommitsOutsideRoots(root: string, target: string, upstream: string, roots: string[]): Array<{ sha: string; paths: string[] }> | null {
- if (roots.includes('')) return [];
- const local = git(root, ['rev-list', '--no-merges', '--max-count=200', target, '--not', upstream]);
- if (local.code !== 0) return null;
- const offending: Array<{ sha: string; paths: string[] }> = [];
- for (const sha of local.stdout.split('\n').filter(Boolean)) {
- const paths = git(root, ['diff-tree', '--no-commit-id', '--name-only', '--no-renames', '-r', '-z', '--root', sha]).stdout.split('\0').filter(p => p && !insideSourceRoots(p, roots));
- if (paths.length) offending.push({ sha, paths });
++ Atomics.wait(sleeper, 0, 0, 100 * 2 ** attempt + Math.floor(Math.random() * 100));
}
- return offending;
}
- function shellWord(v: string): string {
- return /^[A-Za-z0-9._\/@%+:-]+$/.test(v) ? v : `'${v.replace(/'/g, `'\\''`)}'`;
-/**
- * Refuse to publish a local commit that changes files outside the configured source root(s). In a shared
- * checkout a commit made without paths (a cron's `git add <dir>; git commit`) carries whatever any writer
- * had staged; the source-root config is how a brain inside a larger repository says which files are its own.
- * Merge commits are not judged (gbrain's in-memory merges bring remote files in). With no root configured
- * the whole checkout is the root and nothing is refused.
- */
-function assertLocalCommitsInsideRoots(ctx: Ctx, target: string, roots: string[]): void {
- const offending = localCommitsOutsideRoots(ctx.root, target, ctx.trackingRef, roots) ?? [];
- if (!offending.length) return;
- const files = [...new Set(offending.flatMap(o => o.paths))];
- const shas = offending.map(o => o.sha.slice(0, 12)).join(', ');
- throw opError('commit_outside_source_root', `${offending.length} local commit(s) (${shas}) change ${files.length} file(s) outside this brain's source root (${roots.join(', ')}): ${files.slice(0, 10).join(', ')}${files.length > 10 ? ', ...' : ''}. Nothing was pushed.`,
- `A commit made without gbrain git commit-push (for example a cron's git add plus git commit) can carry files other writers had staged. Show the user git show --stat ${offending[0].sha.slice(0, 12)}; if they want it published as is, rerun with --allow-outside-source-root. See docs/guides/shared-checkout-git.md#source-roots.`,
- { detail: JSON.stringify({ roots, commits: offending }),
- fix: { ask_user: true, consent: [], actor: 'user', requires_exclusive: false,
- argv: ['gbrain', 'git', 'commit-push', '--push-only', '--allow-outside-source-root', '--path', ctx.root],
- why: 'These commits change files that are not the brain\'s; publishing them can overwrite other projects\' or writers\' work on the remote.',
- user_message: `Local commit(s) ${shas} change files outside the brain's folder (${files.slice(0, 5).join(', ')}${files.length > 5 ? ', ...' : ''}). Publish them anyway?`,
- docs: 'docs/guides/shared-checkout-git.md#source-roots' } });
--}
--
- function conflictError(ctx: Ctx, ours: string, theirs: string, merged: MergeTree & { superseded?: string[] }, preface = ''): OperationError {
- const paths = merged.conflicts;
- const local = ours.slice(0, 12);
- const remote = theirs.slice(0, 12);
- const compare = `Compare the two versions (this machine's: git show ${local}:<path>; the remote's: git show ${remote}:<path>)`;
- const fix = merged.structural.length
- ? `${preface}The local commit ${local} stays local and the checkout is unchanged. ${merged.structural.map(shellWord).join(', ')} ${merged.structural.length === 1 ? 'is' : 'are'} a file/directory or rename conflict that a per-file choice cannot resolve. ${compare}, then move or remove the local path in a new commit (gbrain git commit-push -m "<msg>" -- <paths>) and rerun gbrain git commit-push --push-only. See docs/guides/shared-checkout-git.md#conflicts.`
- : `${preface}The local commit ${local} stays local and the checkout is unchanged. ${compare}, then run gbrain git commit-push --push-only${ctx.keepCheckout ? ' --keep-checkout' : ''} --expect-remote ${remote} ${paths.map(p => `--resolve ${shellWord(p)}=ours|theirs`).join(' ')} (ours = this machine's version, theirs = the remote's, or =file:<path> with a merged copy). Until then every push from this checkout reports this conflict. See docs/guides/shared-checkout-git.md#conflicts.`;
- return opError('integrate_conflict', `Local and remote commits both changed ${paths.length} file(s) on ${ctx.branch}; nothing was merged.`, fix,
- { detail: JSON.stringify({ local: ours, remote: theirs, paths, structural: merged.structural, ...(merged.superseded?.length ? { superseded: merged.superseded } : {}) }),
-/** The automatic-publish secret gate: scan what the commits in trackingRef..target add (the exact range this publish pushes, under its lock). */
-function assertNoSecretsInRange(ctx: Ctx, target: string): void {
- const scan = scanRange(ctx.root, ctx.trackingRef, target);
- if (scan.unreadable !== undefined) {
- throw opError('publish_scan_unreadable', `The secret scan could not read the local commits ${ctx.trackingRef}..${target.slice(0, 12)} (${scan.unreadable}). No secret was reported. Nothing was pushed.`,
- `The publish pushes only commits it has read in full. Check the checkout with git fsck in ${ctx.root} (a missing or corrupt object, a full disk, or a git too slow for the 300 s budget), fix what it reports, then retry. Never publish with a command that skips this scan.`,
- { detail: JSON.stringify({ unreadable: scan.unreadable }), fix: { ask_user: true, consent: [], actor: 'user', requires_exclusive: false,
- argv: ['git', '-C', ctx.root, 'fsck'],
- why: 'Read-only: names missing or corrupt objects in the unpublished commits, the usual reason the scan cannot read them.',
- user_message: `The secret scan could not read the unpublished commits in ${ctx.root}, so nothing was pushed. Check the checkout with git fsck and fix what it reports?`,
- docs: 'docs/guides/shared-checkout-git.md#publish_scan_unreadable' } });
- }
- if (!scan.findings.length && !scan.unscanned.length && !scan.gate_changes.length) return;
- const named = [...scan.findings.map(f => `${f.path}:${f.line} (${f.pattern}, ${f.commit.slice(0, 7)})`), ...scan.unscanned.map(u => `${u.path} (too large to scan, ${u.commit.slice(0, 7)})`),
- ...scan.gate_changes.map(g => `${g.path} (changes what the scan sees, ${g.commit.slice(0, 7)})`)];
- throw opError('publish_secret_found',
- `${named.length} item(s) in the local commits ${ctx.trackingRef}..${target.slice(0, 12)} look like secrets or could not be scanned: ${named.slice(0, 10).join(', ')}${named.length > 10 ? ', ...' : ''}. Nothing was pushed.`,
- 'Remove the value from those commits (rewriting unpushed local commits is the user\'s call), or add a false positive\'s fingerprint to .gbrain-scan-allow, then retry. Never publish them with a command that skips this scan.',
- { detail: JSON.stringify(scan),
-- fix: { ask_user: true, consent: [], actor: 'user', requires_exclusive: false,
- why: 'Choosing which version of a file wins discards the other side; ask the user before resolving.',
- user_message: `Both this machine and the remote changed ${paths.join(', ')}. Which version should win, or should they be merged by hand?`,
- ...(merged.structural.length ? {} : { argv: ['gbrain', 'git', 'commit-push', '--push-only', ...(ctx.keepCheckout ? ['--keep-checkout'] : []), '--path', ctx.root, '--expect-remote', theirs, ...paths.flatMap(p => ['--resolve', `${p}=<ours|theirs>`])] }),
- docs: 'docs/guides/shared-checkout-git.md#conflicts' } });
- argv: ['git', '-C', ctx.root, 'log', '--stat', `${ctx.trackingRef}..${target}`],
- why: 'Lists the unpublished commits the scan refused; read-only. A secret pushed to the remote stays in its history.',
- user_message: `Unpublished commits in ${ctx.root} hold ${named.length || 'some'} item(s) that look like secrets or could not be scanned (${named.slice(0, 3).join(', ')}). Nothing was pushed. Remove them from those commits, or confirm a false positive so it can be allowlisted by fingerprint?`,
- docs: 'docs/guides/shared-checkout-git.md#publish_secret_found' } });
--}
--
- /** Honors the user's commit signing config, like the `git pull` it replaces. */
- function buildMerge(ctx: Ctx, ours: string, theirs: string, tree: string, skipped: string[] = [], extra: string[] = []): string {
- const remote = `${ctx.remote}/${ctx.mergeRef.replace(/^refs\/heads\//, '')}`;
- const note = skipped.length
- ? ['-m', `Left out ${skipped.length} local commit(s) whose patch ${remote} already has: ${skipped.slice(0, 20).map(s => s.slice(0, 12)).join(' ')}${skipped.length > 20 ? ' ...' : ''}`] : [];
- const sha = gitOk(ctx.root, ['commit-tree', tree, '-p', ours, '-p', theirs, '-m', `gbrain: merge ${remote} into ${ctx.branch}`, ...note, ...extra.flatMap(m => ['-m', m])], 'commit-tree');
- recordCommit(ctx.root, { sha, writer: 'merge', ref: null });
- return sha;
-/** Advance the shared checkout (caller holds the commit lock) with a real compare-and-swap: fast-forward only, hooks off, never autostash. */
-function advanceLocked(root: string, target: string, expectedHead: string): { checkout: CheckoutState; reason?: string } {
- const head = git(root, ['rev-parse', 'HEAD']).stdout.trim();
- if (head === target || isAncestor(root, target, head)) return { checkout: 'unchanged' };
- if (head !== expectedHead) {
- return { checkout: 'lagging', reason: isAncestor(root, expectedHead, head)
- ? `a newer local commit (${head.slice(0, 12)}) landed during the push; publishing it advances the checkout`
- : `HEAD moved to ${head.slice(0, 12)} during the push (a writer that did not take the commit lock)` };
- }
- if (!isAncestor(root, head, target)) return { checkout: 'lagging', reason: `HEAD ${head.slice(0, 12)} is not part of the published history (it was rewritten locally)` };
- const r = withIndexRetry(root, ['-c', 'core.hooksPath=/dev/null', '-c', 'merge.autoStash=false', 'merge', '--ff-only', '--quiet', target], 'checkout advance');
- if (r.code === 0) return { checkout: 'advanced' };
- const dirty = [...r.stderr.matchAll(/^\t(.+)$/gm)].map(m => m[1]);
- if (dirty.length) return { checkout: 'lagging', reason: `local edits in ${dirty.join(', ')} block the fast-forward` };
- throw opError('git_unavailable', `git could not fast-forward ${root} to ${target.slice(0, 12)}.`,
- `${r.stderr.trim().slice(0, 300) || `exit ${r.code}`}. Nothing in the working tree changed; run gbrain git commit-push --pull once git works in this checkout.`, { detail: target });
-}
-
-function advanceWithLock(root: string, target: string, expectedHead: string, onlyWhenClean: boolean, lockWaitMs?: number): { checkout: CheckoutState; reason?: string } {
- let lock: CommitLock;
- try { lock = acquireCommitLock(root, lockWaitMs); } catch (e) {
- if ((e as { code?: string }).code !== 'commit_lock_busy') throw e;
- return { checkout: 'lagging', reason: 'another writer held the commit lock; the next publish or --pull advances the checkout' };
- }
- try {
- if (onlyWhenClean && git(root, ['status', '--porcelain']).stdout.trim()) {
- return { checkout: 'lagging', reason: 'the checkout has local edits and this unattended run never moves files under them' };
- }
- return advanceLocked(root, target, expectedHead);
- } finally {
- lock.release();
++/** A staged rename (`git mv`) commits both sides: committing only the new name would publish a duplicate and leave the deletion staged for another writer's commit. */
++function withRenamePartners(root: string, rel: string[]): string[] {
++ const fields = git(root, ['diff', '--cached', '-M', '--name-status', '-z']).stdout.split('\0');
++ const out = new Set(rel);
++ for (let i = 0; i < fields.length;) {
++ const status = fields[i];
++ if (!status) break;
++ if (/^[RC]/.test(status)) {
++ const [from, to] = [fields[i + 1], fields[i + 2]];
++ if (status.startsWith('R') && (out.has(from) || out.has(to))) { out.add(from); out.add(to); }
++ i += 3;
++ } else i += 2;
+ }
++ return [...out];
}
- function fetchTracking(ctx: Ctx): string | null {
- const r = remoteGit(ctx.root, 'fetch', [...fetchFlags(ctx.root), '--', ctx.remote, `+${ctx.mergeRef}:${ctx.trackingRef}`]);
- if (r.code !== 0) return null;
- return git(ctx.root, ['rev-parse', '--verify', '--quiet', ctx.trackingRef]).stdout.trim() || null;
-// ── Conflict state (doctor / put_page read it) ──────────────────────────────
-
-export interface IntegrateConflictState { branch: string; at: string; local: string; remote: string; paths: string[] }
++/** Index entries that differ from HEAD, whoever staged them, with rename detection off so both sides of a rename are listed. */
++function stagedPaths(root: string): string[] {
++ return git(root, ['diff', '--cached', '--no-renames', '--name-only', '-z']).stdout.split('\0').filter(Boolean);
+}
- function isAncestor(root: string, a: string, b: string): boolean {
- return git(root, ['merge-base', '--is-ancestor', a, b]).code === 0;
-/** The unresolved integrate_conflict recorded for this checkout, if any. */
-export function readIntegrateConflict(repo: string): IntegrateConflictState | null {
- try {
- const root = checkoutRoot(repo);
- const p = absGitPath(root, CONFLICT_STATE_NAME);
- return existsSync(p) ? JSON.parse(readFileSync(p, 'utf8')) as IntegrateConflictState : null;
- } catch {
- return null;
- }
++/** The index entries under `rel` as `ls-files -s` records, so a failed commit can put them back exactly. */
++function indexEntries(root: string, rel: string[]): string[] {
++ return git(root, ['ls-files', '-s', '-z', '--', ...literalPathspecs(rel)]).stdout.split('\0').filter(Boolean);
}
-function recordConflict(root: string, branch: string, e: unknown): void {
- try {
- const d = JSON.parse(String((e as { detail?: string }).detail ?? '{}'));
- writeFileSync(absGitPath(root, CONFLICT_STATE_NAME), JSON.stringify({ branch, at: new Date().toISOString(), local: d.local, remote: d.remote, paths: d.paths ?? [] }));
- } catch { /* best-effort */ }
+/**
- * #5138: true only when EVERY effective push destination (pushurl and
- * pushInsteadOf expanded) has `sha` on the exact target branch. A URL that git
- * would resolve as another remote alias fails closed, and remote evidence is
- * read live (ls-remote), never from a stale tracking ref or the fetch repo.
++ * Put the index under `rel` back to `before` after a commit that did not land:
++ * `git add` already staged the paths, and an entry left staged in the shared
++ * index is what the next writer's commit without paths sweeps up.
+ */
- function remoteContains(ctx: Ctx, sha: string): boolean {
- const branchRef = ctx.mergeRef;
- if (git(ctx.root, ['check-ref-format', branchRef]).code !== 0) return false;
- const urls = git(ctx.root, ['remote', 'get-url', '--push', '--all', '--', ctx.remote]).stdout.split('\n').map(u => u.trim()).filter(Boolean);
- if (urls.length === 0) return false;
- for (const url of urls) {
- if (git(ctx.root, ['ls-remote', '--get-url', '--', url]).stdout.trim() !== url) return false;
- const listed = git(ctx.root, [...transportFlags(), 'ls-remote', '--exit-code', '--', url, branchRef], { auth: true, timeoutMs: 60_000 });
- if (listed.code !== 0) return false;
- const tip = listed.stdout.split(/\s/)[0];
- if (!/^[0-9a-f]{40,64}$/.test(tip)) return false;
- if (git(ctx.root, ['cat-file', '-e', `${tip}^{commit}`]).code !== 0) {
- const got = git(ctx.root, [...transportFlags(), 'fetch', '--quiet', ...fetchFlags(ctx.root), ...GIT_SSRF_SUBCOMMAND_FLAGS, '--', url, tip], { auth: true, timeoutMs: 120_000 });
- if (got.code !== 0) return false;
- }
- if (!isAncestor(ctx.root, sha, tip)) return false;
- }
- return true;
++function restoreIndex(root: string, rel: string[], before: string[]): void {
++ const pathOf = (line: string) => line.slice(line.indexOf('\t') + 1);
++ const kept = new Set(before.map(pathOf));
++ const zero = '0'.repeat(git(root, ['rev-parse', 'HEAD']).stdout.trim().length || 40);
++ const records = [...indexEntries(root, rel).map(pathOf).filter(p => !kept.has(p)).map(p => `0 ${zero}\t${p}`), ...before];
++ if (records.length) withIndexRetry(root, ['update-index', '-z', '--index-info'], 'index restore', undefined, records.map(l => `${l}\0`).join(''));
}
- interface Published { sha: string; integrated: number; confirmed: 'push' | 'remote'; quarantined?: QuarantineEntry; superseded?: string[] }
-
- // ── Quarantine (opt-in) ─────────────────────────────────────────────────────
-
- const QUARANTINE_LEDGER_NAME = 'brain-quarantine.log';
- export const QUARANTINE_REF_PREFIX = 'refs/gbrain/quarantine/';
-
- export interface QuarantineEntry { ref: string; local: string; remote: string; paths: string[]; at: string }
-
- const quarantineEnabled = (root: string) => git(root, ['config', '--type=bool', '--get', 'gbrain.quarantine']).stdout.trim() === 'true';
-
- /** Name the local commit under refs/gbrain/quarantine/ and note which files it parks; the ref keeps it even if history is later rewritten. */
- function parkLocalVersion(root: string, local: string, remote: string, paths: string[]): QuarantineEntry {
- const at = new Date().toISOString();
- const ref = `${QUARANTINE_REF_PREFIX}${at.replace(/[-:]/g, '').replace(/\.\d+Z$/, 'Z')}-${local.slice(0, 12)}`;
- gitOk(root, ['update-ref', ref, local], 'update-ref quarantine');
- const entry = { ref, local, remote, paths, at };
- appendFileSync(absGitPath(root, QUARANTINE_LEDGER_NAME), `${JSON.stringify(entry)}\n`);
- return entry;
- }
-// ── Public entry points ─────────────────────────────────────────────────────
++interface CommitScope { roots: string[]; lockPath: string; markHeld: boolean; bases?: ReadonlyMap<string, string> }
- /** Parked local versions whose ref still exists (deleting the ref is how the user says they are done with it). */
- export function readQuarantine(repo: string): QuarantineEntry[] {
- try {
- const root = checkoutRoot(repo);
- const p = absGitPath(root, QUARANTINE_LEDGER_NAME);
- if (!existsSync(p)) return [];
- const live = new Set(git(root, ['for-each-ref', '--format=%(refname)', QUARANTINE_REF_PREFIX]).stdout.split('\n').filter(Boolean));
- return readFileSync(p, 'utf8').split('\n').flatMap(line => {
- try { const e = JSON.parse(line) as QuarantineEntry; return live.has(e.ref) ? [e] : []; } catch { return []; }
- });
- } catch {
- return [];
- }
- }
-function defaultPublishWaitMs(): number {
- const raw = process.env.GBRAIN_PUBLISH_LOCK_WAIT_SECONDS ?? process.env.GBRAIN_PUSH_LOCK_WAIT_SECONDS;
- const secs = raw === undefined ? 300 : Number(raw);
- return Number.isFinite(secs) && secs >= 0 ? secs * 1000 : 300_000;
++/** A named path `git add -A` left out of the index while still exiting 0 (GST-2116). */
++export interface SkippedPath { path: string; reason: 'assume_unchanged' | 'skip_worktree' | 'not_staged' }
+
- /**
- * Push `start` (an immutable sha), merging remote commits in memory as needed.
- * When the remote already holds the candidate, the published tip (which may be
- * a merge built over it earlier) is returned so a lagging checkout catches up.
- */
- function publish(ctx: Ctx, start: string, resolutions: Map<string, Resolution> | undefined, expectRemote: string | undefined, cwd: string): Published {
- const bound = expectRemote && !resolutions?.size ? gitOk(ctx.root, ['rev-parse', '--verify', `${expectRemote}^{commit}`], 'rev-parse --expect-remote') : undefined;
- let candidate = start;
- let integrated = 0;
- let lastError = '';
- let stalled = 0;
- let quarantined: QuarantineEntry | undefined;
- const superseded = new Set<string>();
- const notes = () => ({ ...(quarantined ? { quarantined } : {}), ...(superseded.size ? { superseded: [...superseded] } : {}) });
- const onRemote = (): Published => {
- const tip = fetchTracking(ctx);
- return { sha: tip && isAncestor(ctx.root, candidate, tip) ? tip : candidate, integrated, confirmed: 'remote', ...notes() };
- };
- for (let attempt = 0; attempt < MAX_PUSH_ATTEMPTS; attempt++) {
- if (attempt) Atomics.wait(sleeper, 0, 0, Math.min(2000, 50 * 2 ** attempt) + Math.floor(Math.random() * 100));
- let remoteTip = bound && !isAncestor(ctx.root, bound, candidate) ? bound : null;
- if (!remoteTip) {
- const push = remoteGit(ctx.root, 'push', [...(ctx.keepCheckout ? ['--no-verify'] : []), ...(bound ? [`--force-with-lease=${ctx.mergeRef}:${bound}`] : []), '--', ctx.remote, `${candidate}:${ctx.mergeRef}`]);
- if (push.code === 0) return { sha: candidate, integrated, confirmed: 'push', ...notes() };
- lastError = push.stderr.trim();
- if (remoteContains(ctx, candidate)) return onRemote();
- remoteTip = fetchTracking(ctx);
- if (!remoteTip) break;
- if (bound && remoteTip !== bound) {
- throw opError('push_unconfirmed', `The remote moved to ${remoteTip.slice(0, 12)} after --expect-remote ${bound.slice(0, 12)} was checked, so nothing was pushed: publishing now could merge back commits a rewrite removed.`,
- 'Check the remote history first (gbrain sources refresh checks it for a force-push), then rerun.', { detail: candidate, retryable: true });
- }
- if (isAncestor(ctx.root, remoteTip, candidate)) {
- if (++stalled > 1) break;
- continue;
- }
- }
- const raw = integrate(ctx.root, candidate, remoteTip);
- const kept = supersededPaths(ctx.root, candidate, remoteTip, raw, resolutions);
- const merged = kept.length
- ? { ...raw, superseded: kept, conflicts: raw.conflicts.filter(p => !kept.includes(p)),
- tree: resolvedTree(ctx, candidate, remoteTip, { ...raw, conflicts: kept }, new Map(kept.map(p => [p, { kind: 'ours' } as Resolution])), cwd) }
- : raw;
- let tree = merged.tree!;
- let mergeNotes: string[] = kept.length
- ? [`Kept this machine's version of ${kept.length} file(s) where the remote held a version this checkout had already replaced: ${kept.slice(0, 20).join(', ')}${kept.length > 20 ? ', ...' : ''}`] : [];
- if (merged.conflicts.length && !resolutions?.size && !merged.structural.length && quarantineEnabled(ctx.root)) {
- tree = resolvedTree(ctx, candidate, remoteTip, merged, new Map(merged.conflicts.map(p => [p, { kind: 'theirs' } as Resolution])), cwd);
- quarantined = parkLocalVersion(ctx.root, candidate, remoteTip, merged.conflicts);
- mergeNotes = [...mergeNotes, `Quarantined this machine's version of ${merged.conflicts.length} conflicting file(s) under ${quarantined.ref}: ${merged.conflicts.slice(0, 20).join(', ')}`];
- } else if (merged.conflicts.length) {
- if (!resolutions?.size) throw conflictError(ctx, candidate, remoteTip, merged);
- if (!expectRemote || !remoteTip.startsWith(expectRemote.toLowerCase())) {
- throw conflictError(ctx, candidate, remoteTip, merged,
- `The remote moved to ${remoteTip.slice(0, 12)}${expectRemote ? ` after the choice was made against ${expectRemote.slice(0, 12)}` : ''}; review the remote's current version before choosing. `);
- }
- tree = resolvedTree(ctx, candidate, remoteTip, merged, resolutions, cwd);
- }
- integrated += Number(git(ctx.root, ['rev-list', '--count', `${candidate}..${remoteTip}`]).stdout.trim() || 0);
- candidate = buildMerge(ctx, candidate, remoteTip, tree, merged.skipped, mergeNotes);
- for (const p of kept) superseded.add(p);
- }
- if (remoteContains(ctx, candidate)) return onRemote();
- throw opError('push_unconfirmed', `The commit is durable locally but no push to ${ctx.remote}/${ctx.mergeRef.replace(/^refs\/heads\//, '')} was confirmed.`,
- `git push failed (network, credentials, branch protection, or a remote that kept moving): ${lastError.slice(0, 500) || 'no detail'}. Rerun gbrain git commit-push --push-only once the remote is reachable; never git pull --rebase in this checkout.`,
- { detail: candidate, retryable: true });
- }
-
- /** Non-merge commits in `target` but not in `upstream` (at most 200) that change files outside `roots`; null when git cannot list them. */
- export function localCommitsOutsideRoots(root: string, target: string, upstream: string, roots: string[]): Array<{ sha: string; paths: string[] }> | null {
- if (roots.includes('')) return [];
- const local = git(root, ['rev-list', '--no-merges', '--max-count=200', target, '--not', upstream]);
- if (local.code !== 0) return null;
- const offending: Array<{ sha: string; paths: string[] }> = [];
- for (const sha of local.stdout.split('\n').filter(Boolean)) {
- const paths = git(root, ['diff-tree', '--no-commit-id', '--name-only', '--no-renames', '-r', '-z', '--root', sha]).stdout.split('\0').filter(p => p && !insideSourceRoots(p, roots));
- if (paths.length) offending.push({ sha, paths });
++/** The flagged index entries in `listed` (`ls-files -v`: lower case for assume-unchanged, S for skip-worktree) whose bytes on disk HEAD lacks. A skip-worktree entry absent from disk is a sparse checkout, not a change. */
++function flaggedChanges(root: string, listed: string[]): SkippedPath[] {
++ const changed: SkippedPath[] = [];
++ const flagged = listed.filter(entry => /^[a-zS] /.test(entry));
++ const gitlinks = new Set(flagged.length
++ ? gitOk(root, ['ls-files', '-s', '-z', '--', ...literalPathspecs(flagged.map(line => line.slice(2)))], 'ls-files -s')
++ .split('\0').filter(entry => entry.startsWith('160000 ')).map(entry => entry.slice(entry.indexOf('\t') + 1))
++ : []);
++ for (const line of flagged) {
++ const path = line.slice(2);
++ if (gitlinks.has(path)) continue;
++ const abs = join(root, path);
++ const reason = /^[sS]/.test(line) ? 'skip_worktree' as const : 'assume_unchanged' as const;
++ const stat = (() => { try { return lstatSync(abs); } catch { return null; } })();
++ if (!stat && reason === 'skip_worktree') continue;
++ const hashed = !stat ? null : stat.isSymbolicLink()
++ ? git(root, ['hash-object', '--stdin'], { input: readlinkSync(abs) })
++ : git(root, ['hash-object', '--', path]);
++ // An entry git cannot hash (a missing required filter, an unreadable file, a directory now) counts as changed, so it is reported, never dropped.
++ const disk = hashed && (hashed.code === 0 ? hashed.stdout.trim() : undefined);
++ const committed = git(root, ['rev-parse', '--verify', '--quiet', `HEAD:${path}`]).stdout.trim() || null;
++ if (disk !== committed) changed.push({ path, reason });
+ }
- return offending;
++ return changed;
}
/**
- * Refuse to publish a local commit that changes files outside the configured source root(s). In a shared
- * checkout a commit made without paths (a cron's `git add <dir>; git commit`) carries whatever any writer
- * had staged; the source-root config is how a brain inside a larger repository says which files are its own.
- * Merge commits are not judged (gbrain's in-memory merges bring remote files in). With no root configured
- * the whole checkout is the root and nothing is refused.
- * Q1: on a managed canonical worktree commit-push commits only the paths the caller names (pages written outside gbrain,
- * which would otherwise land as bare commits), under the commit lock, and nothing more: no fetch, merge, push or checkout
- * move, so the owner stays the only publisher. The commit reaches the remote on the owner's next Git publish, or with
- * `gbrain git commit-push --push-only --keep-checkout`.
++ * GST-2116: the named paths whose bytes on disk HEAD still lacks once the commit step is done. `git add -A` stages
++ * nothing and exits 0 for a modified entry flagged assume-unchanged or skip-worktree (`ls-files -v`: lower case, or S;
++ * `commit --only` may still pick one up beside another path, so the check reads HEAD) and for a file inside an untracked
++ * nested repository. A skip-worktree entry absent from disk is a sparse checkout, not a change, and a flagged gitlink
++ * is left out (its commit lives in the nested repository, which hash-object cannot read). Ignored files under a named
++ * directory are left out as git leaves them; a named ignored file is refused by `git add` itself.
*/
- function assertLocalCommitsInsideRoots(ctx: Ctx, target: string, roots: string[]): void {
- const offending = localCommitsOutsideRoots(ctx.root, target, ctx.trackingRef, roots) ?? [];
- if (!offending.length) return;
- const files = [...new Set(offending.flatMap(o => o.paths))];
- const shas = offending.map(o => o.sha.slice(0, 12)).join(', ');
- throw opError('commit_outside_source_root', `${offending.length} local commit(s) (${shas}) change ${files.length} file(s) outside this brain's source root (${roots.join(', ')}): ${files.slice(0, 10).join(', ')}${files.length > 10 ? ', ...' : ''}. Nothing was pushed.`,
- `A commit made without gbrain git commit-push (for example a cron's git add plus git commit) can carry files other writers had staged. Show the user git show --stat ${offending[0].sha.slice(0, 12)}; if they want it published as is, rerun with --allow-outside-source-root. See docs/guides/shared-checkout-git.md#source-roots.`,
- { detail: JSON.stringify({ roots, commits: offending }),
- fix: { ask_user: true, consent: [], actor: 'user', requires_exclusive: false,
- argv: ['gbrain', 'git', 'commit-push', '--push-only', '--allow-outside-source-root', '--path', ctx.root],
- why: 'These commits change files that are not the brain\'s; publishing them can overwrite other projects\' or writers\' work on the remote.',
- user_message: `Local commit(s) ${shas} change files outside the brain's folder (${files.slice(0, 5).join(', ')}${files.length > 5 ? ', ...' : ''}). Publish them anyway?`,
- docs: 'docs/guides/shared-checkout-git.md#source-roots' } });
- }
-
- /** The automatic-publish secret gate: scan what the commits in trackingRef..target add (the exact range this publish pushes, under its lock). */
- function assertNoSecretsInRange(ctx: Ctx, target: string): void {
- const scan = scanRange(ctx.root, ctx.trackingRef, target);
- if (scan.unreadable !== undefined) {
- throw opError('publish_scan_unreadable', `The secret scan could not read the local commits ${ctx.trackingRef}..${target.slice(0, 12)} (${scan.unreadable}). No secret was reported. Nothing was pushed.`,
- `The publish pushes only commits it has read in full. Check the checkout with git fsck in ${ctx.root} (a missing or corrupt object, a full disk, or a git too slow for the 300 s budget), fix what it reports, then retry. Never publish with a command that skips this scan.`,
- { detail: JSON.stringify({ unreadable: scan.unreadable }), fix: { ask_user: true, consent: [], actor: 'user', requires_exclusive: false,
- argv: ['git', '-C', ctx.root, 'fsck'],
- why: 'Read-only: names missing or corrupt objects in the unpublished commits, the usual reason the scan cannot read them.',
- user_message: `The secret scan could not read the unpublished commits in ${ctx.root}, so nothing was pushed. Check the checkout with git fsck and fix what it reports?`,
- docs: 'docs/guides/shared-checkout-git.md#publish_scan_unreadable' } });
- }
- if (!scan.findings.length && !scan.unscanned.length && !scan.gate_changes.length) return;
- const named = [...scan.findings.map(f => `${f.path}:${f.line} (${f.pattern}, ${f.commit.slice(0, 7)})`), ...scan.unscanned.map(u => `${u.path} (too large to scan, ${u.commit.slice(0, 7)})`),
- ...scan.gate_changes.map(g => `${g.path} (changes what the scan sees, ${g.commit.slice(0, 7)})`)];
- throw opError('publish_secret_found',
- `${named.length} item(s) in the local commits ${ctx.trackingRef}..${target.slice(0, 12)} look like secrets or could not be scanned: ${named.slice(0, 10).join(', ')}${named.length > 10 ? ', ...' : ''}. Nothing was pushed.`,
- 'Remove the value from those commits (rewriting unpushed local commits is the user\'s call), or add a false positive\'s fingerprint to .gbrain-scan-allow, then retry. Never publish them with a command that skips this scan.',
- { detail: JSON.stringify(scan),
- fix: { ask_user: true, consent: [], actor: 'user', requires_exclusive: false,
- argv: ['git', '-C', ctx.root, 'log', '--stat', `${ctx.trackingRef}..${target}`],
- why: 'Lists the unpublished commits the scan refused; read-only. A secret pushed to the remote stays in its history.',
- user_message: `Unpublished commits in ${ctx.root} hold ${named.length || 'some'} item(s) that look like secrets or could not be scanned (${named.slice(0, 3).join(', ')}). Nothing was pushed. Remove them from those commits, or confirm a false positive so it can be allowlisted by fingerprint?`,
- docs: 'docs/guides/shared-checkout-git.md#publish_secret_found' } });
- }
-
- /** Advance the shared checkout (caller holds the commit lock) with a real compare-and-swap: fast-forward only, hooks off, never autostash. */
- function advanceLocked(root: string, target: string, expectedHead: string): { checkout: CheckoutState; reason?: string } {
- const head = git(root, ['rev-parse', 'HEAD']).stdout.trim();
- if (head === target || isAncestor(root, target, head)) return { checkout: 'unchanged' };
- if (head !== expectedHead) {
- return { checkout: 'lagging', reason: isAncestor(root, expectedHead, head)
- ? `a newer local commit (${head.slice(0, 12)}) landed during the push; publishing it advances the checkout`
- : `HEAD moved to ${head.slice(0, 12)} during the push (a writer that did not take the commit lock)` };
- }
- if (!isAncestor(root, head, target)) return { checkout: 'lagging', reason: `HEAD ${head.slice(0, 12)} is not part of the published history (it was rewritten locally)` };
- const r = withIndexRetry(root, ['-c', 'core.hooksPath=/dev/null', '-c', 'merge.autoStash=false', 'merge', '--ff-only', '--quiet', target], 'checkout advance');
- if (r.code === 0) return { checkout: 'advanced' };
- const dirty = [...r.stderr.matchAll(/^\t(.+)$/gm)].map(m => m[1]);
- if (dirty.length) return { checkout: 'lagging', reason: `local edits in ${dirty.join(', ')} block the fast-forward` };
- throw opError('git_unavailable', `git could not fast-forward ${root} to ${target.slice(0, 12)}.`,
- `${r.stderr.trim().slice(0, 300) || `exit ${r.code}`}. Nothing in the working tree changed; run gbrain git commit-push --pull once git works in this checkout.`, { detail: target });
- }
-
- function advanceWithLock(root: string, target: string, expectedHead: string, onlyWhenClean: boolean, lockWaitMs?: number): { checkout: CheckoutState; reason?: string } {
- let lock: CommitLock;
- try { lock = acquireCommitLock(root, lockWaitMs); } catch (e) {
- if ((e as { code?: string }).code !== 'commit_lock_busy') throw e;
- return { checkout: 'lagging', reason: 'another writer held the commit lock; the next publish or --pull advances the checkout' };
- }
- try {
- if (onlyWhenClean && git(root, ['status', '--porcelain']).stdout.trim()) {
- return { checkout: 'lagging', reason: 'the checkout has local edits and this unattended run never moves files under them' };
- }
- return advanceLocked(root, target, expectedHead);
- } finally {
- lock.release();
-function commitManagedPaths(root: string, opts: CommitPushOptions, managed: ManagedFilesystemRoot): CommitPushResult {
- const where = `${root} is the managed canonical worktree${managed.sourceId ? ` of source ${managed.sourceId}` : ''}`;
- if (opts.pending || opts.branch || opts.resolutions || opts.expectRemote || opts.allowOutsideSourceRoot || opts.advanceOnlyWhenClean) {
- throw opError('commit_paths_invalid', `${where}: commit-push there only commits the paths you name.`,
- `Run gbrain git commit-push with only -m and the page paths after --; gbrain sources refresh${managed.sourceId ? ` ${managed.sourceId}` : ''} brings remote commits in.`);
++function unstagedPaths(root: string, rel: string[], listed: string[]): SkippedPath[] {
++ const skipped = new Map(flaggedChanges(root, listed).map(s => [s.path, s.reason]));
++ for (const path of unindexedFiles(root, rel, listed)) if (!skipped.has(path)) skipped.set(path, 'not_staged');
++ // Only a named directory can hide an unstaged change from the two checks above (a nested repository inside it).
++ const dirs = rel.filter(path => { try { return lstatSync(join(root, path)).isDirectory(); } catch { return false; } });
++ // Status lists nothing under a directory that sits inside an untracked nested repository.
++ for (const path of dirs) {
++ const parents = path.split('/').slice(0, -1).map((_, i, parts) => parts.slice(0, i + 1).join('/'));
++ if (!skipped.has(path) && parents.some(parent => existsSync(join(root, parent, '.git')))) skipped.set(path, 'not_staged');
}
- const result = commitPathsOnly(root, opts, where, configuredSourceRoots(root), 'Leave the checkout to its owner; gbrain sources writer status names its state.');
- const counted = git(root, ['rev-list', '--count', '@{upstream}..HEAD']);
- const upstream = git(root, ['for-each-ref', '--format=%(upstream:short)', `refs/heads/${result.branch}`]).stdout.trim();
- return { ...result, managed: true, unpublished: counted.code === 0 ? Number(counted.stdout.trim()) : null, upstream: upstream || null };
--}
--
- // ── Conflict state (doctor / put_page read it) ──────────────────────────────
-/** A checkout with no Git remote at all: no remote is configured and the branch names none (a named but missing remote is refused by resolveCtx). A git command that fails is not proof of "no remote". */
-function hasNoRemote(root: string): boolean {
- const branch = git(root, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
- if (branch.code !== 0 || git(root, ['rev-parse', '--verify', '--quiet', 'HEAD']).code !== 0) return false;
- const remotes = git(root, ['remote']);
- if (remotes.code !== 0 || remotes.stdout.trim()) return false;
- return git(root, ['config', '--get', `branch.${branch.stdout.trim()}.remote`]).code === 1;
-}
--
- export interface IntegrateConflictState { branch: string; at: string; local: string; remote: string; paths: string[] }
-/** GBRA-133: with no remote there is nothing to publish to, so commit-push only commits the named paths, like a managed worktree. */
-function commitRemotelessPaths(root: string, opts: CommitPushOptions): CommitPushResult {
- const where = `${root} has no Git remote, so there is nothing to publish to`;
- if (opts.pushOnly || opts.pending || opts.branch || opts.resolutions || opts.expectRemote || opts.advanceOnlyWhenClean) {
- throw opError('commit_paths_invalid', `${where}; commit-push there only commits the paths you name.`,
- 'Run gbrain git commit-push -m <msg> -- <paths> to commit them locally, or add a remote (git remote add origin <url>) and set the branch upstream to publish.');
- }
- return { ...commitPathsOnly(root, opts, where, opts.allowOutsideSourceRoot ? [''] : configuredSourceRoots(root), 'Check out a branch (git switch <branch>), then rerun.'), no_remote: true };
-}
--
- /** The unresolved integrate_conflict recorded for this checkout, if any. */
- export function readIntegrateConflict(repo: string): IntegrateConflictState | null {
-/** Commit only the named paths under the commit lock and nothing more: no fetch, merge, push or checkout move. */
-function commitPathsOnly(root: string, opts: CommitPushOptions, where: string, roots: string[], detachedFix: string): CommitPushResult {
- if (!opts.message?.trim()) throw opError('commit_paths_invalid', 'A commit message is required.', 'Pass the commit message with -m.');
- const rel = scopePaths(root, opts.paths ?? [], opts.cwd ?? process.cwd());
- if (!rel.length) throw opError('commit_paths_invalid', `${where}: name the paths to commit.`, 'Pass -- <paths> after the message.');
- const branch = git(root, ['symbolic-ref', '--quiet', '--short', 'HEAD']).stdout.trim();
- if (!branch) throw opError('git_detached_head', `${root} is on a detached HEAD, so there is no branch to commit to.`, detachedFix);
- assertNoOperationInProgress(root);
- const lock = acquireCommitLock(root, opts.lockWaitMs);
- let committed: string | null;
-- try {
- const root = checkoutRoot(repo);
- const p = absGitPath(root, CONFLICT_STATE_NAME);
- return existsSync(p) ? JSON.parse(readFileSync(p, 'utf8')) as IntegrateConflictState : null;
- } catch {
- return null;
- assertNoOperationInProgress(root);
- committed = commitPaths(root, rel, opts.message.trim(), { roots, lockPath: lock.lockPath, markHeld: true, bases: scopeBases(root, opts, rel) });
- } finally {
- lock.release();
- }
- const remote = git(root, ['config', '--get', `branch.${branch}.remote`]).stdout.trim();
- return { outcome: committed ? 'committed_local' : 'nothing_to_commit', sha: committed, committed, branch, remote, paths: rel, integrated: 0, checkout: 'unchanged' };
-}
-
-export function commitAndPush(opts: CommitPushOptions): CommitPushResult {
- const root = checkoutRoot(opts.repo);
- if (opts.keepCheckout && !opts.pushOnly) throw opError('commit_paths_invalid', 'keepCheckout publishes commits already on the branch; it commits nothing.', 'Use --push-only --keep-checkout.');
- const managed = opts.keepCheckout || opts.pushOnly ? null : managedFilesystemRootFor(root);
- if (managed && !hasFilesystemPublication(root)) return commitManagedPaths(root, opts, managed);
- if (!opts.keepCheckout) assertManagedFilesystemWrite(root);
- if (hasNoRemote(root)) return commitRemotelessPaths(root, opts);
- const cwd = opts.cwd ?? process.cwd();
- const roots = configuredSourceRoots(root);
- const rel = opts.pushOnly ? [] : opts.pending
- ? [...dirtyPaths(root, readPendingWriteThrough(root).map(e => e.path).filter(p => insideSourceRoots(p, roots)))]
- : scopePaths(root, opts.paths ?? [], cwd);
- if (!opts.pushOnly && !opts.message?.trim()) {
- throw opError('commit_paths_invalid', 'A commit message is required.', 'Pass -m "<message>".');
- }
- const upstream = resolveCtx(root);
- const ctx = { ...withBranch(upstream, opts.branch), ...(opts.keepCheckout ? { keepCheckout: true } : {}) };
- const elsewhere = ctx.mergeRef !== upstream.mergeRef;
- assertNoOperationInProgress(root);
-
- let committed: string | null = null;
- if (!opts.pushOnly) {
- const lock = acquireCommitLock(root, opts.lockWaitMs);
- try {
- assertNoOperationInProgress(root);
- committed = rel.length ? commitPaths(root, rel, opts.message!.trim(), { roots: opts.allowOutsideSourceRoot ? [''] : roots, lockPath: lock.lockPath, markHeld: true, bases: scopeBases(root, opts, rel) }) : null;
- settlePending(root);
- } finally {
- lock.release();
- }
++ const status = dirs.length ? gitOk(root, ['--no-optional-locks', 'status', '--porcelain=v1', '-z', '--untracked-files=all', '--no-renames', '--', ...literalPathspecs(dirs)], 'status') : '';
++ for (const entry of status.split('\0').filter(Boolean)) {
++ const path = entry.slice(3);
++ if ((entry[1] !== ' ' || entry.startsWith('??')) && !skipped.has(path)) skipped.set(path, 'not_staged');
}
++ return [...skipped].map(([path, reason]) => ({ path, reason })).sort((a, b) => a.path.localeCompare(b.path));
+}
- function recordConflict(root: string, branch: string, e: unknown): void {
- try {
- const d = JSON.parse(String((e as { detail?: string }).detail ?? '{}'));
- writeFileSync(absGitPath(root, CONFLICT_STATE_NAME), JSON.stringify({ branch, at: new Date().toISOString(), local: d.local, remote: d.remote, paths: d.paths ?? [] }));
- } catch { /* best-effort */ }
- }
-
- // ── Public entry points ─────────────────────────────────────────────────────
- const unattended = !!opts.advanceOnlyWhenClean;
- const publishLockPath = absGitPath(root, PUBLISH_LOCK_NAME);
- const requestPath = absGitPath(root, PUBLISH_REQUEST_NAME);
- const waitMs = unattended ? 0 : opts.publishWaitMs ?? defaultPublishWaitMs();
- let pub = acquireNativeLockSync(publishLockPath, { timeoutMs: waitMs });
- if (!pub) {
- writeFileSync(requestPath, `${process.pid}\n`);
- pub = acquireNativeLockSync(publishLockPath, { timeoutMs: 0 });
- }
- if (!pub) {
- if (unattended) {
- return { outcome: 'push_deferred', sha: null, committed, branch: ctx.branch, remote: ctx.remote, paths: rel, integrated: 0, checkout: 'unchanged' };
- }
- throw opError('push_unconfirmed', `${committed ? 'The commit is durable locally, but another' : 'Another'} publish held this checkout's push lock for ${Math.round(waitMs / 1000)}s.`,
- `The running publish was asked to push HEAD too once it finishes. Rerun gbrain git commit-push --push-only to confirm; never git pull --rebase in this checkout.`,
- { detail: committed ?? '', retryable: true });
- }
- function defaultPublishWaitMs(): number {
- const raw = process.env.GBRAIN_PUBLISH_LOCK_WAIT_SECONDS ?? process.env.GBRAIN_PUSH_LOCK_WAIT_SECONDS;
- const secs = raw === undefined ? 300 : Number(raw);
- return Number.isFinite(secs) && secs >= 0 ? secs * 1000 : 300_000;
- const cycle = (onlyWhenClean: boolean, start: string | null, resolutions?: Map<string, Resolution>, expectRemote?: string) => {
- const requested = existsSync(requestPath);
- rmSync(requestPath, { force: true });
- try {
- const head = gitOk(root, ['rev-parse', 'HEAD'], 'rev-parse HEAD');
- const target = start && !isAncestor(root, start, head) ? start : head;
- if (!opts.allowOutsideSourceRoot) assertLocalCommitsInsideRoots(ctx, target, roots);
- if (opts.scanSecrets) assertNoSecretsInRange(ctx, target);
- const published = publish(ctx, target, resolutions, expectRemote, cwd);
- if (!elsewhere) rmSync(absGitPath(root, CONFLICT_STATE_NAME), { force: true });
- const moved = published.sha === head || elsewhere || opts.keepCheckout ? { checkout: 'unchanged' as const } : advanceWithLock(root, published.sha, head, onlyWhenClean, opts.lockWaitMs);
- return { published, moved };
- } catch (e) {
- if ((e as { code?: string }).code === 'integrate_conflict' && !elsewhere) recordConflict(root, ctx.branch, e);
- if (requested) writeFileSync(requestPath, `${process.pid}\n`);
- throw e;
- }
- };
++/** Named paths that are files on disk yet absent from the index (`listed`: `ls-files -v` after `git add -A`), as a file inside a nested repository is. */
++function unindexedFiles(root: string, rel: string[], listed: string[]): string[] {
++ const indexed = new Set(listed.map(line => line.slice(2)));
++ return rel.filter(path => {
++ if (indexed.has(path)) return false;
++ try { return !lstatSync(join(root, path)).isDirectory(); } catch { return false; }
++ });
+}
- let first: ReturnType<typeof cycle>;
- try {
- first = cycle(unattended, committed, opts.resolutions, opts.expectRemote);
- } finally {
- pub.release();
- }
- // Publishers that found the push lock busy left a request; honor it after releasing (no commit is stranded).
- for (let i = 0; i < 16 && existsSync(requestPath); i++) {
- const again = acquireNativeLockSync(publishLockPath, { timeoutMs: 0 });
- if (!again) break;
- try { cycle(true, null); } catch { break; } finally { again.release(); }
+/**
- * Q1: on a managed canonical worktree commit-push commits only the paths the caller names (pages written outside gbrain,
- * which would otherwise land as bare commits), under the commit lock, and nothing more: no fetch, merge, push or checkout
- * move, so the owner stays the only publisher. The commit reaches the remote on the owner's next Git publish, or with
- * `gbrain git commit-push --push-only --keep-checkout`.
++ * GST-2116: a run that left a named path uncommitted fails, after committing (and, on a classic checkout, pushing) the
++ * rest, so a write is never reported as saved when it is not. In a managed canonical worktree a skipped page is the
++ * owner's to save (`writer_coordinator_required`); anything else is `commit_paths_skipped`.
+ */
- function commitManagedPaths(root: string, opts: CommitPushOptions, managed: ManagedFilesystemRoot): CommitPushResult {
- const where = `${root} is the managed canonical worktree${managed.sourceId ? ` of source ${managed.sourceId}` : ''}`;
- if (opts.pending || opts.branch || opts.resolutions || opts.expectRemote || opts.allowOutsideSourceRoot || opts.advanceOnlyWhenClean) {
- throw opError('commit_paths_invalid', `${where}: commit-push there only commits the paths you name.`,
- `Run gbrain git commit-push with only -m and the page paths after --; gbrain sources refresh${managed.sourceId ? ` ${managed.sourceId}` : ''} brings remote commits in.`);
- }
- const { result: committed, skipped } = commitPathsOnly(root, opts, where, configuredSourceRoots(root), 'Leave the checkout to its owner; gbrain sources writer status names its state.');
- const counted = git(root, ['rev-list', '--count', '@{upstream}..HEAD']);
- const upstream = git(root, ['for-each-ref', '--format=%(upstream:short)', `refs/heads/${committed.branch}`]).stdout.trim();
- const result: CommitPushResult = { ...committed, managed: true, unpublished: counted.code === 0 ? Number(counted.stdout.trim()) : null, upstream: upstream || null };
- if (skipped.length) throw skippedPathsError(root, skipped, result, managed);
- return result;
- }
-
- /** A checkout with no Git remote at all: no remote is configured and the branch names none (a named but missing remote is refused by resolveCtx). A git command that fails is not proof of "no remote". */
- function hasNoRemote(root: string): boolean {
- const branch = git(root, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
- if (branch.code !== 0 || git(root, ['rev-parse', '--verify', '--quiet', 'HEAD']).code !== 0) return false;
- const remotes = git(root, ['remote']);
- if (remotes.code !== 0 || remotes.stdout.trim()) return false;
- return git(root, ['config', '--get', `branch.${branch.stdout.trim()}.remote`]).code === 1;
- }
-
- /** GBRA-133: with no remote there is nothing to publish to, so commit-push only commits the named paths, like a managed worktree. */
- function commitRemotelessPaths(root: string, opts: CommitPushOptions): CommitPushResult {
- const where = `${root} has no Git remote, so there is nothing to publish to`;
- if (opts.pushOnly || opts.pending || opts.branch || opts.resolutions || opts.expectRemote || opts.advanceOnlyWhenClean) {
- throw opError('commit_paths_invalid', `${where}; commit-push there only commits the paths you name.`,
- 'Run gbrain git commit-push -m <msg> -- <paths> to commit them locally, or add a remote (git remote add origin <url>) and set the branch upstream to publish.');
- }
- const { result: committed, skipped } = commitPathsOnly(root, opts, where, opts.allowOutsideSourceRoot ? [''] : configuredSourceRoots(root), 'Check out a branch (git switch <branch>), then rerun.');
- const result: CommitPushResult = { ...committed, no_remote: true };
- if (skipped.length) throw skippedPathsError(root, skipped, result);
- return result;
- }
-
- /** Commit only the named paths under the commit lock and nothing more: no fetch, merge, push or checkout move. */
- function commitPathsOnly(root: string, opts: CommitPushOptions, where: string, roots: string[], detachedFix: string): { result: CommitPushResult; skipped: SkippedPath[] } {
- if (!opts.message?.trim()) throw opError('commit_paths_invalid', 'A commit message is required.', 'Pass the commit message with -m.');
- const rel = scopePaths(root, opts.paths ?? [], opts.cwd ?? process.cwd());
- if (!rel.length) throw opError('commit_paths_invalid', `${where}: name the paths to commit.`, 'Pass -- <paths> after the message.');
- const branch = git(root, ['symbolic-ref', '--quiet', '--short', 'HEAD']).stdout.trim();
- if (!branch) throw opError('git_detached_head', `${root} is on a detached HEAD, so there is no branch to commit to.`, detachedFix);
- assertNoOperationInProgress(root);
- const lock = acquireCommitLock(root, opts.lockWaitMs);
- let commit: ReturnType<typeof commitPaths>;
- try {
- assertNoOperationInProgress(root);
- commit = commitPaths(root, rel, opts.message.trim(), { roots, lockPath: lock.lockPath, markHeld: true, bases: scopeBases(root, opts, rel) });
- } finally {
- lock.release();
- }
- const committed = commit.sha;
- const remote = git(root, ['config', '--get', `branch.${branch}.remote`]).stdout.trim();
- return { result: { outcome: committed ? 'committed_local' : 'nothing_to_commit', sha: committed, committed, branch, remote, paths: rel, integrated: 0, checkout: 'unchanged' }, skipped: commit.skipped };
- }
-
- export function commitAndPush(opts: CommitPushOptions): CommitPushResult {
- const root = checkoutRoot(opts.repo);
- if (opts.keepCheckout && !opts.pushOnly) throw opError('commit_paths_invalid', 'keepCheckout publishes commits already on the branch; it commits nothing.', 'Use --push-only --keep-checkout.');
- const managed = opts.keepCheckout || opts.pushOnly ? null : managedFilesystemRootFor(root);
- if (managed && !hasFilesystemPublication(root)) return commitManagedPaths(root, opts, managed);
- if (!opts.keepCheckout) assertManagedFilesystemWrite(root);
- if (hasNoRemote(root)) return commitRemotelessPaths(root, opts);
- const cwd = opts.cwd ?? process.cwd();
- const roots = configuredSourceRoots(root);
- const rel = opts.pushOnly ? [] : opts.pending
- ? [...dirtyPaths(root, readPendingWriteThrough(root).map(e => e.path).filter(p => insideSourceRoots(p, roots)))]
- : scopePaths(root, opts.paths ?? [], cwd);
- if (!opts.pushOnly && !opts.message?.trim()) {
- throw opError('commit_paths_invalid', 'A commit message is required.', 'Pass -m "<message>".');
- }
- const upstream = resolveCtx(root);
- const ctx = { ...withBranch(upstream, opts.branch), ...(opts.keepCheckout ? { keepCheckout: true } : {}) };
- const elsewhere = ctx.mergeRef !== upstream.mergeRef;
- assertNoOperationInProgress(root);
-
- let committed: string | null = null;
- let skipped: SkippedPath[] = [];
- if (!opts.pushOnly) {
- const lock = acquireCommitLock(root, opts.lockWaitMs);
- try {
- assertNoOperationInProgress(root);
- if (rel.length) ({ sha: committed, skipped } = commitPaths(root, rel, opts.message!.trim(), { roots: opts.allowOutsideSourceRoot ? [''] : roots, lockPath: lock.lockPath, markHeld: true, bases: scopeBases(root, opts, rel) }));
- settlePending(root);
- } finally {
- lock.release();
- }
- }
-
- const unattended = !!opts.advanceOnlyWhenClean;
- const publishLockPath = absGitPath(root, PUBLISH_LOCK_NAME);
- const requestPath = absGitPath(root, PUBLISH_REQUEST_NAME);
- const waitMs = unattended ? 0 : opts.publishWaitMs ?? defaultPublishWaitMs();
- let pub = acquireNativeLockSync(publishLockPath, { timeoutMs: waitMs });
- if (!pub) {
- writeFileSync(requestPath, `${process.pid}\n`);
- pub = acquireNativeLockSync(publishLockPath, { timeoutMs: 0 });
- }
- const unpublished: CommitPushResult = { outcome: 'committed_local', sha: null, committed, branch: ctx.branch, remote: ctx.remote, paths: rel, integrated: 0, checkout: 'unchanged' };
- if (!pub) {
- if (unattended) {
- const deferred: CommitPushResult = { ...unpublished, outcome: 'push_deferred' };
- if (skipped.length) throw skippedPathsError(root, skipped, deferred);
- return deferred;
- }
- const busy = opError('push_unconfirmed', `${committed ? 'The commit is durable locally, but another' : 'Another'} publish held this checkout's push lock for ${Math.round(waitMs / 1000)}s.`,
- `The running publish was asked to push HEAD too once it finishes. Rerun gbrain git commit-push --push-only to confirm; never git pull --rebase in this checkout.`,
- { detail: committed ?? '', retryable: true });
- if (skipped.length) throw skippedPathsError(root, skipped, unpublished, undefined, busy);
- throw busy;
++function skippedPathsError(root: string, skipped: SkippedPath[], result: CommitPushResult, managed?: ManagedFilesystemRoot, publish?: unknown): OperationError {
++ const list = `${skipped.slice(0, 20).map(s => `${s.path} (${s.reason})`).join(', ')}${skipped.length > 20 ? ', ...' : ''}`;
++ const pushed = !!result.committed && (result.outcome === 'pushed' || result.outcome === 'pushed_checkout_lagging');
++ const done = result.committed
++ ? `The other named paths were committed as ${result.committed.slice(0, 7)}${pushed ? ` and pushed to ${result.remote}/${result.branch}` : ', not pushed'}.`
++ : 'Nothing was committed.';
++ const failed = publish as { code?: string; message?: string; detail?: string } | undefined;
++ const rest = `${done}${failed ? ` The push failed too (${failed.code ?? 'error'}): ${failed.message ?? String(publish)}` : ''}`;
++ const detail = JSON.stringify({ skipped, committed: result.committed, ...(pushed ? { pushed: result.sha } : {}), branch: result.branch,
++ ...(failed ? { publish: { code: failed.code ?? null, detail: failed.detail ?? null } } : {}) });
++ const docs = 'docs/guides/shared-checkout-git.md#outcomes';
++ const flagged = skipped.filter(s => s.reason !== 'not_staged');
++ // One update-index call per flag: given both, git clears only the first.
++ const clears = (['assume_unchanged', 'skip_worktree'] as const)
++ .map(reason => ({ flag: reason === 'skip_worktree' ? '--no-skip-worktree' : '--no-assume-unchanged', paths: flagged.filter(s => s.reason === reason).map(s => s.path) }))
++ .filter(c => c.paths.length)
++ .map(c => ['git', '-C', root, 'update-index', c.flag, '--', ...c.paths]);
++ const clearCommand = clears.map(argv => shellQuote(argv)).join(' && ');
++ const flagNote = 'an assume-unchanged or skip-worktree flag; an editor, an indexer or a sparse checkout can leave one, and people also set skip-worktree on purpose to keep local edits out of commits, so clearing it commits those edits';
++ const chain = (steps: string[][], last?: Action): Action | undefined => steps.reduceRight<Action | undefined>((then, argv) =>
++ ({ argv, consent: [], actor: 'agent', requires_exclusive: false, why: 'Clears the flag so git sees the edit on disk; the file keeps its bytes.', ...(then ? { then } : {}) }), last);
++ const pages = managed ? skipped.filter(s => isSyncable(s.path)) : [];
++ if (managed && pages.length) {
++ const source = managed.sourceId ? { argv: ['--source-id', managed.sourceId], mcp: { source_id: managed.sourceId } } : { argv: [], mcp: {} };
++ const put: Action = { argv: ['gbrain', 'put', ...source.argv, '<slug>'],
++ mcp: { tool: 'put_page', arguments: { slug: '<slug>', ...source.mcp, content: '<the page file>' } },
++ inputs: [{ name: 'slug', how: `Each listed page path without its .md extension; pass the file's content on stdin: ${pages.slice(0, 5).map(s => s.path).join(', ')}` }],
++ consent: [], actor: 'agent', requires_exclusive: false,
++ why: 'put_page saves the page through the owner, which writes the file, commits only that path and pushes it.',
++ verify: { argv: ['gbrain', 'sources', 'writer', 'status', managed.sourceId ?? '<source>', '--json'] } };
++ return opError('writer_coordinator_required',
++ `${root} is the managed canonical worktree${managed.sourceId ? ` of source ${managed.sourceId}` : ''}, and git did not commit ${skipped.length} named path(s): ${list}. ${rest}`,
++ `${clears.length ? `First, with the user's agreement, clear the flags (${clearCommand}), since the owner's own Git step cannot see a flagged edit either. ` : ''}Then save those pages through gbrain (put_page, edit_page or capture; on the CLI, gbrain put${managed.sourceId ? ` --source-id ${managed.sourceId}` : ''} with the page slug and the page on stdin): the persistence owner commits and pushes them. Never commit page files around it.`,
++ { docs, detail,
++ why: 'The persistence owner is the only Git writer of pages in a managed worktree; a page file written there directly and left uncommitted is neither in Git nor in the database, so reporting success would lose the write silently.',
++ fix: { ...(chain(clears, put) ?? put), ask_user: true,
++ user_message: `These page files were written straight into the managed checkout and git did not commit them: ${pages.slice(0, 10).map(s => s.path).join(', ')}.${clears.length ? ` Git hides their edits (${flagNote}); clear the flags first.` : ''} Save each one through gbrain (put_page), which replaces the stored page with the file's content?` } });
}
++ return opError('commit_paths_skipped', `git did not commit ${skipped.length} named path(s) in ${root}: ${list}. ${rest}`,
++ flagged.length
++ ? `Git hides edits to the assume_unchanged and skip_worktree paths from commits. With the user's agreement clear the flags (${clearCommand}), then rerun the same commit-push.`
++ : 'Git did not stage the not_staged paths (a file inside a nested Git repository is the usual cause). Move them into the brain checkout proper, or commit them in their own repository, then rerun.',
++ { docs, detail,
++ why: 'git add stages nothing and still exits 0 for a modified file flagged assume-unchanged or skip-worktree, or a file inside a nested repository; reporting success would leave the write uncommitted with nothing in any log.',
++ fix: flagged.length
++ ? { ...chain(clears)!, ask_user: true,
++ user_message: `Git is set to ignore edits to ${flagged.slice(0, 10).map(s => s.path).join(', ')} (${flagNote}), so they were not committed. Clear those flags and commit the edits?`,
++ verify: { argv: ['git', '-C', root, 'ls-files', '-v', '--', ...flagged.map(s => s.path)] } }
++ : { consent: [], actor: 'user', requires_exclusive: false,
++ why: 'Git cannot commit a file that belongs to another repository, so only moving it or committing it there settles it.',
++ user_message: `Git did not commit ${skipped.slice(0, 10).map(s => s.path).join(', ')} in ${root} (a file inside a nested Git repository is the usual cause). Where should they be committed?` } });
++}
- const cycle = (onlyWhenClean: boolean, start: string | null, resolutions?: Map<string, Resolution>, expectRemote?: string) => {
- const requested = existsSync(requestPath);
- rmSync(requestPath, { force: true });
- try {
- const head = gitOk(root, ['rev-parse', 'HEAD'], 'rev-parse HEAD');
- const target = start && !isAncestor(root, start, head) ? start : head;
- if (!opts.allowOutsideSourceRoot) assertLocalCommitsInsideRoots(ctx, target, roots);
- if (opts.scanSecrets) assertNoSecretsInRange(ctx, target);
- const published = publish(ctx, target, resolutions, expectRemote, cwd);
- if (!elsewhere) rmSync(absGitPath(root, CONFLICT_STATE_NAME), { force: true });
- const moved = published.sha === head || elsewhere || opts.keepCheckout ? { checkout: 'unchanged' as const } : advanceWithLock(root, published.sha, head, onlyWhenClean, opts.lockWaitMs);
- return { published, moved };
- } catch (e) {
- if ((e as { code?: string }).code === 'integrate_conflict' && !elsewhere) recordConflict(root, ctx.branch, e);
- if (requested) writeFileSync(requestPath, `${process.pid}\n`);
- throw e;
- }
- const { published, moved } = first;
- return {
- outcome: moved.checkout === 'lagging' ? 'pushed_checkout_lagging' : committed || opts.pushOnly ? 'pushed' : 'nothing_to_commit',
- sha: published.sha, committed, branch: ctx.branch, remote: ctx.remote, paths: rel,
- integrated: published.integrated, confirmed: published.confirmed, checkout: moved.checkout, ...(moved.reason ? { lagging_reason: moved.reason } : {}),
- ...(published.quarantined ? { quarantined: published.quarantined } : {}),
- ...(published.superseded ? { superseded_remote_paths: published.superseded } : {}),
-- };
-
- let first: ReturnType<typeof cycle>;
- try {
- first = cycle(unattended, committed, opts.resolutions, opts.expectRemote);
- } catch (e) {
- if (skipped.length) throw skippedPathsError(root, skipped, unpublished, undefined, e);
- throw e;
- } finally {
- pub.release();
- }
- // Publishers that found the push lock busy left a request; honor it after releasing (no commit is stranded).
- for (let i = 0; i < 16 && existsSync(requestPath); i++) {
- const again = acquireNativeLockSync(publishLockPath, { timeoutMs: 0 });
- if (!again) break;
- try { cycle(true, null); } catch { break; } finally { again.release(); }
++/** `--base` keyed by the repository-relative path it names; each must also be a committed path. */
++function scopeBases(root: string, opts: CommitPushOptions, rel: string[]): Map<string, string> | undefined {
++ if (!opts.bases?.size) return undefined;
++ const scoped = new Map<string, string>();
++ for (const [path, blob] of opts.bases) {
++ const [key] = scopePaths(root, [path], opts.cwd ?? process.cwd());
++ if (!key || !rel.includes(key)) throw opError('commit_paths_invalid', `--base names ${path}, which is not one of the paths to commit.`, 'Name every --base path after -- as well.');
++ scoped.set(key, blob);
+ }
-
- const { published, moved } = first;
- const result: CommitPushResult = {
- outcome: moved.checkout === 'lagging' ? 'pushed_checkout_lagging' : committed || opts.pushOnly ? 'pushed' : 'nothing_to_commit',
- sha: published.sha, committed, branch: ctx.branch, remote: ctx.remote, paths: rel,
- integrated: published.integrated, confirmed: published.confirmed, checkout: moved.checkout, ...(moved.reason ? { lagging_reason: moved.reason } : {}),
- ...(published.quarantined ? { quarantined: published.quarantined } : {}),
- ...(published.superseded ? { superseded_remote_paths: published.superseded } : {}),
- };
- if (skipped.length) throw skippedPathsError(root, skipped, result);
- return result;
++ return scoped;
}
/**
-- * Bring remote commits into the shared checkout without rebasing it: fetch
-- * outside the lock, then (under the commit lock) fast-forward, or merge
-- * diverged history in memory and fast-forward to the merge. Never pushes.
-- * `requireClean` keeps the unattended cron's conservative "any local edit →
-- * skip" rule.
++ * Stage and commit exactly `rel` (the caller holds the commit lock). Refused
++ * before anything is staged: a path outside the source root(s), and a file
++ * another writer already staged under a named directory (name it to claim
++ * it). A commit git refuses leaves the index as it found it. `skipped` lists
++ * the named paths git left out (GST-2116); the rest are still committed.
*/
--export function pullShared(repo: string, opts: { requireClean?: boolean; lockWaitMs?: number; fetchTimeoutMs?: number; remoteBranch?: string } = {}): PullResult {
-- const root = checkoutRoot(repo);
-- assertManagedFilesystemWrite(root);
-- const ctx = withBranch(resolveCtx(root), opts.remoteBranch);
-- if (opts.requireClean && git(root, ['status', '--porcelain']).stdout.trim()) return { status: 'skipped_dirty' };
-- assertNoOperationInProgress(root);
-- const fetched = remoteGit(root, 'fetch', [...fetchFlags(root), '--', ctx.remote, `+${ctx.mergeRef}:${ctx.trackingRef}`], opts.fetchTimeoutMs ?? 300_000);
-- if (fetched.code !== 0) {
-- throw opError('git_unavailable', `git fetch from ${ctx.remote} failed in ${root}.`, fetched.stderr.trim().slice(0, 300) || 'Check the remote and its credentials.');
-- }
-- const remoteTip = gitOk(root, ['rev-parse', ctx.trackingRef], 'rev-parse tracking ref');
-- const lock = acquireCommitLock(root, opts.lockWaitMs);
-- try {
-- assertNoOperationInProgress(root);
-- if (opts.requireClean && git(root, ['status', '--porcelain']).stdout.trim()) return { status: 'skipped_dirty' };
-- const head = gitOk(root, ['rev-parse', 'HEAD'], 'rev-parse HEAD');
-- if (head === remoteTip || isAncestor(root, remoteTip, head)) return { status: head === remoteTip ? 'up_to_date' : 'ahead' };
-- let target = remoteTip;
-- let merged = false;
-- if (!isAncestor(root, head, remoteTip)) {
-- const tree = integrate(root, head, remoteTip);
-- if (tree.conflicts.length) throw conflictError(ctx, head, remoteTip, tree);
-- target = buildMerge(ctx, head, remoteTip, tree.tree!, tree.skipped);
-- merged = true;
-- }
-- const moved = advanceLocked(root, target, head);
-- if (moved.checkout === 'lagging') return { status: 'lagging', from: head, reason: moved.reason };
-- return { status: 'advanced', from: head, to: target, merged };
-- } finally {
-- lock.release();
++function commitPaths(root: string, rel: string[], message: string, scope: CommitScope): { sha: string | null; skipped: SkippedPath[] } {
++ const outside = rel.filter(p => !insideSourceRoots(p, scope.roots));
++ if (outside.length) throw outsideRootError(root, scope.roots, outside, 'Refusing to commit');
++ for (const [path, base] of scope.bases ?? []) {
++ const head = git(root, ['rev-parse', '--verify', '-q', `HEAD:${path}`]).stdout.trim() || 'absent';
++ if (head !== base) throw opError('commit_base_moved', `${path} changed at HEAD since the writer read it (base ${base}, HEAD ${head}).`,
++ `Nothing was staged or committed. Read ${path} at HEAD again (git -C ${root} show HEAD:${path}), redo the change on it, and rerun with --base ${path}=${head}.`,
++ { detail: JSON.stringify({ path, base, head }), docs: 'docs/guides/shared-checkout-git.md#base-check' });
}
--}
++ const swept = stagedPaths(root).filter(p => !rel.includes(p) && rel.some(spec => covers(spec, p)));
++ if (swept.length) {
++ const list = `${swept.slice(0, 10).join(', ')}${swept.length > 10 ? ', ...' : ''}`;
++ throw opError('commit_prestaged_paths', `${swept.length} file(s) under the named path(s) were already staged by another writer: ${list}.`,
diff --cc test/adopt-local-edit.test.ts
index 2a32bffcf1,b0ba2f9d8d..bc46adba80
--- a/test/adopt-local-edit.test.ts
+++ b/test/adopt-local-edit.test.ts
@@@ -36,9 -35,11 +36,11 @@@ import { performManagedSync } from '../
import { ledgerFiles, readLedger, recordIntent } from '../src/core/git/commit-ledger.ts';
import { isTerminal, requestPrincipal, type WriteRequest } from '../src/core/persistence/model.ts';
import { cancelWriteRequest } from '../src/core/persistence/control.ts';
+ import { recoverPublication } from '../src/core/persistence/coordinator.ts';
-import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { encodedPostgres, isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { managedBrain } from './helpers/managed-brain.ts';
import { testBackends } from './helpers/test-backends.ts';
+ import { waitFor } from './helpers/wait-for.ts';
import { commitFile, git, page, withRefreshFixture, type RefreshFixture } from './helpers/worktree-refresh-fixture.ts';
const backends = testBackends();