Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(reconcile): opt-in structural resolution of additive file/database drift; audit --classify (#5974)
garrytana26b8e60c29b
diff --git a/.github/workflows/persistence-validation.yml b/.github/workflows/persistence-validation.ymlindex 6e0f6be6db..4623f21cc2 100644--- a/.github/workflows/persistence-validation.yml+++ b/.github/workflows/persistence-validation.yml@@ -107,6 +107,7 @@ jobs:test/persistence-admission-observer.test.ts \test/persistence-read-diagnostics.test.ts \test/persistence-journal.test.ts \+ test/persistence-publication-refusal-5974.test.ts \test/persistence-staging.test.ts \test/persistence-effect-recovery-fairness.test.ts \test/import-publication-guards.test.ts \@@ -149,6 +150,7 @@ jobs:run: >-bun --no-env-file test --timeout=120000test/persistence-reconcile.test.ts+ test/persistence-reconcile-additive-5974.test.tstest/e2e/reconcile-pgbouncer.test.tstest/e2e/extract-atoms-page-state.test.ts- if: always()diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.mdindex dce0963f6c..bd7a5673df 100644--- a/docs/architecture/key-files/canonical-reconciliation.md+++ b/docs/architecture/key-files/canonical-reconciliation.md@@ -4,6 +4,10 @@- `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. `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`).+- `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.++- `src/core/persistence/publication-failure.ts` (#5974) — maps a P0001 from the managed-writer guard (which raises TABLE/SCHEMA, `managed_writer_guard:<branch>` and a JSON DETAIL) or another trigger to a bounded `error_detail` (origin, raiser, table, op, branch, relationship, stage, plus owner-only source ids and the attempt's build/host). Receipts expose only `publicFailureDetail`; `sources writer status` lists the full detail under `recent_failures`.+- `src/core/cycle/extract-atoms-page-state.ts` — derived page scan/failure state keyed by source incarnation, stable page identity and content hash. Compare-and-swap stamps never update canonical frontmatter. Reviewed reconciliation can carry matching state across removal of legacy bookkeeping fields. Atom item completion still waits for all atoms and provenance links; managed extraction uses journaled publication and a durable completion receipt after trusted local source-wide authority checks and, for filesystem publication, owner preflight.- `src/core/persistence/grandfather.ts` — provider-free canonical publication for the grandfather compatibility flag on active managed Markdown pages. Admission retains a checkpointed request UUID, exact source/incarnation/page/revision identity and a private rollback snapshot. Publication preserves chunks/vectors and only already-valid text seals, carries matching atom scan state across the metadata hash change, and defers embeddings without queuing fact extraction. Explicit validation choices, archived sources and non-Markdown artifacts remain untouched; unpublished file edits refuse. Pages under a declared `storage.db_only` dir without a local cache file publish database-only. The committed revision is returned so the migration's verify phase can tell a later rewrite from a lost write. `admitCanonicalGrandfather` splits admission from `complete()` (wait, then settle the checkpoint exactly as the serial `grandfatherCanonicalPage` does); the migration admits a 50-page window before waiting, so the pages' Git effects coalesce (#5530). The unmanaged migration keeps its bounded SQL batches. `test/grandfather-managed.test.ts` covers both engines, replay, races and preserved artifacts; the unchanged local-install lifecycle exercises the public upgrade path.diff --git a/docs/guides/concurrent-writes.md b/docs/guides/concurrent-writes.mdindex 3e8aa8c006..16e761a2df 100644--- a/docs/guides/concurrent-writes.md+++ b/docs/guides/concurrent-writes.md@@ -171,6 +171,48 @@ reasons without page content. Whole-source audit requires a CLI grant without aslug-prefix restriction. `sources writer activate --dry-run` includes a boundeddrift sample and identifies incomplete samples without authorizing repairs.+### Many drifted pages: classify, then resolve additive drift++When an audit finds many drifted pages, something outside GBrain is usually+editing the canonical files. Classify before repairing anything:++```bash+gbrain sources reconcile workspace --brain host --audit --classify --limit 25 --json+```++Each drifted finding gets a `classification` and its `drift_paths` (paths, rule+outcomes and reasons, never values), and `classified` counts the batch:++| Classification | Meaning | Next step |+| --- | --- | --- |+| `structurally_additive` | Only additive metadata changed: a `contacts` list with entries appended after every stored entry (order and repeats kept), an activity date that moved forward (`updated`, `last_*`, `*_last_used`), or a field present on one side only. | Preview with `--auto-additive`, then apply. |+| `additive_with_suggestions` | The above, plus body or timeline lines inserted without changing or removing any stored line. | Read the inserted lines, then preview with `--auto-additive --accept-suggested`. |+| `review_required` | Stored text changed or was removed; or a policy, privacy, title, type, tag, alias or fence change; or a date that moved backward, changed format or is in the future. | Resolve manually as above, after asking the user. |+| `formatting_only` | The parsed content already agrees. | Preview; the result is the database content. |++`file_modified_after_database` says whether the file changed after the page's+last database write, a hint for finding the process that edits files directly.++```bash+gbrain sources reconcile workspace people/example --brain host \+ --preview --auto-additive --out ~/.gbrain/repair/example.auto.json --json+```++`--auto-additive` writes `take_file` decisions only for the paths its rules+cover and lists them in `auto_decided_paths`. Inserted body and timeline lines+are never decided automatically, because an added line can still contradict an+older one ("Correction: the earlier note is wrong"). The structure rules cannot+see that. Read the inserted lines in the private artifact (show them to the+user when the page is private or the claims matter), then add+`--accept-suggested`. If any path needs review, the preview stays+`needs_resolution` and `next_action` says what to ask.++The artifact (format version 2) records each automatic decision with its rule+and an evidence digest of the exact values it judged. Apply and the owner both+re-run the rules against the pinned file and database copies; any change means+a fresh preview. Apply, backups and the retry of the blocked write work exactly+as above.+Atom scan/failure bookkeeping now lives outside canonical note metadata soprocessing progress does not create new disagreements. Managed atom extractionchecks trusted local source-wide authority and, for filesystem writes, ownerdiff --git a/src/commands/source-reconcile.ts b/src/commands/source-reconcile.tsindex 20b27ffde3..2bcdb6fb70 100644--- a/src/commands/source-reconcile.ts+++ b/src/commands/source-reconcile.ts@@ -23,9 +23,11 @@ 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 --from <preview-file>--decisions <decisions-file> --out <new-file> [--json]+ gbrain sources reconcile <source> <slug> --brain <id> --preview --auto-additive [--accept-suggested]+ --out <new-file> [--json]gbrain sources reconcile <source> <slug> --brain <id> --apply <resolved-preview-file>--request-id <uuid> [--json]- gbrain sources reconcile <source> --brain <id> --audit [--limit <1-100>] [--after <slug>] [--json]+ gbrain sources reconcile <source> --brain <id> --audit [--classify] [--limit <1-100>] [--after <slug>] [--json]gbrain sources reconcile <source> <slug> --brain <id> --backups [--limit <1-100>] [--after <request-uuid>] [--json]gbrain sources reconcile <source> <slug> --brain <id> --remove-backup <exact-reference> [--json]@@ -45,7 +47,15 @@ and .result locally before applying; stdout contains only a summary.Use the same request ID and arguments after a lost response or pending receipt.After a terminal conflict, make a new preview and use a new request ID.Retry any originally blocked memory write separately, with its own new ID.-Audit is bounded and read-only; its cursor is not a sync checkpoint.+--auto-additive decides only structurally additive drift: an appended contacts+list (every stored entry kept in order), an advanced activity date (updated,+last_*, *_last_used) and fields present on one side only. Inserted body or+timeline lines are suggested, not decided, because an added line can still+contradict an old one; read them in the private preview, then rerun with+--accept-suggested. Anything else (changed or removed text, policy, privacy,+title, type, tags, fences) keeps the preview unready for a person to decide.+Audit is bounded and read-only; its cursor is not a sync checkpoint. --classify+adds each drifted page's structural classification and counts, never values.Backups persist until explicitly removed. Removal deletes that private history,not the page or immutable receipt, and refuses nonterminal/recovering requests.`;@@ -62,7 +72,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']);+ const boolean = new Set(['--preview', '--audit', '--backups', '--json', '--auto-additive', '--accept-suggested', '--classify']);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];@@ -98,7 +108,11 @@ export function parseReconcileArgs(args: string[]): ReconcileCliArgs {if (applying && !isWriteRequestId(flags.get('--request-id'))) throw new OperationError('invalid_params', 'Apply requires an explicit UUID --request-id.');if (flags.has('--decisions') && !flags.has('--from')) throw new OperationError('invalid_params', '--decisions requires --from.');if (!audit && !flags.has('--backups') && (flags.has('--limit') || flags.has('--after'))) throw new OperationError('invalid_params', '--limit and --after are only valid with --audit or --backups.');- if (audit && ['--preview', '--out', '--from', '--decisions'].some(flag => flags.has(flag))) throw new OperationError('invalid_params', 'Audit cannot create or resolve a page preview.');+ if (audit && ['--preview', '--out', '--from', '--decisions', '--auto-additive', '--accept-suggested'].some(flag => flags.has(flag))) throw new OperationError('invalid_params', 'Audit cannot create or resolve a page preview.');+ if (flags.has('--classify') && !audit) throw new OperationError('invalid_params', '--classify is only valid with --audit.');+ if ((applying || backups) && (flags.has('--auto-additive') || flags.has('--accept-suggested'))) throw new OperationError('invalid_params', '--auto-additive and --accept-suggested only shape a preview.');+ if (flags.has('--accept-suggested') && !flags.has('--auto-additive')) throw new OperationError('invalid_params', '--accept-suggested requires --auto-additive.');+ if (flags.has('--auto-additive') && flags.has('--decisions')) throw new OperationError('invalid_params', '--auto-additive computes its own decisions; omit --decisions.');if (backups && ['--preview', '--out', '--from', '--decisions', '--apply', '--audit'].some(flag => flags.has(flag)) || flags.has('--backups') && flags.has('--remove-backup')) {throw new OperationError('invalid_params', 'Backup administration cannot be combined with preview, apply, audit, or another backup action.');}@@ -111,6 +125,9 @@ export function parseReconcileArgs(args: string[]): ReconcileCliArgs {if (flags.has('--after') && !isWriteRequestId(flags.get('--after'))) throw new OperationError('invalid_params', 'Backup pagination requires a request UUID cursor.');}if (applying) params.request_id = flags.get('--request-id');+ if (flags.has('--auto-additive')) params.auto_additive = true;+ if (flags.has('--accept-suggested')) params.accept_suggested = true;+ if (flags.has('--classify')) params.classify = true;if (flags.has('--limit')) {const limit = Number(flags.get('--limit'));if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw new OperationError('invalid_params', 'Audit limit must be an integer from 1 to 100.');diff --git a/src/core/persistence/reconcile-additive.ts b/src/core/persistence/reconcile-additive.tsnew file mode 100644index 0000000000..1437244710--- /dev/null+++ b/src/core/persistence/reconcile-additive.ts@@ -0,0 +1,171 @@+import type { ParsedPage } from '../import-file.ts';+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END } from '../facts-fence.ts';+import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../takes-fence.ts';+import { OperationError } from '../ops/contract.ts';+import { digest } from './digest.ts';+import { protectedReconcileKey, type ReconcileConflict, type ReconcileDecision } from './reconcile-merge.ts';++/**+ * #5974: structural classification of file/database drift. It proves only+ * structure, never truth: an inserted line can still contradict an older one,+ * so inserted text is `suggested` (an explicit operator acceptance applies it)+ * while only append-only contact lists and allowlisted activity dates are+ * `auto`. Everything else is `review`. Pure; no I/O.+ */+export const ADDITIVE_RULE_VERSION = 1;+export type AdditiveRule = 'text_insertion_only' | 'contacts_append_only' | 'activity_date_advance' | 'file_only_field' | 'database_only_kept';+export type DriftClass = 'auto' | 'suggested' | 'review';+export interface DriftPath { path: string; class: DriftClass; rule?: AdditiveRule; reason: string; inserted_lines?: number; appended?: number }+export interface DriftClassification { paths: DriftPath[]; verdict: 'structurally_additive' | 'additive_with_suggestions' | 'review_required' | 'no_drift' }+export interface AutoDecision { path: string; rule: AdditiveRule; rule_version: number; evidence_digest: string }++const APPEND_ONLY_ARRAYS = new Set(['contacts']);+const ACTIVITY_DATE = /^(?:updated|updated_at|modified|last_modified|last_[a-z0-9_]+|[a-z0-9_]+_last_used)$/;+// Policy-bearing metadata a structural rule must never decide, beyond the protected merge keys.+const POLICY_KEYS = new Set(['access', 'confidentiality', 'grants', 'grant', 'owner', 'owners', 'permissions', 'acl', 'sharing',+ 'private', 'visibility', 'status', 'aliases', 'slug', 'id', 'type', 'title', 'tags', 'withdrawn', 'withdrawals', 'expires', 'expires_at',+ 'valid_until', 'archived', 'archived_at', 'deleted', 'deleted_at', 'consent', 'consented_at']);+const MAX_APPENDED = 500;+const DAY_MS = 86_400_000;++const lines = (text: string) => text.replace(/\r\n?/g, '\n').split('\n');+const escaped = (key: string) => key.replace(/~/g, '~0').replace(/\//g, '~1');++function fenceRegions(fileLines: string[]): boolean[] {+ const inside: boolean[] = [];+ let open: string | null = null;+ for (const line of fileLines) {+ const trimmed = line.trim();+ if (open === null && (trimmed === FACTS_FENCE_BEGIN || trimmed === TAKES_FENCE_BEGIN)) { open = trimmed === FACTS_FENCE_BEGIN ? FACTS_FENCE_END : TAKES_FENCE_END; inside.push(true); continue; }+ if (open === null && /^(```|~~~)/.test(trimmed)) { open = trimmed.slice(0, 3); inside.push(true); continue; }+ if (open !== null) { inside.push(true); if (trimmed === open || (open.length === 3 && trimmed.startsWith(open))) open = null; continue; }+ inside.push(false);+ }+ return inside;+}++/** Every database line kept, in order and unchanged; only whole lines inserted, none inside a fence or structural block. */+export function classifyTextInsertion(file: string, database: string): { ok: true; inserted: number } | { ok: false; reason: string } {+ const f = lines(file), d = lines(database);+ const matched = new Array<boolean>(f.length).fill(false);+ let i = 0;+ for (const line of d) {+ while (i < f.length && f[i] !== line) i++;+ if (i === f.length) return { ok: false, reason: 'database_text_changed_or_removed' };+ matched[i++] = true;+ }+ const fenced = fenceRegions(f);+ let inserted = 0;+ for (let k = 0; k < f.length; k++) {+ if (matched[k]) continue;+ if (!f[k].trim()) { inserted++; continue; }+ inserted++;+ if (fenced[k] || [FACTS_FENCE_BEGIN, FACTS_FENCE_END, TAKES_FENCE_BEGIN, TAKES_FENCE_END].some(m => f[k].includes(m))) return { ok: false, reason: 'fence_insertion' };+ if (/^\s*#/.test(f[k])) return { ok: false, reason: 'heading_insertion' };+ if (/^\s*\|/.test(f[k])) return { ok: false, reason: 'table_insertion' };+ }+ return { ok: true, inserted };+}++function classifyDate(file: unknown, database: unknown, now: number): { ok: true } | { ok: false; reason: string } {+ if (typeof file !== 'string' || typeof database !== 'string') return { ok: false, reason: 'date_not_text' };+ const dateOnly = /^\d{4}-\d{2}-\d{2}$/, stamp = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})$/;+ const format = (v: string) => dateOnly.test(v) ? 'date' : stamp.test(v) ? 'timestamp' : null;+ if (!format(file) || format(file) !== format(database)) return { ok: false, reason: 'date_format_changed' };+ const valid = (v: string) => { const t = Date.parse(v); return Number.isFinite(t) && (format(v) !== 'date' || new Date(t).toISOString().slice(0, 10) === v) ? t : NaN; };+ const f = valid(file), d = valid(database);+ if (!Number.isFinite(f) || !Number.isFinite(d)) return { ok: false, reason: 'invalid_date' };+ if (f < d) return { ok: false, reason: 'date_moved_backward' };+ if (f > now + DAY_MS) return { ok: false, reason: 'future_date' };+ return { ok: true };+}++function classifyAppend(file: unknown, database: unknown): { ok: true; appended: number } | { ok: false; reason: string } {+ if (!Array.isArray(file) || !Array.isArray(database)) return { ok: false, reason: 'not_a_list' };+ if (file.length < database.length) return { ok: false, reason: 'list_entries_removed' };+ for (let k = 0; k < database.length; k++) if (digest(file[k]) !== digest(database[k])) return { ok: false, reason: 'list_entries_changed_or_reordered' };+ if (file.length - database.length > MAX_APPENDED) return { ok: false, reason: 'too_many_appended' };+ return { ok: true, appended: file.length - database.length };+}++const absent = Symbol('absent');+/** Classifies the complete delta between the parsed file and the database page, not only merge conflicts. */+export function classifyDrift(file: ParsedPage, database: ParsedPage, now = Date.now()): DriftClassification {+ const paths: DriftPath[] = [];+ for (const key of ['title', 'type'] as const) if (file[key] !== database[key]) paths.push({ path: `/${key}`, class: 'review', reason: 'identity_field_changed' });+ for (const key of ['compiled_truth', 'timeline'] as const) {+ const f = file[key] ?? '', d = database[key] ?? '';+ if (f === d) continue;+ const text = classifyTextInsertion(f, d);+ paths.push(text.ok ? { path: `/${key}`, class: 'suggested', rule: 'text_insertion_only', reason: 'inserted_lines_need_acceptance', inserted_lines: text.inserted }+ : { path: `/${key}`, class: 'review', reason: text.reason });+ }+ const fileTags = new Set(file.tags), dbTags = new Set(database.tags);+ if (file.tags.length !== database.tags.length || file.tags.some(t => !dbTags.has(t)) || database.tags.some(t => !fileTags.has(t))) {+ paths.push({ path: '/tags', class: 'review', reason: 'tags_changed' });+ }+ const fm = file.frontmatter ?? {}, dm = database.frontmatter ?? {};+ for (const key of [...new Set([...Object.keys(fm), ...Object.keys(dm)])].sort()) {+ const f = Object.hasOwn(fm, key) ? fm[key] : absent, d = Object.hasOwn(dm, key) ? dm[key] : absent;+ if (f !== absent && d !== absent && digest(f) === digest(d)) continue;+ const path = `/frontmatter/${escaped(key)}`;+ if (POLICY_KEYS.has(key) || protectedReconcileKey(key)) { paths.push({ path, class: 'review', reason: 'policy_field_changed' }); continue; }+ if (f === absent) { paths.push({ path, class: 'auto', rule: 'database_only_kept', reason: 'database_value_kept' }); continue; }+ if (d === absent) { paths.push({ path, class: 'auto', rule: 'file_only_field', reason: 'file_field_added' }); continue; }+ if (APPEND_ONLY_ARRAYS.has(key)) {+ const append = classifyAppend(f, d);+ paths.push(append.ok ? { path, class: 'auto', rule: 'contacts_append_only', reason: 'entries_appended', appended: append.appended }+ : { path, class: 'review', reason: append.reason });+ continue;+ }+ if (ACTIVITY_DATE.test(key)) {+ const date = classifyDate(f, d, now);+ paths.push(date.ok ? { path, class: 'auto', rule: 'activity_date_advance', reason: 'activity_date_advanced' } : { path, class: 'review', reason: date.reason });+ continue;+ }+ paths.push({ path, class: 'review', reason: 'value_changed' });+ }+ const verdict = !paths.length ? 'no_drift' : paths.some(p => p.class === 'review') ? 'review_required'+ : paths.some(p => p.class === 'suggested') ? 'additive_with_suggestions' : 'structurally_additive';+ return { paths, verdict };+}++/** Evidence binding one automatic decision to the exact values it judged. */+export function additiveEvidence(path: string, file: ParsedPage, database: ParsedPage): string {+ const pick = (page: ParsedPage) => path.split('/').slice(1).map(k => k.replace(/~1/g, '/').replace(/~0/g, '~'))+ .reduce<unknown>((value, key) => value && typeof value === 'object' ? (value as Record<string, unknown>)[key] : undefined, page);+ return digest({ path, file: pick(file) ?? null, database: pick(database) ?? null, rule_version: ADDITIVE_RULE_VERSION });+}++/**+ * Decisions for the conflict paths the classification may resolve: `auto`+ * always, `suggested` only with explicit acceptance. Paths left undecided keep+ * the preview in needs_resolution.+ */+export function additiveDecisions(classification: DriftClassification, conflicts: ReconcileConflict[], file: ParsedPage, database: ParsedPage,+ acceptSuggested: boolean): { decisions: ReconcileDecision[]; auto: AutoDecision[] } {+ const byPath = new Map(classification.paths.map(p => [p.path, p]));+ const decisions: ReconcileDecision[] = [], auto: AutoDecision[] = [];+ for (const conflict of conflicts) {+ const entry = byPath.get(conflict.path);+ if (!entry?.rule || entry.class === 'review' || entry.class === 'suggested' && !acceptSuggested) continue;+ decisions.push({ path: conflict.path, action: 'take_file' });+ auto.push({ path: conflict.path, rule: entry.rule, rule_version: ADDITIVE_RULE_VERSION, evidence_digest: additiveEvidence(conflict.path, file, database) });+ }+ return { decisions, auto };+}++/** Apply-time recheck: every recorded automatic decision still classifies the same against the pinned inputs. */+export function assertAutoDecisions(auto: AutoDecision[], file: ParsedPage, database: ParsedPage, decisions: ReconcileDecision[], now = Date.now()): void {+ if (!auto.length) return;+ const current = new Map(classifyDrift(file, database, now).paths.map(p => [p.path, p]));+ for (const entry of auto) {+ const path = current.get(entry.path);+ if (entry.rule_version !== ADDITIVE_RULE_VERSION || !path || path.rule !== entry.rule || path.class === 'review'+ || additiveEvidence(entry.path, file, database) !== entry.evidence_digest+ || !decisions.some(d => d.path === entry.path && d.action === 'take_file')) {+ throw new OperationError('source_changed', `The automatic decision for ${entry.path} no longer holds.`,+ 'Create a new preview with --auto-additive and apply it with a new request ID.');+ }+ }+}diff --git a/src/core/persistence/reconcile-audit.ts b/src/core/persistence/reconcile-audit.tsindex 202dd09814..2aeba2ff22 100644--- a/src/core/persistence/reconcile-audit.ts+++ b/src/core/persistence/reconcile-audit.ts@@ -11,20 +11,25 @@ import { submissionAuthority } from './authority.ts';import { currentVerifiedLocalWriter, existingLocalHostId, readLocalWriter, verifyLocalWriter } from './identity.ts';import { getWorktreeBinding } from './ownership.ts';import { prepareFileTarget } from './page-prepare.ts';+import { readReconcileState } from './reconcile-state.ts';+import { reconcileCanonical } from './reconcile-merge.ts';+import { classifyDrift } from './reconcile-additive.ts';export interface ReconcileAuditReport extends Record<string, unknown> {source_id: string;inspected: number;drifted: number;errors: number;- findings: Array<{ slug: string; reason: string; suggestion: string }>;+ findings: Array<{ slug: string; reason: string; suggestion: string; classification?: string;+ drift_paths?: Array<{ path: string; class: string; reason: string }>; file_modified_after_database?: boolean }>;+ classified?: Record<string, number>;next_after: string | null;complete: boolean;snapshot_only: true;}export async function auditCanonicalSource(engine: BrainEngine, sourceId: string,- options: { limit?: number; after?: string } = {}): Promise<ReconcileAuditReport> {+ options: { limit?: number; after?: string; classify?: boolean } = {}): Promise<ReconcileAuditReport> {const limit = options.limit ?? 25;if (!isValidSourceId(sourceId) || !Number.isInteger(limit) || limit < 1 || limit > 100) {throw new OperationError('invalid_params', 'Audit requires an explicit source and a limit from 1 to 100.');@@ -44,7 +49,8 @@ export async function auditCanonicalSource(engine: BrainEngine, sourceId: stringFROM pages WHERE source_id=$1 AND deleted_at IS NULL AND page_kind='markdown' AND slug>$2ORDER BY slug LIMIT $3`, [sourceId, options.after ?? '', limit + 1]);const report: ReconcileAuditReport = { source_id: sourceId, inspected: 0, drifted: 0, errors: 0, findings: [],- next_after: rows.length > limit ? rows[limit - 1].slug : null, complete: rows.length <= limit, snapshot_only: true };+ next_after: rows.length > limit ? rows[limit - 1].slug : null, complete: rows.length <= limit, snapshot_only: true,+ ...(options.classify ? { classified: { structurally_additive: 0, additive_with_suggestions: 0, review_required: 0, formatting_only: 0, error: 0 } } : {}) };const mode = await scannerSlugRootMode(engine, sourceId, root);for (const candidate of rows.slice(0, limit)) {report.inspected++;@@ -68,18 +74,40 @@ export async function auditCanonicalSource(engine: BrainEngine, sourceId: stringconst reason = error instanceof OperationError ? error.code : 'storage_error';if (reason === 'source_changed') report.drifted++;else report.errors++;- report.findings.push({ slug: candidate.slug, reason,+ const finding: ReconcileAuditReport['findings'][number] = { slug: candidate.slug, reason,suggestion: reason === 'source_changed'? 'Preview this exact page with sources reconcile before attempting another write.'- : 'Inspect this page on the canonical host; no repair was attempted.' });+ : 'Inspect this page on the canonical host; no repair was attempted.' };+ if (options.classify && reason === 'source_changed') Object.assign(finding, await classifyFinding(engine, sourceId, candidate.slug, report.classified!));+ report.findings.push(finding);}}return report;}+/** #5974: read-only structural classification of one drifted page; reports paths and rule outcomes, never values. */+async function classifyFinding(engine: BrainEngine, sourceId: string, slug: string, counts: Record<string, number>) {+ try {+ const state = await readReconcileState(engine, sourceId, slug);+ const classification = classifyDrift(state.file, reconcileCanonical(state.snapshot.page, state.snapshot.tags));+ const verdict = classification.verdict === 'no_drift' ? 'formatting_only' : classification.verdict;+ counts[verdict]++;+ const updated = Date.parse(String(state.snapshot.page.updated_at ?? ''));+ const suggestion = verdict === 'formatting_only' ? `Only formatting differs. Preview with gbrain sources reconcile ${sourceId} ${slug} --brain <brain> --preview; the result is the database content.`+ : verdict === 'review_required' ? `Not structurally additive. Preview gbrain sources reconcile ${sourceId} ${slug} --brain <brain> --preview --out <new file> and ask the user before deciding the review paths.`+ : `Preview gbrain sources reconcile ${sourceId} ${slug} --brain <brain> --preview --auto-additive --out <new file>${verdict === 'additive_with_suggestions' ? ', read the inserted lines, then add --accept-suggested' : ''}; apply it with a new request ID.`;+ return { classification: verdict, suggestion, drift_paths: classification.paths.map(({ path, class: kind, reason }) => ({ path, class: kind, reason })),+ ...(Number.isFinite(updated) ? { file_modified_after_database: statSync(state.path).mtimeMs > updated } : {}) };+ } catch {+ counts.error++;+ return { classification: 'error' };+ }+}+export async function runReconcileAudit(engine: BrainEngine, params: Record<string, unknown>): Promise<ReconcileAuditReport> {- if (Object.keys(params).some(key => !['source_id', 'limit', 'after'].includes(key)) || !isValidSourceId(params.source_id)) {- throw new OperationError('invalid_params', 'Audit accepts only source_id, limit, and after.');+ if (Object.keys(params).some(key => !['source_id', 'limit', 'after', 'classify'].includes(key)) || !isValidSourceId(params.source_id)+ || params.classify !== undefined && typeof params.classify !== 'boolean') {+ throw new OperationError('invalid_params', 'Audit accepts only source_id, limit, after, and classify.');}const writer = currentVerifiedLocalWriter() ?? await verifyLocalWriter(engine, await readLocalWriter(engine, 'cli'));if (writer.remote || writer.principal.kind !== 'local_cli' || writer.grant.slugPrefixes !== null) {@@ -92,7 +120,8 @@ export async function runReconcileAudit(engine: BrainEngine, params: Record<striif (!source) throw new OperationError('source_changed', 'The selected source is unavailable.');await submissionAuthority({ engine, remote: false, sourceId: params.source_id } as OperationContext,'put_page', params.source_id, source.incarnation, '__reconciliation_audit__');- const report = await auditCanonicalSource(engine, params.source_id, { limit: params.limit as number | undefined, after: params.after as string | undefined });+ const report = await auditCanonicalSource(engine, params.source_id, { limit: params.limit as number | undefined, after: params.after as string | undefined,+ classify: params.classify === true });await submissionAuthority({ engine, remote: false, sourceId: params.source_id } as OperationContext,'put_page', params.source_id, source.incarnation, '__reconciliation_audit__');return report;diff --git a/src/core/persistence/reconcile-prepare.ts b/src/core/persistence/reconcile-prepare.tsindex 683e0663fd..89e4267697 100644--- a/src/core/persistence/reconcile-prepare.ts+++ b/src/core/persistence/reconcile-prepare.ts@@ -20,6 +20,7 @@ import { mergeReconcile, reconcileCanonical, type ReconcileDecision } from './reimport { stabilizeSafetyAssessments } from './reconcile-safety.ts';import { assertReconcilePins, readReconcileState, staleReconcile, validateReconcileArtifact, type ReconcileState } from './reconcile-state.ts';import { verifyReconcileBackup } from './reconcile-backup.ts';+import { assertAutoDecisions } from './reconcile-additive.ts';function preservePrivateFacts(incoming: string, stored: string): string {const next = parseFactsFence(incoming), prior = parseFactsFence(stored);@@ -72,6 +73,7 @@ export async function prepareReconcileMutation(engine: BrainEngine, row: WriteRe}const state = await readReconcileState(engine, row.source_id, row.slug, artifact.preconditions.assessment_at);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);if (!prepared.ready || digest(prepared.result) !== artifact.result_digest) staleReconcile('canonical policy result changed');const content = serializePageToMarkdown({ ...state.snapshot.page, ...prepared.result }, prepared.result.tags);diff --git a/src/core/persistence/reconcile-state.ts b/src/core/persistence/reconcile-state.tsindex 7a0763b8c8..578d0ae996 100644--- a/src/core/persistence/reconcile-state.ts+++ b/src/core/persistence/reconcile-state.ts@@ -17,6 +17,7 @@ import { getWorktreeBinding, type WorktreeBinding } from './ownership.ts';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';export interface ReconcilePins {brain_id: string; source_id: string; source_incarnation: string; slug: string; page_id: number;@@ -24,10 +25,12 @@ export interface ReconcilePins {raw_file_hash: string; relative_path: string; policy_digest: string; withdrawals_digest: string; assessment_at: string;}export interface ReconcileArtifact {- format_version: 1; preview_id: string; preconditions: ReconcilePins;+ /** 2 when the preview carries #5974 automatic decisions. */+ format_version: 1 | 2; preview_id: string; preconditions: ReconcilePins;preimages: { file_base64: string; database: PageSnapshot; stored_page: Record<string, unknown> };decisions: ReconcileDecision[]; conflicts: ReconcileConflict[]; result: ParsedPage; result_digest: string;status: 'needs_resolution' | 'ready';+ auto_decisions?: AutoDecision[];}export interface ReconcileState {binding: WorktreeBinding; root: string; path: string; raw: Buffer; snapshot: PageSnapshot;@@ -141,7 +144,20 @@ export function assertReconcilePins(expected: ReconcilePins, actual: ReconcilePi}export function validateReconcileArtifact(value: unknown): ReconcileArtifact {validateReconcileJson(value);- strictReconcileKeys(value, ['format_version', 'preview_id', 'preconditions', 'preimages', 'decisions', 'conflicts', 'result', 'result_digest', 'status']);+ const v2 = (value as Record<string, unknown> | null)?.format_version === 2;+ strictReconcileKeys(value, ['format_version', 'preview_id', 'preconditions', 'preimages', 'decisions', 'conflicts', 'result', 'result_digest', 'status',+ ...(v2 ? ['auto_decisions'] : [])], ['format_version', 'preview_id', 'preconditions', 'preimages', 'decisions', 'conflicts', 'result', 'result_digest', 'status',+ ...(v2 ? ['auto_decisions'] : [])]);+ if (v2) {+ if (!Array.isArray(value.auto_decisions) || !value.auto_decisions.length || value.auto_decisions.length > 1000) throw new OperationError('invalid_params', 'Malformed automatic reconciliation decisions.');+ for (const entry of value.auto_decisions as unknown[]) {+ strictReconcileKeys(entry, ['path', 'rule', 'rule_version', 'evidence_digest']);+ if (typeof entry.path !== 'string' || typeof entry.rule !== 'string' || !Number.isSafeInteger(entry.rule_version)+ || typeof entry.evidence_digest !== 'string' || !/^[a-f0-9]{64}$/.test(entry.evidence_digest)) {+ throw new OperationError('invalid_params', 'Malformed automatic reconciliation decisions.');+ }+ }+ }strictReconcileKeys(value.preconditions, ['brain_id', 'source_id', 'source_incarnation', 'slug', 'page_id', 'worktree_id', 'binding_digest','owner_epoch', 'revision', 'raw_file_hash', 'relative_path', 'policy_digest', 'withdrawals_digest', 'assessment_at']);strictReconcileKeys(value.preimages, ['file_base64', 'database', 'stored_page']);@@ -154,7 +170,7 @@ export function validateReconcileArtifact(value: unknown): ReconcileArtifact {'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 || typeof value.preview_id !== 'string' || !['ready', 'needs_resolution'].includes(String(value.status)) ||+ 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') ||['type', 'title', 'compiled_truth', 'timeline'].some(key => typeof result[key] !== 'string') ||diff --git a/src/core/persistence/reconcile.ts b/src/core/persistence/reconcile.tsindex 753fefb9f7..34eebe735f 100644--- a/src/core/persistence/reconcile.ts+++ b/src/core/persistence/reconcile.ts@@ -9,7 +9,8 @@ import { currentVerifiedLocalWriter } from './identity.ts';import { admitWrite, assertPageRequestIdentity, assertReplayIntent, getWriteRequest, intentDigest } from './journal.ts';import { assertPersistenceAccepting, waitForWrite, writeResponse } from './service.ts';import { digest, requireUuid, sha256, stableJson } from './digest.ts';-import { reconcileCanonical, reconcileDecisions, strictReconcileKeys } from './reconcile-merge.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 { prepareReconcileResult } from './reconcile-prepare.ts';import { assertReconcileOutputPath, assertReconcileSize, manageReconcileBackups, retainReconcileBackup } from './reconcile-backup.ts';@@ -49,11 +50,27 @@ function assertPreimages(artifact: ReconcileArtifact, state: ReconcileState): voif (artifact.preimages.file_base64 !== state.raw.toString('base64') || digest(canonical(artifact.preimages.database)) !== digest(canonical(state.snapshot)) ||digest(artifact.preimages.stored_page) !== digest(state.storedPage)) staleReconcile('preimages changed or were edited');}+/** Agent-facing next step for an --auto-additive preview. */+function additiveNextAction(classification: DriftClassification, status: string): string {+ if (classification.verdict === 'no_drift') return 'No drift: the file and database agree. Retry the original write with a new request ID.';+ if (classification.verdict === 'review_required') return 'Some paths are not structurally additive (see drift_paths with class review). Do not apply this preview; '+ + 'show the user the private preview file\'s conflicts and result, then resolve with --from <preview> --decisions <file> after they decide.';+ if (status === 'ready') return `Apply with --apply <preview file> --request-id <new uuid>, then retry the original write with a new request ID.`;+ if (classification.verdict !== 'additive_with_suggestions') return 'Resolve the remaining conflict_paths with --from <preview> --decisions <file>; no automatic rule covers them.';+ return 'Inserted text is structurally additive but can still contradict existing text. Read the inserted lines in the private preview file '+ + '(or show them to the user if the page is private or the claims matter), then rerun the preview with --auto-additive --accept-suggested.';+}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'], ['source_id', 'slug']);+ strictReconcileKeys(params, ['source_id', 'slug', 'from', 'decisions', 'output_path', 'auto_additive', 'accept_suggested'], ['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)) {+ throw new OperationError('invalid_params', 'accept_suggested requires auto_additive; both are booleans.');+ }+ if (auto && params.decisions !== undefined) throw new OperationError('invalid_params', 'auto_additive computes its own decisions; omit decisions, or resolve manually without auto_additive.');const { sourceId, slug } = await authorize(engine, params.source_id, params.slug);if (params.output_path !== undefined) {if (typeof params.output_path !== 'string') throw new OperationError('invalid_params', 'output_path must be an absolute private file path.');@@ -64,14 +81,26 @@ export async function runReconcilePreview(engine: BrainEngine, params: Record<stif (from && (from.preconditions.source_id !== sourceId || from.preconditions.slug !== slug)) throw new OperationError('invalid_params', 'The previous preview names a different page.');const state = await readReconcileState(engine, sourceId, slug, from?.preconditions.assessment_at);if (from) assertPreimages(from, state);- const decisions = reconcileDecisions(params.decisions ?? from?.decisions ?? []);+ const database = reconcileCanonical(state.snapshot.page, state.snapshot.tags);+ const classification = auto ? classifyDrift(state.file, database) : undefined;+ let decisions = reconcileDecisions(params.decisions ?? from?.decisions ?? []);+ let autoDecisions: AutoDecision[] = params.decisions === undefined ? from?.auto_decisions ?? [] : [];+ if (classification) {+ const chosen = additiveDecisions(classification, mergeReconcile(state.file, database, []).conflicts, state.file, database, params.accept_suggested === true);+ decisions = reconcileDecisions(chosen.decisions);+ autoDecisions = chosen.auto;+ }+ if (autoDecisions.length) assertAutoDecisions(autoDecisions, state.file, database, decisions);const prepared = await prepareReconcileResult(engine, state, decisions);- const preview: ReconcileArtifact = { format_version: 1, preview_id: from?.preview_id ?? randomUUID(), preconditions: state.pins,+ const reviewRequired = classification?.verdict === 'review_required';+ const preview: ReconcileArtifact = { format_version: autoDecisions.length ? 2 : 1, preview_id: from?.preview_id ?? randomUUID(), preconditions: state.pins,preimages: JSON.parse(stableJson({ file_base64: state.raw.toString('base64'), database: state.snapshot, stored_page: state.storedPage })),decisions, conflicts: prepared.conflicts, result: prepared.result, result_digest: digest(prepared.result),- status: prepared.conflicts.length ? 'needs_resolution' : 'ready' };+ status: prepared.conflicts.length || reviewRequired ? 'needs_resolution' : 'ready', ...(autoDecisions.length ? { auto_decisions: autoDecisions } : {}) };await assertReconcileSize(engine, preview);return { source_id: sourceId, slug, preview_id: preview.preview_id, status: preview.status,+ ...(classification ? { classification: classification.verdict, drift_paths: classification.paths,+ auto_decided_paths: autoDecisions.map(d => d.path), next_action: additiveNextAction(classification, preview.status) } : {}),conflict_paths: prepared.conflicts.map(c => c.path), protected_paths: prepared.protectedPaths,migrated_scan_paths: prepared.scanPaths, relative_path: state.pins.relative_path,line_endings: state.raw.includes(Buffer.from('\r\n')) ? 'crlf' : 'lf',@@ -105,6 +134,7 @@ export async function runReconcileApply(engine: BrainEngine, params: Record<striawait assertReconcileSize(engine, artifact);const state = await readReconcileState(engine, sourceId, slug, artifact.preconditions.assessment_at);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);if (!prepared.ready || digest(prepared.result) !== artifact.result_digest) staleReconcile('resolved content or canonical policy changed');const preparedReplay = await replay();diff --git a/test/persistence-reconcile-additive-5974.test.ts b/test/persistence-reconcile-additive-5974.test.tsnew file mode 100644index 0000000000..9badfb5e75--- /dev/null+++ b/test/persistence-reconcile-additive-5974.test.ts@@ -0,0 +1,202 @@+/**+ * #5974: opt-in structural resolution of file/database drift. Pure+ * classifier truth table, then the reporter's page shape end to end on PGLite+ * (and an isolated Postgres database when DATABASE_URL is set): audit+ * classification, --auto-additive preview, apply, the previously blocked+ * remember, and independent readback through the MCP route.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { configDir } from '../src/core/config.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import type { ParsedPage } from '../src/core/import-file.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { parseMarkdown, serializePageToMarkdown } from '../src/core/markdown.ts';+import { parseFactsFence } from '../src/core/facts-fence.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { registerLocalWriter, withVerifiedLocalRegistration, type LocalRegistration } from '../src/core/persistence/identity.ts';+import { runReconcileApply, runReconcilePreview } from '../src/core/persistence/reconcile.ts';+import { auditCanonicalSource } from '../src/core/persistence/reconcile-audit.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { classifyDrift, classifyTextInsertion } from '../src/core/persistence/reconcile-additive.ts';+import { operationsByName } from '../src/core/operations.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { withEnv } from './helpers/with-env.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++const page = (over: Partial<ParsedPage> = {}): ParsedPage => ({ type: 'person', title: 'Example', compiled_truth: 'Line one.\nLine two.',+ timeline: '- **2026-01-01** | meeting — Met about the plan.', frontmatter: { contacts: ['alice-example', 'bob-example'], updated: '2026-01-01T00:00:00.000Z' },+ tags: ['friend'], ...over });+const NOW = Date.parse('2026-10-03T00:00:00Z');+const classOf = (file: ParsedPage, db = page()) => Object.fromEntries(classifyDrift(file, db, NOW).paths.map(p => [p.path, `${p.class}:${p.reason}`]));++describe('structural drift classifier', () => {+ test('inserted whole lines are suggested; changed, removed or structural insertions need review', () => {+ expect(classifyTextInsertion('A\nnew\nB\nC\nappended', 'A\nB\nC')).toEqual({ ok: true, inserted: 2 });+ expect(classifyTextInsertion('A\r\nB\r\nC', 'A\nB\nC')).toEqual({ ok: true, inserted: 0 });+ expect(classifyTextInsertion('A\nB changed\nC', 'A\nB\nC')).toEqual({ ok: false, reason: 'database_text_changed_or_removed' });+ expect(classifyTextInsertion('A\nC', 'A\nB\nC')).toEqual({ ok: false, reason: 'database_text_changed_or_removed' });+ expect(classifyTextInsertion('B\nA', 'A\nB')).toEqual({ ok: false, reason: 'database_text_changed_or_removed' });+ expect(classifyTextInsertion('A not\nB', 'A\nB')).toEqual({ ok: false, reason: 'database_text_changed_or_removed' });+ expect(classifyTextInsertion('A\n## New heading\nB', 'A\nB')).toEqual({ ok: false, reason: 'heading_insertion' });+ expect(classifyTextInsertion('A\n| 9 | row |\nB', 'A\nB')).toEqual({ ok: false, reason: 'table_insertion' });+ expect(classifyTextInsertion('A\n<!--- gbrain:facts:begin -->\nx\n<!--- gbrain:facts:end -->\nB', 'A\nB')).toEqual({ ok: false, reason: 'fence_insertion' });+ expect(classifyTextInsertion('A\n```\ncode\n```\nB', 'A\nB')).toEqual({ ok: false, reason: 'fence_insertion' });+ // Structure only: an appended contradiction is still "insertion-only", which is why prose stays suggested.+ expect(classifyTextInsertion('A\nB\nCorrection: the above is wrong.', 'A\nB')).toEqual({ ok: true, inserted: 1 });+ });++ test('contacts are append-only with multiplicity; dates advance only on the activity allowlist', () => {+ const ok = classOf(page({ frontmatter: { contacts: ['alice-example', 'bob-example', 'carol-example', 'alice-example'], updated: '2026-02-02T00:00:00.000Z' } }));+ expect(ok).toEqual({ '/frontmatter/contacts': 'auto:entries_appended', '/frontmatter/updated': 'auto:activity_date_advanced' });+ const db = page({ frontmatter: { contacts: ['a', 'a', 'b'] } });+ expect(classOf(page({ frontmatter: { contacts: ['a', 'b'] } }), db)['/frontmatter/contacts']).toBe('review:list_entries_removed');+ expect(classOf(page({ frontmatter: { contacts: ['a', 'b', 'a'] } }), db)['/frontmatter/contacts']).toBe('review:list_entries_changed_or_reordered');+ expect(classOf(page({ frontmatter: { contacts: ['a', 'a', 'b', 'c'] } }), db)['/frontmatter/contacts']).toBe('auto:entries_appended');+ expect(classOf(page({ frontmatter: { contacts: [{ name: 'a' }, 'a', 'b'] } }), db)['/frontmatter/contacts']).toBe('review:list_entries_changed_or_reordered');+ const date = (file: unknown, stored: unknown, key = 'phone_last_used') => classOf(page({ frontmatter: { [key]: file } }), page({ frontmatter: { [key]: stored } }))[`/frontmatter/${key}`];+ expect(date('2026-02-02', '2026-01-01')).toBe('auto:activity_date_advanced');+ expect(date('2025-12-31', '2026-01-01')).toBe('review:date_moved_backward');+ expect(date('2026-02-30', '2026-01-01')).toBe('review:invalid_date');+ expect(date('2026-02-02T00:00:00Z', '2026-01-01')).toBe('review:date_format_changed');+ expect(date('2030-01-01', '2026-01-01')).toBe('review:future_date');+ expect(date('2026-02-02', '2026-01-01', 'expires_at')).toBe('review:policy_field_changed');+ expect(date('2026-02-02', '2026-01-01', 'renewal_date')).toBe('review:value_changed');+ });++ test('policy, privacy, identity and tag changes always need review; one-sided ordinary fields are additive', () => {+ for (const key of ['access', 'confidentiality', 'visibility', 'grants', 'owner', 'aliases', 'trust', 'provenance']) {+ expect(classOf(page({ frontmatter: { ...page().frontmatter, [key]: 'private' } }))[`/frontmatter/${key}`]).toBe('review:policy_field_changed');+ }+ expect(classOf(page({ title: 'Renamed' }))['/title']).toBe('review:identity_field_changed');+ expect(classOf(page({ tags: ['friend', 'investor'] }))['/tags']).toBe('review:tags_changed');+ expect(classOf(page({ frontmatter: { ...page().frontmatter, phone: '555-0100' } }))['/frontmatter/phone']).toBe('auto:file_field_added');+ expect(classOf(page({ frontmatter: { contacts: ['alice-example', 'bob-example'] } }))['/frontmatter/updated']).toBe('auto:database_value_kept');+ expect(classifyDrift(page(), page(), NOW).verdict).toBe('no_drift');+ expect(classifyDrift(page({ compiled_truth: 'Line one.\nNew.\nLine two.' }), page(), NOW).verdict).toBe('additive_with_suggestions');+ expect(classifyDrift(page({ frontmatter: { ...page().frontmatter, access: 'public' } }), page(), NOW).verdict).toBe('review_required');+ });+});++const home = mkdtempSync(join(tmpdir(), 'gbrain-reconcile-additive-'));+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;+beforeAll(async () => {+ const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); engines.push(engine);+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }+}, 120_000);+afterAll(async () => {+ await withEnv({ GBRAIN_HOME: home }, async () => { for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); } });+ await closePostgres?.(); rmSync(home, { recursive: true, force: true });+});+const isolated = (fn: (engine: BrainEngine) => Promise<void>) => withEnv({ GBRAIN_HOME: home, OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined }, async () => {+ for (const engine of engines) await fn(engine);+});+const local = <T>(engine: BrainEngine, registration: LocalRegistration, fn: () => Promise<T>) => withVerifiedLocalRegistration(engine, registration, fn);++const STORED = `---\ntype: person\ntitle: Example\naccess: private\nvisibility: private\ncontacts:\n - alice-example\n - bob-example\nphone_last_used: '2026-01-01'\nupdated: '2026-01-01'\n---\nA synthetic biography.\n\nWorks at [[companies/acme-example]].\n\n## Timeline\n\n- **2026-01-01** | meeting — Met [[people/alice-example]] about the plan.\n`;++/** Two drifted pages: an insertion-only superset and one whose stored line was replaced. */+async function fixture(engine: BrainEngine) {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ const id = `additive-${randomUUID().slice(0, 12)}`, root = join(home, id);+ mkdirSync(join(root, 'people'), { recursive: true });+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [id, root]);+ const write = async (slug: string, edit: (p: { compiled_truth: string; timeline: string; frontmatter: Record<string, unknown> }) => void) => {+ await importFromContent(engine, slug, STORED, { sourceId: id, sourcePath: `${slug}.md`, noEmbed: true });+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId: id }))!;+ const next = { compiled_truth: snapshot.page.compiled_truth, timeline: snapshot.page.timeline ?? '', frontmatter: { ...snapshot.page.frontmatter } };+ edit(next);+ writeFileSync(join(root, `${slug}.md`), serializePageToMarkdown({ ...snapshot.page, ...next }, snapshot.tags));+ return snapshot;+ };+ const additive = await write('people/additive-example', p => {+ p.compiled_truth = p.compiled_truth.replace('A synthetic biography.', 'A synthetic biography.\nAlso advises [[companies/beta-example]].');+ p.timeline += '\n- **2026-02-02** | call — Spoke with [[people/carol-example]].';+ p.frontmatter.contacts = ['alice-example', 'bob-example', 'carol-example', 'alice-example'];+ p.frontmatter.phone_last_used = '2026-02-02';+ p.frontmatter.updated = '2026-02-02';+ });+ await write('people/replaced-example', p => { p.compiled_truth = p.compiled_truth.replace('A synthetic biography.', 'A different biography.'); });+ const binding = await claimWorktree(engine, id, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const registration = await registerLocalWriter(engine, 'cli');+ return { id, root, binding, registration, additive };+}++test('the reporter\'s additive page reconciles under --auto-additive; a replaced page stays blocked; remember then commits and reads back', async () => isolated(async engine => {+ const f = await fixture(engine), slug = 'people/additive-example', file = join(f.root, `${slug}.md`);+ const ctx: OperationContext = { engine, remote: false, sourceId: f.id, config: { engine: engine.kind }, dryRun: false, logger: { info() {}, warn() {}, error() {} } };+ await local(engine, f.registration, async () => {+ const fact = 'Prefers the synthetic morning review.', provenance = 'Synthetic operator conversation';+ await expect(operationsByName.remember!.handler(ctx, { fact, provenance, entity: slug, visibility: 'private', request_id: randomUUID() }))+ .rejects.toMatchObject({ writeError: 'source_changed' });++ const audit = await auditCanonicalSource(engine, f.id, { classify: true });+ expect(audit.classified).toEqual({ structurally_additive: 0, additive_with_suggestions: 1, review_required: 1, formatting_only: 0, error: 0 });+ expect(JSON.stringify(audit)).not.toContain('carol-example');+ expect(audit.findings.find(x => x.slug === 'people/replaced-example')).toMatchObject({ classification: 'review_required',+ drift_paths: [{ path: '/compiled_truth', class: 'review', reason: 'database_text_changed_or_removed' }] });++ const blocked = await runReconcilePreview(engine, { source_id: f.id, slug: 'people/replaced-example', auto_additive: true });+ expect(blocked).toMatchObject({ status: 'needs_resolution', classification: 'review_required', auto_decided_paths: [] });++ const suggested = await runReconcilePreview(engine, { source_id: f.id, slug, auto_additive: true });+ expect(suggested).toMatchObject({ status: 'needs_resolution', classification: 'additive_with_suggestions',+ auto_decided_paths: ['/frontmatter/contacts', '/frontmatter/phone_last_used', '/frontmatter/updated'], conflict_paths: ['/compiled_truth', '/timeline'] });+ expect(String(suggested.next_action)).toContain('--accept-suggested');++ const ready = await runReconcilePreview(engine, { source_id: f.id, slug, auto_additive: true, accept_suggested: true });+ expect(ready.status).toBe('ready');+ expect(ready.preview.format_version).toBe(2);+ expect(ready.preview.auto_decisions!.map(d => d.rule)).toEqual(['text_insertion_only', 'contacts_append_only', 'activity_date_advance', 'activity_date_advance', 'text_insertion_only']);++ const tampered = structuredClone(ready.preview);+ tampered.auto_decisions![0].evidence_digest = '0'.repeat(64);+ await expect(runReconcileApply(engine, { source_id: f.id, slug, preview: tampered, request_id: randomUUID() })).rejects.toMatchObject({ code: 'source_changed' });++ const applied = await runReconcileApply(engine, { source_id: f.id, slug, preview: ready.preview, request_id: randomUUID() });+ expect(applied.state).toBe('committed');+ const backup = join(configDir(), 'reconciliation-previews', (applied.outcome as { backup_reference: string }).backup_reference);+ expect(existsSync(backup)).toBe(true);+ expect(JSON.parse(readFileSync(backup, 'utf8')).preview.preimages.database.page.compiled_truth).toBe(f.additive.page.compiled_truth);++ const reconciled = (await engine.readPageSnapshot(slug, { sourceId: f.id }))!;+ expect(reconciled.page.compiled_truth).toContain('Also advises [[companies/beta-example]].');+ expect(reconciled.page.timeline).toContain('Spoke with [[people/carol-example]]');+ expect(reconciled.page.frontmatter).toMatchObject({ access: 'private', visibility: 'private', phone_last_used: '2026-02-02',+ contacts: ['alice-example', 'bob-example', 'carol-example', 'alice-example'] });++ const saved = await operationsByName.remember!.handler(ctx, { fact, provenance, entity: slug, visibility: 'private', request_id: randomUUID() }) as Record<string, unknown>;+ expect(saved).toMatchObject({ status: 'inserted', state: 'committed' });+ const current = (await engine.readPageSnapshot(slug, { sourceId: f.id }))!;+ expect(parseFactsFence(current.page.compiled_truth).facts).toEqual(expect.arrayContaining([expect.objectContaining({ claim: fact, visibility: 'private' })]));+ expect(parseMarkdown(readFileSync(file, 'utf8'), slug).compiled_truth).toBe(current.page.compiled_truth);++ const read = await dispatchToolCall(engine, 'get_page', { slug, source_id: f.id }, { remote: false, sourceId: f.id, config: { engine: engine.kind },+ logger: { info() {}, warn() {}, error() {} } });+ expect(read.isError).toBeFalsy();+ expect((read.content[0] as { text: string }).text).toContain(fact);++ const stillBlocked = await operationsByName.remember!.handler({ ...ctx }, { fact, provenance, entity: 'people/replaced-example', visibility: 'private', request_id: randomUUID() })+ .then(() => null, e => e);+ expect(stillBlocked).toMatchObject({ writeError: 'source_changed' });+ });+}), 180_000);++test('a file change after an --auto-additive preview makes apply refuse instead of publishing stale decisions', async () => isolated(async engine => {+ const f = await fixture(engine), slug = 'people/additive-example', file = join(f.root, `${slug}.md`);+ await local(engine, f.registration, async () => {+ const ready = await runReconcilePreview(engine, { source_id: f.id, slug, auto_additive: true, accept_suggested: true });+ writeFileSync(file, readFileSync(file, 'utf8') + '\nA concurrent edit.\n');+ await expect(runReconcileApply(engine, { source_id: f.id, slug, preview: ready.preview, request_id: randomUUID() })).rejects.toMatchObject({ code: 'source_changed' });+ const again = await runReconcilePreview(engine, { source_id: f.id, slug, auto_additive: true, accept_suggested: true });+ expect(again.status).toBe('ready');+ });+}), 180_000);