Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sources): url_source_origin doctor check, sources record-origin, scrubbed hooks-off check
garrytan2a12a784ec91
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0011813b94..0617647553 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,18 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased]++**Older URL sources can get the same reclone settings as new ones remote callers add.** URL sources added before gbrain recorded who added them carry no record, and nothing stored tells a remote caller's add from the local operator's, so their reclones used the clone settings of a local add. The new doctor check `url_source_origin` lists them and asks the user who added each one. `gbrain sources record-origin <id>... --remote|--local` records that answer, as a preview until `--apply`. With `--remote`, every later reclone of the source clones with git-lfs downloads and hooks off, like a source a remote caller adds today. A checkout that tracks git-lfs files is refused, because changing its settings would make the next reclone fail to match its canonical content. Nothing changes on upgrade.++**`gbrain frontmatter install-hook` reads a clone's hooks-off setting from that clone's own config only, and its skip message names only that setting.** The check that leaves a clone with `core.hooksPath=/dev/null` alone now runs with `GIT_DIR`, `GIT_WORK_TREE` and the `GIT_CONFIG*` variables scrubbed, so a variable inherited from the caller's shell cannot point the read at another repository or config file. The `skipped — …` line says the clone's own config turns hooks off, without naming a cause it did not check.++### Itemized changes++- `src/commands/frontmatter-install-hook.ts`: `hooksOffInClone` runs `git config --local --get core.hooksPath` with `gitChildEnv()` minus `GIT_CONFIG_GLOBAL`, `GIT_CONFIG_SYSTEM` and `GIT_CONFIG_NOSYSTEM`. `hooksPathBlocker` returns `hooks are off in this clone's own config (core.hooksPath=/dev/null), and gbrain leaves them off`. Other git reads in the file keep the caller's environment.+- `src/core/url-source-origin.ts`, `src/commands/sources-record-origin.ts`, `src/commands/doctor/checks/url-source-origin.ts`, `src/commands/doctor/wave-checks.ts`: doctor `url_source_origin` (host-only, read-only) lists active URL sources in the default clone directory with no `added_by_remote_caller` record; a clone in another directory is a local add and is not listed. `gbrain sources record-origin` is trusted local CLI only (`trusted_local_only` for any other caller) and writes the record in one transaction that re-reads the row. `--remote` refuses `lfs_tracked` (a tracked path with `filter=lfs`) and `lfs_unknown` (a checkout that is missing or Git cannot list); `--local` never replaces a remote record. Without git-lfs files the tracked bytes of a reclone are unchanged, so the stored writer manifest is not rewritten.+- Tests: `test/frontmatter-install-hook.test.ts`; `test/url-source-origin.test.ts` on PGLite and Postgres; the doctor goldens gain the `url_source_origin` row.+## [0.60.611.0] - 2026-11-08**Doctor `foreign_writers` no longer reads an unreadable ledger or a skipped repository as clean, the owner-path commit guard fails closed, and the opt-in local-edit adoption (`persistence.adopt_local_edits`, off by default) gets the hardening it needed before any source turns it on.** `foreign_writers` now marks a scan partial when a root's Git probe fails, when roots pass the 50-root cap, or when the commit ledger exists but cannot be read. It names a foreign commit that carries a `gbrain-` trailer as possibly an older gbrain without the ledger, and still fails it. `gbrain git commit-push` refuses a repository that only encloses a registered checkout, even when an older gbrain left a stale marker in it. Adoption keeps its refusal for a conflicted path or a merge in progress, a stale editor save, a segmented or oversized page, and a caller whose claim is gone, and checks the claim, the conflict and the merge again in the transaction that publishes its commit. Its quiet wait is capped at the foreground budget, and an adoption whose publication failed after its commit is retried instead of left orphaned.diff --git a/docs/architecture/key-files/commands-3-continued.md b/docs/architecture/key-files/commands-3-continued.mdindex 071a10a7af..bd0493e996 100644--- a/docs/architecture/key-files/commands-3-continued.md+++ b/docs/architecture/key-files/commands-3-continued.md@@ -15,6 +15,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/friction.ts` + `src/core/friction.ts` — `gbrain friction {log,render,list,summary,diff}` reporter. Append-only JSONL under `$GBRAIN_HOME/.gbrain/friction/<run-id>.jsonl`. Schema is a flat extension of `StructuredAgentError`; every claw-test run opens with a `phase-marker`/`start` meta record carrying `agent` + `scenario` + `harness_schema` (agent-name resolution depends on it). Render groups by severity → phase, defaults to `--redact` for md output (strips `$HOME`/`$CWD` to placeholders so reports paste safely in PRs). `diff --base <run-or-agent> --compare <run-or-agent>` is the cross-agent instrument: exact run-id wins, else agent name resolves to that agent's latest run; identity is `(kind, phase, normalized 80-char message prefix — digit runs collapsed so durations/counts don't split identities)` over `kind ∈ {friction, delight}` as MULTISETS (per-severity counts + totals are the compared attributes: `count_changed` = volume, `severity_changed` = distribution shape via exact integer proportion test, so a delight→friction flip or a 2×error+1×nit → 1×error+2×nit redistribution always surfaces; markers/interrupted feed the compatibility banner, which warns on scenario/version mismatch); output labels sections "unique to <run>" — an instrument, never a blame-attributor. Run-id resolves from `--run-id` > `$GBRAIN_FRICTION_RUN_ID` > `standalone.jsonl`. Skills the claw-test exercises carry a `_friction-protocol.md` callout so agents know when to log friction.-- `src/commands/frontmatter-install-hook.ts` — `gbrain frontmatter install-hook [--source <id>] [--force] [--uninstall]`: writes the frontmatter pre-commit hook at `<git root>/.githooks/pre-commit` and sets `core.hooksPath` when unset. The root comes from `discoverGitRoot` (the same `git rev-parse --show-toplevel` walk `gbrain sync` uses, realpath'd on both sides), so a source registered as a SUBDIRECTORY of a host repo (bootstrap's `<workspace>/brain`) is accepted rather than skipped: the hook lands at the host root with `git diff --cached` limited to that subdirectory via shell-quoted git pathspecs, recorded as `# gbrain-scope: <dir>/` marker lines (one per guarded scope). The script carries `# gbrain-hook-version: N` (`FRONTMATTER_HOOK_VERSION`; no marker = version 1, which validated working-tree bytes), lists staged paths with `-z | tr '\0' '\n'`, collects them in a heredoc-fed `while IFS= read -r` loop (spaces and non-ASCII names survive; a newline inside a name is unsupported) and runs ONE `gbrain frontmatter validate --staged -- <paths>`, which checks the staged blobs under the strict producer rule and names failures as staged content. `inspectFrontmatterHook(localPath, sourceId?)` (read-only) returns the installed gbrain hook's version, `current`, and the `install-hook --force` refresh argv for doctor and post-upgrade. One hook per root — nested sources union their scopes on install and drop only their own on uninstall (the last one removes the file); a root-registered source renders the unscoped script and owns the whole hook. A foreign `.githooks/pre-commit` still needs `--force` (`.bak` saved, restored on uninstall). Both install and uninstall resolve the hook location through `hookPaths(root)`, which lstat-refuses a symlinked `.githooks/` or `pre-commit` (a committed link in a host repo would redirect the write/chmod/rm elsewhere); the CLI prints the refusal as a `skipped` line and continues with the other sources. Only a path outside any repo is otherwise skipped. Every branch that leaves a hook on disk — fresh write, `--force` overwrite, or a byte-identical refresh — reaches the wiring step, because the hook FILE travels with the repo while `core.hooksPath` is per-clone config: a fresh clone of a repo that committed the hook reports `installed` (and gets wired) rather than `unchanged` while inert; `unchanged` means current AND wired. Before wiring `core.hooksPath`, `hooksPathBlocker(root)` returns the operator-facing reason wiring is unsafe, or null: a `core.hooksPath` already set (any scope — a global/corporate value counts; `--type=path`-expanded and resolved against the root) to anywhere that does not realpath to `.githooks` (theirs to keep; git never reads `.githooks/` then — one resolving to `.githooks` counts as wired), a foreign executable under `.githooks/` (wiring would start running it — third-party clones commit hooks there) or an active hook in the repo's own hooks dir (`activeGitHooks` — executable non-`*.sample` entries under `<git rev-parse --git-common-dir>/hooks`, immune to a foreign `core.hooksPath`; wiring would make git ignore them). Every git spawn passes `env: process.env` (Bun's default child env is a startup snapshot), so `GIT_CONFIG_*` overrides reach the child. A `core.hooksPath` of `/dev/null` in the clone's own (`--local`) config (a URL source a remote caller added: hooks off on purpose; a global or system value does not count) returns `skipped_hooks_off` before anything is written, `--force` included, `hooksPathBlocker` names it without wiring advice, and `inspectFrontmatterHook` returns null so doctor never proposes a refresh install-hook would skip. Any other blocker returns `installed_unwired` — the hook is written, `core.hooksPath` stays untouched, and the CLI prints the reason + the manual `git config core.hooksPath .githooks` step. Pinned by `test/frontmatter-install-hook.test.ts`.+- `src/commands/frontmatter-install-hook.ts` — `gbrain frontmatter install-hook [--source <id>] [--force] [--uninstall]`: writes the frontmatter pre-commit hook at `<git root>/.githooks/pre-commit` and sets `core.hooksPath` when unset. The root comes from `discoverGitRoot` (the same `git rev-parse --show-toplevel` walk `gbrain sync` uses, realpath'd on both sides), so a source registered as a SUBDIRECTORY of a host repo (bootstrap's `<workspace>/brain`) is accepted rather than skipped: the hook lands at the host root with `git diff --cached` limited to that subdirectory via shell-quoted git pathspecs, recorded as `# gbrain-scope: <dir>/` marker lines (one per guarded scope). The script carries `# gbrain-hook-version: N` (`FRONTMATTER_HOOK_VERSION`; no marker = version 1, which validated working-tree bytes), lists staged paths with `-z | tr '\0' '\n'`, collects them in a heredoc-fed `while IFS= read -r` loop (spaces and non-ASCII names survive; a newline inside a name is unsupported) and runs ONE `gbrain frontmatter validate --staged -- <paths>`, which checks the staged blobs under the strict producer rule and names failures as staged content. `inspectFrontmatterHook(localPath, sourceId?)` (read-only) returns the installed gbrain hook's version, `current`, and the `install-hook --force` refresh argv for doctor and post-upgrade. One hook per root — nested sources union their scopes on install and drop only their own on uninstall (the last one removes the file); a root-registered source renders the unscoped script and owns the whole hook. A foreign `.githooks/pre-commit` still needs `--force` (`.bak` saved, restored on uninstall). Both install and uninstall resolve the hook location through `hookPaths(root)`, which lstat-refuses a symlinked `.githooks/` or `pre-commit` (a committed link in a host repo would redirect the write/chmod/rm elsewhere); the CLI prints the refusal as a `skipped` line and continues with the other sources. Only a path outside any repo is otherwise skipped. Every branch that leaves a hook on disk — fresh write, `--force` overwrite, or a byte-identical refresh — reaches the wiring step, because the hook FILE travels with the repo while `core.hooksPath` is per-clone config: a fresh clone of a repo that committed the hook reports `installed` (and gets wired) rather than `unchanged` while inert; `unchanged` means current AND wired. Before wiring `core.hooksPath`, `hooksPathBlocker(root)` returns the operator-facing reason wiring is unsafe, or null: a `core.hooksPath` already set (any scope — a global/corporate value counts; `--type=path`-expanded and resolved against the root) to anywhere that does not realpath to `.githooks` (theirs to keep; git never reads `.githooks/` then — one resolving to `.githooks` counts as wired), a foreign executable under `.githooks/` (wiring would start running it — third-party clones commit hooks there) or an active hook in the repo's own hooks dir (`activeGitHooks` — executable non-`*.sample` entries under `<git rev-parse --git-common-dir>/hooks`, immune to a foreign `core.hooksPath`; wiring would make git ignore them). Every git spawn passes `env: process.env` (Bun's default child env is a startup snapshot), so `GIT_CONFIG_*` overrides reach the child. A `core.hooksPath` of `/dev/null` in the clone's own (`--local`) config (a URL source a remote caller added: hooks off on purpose; a global or system value does not count; that one read runs with `gitChildEnv()` minus `GIT_CONFIG_GLOBAL`/`SYSTEM`/`NOSYSTEM`, so an inherited `GIT_DIR`, `GIT_WORK_TREE` or `GIT_CONFIG*` cannot redirect it) returns `skipped_hooks_off` before anything is written, `--force` included, `hooksPathBlocker` names it without wiring advice, and `inspectFrontmatterHook` returns null so doctor never proposes a refresh install-hook would skip. Any other blocker returns `installed_unwired` — the hook is written, `core.hooksPath` stays untouched, and the CLI prints the reason + the manual `git config core.hooksPath .githooks` step. Pinned by `test/frontmatter-install-hook.test.ts`.- `src/commands/doctor/checks/outside-content-fences.ts` — `outside_content_fences` (GBRA-221, BRAIN, registered before `fence_integrity`). Lists facts (`row_num` set, active; world-visible counted apart), active takes and `links_fence` links indexed from a fence on an imported page whose body is outside-authored text (Google `email`/`meeting` pages, every GitHub-source page, pages with `transcript_import` frontmatter). Reads the derived rows, never a page body, so segmented pages are covered. Before GBRA-221 a sender could plant such rows and a re-render carries a stored fence forward; gbrain writers also add rows on purpose, so it only lists pages (location and counts, never a cell value) with an `ask_user` review fix (`gbrain get`) and removes nothing.- `src/commands/doctor/checks/owner-host-stale.ts` + `src/commands/doctor/checks/embedding-plane.ts` — GBRA-248: doctor `owner_host_stale` (writes waiting on worktrees whose owner is stale per persistence/owner-activity.ts; fix is the read-only writer status) and `embedding_plane_disagreement` (the config file disables embeddings while the database does not and holds vectors; fix is `enableArgv` from core/readiness.ts for the stored model and width).diff --git a/docs/architecture/key-files/files-and-sync-2.md b/docs/architecture/key-files/files-and-sync-2.mdindex 253c9e1f1d..aa55f85b6f 100644--- a/docs/architecture/key-files/files-and-sync-2.md+++ b/docs/architecture/key-files/files-and-sync-2.md@@ -29,4 +29,5 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/persistence/sync-entry-fault.ts` — GBRA-133 (#6712 PR 4b): the per-entry faults of a managed sync freeze, so one odd file never stops its source. `nullBytesRefusal` holds a Markdown text with U+0000 `content_null_bytes` (line of the first NUL; a UTF-16 byte order mark says save as UTF-8), from `screenFrozenImport` with holds on and as a typed run stop under `sync.holds=fail`. `committedContentOrMissing` (called by `pinnedContent` when the pinned read fails) imports a committed file whose blob object is gone from working-tree bytes that hash to that blob id, else throws `git_object_missing`; a committed name with U+FFFD that names nothing on disk (a name that is not UTF-8) throws `path_not_utf8` first. `directoryAt` lets a deletion whose name became a directory apply (freeze and the owner's raw-hash check). `freezeFaultHold` is `freezeEntry`'s catch (`sync-run.ts` wraps `freezeEntryOnce`): `git_object_missing` and `path_not_utf8` are held under their codes; a page-body fault (`PAGE_BODY_FAULT_CODES`: `page_body_segmented`, `page_body_rows_unreadable`, e.g. a segmented page whose segment rows don't cover its body) is held `page_write_failed` with `write_failure.code` set to that code, which `sync status` classifies by the `freeze_page_body_*` rows of `SYNC_FAULT_TABLE`; any other `OperationError` and every run-scoped error (`classifyItemFailure` scope run, connection, statement timeout, lock, back-pressure, abort) rethrows, and an unexpected throw is held `page_write_failed` with `write_failure.origin: 'freeze'` and `request_id: null`, re-tested by every sync until held `HOLD_ATTEMPTS_NEEDS_HUMAN` times; a run with `ITEM_BREAKER_MIN_ITEMS` faults and no more clean freezes than faults is systemic and rethrows.- `src/core/url-clone.ts` — gbrain-owned `sources add --url` clones (#6946, GBRA-130 C-2). `isOwnedClone` (config `managed_clone` or a `local_path` under the default clone dir) and `defaultCloneDir`; `urlCloneReadOnly` is the one predicate (owned clone on a brain without managed persistence) the fence writer (`fence-write.ts`, `databaseOnlyReason: 'url_clone'`), write-through (`skipped: 'url_clone'`), timeline write-through, unfenced-facts adoption, the empty-fence guard and `sourceMirrorReadOnly` consult, so nothing gbrain writes lands in a checkout it updates with `git pull --ff-only`. `urlClonePullBlock` reads the tracked changes of a clone whose pull failed and returns `pull_blocked_local_changes` with an `ask_user` fix naming the preview `gbrain repair url-clone-fences --source <id>`; `formatUrlClonePullBlock` renders it for sync's stderr (`sync/preflight.ts`) and `cycle.ts` puts it in the sync phase detail as `pull_blocked`. Test: `test/pathological/c2-url-clone-fences.test.ts`.+- `src/core/url-source-origin.ts`, `src/commands/sources-record-origin.ts` and `src/commands/doctor/checks/url-source-origin.ts` — who added a URL source (`sources.config.added_by_remote_caller`). URL sources added before that record existed carry none, and nothing stored tells a remote caller's add from the local operator's (same row, same default clone directory); a clone outside `$GBRAIN_HOME/clones/<id>` (or a `clones/<id>` under an earlier home) proves a local add. `urlSourcesWithoutOrigin` (read-only) feeds the wave check `url_source_origin` (host-only, `resolution: 'operator'`, `warn` with an `ask_user` fix whose argv is the preview). `recordSourceOrigin(engine, ids, { origin, apply, remote })` backs `gbrain sources record-origin <id>... --remote|--local [--apply] [--json]`: it throws `trusted_local_only` unless `remote === false`, previews unless `apply`, writes `true` (`--remote`) or `false` (`--local`) in one transaction that re-reads the row `FOR UPDATE` and refuses `source_changed` if its path or URL moved, never removes a `true`, and refuses `--remote` for a checkout with any tracked `filter=lfs` path (`lfs_tracked`, read with `hardenedGitSync` `ls-files -- ':(attr:filter=lfs)'`) or one Git cannot list (`lfs_unknown`), because a lock-down reclone would not match the stored writer manifest there. Without git-lfs files the tracked bytes are the same, so no manifest is written. Pinned by `test/url-source-origin.test.ts` (PGLite and Postgres).- `src/core/write-through.ts` — shared atomic disk write-through for the canonical ingestion path. `resolvePageWriteTarget(engine, slug, sourceId, { includeDeleted? })` (active rows by default; `includeDeleted: true` resolves a tombstone's recorded `source_path` for the purge remediation retry) is the exported single source of truth for the ONE file a (source, slug) pair lives in on disk: a source with its own `local_path` writes at that tree's ROOT (never nested under `.sources/`); a source without one nests under the host repo (`sync.repo_path`, default at root, non-default under `.sources/<id>/`) unless that path is another source's own working tree (leak guard → `source_repo_belongs_to_other_source`; a live source whose `local_path` is relative counts as owning every tree, and a relative `local_path` or `sync.repo_path` target is `repo_not_found`); the page's recorded `source_path` (or a contained absolute `file://` `source_uri`; a relative or host-only `file://` names no local file and is read as absent) is preferred over a slug-derived name so writes land in the file of record instead of minting a twin; and `isWriteTargetContained` rejects hostile rows escaping the tree (`path_escapes_source_root`). The ok-result also carries `sourcePathToBind` — the target expressed in the file scanner's `source_path` convention for the source's pinned `slug_root_mode` (or the mode its first sync would pin, via `scannerSlugRootMode`): GIT-ROOT-relative under `git-root` when the scan root sits inside a git repo, scan-root-relative under `source-root` and for non-git or git-root scan roots, so a put-born page binds the same form managed sync and delete-reconcile key on. Every recorded-path reader (write targets, takes, reconcile, audit, export restore, doctor) decodes with the same mode (`resolveSourceLocalFilePath(..., slugRootMode)`): under `source-root` the scope prefix is removed only from the legacy Git-root form whose remainder names the page slug, and basename rows resolve under the unstripped slug directory. The resolver is shared by `writePageThrough`, the facts fence writer (`src/core/facts/fence-write.ts`), and fence forget (`src/core/facts/forget.ts`) — the fence appends to the page's file, so all writers MUST compute the identical path or the fence lands in a file sync never reads back and the next extract_facts reconcile deletes the fence-owned DB rows. `writePageThrough(engine, slug, {sourceId?, frontmatterOverrides?, inlineOnly?, logger?, expectedFileBytes?, deferCommit?})` resolves the target through it, re-reads the just-written DB row (`getPage`), renders an inline page via `serializePageToMarkdown`, and writes the `.md`. A page stored in segments is never rendered whole: its file is measured from its segments at the snapshot's revision (`unreadPageFile`; a page that moved since refuses `revision_conflict`), checked against `PUSH_SCAN_MAX_FILE_BYTES` before `source_path` is bound (a body already over the cap by `body_bytes` is refused without streaming), streamed through `stageStreamedContent` on the engine it was given (so a caller inside a transaction works) keeping the existing file's mode, and renamed over the target after the file-changed check; `frontmatterOverrides` on such a page return an error result, and `inlineOnly` (the derived writer) skips it as `segmented_page` so the brain has a committable artifact that round-trips through `gbrain sync`. Rendering from the row keeps the serialized content consistent at write time. The fsync-backed `atomicWriteFileSync` stages and renames the file after required source-path bookkeeping; lock/lease checks run before publication. `put_page` holds the root lock before importing and invokes write-through inside its database transaction, so ordinary filesystem rejection rolls back existing content, tags, chunks, and versions. A crash or database COMMIT failure after rename can still leave canonical Markdown ahead of the index; this is not distributed ACID or a durable queue. Never throws — returns `WriteThroughResult { written, path?, content? (the bytes written; inline pages only), skipped?: 'disabled_by_config' | 'url_clone' | 'no_repo_configured' | 'repo_not_found' | 'source_repo_belongs_to_other_source' | 'page_not_found_after_write' | 'path_escapes_source_root' | 'case_insensitive_collision' | 'file_changed' | 'over_push_scan_cap' | 'segmented_page', warning?, error? }` (`file_changed`: the caller's `expectedFileBytes` preimage, null for absent, no longer matches the file under the source filesystem lock, so the file is left untouched) so the caller decides messaging + exit codes. `withNoRepoWriteThroughWarning(result, sourceId)` decorates an unwritten `no_repo_configured` result with `warning` (the write landed only in the database; bind the token/server to a git-backed source or configure `local_path`/`sync.repo_path`); `put_page` applies it for untrusted callers only (`ctx.remote !== false`), so local CLI responses and the `disabled_by_config` operator opt-out stay silent. `isWriteThroughDisabled` (shared with the fence lane, ~30s per-engine cache) honors the `sync.write_through` opt-out. Trust gating (subagent sandbox, dry-run) stays at the CALLER. On a durability-hardened repo (`isDurabilityHardened` — the gbrain post-commit hook is installed, i.e. the user ran `gbrain sources harden`), a successful write is best-effort COMMITTED via `commitWriteThroughFile` (path-limited `git commit -- <file>`, never sweeps unrelated edits; the hook then background-pushes) unless the caller passes `deferCommit` (the derived write-through commits its batch itself, #8073; `deletePageThrough` takes it too) so write-through content reaches git instead of accumulating uncommitted forever; result carries `committed?: boolean`. Unhardened repos keep write-only behavior. `deletePageThrough(engine, slug, {sourceId?, target?, logger?})` is the delete-side sink (sole caller: the `delete_page` op): resolves the same target, unlinks the `.md`, and on a hardened repo best-effort commits the removal path-limited through the same helper with subject `gbrain: delete write-through <slug>`, reporting `committed?: boolean` on `DeleteThroughResult` (absent when unhardened or when the commit did not land — the unlink still stands; a never-committed page leaves nothing to commit, so no empty commit). Pinned by `test/delete-write-through-commit.test.ts`. Consumers: `put_page` op and `gbrain brainstorm/lsd --save` via `persistSavedIdea`. Pinned by `test/write-through.test.ts` + `test/write-through-commit.test.ts`. The `put_page` op is that deciding caller for direct writes: a skip outside the deliberate DB-only set (`no_repo_configured`/`disabled_by_config`/`subagent_sandbox`/`dry_run`) throws `storage_error` inside the import transaction, rolling back the page revision, tags, chunks and version snapshot instead of deleting a just-created row afterward. #6946: on a gbrain-owned `--url` clone of an unmanaged brain (`urlCloneReadOnly`), `writePageThrough` returns `skipped: 'url_clone'` and `deletePageThrough` returns `removed: false, skipped: 'url_clone'`; `timeline-write-through.ts` skips the same way.diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 7eb5cce7dc..7e89fb06c8 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -2763,6 +2763,54 @@ since the preview. Preview again and approve the new hash. Undo by copying the bthe file. It is explicit-only and never runs from `--all`, doctor'sremediation plan, the maintenance cycle or an upgrade.+<a id="url-source-origin"></a>+### URL source origin++A URL source a remote caller (an MCP client) adds records that on its row, and+every later reclone of it, managed or not, clones with git-lfs downloads and+hooks off. URL sources added before that record existed carry none, and nothing+stored tells a remote caller's add from the local operator's: both wrote the+same row and cloned into the default clone directory (`$GBRAIN_HOME/clones/<id>`).+Their reclones use the clone settings of a local add. Doctor+`url_source_origin` (read-only, `warn`) lists them and says it cannot tell who+added them. A clone outside the default directory is not listed: only the local+CLI can choose that directory. A brain with no URL sources, such as a fresh+keyless brain, has nothing to list.++**Say to your agent:** *"Show me the URL sources gbrain can't place, and record+the ones I say a remote caller added."*++```bash+gbrain doctor --only url_source_origin --json # lists the sources, asks who added them+gbrain sources record-origin <id>... --remote # preview: would_record / refused, writes nothing+gbrain sources record-origin <id>... --remote --apply # records the ids the user named+gbrain sources record-origin <id>... --local --apply # records the rest as local adds+```++`--remote` writes the same record a remote add writes, so the next reclone+clones with git-lfs downloads and hooks off; `--local` records a local add, and+doctor stops listing either. Each apply re-reads the source inside one+transaction and refuses `source_changed` if it moved since the check. Without+git-lfs files a clone with these settings holds the same tracked bytes, so the+stored writer manifest needs no change and the reclone verifies as before.+`--remote` refuses, writing nothing:++- `lfs_tracked`: the checkout tracks files with git-lfs (any tracked path with+ `filter=lfs`). A clone with git-lfs downloads off holds pointer files where+ this checkout holds their content, so its next reclone would stop at+ `writer_manifest_mismatch`, and converting the checkout rewrites its files,+ which this command does not do. If the source should not keep those files,+ check that nothing in its checkout is unpushed or only local, then remove it+ with `gbrain sources remove <id> --confirm-destructive`.+- `lfs_unknown`: the checkout is missing or Git cannot list it, so gbrain+ cannot confirm it has no git-lfs files. Restore the checkout and run it again.+- `custom_clone_dir`: the clone sits where only the local CLI can clone.+- `recorded_remote` (`--local`): the source is already recorded as a remote+ add; this command never removes that record.++It runs only from the trusted local CLI on the brain host; no MCP operation+reaches it, and nothing records an origin on upgrade.+<a id="file-drift"></a>### File driftdiff --git a/docs/integrations/pre-commit.md b/docs/integrations/pre-commit.mdindex 52b535aecf..e3510c6980 100644--- a/docs/integrations/pre-commit.md+++ b/docs/integrations/pre-commit.md@@ -73,9 +73,10 @@ contains a line terminator; refusing to install hook`), or `.githooks/` /— the installer never writes or removes through the link; the other sourcesstill install). A clone whose own (`--local`) config sets `core.hooksPath` to`/dev/null` (a URL source a remote caller added: hooks off on purpose) is also-skipped (`skipped — hooks are off in this clone on purpose …`) with nothing+skipped (`skipped — hooks are off in this clone's own config …`) with nothingwritten, `--force` included; a global or system `/dev/null` value does not-count.+count, and neither do inherited `GIT_DIR`, `GIT_WORK_TREE` or `GIT_CONFIG*`+variables.## Bypassdiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 753b73979d..9f765989fe 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -30,7 +30,7 @@ src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connesrc/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)src/commands/bootstrap.ts 2154 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags); +13 #4082: runAdoptHooks (the --adopt branch of the hooks subcommand, kept out of runHooks for the function-size ratchet) and its two help lines (adoption logic lives in core/bootstrap/adopt-connection.ts + adopted-connections.ts); +4 #8426/#8428: the user-scope MCP registration, its verify and the workspace and Codex SessionEnd hooks start gbrain through the hook launcher (logic in core/setup/hook-launcher.ts); +2 #8435: the user-global opencode entry starts serve through the hook launcher (logic in core/setup/hook-launcher.ts); +1 GBRA-224: INSTALL_PIN import (core/install-ref.ts; re-summed at the GBRA-346 merge: master 2153 + 1)src/core/minions/worker.ts 1795 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry; +9 Lane D: JobDeferredError routing (deferJob helper); +1 spend authorization: runWithJobSpend import (both handler seams call it in place of the bare handler); +3 watchdog: gracefulShutdown records its reason and launchJob aborts a claim committed before it fired; +5 GBRA-130 A-30: watchdog-attribution import, InFlightJob.shared (interface field), the suspect-alone claim gate and option, and the watchdog settle call in the executeJob catch (logic in minions/watchdog-attribution.ts); +6 GBRA-133 2a.4 sync-queue wake: IdleWaiter import and field, claimStarted before each claim, the idle poll through it, and stop/requestShutdown ending its wait (logic in minions/idle-wait.ts); +1 GBRA-158 #7239: refusal.ts import (a deterministic refusal ends the job at once; classification in minions/refusal.ts); +3 #7242 lane reservation: lanes import and the longJobNames/shortJobReservedSlots defaults (the claim passes claimExclusions; policy in minions/lanes.ts); +2 #7242 terminal hook: onJobSettled default and the settle call (logic in terminal-hook.ts); #7252 x #7249 merge: both sides grew the file, re-summed (1794 measured); GBRA-151 #7183/#7187/#7188 re-summed at the v0.60.402.0 merge (1795 measured)-src/commands/sources.ts 2113 ratchet +3 PR B: sources guard dispatch and help rows (body in sources-guard.ts); +3 G7b-2: sources host-repo dispatch and help row (body in sources-host-repo.ts and core/persistence/hosted-repo.ts); +5 PR #5955 / fix wave 14 P2.7: sources set-strategy dispatch and help row, the strategy field of sources list --json (body in sources-strategy.ts); +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row; +1 GBRA-133: sources reset-upstream help row (body in sources-reset-upstream.ts); fix wave 20 integration: lane 3 (#6827) and master growth compose at 2062 measured; +3 GBRA-150: sources resolve-path dispatch and help rows (body in sources-resolve-path.ts); +10 #7326: sources status parses --holds/--limit/--cursor and passes the git_holds listing mode, plus 4 help lines (bounding logic in persistence/connector-status.ts gitHoldStatusJson); +2 GBRA-133 Q1: sources set-sync dispatch and help row (body in sources-sync-enabled.ts); +4 G1 git-canonical: sources git-gap dispatch, doc line and help rows (body in sources-git-gap.ts); +4 G3 git-canonical: sources reindex dispatch, doc line and help rows (body in sources-reindex.ts); +1 GBRA-156: the sources add non-federated warning line; re-summed at the master 33d73cb5 merge (2086 measured); +4 G8a git-canonical: sources canonical dispatch, doc line and help rows (body in sources-canonical.ts, plan and apply in persistence/git-conversion.ts); GBRA-156: sources add --json and its next step (logic in sources-add-next.ts); re-summed at the master ade6d638 merge (2100 measured); +2 GBRA-220 PR 2: the unmanaged sources add routes --kind meetings|slack to the shared lifecycle parser (body in sources-add-api.ts); re-summed at the master b85dd645 merge (2102 measured); +2 #7701: the archived field of SourceListEntry and its list entry (sources list now marks archived sources; an interface field cannot move): re-summed at the 0.60.583.0 merge: 2102 + 2; +1 GST-1113: sources federate refuses a QM scope source (one line; the check lives in core/access/attest-sources.ts), re-summed at the 0.60.594.0 gate-ahead: 2107 + 1; +5 GST-1113 /ship fix round: sources federate checks the scope mark and writes the config in one transaction under the source row lock (the check lives in core/access/attest-sources.ts)+src/commands/sources.ts 2116 ratchet +3 url_source_origin: sources record-origin dispatch and help rows (body in sources-record-origin.ts, logic in core/url-source-origin.ts); +3 PR B: sources guard dispatch and help rows (body in sources-guard.ts); +3 G7b-2: sources host-repo dispatch and help row (body in sources-host-repo.ts and core/persistence/hosted-repo.ts); +5 PR #5955 / fix wave 14 P2.7: sources set-strategy dispatch and help row, the strategy field of sources list --json (body in sources-strategy.ts); +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row; +1 GBRA-133: sources reset-upstream help row (body in sources-reset-upstream.ts); fix wave 20 integration: lane 3 (#6827) and master growth compose at 2062 measured; +3 GBRA-150: sources resolve-path dispatch and help rows (body in sources-resolve-path.ts); +10 #7326: sources status parses --holds/--limit/--cursor and passes the git_holds listing mode, plus 4 help lines (bounding logic in persistence/connector-status.ts gitHoldStatusJson); +2 GBRA-133 Q1: sources set-sync dispatch and help row (body in sources-sync-enabled.ts); +4 G1 git-canonical: sources git-gap dispatch, doc line and help rows (body in sources-git-gap.ts); +4 G3 git-canonical: sources reindex dispatch, doc line and help rows (body in sources-reindex.ts); +1 GBRA-156: the sources add non-federated warning line; re-summed at the master 33d73cb5 merge (2086 measured); +4 G8a git-canonical: sources canonical dispatch, doc line and help rows (body in sources-canonical.ts, plan and apply in persistence/git-conversion.ts); GBRA-156: sources add --json and its next step (logic in sources-add-next.ts); re-summed at the master ade6d638 merge (2100 measured); +2 GBRA-220 PR 2: the unmanaged sources add routes --kind meetings|slack to the shared lifecycle parser (body in sources-add-api.ts); re-summed at the master b85dd645 merge (2102 measured); +2 #7701: the archived field of SourceListEntry and its list entry (sources list now marks archived sources; an interface field cannot move): re-summed at the 0.60.583.0 merge: 2102 + 2; +1 GST-1113: sources federate refuses a QM scope source (one line; the check lives in core/access/attest-sources.ts), re-summed at the 0.60.594.0 gate-ahead: 2107 + 1; +5 GST-1113 /ship fix round: sources federate checks the scope mark and writes the config in one transaction under the source row lock (the check lives in core/access/attest-sources.ts)src/core/link-extraction.ts 2424 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at; +1 fix wave 11 #6191: imports targetTakesVerb (role-verb target guard lives in link-target-roles.ts); v0.60.105.0 merge: #5984 Phase 5 link preparation (+6) re-summed over wave 11 at 2211; +109 Q2 Track C: stable verb-rule ids, traceLinkType/explainLinkType (reasons for every typing decision), per-occurrence typer hoisted out of extractPageLinks (makeTypeFor); unit logic lives in core/link-typing-units.ts; +25 Q2 Track C: typing-unit verb rules and vetoes in attachedVerb/traceLinkType, validity stints in explainLinkType; +4 U3: board-seat rule split out of INVESTED_RE (same verb and precedence) and investor-prior/link offsets passed to unit vetoes; +11 U2: locateLink shared by attachedVerb and the U2 post-pass in traceLinkType; -11 lowered: Q2 verdict reverted U2 (locateLink and the post-pass); +21 fix wave 13 P4.10 #6266: resolveSameDirSlug + exported resolveMarkdownLinkSlug, shared with the link validator; +41 Wave B PR 2 lane 2e: extractPageLinks split into extractBodyLinks (window-scoped, offset-shifted, pass-tagged candidates) and frontmatterLinks, plus entityRefPasses, candidateKey, rolePriorPhrases and the roleText/regexBudget/window options, so a segmented page streams through the same extractor (window and merge logic in core/page-body/segment-links.ts); +1 at the #6869 gate-ahead merge: the #6803 wave EXTRACTOR_BUMP_NOTES comment composed with lane 2e (2420 + 1); +3 G5 (GBRA-60): extractBodyLinks masks the ## Links fence (links-fence.ts), whose rows are projected as their own edgessrc/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify; +17 #5334: smoke check samples one representative chunk per distinct page (bounded index-ordered batch walk, longest chunk re-read under the page lock, title-prefixed bounded query); +1 #5334: the smoke-query length limits are shared with the worst-case budgetsrc/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh@@ -47,4 +47,4 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: linksrc/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/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 1680 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+src/core/behavior-change-notice.ts 1681 ratchet +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move); +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 + 6diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 92c95c796d..399892acc2 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -201,7 +201,7 @@ test/fix-wave-structural.test.ts v0.41.8.0 #1340 — PGLite WASM init classifiertest/fix-wave-structural.test.ts v0.42.20.0 — background-work registry drains every sink before disconnect 9 readFileSync,source-surface-helpertest/fix-wave-structural.test.ts v0.42.20.0 — search-cache drained via the background-work registry 1 source-surface-helpertest/fix-wave-structural.test.ts v0.42.43.0 #2095 — volunteer-events sink + cycle purge wiring (structural pins) 2 readFileSync,source-surface-helper-test/frontmatter-install-hook.test.ts frontmatter install-hook (B13) 28 readFileSync+test/frontmatter-install-hook.test.ts frontmatter install-hook (B13) 30 readFileSynctest/fts-cjk-boundary.test.ts one copy of the DDL 2 readFileSynctest/gbrain-owned-page-types.test.ts #5881 gbrain-owned page types are declared by gbrain-base-v2 3 readFileSynctest/get-page-federated-scope.test.ts #2555 get_chunks federated scope 5 source-surface-helperdiff --git a/src/commands/doctor/checks/graph-health.ts b/src/commands/doctor/checks/graph-health.tsindex 671901e904..c70069ed61 100644--- a/src/commands/doctor/checks/graph-health.ts+++ b/src/commands/doctor/checks/graph-health.ts@@ -373,6 +373,7 @@ export const timelineHistoryEntry: DoctorEntry = {'connector_held_items','git_held_files','frontmatter_hook',+ 'url_source_origin','orphan_persistence_bindings','foreign_ownership_marker','coordination_lock_location',diff --git a/src/commands/doctor/checks/url-source-origin.ts b/src/commands/doctor/checks/url-source-origin.tsnew file mode 100644index 0000000000..af4109b435--- /dev/null+++ b/src/commands/doctor/checks/url-source-origin.ts@@ -0,0 +1,28 @@+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { doctorVerify } from '../check-fix.ts';++/**+ * Active URL sources in the default clone directory with no record of who added them (`url-source-origin.ts`).+ * Read-only. gbrain cannot tell a remote caller's add from the local operator's for these, so the fix asks the user+ * and points at `gbrain sources record-origin`, whose preview changes nothing.+ */+export async function urlSourceOriginCheck(engine: BrainEngine): Promise<Check> {+ const { urlSourcesWithoutOrigin, recordOriginArgv, RECORD_ORIGIN_DOCS } = await import('../../../core/url-source-origin.ts');+ try {+ const sources = await urlSourcesWithoutOrigin(engine);+ const ids = sources.map(source => source.id);+ const details = { count: sources.length, sources, docs: RECORD_ORIGIN_DOCS };+ if (!sources.length) return { name: 'url_source_origin', status: 'ok', message: 'Every URL source clone records who added it, or was cloned where only the local CLI can clone.', details };+ return { name: 'url_source_origin', status: 'warn', details,+ message: `${sources.length} URL source(s) have no record of who added them: ${ids.join(', ')}. gbrain cannot tell whether a remote caller or the local operator added each one, `+ + `so their reclones use the clone settings of a local add. Ask the user which ones a remote caller added, preview with ${recordOriginArgv(['<id>...'], 'remote').join(' ')} `+ + '(or --local for the rest), then add --apply.',+ fix: { ask_user: true, argv: recordOriginArgv(ids, 'remote'), consent: [], actor: 'agent', requires_exclusive: false, docs: RECORD_ORIGIN_DOCS, verify: doctorVerify('url_source_origin'),+ why: 'Previews recording these sources as added by a remote caller and changes nothing; drop the ids the user says were added locally and record those with --local.',+ user_message: `gbrain cannot tell who added these URL sources: ${ids.join(', ')}. Which of them did a remote caller (an MCP client) add? Those get the clone settings sources added by remote callers get today; the rest are recorded as yours.` } };+ } catch (error) {+ return { name: 'url_source_origin', status: 'warn', fix_unavailable_reason: 'check_errored', details: { count: 'unknown' },+ message: `URL source origins could not be read: ${error instanceof Error ? error.message : String(error)}. Health is unknown.` };+ }+}diff --git a/src/commands/doctor/wave-checks.ts b/src/commands/doctor/wave-checks.tsindex 2b5b335f82..126810d030 100644--- a/src/commands/doctor/wave-checks.ts+++ b/src/commands/doctor/wave-checks.ts@@ -179,6 +179,14 @@ export const WAVE_CHECKS: readonly WaveCheckSpec[] = [instruction: 'Refresh it on the brain host with `gbrain frontmatter install-hook --force` (add `--source <id>` for one source); only the gbrain hook script is rewritten.',run: async (engine, scope) => (await import('./checks/frontmatter-hook.ts')).frontmatterHookCheck(engine, scope.sourceIds),},+ {+ id: 'url_source_origin', resolution: 'operator', registration: 'wave',+ hostOnly: 'Which caller added a source is a decision only the brain host operator can record.',+ count: d => Number(d.count ?? 0),+ impact: 'Some URL source clones have no record of who added them, so their reclones use the clone settings of a local add',+ instruction: 'Ask the user which of the listed sources a remote caller added; on the brain host, preview `gbrain sources record-origin <id>... --remote` (`--local` for the rest), then rerun it with --apply.',+ run: async engine => (await import('./checks/url-source-origin.ts')).urlSourceOriginCheck(engine),+ },{id: 'orphan_persistence_bindings', resolution: 'repair', registration: 'wave',hostOnly: 'Bindings of removed sources are brain-wide persistence bookkeeping outside any source scope.',diff --git a/src/commands/frontmatter-install-hook.ts b/src/commands/frontmatter-install-hook.tsindex 4f0121bbd7..03ab59afbe 100644--- a/src/commands/frontmatter-install-hook.ts+++ b/src/commands/frontmatter-install-hook.ts@@ -37,6 +37,7 @@ import type { BrainEngine } from '../core/engine.ts';import { loadConfig, toEngineConfig } from '../core/config.ts';import { createEngine } from '../core/engine-factory.ts';import { discoverGitRoot } from '../core/sync-git.ts';+import { gitChildEnv } from '../core/git-env.ts';const HOOK_BANNER = '# gbrain frontmatter pre-commit hook (v0.22.4+)';/** One line per guarded subdirectory (root-relative, trailing slash). No lines = whole repo. */@@ -406,10 +407,16 @@ function currentHooksPath(root: string): string {}}-/** The clone's own config turns hooks off (LFS_OFF_CLONE_CONFIG on a URL source a remote caller added); a global or system value does not count. */+/**+ * The clone's own config turns hooks off (LFS_OFF_CLONE_CONFIG); a global or system value does not count. Read with+ * the repository-locating and config variables scrubbed, so an inherited GIT_DIR, GIT_WORK_TREE or GIT_CONFIG* cannot+ * point the read at another repository or config file.+ */function hooksOffInClone(root: string): boolean {+ const env = gitChildEnv();+ delete env.GIT_CONFIG_GLOBAL; delete env.GIT_CONFIG_SYSTEM; delete env.GIT_CONFIG_NOSYSTEM;try {- return git(root, ['config', '--local', '--get', 'core.hooksPath']) === HOOKS_OFF;+ return execFileSync('git', ['-C', root, 'config', '--local', '--get', 'core.hooksPath'], { encoding: 'utf8', env }).trim() === HOOKS_OFF;} catch {return false;}@@ -429,7 +436,7 @@ const samePath = (a: string, b: string): boolean => {* `.githooks/<hook>` or a live `.git/hooks/<hook>` both block it too.*/export function hooksPathBlocker(root: string): string | null {- if (hooksOffInClone(root)) return `hooks are off in this clone on purpose (core.hooksPath=${HOOKS_OFF}, set on a source a remote caller added by URL), and gbrain leaves them off`;+ if (hooksOffInClone(root)) return `hooks are off in this clone's own config (core.hooksPath=${HOOKS_OFF}), and gbrain leaves them off`;const current = currentHooksPath(root);if (current) {// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- fixed literal tail under the discovered git rootdiff --git a/src/commands/sources-record-origin.ts b/src/commands/sources-record-origin.tsnew file mode 100644index 0000000000..ad7134f275--- /dev/null+++ b/src/commands/sources-record-origin.ts@@ -0,0 +1,28 @@+/**+ * `gbrain sources record-origin <id>... --remote|--local [--apply] [--json]`: record who added older URL sources+ * (`url-source-origin.ts`), for the ids the operator names. Preview unless --apply; exit 1 when any id is refused,+ * 2 on a usage error. Trusted local CLI only; no MCP operation reaches it.+ */+import type { BrainEngine } from '../core/engine.ts';+import { setCliExitVerdict } from '../core/cli-force-exit.ts';+import { recordSourceOrigin, type SourceOrigin } from '../core/url-source-origin.ts';++const USAGE = 'Usage: gbrain sources record-origin <id>... --remote|--local [--apply] [--json]';++export async function runRecordOrigin(engine: BrainEngine, args: string[]): Promise<void> {+ const ids = args.filter(arg => !arg.startsWith('-'));+ const flags = args.filter(arg => arg.startsWith('-'));+ const origins = flags.filter(flag => flag === '--remote' || flag === '--local');+ if (!ids.length || origins.length !== 1 || flags.some(flag => !['--remote', '--local', '--apply', '--json'].includes(flag))) {+ console.error(USAGE);+ process.exit(2);+ }+ const report = await recordSourceOrigin(engine, ids, { origin: origins[0]!.slice(2) as SourceOrigin, apply: flags.includes('--apply'), remote: false });+ if (flags.includes('--json')) console.log(JSON.stringify(report, null, 2));+ else {+ for (const result of report.results) console.log(`[${result.source_id}] ${result.status}${result.code ? ` (${result.code})` : ''}: ${result.reason}`);+ if (!report.apply && report.results.some(result => result.status === 'would_record'))+ console.log(`(preview; nothing changed) Apply with: gbrain sources record-origin ${report.results.filter(result => result.status === 'would_record').map(result => result.source_id).join(' ')} --${report.origin} --apply`);+ }+ if (report.results.some(result => result.status === 'refused')) setCliExitVerdict(1);+}diff --git a/src/commands/sources.ts b/src/commands/sources.tsindex 0989fde8c7..0f2bba8dc7 100644--- a/src/commands/sources.ts+++ b/src/commands/sources.ts@@ -1924,6 +1924,7 @@ export async function runSources(engine: BrainEngine, args: string[]): Promise<vcase 'federate': return runFederate(engine, rest, true);case 'unfederate': return runFederate(engine, rest, false);case 'mirror-readonly': case 'mirror-writable': return (await import('./sources-mirror.ts')).runMirrorMode(engine, rest, sub === 'mirror-readonly');+ case 'record-origin': return (await import('./sources-record-origin.ts')).runRecordOrigin(engine, rest);case 'set-strategy': return (await import('./sources-strategy.ts')).runSetStrategy(engine, rest);case 'set-pull-strategy': return (await import('./sources-pull-strategy.ts')).runSetPullStrategy(engine, rest);case 'set-sync': return (await import('./sources-sync-enabled.ts')).runSetSync(engine, rest);@@ -2030,6 +2031,8 @@ Subcommands:unfederate <id> Isolate source from default search.mirror-readonly <id> [--dry-run] Read-only mirror (#5409): managed writes never touch its checkout.mirror-writable <id> [--dry-run] Undo mirror-readonly. --dry-run previews either and writes nothing.+ record-origin <id>... --remote|--local [--apply] [--json]+ Record who added older URL sources (doctor url_source_origin); preview unless --apply.set-strategy <id> <markdown|code|auto> Persist the sync strategy every sync of the source uses (PR #5955).set-pull-strategy <id> <rebase|merge> How pulls reconcile local commits with origin (#5429); default rebase.set-sync <id> <on|off> [--dry-run] [--expect <on|off>] Include or exclude the source from automatic sync (config.syncEnabled).diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex d4fc1e147c..b863e9411a 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1482,6 +1482,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.611.0', id: 'adopt_local_edits_hardening_8755', text: 'With `persistence.adopt_local_edits` on for a source (off by default), a local edit is no longer adopted, and the write keeps its `file_database_drift` refusal, when its path has merge conflicts, while a merge, cherry-pick, revert or rebase is in progress, when the file equals one of the page\'s last 50 revisions or drops rows the current revision added (a stale editor save), when the page is segmented, or when the write\'s claim ended meanwhile. The quiet wait is capped at 30 s (it was up to three `persistence.adopt_quiet_ms` windows, 180 s at that key\'s cap), and an empty `persistence.adopt_quiet_ms` reads as the 5000 default instead of no wait. Doctor `local_edit_adoptions` still counts an adoption after its receipt is compacted.' },{ since: '0.60.611.0', id: 'managed_sync_kind_reserved_8765', text: 'A page write that passes a `kind` starting with `managed_sync_` (for example `capture` with `kind: managed_sync_import`) is now refused `invalid_params` and writes nothing: that prefix is reserved for managed sync, and with `persistence.refresh_barrier` on a waiting write now tells sync\'s own imports apart from later writes by the operation that wrote them, not by the kind. Use another kind, or drop `kind`.' },{ since: '0.60.608.0', id: 'refresh_barrier_later_write_gst1623', text: 'With `persistence.refresh_barrier` on, a write that waited behind a refresh or an import (other than a `remember` or `add_timeline_entry`, which still applies on top) now ends `revision_conflict` instead of applying when a later write to the same page committed first, which a consumer from an older release can cause; read the page again and resubmit with a new `request_id`. A write held again and again behind imports now expires once it has waited four wait limits (at least 4 hours) since its admission, even when each hold is shorter than one wait limit. With the barrier on or off, a plain-git commit that lands on the start commit right before a refresh merges makes git refuse the fast-forward, and the refresh now ends `refresh_source_changed` with the fence lifted and the commit kept, instead of leaving the checkout `recovery_required`; one that lands right after the merge is recorded and synced.' },+ { since: 'TBD', id: 'url_source_origin', text: 'New doctor check `url_source_origin` (warn) lists URL sources in the default clone directory with no record of who added them, which is every URL source added before that record existed: gbrain cannot tell whether a remote caller or the local operator added each one, so their reclones use the clone settings of a local add. `gbrain sources record-origin <id>... --remote|--local` records the answer the user gives, as a preview until `--apply`, on the brain host only. `--remote` gives the source the clone settings a remote add gets (git-lfs downloads and hooks off on every later reclone) and refuses a checkout that tracks git-lfs files or cannot be inspected. Nothing changes on upgrade.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex d41e26eeb2..28963dab16 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -52,7 +52,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'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-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', '--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', '--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', '--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'],+ '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', '--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', '--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'],'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'],@@ -78,14 +78,14 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--request-id', '--source', '--type'],'hook': ['--allow-unverified-remote', '--auto', '--batch-check', '--brain', '--branch', '--cached', '--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'],'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': ['--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-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', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retire', '--retry-failed', '--retry-parked', '--runtime', '--save', '--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', '--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': ['--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', '--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', '--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', '--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-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'],'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', '--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', '--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'],+ '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'],'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'],@@ -115,7 +115,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'repair': ['--accept-pending', '--acknowledge-managed', '--after', '--all', '--all-drifted', '--apply', '--as', '--auto-additive', '--background', '--brain', '--break-lock', '--class', '--client', '--close', '--cursor', '--cwd', '--day', '--diff', '--expect', '--explain', '--ff-only', '--follow', '--force', '--force-break-lock', '--from', '--full', '--full-history', '--generation', '--held', '--help', '--id', '--include-ambiguous', '--include-cross-entity', '--include-failures', '--include-repairs', '--json', '--keep', '--key', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--mode', '--no-accept-pending', '--no-delegate', '--no-embed', '--no-llm', '--older-than', '--only', '--prefer', '--principal', '--probe', '--progress-interval', '--progress-json', '--provenance', '--quiet', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--rules', '--run', '--scopes', '--seat', '--session', '--side', '--since', '--skip', '--skip-failed', '--slug', '--slugs', '--source', '--stale', '--state', '--timeout', '--timings', '--url', '--wait', '--yes'],'repair-jsonb': ['--accept-pending', '--as', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--timings', '--url', '--wait'],'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],- 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--approval-out', '--approved', '--attest-actor', '--attest-ops', '--attest-sources', '--audit', '--auto-additive', '--autostash', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--config', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--install', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--limit', '--list-out', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--may-act-for', '--member', '--message', '--migrate-legacy', '--migration', '--min-trust', '--mode', '--name', '--name-only', '--no-autostash', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operation', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--private-pages', '--probe', '--profile', '--pull', '--push-only', '--push-remote', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retire', '--retry-failed', '--sample', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--to', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--uninstall', '--unset-all', '--unsettle', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],+ 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--approval-out', '--approved', '--attest-actor', '--attest-ops', '--attest-sources', '--audit', '--auto-additive', '--autostash', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--config', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--install', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--limit', '--list-out', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--may-act-for', '--member', '--message', '--migrate-legacy', '--migration', '--min-trust', '--mode', '--name', '--name-only', '--no-autostash', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operation', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--private-pages', '--probe', '--profile', '--pull', '--push-only', '--push-remote', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remote', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retire', '--retry-failed', '--sample', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--to', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--uninstall', '--unset-all', '--unsettle', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],'resolvers': ['--backend', '--brain', '--cost', '--help', '--json', '--source'],'retrieval-upgrade': ['--accept-pending', '--all', '--as', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--plan', '--priority', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--timings', '--to', '--wait', '--yes'],'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],@@ -129,11 +129,11 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--probe', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--version', '--workspace', '--yes'],'skillpack-check': ['--accept-pending', '--as', '--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--strict', '--timeout', '--timings', '--wait', '--yes'],'smoke-test': ['--brain', '--help', '--json', '--source'],- 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--approval-out', '--approved', '--as', '--attest-actor', '--attest-ops', '--attest-sources', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--channels', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--config', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--install', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--legacy-lock', '--limit', '--list-out', '--local', '--local-env-vars', '--lookback-days', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--max-requests', '--may-act-for', '--member', '--message', '--migrate-legacy', '--migration', '--min-trust', '--mode', '--name', '--name-only', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operation', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--private-pages', '--probe', '--profile', '--progress-interval', '--progress-json', '--provider', '--pull', '--push-only', '--push-remote', '--quiet', '--read-sources', '--rebase', '--record', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retire', '--retry-failed', '--sample', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--skip', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--sync-interval-min', '--takes-holders', '--timeout', '--timezone', '--timings', '--to', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--transcript', '--unindexed', '--uninstall', '--unset-all', '--unsettle', '--untracked-files', '--url', '--usage', '--verify', '--visibility', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],+ 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--approval-out', '--approved', '--as', '--attest-actor', '--attest-ops', '--attest-sources', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--channels', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--config', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--install', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--legacy-lock', '--limit', '--list-out', '--local', '--local-env-vars', '--lookback-days', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--max-requests', '--may-act-for', '--member', '--message', '--migrate-legacy', '--migration', '--min-trust', '--mode', '--name', '--name-only', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operation', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--private-pages', '--probe', '--profile', '--progress-interval', '--progress-json', '--provider', '--pull', '--push-only', '--push-remote', '--quiet', '--read-sources', '--rebase', '--record', '--redirect-uri', '--refresh-operations', '--remote', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retire', '--retry-failed', '--sample', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--skip', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--sync-interval-min', '--takes-holders', '--timeout', '--timezone', '--timings', '--to', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--transcript', '--unindexed', '--uninstall', '--unset-all', '--unsettle', '--untracked-files', '--url', '--usage', '--verify', '--visibility', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--check', '--code', '--concurrency', '--confirm-destructive', '--count', '--cursor', '--deadline-ms', '--delete', '--detail', '--diff-filter', '--empty', '--enable', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--funnel', '--hard-deadline', '--help', '--hold-state', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--limit', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--others', '--parallel', '--path', '--prefer', '--preview', '--priority', '--quiet', '--redact-paths', '--repo', '--request-id', '--reset-checkpoint', '--retry-failed', '--retry-held', '--reverse', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],'storage': ['--brain', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],'sweep': ['--accept-pending', '--apply', '--as', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--session', '--source', '--source-id', '--stale', '--timeout', '--timings', '--wait'],- 'sync': ['--abbrev-ref', '--absolute-git-dir', '--accept-pending', '--access-policy', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-empty', '--allow-outside-source-root', '--apply', '--apply-rewrites', '--as', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--check-only', '--class', '--clear', '--client', '--close', '--code', '--concurrency', '--config', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cursor', '--cwd', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--end-of-options', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--home', '--http', '--id', '--ignore-missing', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--interval', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-instructions', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--output', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--session', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--token-env', '--top-k', '--type', '--unindexed', '--unshallow', '--untracked-files', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--workspace', '--yes'],+ 'sync': ['--abbrev-ref', '--absolute-git-dir', '--accept-pending', '--access-policy', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-empty', '--allow-outside-source-root', '--apply', '--apply-rewrites', '--as', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--check-only', '--class', '--clear', '--client', '--close', '--code', '--concurrency', '--config', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cursor', '--cwd', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--end-of-options', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--home', '--http', '--id', '--ignore-missing', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--interval', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-instructions', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--output', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--session', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--token-env', '--top-k', '--type', '--unindexed', '--unshallow', '--untracked-files', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--workspace', '--yes'],'takes': ['--about', '--accept', '--applied', '--apply', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--date', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--failed', '--force', '--from-pages', '--group-by', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--min-confidence', '--min-n', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--retry-failed', '--row', '--semantic', '--since', '--slug', '--sort', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--to', '--unapplied', '--unit', '--until', '--value', '--verdict', '--weight', '--who', '--yes'],'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--images', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--request-id', '--rounds', '--save', '--since', '--source', '--source-id', '--stale', '--take', '--until', '--with-calibration'],'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--as', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--timings', '--wait'],diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 8f9bbce2a4..82c2fd5399 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -314,6 +314,8 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set([// Cat 41: the provider-use decision gbrain setup recorded; declined = no provider request (discovery, probe).'provider_consent','frontmatter_hook',+ // URL source clones with no record of who added them (url-source-origin.ts).+ 'url_source_origin',// F4b: PGLite row-delta planner statistics / Postgres autovacuum ANALYZE lag on the hot tables.'planner_stats_stale','alternative_providers',diff --git a/src/core/url-source-origin.ts b/src/core/url-source-origin.tsnew file mode 100644index 0000000000..e6f54dd4ca--- /dev/null+++ b/src/core/url-source-origin.ts@@ -0,0 +1,119 @@+/**+ * Who added a URL source, as recorded on its row (`sources.config.added_by_remote_caller`).+ *+ * A URL source a remote caller adds records `added_by_remote_caller: true`, and every reclone of it, managed or+ * not, clones with git-lfs downloads and hooks off (`lfsDownloadsOff`). Sources added before that record existed+ * carry no record, and nothing else stored on the row, the clone or the request log says whether a remote caller+ * or the local operator added them: both wrote the same row and cloned into the default clone directory. Only a+ * clone outside that directory proves a local add (remote callers cannot choose `clone_dir`).+ *+ * `urlSourcesWithoutOrigin` lists the undecided ones for the `url_source_origin` doctor check, read-only.+ * `recordSourceOrigin` (`gbrain sources record-origin`, trusted local CLI only) records the operator's answer:+ * `remote` writes `true`, `local` writes `false`. It previews unless `apply`. `remote` refuses a checkout that tracks+ * files with git-lfs, or one it cannot inspect: a clone with git-lfs downloads off holds pointer files where that+ * checkout holds the files' content, so the next managed reclone would not match the canonical manifest, and+ * converting the checkout rewrites its files, which this does not do. Without git-lfs files a clone with these+ * settings has the same tracked bytes, so the stored manifest needs no change.+ */+import { basename, dirname, resolve } from 'node:path';+import type { BrainEngine } from './engine.ts';+import { opError } from './ops/contract.ts';+import { hardenedGitSync } from './hardened-git.ts';+import { normalizeSourceConfig, parseSourceConfig } from './sources-load.ts';+import { defaultCloneDir } from './url-clone.ts';++export type SourceOrigin = 'remote' | 'local';+type OriginState = 'not_url_clone' | 'custom_clone_dir' | 'remote' | 'local' | 'unknown';+interface SourceRowLike { id: string; local_path: string | null; config: unknown; archived?: boolean | null }++export const RECORD_ORIGIN_DOCS = 'docs/guides/repair.md#url-source-origin';+export const recordOriginArgv = (ids: string[], origin: SourceOrigin): string[] => ['gbrain', 'sources', 'record-origin', ...ids, `--${origin}`];++/** The default clone directory, or a `clones/<id>` directory under an earlier GBRAIN_HOME. */+function atDefaultCloneDir(id: string, localPath: string): boolean {+ const path = resolve(localPath);+ return path === resolve(defaultCloneDir(id)) || (basename(path) === id && basename(dirname(path)) === 'clones');+}++function originState(row: SourceRowLike): OriginState {+ const config = parseSourceConfig(row.config);+ if (config.managed_clone !== true || typeof config.remote_url !== 'string' || !row.local_path) return 'not_url_clone';+ if (config.added_by_remote_caller === true) return 'remote';+ if (config.added_by_remote_caller === false) return 'local';+ return atDefaultCloneDir(row.id, row.local_path) ? 'unknown' : 'custom_clone_dir';+}++/** Active URL sources in the default clone directory with no record of who added them. */+export async function urlSourcesWithoutOrigin(engine: BrainEngine): Promise<Array<{ id: string; local_path: string }>> {+ const rows = await engine.executeRaw<SourceRowLike>(+ 'SELECT id, local_path, config FROM sources WHERE archived IS NOT TRUE AND local_path IS NOT NULL ORDER BY id');+ return rows.filter(row => originState(row) === 'unknown').map(row => ({ id: row.id, local_path: row.local_path! }));+}++/** `none` only when Git lists the checkout and no tracked path has `filter=lfs`; a missing or unreadable checkout is not known to be free of git-lfs. */+function lfsTracked(root: string): 'none' | 'tracked' | 'unknown' {+ const listed = hardenedGitSync(root, ['ls-files', '-z', '--cached', '--', ':(attr:filter=lfs)'], { timeoutMs: 30_000, maxBytes: 64 * 1024 * 1024 });+ if (!listed.ok) return 'unknown';+ return listed.stdout.length ? 'tracked' : 'none';+}++export interface RecordOriginResult {+ source_id: string;+ status: 'would_record' | 'recorded' | 'already_recorded' | 'refused';+ code?: 'not_found' | 'archived' | 'not_url_clone' | 'custom_clone_dir' | 'recorded_remote' | 'lfs_tracked' | 'lfs_unknown' | 'source_changed';+ reason: string;+}++const refusal = (id: string, code: NonNullable<RecordOriginResult['code']>, reason: string): RecordOriginResult => ({ source_id: id, status: 'refused', code, reason });++/** The outcome that needs no checkout inspection, or null when the source can take the record. */+function check(row: SourceRowLike | undefined, id: string, origin: SourceOrigin): RecordOriginResult | null {+ if (!row) return refusal(id, 'not_found', `No source ${id} is registered.`);+ if (row.archived) return refusal(id, 'archived', `Source ${id} is archived; restore it first if its origin still matters.`);+ const state = originState(row);+ if (state === 'not_url_clone') return refusal(id, 'not_url_clone', `Source ${id} is not a URL clone gbrain made, so it has no clone settings to record.`);+ if (state === 'custom_clone_dir') return origin === 'local'+ ? { source_id: id, status: 'already_recorded', reason: `Source ${id} was cloned into a directory only the local CLI can choose, so it is already treated as a local add.` }+ : refusal(id, 'custom_clone_dir', `Source ${id} was cloned into a directory only the local CLI can choose, so a remote caller did not add it; nothing changed.`);+ if (state === origin) return { source_id: id, status: 'already_recorded', reason: `Source ${id} is already recorded as added by ${origin === 'remote' ? 'a remote caller' : 'the local operator'}.` };+ if (state === 'remote') return refusal(id, 'recorded_remote', `Source ${id} is recorded as added by a remote caller; this command does not remove that record or its clone settings.`);+ return null;+}++/**+ * Records who added each named URL source. Preview unless `apply`; each apply re-reads and locks the row, so a source+ * changed since its check is refused `source_changed` and left alone. Trusted local CLI only: `remote` must be false.+ */+export async function recordSourceOrigin(engine: BrainEngine, ids: string[], opts: { origin: SourceOrigin; apply: boolean; remote?: boolean })+ : Promise<{ origin: SourceOrigin; apply: boolean; results: RecordOriginResult[] }> {+ if (opts.remote !== false) throw opError('trusted_local_only', 'Recording who added a source runs only from the trusted local CLI on the brain host, not over MCP.',+ 'Ask the user to run the command in fix on the brain host.', { legacy_error: 'permission_denied',+ fix: { argv: recordOriginArgv(ids, opts.origin), consent: [], actor: 'user', requires_exclusive: false, docs: RECORD_ORIGIN_DOCS,+ why: 'Previews which sources would get the record; only the local operator can say who added a source.' } });+ const results: RecordOriginResult[] = [];+ const recordedAs = opts.origin === 'remote' ? 'a remote caller' : 'the local operator';+ for (const id of [...new Set(ids)]) {+ const [row] = await engine.executeRaw<SourceRowLike>('SELECT id, local_path, config, archived FROM sources WHERE id=$1', [id]);+ const early = check(row, id, opts.origin);+ if (early) { results.push(early); continue; }+ if (opts.origin === 'remote') {+ const lfs = lfsTracked(row!.local_path!);+ if (lfs === 'tracked') { results.push(refusal(id, 'lfs_tracked', `Source ${id} tracks files with git-lfs. A clone with git-lfs downloads off holds pointer files where this checkout holds their content, so its next reclone would not match the canonical manifest, and converting the checkout rewrites its files, which this command does not do; nothing changed. If the source should not keep these files, check that nothing in its checkout is unpushed or only local, then remove it (gbrain sources remove ${id} --confirm-destructive).`)); continue; }+ if (lfs === 'unknown') { results.push(refusal(id, 'lfs_unknown', `Source ${id}'s checkout is missing or Git could not list it, so gbrain cannot confirm that no file is tracked with git-lfs; nothing changed. Restore the checkout, then run this again.`)); continue; }+ }+ if (!opts.apply) {+ results.push({ source_id: id, status: 'would_record', reason: `Source ${id} would be recorded as added by ${recordedAs}${opts.origin === 'remote' ? '; its next reclone clones with git-lfs downloads and hooks off' : ''}.` });+ continue;+ }+ results.push(await engine.transaction(async tx => {+ const [locked] = await tx.executeRaw<SourceRowLike>('SELECT id, local_path, config, archived FROM sources WHERE id=$1 FOR UPDATE', [id]);+ const config = locked ? parseSourceConfig(locked.config) : {};+ if (check(locked, id, opts.origin) || locked!.local_path !== row!.local_path || config.remote_url !== parseSourceConfig(row!.config).remote_url)+ return refusal(id, 'source_changed', `Source ${id} changed while its origin was being recorded; nothing changed. Run the preview again.`);+ await tx.executeRaw('UPDATE sources SET config=$2::text::jsonb WHERE id=$1',+ [id, JSON.stringify(normalizeSourceConfig({ ...config, added_by_remote_caller: opts.origin === 'remote' }))]);+ return { source_id: id, status: 'recorded' as const, reason: `Source ${id} is recorded as added by ${recordedAs}.` };+ }));+ }+ return { origin: opts.origin, apply: opts.apply, results };+}diff --git a/test/fixtures/goldens/doctor/content-pglite-human.json b/test/fixtures/goldens/doctor/content-pglite-human.jsonindex ce81fc665a..b6ead46268 100644--- a/test/fixtures/goldens/doctor/content-pglite-human.json+++ b/test/fixtures/goldens/doctor/content-pglite-human.json@@ -123,6 +123,7 @@" [OK] connector_held_items: No connector items are held."," [OK] git_held_files: No Git source files are held."," [OK] frontmatter_hook: No outdated gbrain frontmatter pre-commit hook is installed.",+ " [OK] url_source_origin: Every URL source clone records who added it, or was cloned where only the local CLI can clone."," [OK] orphan_persistence_bindings: Every persistence source binding belongs to an existing source."," [OK] foreign_ownership_marker: Every ownership marker beside a source checkout belongs to this brain."," [OK] coordination_lock_location: Every checkout's recorded coordination lock agrees with GBRAIN_COORDINATION_HOME, or the variable does not apply.",diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.jsonindex ef19f5a0bc..8b5c46d461 100644--- a/test/fixtures/goldens/doctor/content-pglite-json.json+++ b/test/fixtures/goldens/doctor/content-pglite-json.json@@ -1627,6 +1627,18 @@"name": "frontmatter_hook","status": "ok"},+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/repair.md#url-source-origin",+ "sources": []+ },+ "elapsed_ms": "<volatile>",+ "message": "Every URL source clone records who added it, or was cloned where only the local CLI can clone.",+ "name": "url_source_origin",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.jsonindex 0815d16093..e6b1b20faf 100644--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json@@ -1806,6 +1806,18 @@"name": "frontmatter_hook","status": "ok"},+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/repair.md#url-source-origin",+ "sources": []+ },+ "elapsed_ms": "<volatile>",+ "message": "Every URL source clone records who added it, or was cloned where only the local CLI can clone.",+ "name": "url_source_origin",+ "status": "ok"+ },{"category": "brain","details": {@@ -6877,6 +6889,18 @@"name": "frontmatter_hook","status": "ok"},+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/repair.md#url-source-origin",+ "sources": []+ },+ "elapsed_ms": "<volatile>",+ "message": "Every URL source clone records who added it, or was cloned where only the local CLI can clone.",+ "name": "url_source_origin",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.jsonindex 1abf0ce88d..c7e4e54412 100644--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json@@ -1798,6 +1798,18 @@"name": "frontmatter_hook","status": "ok"},+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/repair.md#url-source-origin",+ "sources": []+ },+ "elapsed_ms": "<volatile>",+ "message": "Every URL source clone records who added it, or was cloned where only the local CLI can clone.",+ "name": "url_source_origin",+ "status": "ok"+ },{"category": "brain","details": {@@ -6870,6 +6882,18 @@"name": "frontmatter_hook","status": "ok"},+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/repair.md#url-source-origin",+ "sources": []+ },+ "elapsed_ms": "<volatile>",+ "message": "Every URL source clone records who added it, or was cloned where only the local CLI can clone.",+ "name": "url_source_origin",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 5f5b99f440..8a1a008aee 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -1504,6 +1504,18 @@"name": "frontmatter_hook","status": "ok"},+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/repair.md#url-source-origin",+ "sources": []+ },+ "elapsed_ms": "<volatile>",+ "message": "Every URL source clone records who added it, or was cloned where only the local CLI can clone.",+ "name": "url_source_origin",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 1148782d65..ca45947e30 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -1560,6 +1560,18 @@"name": "frontmatter_hook","status": "ok"},+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/repair.md#url-source-origin",+ "sources": []+ },+ "elapsed_ms": "<volatile>",+ "message": "Every URL source clone records who added it, or was cloned where only the local CLI can clone.",+ "name": "url_source_origin",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex 8550797000..0d9ee92299 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -1552,6 +1552,18 @@"name": "frontmatter_hook","status": "ok"},+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/repair.md#url-source-origin",+ "sources": []+ },+ "elapsed_ms": "<volatile>",+ "message": "Every URL source clone records who added it, or was cloned where only the local CLI can clone.",+ "name": "url_source_origin",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex dbe187e7ad..d40e63ccdd 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -537,6 +537,10 @@"category": "ops","name": "frontmatter_hook"},+ {+ "category": "ops",+ "name": "url_source_origin"+ },{"category": "brain","name": "orphan_persistence_bindings"diff --git a/test/frontmatter-install-hook.test.ts b/test/frontmatter-install-hook.test.tsindex d972fec420..27fa110754 100644--- a/test/frontmatter-install-hook.test.ts+++ b/test/frontmatter-install-hook.test.ts@@ -337,6 +337,36 @@ describe('frontmatter install-hook (B13)', () => {expect(localHooksPath(tmp)).toBe('/dev/null');});+ test('the hooks-off reason names the clone setting it checked and no cause it did not check', () => {+ execFileSync('git', ['-C', tmp, 'config', 'core.hooksPath', '/dev/null']);+ expect(hooksPathBlocker(tmp)).toBe("hooks are off in this clone's own config (core.hooksPath=/dev/null), and gbrain leaves them off");+ });++ test('inherited GIT_DIR, GIT_WORK_TREE or GIT_CONFIG* variables cannot change the hooks-off decision', async () => {+ const plain = mkdtempSync(join(tmpdir(), 'fm-hook-plain-'));+ try {+ gitInit(plain);+ await install(plain);+ execFileSync('git', ['-C', tmp, 'config', 'core.hooksPath', '/dev/null']);+ const plainConfig = join(plain, '.git', 'config'), offConfig = join(tmp, '.git', 'config');+ const intoPlain = [{ GIT_DIR: join(plain, '.git') }, { GIT_DIR: join(plain, '.git'), GIT_WORK_TREE: plain }, { GIT_CONFIG: plainConfig },+ { GIT_CONFIG_GLOBAL: plainConfig, GIT_CONFIG_SYSTEM: plainConfig }, { GIT_CONFIG_COUNT: '1', GIT_CONFIG_KEY_0: 'core.hooksPath', GIT_CONFIG_VALUE_0: '.githooks' },+ { GIT_CONFIG_PARAMETERS: "'core.hookspath'='.githooks'" }];+ for (const env of intoPlain) {+ await withEnv(env, async () => {+ expect(installHook(tmp, true)).toBe('skipped_hooks_off');+ expect(inspectFrontmatterHook(tmp, 'source-a')).toBeNull();+ });+ expect(existsSync(join(tmp, '.githooks'))).toBe(false);+ expect(localHooksPath(tmp)).toBe('/dev/null');+ }+ for (const env of [{ GIT_DIR: join(tmp, '.git') }, { GIT_DIR: join(tmp, '.git'), GIT_WORK_TREE: tmp }, { GIT_CONFIG: offConfig }])+ await withEnv(env, async () => { expect(inspectFrontmatterHook(plain, 'source-a')).not.toBeNull(); });+ } finally {+ rmSync(plain, { recursive: true, force: true });+ }+ });+test('hooks off machine-wide (a global core.hooksPath=/dev/null) is not a hooks-off clone: the hook is written unwired with the usual advice', () => {const globalConfig = join(tmp, '..', `fm-global-${process.pid}.gitconfig`);writeFileSync(globalConfig, '[core]\n\thooksPath = /dev/null\n');diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex b7a3e81a18..a52db7d394 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -589,6 +589,7 @@ test/trust-owner-actions.test.tstest/unbound-source-6536.test.tstest/unindexed-files-convergence-7149.test.tstest/unindexed-files.test.ts+test/url-source-origin.test.tstest/v273-validate-timeouts.test.tstest/valid-time-gbra217.test.tstest/vector-manifest-probe-bound.test.tsdiff --git a/test/url-source-origin.test.ts b/test/url-source-origin.test.tsnew file mode 100644index 0000000000..bd3bec6ff7--- /dev/null+++ b/test/url-source-origin.test.ts@@ -0,0 +1,144 @@+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { registerLocalWriter } from '../src/core/persistence/identity.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { runManagedSourceClone } from '../src/core/persistence/topology-clone.ts';+import { topologyPrincipal } from '../src/core/persistence/topology-locks.ts';+import { LFS_OFF_CLONE_CONFIG } from '../src/core/git-remote.ts';+import { lfsDownloadsOff } from '../src/core/sources-ops.ts';+import { defaultCloneDir } from '../src/core/url-clone.ts';+import { operations } from '../src/core/operations.ts';+import { recordSourceOrigin } from '../src/core/url-source-origin.ts';+import { urlSourceOriginCheck } from '../src/commands/doctor/checks/url-source-origin.ts';++const URL_CONFIG = { managed_clone: true, remote_url: 'https://example.invalid/source-a.git' };+const git = (args: string[]) => execFileSync('git', ['-c', '[email protected]', '-c', 'user.name=alice-example', '-c', 'commit.gpgsign=false', ...args],+ { stdio: 'pipe', env: { ...process.env, GIT_LFS_SKIP_SMUDGE: '1' } });++/** A bare repository with one note, plus a git-lfs-tracked file when `lfs`. */+function bareRepo(home: string, lfs: boolean): string {+ const work = join(home, 'work'), bare = join(home, 'remote.git');+ git(['init', '-q', '-b', 'main', work]);+ writeFileSync(join(work, 'example.md'), '---\ntitle: Example\ntype: note\n---\n\nCanonical\n');+ if (lfs) { writeFileSync(join(work, '.gitattributes'), '*.bin filter=lfs diff=lfs merge=lfs -text\n'); writeFileSync(join(work, 'blob.bin'), 'binary-example'); }+ git(['-C', work, 'add', '-A']);+ git(['-C', work, 'commit', '-q', '-m', 'init']);+ git(['clone', '-q', '--bare', work, bare]);+ return bare;+}++const databaseUrl = process.env.DATABASE_URL;+for (const flavor of ['pglite', ...(databaseUrl ? ['postgres'] : [])] as const) describe(`URL source origin (${flavor})`, () => {+ let engine: BrainEngine;+ let closePostgres: (() => Promise<void>) | undefined;+ beforeAll(async () => {+ if (flavor === 'postgres') { const fixture = await isolatedPersistencePostgres(databaseUrl!); engine = fixture.engine; closePostgres = fixture.close; }+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }+ }, 120_000);+ afterAll(async () => { if (!engine) return; await disposePersistenceConsumer(engine); if (closePostgres) await closePostgres(); else await engine.disconnect(); });++ async function brain(run: (home: string) => Promise<void>) {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-url-origin-'));+ try {+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ await resetPgliteState(engine as PGLiteEngine);+ await run(home);+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+ }+ const insert = (id: string, localPath: string | null, config: Record<string, unknown>) =>+ engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,$3::text::jsonb)', [id, localPath, JSON.stringify(config)]);+ const config = async (id: string) => (await engine.executeRaw<{ config: unknown }>('SELECT config FROM sources WHERE id=$1', [id]))[0]!.config;+ const check = () => urlSourceOriginCheck(engine);++ /** A managed brain whose URL source was cloned before any origin was recorded, at the default clone directory. */+ async function managedUrlSource(home: string, lfs: boolean) {+ const source = 'source-a', root = defaultCloneDir(source), bare = bareRepo(home, lfs);+ mkdirSync(join(home, 'clones'), { recursive: true });+ git(['clone', '-q', bare, root]);+ await registerLocalWriter(engine, 'cli');+ await insert(source, root, URL_CONFIG);+ await claimWorktree(engine, source, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ return { source, root, bare };+ }++ test('doctor lists a URL source with no recorded origin at the default clone directory, and nothing on a brain without URL sources', () => brain(async home => {+ const empty = await check();+ expect(empty).toMatchObject({ name: 'url_source_origin', status: 'ok', details: { count: 0 } });+ await insert('source-a', defaultCloneDir('source-a'), URL_CONFIG);+ await insert('source-b', defaultCloneDir('source-b'), { ...URL_CONFIG, added_by_remote_caller: true });+ await insert('source-c', join(home, 'elsewhere', 'source-c'), URL_CONFIG);+ await insert('source-d', defaultCloneDir('source-d'), { ...URL_CONFIG, added_by_remote_caller: false });+ await insert('source-e', join(home, 'notes'), {});+ const found = await check();+ expect(found.status).toBe('warn');+ expect((found.details as { sources: Array<{ id: string }> }).sources.map(source => source.id)).toEqual(['source-a']);+ expect(found.message).toContain('cannot tell whether a remote caller or the local operator added');+ expect(found.fix).toMatchObject({ ask_user: true, argv: ['gbrain', 'sources', 'record-origin', 'source-a', '--remote'], verify: { argv: ['gbrain', 'doctor', '--only', 'url_source_origin', '--json'] } });+ }), 60_000);++ test('record-origin previews, then records; the next managed reclone clones with the remote-add settings and matches the manifest', () => brain(async home => {+ const { source, root, bare } = await managedUrlSource(home, false);+ const preview = await recordSourceOrigin(engine, [source], { origin: 'remote', apply: false, remote: false });+ expect(preview.results).toEqual([expect.objectContaining({ source_id: source, status: 'would_record' })]);+ expect(lfsDownloadsOff(await config(source))).toBe(false);+ expect((await check()).status).toBe('warn');++ const applied = await recordSourceOrigin(engine, [source], { origin: 'remote', apply: true, remote: false });+ expect(applied.results).toEqual([expect.objectContaining({ source_id: source, status: 'recorded' })]);+ expect(lfsDownloadsOff(await config(source))).toBe(true);+ expect((await check()).status).toBe('ok');+ expect((await recordSourceOrigin(engine, [source], { origin: 'local', apply: true, remote: false })).results[0]).toMatchObject({ status: 'refused', code: 'recorded_remote' });++ const seen: Array<{ skipLfs: boolean }> = [];+ const input = { operation: 'reclone' as const, sourceId: source, requestId: randomUUID() };+ const result = await runManagedSourceClone(engine, input, await topologyPrincipal(engine), input.requestId, { ...input, requestId: undefined, dryRun: undefined }, {+ clone: async (_url, stage, _budget, options) => { seen.push(options); git(['clone', '-q', ...(options.skipLfs ? LFS_OFF_CLONE_CONFIG : []), bare, stage]); },+ });+ expect(result).toMatchObject({ state: 'committed' });+ expect(seen).toEqual([{ skipLfs: true }]);+ expect(execFileSync('git', ['-C', root, 'config', '--local', '--get', 'core.hooksPath'], { encoding: 'utf8' }).trim()).toBe('/dev/null');+ }), 120_000);++ test('record-origin refuses a checkout that tracks git-lfs files, or one it cannot inspect, and writes nothing', () => brain(async home => {+ const { source, root } = await managedUrlSource(home, true);+ for (const apply of [false, true]) {+ const report = await recordSourceOrigin(engine, [source], { origin: 'remote', apply, remote: false });+ expect(report.results).toEqual([expect.objectContaining({ source_id: source, status: 'refused', code: 'lfs_tracked' })]);+ expect(report.results[0]!.reason).toContain('nothing changed');+ }+ expect(await config(source)).toEqual(URL_CONFIG);+ rmSync(root, { recursive: true, force: true });+ expect((await recordSourceOrigin(engine, [source], { origin: 'remote', apply: true, remote: false })).results[0]).toMatchObject({ status: 'refused', code: 'lfs_unknown' });+ expect(await config(source)).toEqual(URL_CONFIG);+ }), 120_000);++ test('--local records the local operator, so doctor stops listing it; a clone outside the default directory is never recorded as remote', () => brain(async home => {+ await insert('source-a', defaultCloneDir('source-a'), URL_CONFIG);+ await insert('source-c', join(home, 'elsewhere', 'source-c'), URL_CONFIG);+ expect((await recordSourceOrigin(engine, ['source-a'], { origin: 'local', apply: true, remote: false })).results[0]).toMatchObject({ status: 'recorded' });+ expect(await config('source-a')).toEqual({ ...URL_CONFIG, added_by_remote_caller: false });+ expect((await check()).status).toBe('ok');+ expect((await recordSourceOrigin(engine, ['source-c'], { origin: 'remote', apply: true, remote: false })).results[0]).toMatchObject({ status: 'refused', code: 'custom_clone_dir' });+ expect(await config('source-c')).toEqual(URL_CONFIG);+ }), 60_000);++ test('a remote caller cannot record an origin: trusted local CLI only, and no MCP operation reaches it', () => brain(async () => {+ await insert('source-a', defaultCloneDir('source-a'), URL_CONFIG);+ for (const remote of [true, undefined])+ await expect(recordSourceOrigin(engine, ['source-a'], { origin: 'remote', apply: true, remote })).rejects.toMatchObject({ canonical: 'trusted_local_only' });+ expect(await config('source-a')).toEqual(URL_CONFIG);+ expect(operations.filter(op => /record.?origin/.test(op.name) || 'added_by_remote_caller' in (op.params ?? {})).map(op => op.name)).toEqual([]);+ }), 60_000);+});