Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(file-drift): file wins imports a segmented page with protected parts; refusals carry a fix (GST-1555)

garrytanae46b45e341b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 76ca414438..021f6b311a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,19 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+**`gbrain repair file-drift --prefer file` now imports a page stored in segments that keeps protected parts, instead of refusing every apply with no next step.**
+
+A held page whose body is stored in segments (`pages.segmented_storage`, a page over 1 MiB) and whose database copy keeps a protected frontmatter key and a timeline row the file lacks previewed cleanly, listing both exceptions and an apply command. That apply refused every time with `invalid_params` "Unsupported or missing reconciliation fields." and no `fix`, so the page stayed held and blocked writes to it. The apply now imports the file with the same protections (the file keeps its bytes plus the appended key and row, the page keeps both), the page stays segmented and searchable, and the next sync releases the hold. A preview now refuses a page its own apply would refuse, and every refusal on this path names its next step.
+
+### Itemized changes
+
+- `src/core/persistence/reconcile-state.ts`: a reconcile preview of a segmented page validates: its snapshot's `bodyGeneration` and the page's `body_storage` / `body_bytes` are accepted (the preimage checks are unchanged). A page with no revision yet (the revision backfill has not reached it) refuses `revision_backfill_pending` in the preview, with `gbrain apply-migrations --force-schema` in `fix`, instead of a stale-preview refusal with none; `revision_backfill_pending` joins the error registry.
+- `src/core/persistence/reconcile-prepare.ts`: the reconcile publication of a segmented page leaves its text seal to the segmented import (as the managed file repair does), runs the import's `afterCommit`, and reads the published page back materialized.
+- `src/core/repair/file-drift.ts`: the preview validates each page's reconcile artifact as the apply reads it back, so a page the apply would refuse is listed `refused` in the preview. A refused preview row carries the refusal's `fix`; a refused or changed apply outcome carries its `fix`, or a read-only preview of that page alone. `gbrain repair` prints both.
+- `src/core/persistence/reconcile-merge.ts`: "Unsupported or missing reconciliation fields." names the fields in `why`.
+
## [0.60.586.0] - 2026-11-06
**A `remember` refused for its arguments now names the whole valid call, so an agent that never read the schema saves on its next try.**
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 6a39fdaaa7..96ee815577 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -4134,6 +4134,16 @@ More: [docs/guides/windowed-reads.md#result_too_large](../../docs/guides/windowe
|---|---|---|---|---|---|---|
| Resume spec mismatch. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+### revision_backfill_pending
+
+<a id="revision_backfill_pending"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The page was written before page revisions existed and the revision backfill has not reached it, so it has no revision a write or preview can bind to. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. Run: gbrain apply-migrations --force-schema | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/write-refusals.md#revision-backfill](../../docs/guides/write-refusals.md#revision-backfill)
+
### revision_changed
<a id="revision_changed"></a>
diff --git a/src/commands/repair.ts b/src/commands/repair.ts
index f28a8ccd91..ba17f2e5c6 100644
--- a/src/commands/repair.ts
+++ b/src/commands/repair.ts
@@ -444,14 +444,19 @@ export function renderRepairResult(result: RepairResult, opts: { diff: boolean }
if (result.scan?.partial) lines.push(' scan: partial (the census did not finish within its bound; more candidates may exist, rerun to resume it)');
if (result.stopped) lines.push(` STOPPED: ${result.stopped.message}`);
if (result.stopped?.fix?.argv) lines.push(` fix: ${shellQuote(result.stopped.fix.argv)}${result.stopped.fix.consent.length ? ` (asks the user first: ${result.stopped.fix.consent.join(', ')})` : ''}`);
- for (const entry of result.listing ?? []) lines.push(` ${entry.class}: ${entry.item}${entry.detail ? ` (${entry.detail})` : ''}`);
+ for (const entry of result.listing ?? []) {
+ lines.push(` ${entry.class}: ${entry.item}${entry.detail ? ` (${entry.detail})` : ''}`);
+ if (entry.fix?.argv) lines.push(` fix: ${shellQuote(entry.fix.argv)}`);
+ }
const render = repairSpec(result.kind).handler.render;
if (result.details && render) lines.push(...render(result.details, opts));
if (result.mode === 'apply' && result.outcomes) lines.push(` outcomes: ${Object.entries(result.outcomes).map(([k, v]) => `${k}=${v}`).join(', ')}`);
for (const outcome of result.mode === 'apply' ? result.outcome_items ?? [] : []) {
if (!outcome.detail) continue;
- lines.push(` ${outcome.outcome}: ${outcome.item} ${Object.entries(outcome.detail).filter(([key]) => key !== 'commit_step').map(([k, v]) => `${k}=${v}`).join(', ')}${outcome.reason ? ` (${outcome.reason})` : ''}`);
+ lines.push(` ${outcome.outcome}: ${outcome.item} ${Object.entries(outcome.detail).filter(([key]) => key !== 'commit_step' && key !== 'fix').map(([k, v]) => `${k}=${v}`).join(', ')}${outcome.reason ? ` (${outcome.reason})` : ''}`);
if (typeof outcome.detail.commit_step === 'string') lines.push(` commit: ${outcome.detail.commit_step}`);
+ const fix = outcome.detail.fix as { argv?: string[] } | undefined;
+ if (fix?.argv) lines.push(` fix: ${shellQuote(fix.argv)}`);
}
if (result.mode === 'dry_run' && result.affected) lines.push(` apply: ${result.apply_command}`);
return lines.join('\n');
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 4e42d0dfff..58849be985 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -81,7 +81,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'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'],
'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', '--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', '--force-schema', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--of', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--qm', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--reason-scan-limit', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--restart-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--save', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--token-env', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
'lint': ['--abbrev-ref', '--accept-pending', '--add', '--admin-intent', '--adopt-slug-path', '--as', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--get-all', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--older-than', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--timeout', '--timings', '--unset-all', '--wait', '--yes'],
'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index dbf85164b5..3edf414fd1 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -679,6 +679,7 @@ export const CODES = {
resume_spec_mismatch: { class: 'caller', summary: "Resume spec mismatch." },
result_too_large: { class: 'caller', summary: "The tool's result is larger than this connection can carry in one response, so it was replaced by this error; nothing was cut.", why: "Results are measured as the complete encoded JSON-RPC frame (every block, notice and escape). A frame over the connection's cap (mcp.max_result_bytes_stdio, 4 MiB; mcp.max_result_bytes_http, 1 MiB) would be rejected or silently cut by the client.", docs: 'docs/guides/windowed-reads.md#result_too_large', legacy_error: 'invalid_params', suggestion: "Ask for less in one call: a window (get_page body: 'window'), a page of rows (limit / from_index), or metadata only (get_versions include_body: false).", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'outline' } }, consent: [], actor: 'agent', why: "Returns the page's size and outline, which name the windows to read.", requires_exclusive: false } },
revision_changed: { class: 'caller', summary: "The page changed since the cursor or chunk id was issued, so that position no longer names the same text.", why: "Cursors and chunk positions are bound to one page revision; reading on from them after an edit could skip or repeat text without saying so.", docs: 'docs/guides/windowed-reads.md#revision_changed', legacy_error: 'invalid_params', suggestion: "Read again from the position in fix (the same byte offset at the current revision), or start over with body: 'outline'.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'none' } }, consent: [], actor: 'agent', why: "Returns the current revision and size.", requires_exclusive: false } },
+ revision_backfill_pending: { class: 'caller', summary: "The page was written before page revisions existed and the revision backfill has not reached it, so it has no revision a write or preview can bind to.", fix: { argv: ['gbrain', 'apply-migrations', '--force-schema'], consent: [], actor: 'agent', why: "Re-runs the schema migration pass on the brain host, which resumes the page revision backfill and prints its progress; it changes no page content.", requires_exclusive: true }, docs: 'docs/guides/write-refusals.md#revision-backfill' },
revision_conflict: { class: 'caller', summary: "The target changed since it was read; the expected revision no longer matches.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}' } }, consent: [], actor: 'agent', why: "Reads the current page and revision; resubmit against that revision with a new request_id.", requires_exclusive: false } },
revision_required: { class: 'caller', summary: "The target already exists and the write named no revision: supply the expected revision read from the page (or the policy epoch) before replacing it.", why: "Without the revision the write cannot tell an intentional replacement from an overwrite of an edit it never saw; nothing was changed.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}' } }, consent: [], actor: 'agent', why: "Reads the current page and its revision; resubmit with that expected_revision (or force: true for an intentional overwrite).", requires_exclusive: false } },
revision_unavailable: { class: 'unavailable', summary: "The exact authorized revision is unavailable." },
diff --git a/src/core/persistence/reconcile-merge.ts b/src/core/persistence/reconcile-merge.ts
index a47a3febac..bd3e7e6cf7 100644
--- a/src/core/persistence/reconcile-merge.ts
+++ b/src/core/persistence/reconcile-merge.ts
@@ -39,10 +39,13 @@ export function validateReconcileJson(value: unknown, allowDates = false): void
visit(value, 0);
}
export function strictReconcileKeys(value: unknown, allowed: string[], required = allowed): asserts value is Record<string, unknown> {
- if (!object(value) || Object.keys(value).some(k => !allowed.includes(k)) || required.some(k => !Object.hasOwn(value, k))) {
- throw opError('invalid_params', 'Unsupported or missing reconciliation fields.',
- 'Pass the preview file written by --out unchanged, and give each decision only path, action and, for set_value, value.');
- }
+ if (!object(value)) throw opError('invalid_params', 'Unsupported or missing reconciliation fields.',
+ 'Pass the preview file written by --out unchanged, and give each decision only path, action and, for set_value, value.',
+ { why: 'Expected a JSON object with the reconciliation fields.' });
+ const unsupported = Object.keys(value).filter(k => !allowed.includes(k)).sort(), missing = required.filter(k => !Object.hasOwn(value, k));
+ if (unsupported.length || missing.length) throw opError('invalid_params', 'Unsupported or missing reconciliation fields.',
+ 'Pass the preview file written by --out unchanged, and give each decision only path, action and, for set_value, value.',
+ { why: [unsupported.length ? `unsupported: ${unsupported.join(', ')}` : '', missing.length ? `missing: ${missing.join(', ')}` : ''].filter(Boolean).join('; ') });
}
function pointer(path: string): string[] {
if (!path.startsWith('/') || /~(?![01])/u.test(path)) throw opError('invalid_params', 'Decisions require escaped JSON Pointer paths.',
diff --git a/src/core/persistence/reconcile-prepare.ts b/src/core/persistence/reconcile-prepare.ts
index 9fc7ace76d..80c2f908a4 100644
--- a/src/core/persistence/reconcile-prepare.ts
+++ b/src/core/persistence/reconcile-prepare.ts
@@ -29,6 +29,7 @@ import { verifyReconcileBackup } from './reconcile-backup.ts';
import { assertAutoDecisions } from './reconcile-additive.ts';
import { admissionAllows, readSyncAdmission } from './sync-admission.ts';
import { bindOrigin } from './origin-guard.ts';
+import { materializedSnapshot } from './segmented-apply.ts';
const pageFix = (sourceId: string, slug: string): Action => readFix(`Shows page ${slug} in source ${sourceId} as stored now, with its revision, read-only.`,
{ argv: ['gbrain', 'get', '--source', sourceId, '--', slug] });
@@ -171,6 +172,7 @@ export async function prepareReconcileMutation(engine: BrainEngine, row: WriteRe
file: { path: state.path, root: state.root, content, expectedBeforeHash: absent ? null : state.pins.raw_file_hash },
// A database-only page matched by its slug path always records that file as its origin.
noop: ready.noop && sha256(content) === state.pins.raw_file_hash && state.origin === 'recorded',
+ ...(ready.afterCommit ? { afterCommit: (target: BrainEngine) => ready.afterCommit!(target) } : {}),
validate: async tx => {
await authorizeStoredRequest(tx, row, true);
await assertKeepDbAdmission(tx, row);
@@ -179,15 +181,16 @@ export async function prepareReconcileMutation(engine: BrainEngine, row: WriteRe
await ready.validate(tx);
},
apply: async tx => {
- await ready.apply(tx);
+ const installed = await ready.apply(tx);
if (state.originSourcePath) {
await bindOrigin(tx, { sourceId: row.source_id, slug: row.slug, sourcePath: state.originSourcePath, onlyIfUnset: true, liveOnly: true });
}
// The page has a canonical origin (adopted above, or already recorded, #6536): drop the #5254 database-only classification.
await tx.executeRaw(`UPDATE pages SET database_only_reason=NULL WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL
AND database_only_reason IN ('unbound_source', 'origin_twin', 'mirror_read_only') AND source_path IS NOT NULL`, [row.source_id, row.slug]);
- if (!ready.noop) { await prepared.project!(tx); await sealPageTextProjection(tx, row.slug, row.source_id); }
- const final = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id });
+ // A body stored in segments was sealed by its import's apply when complete (sealSegmentedPage); the inline text seal reads the whole timeline.
+ if (!ready.noop) { await prepared.project!(tx); if (!installed?.segmented) await sealPageTextProjection(tx, row.slug, row.source_id); }
+ const final = await materializedSnapshot(tx, await tx.readPageSnapshot(row.slug, { sourceId: row.source_id }));
const scanStateTransferred = final ? await transferLegacyAtomPageState(tx, state.snapshot, final) : false;
const reading = reconcileFileReading(readFileSync(state.path, 'utf8'), state.importPath, final?.page ?? state.snapshot.page);
const file = parseMarkdown(reading.content, row.slug);
diff --git a/src/core/persistence/reconcile-state.ts b/src/core/persistence/reconcile-state.ts
index 6ae96b2f9b..da721e34be 100644
--- a/src/core/persistence/reconcile-state.ts
+++ b/src/core/persistence/reconcile-state.ts
@@ -8,7 +8,8 @@ import { alignWithStored } from './align-stored.ts';
import { parseDataFrontmatter } from '../data-frontmatter.ts';
import { OperationError, opError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
-import type { PageSnapshot } from '../page-state/types.ts';
+import { REVISION_BACKFILL_PENDING, type PageSnapshot } from '../page-state/types.ts';
+import { REVISION_BACKFILL_RESUME_COMMAND } from '../page-state/revision-backfill-schema.ts';
import { isWriteTargetContained } from '../path-confine.ts';
import { recordedPathFromFileUri, scannerSlugRootMode, scannerSourcePath } from '../write-through.ts';
import { absentCanonicalPath, findLiveFileClaimants, recordedReconcilePath, type FileClaimTarget } from './file-claims.ts';
@@ -229,6 +230,10 @@ export async function readReconcileState(engine: BrainEngine, sourceId: string,
if (!snapshot || snapshot.page.deleted_at) throw opError('page_not_found', 'Reconciliation requires an existing live page; use the separate restore workflow for deleted pages.',
`Page ${slug} in '${sourceId}' is deleted or missing; nothing changed. If it was deleted by mistake, restore it (gbrain restore, within the 72-hour window) and then preview it again.`,
{ fix: readFix('Shows whether the page exists or is soft-deleted in this source.', { argv: ['gbrain', 'get', '--source', sourceId, '--include-deleted', '--', slug] }) });
+ if (snapshot.revision === REVISION_BACKFILL_PENDING) throw opError('revision_backfill_pending', 'Reconciliation requires the page revision, and this page has none yet.',
+ `Nothing changed. Page ${slug} in '${sourceId}' was written before page revisions and the revision backfill has not reached it, so no reconcile preview can bind to it. Resume the backfill on the brain host with ${REVISION_BACKFILL_RESUME_COMMAND} (the command in fix), then preview the page again.`,
+ { fix: { argv: REVISION_BACKFILL_RESUME_COMMAND.split(' '), consent: [], actor: 'agent', requires_exclusive: true, docs: 'docs/guides/write-refusals.md#revision-backfill',
+ why: 'Re-runs the schema migration pass on the brain host, which resumes the page revision backfill and prints its progress; it changes no page content.' } });
if (binding.source_incarnation !== snapshot.sourceIncarnation) staleReconcile('source binding incarnation');
const [storedPage] = await engine.executeRaw<Record<string, unknown>>(`SELECT id,source_id,slug,type,title,compiled_truth,timeline,frontmatter,
content_hash,source_path,source_kind,source_uri,ingested_via,ingested_at,knowledge_revision,deleted_at FROM pages WHERE id=$1 AND source_id=$2`, [snapshot.page.id, sourceId]);
@@ -339,20 +344,22 @@ export function validateReconcileArtifact(value: unknown): ReconcileArtifact {
'owner_epoch', 'revision', 'raw_file_hash', 'relative_path', 'policy_digest', 'withdrawals_digest', 'assessment_at']);
strictReconcileKeys(value.preimages, ['file_base64', 'database', 'stored_page']);
// globalPurges is optional here so an artifact written before the '*' purge marker validates and then reads stale (assertPreimages).
- strictReconcileKeys(value.preimages.database, ['page', 'tags', 'revision', 'sourceIncarnation', 'withdrawals', 'globalPurges'],
+ // A page stored in segments (`body_storage`) is reconciled from its materialized body; its snapshot pins the body generation.
+ strictReconcileKeys(value.preimages.database, ['page', 'tags', 'revision', 'sourceIncarnation', 'withdrawals', 'globalPurges', 'bodyGeneration'],
['page', 'tags', 'revision', 'sourceIncarnation', 'withdrawals']);
if (value.preimages.database.globalPurges !== undefined) strictReconcileKeys(value.preimages.database.globalPurges, ['count', 'latest', 'world_only']);
strictReconcileKeys(value.preimages.database.page, ['id', 'slug', 'source_id', 'type', 'title', 'compiled_truth', 'timeline', 'frontmatter',
'content_hash', 'source_path', 'knowledge_revision', 'text_projection_revision', 'emotional_weight', 'created_at', 'updated_at', 'updated_at_iso',
'deleted_at', 'effective_date', 'effective_date_source', 'import_filename', 'salience_touched_at', 'source_kind', 'source_uri', 'ingested_via',
- 'ingested_at', 'contextual_retrieval_mode', 'corpus_generation', 'withheld_source_path'], ['id', 'slug', 'source_id', 'type', 'title', 'compiled_truth', 'timeline', 'frontmatter']);
+ 'ingested_at', 'contextual_retrieval_mode', 'corpus_generation', 'withheld_source_path', 'body_storage', 'body_bytes'], ['id', 'slug', 'source_id', 'type', 'title', 'compiled_truth', 'timeline', 'frontmatter']);
strictReconcileKeys(value.preimages.stored_page, ['id', 'source_id', 'slug', 'type', 'title', 'compiled_truth', 'timeline', 'frontmatter',
'content_hash', 'source_path', 'source_kind', 'source_uri', 'ingested_via', 'ingested_at', 'knowledge_revision', 'deleted_at']);
strictReconcileKeys(value.result, ['type', 'title', 'compiled_truth', 'timeline', 'frontmatter', 'tags']);
const result = value.result;
if (value.format_version !== 1 && !v2 || typeof value.preview_id !== 'string' || !['ready', 'needs_resolution'].includes(String(value.status)) ||
!Array.isArray(value.conflicts) || !Array.isArray(value.decisions) || !Array.isArray(value.preimages.database.tags) ||
- !Array.isArray(value.preimages.database.withdrawals) || !Array.isArray(value.result.tags) || value.result.tags.some(v => typeof v !== 'string') ||
+ !Array.isArray(value.preimages.database.withdrawals) || value.preimages.database.bodyGeneration !== undefined && !Number.isSafeInteger(value.preimages.database.bodyGeneration) ||
+ !Array.isArray(value.result.tags) || value.result.tags.some(v => typeof v !== 'string') ||
['type', 'title', 'compiled_truth', 'timeline'].some(key => typeof result[key] !== 'string') ||
value.result.frontmatter === null || typeof value.result.frontmatter !== 'object' || Array.isArray(value.result.frontmatter) ||
typeof value.preimages.file_base64 !== 'string' ||
diff --git a/src/core/repair/core.ts b/src/core/repair/core.ts
index a966c50802..ca9d4aeba7 100644
--- a/src/core/repair/core.ts
+++ b/src/core/repair/core.ts
@@ -92,7 +92,7 @@ export interface RepairPlan {
scan?: { fresh_at: string | null; partial: boolean };
}
-export interface RepairListing { item: string; class: string; detail?: string }
+export interface RepairListing { item: string; class: string; detail?: string; fix?: Action }
/**
* What the run was asked to do; preview-bound kinds read `expect`, `includeAmbiguous` and the `only`/`skip` path
diff --git a/src/core/repair/file-drift.ts b/src/core/repair/file-drift.ts
index 17d6b4a687..99ad7f8d05 100644
--- a/src/core/repair/file-drift.ts
+++ b/src/core/repair/file-drift.ts
@@ -72,7 +72,7 @@ import { canonicalFilesystemPath } from '../persistence/root-registry.ts';
import { auditDriftConflicts, DRIFT_CLASSES, driftClass, liveFileDrift, type DriftClass } from '../persistence/drift-conflicts.ts';
import { protectedReconcileKey, reconcileCanonical, RECONCILE_SCAN_KEYS, type ReconcileDecision } from '../persistence/reconcile-merge.ts';
import { fileWinsContent } from '../persistence/file-wins-content.ts';
-import { ABSENT_FILE_HASH, canonicalDeletionState, missingFileRoute, readCanonicalFileText, readDeletedDriftTarget, readReconcileState, type DeletedDriftChange, type DeletedDriftTarget, type ReconcileArtifact } from '../persistence/reconcile-state.ts';
+import { ABSENT_FILE_HASH, canonicalDeletionState, missingFileRoute, readCanonicalFileText, readDeletedDriftTarget, readReconcileState, validateReconcileArtifact, type DeletedDriftChange, type DeletedDriftTarget, type ReconcileArtifact } from '../persistence/reconcile-state.ts';
import { sourceDbOnlyVerdict } from '../persistence/source-storage.ts';
import { clearGitHold, readGitHold, fileDriftActionVerb, fileDriftSide, FILE_DRIFT_DELETED_STATES, FILE_DRIFT_SIDES, GIT_HOLD_OP, heldDriftPreviewArgv, requestGitHoldRetry, type FileDriftDeletedState, type FileDriftSide, type GitHoldRecord } from '../persistence/sync-holds.ts';
import { prepareRepairPublication, repairScreenConfig, submitManagedFileRepair } from '../persistence/file-repair.ts';
@@ -516,6 +516,11 @@ export async function prepareDriftPage(engine: BrainEngine, sourceId: string, sl
preimages: JSON.parse(stableJson({ file_base64: state.raw.toString('base64'), database: state.snapshot, stored_page: state.storedPage })),
decisions, conflicts: [], result: prepared.result, result_digest: digest(prepared.result), status: 'ready' };
await assertReconcileSize(engine, preview);
+ // The apply reads this preview back from the artifact file and refuses one its validation rejects; refuse it here instead.
+ try { validateReconcileArtifact(JSON.parse(stableJson(preview))); } catch (error) {
+ if (error instanceof OperationError && !error.fix) error.fix = readFix(`gbrain wrote a reconcile preview of ${slug} that its own apply refuses, so nothing was approved or written; report it with the output of gbrain doctor --json.`, {});
+ throw error;
+ }
return { slug, prefer, adopt_slug_path: adopt, exceptions: driftExceptions(prepared.result, prefer === 'file' ? file : database), result: prepared.result, preview,
...(opts.fileGone ? { file_gone: true as const } : {}), ...(appends ? { file_appended: true as const } : {}) };
}
@@ -680,7 +685,8 @@ async function applyDeletedSide(ctx: OperationContext, page: ApprovedPage, artif
} catch (error) {
if (acceptedPendingReceipt(error) || !(error instanceof OperationError) || ['owner_unavailable', 'writer_lock_unavailable', 'writer_busy', 'write_pending'].includes(error.code)) throw error;
const changed = ['changed_since_preview', 'revision_conflict', 'page_identity_changed', 'page_not_found', 'source_changed'].includes(error.code);
- return { applied: false, outcome: changed ? 'changed_since_preview' : 'refused', reason: error.code, detail: { request_id: requestId, action, message: error.message } };
+ return { applied: false, outcome: changed ? 'changed_since_preview' : 'refused', reason: error.code,
+ detail: { request_id: requestId, action, message: error.message, fix: error.fix ?? repreviewFix(page, artifact.prefer) } };
}
}
@@ -707,6 +713,12 @@ function provenanceText(found: DeletionProvenance): string {
: 'provenance unknown: Git could not name the deleting commit';
}
+/** The next step after a page's apply refused or found it changed: preview that page alone again (read-only), which names its current refusal or a fresh apply command. */
+function repreviewFix(page: ApprovedPage, prefer: DriftSide) {
+ return readFix(`Previews ${page.slug} in '${page.source_id}' alone again: it re-reads the page and its file and prints the current refusal with its fix, or a new apply command.`,
+ { argv: ['gbrain', 'repair', 'file-drift', '--source', page.source_id, '--slug', page.slug, '--prefer', prefer] });
+}
+
function item(page: ApprovedPage, index: number, hash: string, last: boolean, prefer: DriftSide): DriftItem {
return { cursor: { phase: 0, id: index + 1 }, source_id: page.source_id, slug: page.slug, chars: 0, action: `prefer_${prefer}`, page, hash, last };
}
@@ -831,7 +843,7 @@ export const fileDriftRepair: RepairHandler = {
} catch (error) {
if (!(error instanceof OperationError) || ['owner_unavailable', 'writer_registration_required'].includes(error.code)) throw error;
count(`refused_${error.code}`);
- listing.push({ item: `${sourceId}:${label}`, class: 'refused', detail: `${error.code}: ${error.message}` });
+ listing.push({ item: `${sourceId}:${label}`, class: 'refused', detail: `${error.code}: ${error.message}`, ...(error.fix ? { fix: error.fix } : {}) });
}
}
});
@@ -917,7 +929,8 @@ export const fileDriftRepair: RepairHandler = {
if (acceptedPendingReceipt(error) || !(error instanceof OperationError) || ['owner_unavailable', 'writer_lock_unavailable', 'writer_busy', 'write_pending'].includes(error.code)) throw error;
const changed = error.code === 'revision_conflict' || error.code === 'page_identity_changed' || error.code === 'page_not_found'
|| error.code === 'source_changed' && error.message.startsWith('Reconciliation preview is stale');
- outcome = { applied: false, outcome: changed ? 'changed_since_preview' : 'refused', reason: error.code, detail: { request_id: requestId, message: error.message } };
+ outcome = { applied: false, outcome: changed ? 'changed_since_preview' : 'refused', reason: error.code,
+ detail: { request_id: requestId, message: error.message, fix: error.fix ?? repreviewFix(page, artifact.prefer) } };
}
if (last) {
await clearApprovedSet(ctx.engine, { command: 'file-drift', hash });
diff --git a/test/e2e/file-drift-segmented-protected-gst1555-postgres.test.ts b/test/e2e/file-drift-segmented-protected-gst1555-postgres.test.ts
new file mode 100644
index 0000000000..3ca26c6775
--- /dev/null
+++ b/test/e2e/file-drift-segmented-protected-gst1555-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../file-drift-segmented-protected-gst1555.test.ts'));
diff --git a/test/file-drift-segmented-protected-gst1555.test.ts b/test/file-drift-segmented-protected-gst1555.test.ts
new file mode 100644
index 0000000000..b8e47ea7d3
--- /dev/null
+++ b/test/file-drift-segmented-protected-gst1555.test.ts
@@ -0,0 +1,161 @@
+/**
+ * GST-1555: `gbrain repair file-drift --prefer file` on a page stored in segments whose database copy keeps protected parts.
+ *
+ * 1. Protects: a held `file_drift` page (side unknown: an older gbrain forgot its import record) whose body is stored in
+ * segments (`pages.segmented_storage`), with a protected frontmatter key and a timeline row only the database has. Its
+ * preview listed both exceptions (`protected_metadata`, `protected_takes_or_private_facts`) and an apply command, and that
+ * apply refused every time with `invalid_params` "Unsupported or missing reconciliation fields." and no fix: the preview's
+ * snapshot of a segmented page carries `bodyGeneration` and `body_storage`, which the artifact validation did not accept,
+ * and past it the publication sealed the page with the inline text seal, which refuses a segmented body. The apply now
+ * imports the file with the same protections (the file keeps its bytes plus the appended key and row; the page keeps the
+ * key and the row), the page stays segmented and sealed, and the next sync releases the hold. The preview validates its
+ * own artifact as the apply will, so a preview the apply would refuse is refused in the preview.
+ * 2. A page with no revision (the revision backfill has not reached it) refused in the preview as a stale preview with no
+ * fix. It now refuses `revision_backfill_pending` with the backfill resume command in fix, and writes nothing.
+ * 3. A page whose apply refuses or finds it changed carries a fix (a read-only preview of that page alone).
+ * 4. Repo-less: a plain-directory source (no Git) resolves the same segmented page through `--slug`.
+ *
+ * Runs on PGLite, and on Postgres when DATABASE_URL is set (test/e2e/file-drift-segmented-protected-gst1555-postgres.test.ts).
+ */
+import { describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { registerLocalWriter, withVerifiedLocalRegistration } from '../src/core/persistence/identity.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { strictReconcileKeys } from '../src/core/persistence/reconcile-merge.ts';
+import { materializedSnapshot } from '../src/core/persistence/segmented-apply.ts';
+import { resolveRepairScope } from '../src/core/repair/core.ts';
+import { repairRunner } from '../src/core/repair/registry.ts';
+import { managedBrain, settleManagedGitEffects } 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', 'user.name=Example', '-c', '[email protected]',
+ '-c', 'commit.gpgsign=false', ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const commitAll = (root: string, message: string) => { git(root, 'add', '-A'); git(root, 'commit', '-qm', message); };
+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };
+const logger = { info() {}, warn() {}, error() {} };
+const SLUG = 'notes/alpha';
+/** Over the 1 MiB inline bound, so the page is stored in segments. */
+const FILLER = Array.from({ length: 16_000 }, (_, i) => `- ${String(i).padStart(9, '0')} acme-example journal line with enough text to fill a segment\n`).join('');
+const FILE = `---\ntitle: Alpha Example\ntype: concept\n---\n\nIntro paragraph.\n\n${FILLER}\n## Timeline\n\n- 2026-01-01: First event.\n`;
+
+const coordinated = (engine: BrainEngine, sql: string, params: unknown[] = []) =>
+ engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(sql, params), TEST_WRITE_ATTRIBUTION));
+const holds = async (engine: BrainEngine) => (await engine.executeRaw<{ r: { path: string; code: string; meta: { side?: string } } }>(
+ "SELECT completed_keys->0 AS r FROM op_checkpoints WHERE op='sync-hold' ORDER BY fingerprint")).map(({ r }) => `${r.path} ${r.code} ${r.meta.side ?? ''}`.trim());
+const fileDrift = async (engine: BrainEngine, opts: Record<string, unknown>) => withVerifiedLocalRegistration(engine, await registerLocalWriter(engine, 'cli'), async () =>
+ (await repairRunner(engine, { apply: opts.expect !== undefined, logger })).run('file-drift', await resolveRepairScope(engine, 'default'),
+ { explicit: true, sourceFlag: 'default', prefer: 'file', ...opts }));
+type Listing = Array<{ item: string; class: string; detail?: string; fix?: { argv?: string[] } }>;
+type Outcome = Array<{ item: string; outcome: string; reason?: string; detail?: { fix?: { argv?: string[] } } }>;
+
+async function segmentedOn(engine: BrainEngine): Promise<void> {
+ await engine.setConfig('pages.segmented_storage', 'on');
+ await engine.setConfig('pages.max_bytes', String(64 * 1024 * 1024));
+}
+/** The database copy keeps a protected key and a timeline row the file lacks; the file then gets its own edit. */
+async function protectedParts(engine: BrainEngine, root: string): Promise<void> {
+ await coordinated(engine, `UPDATE pages SET frontmatter = frontmatter || '{"embed_skip": true}'::jsonb WHERE source_id='default' AND slug=$1`, [SLUG]);
+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.addTimelineEntry(SLUG,
+ { date: '2026-02-01', summary: 'A database-only event.', source: 'example', detail: '' }, { sourceId: 'default' }), TEST_WRITE_ATTRIBUTION));
+ writeFileSync(join(root, `${SLUG}.md`), readFileSync(join(root, `${SLUG}.md`), 'utf8').replace('Intro paragraph.', 'Intro paragraph, edited.'));
+}
+async function assertImported(engine: BrainEngine, root: string, before: string): Promise<void> {
+ const after = readFileSync(join(root, `${SLUG}.md`), 'utf8');
+ // The file keeps its own bytes; only the protected key (before the closing ---) and the database-only row (at the end) are added.
+ let kept = after.replace(/\nembed_skip: true\n---\n/, '\n---\n').replace(/<!-- gbrain:materialized v1 [0-9a-f]+ -->\n- \*\*2026-02-01\*\* \| example — A database-only event\.\n$/, '');
+ if (!before.includes('<!-- timeline -->')) kept = kept.replace('<!-- timeline -->\n\n', '');
+ expect(kept).toBe(before);
+ expect(after).not.toBe(before);
+ const [row] = await engine.executeRaw<{ body_storage: string; embed_skip: boolean; sealed: boolean }>(`SELECT body_storage, (frontmatter->>'embed_skip')::boolean AS embed_skip,
+ text_projection_revision = knowledge_revision AS sealed FROM pages WHERE source_id='default' AND slug=$1`, [SLUG]);
+ expect(row).toEqual({ body_storage: 'segmented', embed_skip: true, sealed: true });
+ const { page } = (await materializedSnapshot(engine, await engine.readPageSnapshot(SLUG, { sourceId: 'default' })))!;
+ expect(page.compiled_truth).toContain('Intro paragraph, edited.');
+ expect(page.timeline).toContain('A database-only event.');
+}
+
+for (const backend of testBackends()) describe(`GST-1555 file wins on a segmented page with protected parts (${backend})`, () => {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+ const repo = async ({ engine, root }: { engine: BrainEngine; root: string }) => {
+ await segmentedOn(engine);
+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');
+ writeFileSync(join(root, `${SLUG}.md`), FILE); commitAll(root, 'alpha');
+ };
+
+ test('the held page imports file-wins with its protections, stays segmented and sealed, and the next sync releases the hold', () => managedBrain(async ({ engine, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ expect((await engine.executeRaw<{ body_storage: string }>("SELECT body_storage FROM pages WHERE slug=$1", [SLUG]))[0]!.body_storage).toBe('segmented');
+ await coordinated(engine, `DELETE FROM op_checkpoints WHERE op='sync-import-provenance'
+ AND completed_keys->0->>'page_id' IN (SELECT id::text FROM pages WHERE source_id='default' AND slug=$1)`, [SLUG]);
+ await coordinated(engine, "UPDATE pages SET knowledge_revision=$2::uuid, revision_write_request_id=NULL WHERE source_id='default' AND slug=$1", [SLUG, randomUUID()]);
+ await protectedParts(engine, root); commitAll(root, 'edit alpha');
+ await performManagedSync(engine, OPTS);
+ expect(await holds(engine)).toEqual(['notes/alpha.md file_drift unknown']);
+ const before = readFileSync(join(root, `${SLUG}.md`), 'utf8');
+
+ const preview = await fileDrift(engine, { held: true, side: 'unknown' });
+ expect((preview.listing as Listing).map(row => `${row.item} ${row.class}`)).toEqual(['default:notes/alpha prefer_file']);
+ expect((preview.details!.pages as Array<{ exceptions: Array<{ path: string; reason: string }> }>)[0]!.exceptions)
+ .toEqual([{ path: '/timeline', reason: 'protected_takes_or_private_facts' }, { path: '/frontmatter/embed_skip', reason: 'protected_metadata' }]);
+ const applied = await fileDrift(engine, { held: true, side: 'unknown', expect: preview.preview_hash });
+ expect(applied.outcomes).toEqual({ repaired: 1 });
+ await assertImported(engine, root, before);
+ commitAll(root, 'repair');
+ await performManagedSync(engine, OPTS);
+ expect(await holds(engine)).toEqual([]);
+ }, { databaseUrl, setup: repo }), 240_000);
+
+ test('a page with no revision refuses revision_backfill_pending in the preview, with the backfill resume command in fix', () => managedBrain(async ({ engine, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ await protectedParts(engine, root); commitAll(root, 'edit alpha');
+ await engine.executeRaw('ALTER TABLE pages ALTER COLUMN knowledge_revision DROP NOT NULL');
+ await engine.executeRaw('ALTER TABLE pages DISABLE TRIGGER USER');
+ await engine.executeRaw("UPDATE pages SET knowledge_revision=NULL WHERE source_id='default' AND slug=$1", [SLUG]);
+ await engine.executeRaw('ALTER TABLE pages ENABLE TRIGGER USER');
+ const before = readFileSync(join(root, `${SLUG}.md`), 'utf8');
+ const preview = await fileDrift(engine, { slugs: [SLUG] });
+ const [row] = preview.listing as Listing;
+ expect(row).toMatchObject({ item: 'default:notes/alpha', class: 'refused' });
+ expect(row!.detail).toStartWith('revision_backfill_pending: ');
+ expect(row!.fix?.argv).toEqual(['gbrain', 'apply-migrations', '--force-schema']);
+ expect(preview.details!.pages).toEqual([]);
+ expect(readFileSync(join(root, `${SLUG}.md`), 'utf8')).toBe(before);
+ }, { databaseUrl, setup: repo }), 240_000);
+
+ test('repo-less: a plain-directory source imports the segmented page file-wins with its protections, and a changed page carries a fix', () => managedBrain(async ({ engine, ctx, root }) => {
+ await segmentedOn(engine);
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: SLUG, content: FILE, request_id: randomUUID() } });
+ await settleManagedGitEffects(engine);
+ expect((await engine.executeRaw<{ body_storage: string }>("SELECT body_storage FROM pages WHERE slug=$1", [SLUG]))[0]!.body_storage).toBe('segmented');
+ await protectedParts(engine, root);
+ const before = readFileSync(join(root, `${SLUG}.md`), 'utf8');
+ const preview = await fileDrift(engine, { slugs: [SLUG] });
+ expect((preview.listing as Listing).map(row => row.class)).toEqual(['prefer_file']);
+
+ // An edit after the preview: the apply finds the page changed, writes nothing and names the next step.
+ writeFileSync(join(root, `${SLUG}.md`), before.replace('Intro paragraph, edited.', 'Intro paragraph, edited twice.'));
+ const changed = await fileDrift(engine, { slugs: [SLUG], expect: preview.preview_hash });
+ const [item] = changed.outcome_items as Outcome;
+ expect(item).toMatchObject({ item: 'default:notes/alpha', outcome: 'changed_since_preview' });
+ expect(item!.detail?.fix?.argv).toEqual(['gbrain', 'repair', 'file-drift', '--source', 'default', '--slug', SLUG, '--prefer', 'file']);
+
+ writeFileSync(join(root, `${SLUG}.md`), before);
+ const again = await fileDrift(engine, { slugs: [SLUG] });
+ expect((await fileDrift(engine, { slugs: [SLUG], expect: again.preview_hash })).outcomes).toEqual({ repaired: 1 });
+ await assertImported(engine, root, before);
+ }, { databaseUrl }), 240_000);
+});
+
+describe('GST-1555 reconcile field refusals name the fields', () => {
+ test('an unsupported or missing field is named in why', () => {
+ const refusal = (() => { try { strictReconcileKeys({ path: '/title', extra: 1 }, ['path', 'action'], ['path', 'action']); } catch (error) { return error; } })() as { code: string; why: string };
+ expect(refusal).toMatchObject({ code: 'invalid_params', why: 'unsupported: extra; missing: action' });
+ });
+});