Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(reconcile): opt-in --adopt-slug-path for a page with no recorded origin (#6394)

time-attack8d6df086e592
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.md
index 0872b10c86..0597f12548 100644
--- a/docs/architecture/key-files/canonical-reconciliation.md
+++ b/docs/architecture/key-files/canonical-reconciliation.md
@@ -2,7 +2,7 @@
- `src/commands/sync-diagnostics.ts` + `src/core/persistence/{sync-run,verb-errors}.ts` — bounded source/slug/path/reason diagnostics derive from immutable managed-sync receipts, including when the local failure ledger is unavailable. Direct and resident-owner JSON carry the same receipt; human memory errors lead with the specific write reason without widening frozen v1 error codes. Pending requests retain their original UUID, terminal corrections require a new UUID, and neither retry nor line-ending diagnostics bypasses raw-byte or skip guards.
-- `src/core/persistence/reconcile*.ts` — trusted-local exact-page reconciliation: loss-preserving semantic preview, explicit JSON Pointer choices, pinned identity/revision/raw-file/policy checks, durable private preimages and same-ID replay through the existing coordinator. Normal overwrite protection stays unchanged. The bounded audit reports source-scoped drift without repair or checkpoint changes; a database-only page (`isDatabaseOnlyPage`, with no file at its slug-derived path) counts as `database_only` with no reconcile suggestion, never as drift, while a legacy row that merely lacks `source_path` is audited as usual. `src/commands/source-reconcile.ts` provides strict CLI parsing, private artifact I/O, brain routing and resident-owner delegation; the operations stay outside public MCP. Operator flow: `docs/guides/concurrent-writes.md`. Tests cover merge choices, both engines, grants, stale previews, read-only audit, and private files. A database-only page (no `source_path`, no `source_uri`; `isDatabaseOnlyPage` in `src/core/persistence/unbound-pages.ts`) is matched to the canonical file at its slug-derived path (`ReconcileState.origin: 'slug_derived'`), and apply records that path as its `source_path` (the #5254 unbound collision; `test/reconcile-unbound-collision.test.ts`). Private fact rows (#6137): `reconcile-prepare.ts` `privateFactViolation` identifies a fact row by (row number, claim), as `restoreHiddenFactRows` does. A stored non-world row carried at its identity must be unchanged; a row at no stored identity may not carry a stored private claim under another visibility, and a world row may not carry (or newly gain) a stored private row's context of 24 or more characters verbatim; sources are not compared. The `permission_denied` refusal names only the row number, with a `gbrain get` read fix. It guards verbatim copies, not reworded text. #6138: an `--auto-additive` preview classified `no_drift` asks Git (`hardened-git.ts` `hardenedPathDirty`: filter-free plumbing, never `git status`, so the checkout's clean/process filters never run; `null` when only repository config could decide) whether the canonical file differs from its last commit and returns `git_dirty`; a dirty file's `next_action` says the content agrees, the difference is only how it is written, reconcile does not commit, and names `git -C <root> diff -- <file>` (committing it is the user's decision; the managed commit path is deferred, D5). The "retry the original write" step is conditional on the preview coming from a refused write. Tests: `test/persistence-reconcile-git-dirty-6138.test.ts`. #6222/#6254: `assertSoleFileClaim` (reconcile-state.ts) pages the "no other page claims this file" census 100 rows at a time below the source's highest page id, so a common file name no longer refuses; realpath still decides each candidate. Its predicates (`fileClaimCandidatesSql`) match the v219 expression indexes `pages_source_path_name_idx` and `pages_file_uri_name_idx` (built online, one statement per call). `sources reconcile` help says writes to one source publish one at a time. Tests: `test/persistence-reconcile.test.ts`, `test/e2e/pages-reconcile-name-indexes-postgres.test.ts`.
+- `src/core/persistence/reconcile*.ts` — trusted-local exact-page reconciliation: loss-preserving semantic preview, explicit JSON Pointer choices, pinned identity/revision/raw-file/policy checks, durable private preimages and same-ID replay through the existing coordinator. Normal overwrite protection stays unchanged. The bounded audit reports source-scoped drift without repair or checkpoint changes; a database-only page (`isDatabaseOnlyPage`, with no file at its slug-derived path) counts as `database_only` with no reconcile suggestion, never as drift, while a legacy row that merely lacks `source_path` is audited as usual. `src/commands/source-reconcile.ts` provides strict CLI parsing, private artifact I/O, brain routing and resident-owner delegation; the operations stay outside public MCP. Operator flow: `docs/guides/concurrent-writes.md`. Tests cover merge choices, both engines, grants, stale previews, read-only audit, and private files. A database-only page (no `source_path`, no `source_uri`; `isDatabaseOnlyPage` in `src/core/persistence/unbound-pages.ts`) is matched to the canonical file at its slug-derived path (`ReconcileState.origin: 'slug_derived'`), and apply records that path as its `source_path` (the #5254 unbound collision; `test/reconcile-unbound-collision.test.ts`). Private fact rows (#6137): `reconcile-prepare.ts` `privateFactViolation` identifies a fact row by (row number, claim), as `restoreHiddenFactRows` does. A stored non-world row carried at its identity must be unchanged; a row at no stored identity may not carry a stored private claim under another visibility, and a world row may not carry (or newly gain) a stored private row's context of 24 or more characters verbatim; sources are not compared. The `permission_denied` refusal names only the row number, with a `gbrain get` read fix. It guards verbatim copies, not reworded text. #6138: an `--auto-additive` preview classified `no_drift` asks Git (`hardened-git.ts` `hardenedPathDirty`: filter-free plumbing, never `git status`, so the checkout's clean/process filters never run; `null` when only repository config could decide) whether the canonical file differs from its last commit and returns `git_dirty`; a dirty file's `next_action` says the content agrees, the difference is only how it is written, reconcile does not commit, and names `git -C <root> diff -- <file>` (committing it is the user's decision; the managed commit path is deferred, D5). The "retry the original write" step is conditional on the preview coming from a refused write. Tests: `test/persistence-reconcile-git-dirty-6138.test.ts`. #6222/#6254: `assertSoleFileClaim` (reconcile-state.ts) pages the "no other page claims this file" census 100 rows at a time below the source's highest page id, so a common file name no longer refuses; realpath still decides each candidate. Its predicates (`fileClaimCandidatesSql`) match the v219 expression indexes `pages_source_path_name_idx` and `pages_file_uri_name_idx` (built online, one statement per call). `sources reconcile` help says writes to one source publish one at a time. Tests: `test/persistence-reconcile.test.ts`, `test/e2e/pages-reconcile-name-indexes-postgres.test.ts`. #6394: `readReconcileState(..., { adoptSlugPath })` lets a live page with no recorded origin and no database-only marker reconcile against the file at its slug path (`slugDerivedOrigin`, mode-aware), never for a declared db_only slug, a never-filed derive-phase page, a page with a `source_uri` or a mirror-only page; the CLI flag is `gbrain sources reconcile … --preview --adopt-slug-path`, and apply and the consumer's prepare adopt only when the preview's stored page recorded no origin (`reconcilePreviewAdopts`), with the pinned relative path and binding digest unchanged. The drift refusal names the flag for such a page.
- `src/core/persistence/reconcile-additive.ts` (#5974) — pure structural drift classifier over the complete file/database delta: inserted whole lines (two-pointer subsequence, CRLF-normalized; fence, heading and table insertions excluded) are `suggested`; an append-only `contacts` list, an allowlisted activity date moving forward, and one-sided ordinary fields are `auto`; policy/privacy/identity/tag changes and everything else are `review`. `--auto-additive` previews write `take_file` only for `auto` (and `suggested` with `--accept-suggested`), recorded as format-2 `auto_decisions` with an evidence digest that apply and owner preparation recheck. `--audit --classify` reports per-page verdicts and counts, never values.
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index a59a1fc1a7..7290aa48e6 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -36,7 +36,7 @@ of making a duplicate.
| Reason | Error code | What it means | Recovery |
| --- | --- | --- | --- |
-| `file_database_drift` | `source_changed` | The page's canonical file and its database copy disagree, usually because the file was edited outside a coordinated write. Neither copy was overwritten. A file with no `type:` line keeps the stored type, and titles compare trimmed, so those alone do not cause this. | `gbrain sources reconcile <source> <slug> --brain <brain> --preview`, review the preview, resolve it, then `--apply <resolved-preview-file> --request-id <new uuid>`. Retry the original write with a **new** request ID. See [repair a file/database disagreement](concurrent-writes.md#repair-a-filedatabase-disagreement). |
+| `file_database_drift` | `source_changed` | The page's canonical file and its database copy disagree, usually because the file was edited outside a coordinated write. Neither copy was overwritten. A file with no `type:` line keeps the stored type, and titles compare trimmed, so those alone do not cause this. | `gbrain sources reconcile <source> <slug> --brain <brain> --preview`, review the preview, resolve it, then `--apply <resolved-preview-file> --request-id <new uuid>`. Retry the original write with a **new** request ID. A page that records no file of its own (no `source_path`, typically written by an older release whose write-through also put `ingested_via` / `ingested_at` / `source_kind` in the file only) reconciles against the file at its slug path only when you add `--adopt-slug-path` to the preview; the refusal names the flag in that case, and apply records that file as the page's origin. See [repair a file/database disagreement](concurrent-writes.md#repair-a-filedatabase-disagreement). |
| <a id="writer-coordinator-required"></a>`database_guard` or `database_trigger` | `writer_coordinator_required` (or `storage_error` for another trigger) | A database trigger refused a row while a write was being prepared or published, so nothing was committed and any canonical file already replaced was restored. With `database_guard`, a gbrain process wrote a row its publication does not own (another source, an unresolvable source, or a source checkpoint/topology change outside owner administration). This is a gbrain defect or a version mismatch between gbrain processes sharing the database, not a content conflict. The receipt's `write_error_detail` names the table, operation, guard branch, source relationship and stage; it never contains page text or source names. | On the brain host run `gbrain sources writer status --probe --json`. Its `recent_failures[].error_detail` adds the source ids and the gbrain build and host that ran the attempt (`attempt.consumer_version`). If that build differs from `gbrain --version`, upgrade or restart every gbrain process that shares the database (serve, autopilot, sync jobs), then retry with a **new** request ID. If the builds match, report `error_detail` on the gbrain issue tracker. Never force-write, edit SQL or disable the guard. |
| `ambiguous_source_path` | `page_identity_changed` | A source registered at a Git subfolder `<sub>` has a page whose stored path `<sub>/<file>` could mean either `<file>` in the source directory (the older Git-root spelling) or `<sub>/<file>` inside a folder of the source that repeats its name, and both files exist. Sync refuses instead of guessing. See [sources in a Git subfolder](multi-source-brains.md#sources-in-a-git-subfolder). | Rename or move one of the two files, commit, then `gbrain sync --source <source> --no-pull --retry-failed`. |
| `physical_root_device_changed` | `recovery_required` | The checkout's filesystem device number changed while everything else matches, which macOS can do after a reboot. When the owner token, brain, worktree, root, inode and a non-zero birth time all match and the caller can verify database ownership, the write path re-stamps ownership by itself and the write proceeds. This refusal means the automatic re-stamp could not be verified; the suggestion says why. | Do a deliberate self-transfer: `gbrain sources writer status <source>` (note `admin_state`), then `gbrain sources writer transfer prepare <source> --self-transfer --admin-intent writer_transfer_prepare --expected-state <admin_state>`, then `gbrain sources writer transfer accept <source> --path <root> --expected-epoch <epoch> --manifest <digest from prepare> --self-transfer --admin-intent writer_transfer_accept --expected-state <fresh admin_state>`. Retry the original write with the **same** request ID. Never delete ownership marker files. |
diff --git a/src/commands/source-reconcile.ts b/src/commands/source-reconcile.ts
index 0c9693378e..1471e49d13 100644
--- a/src/commands/source-reconcile.ts
+++ b/src/commands/source-reconcile.ts
@@ -21,7 +21,7 @@ import { readLocalWriter, withVerifiedLocalRegistration } from '../core/persiste
import { reportPersistenceCliError } from './persistence-delegate.ts';
export const RECONCILE_HELP = `Usage:
- gbrain sources reconcile <source> <slug> --brain <id> [--preview] [--out <new-file>] [--json]
+ gbrain sources reconcile <source> <slug> --brain <id> [--preview] [--adopt-slug-path] [--out <new-file>] [--json]
gbrain sources reconcile <source> <slug> --brain <id> --preview --from <preview-file>
--decisions <decisions-file> --out <new-file> [--json]
gbrain sources reconcile <source> <slug> --brain <id> --preview --auto-additive [--accept-suggested]
@@ -35,7 +35,11 @@ export const RECONCILE_HELP = `Usage:
Preview is the default and never changes canonical content. A database-only
page (no recorded origin, for example one written while the source was unbound)
is previewed against the canonical file at its slug path; apply records that
-file as the page's origin. --out creates a new
+file as the page's origin. A page that records no origin and carries no
+database-only marker (an older write) is previewed against the file at its slug
+path only with --adopt-slug-path; the preview pins that file, apply records it
+as the page's origin, and the flag is refused for pages that are database-only
+by design. --out creates a new
private file outside canonical worktrees; it never replaces an existing file.
Resolve conflicts with JSON-Pointer decisions and inspect the resolved preview
before applying. Apply preserves both originals and uses the current canonical
@@ -77,7 +81,7 @@ export interface ReconcileCliArgs {
export function parseReconcileArgs(args: string[]): ReconcileCliArgs {
const flags = new Map<string, string | true>();
const positional: string[] = [];
- const boolean = new Set(['--preview', '--audit', '--backups', '--json', '--auto-additive', '--accept-suggested', '--classify']);
+ const boolean = new Set(['--preview', '--audit', '--backups', '--json', '--auto-additive', '--accept-suggested', '--classify', '--adopt-slug-path']);
const values = new Set(['--brain', '--out', '--from', '--decisions', '--apply', '--request-id', '--limit', '--after', '--remove-backup']);
for (let i = 0; i < args.length; i++) {
const token = args[i];
@@ -91,7 +95,7 @@ export function parseReconcileArgs(args: string[]): ReconcileCliArgs {
continue;
}
if (!values.has(flag)) throw opError('invalid_params', `Unknown reconciliation option: ${flag}.`,
- 'Reconciliation accepts --brain, --preview, --out, --from, --decisions, --apply, --request-id, --audit, --backups, --remove-backup, --limit, --after and --json; the help in fix shows which forms combine.',
+ 'Reconciliation accepts --brain, --preview, --adopt-slug-path, --out, --from, --decisions, --apply, --request-id, --audit, --backups, --remove-backup, --limit, --after and --json; the help in fix shows which forms combine.',
{ fix: readFix('Lists every reconciliation form and its options.', { argv: ['gbrain', 'sources', 'reconcile', '--help'] }) });
const value = equal >= 0 ? token.slice(equal + 1) : args[++i];
if (!value || value.startsWith('-') || value.includes('\0')) throw opError('invalid_params', `${flag} requires a value.`,
@@ -132,6 +136,8 @@ export function parseReconcileArgs(args: string[]): ReconcileCliArgs {
'Run the audit without --preview, --out, --from, --decisions, --auto-additive or --accept-suggested, then preview a page it lists in a separate command.');
if (flags.has('--classify') && !audit) throw opError('invalid_params', '--classify is only valid with --audit.',
'Add --audit (with --source), or drop --classify.');
+ if ((applying || backups || audit) && flags.has('--adopt-slug-path')) throw opError('invalid_params', '--adopt-slug-path only shapes a preview.',
+ 'Use --adopt-slug-path with --preview; apply adopts the file the written preview pinned.');
if ((applying || backups) && (flags.has('--auto-additive') || flags.has('--accept-suggested'))) throw opError('invalid_params', '--auto-additive and --accept-suggested only shape a preview.',
'Use --auto-additive (and --accept-suggested) with --preview, then apply the written preview with --from.');
if (flags.has('--accept-suggested') && !flags.has('--auto-additive')) throw opError('invalid_params', '--accept-suggested requires --auto-additive.',
@@ -155,6 +161,7 @@ export function parseReconcileArgs(args: string[]): ReconcileCliArgs {
}
if (applying) params.request_id = flags.get('--request-id');
if (flags.has('--auto-additive')) params.auto_additive = true;
+ if (flags.has('--adopt-slug-path')) params.adopt_slug_path = true;
if (flags.has('--accept-suggested')) params.accept_suggested = true;
if (flags.has('--classify')) params.classify = true;
if (flags.has('--limit')) {
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 3634fcc101..8a1b7f8c50 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -373,7 +373,7 @@ export const CODES = {
skill_retention_capacity: { class: 'caller', summary: "Retained skill revisions exceed this source storage budget." },
skill_unavailable: { class: 'caller', summary: "The qualified shared skill is not in this installation's current authorized view.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },
source_binding_required: { class: 'caller', summary: "A write needs an explicit source binding on this MCP server (--source-guard)." },
- source_changed: { class: 'caller', summary: "The source changed during the operation; nothing was committed." },
+ source_changed: { class: 'caller', summary: "The source changed during the operation; nothing was committed.", why: "Covers a replaced, archived or re-bound source and a canonical file that differs from the page's database copy (detail file_database_drift). A page that records no file of its own reconciles against the file at its slug path only with gbrain sources reconcile <source> <slug> --preview --adopt-slug-path." },
source_id_taken: { class: 'caller', summary: "This source already exists and does not match this exact admitted request." },
source_not_ready: { class: 'caller', summary: "A committed source and approved schema are required." },
source_profile_no_backfill: { class: 'unavailable', summary: "This source profile disables automatic embedding backfill." },
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 286d25be6a..c4acfbdf26 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -202,10 +202,12 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequ
if (!await fileMatchesSnapshot(engine, row.slug, before.toString('utf8'), snapshot, options.activePack)) {
const held = await heldFileRefusal(engine, row, root, path, 'drift', options.remote === true);
if (held) throw held;
+ // #6394: a page that never recorded its file reconciles against the file at its slug path only when adopted explicitly.
+ const adopt = !snapshot.page.source_path && !snapshot.page.source_uri ? ['--adopt-slug-path'] : [];
throw opError('source_changed', 'The canonical file contains an uncoordinated local edit.',
- `On the brain host, run gbrain sources reconcile ${row.source_id} ${row.slug} --brain <brain id, host by default> --preview, review and apply the resolved preview, then retry this write with a new request_id. Neither copy was overwritten.`,
+ `On the brain host, run gbrain sources reconcile ${row.source_id} ${row.slug} --brain <brain id, host by default> --preview${adopt.length ? ' --adopt-slug-path (the page records no file of its own, so the preview adopts the file at its slug path)' : ''}, review and apply the resolved preview, then retry this write with a new request_id. Neither copy was overwritten.`,
{ detail: 'file_database_drift', fix: readFix(`Previews how page ${row.slug}'s canonical file and database copy reconcile; a preview never changes canonical content.`,
- { argv: ['gbrain', 'sources', 'reconcile', row.source_id, row.slug, '--brain', 'host', '--preview'] }) });
+ { argv: ['gbrain', 'sources', 'reconcile', row.source_id, row.slug, '--brain', 'host', '--preview', ...adopt] }) });
}
} else if (before && !snapshot && content !== null && sha256(before) !== sha256(content)
&& !(options.capture && sha256(before) === options.capture.hash)) {
diff --git a/src/core/persistence/reconcile-prepare.ts b/src/core/persistence/reconcile-prepare.ts
index 7257c02fc8..6e7e7fb83f 100644
--- a/src/core/persistence/reconcile-prepare.ts
+++ b/src/core/persistence/reconcile-prepare.ts
@@ -21,7 +21,7 @@ import { preserveProtectedTakes } from './protected-takes.ts';
import { digest, sha256 } from './digest.ts';
import { mergeReconcile, reconcileCanonical, type ReconcileDecision } from './reconcile-merge.ts';
import { stabilizeSafetyAssessments } from './reconcile-safety.ts';
-import { assertReconcilePins, readReconcileState, staleReconcile, validateReconcileArtifact, type ReconcileState } from './reconcile-state.ts';
+import { assertReconcilePins, readReconcileState, reconcilePreviewAdopts, staleReconcile, validateReconcileArtifact, type ReconcileState } from './reconcile-state.ts';
import { verifyReconcileBackup } from './reconcile-backup.ts';
import { assertAutoDecisions } from './reconcile-additive.ts';
@@ -130,7 +130,8 @@ export async function prepareReconcileMutation(engine: BrainEngine, row: WriteRe
`The resolved preview applied by request ${row.request_id} is not ready or names a different source, page or page id than ${row.slug} in source ${row.source_id}. ${freshPreview(row.source_id, row.slug)}`,
{ fix: receiptFix(row) });
}
- const state = await readReconcileState(engine, row.source_id, row.slug, artifact.preconditions.assessment_at);
+ const adopt = { adoptSlugPath: reconcilePreviewAdopts(artifact) };
+ const state = await readReconcileState(engine, row.source_id, row.slug, artifact.preconditions.assessment_at, adopt);
assertReconcilePins(artifact.preconditions, state.pins);
assertAutoDecisions(artifact.auto_decisions ?? [], state.file, reconcileCanonical(state.snapshot.page, state.snapshot.tags), artifact.decisions);
const prepared = await prepareReconcileResult(engine, state, artifact.decisions);
@@ -144,7 +145,7 @@ export async function prepareReconcileMutation(engine: BrainEngine, row: WriteRe
noop: ready.noop && sha256(content) === state.pins.raw_file_hash && state.origin === 'recorded',
validate: async tx => {
await authorizeStoredRequest(tx, row, true);
- assertReconcilePins(artifact.preconditions, (await readReconcileState(tx, row.source_id, row.slug, artifact.preconditions.assessment_at)).pins);
+ assertReconcilePins(artifact.preconditions, (await readReconcileState(tx, row.source_id, row.slug, artifact.preconditions.assessment_at, adopt)).pins);
verifyReconcileBackup(reference, artifact);
await ready.validate(tx);
},
diff --git a/src/core/persistence/reconcile-state.ts b/src/core/persistence/reconcile-state.ts
index 995c307bb6..ff3d2345e7 100644
--- a/src/core/persistence/reconcile-state.ts
+++ b/src/core/persistence/reconcile-state.ts
@@ -19,6 +19,8 @@ import { digest, requireUuid, sha256, stableJson } from './digest.ts';
import { reconcileCanonical, strictReconcileKeys, validateReconcileJson, type ReconcileConflict, type ReconcileDecision } from './reconcile-merge.ts';
import type { ParsedPage } from '../import-file.ts';
import type { AutoDecision } from './reconcile-additive.ts';
+import { publishesDatabaseOnly } from './page-prepare.ts';
+import { isMirrorOnlyPage } from './mirror-read-only.ts';
export interface ReconcilePins {
brain_id: string; source_id: string; source_incarnation: string; slug: string; page_id: number;
@@ -127,7 +129,13 @@ async function assertSoleFileClaim(engine: BrainEngine, target: { sourceId: stri
afterId = Number(candidates[candidates.length - 1]!.id);
}
}
-export async function readReconcileState(engine: BrainEngine, sourceId: string, slug: string, assessmentAt = new Date().toISOString()): Promise<ReconcileState> {
+/**
+ * #6394: `adoptSlugPath` lets a live page with no recorded origin and no database-only marker reconcile against the file
+ * at its slug path (mode-aware, as discovery names it). A page that publishes database-only by design (a declared db_only
+ * slug, a never-filed derive-phase page) or a mirror-only page never adopts one.
+ */
+export async function readReconcileState(engine: BrainEngine, sourceId: string, slug: string, assessmentAt = new Date().toISOString(),
+ opts: { adoptSlugPath?: boolean } = {}): Promise<ReconcileState> {
const binding = await getWorktreeBinding(engine, sourceId);
if (!binding?.local_path || binding.owner_host_id !== localHostId() || binding.state !== 'active') {
throw new OperationError('owner_unavailable', 'Reconciliation requires the existing active owner on this host.', 'Run repair on the current owner; repair never claims or activates a source.');
@@ -144,12 +152,16 @@ export async function readReconcileState(engine: BrainEngine, sourceId: string,
const recorded = recordedPathFromFileUri(snapshot.page.source_uri, root);
const mode = await scannerSlugRootMode(engine, sourceId, root);
const recordedPath = recordedReconcilePath(root, snapshot.page, mode);
- const derived = !recordedPath && isDatabaseOnlyPage({ ...snapshot.page,
- database_only_reason: await isUnboundSourcePage(engine, sourceId, slug) ? 'unbound_source' : null }) ? slugDerivedOrigin(root, slug, mode) : null;
+ const marked = !recordedPath && isDatabaseOnlyPage({ ...snapshot.page,
+ database_only_reason: await isUnboundSourcePage(engine, sourceId, slug) ? 'unbound_source' : null });
+ const adoptable = !recordedPath && !marked && opts.adoptSlugPath === true && !snapshot.page.source_uri
+ && !publishesDatabaseOnly(root, slug, snapshot) && !await isMirrorOnlyPage(engine, sourceId, slug);
+ const derived = marked || adoptable ? slugDerivedOrigin(root, slug, mode) : null;
const origin = derived ? 'slug_derived' : 'recorded';
const path = recordedPath ?? derived?.path ?? null;
if (!path || !isWriteTargetContained(path, root)) throw opError('source_changed', 'The page has no unambiguous confined recorded Markdown origin.',
- `Page ${slug} in '${sourceId}' records no Markdown file inside the source checkout, so there is nothing to reconcile it against; nothing changed. Check its recorded source path with the command in fix.`,
+ `Page ${slug} in '${sourceId}' records no Markdown file inside the source checkout, so there is nothing to reconcile it against; nothing changed. ${!recordedPath && !marked && !snapshot.page.source_uri && opts.adoptSlugPath !== true
+ ? `If the file at its slug path is this page's canonical file, preview again with --adopt-slug-path (gbrain sources reconcile ${sourceId} ${slug} --preview --adopt-slug-path) to adopt it; otherwise check its recorded source path with the command in fix.` : 'Check its recorded source path with the command in fix.'}`,
{ fix: readFix('Shows the page and its recorded source path.', { argv: ['gbrain', 'get', '--source', sourceId, '--', slug] }) });
let size: number;
try {
@@ -190,6 +202,11 @@ export async function readReconcileState(engine: BrainEngine, sourceId: string,
policy_digest: await reconcilePolicyDigest(engine, sourceId), withdrawals_digest: digest({ withdrawals: snapshot.withdrawals, global_purges: snapshot.globalPurges ?? null }), assessment_at: assessmentAt };
return { binding, root, path, raw, snapshot, storedPage, file: reconcileCanonical(parsed, parsed.tags), pins, origin, originSourcePath: derived?.sourcePath ?? null };
}
+/** #6394: a preview made with --adopt-slug-path recorded a page with no origin; apply and publication adopt the same pinned file. */
+export function reconcilePreviewAdopts(artifact: Pick<ReconcileArtifact, 'preimages'>): boolean {
+ const stored = (artifact.preimages as { stored_page?: { source_path?: unknown; source_uri?: unknown } | null } | null)?.stored_page;
+ return stored != null && stored.source_path == null && stored.source_uri == null;
+}
export function assertReconcilePins(expected: ReconcilePins, actual: ReconcilePins): void {
for (const key of Object.keys(expected) as Array<keyof ReconcilePins>) if (expected[key] !== actual[key]) staleReconcile(key);
}
diff --git a/src/core/persistence/reconcile.ts b/src/core/persistence/reconcile.ts
index d8690852c9..12947db038 100644
--- a/src/core/persistence/reconcile.ts
+++ b/src/core/persistence/reconcile.ts
@@ -13,7 +13,7 @@ import { assertPersistenceAccepting, waitForWrite, writeResponse } from './servi
import { digest, requireUuid, sha256, stableJson } from './digest.ts';
import { mergeReconcile, reconcileCanonical, reconcileDecisions, strictReconcileKeys } from './reconcile-merge.ts';
import { additiveDecisions, assertAutoDecisions, classifyDrift, type AutoDecision, type DriftClassification } from './reconcile-additive.ts';
-import { assertReconcilePins, readReconcileState, staleReconcile, validateReconcileArtifact, type ReconcileArtifact, type ReconcileState } from './reconcile-state.ts';
+import { assertReconcilePins, readReconcileState, reconcilePreviewAdopts, staleReconcile, validateReconcileArtifact, type ReconcileArtifact, type ReconcileState } from './reconcile-state.ts';
import { prepareReconcileResult } from './reconcile-prepare.ts';
import { assertReconcileOutputPath, assertReconcileSize, manageReconcileBackups, retainReconcileBackup } from './reconcile-backup.ts';
import type { LocalGrant } from './identity.ts';
@@ -90,7 +90,7 @@ async function config(engine: BrainEngine): Promise<GBrainConfig> {
return await loadConfigWithEngine(engine, loadConfig()) ?? { engine: engine.kind } as GBrainConfig;
}
export async function runReconcilePreview(engine: BrainEngine, params: Record<string, unknown>): Promise<Record<string, unknown> & { preview: ReconcileArtifact }> {
- strictReconcileKeys(params, ['source_id', 'slug', 'from', 'decisions', 'output_path', 'auto_additive', 'accept_suggested'], ['source_id', 'slug']);
+ strictReconcileKeys(params, ['source_id', 'slug', 'from', 'decisions', 'output_path', 'auto_additive', 'accept_suggested', 'adopt_slug_path'], ['source_id', 'slug']);
const auto = params.auto_additive === true;
if (params.auto_additive !== undefined && typeof params.auto_additive !== 'boolean'
|| params.accept_suggested !== undefined && (typeof params.accept_suggested !== 'boolean' || !auto)) {
@@ -110,7 +110,8 @@ export async function runReconcilePreview(engine: BrainEngine, params: Record<st
'Pass the preview being resolved along with the decisions (CLI: --from with the preview file written by --out).');
if (from && (from.preconditions.source_id !== sourceId || from.preconditions.slug !== slug)) throw opError('invalid_params', 'The previous preview names a different page.',
`Use the preview made for ${slug} in '${sourceId}', or run the command with the source and slug that preview file names.`);
- const state = await readReconcileState(engine, sourceId, slug, from?.preconditions.assessment_at);
+ const state = await readReconcileState(engine, sourceId, slug, from?.preconditions.assessment_at,
+ { adoptSlugPath: params.adopt_slug_path === true || (from !== undefined && reconcilePreviewAdopts(from)) });
if (from) assertPreimages(from, state);
const database = reconcileCanonical(state.snapshot.page, state.snapshot.tags);
const classification = auto ? classifyDrift(state.file, database) : undefined;
@@ -166,7 +167,8 @@ export async function runReconcileApply(engine: BrainEngine, params: Record<stri
try {
assertPersistenceAccepting(engine);
await assertReconcileSize(engine, artifact);
- const state = await readReconcileState(engine, sourceId, slug, artifact.preconditions.assessment_at);
+ const adopt = { adoptSlugPath: reconcilePreviewAdopts(artifact) };
+ const state = await readReconcileState(engine, sourceId, slug, artifact.preconditions.assessment_at, adopt);
assertPreimages(artifact, state);
assertAutoDecisions(artifact.auto_decisions ?? [], state.file, reconcileCanonical(state.snapshot.page, state.snapshot.tags), artifact.decisions);
const prepared = await prepareReconcileResult(engine, state, artifact.decisions);
@@ -176,7 +178,7 @@ export async function runReconcileApply(engine: BrainEngine, params: Record<stri
const reference = await retainReconcileBackup(engine, artifact, authority.principal, requestId);
const retainedReplay = await replay();
if (retainedReplay) return retainedReplay;
- const current = await readReconcileState(engine, sourceId, slug, artifact.preconditions.assessment_at);
+ const current = await readReconcileState(engine, sourceId, slug, artifact.preconditions.assessment_at, adopt);
assertPreimages(artifact, current);
const row = await admitWrite(engine, { principal: authority.principal, operation: 'put_page', sourceId,
sourceIncarnation: state.pins.source_incarnation, slug, pageId: state.pins.page_id, worktreeId: state.pins.worktree_id,
diff --git a/test/reconcile-unbound-collision.test.ts b/test/reconcile-unbound-collision.test.ts
index 142a7b9bc4..559f9d730f 100644
--- a/test/reconcile-unbound-collision.test.ts
+++ b/test/reconcile-unbound-collision.test.ts
@@ -21,6 +21,7 @@ import { registerLocalWriter, withVerifiedLocalRegistration } from '../src/core/
import { runReconcileApply, runReconcilePreview } from '../src/core/persistence/reconcile.ts';
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { withEnv } from './helpers/with-env.ts';
+import { operations } from '../src/core/operations.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { testBackends } from './helpers/test-backends.ts';
@@ -150,3 +151,51 @@ test('a Git subfolder page never matches a source-relative file whose scanned sl
}
});
}, 180_000);
+
+// #6394: an unmarked page with no recorded origin and a file at its slug path refused every write, and reconcile (the remedy
+// the refusal named) could not adopt it. --adopt-slug-path adopts that file explicitly; the default stays unchanged above.
+test('--adopt-slug-path previews an unmarked null-origin page against its slug file, apply records the origin, and a later write commits', async () => {
+ await withEnv({ GBRAIN_HOME: home, OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined }, async () => {
+ for (const engine of engines) {
+ const f = await collision(engine, { marked: false });
+ await withVerifiedLocalRegistration(engine, f.registration, async () => {
+ const refused = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug }).catch((error: { suggestion?: string; message: string }) => error);
+ expect(String((refused as { suggestion?: string }).suggestion ?? '')).toContain('--adopt-slug-path');
+ const preview = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug, adopt_slug_path: true });
+ expect(preview.relative_path).toBe('notes/example.md');
+ expect(preview.status).toBe('needs_resolution');
+ const resolved = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug, from: preview.preview,
+ decisions: (preview.conflict_paths as string[]).map(path => ({ path, action: 'take_file' })) });
+ expect(resolved.status).toBe('ready');
+ const receipt = await runReconcileApply(engine, { source_id: f.id, slug: f.slug, preview: resolved.preview, request_id: randomUUID() });
+ expect(receipt.state).toBe('committed');
+ const [page] = await engine.executeRaw<{ source_path: string | null }>('SELECT source_path FROM pages WHERE source_id=$1 AND slug=$2', [f.id, f.slug]);
+ expect(page!.source_path).toBe('notes/example.md');
+ const adopted = (await engine.readPageSnapshot(f.slug, { sourceId: f.id }))!;
+ expect(adopted.page.compiled_truth).toContain('another host');
+ const put = operations.find(o => o.name === 'put_page')!;
+ const written = await put.handler({ engine, config: { engine: engine.kind, embedding_disabled: true } as never, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: false, sourceId: f.id },
+ { slug: f.slug, content: '---\ntype: note\ntitle: Example\n---\nWritten after adoption.\n', expected_revision: adopted.revision, request_id: randomUUID() }) as { state?: string };
+ expect(written.state).toBe('committed');
+ expect(readFileSync(f.file, 'utf8')).toContain('Written after adoption.');
+ });
+ }
+ });
+}, 180_000);
+
+test('--adopt-slug-path refuses a page that is database-only by design (a never-filed derive-phase atom)', async () => {
+ await withEnv({ GBRAIN_HOME: home, OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined }, async () => {
+ for (const engine of engines) {
+ const f = await collision(engine, { marked: false });
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await importFromContent(engine, 'atoms/example', databaseSide, { sourceId: f.id, noEmbed: true });
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ mkdirSync(join(home, f.id, 'atoms'), { recursive: true });
+ writeFileSync(join(home, f.id, 'atoms/example.md'), fileSide);
+ await withVerifiedLocalRegistration(engine, f.registration, async () => {
+ await expect(runReconcilePreview(engine, { source_id: f.id, slug: 'atoms/example', adopt_slug_path: true })).rejects.toMatchObject({ code: 'source_changed' });
+ });
+ expect(readFileSync(join(home, f.id, 'atoms/example.md'), 'utf8')).toBe(fileSide);
+ }
+ });
+}, 180_000);