Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

convergence PR A: evidence in rows-behind repair, doctor live-page counts, tests, docs and notice rows

garrytan549da47e8482
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 6a39fdaaa7..e4f2d2aeaf 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -1068,6 +1068,16 @@ More: [docs/ai-providers/claude-cli.md#claude-cli-troubleshooting](../../docs/ai
More: [docs/guides/sync-unblock-runbook.md#dry-run-convergence-classes](../../docs/guides/sync-unblock-runbook.md#dry-run-convergence-classes)
+### conversion_file_in_source_root
+
+<a id="conversion_file_in_source_root"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A conversion review list, decisions file or approval was refused because its path is inside a source's checkout. | Those files name pages and paths. Written or read only outside every registered source root (mode 0600), they can never be synced, imported or committed. | Pass a path outside every source checkout, e.g. under ~/.gbrain. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/git-canonical.md#review-list-and-decisions](../../docs/guides/git-canonical.md#review-list-and-decisions)
+
### core_budget_exceeded
<a id="core_budget_exceeded"></a>
@@ -1958,12 +1968,22 @@ More: [docs/guides/repair.md#ghost-pages](../../docs/guides/repair.md#ghost-page
| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
|---|---|---|---|---|---|---|
-| Converting a source to git-canonical would discard database content or cannot place it, so the apply wrote nothing. | gbrain sources canonical --to git applies only when every database row will be in Git or in a declared database-only class afterwards. The preview counts what would be lost or cannot be placed by category (detail lists them): both_moved and held_drift_both, a page Git and the database both changed; deleted_in_git, a page Git deleted that the database edited since; uncommitted_edit, a working-tree edit the adoption would overwrite; ignored_target, a page whose file Git ignores without a declared class; unparseable and unsafe_path, a committed file or path sync cannot read; segmented_page, a segmented page conversion does not adopt yet; export_mismatch, a page whose export does not read back equal; git_overwrites_database, a page version a strict pass would replace that nothing accepted; ignore_status_unknown, a target whose ignore status Git cannot read (beyond a symlink, outside the checkout, a timed-out check). There is no override. | Relay the categories and their paths (the --dry-run preview lists them) and ask the user how each should be resolved; preview again afterwards. | user | `repeat the read that failed` | 1 | no |
+| Converting a source to git-canonical would discard database content or cannot place it, so the apply wrote nothing. | gbrain sources canonical --to git applies only when every database row will be in Git or in a declared database-only class afterwards. The preview counts what would be lost or cannot be placed by category (detail lists them): both_moved and held_drift_both, a page Git and the database both changed; no_record_both_moved and no_record_no_evidence, a page with no import record whose content history shows both sides moved, or shows nothing, until the owner's --decisions file decides it; deleted_in_git, a page Git deleted that the database edited since; uncommitted_edit, a working-tree edit the adoption would overwrite; ignored_target, a page whose file Git ignores without a declared class; unparseable and unsafe_path, a committed file or path sync cannot read; segmented_page, a segmented page conversion does not adopt yet; export_mismatch, a page whose export does not read back equal; git_overwrites_database, a page version a strict pass would replace that nothing accepted; ignore_status_unknown, a target whose ignore status Git cannot read (beyond a symlink, outside the checkout, a timed-out check). There is no override. | Relay the categories and their paths (the --dry-run preview lists them) and ask the user how each should be resolved; preview again afterwards. | user | `repeat the read that failed` | 1 | no |
-Reasons: `both_moved`, `held_drift_both`, `held_drift_unknown_differs`, `deleted_in_git`, `uncommitted_edit`, `ignored_target`, `unparseable`, `unsafe_path`, `segmented_page`, `export_mismatch`, `git_overwrites_database`, `ignore_status_unknown`.
+Reasons: `both_moved`, `held_drift_both`, `held_drift_unknown_differs`, `deleted_in_git`, `uncommitted_edit`, `ignored_target`, `unparseable`, `unsafe_path`, `segmented_page`, `export_mismatch`, `git_overwrites_database`, `ignore_status_unknown`, `no_record_both_moved`, `no_record_no_evidence`.
More: [docs/designs/GIT_CANONICAL_MEMORY.md#conversion](../../docs/designs/GIT_CANONICAL_MEMORY.md#conversion)
+### git_conversion_delta
+
+<a id="git_conversion_delta"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| An approved conversion found pages that changed since the approval, or decisions it did not approve, so only the unchanged pages were applied and the source stays mixed. | gbrain sources canonical --to git --apply --approved applies only the pages whose slug, revision, committed blob, evidence and action are the ones the owner approved. A page that changed since, a new page, a database edit the plan would now discard, and any decision the approval did not hold stay unapplied and are listed (delta) with counts; nothing outside the approved set is applied without a new decision. | Relay the delta list and its counts to the owner; once they decide, preview again with --approval-out and apply the new approval. | user | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/git-canonical.md#approval-across-time](../../docs/guides/git-canonical.md#approval-across-time)
+
### git_conversion_incomplete
<a id="git_conversion_incomplete"></a>
diff --git a/docs/guides/git-canonical.md b/docs/guides/git-canonical.md
index 27dc6db166..4ed30388cf 100644
--- a/docs/guides/git-canonical.md
+++ b/docs/guides/git-canonical.md
@@ -76,7 +76,7 @@ The plan puts every live page in one category and prints a preview hash:
| git wins | Git moved and the database did not (or the hold already matches the committed file). The strict pass indexes the committed file. |
| holds | Open sync holds are cleared so Git's verdict runs over them. |
| parked effects | Retried once, or recorded as declared when Git ignores the target. |
-| discard | Database content that Git-wins would throw away. The apply refuses with `git_conversion_blocked` until this is 0, and there is no override. |
+| discard | Database content that Git-wins would throw away, or a page with no import record whose side the content evidence could not place (`no_record_both_moved`, `no_record_no_evidence`). The apply refuses with `git_conversion_blocked` until this is 0, and there is no override: undecided pages need a [decision](#review-list-and-decisions). |
When the plan is what you expect, apply exactly that plan:
@@ -94,6 +94,79 @@ before the flag was set, and strict (Git wins) if it stopped after. Wait until
`gbrain sync status --source <id> --json` shows it idle, preview again and apply
the new hash.
+### Pages with no import record: content evidence
+
+A page whose database copy differs from its committed file and that has no
+import record (it was imported before records existed) gives no record to say
+which side moved. The plan decides it from content, never from a timestamp: it
+compares the page's archived versions with the blobs its path held in Git
+(newest first, 32 of each, following renames through the paths its versions
+recorded):
+
+| Evidence | Meaning | Category |
+|---|---|---|
+| `adopt_db_moved` | An older version of the page equals the committed file: only the database moved. | adopt |
+| `git_wins_file_moved` | The page equals an older committed blob of its path: only the file moved (a plain `git commit`, for example). | git wins (`file_moved`) |
+| `both_moved` | Both sides moved since the last state they shared. | discard until decided |
+| `no_evidence` | Nothing shared within the depth (no archived version, a path with one blob, a segmented page whose export matches no blob). | discard until decided |
+
+A later `updated_at` on the database row changes nothing here. The evidence
+kind of each page is part of the preview hash, and `gbrain sources git-gap
+<source-id> --json` reports the same split as `direction_evidence`.
+
+### Review list and decisions
+
+The undecided pages go on a review list:
+
+```bash
+gbrain sources canonical <source-id> --to git --dry-run --list-out ~/review.json
+```
+
+The file lists each page with its slug, path, revision, committed blob, evidence
+and `decision: null`, newest first. Fill in `decision` (`adopt` or `git_wins`)
+for the pages you decide, then preview with the file:
+
+```bash
+gbrain sources canonical <source-id> --to git --dry-run --decisions ~/review.json
+gbrain sources canonical <source-id> --to git --apply --expect <hash> --decisions ~/review.json
+```
+
+A decision names the page at its revision, blob and evidence: once the page
+moves again it is counted `stale` and not applied, and the page waits for a new
+decision. The file is bound into the preview hash. Review lists, decision files
+and approvals hold page names, so gbrain writes them owner-only (mode 0600) and
+refuses any path inside a source's checkout (`conversion_file_in_source_root`).
+
+### Approval across time
+
+A preview hash is bound to HEAD, so a commit between review and apply refuses
+the whole apply. When the owner approves a large plan, write the approval
+instead and apply it later:
+
+```bash
+gbrain sources canonical <source-id> --to git --dry-run [--decisions <file>] --approval-out ~/approval.json
+gbrain sources canonical <source-id> --to git --apply --approved ~/approval.json
+```
+
+The approval records the categories and each item's page, revision, blob and
+evidence. The apply plans again and compares every item with the approved one.
+With no difference it converts as `--expect` would. Otherwise it commits only the
+adoptions and withholds that are unchanged since the approval, leaves the source
+mixed, and exits 1 with `git_conversion_delta`: the list of changed, new and
+undecided items with counts, for the owner to decide before a new approval.
+
+### When an apply stops
+
+A failed apply reports where it stopped (`recovery` in `--json`): the mode it
+reached (`mixed` or `git`), the door commits it made (each group's sha), their
+push state and the writes it made. Pages that changed during the apply are held
+instead of overwritten (`changed_since_preview`), so a page written between
+the preview's recheck and the strict pass keeps its database version. Nothing is
+rewritten on the way back: a source left strict is re-derived with
+`gbrain sources reindex <source-id> --from-git` and returned with `--to mixed`;
+the adopted pages keep the content they had, because their committed files
+hold the database's own bytes.
+
**A new, empty source** can start strict instead:
`gbrain sources host-repo <id> --dir <path> [--push-remote <url>]` previews a bare
repository people clone, with a worktree gbrain owns; running the printed
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index c2930d41f8..fcf1487a9a 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -164,7 +164,7 @@ work behind exits 0, so scripts should also check `results[].complete`.
| `file-drift` | `maintenance_write_drift` | Explicit-only, preview-bound. Resolves pages whose canonical file differs from the database copy (`source_changed` / `file_database_drift`) through canonical reconciliation, preferring the file or the database copy within reconcile's protections. `--all-drifted` refuses mixed drift classes unless `--class` keeps one; `--only`/`--skip` narrow by canonical file path glob. Opt-in `storage.keep_db` lets the owner host's resident consumer resolve drift under declared prefixes with the database copy. A page whose file is gone from the last commit: `--prefer database` recreates the file, `--prefer file` soft-deletes the page ([deleted canonical files](#deleted-canonical-files)). See [file drift](#file-drift). | Protected metadata, the tag union and protected takes or private fact rows, listed per page as `exceptions`; pages changed after the preview (`changed_since_preview`). |
| `ghost-pages` | `ghost_pages` | Explicit-only, preview-bound, destructive consent. Soft-deletes live pages whose canonical file is missing on the owner host (ghost pages: every write refuses `canonical_file_missing` and no sync can import a file that is not there), through `delete_page` bound to the previewed owner, path and revision. `--apply --expect <hash> --yes`. See [ghost pages](#ghost-pages). | Declared db_only and never-filed derived pages (never listed); a page whose file came back before the apply (`file_restored`); pages changed after the preview (`changed_since_preview`). |
| `uncommitted-deletions` | `uncommitted_sync_deletions` | Explicit-only, preview-bound, consent. Restores soft-deleted pages a managed sync removed before #7130 although Git never held their recorded file (`.gitignore` excludes it, or no commit holds it and it is not on the disk), one `restore_page` with `detach` each, published database-only: the page comes back live, forgets its recorded file, and no file is written. `--apply --expect <hash> --yes`. See [uncommitted deletions](#uncommitted-deletions). | Pages another writer deleted (listed, restored only with `--include-ambiguous`); tombstones whose file Git once committed or that is on the disk again; paths Git could not answer for (`unknown`); purged pages (only a backup brings them back). |
-| `rows-behind` | `sync_rows_behind_checkpoint` | Explicit-only, preview-bound. Re-imports live pages of a managed source whose row holds an older version of its file than the sync checkpoint (`sources.last_commit`) says was imported, with no hold (#8071), from the file as committed at the checkpoint, through the managed file repair (no file is written). A file whose import is refused, or that is over the sync read bound, is held with that code instead. `--source <id>`, then `--apply --expect <hash>`. See [rows behind the checkpoint](#rows-behind). | Rows with no import record (`excluded:unproven`, joined with `--include-ambiguous`), rows with an uncommitted working-tree edit (`excluded:worktree_differs`), rows whose import would keep page data the file does not carry (`excluded:import_overlay`); rows that moved after the preview (`changed_since_preview`). |
+| `rows-behind` | `sync_rows_behind_checkpoint` | Explicit-only, preview-bound. Re-imports live pages of a managed source whose row holds an older version of its file than the sync checkpoint (`sources.last_commit`) says was imported, with no hold (#8071), from the file as committed at the checkpoint, through the managed file repair (no file is written). A file whose import is refused, or that is over the sync read bound, is held with that code instead. `--source <id>`, then `--apply --expect <hash>`. See [rows behind the checkpoint](#rows-behind). | Rows with no import record (`excluded:unproven`, joined with `--include-ambiguous`; one whose older version equals its committed file, so the database moved since, never joins: `excluded:database_moved`), rows with an uncommitted working-tree edit (`excluded:worktree_differs`), rows whose import would keep page data the file does not carry (`excluded:import_overlay`); rows that moved after the preview (`changed_since_preview`). |
| `receipt-compaction` | `persistence_capacity` (terminal bytes) | Explicit-only, preview-bound, destructive consent. Compacts terminal write receipts now instead of on the idle maintenance tick (#6696): the intent and error message are dropped, the outcome, error code and detail stay, and the unused reservation returns to the receipt-bytes counters. `--older-than <72h\|30d>` is floored at the configured retention unless `--force`; committed receipts only unless `--include-failures`. No admission, so it runs at a full cap. See [receipt compaction](#receipt-compaction). | `failures_kept`: failed, conflict and cancelled receipts left without `--include-failures`. Receipts of a run whose sync cursor is still open, and the newest sync receipt of each worktree, are never listed. |
| `aliases` | `dangling_aliases` (orphaned rows) | Explicit-only. Deletes free-text page aliases and slug redirects whose target page has no row at all (a page purged before purge removed its aliases, #6619, or a hard-deleted page), each target rechecked under its page lock; a coordinated maintenance write on a managed brain. A redirect from an old name of a page that still exists is never touched. See [aliases](#aliases). | `soft_deleted_target`: aliases of a soft-deleted page, kept for `gbrain restore` and removed when the page is purged. |
| `rename-identity` | `rename_identity_downgrades` | Explicit-only, preview-bound, destructive consent. For an inexact Git rename that sync split into a delete plus an add (#6729): carries the old page's identity (id, version history, timeline, links, facts, aliases) onto the new slug, imports the new file onto it as an edit and retires the provisional page; or, with `--close`, settles the pair and moves nothing. `--slug <new-slug>` (and `--from <old-slug>`) names one pair; `--apply --expect <hash> --yes`. See [rename identity](#rename-identity). | `fact_rows_collide` (a fence row of the old page the new file does not keep with the same claim); `managed_remedy_unavailable` (a carry on a managed source; `--close` is the remedy there); pages changed after the preview (`changed_since_preview`). |
@@ -1632,8 +1632,11 @@ The preview writes nothing. Each row in the set has one action:
[held files](#held-files) steps clear it.
Listed but left out of the set: rows with no import record
-(`excluded:unproven`, joined with `--include-ambiguous`, which replaces any
-database-only edit those rows hold), rows whose
+(`excluded:unproven`, joined with `--include-ambiguous`), rows with no import
+record whose older version equals the committed file, so the database moved
+since and a re-import would replace that edit (`excluded:database_moved`, never
+joined; `gbrain repair file-drift --source <id> --slug <slug> --prefer database`
+keeps it), rows whose
working-tree file differs from the committed one (`excluded:worktree_differs`:
commit the edit and sync), and rows whose import would keep page data the
file does not carry (`excluded:import_overlay`; resolve them with
diff --git a/src/commands/doctor/checks/db-ahead-of-git.ts b/src/commands/doctor/checks/db-ahead-of-git.ts
index 49ad97b69c..2efc613217 100644
--- a/src/commands/doctor/checks/db-ahead-of-git.ts
+++ b/src/commands/doctor/checks/db-ahead-of-git.ts
@@ -20,7 +20,7 @@ export function gitGapScanTimeoutMs(): number {
return Number.isFinite(n) && n > 0 ? n : 10_000;
}
-type SourceTotals = Pick<GitGapCensus, 'source_id' | 'complete' | 'pages' | 'states' | 'declared' | 'worktree'>;
+type SourceTotals = Pick<GitGapCensus, 'source_id' | 'complete' | 'pages' | 'live_pages' | 'states' | 'declared' | 'worktree'>;
const nonzero = (record: Record<string, number>) => Object.entries(record).filter(([, n]) => n > 0).map(([k, n]) => `${n} ${k}`).join(', ') || 'no pages';
@@ -36,8 +36,8 @@ async function runDbAheadOfGit(ctx: DoctorContext): Promise<Check[]> {
for (const row of withCheckout) {
if (Date.now() >= deadlineAt) { unread.push(row.id); continue; }
try {
- const { source_id, complete, pages, states, declared, worktree } = await censusGitGap(engine, row.id, { sample: 0, deadlineAt });
- sources.push({ source_id, complete, pages, states, declared, worktree });
+ const { source_id, complete, pages, live_pages, states, declared, worktree } = await censusGitGap(engine, row.id, { sample: 0, deadlineAt });
+ sources.push({ source_id, complete, pages, live_pages, states, declared, worktree });
} catch (error) {
errors.push({ source_id: row.id, message: error instanceof Error ? error.message : String(error) });
}
@@ -45,7 +45,7 @@ async function runDbAheadOfGit(ctx: DoctorContext): Promise<Check[]> {
const partial = [...sources.filter(source => !source.complete).map(source => source.source_id), ...unread];
const details = { informational: true, sources, partial_sources: partial, errors, sources_without_git_checkout: rows.length - withCheckout.length,
timeout_ms: gitGapScanTimeoutMs(), docs: GIT_GAP_DOCS };
- const listed = sources.map(source => `${source.source_id}: ${nonzero(source.states)}${source.complete ? '' : ' (partial)'}`);
+ const listed = sources.map(source => `${source.source_id}: ${source.complete ? `${source.live_pages} live page(s)` : `PARTIAL, ${source.pages} of ${source.live_pages} live page(s) read`}, ${nonzero(source.states)}`);
const message = withCheckout.length
? `Informational, nothing to do: the database compared with the commit at HEAD, per source with a Git checkout.${listed.length ? ` ${listed.join('; ')}.` : ''}`
+ `${unread.length ? ` Not reached within the ${details.timeout_ms / 1000}s budget: ${unread.join(', ')}.` : ''}`
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 5f3c140e04..84e84879e9 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1450,6 +1450,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.577.0', id: 'refresh_fence_refusal_gst1387', text: 'A write refused because `gbrain sources refresh` is fast-forwarding its checkout (`worktree_refreshing`) is now a registered retryable refusal whose fix is `next: wait` with `retry_after_ms`, instead of class server with `fix: gbrain doctor`; the memory verbs keep `unavailable` and add `canonical: worktree_refreshing`. An interactive CLI or MCP write waits out the fence for up to 10 s before that refusal; a background write is refused at once as before. `remember` with `items` whose every item failed is now refused with the first item\'s error (CLI exit 1, MCP isError) instead of a success envelope with `failed`, and a batch with any failed item adds `status: "error"` and the first failed `code`, so the CLI exits 1 and MCP returns isError with every item\'s receipt.' },
{ since: '0.60.583.0', id: 'sync_write_through_off_writeback_7084', text: 'With `sync.write_through` off, a managed `gbrain sync` no longer writes its canonical correction of a file (the frontmatter, title or tags the page keeps when an upstream edit drops them) back into the checkout (#7084, #8118). The page keeps the correction in the database only, as on a read-only mirror source, and `git status` stays clean. With `sync.write_through` on, nothing changes. Files already rewritten by earlier versions are not touched; restore them with `git checkout -- <paths>` or commit them.' },
{ since: '0.60.583.0', id: 'managed_sync_dry_run_counts_7087', text: 'A managed `gbrain sync --dry-run` now reports the files the run would add, modify, soft-delete and rename, and prints them as one line (#7087). It used to report the cursor\'s committed counts: zero before a run, or the previous run\'s counts when nothing had changed.' },
+ // Convergence PR A (GST-1500, evidence-based baseline). since is stamped at the merge slot.
+ { since: '0.60.586.0', id: 'conversion_content_evidence_pr_a', text: '`gbrain sources canonical <id> --to git` now decides a page with no import record by content evidence instead of calling it database-ahead: an older version equal to the committed file adopts it, a page equal to an older committed blob lets Git win (`git_wins.by.file_moved`), and a page where both moved or nothing is shared is a new discard (`no_record_both_moved`, `no_record_no_evidence`) until the owner decides it. `--list-out <file>` writes the review list, `--decisions <file>` applies the decisions (bound into the hash), and `--approval-out` / `--approved` apply an approval across time: only items unchanged since the approval apply, and the rest returns as `git_conversion_delta` with counts. These files are written 0600 and refused inside a source checkout. A page that changes during the apply is held instead of overwritten, and a failed apply reports `recovery` (mode, commits, push, writes, rollback). See docs/guides/git-canonical.md#review-list-and-decisions.' },
+ { since: '0.60.586.0', id: 'git_gap_live_pages_pr_a', text: '`gbrain sources git-gap` and doctor `db_ahead_of_git` now report each source\'s live pages (`live_pages`) beside the pages read, and a scan the time budget stopped reads `PARTIAL, <read> of <live> live page(s) read` instead of a bare count. `sources git-gap` also reports `direction_evidence` for pages with no import record. `gbrain repair rows-behind` never re-imports a row with no import record whose older version equals its committed file (the database moved since), even with `--include-ambiguous`: it is listed `excluded:database_moved`.' },
{ since: '0.60.583.0', id: 'frontmatter_missing_source_dir_7889', text: 'A registered source whose directory does not exist is no longer reported frontmatter-clean (#7889). The frontmatter audit marks it `missing` (and lists it under `missing_sources`), and doctor `frontmatter_integrity` and `frontmatter_repairable` warn with the path and ask you to restore it or run `gbrain sources set-path <id> <path>`; they no longer call it clean or blame a timeout.' },
];
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 4e42d0dfff..03744c13a6 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', '--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', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--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', '--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', '--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-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', '--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-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', '--write-tree', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--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', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--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', '--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-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-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', '--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,10 +78,10 @@ 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', '--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': ['--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', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--channel', '--chat-model', '--check', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--conversation', '--cursor', '--db-only', '--deadline', '--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', '--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', '--unsettle', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],
+ 'init': ['--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', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--channel', '--chat-model', '--check', '--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', '--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', '--as', '--asof', '--assign-corpus', '--attest-actor', '--attest-ops', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--channel', '--check', '--clear', '--cli-path', '--client', '--close', '--cluster-errors', '--code', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--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', '--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'],
+ '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', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--channel', '--check', '--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', '--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'],
@@ -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', '--attest-actor', '--attest-ops', '--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', '--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', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--may-act-for', '--member', '--message', '--migrate-legacy', '--migration', '--min-trust', '--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', '--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', '--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', '--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', '--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', '--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', '--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,7 +129,7 @@ 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', '--as', '--attest-actor', '--attest-ops', '--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', '--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', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--legacy-lock', '--limit', '--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', '--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', '--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', '--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', '--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', '--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', '--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', '--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'],
diff --git a/src/core/persistence/git-conversion.ts b/src/core/persistence/git-conversion.ts
index ad0862d68b..0272322f9a 100644
--- a/src/core/persistence/git-conversion.ts
+++ b/src/core/persistence/git-conversion.ts
@@ -379,7 +379,7 @@ export async function planGitConversion(engine: BrainEngine, sourceId: string, o
return decision.decision;
};
/** d4: where content evidence sends a page that differs from its committed file with no import record. */
- const byEvidence = (page: GitGapPage, path: string) => {
+ const byEvidence = (page: GitGapPage, path: string, held = false) => {
const evidence = page.evidence!;
tally(preview.evidence, evidence.kind, path);
const subject = { id: page.id, slug: page.slug, revision: page.revision, blob: page.headBlob ?? null, evidence: evidence.kind };
@@ -389,7 +389,8 @@ export async function planGitConversion(engine: BrainEngine, sourceId: string, o
if (decision === 'adopt') { candidates.push({ page, state: 'database_ahead', evidence: 'decided' }); return; }
if (decision === 'git_wins') { gitWins('decided', path, subject); return; }
review.push({ id: page.id, slug: page.slug, path, revision: page.revision, blob: page.headBlob ?? null, evidence });
- discard(evidence.kind === 'both_moved' ? 'no_record_both_moved' : 'no_record_no_evidence', path);
+ // A path sync already holds as an unknown-side drift keeps that category: the evidence did not place it either.
+ discard(held ? 'held_drift_unknown_differs' : evidence.kind === 'both_moved' ? 'no_record_both_moved' : 'no_record_no_evidence', path);
};
const declaredEqual = await equalDeclaredPaths(engine, sourceId, root, mode,
pages.filter(page => page.state === 'declared_database_only' && page.path && page.headBlob && !page.segmented));
@@ -426,13 +427,13 @@ export async function planGitConversion(engine: BrainEngine, sourceId: string, o
case 'unparseable': discard('unparseable', path); bump(preview.discard.detail.unparseable, page.unparseable ?? 'unknown'); continue;
case 'unsafe_path': discard('unsafe_path', path); continue;
case 'git_ahead':
- if (page.evidence && side !== 'both') byEvidence(page, path);
+ if (page.evidence && side !== 'both') byEvidence(page, path, side === 'unknown');
else if (side === 'unknown') discard('held_drift_unknown_differs', path);
else if (page.databaseAlsoMoved && side !== 'both') discard('both_moved', path);
else if (!page.databaseAlsoMoved) gitWins('git_ahead', path, { id: page.id, slug: page.slug, revision: page.revision, blob: page.headBlob ?? null });
continue;
case 'database_ahead':
- if (page.evidence && side !== 'both') { byEvidence(page, path); continue; }
+ if (page.evidence && side !== 'both') { byEvidence(page, path, side === 'unknown'); continue; }
if (side === 'unknown') { discard('held_drift_unknown_differs', path); continue; }
if (side === 'both') continue;
candidates.push({ page, state: 'database_ahead' });
@@ -751,6 +752,7 @@ export async function applyApprovedConversion(engine: BrainEngine, sourceId: str
.map(decision => ({ item: `decision:${decision.slug}`, reason: 'new_decision' as const }));
const current = approvalItems(plan);
for (const [item, fingerprint] of Object.entries(current)) if (approval.items[item] !== fingerprint) delta.push({ item, reason: approval.items[item] === undefined ? 'new' : 'changed' });
+ for (const item of Object.keys(approval.items)) if (current[item] === undefined) delta.push({ item, reason: 'changed' });
for (const category of DISCARD_CATEGORIES) if (plan.preview.discard.by[category]) delta.push({ item: `discard:${category}`, reason: `discard:${category}` });
if (!delta.length) return runConversion(engine, plan, plan.preview.preview_hash, opts);
const unchanged = (kind: string, path: string) => current[`${kind}:${path}`] === approval.items[`${kind}:${path}`];
@@ -780,7 +782,8 @@ async function runConversion(engine: BrainEngine, plan: GitConversionPlan, expec
// Item 3: the strict passes may replace a database version only where the plan approved Git replacing that page at that
// revision and blob (an adopted page at its planned revision, its blob being the one just committed); any other is held.
const binding: ConversionBinding = { expect: new Map<string, { id: string; revision: string | null; blob?: string | null }>([...plan.gitWins.flatMap(item => item.id ? [[item.path, { id: item.id, revision: item.revision, blob: item.blob }] as const] : []),
- ...plan.adopt.map(item => [item.path, { id: item.id, revision: item.revision, blob: undefined }] as const)]), reclassified: new Set() };
+ ...plan.adopt.map(item => [item.path, { id: item.id, revision: item.revision, blob: undefined }] as const),
+ ...[...plan.compared].map(([path, page]) => [path, { id: page.id, revision: page.revision, blob: undefined }] as const)]), reclassified: new Set() };
try {
if (plan.preview.discard.count) throw blockedError(plan.preview);
report({});
@@ -842,7 +845,7 @@ async function runConversion(engine: BrainEngine, plan: GitConversionPlan, expec
return { status: after.remaining === 0 && !binding.reclassified.size ? 'converted' : 'incomplete', source_id: sourceId, head: after.head, committed, withheld, holds_cleared: holdsCleared, parked, push,
closing_passes: closing, after, reclassified: [...binding.reclassified].sort() };
} catch (error) {
- if (error instanceof OperationError) {
+ if (error && typeof error === 'object') {
recovery.phase = progress.phase;
recovery.mode = (await engine.executeRaw<{ strict: boolean }>("SELECT COALESCE(config->>'canonical','')='git' AS strict FROM sources WHERE id=$1", [sourceId]).catch(() => []))[0]?.strict ? 'git' : recovery.mode;
recovery.push ??= progress.push ?? null;
diff --git a/src/core/repair/rows-behind.ts b/src/core/repair/rows-behind.ts
index eb6b226f3a..d293020624 100644
--- a/src/core/repair/rows-behind.ts
+++ b/src/core/repair/rows-behind.ts
@@ -10,7 +10,7 @@
* holds those bytes, so no file is written, and the import record is rewritten). `hold:<code>`: the import of the
* checkpoint file is refused (or it is over the sync read bound), so the apply opens the hold sync would have opened, with
* the code and message of the refusal the apply recomputes (not the one saved with the preview). Left out of the set and listed: rows with no import record (`excluded:unproven`, joined
- * by --include-ambiguous), rows whose working-tree file differs from the checkpoint blob (`excluded:worktree_differs`: an
+ * by --include-ambiguous; d4: one whose older version equals its committed file never joins, `excluded:database_moved`), rows whose working-tree file differs from the checkpoint blob (`excluded:worktree_differs`: an
* uncommitted edit; commit it and sync), and rows whose import would keep page data the file does not carry
* (`excluded:import_overlay`). `--apply --expect <hash>` applies exactly that set; a row whose page, checkpoint or file
* changed since is `changed_since_preview`. Never runs on upgrade, from --all or from the remediation plan.
@@ -93,7 +93,7 @@ export const rowsBehindRepair: RepairHandler = {
const items = approved.items.map((row, index) => item(row, opts.expect!, index, index === approved.items.length - 1));
return { items: items.filter(entry => afterCursor(entry.cursor, after)), preview_hash: opts.expect, residuals: {} };
}
- const scan = await scanRowsBehind(engine, sourceId);
+ const scan = await scanRowsBehind(engine, sourceId, { evidence: true });
if (scan.status !== 'known' || !context.ok) {
const hash = previewHash(hashParts(scope, owner, selection, scan.checkpoint, []));
return { items: [], preview_hash: hash, residuals: {}, warnings: [`Source ${sourceId} was not compared (${scan.reason ?? 'not_applicable'}): ${scan.status === 'unknown'
@@ -106,7 +106,12 @@ export const rowsBehindRepair: RepairHandler = {
const describe = (row: RowBehind) => `${row.path} at checkpoint ${scan.checkpoint!.slice(0, 12)} is blob ${row.blob.slice(0, 12)}; the page (revision ${row.revision}) holds an older version`;
for (const row of [...scan.behind, ...scan.unproven]) {
const entry = `${sourceId}:${row.slug}`;
- if (row.record === 'none' && !selection.include_ambiguous) { listing.push({ item: entry, class: 'excluded:unproven', detail: `${describe(row)}; no import record proves the database did not move since, so it joins only with --include-ambiguous` }); continue; }
+ // d4: a row with no import record still joins only with --include-ambiguous, and content evidence names its side. When
+ // only the database moved (an older version of the page equals the committed file), re-importing would replace that
+ // edit, so it never joins, flag or not.
+ const evidence = row.record === 'none' ? row.evidence?.kind ?? 'no_evidence' : null;
+ if (evidence === 'adopt_db_moved') { listing.push({ item: entry, class: 'excluded:database_moved', detail: `${describe(row)}; an older version of the page equals its committed file, so the database moved since and re-importing would replace that edit; gbrain repair file-drift --source ${sourceId} --slug ${row.slug} --prefer database keeps it` }); continue; }
+ if (evidence !== null && !selection.include_ambiguous) { listing.push({ item: entry, class: 'excluded:unproven', detail: `${describe(row)}; no import record proves the database did not move since (content evidence: ${evidence}), so it joins only with --include-ambiguous` }); continue; }
if (row.overlay) { listing.push({ item: entry, class: 'excluded:import_overlay', detail: `${describe(row)}; importing it would keep page data the file does not carry (tags, a withdrawal or sanitized text), so it is not re-imported here; gbrain repair file-drift --source ${sourceId} --slug ${row.slug} --prefer file resolves it` }); continue; }
if (row.refusal) {
selected.push({ ...row, source_id: sourceId, checkpoint: scan.checkpoint!, action: 'hold', owner: context.owner, selection });
@@ -124,8 +129,8 @@ export const rowsBehindRepair: RepairHandler = {
...(scan.truncated ? [`More rows are behind than one preview lists (${scan.behind_count} behind, ${scan.unproven_count} without a record); apply this set, then preview again for the rest.`] : []),
];
return { items: selected.map((row, index) => item(row, hash, index, index === selected.length - 1)), preview_hash: hash, listing, ...(warnings.length ? { warnings } : {}),
- residuals: { ...scan.counts, pages: scan.pages, behind: scan.behind_count, unproven: scan.unproven_count },
- details: { docs: ROWS_BEHIND_DOCS, checkpoint: scan.checkpoint, head: scan.head, rows: selected.map(({ slug, path, blob, action, record, refusal }) => ({ slug, path, blob, action, record, ...(refusal ? { refusal: refusal.code } : {}) })) } };
+ residuals: { ...scan.counts, pages: scan.pages, behind: scan.behind_count, unproven: scan.unproven_count, ...Object.fromEntries(Object.entries(scan.unproven_by ?? {}).map(([kind, n]) => [`unproven_${kind}`, n])) },
+ details: { docs: ROWS_BEHIND_DOCS, checkpoint: scan.checkpoint, head: scan.head, rows: selected.map(({ slug, path, blob, action, record, refusal, evidence }) => ({ slug, path, blob, action, record, ...(refusal ? { refusal: refusal.code } : {}), ...(evidence ? { evidence: evidence.kind } : {}) })) } };
},
async apply(ctx, entry, opts): Promise<RepairItemOutcome> {
const { row, hash, last } = entry as RowItem;
diff --git a/test/git-canonical-conversion-evidence-d4.test.ts b/test/git-canonical-conversion-evidence-d4.test.ts
new file mode 100644
index 0000000000..9ceda3f016
--- /dev/null
+++ b/test/git-canonical-conversion-evidence-d4.test.ts
@@ -0,0 +1,224 @@
+/**
+ * d4 and items 2, 3, 6 and 7 of the convergence plan's PR A, on a managed brain: a page with no import record converts
+ * by content evidence (never a timestamp), undecided pages wait on an owner's decisions file, a database write that races
+ * the recheck is held instead of overwritten, a failed apply reports where it stopped and how to roll back without
+ * rewriting, and an approval applies across time to the pages unchanged since it was given.
+ */
+import { describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { applyApprovedConversion, applyGitConversion, applyMixedConversion, conversionApproval, conversionRecovery, conversionReviewList, planGitConversion,
+ planMixedConversion, readConversionApproval, readConversionDecisions, writeConversionFile, type ConversionDecision } from '../src/core/persistence/git-conversion.ts';
+import { previewReindex, runSourcesReindex } from '../src/commands/sources-reindex.ts';
+import { runSourcesCanonical } from '../src/commands/sources-canonical.ts';
+import { _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';
+import { managedBrain, type ManagedBrain } from './helpers/managed-brain.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, '-c', 'commit.gpgsign=false', ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const note = (slug: string, body: string) => '---\ntype: concept\ntitle: ' + slug + '\n---\n\n' + body + '\n';
+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };
+const PROCESSING = { noEmbed: true, noExtract: true };
+const SLUGS = ['notes/same', 'notes/db', 'notes/file', 'notes/both', 'notes/none'];
+const DB_EDIT = (slug: string) => `Written to the database alone: ${slug}.`;
+const GIT_EDIT = (slug: string) => `Edited by a plain git commit: ${slug}.`;
+
+const strict = async (engine: BrainEngine) => (await engine.executeRaw<{ s: boolean }>("SELECT COALESCE(config->>'canonical','')='git' AS s FROM sources WHERE id='default'"))[0]!.s;
+const body = async (engine: BrainEngine, slug: string) => (await engine.executeRaw<{ body: string }>("SELECT compiled_truth AS body FROM pages WHERE source_id='default' AND slug=$1 AND deleted_at IS NULL", [slug]))[0]?.body;
+const holds = async (engine: BrainEngine) => (await engine.executeRaw<{ r: { path: string; code: string } }>(
+ "SELECT completed_keys->0 AS r FROM op_checkpoints WHERE op='sync-hold' ORDER BY fingerprint")).map(({ r }) => r.path);
+const databaseOnlyEdit = (engine: BrainEngine, slug: string, text: string) => engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(
+ "UPDATE pages SET compiled_truth=$1, knowledge_revision=$2::uuid, revision_write_request_id=NULL WHERE source_id='default' AND slug=$3", [text, randomUUID(), slug]), TEST_WRITE_ATTRIBUTION));
+async function dropImportRecord(engine: BrainEngine, slug: string): Promise<void> {
+ const [row] = await engine.executeRaw<{ id: string }>("SELECT id::text FROM pages WHERE source_id='default' AND slug=$1", [slug]);
+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='sync-import-provenance' AND fingerprint LIKE $1", [`default:%:${row!.id}`]);
+}
+const conversionShas = (root: string, since: string) => git(root, 'log', '--reverse', '--format=%H', `${since}..HEAD`).split('\n').filter(Boolean);
+
+async function cli(engine: BrainEngine, args: string[]): Promise<Record<string, any>> {
+ const lines: string[] = [];
+ const log = console.log, priorExitCode = process.exitCode;
+ console.log = (line: unknown) => { lines.push(String(line)); };
+ try { await runSourcesCanonical(engine, [...args, '--json']); } finally { console.log = log; _resetCliExitVerdictForTests(); process.exitCode = priorExitCode ?? 0; }
+ return JSON.parse(lines.at(-1)!);
+}
+
+const setup = ({ root }: { root: string }) => {
+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');
+ git(root, 'config', 'user.name', 'Example Writer'); git(root, 'config', 'user.email', '[email protected]');
+ for (const slug of SLUGS) writeFileSync(join(root, `${slug}.md`), note(slug, `The committed body of ${slug}.`));
+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 'notes');
+};
+
+/**
+ * After the first sync every page but notes/same loses its import record, as pages imported before records existed have none:
+ * notes/db: a writer archived its preimage and edited the row (only the database moved: adopt);
+ * notes/file: a plain git commit edited the file, and then a non-content updated_at bump (only the file moved: Git wins);
+ * notes/both: both of the above (both moved: a decision);
+ * notes/none: a row edit with no archived version (no evidence: a decision).
+ */
+async function evidenceSource(brain: ManagedBrain): Promise<void> {
+ const { engine, root } = brain;
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ for (const slug of ['notes/db', 'notes/both']) { await engine.createVersion(slug, { sourceId: 'default' }); await databaseOnlyEdit(engine, slug, DB_EDIT(slug)); }
+ await databaseOnlyEdit(engine, 'notes/none', DB_EDIT('notes/none'));
+ for (const slug of ['notes/db', 'notes/file', 'notes/both', 'notes/none']) await dropImportRecord(engine, slug);
+ for (const slug of ['notes/file', 'notes/both']) writeFileSync(join(root, `${slug}.md`), note(slug, GIT_EDIT(slug)));
+ git(root, 'commit', '-qam', 'plain git edit');
+ await engine.executeRaw("UPDATE pages SET updated_at = now() + interval '30 days' WHERE source_id='default' AND slug IN ('notes/file','notes/both')");
+}
+
+/** The owner's decisions for the two undecided pages, written as the review list with "decision" filled in. */
+async function decide(brain: ManagedBrain, dir: string, picks: Record<string, ConversionDecision['decision']>): Promise<ConversionDecision[]> {
+ const list = await conversionReviewList(brain.engine, await planGitConversion(brain.engine, 'default'));
+ const file = join(dir, 'decisions.json');
+ await writeConversionFile(brain.engine, file, '--list-out', { ...list, pages: list.pages.map(entry => ({ ...(entry as object), decision: picks[(entry as { slug: string }).slug] ?? null })) });
+ return readConversionDecisions(brain.engine, file, 'default');
+}
+
+for (const backend of testBackends()) describe(`[${backend}] conversion by content evidence (convergence PR A)`, () => {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+ const outside = () => { const dir = mkdtempSync(join(tmpdir(), 'gbrain-conversion-files-')); return { dir, done: () => rmSync(dir, { recursive: true, force: true }) }; };
+
+ test('d4 and the timestamp trap: each page goes to the side that moved, and the undecided ones wait on a decisions file bound into the hash', () => managedBrain(async brain => {
+ const { engine, root } = brain;
+ const files = outside();
+ try {
+ await evidenceSource(brain);
+ const plan = await planGitConversion(engine, 'default');
+ expect(plan.preview).toMatchObject({ evidence: { count: 4, by: { adopt_db_moved: 1, git_wins_file_moved: 1, both_moved: 1, no_evidence: 1 } },
+ git_wins: { by: { file_moved: 1 } }, discard: { count: 2, by: { no_record_both_moved: 1, no_record_no_evidence: 1 } }, decisions: { digest: null } });
+ expect(plan.preview.adopt.sample).toEqual(['notes/db.md']);
+ expect(plan.preview.git_wins.sample).toEqual(['notes/file.md']);
+ await expect(applyGitConversion(engine, 'default', plan.preview.preview_hash, PROCESSING)).rejects.toMatchObject({ code: 'git_conversion_blocked' });
+
+ // Item 2: the review list and decisions are written 0600 and refused under a source root.
+ await expect(writeConversionFile(engine, join(root, 'review.json'), '--list-out', {})).rejects.toMatchObject({ code: 'conversion_file_in_source_root' });
+ expect((await cli(engine, ['default', '--to', 'git', '--dry-run', '--list-out', join(root, 'notes', 'review.json')]))).toMatchObject({ status: 'refused', code: 'conversion_file_in_source_root' });
+ const list = await conversionReviewList(engine, plan);
+ expect(list.pages.map(entry => (entry as { slug: string }).slug).sort()).toEqual(['notes/both', 'notes/none']);
+ const decisions = await decide(brain, files.dir, { 'notes/both': 'git_wins', 'notes/none': 'adopt' });
+ expect(statSync(join(files.dir, 'decisions.json')).mode & 0o777).toBe(0o600);
+ const decided = await planGitConversion(engine, 'default', { decisions });
+ expect(decided.preview).toMatchObject({ discard: { count: 0 }, decisions: { applied: 2, stale: 0, unused: 0 }, git_wins: { by: { file_moved: 1, decided: 1 } } });
+ expect(decided.preview.decisions.digest).not.toBeNull();
+ expect(decided.preview.preview_hash).not.toBe(plan.preview.preview_hash);
+ await expect(applyGitConversion(engine, 'default', decided.preview.preview_hash, PROCESSING)).rejects.toMatchObject({ code: 'preview_changed' });
+
+ // A decision names a page at its revision: once the page moves again, the decision is stale and not applied.
+ await databaseOnlyEdit(engine, 'notes/none', 'Edited once more.');
+ expect((await planGitConversion(engine, 'default', { decisions })).preview).toMatchObject({ decisions: { applied: 1, stale: 1 }, discard: { by: { no_record_no_evidence: 1 } } });
+ await databaseOnlyEdit(engine, 'notes/none', DB_EDIT('notes/none'));
+ const again = await decide(brain, files.dir, { 'notes/both': 'git_wins', 'notes/none': 'adopt' });
+ const final = await planGitConversion(engine, 'default', { decisions: again });
+ expect(await applyGitConversion(engine, 'default', final.preview.preview_hash, { ...PROCESSING, decisions: again })).toMatchObject({ status: 'converted', reclassified: [] });
+ expect(await body(engine, 'notes/file')).toContain(GIT_EDIT('notes/file'));
+ expect(await body(engine, 'notes/both')).toContain(GIT_EDIT('notes/both'));
+ expect(await body(engine, 'notes/db')).toContain(DB_EDIT('notes/db'));
+ expect(readFileSync(join(root, 'notes/db.md'), 'utf8')).toContain(DB_EDIT('notes/db'));
+ expect(readFileSync(join(root, 'notes/none.md'), 'utf8')).toContain(DB_EDIT('notes/none'));
+ expect(await strict(engine)).toBe(true);
+ } finally { files.done(); }
+ }, { databaseUrl, setup }), 240_000);
+
+ test('item 3: a database write that races the recheck is held, never overwritten, and the source stays mixed', () => managedBrain(async brain => {
+ const { engine, root } = brain;
+ const files = outside();
+ try {
+ await evidenceSource(brain);
+ const base = git(root, 'rev-parse', 'HEAD');
+ const decisions = await decide(brain, files.dir, { 'notes/both': 'git_wins', 'notes/none': 'adopt' });
+ const { preview } = await planGitConversion(engine, 'default', { decisions });
+ installFaultHook(async point => { if (point === 'conversion:after_recheck') await databaseOnlyEdit(engine, 'notes/file', 'A racing database write.'); });
+ let error: unknown;
+ try { await applyGitConversion(engine, 'default', preview.preview_hash, { ...PROCESSING, decisions }); } catch (caught) { error = caught; } finally { installFaultHook(undefined); }
+ expect(error).toMatchObject({ code: 'git_conversion_incomplete', detail: 'changed_since_preview' });
+ expect(await body(engine, 'notes/file')).toBe('A racing database write.');
+ expect(await strict(engine)).toBe(false);
+ expect(await holds(engine)).toContain('notes/file.md');
+ expect(conversionRecovery(error)).toMatchObject({ mode: 'mixed', reclassified: ['notes/file.md'], commits: conversionShas(root, base), rollback: [] });
+ } finally { files.done(); }
+ }, { databaseUrl, setup }), 240_000);
+
+ test('item 6: a failure after the flip reports the mode, commits, push and writes, and the rollback keeps the adopted pages\' live content', () => managedBrain(async brain => {
+ const { engine, root } = brain;
+ const files = outside();
+ try {
+ await evidenceSource(brain);
+ const base = git(root, 'rev-parse', 'HEAD');
+ const decisions = await decide(brain, files.dir, { 'notes/both': 'git_wins', 'notes/none': 'adopt' });
+ const { preview } = await planGitConversion(engine, 'default', { decisions });
+ let error: unknown;
+ try {
+ await applyGitConversion(engine, 'default', preview.preview_hash, { ...PROCESSING, decisions, onProgress: progress => { if (progress.phase === 'strict_pass_2') throw new Error('stopped in the second strict pass'); } });
+ } catch (caught) { error = caught; }
+ expect(String(error)).toContain('stopped in the second strict pass');
+ const recovery = conversionRecovery(error)!;
+ expect(recovery).toMatchObject({ mode: 'git', phase: 'strict_pass_2', accepted: { adopted: 2, withheld: 0 }, push: { state: expect.any(String) },
+ rollback: [['gbrain', 'sources', 'reindex', 'default', '--from-git', '--dry-run'], ['gbrain', 'sources', 'canonical', 'default', '--to', 'mixed', '--dry-run']] });
+ expect(recovery.commits).toEqual(conversionShas(root, base));
+ expect(recovery.commits.length).toBeGreaterThan(0);
+
+ const live = { db: await body(engine, 'notes/db'), none: await body(engine, 'notes/none') };
+ const reindex = await previewReindex(engine, 'default');
+ await runSourcesReindex(engine, ['default', '--from-git', '--apply', '--expect', reindex.preview_hash, '--no-embed', '--no-extract', '--json']);
+ expect(await applyMixedConversion(engine, 'default', (await planMixedConversion(engine, 'default')).preview_hash)).toEqual({ status: 'mixed', source_id: 'default' });
+ expect(await strict(engine)).toBe(false);
+ expect(await body(engine, 'notes/db')).toBe(live.db);
+ expect(await body(engine, 'notes/none')).toBe(live.none);
+ expect(live.db).toContain(DB_EDIT('notes/db'));
+ expect(live.none).toContain(DB_EDIT('notes/none'));
+ } finally { files.done(); }
+ }, { databaseUrl, setup }), 240_000);
+
+ test('item 7: a commit between approval and apply leaves the changed page unapplied and lists the delta with counts', () => managedBrain(async brain => {
+ const { engine, root } = brain;
+ const files = outside();
+ try {
+ await evidenceSource(brain);
+ const decisions = await decide(brain, files.dir, { 'notes/both': 'git_wins', 'notes/none': 'adopt' });
+ const approvalFile = join(files.dir, 'approval.json');
+ const written = await cli(engine, ['default', '--to', 'git', '--dry-run', '--decisions', join(files.dir, 'decisions.json'), '--approval-out', approvalFile]);
+ expect(written.written.approval).toBe(approvalFile);
+ expect(statSync(approvalFile).mode & 0o777).toBe(0o600);
+ const approval = await readConversionApproval(engine, approvalFile, 'default');
+ expect(approval).toMatchObject({ kind: 'gbrain-conversion-approval', decisions: decisions.map(d => ({ slug: d.slug })) });
+ expect(approval).toEqual(conversionApproval(await planGitConversion(engine, 'default', { decisions })));
+
+ writeFileSync(join(root, 'notes/db.md'), note('notes/db', 'A commit that landed after the approval.'));
+ git(root, 'commit', '-qam', 'a commit after the approval');
+ const result = await applyApprovedConversion(engine, 'default', approval, PROCESSING);
+ expect(result).toMatchObject({ status: 'delta', committed: { pages: 1 } });
+ expect(result.delta!.items).toContainEqual({ item: 'adopt:notes/db.md', reason: 'changed' });
+ expect(result.delta!.count).toBe(Object.values(result.delta!.by).reduce((a, b) => a + b, 0));
+ expect(result.delta!.count).toBeGreaterThan(0);
+ expect(await strict(engine)).toBe(false);
+ expect(await body(engine, 'notes/db')).toContain(DB_EDIT('notes/db'));
+ expect(readFileSync(join(root, 'notes/db.md'), 'utf8')).toContain('A commit that landed after the approval.');
+ expect(readFileSync(join(root, 'notes/none.md'), 'utf8')).toContain(DB_EDIT('notes/none'));
+
+ const refused = await cli(engine, ['default', '--to', 'git', '--apply', '--approved', approvalFile, '--no-embed', '--no-extract']);
+ expect(refused).toMatchObject({ status: 'delta', code: 'git_conversion_delta' });
+ } finally { files.done(); }
+ }, { databaseUrl, setup }), 240_000);
+
+ test('item 7: an approval nothing moved under applies whole, as its hash would', () => managedBrain(async brain => {
+ const { engine } = brain;
+ const files = outside();
+ try {
+ await evidenceSource(brain);
+ const decisions = await decide(brain, files.dir, { 'notes/both': 'git_wins', 'notes/none': 'adopt' });
+ const approval = conversionApproval(await planGitConversion(engine, 'default', { decisions }));
+ expect(await applyApprovedConversion(engine, 'default', approval, PROCESSING)).toMatchObject({ status: 'converted', committed: { pages: 2 } });
+ expect(await strict(engine)).toBe(true);
+ } finally { files.done(); }
+ }, { databaseUrl, setup }), 240_000);
+});
diff --git a/test/git-canonical-conversion-g8a.test.ts b/test/git-canonical-conversion-g8a.test.ts
index 7f6091b3e2..f4166b365d 100644
--- a/test/git-canonical-conversion-g8a.test.ts
+++ b/test/git-canonical-conversion-g8a.test.ts
@@ -188,6 +188,8 @@ const DRIFT_COMMITTED = 'The committed edit of notes/drift.';
async function mixedSource(brain: ManagedBrain, driftMatches = true): Promise<void> {
const { engine, root } = brain;
expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ // A real writer archives the preimage before it rewrites a page, so notes/legacy's content evidence shows only the database moved (d4).
+ await engine.createVersion('notes/legacy', { sourceId: 'default' });
for (const slug of ['notes/ahead', 'notes/drift', 'notes/removed', 'notes/legacy']) await databaseOnlyEdit(engine, slug, `Written to the database alone: ${slug}.`);
writeFileSync(join(root, 'notes/drift.md'), note('notes/drift', DRIFT_COMMITTED));
git(root, 'rm', '-q', 'notes/removed.md'); git(root, 'commit', '-qam', 'edit drift, remove removed');
diff --git a/test/git-gap-census.test.ts b/test/git-gap-census.test.ts
index 99f0d916f2..26b9d1ce86 100644
--- a/test/git-gap-census.test.ts
+++ b/test/git-gap-census.test.ts
@@ -385,7 +385,7 @@ for (const backend of testBackends()) describe(`git-gap census (git-canonical G1
expect(check!.status).toBe('ok');
expect(check!.details.sources.find((s: { source_id: string }) => s.source_id === 'default')).toMatchObject({ pages: 2, complete: true,
states: { equal: 1, undeclared_database_only: 1 } });
- expect(check!.message).toContain('default: 1 equal, 1 undeclared_database_only');
+ expect(check!.message).toContain('default: 2 live page(s), 1 equal, 1 undeclared_database_only');
expect(check!.message).not.toContain('notes/');
const [late] = await withEnv({ GBRAIN_DOCTOR_GIT_GAP_TIMEOUT_MS: '1' }, () =>
dbAheadOfGitEntry.run({ engine, progress: { heartbeat: () => {} }, entryDeadlineAt: Date.now() } as never)) as Array<{ status: string; details: any }>;
diff --git a/test/git-gap-direction-evidence-d4.test.ts b/test/git-gap-direction-evidence-d4.test.ts
new file mode 100644
index 0000000000..03f73cd9a3
--- /dev/null
+++ b/test/git-gap-direction-evidence-d4.test.ts
@@ -0,0 +1,138 @@
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { PostgresEngine } from '../src/core/postgres-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { inlineExportMarkdown, readExportPage, readExportWithdrawals } from '../src/core/export-snapshot.ts';
+import { decideDirection } from '../src/core/persistence/git-gap.ts';
+import { censusGitGap, describeGitGap, type GitGapPage } from '../src/commands/sources-git-gap.ts';
+import { dbAheadOfGitEntry } from '../src/commands/doctor/checks/db-ahead-of-git.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+// d4 of the convergence plan: a page that differs from its committed file with no import record is decided by content
+// evidence (its archived versions against its path's committed blobs), never by a timestamp.
+
+function git(root: string, ...args: string[]): string {
+ return execFileSync('git', ['-C', root, ...args], { env: { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1', GIT_AUTHOR_NAME: 'Test',
+ GIT_AUTHOR_EMAIL: '[email protected]', GIT_COMMITTER_NAME: 'Test', GIT_COMMITTER_EMAIL: '[email protected]' } }).toString();
+}
+function put(root: string, rel: string, content: string): void {
+ mkdirSync(dirname(join(root, rel)), { recursive: true });
+ writeFileSync(join(root, rel), content);
+}
+function commitAll(root: string, message: string): void {
+ git(root, 'add', '-A');
+ git(root, 'commit', '-qm', message);
+}
+
+describe('decideDirection (d4 classifier)', () => {
+ const v = (id: number, digest: string) => ({ id, digest });
+ const b = (oid: string, digest: string | null) => ({ oid, digest });
+ test('each state from content alone', () => {
+ expect(decideDirection('row', 'head', [v(2, 'head')], [b('o1', 'older')])).toMatchObject({ kind: 'adopt_db_moved', version: 2 });
+ expect(decideDirection('row', 'head', [v(2, 'older')], [b('o1', 'row')])).toMatchObject({ kind: 'git_wins_file_moved', blob: 'o1' });
+ expect(decideDirection('row', 'head', [v(2, 'head')], [b('o1', 'row')])).toMatchObject({ kind: 'both_moved', basis: 'conflicting_history' });
+ expect(decideDirection('row', 'head', [v(3, 'x'), v(2, 'shared')], [b('o1', 'shared')])).toMatchObject({ kind: 'both_moved', basis: 'shared_older_state', blob: 'o1', version: 2 });
+ expect(decideDirection('row', 'head', [v(2, 'x')], [b('o1', 'y')])).toMatchObject({ kind: 'no_evidence', basis: 'no_shared_state' });
+ expect(decideDirection('row', null, [v(2, 'x')], [b('o1', null)])).toMatchObject({ kind: 'no_evidence' });
+ });
+});
+
+for (const backend of testBackends()) describe(`git-gap direction evidence (d4): ${backend}`, () => {
+ let engine: BrainEngine;
+ const dirs: string[] = [];
+ const tempDir = (prefix: string) => { const dir = realpathSync(mkdtempSync(join(tmpdir(), prefix))); dirs.push(dir); return dir; };
+ beforeAll(async () => {
+ engine = backend === 'postgres' ? new PostgresEngine() : new PGLiteEngine();
+ await engine.connect(backend === 'postgres' ? { database_url: requirePostgresTestDatabase() } : {});
+ await engine.initSchema();
+ }, 60000);
+ afterAll(async () => { await engine.disconnect(); for (const dir of dirs) rmSync(dir, { recursive: true, force: true }); });
+ beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM pages');
+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op IN ('sync-hold','sync-import-provenance')");
+ await engine.executeRaw("UPDATE sources SET local_path=NULL, config='{}'::jsonb WHERE id='default'");
+ });
+ const rendered = (slug: string) => engine.transaction(async tx => {
+ const [key] = await tx.executeRaw<{ id: string; source_id: string; slug: string }>("SELECT id::text, source_id, slug FROM pages WHERE source_id='default' AND slug=$1", [slug]);
+ return inlineExportMarkdown(await readExportPage(tx, key!, await readExportWithdrawals(tx, 'default')));
+ });
+ const body = (slug: string, text: string) => engine.putPage(slug, { type: 'note', title: slug.split('/').pop()!, compiled_truth: text, timeline: '' });
+
+ /** One page in each evidence state, none with an import record. */
+ async function fixture(): Promise<string> {
+ const root = tempDir('git-gap-evidence-');
+ git(root, 'init', '-q');
+ await engine.executeRaw("UPDATE sources SET local_path=$1 WHERE id='default'", [root]);
+ for (const slug of ['notes/db-moved', 'notes/file-moved', 'notes/both-moved', 'notes/equal']) {
+ await body(slug, `First body of ${slug}.`);
+ put(root, `${slug}.md`, await rendered(slug));
+ }
+ await body('notes/no-history', 'A body the file never held.');
+ put(root, 'notes/no-history.md', (await rendered('notes/no-history')).replace('A body the file never held.', 'A body only the file holds.'));
+ commitAll(root, 'first');
+ // Every real writer archives the preimage (createVersion) before it rewrites a page.
+ for (const slug of ['notes/db-moved', 'notes/both-moved']) { await engine.createVersion(slug); await body(slug, 'Edited in the database.'); }
+ for (const slug of ['notes/file-moved', 'notes/both-moved']) put(root, `${slug}.md`, (await rendered(slug)).replace(/First body of [^.]+\.|Edited in the database\./, 'Edited in Git by a plain commit.'));
+ commitAll(root, 'plain git edit');
+ return root;
+ }
+
+ test('the census splits pages with no import record by the side that moved', async () => {
+ await fixture();
+ const pages: GitGapPage[] = [];
+ const census = await censusGitGap(engine, 'default', { sample: 50, evidence: true, collect: page => { pages.push(page); } });
+ expect(census).toMatchObject({ complete: true, pages: 5, live_pages: 5, database_ahead_without_import_record: 4,
+ direction_evidence: { adopt_db_moved: 1, git_wins_file_moved: 1, both_moved: 1, no_evidence: 1 },
+ states: { equal: 1, database_ahead: 2, git_ahead: 2 }, git_ahead_database_also_moved: 1 });
+ const bySlug = Object.fromEntries(pages.map(page => [page.slug, page]));
+ expect(bySlug['notes/db-moved']).toMatchObject({ state: 'database_ahead', evidence: { kind: 'adopt_db_moved', basis: 'older_version_matches_file' } });
+ expect(bySlug['notes/file-moved']).toMatchObject({ state: 'git_ahead', evidence: { kind: 'git_wins_file_moved', basis: 'row_matches_older_file' } });
+ expect(bySlug['notes/both-moved']).toMatchObject({ state: 'git_ahead', databaseAlsoMoved: true, evidence: { kind: 'both_moved' } });
+ expect(bySlug['notes/no-history']).toMatchObject({ state: 'database_ahead', evidence: { kind: 'no_evidence' } });
+ expect(describeGitGap(census)).toContain('5 live page(s)');
+ // Without evidence the old rule stands: every unrecorded difference reads database_ahead.
+ expect(await censusGitGap(engine, 'default', { sample: 0 })).toMatchObject({ direction_evidence: null, states: { database_ahead: 4, git_ahead: 0 } });
+ }, 120000);
+
+ test('the timestamp trap: a non-content updated_at bump after a file edit still goes to Git', async () => {
+ await fixture();
+ await engine.executeRaw("UPDATE pages SET updated_at = now() + interval '30 days' WHERE slug IN ('notes/file-moved','notes/both-moved')");
+ const pages: GitGapPage[] = [];
+ await censusGitGap(engine, 'default', { sample: 0, evidence: true, collect: page => { pages.push(page); } });
+ expect(pages.find(page => page.slug === 'notes/file-moved')).toMatchObject({ state: 'git_ahead', evidence: { kind: 'git_wins_file_moved' } });
+ expect(pages.find(page => page.slug === 'notes/both-moved')).toMatchObject({ state: 'git_ahead', evidence: { kind: 'both_moved' } });
+ }, 120000);
+
+ test('#14: a doctor budget labels its partial count against the live pages, and the full census counts the same live pages', async () => {
+ const root = tempDir('git-gap-partial-');
+ git(root, 'init', '-q');
+ await engine.executeRaw("UPDATE sources SET local_path=$1 WHERE id='default'", [root]);
+ for (let i = 0; i < 7; i++) { await body(`notes/p${i}`, `Body ${i}.`); put(root, `notes/p${i}.md`, await rendered(`notes/p${i}`)); }
+ commitAll(root, 'init');
+ const full = await censusGitGap(engine, 'default', { sample: 0 });
+ expect(full).toMatchObject({ complete: true, pages: 7, live_pages: 7 });
+ const stopped = await censusGitGap(engine, 'default', { sample: 0, deadlineAt: Date.now() - 1 });
+ expect(stopped).toMatchObject({ complete: false, pages: 0, live_pages: 7 });
+ expect(describeGitGap(stopped)).toContain('PARTIAL, 0 of 7 live page(s) read');
+ const [late] = await withEnv({ GBRAIN_DOCTOR_GIT_GAP_TIMEOUT_MS: '1' }, () =>
+ dbAheadOfGitEntry.run({ engine, progress: { heartbeat: () => {} }, entryDeadlineAt: Date.now() + 1 } as never)) as Array<{ message: string; details: any }>;
+ const source = late!.details.sources.find((s: { source_id: string }) => s.source_id === 'default');
+ if (source) {
+ expect(source).toMatchObject({ live_pages: 7 });
+ expect(late!.message).toContain(source.complete ? 'default: 7 live page(s)' : `default: PARTIAL, ${source.pages} of 7 live page(s) read`);
+ } else expect(late!.details.partial_sources).toContain('default');
+ const [done] = await dbAheadOfGitEntry.run({ engine, progress: { heartbeat: () => {} } } as never) as Array<{ message: string }>;
+ expect(done!.message).toContain('default: 7 live page(s), 7 equal');
+ }, 120000);
+
+ test('repo-less: a source without a checkout reads no evidence (not_applicable) and counts its live pages', async () => {
+ await body('notes/a', 'Only in the database.');
+ const census = await censusGitGap(engine, 'default', { sample: 0, evidence: true });
+ expect(census).toMatchObject({ complete: true, pages: 1, live_pages: 1, direction_evidence: null, database_ahead_without_import_record: 0 });
+ });
+});
diff --git a/test/hardened-git-stream-6712.test.ts b/test/hardened-git-stream-6712.test.ts
index a764842bab..dda64ac4db 100644
--- a/test/hardened-git-stream-6712.test.ts
+++ b/test/hardened-git-stream-6712.test.ts
@@ -60,7 +60,7 @@ describe('allow-list additions', () => {
['hash-object', '--no-filters', '--stdin-paths'], ['hash-object', '--stdin-paths', '--no-filters'],
['check-attr', '-z', '--stdin', 'filter', 'text', 'eol', 'working-tree-encoding'],
['diff-tree', '-r', '-z', '--no-renames', 'a', 'b'], ['diff-tree', '--no-renames', '-z', '-r', 'a', 'b', '--', 'notes'],
- ['cat-file', '--batch'], ['cat-file', 'blob', 'abc'],
+ ['cat-file', '--batch'], ['cat-file', '--batch-check'], ['cat-file', 'blob', 'abc'],
]) expect(() => assertHardenedGitArgs(args)).not.toThrow();
});
@@ -76,7 +76,8 @@ describe('allow-list additions', () => {
['diff-tree', '-r', '-z', '--no-renames', '--stdin'], ['diff-tree', '-r', '-z', '--no-renames', '-C', 'a', 'b'],
['cat-file', '--filters', 'HEAD:a'], ['cat-file', '--textconv', 'HEAD:a'], ['cat-file', '--batch-command'],
['cat-file', '--batch-all-objects', '--batch'], ['cat-file', '--batch', '--filters'], ['cat-file', '--batch', '--textconv'],
- ['cat-file', '--batch=%(objectname)'], ['cat-file', '--batch-check'],
+ ['cat-file', '--batch=%(objectname)'], ['cat-file', '--batch-check=%(objectname)'], ['cat-file', '--batch-check', '--filters'],
+ ['cat-file', '--batch-check', '--textconv'], ['cat-file', '--batch-check', '--batch-all-objects'], ['cat-file', '--batch-check', '--follow-symlinks'],
]) expect(() => assertHardenedGitArgs(args)).toThrow(/hardened git refuses/);
});
});
diff --git a/test/rows-behind-checkpoint-8071.test.ts b/test/rows-behind-checkpoint-8071.test.ts
index a0f6146106..22b1f35b7f 100644
--- a/test/rows-behind-checkpoint-8071.test.ts
+++ b/test/rows-behind-checkpoint-8071.test.ts
@@ -201,6 +201,23 @@ for (const backend of testBackends()) describe(`[${backend}] #8071: rows behind
expect((await pageOf(engine, 'notes/c')).body).toContain('The committed body of notes/c.');
}, { databaseUrl, setup }), 240_000);
+ test('d4: a row with no record whose database moved never joins, even with --include-ambiguous; one whose file moved does', () => managedBrain(async ({ engine, ctx, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ await putDatabaseOnly(engine, ctx, 'notes/a', 'A database-only edit of notes/a.');
+ await seedBehind(engine, root, {
+ 'notes/a': { content: note('notes/a', 'The committed body of notes/a.'), record: 'none' },
+ 'notes/d': { content: note('notes/d', 'The redacted body of notes/d.'), record: 'none' },
+ });
+ const scan = await scanRowsBehind(engine, 'default', { evidence: true });
+ expect(scan.unproven.map(row => [row.slug, row.evidence?.kind])).toEqual([['notes/a', 'adopt_db_moved'], ['notes/d', 'git_wins_file_moved']]);
+ expect(scan).toMatchObject({ live_pages: 5, unproven_by: { adopt_db_moved: 1, git_wins_file_moved: 1, both_moved: 0, no_evidence: 0 } });
+ const widened = await repair(engine, { includeAmbiguous: true });
+ expect(listing(widened)).toEqual([['default:notes/a', 'excluded:database_moved'], ['default:notes/d', 'reimport']]);
+ await repair(engine, { apply: true, expect: widened.preview_hash, includeAmbiguous: true });
+ expect((await pageOf(engine, 'notes/a')).body).toContain('A database-only edit of notes/a.');
+ expect((await pageOf(engine, 'notes/d')).body).toContain('The redacted body of notes/d.');
+ }, { databaseUrl, setup }), 240_000);
+
test('a checkpoint file the import refuses is held with the refusal code instead of imported', () => managedBrain(async ({ engine, root }) => {
expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
await seedBehind(engine, root, { 'notes/a': { content: '---\ntype: concept\ntitle: [unclosed\n---\n\nThe redacted body of notes/a.\n', record: 'checkpoint' } });