Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(trust): detect and repair provenance-stamp drift (#7891), file lower_page for maintenance lowerings (#7917), fail closed on unreadable derivations (#7918)

garrytan6838f54ad860
diff --git a/src/commands/doctor/checks/provenance-stamp-drift.ts b/src/commands/doctor/checks/provenance-stamp-drift.ts
new file mode 100644
index 0000000000..bcd06db8d7
--- /dev/null
+++ b/src/commands/doctor/checks/provenance-stamp-drift.ts
@@ -0,0 +1,54 @@
+/**
+ * #7891 `provenance_stamp_drift` (BRAIN): pages whose provenance stamps (`source_kind`, `ingested_via`, `ingested_at`)
+ * a write rewrote, or whose lowering marker a write removed, before #7892 made the stamps server-owned, and classified
+ * pages whose file would re-read above their stored tier (#7918). Read-only; per source it runs `scanProvenanceDrift`
+ * (trust/provenance-drift.ts, at most `DRIFT_SCAN_LIMIT` live pages). `warn` when a remote or unattributed write did
+ * the damage or a marker is missing; the owner's own edits are listed in details only. The fix previews
+ * `gbrain repair provenance`, which writes nothing; applying it only lowers trust and is the user's call.
+ */
+import type { Check } from '../../doctor.ts';
+import { agentFix, checkError } from '../check-fix.ts';
+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
+import { scanProvenanceDrift, type SourceDrift } from '../../../core/trust/provenance-drift.ts';
+
+const DOCS = 'docs/guides/repair.md#provenance';
+
+async function runProvenanceStampDrift(ctx: DoctorContext): Promise<Check[]> {
+ const checks: Check[] = [];
+ try {
+ const engine = connectedEngine(ctx);
+ const sourceIds = ctx.sourceIds ?? (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS NOT TRUE ORDER BY id')).map(row => row.id);
+ const scans: SourceDrift[] = [];
+ for (const sourceId of sourceIds) scans.push(await scanProvenanceDrift(engine, sourceId));
+ const damaged = (scan: SourceDrift) => scan.marker_lost.remote + scan.marker_lost.unattributed + scan.stamps_rewritten.remote
+ + scan.stamps_rewritten.unattributed + scan.marker_missing + scan.needs_review;
+ const pages = (scan: SourceDrift) => scan.items.filter(item => item.verdict.class !== 'local').length;
+ const details = { docs: DOCS, truncated: scans.some(scan => scan.truncated),
+ sources: scans.filter(scan => scan.items.length || scan.truncated || scan.schema !== 'current').map(({ items, ...scan }) => ({ ...scan, pages: items.filter(item => item.verdict.class !== 'local').length })) };
+ const bounded = details.truncated ? ' (bounded scan: more pages were not read)' : '';
+ const found = scans.filter(damaged);
+ if (!found.length) {
+ const local = scans.reduce((sum, scan) => sum + scan.items.length, 0);
+ checks.push({ name: 'provenance_stamp_drift', status: 'ok', details,
+ message: `No page has provenance stamps or a trust marker that another writer removed${local ? `; ${local} page(s) changed them in the owner's own edits (listed in details)` : ''}${bounded}.` });
+ return checks;
+ }
+ const total = found.reduce((sum, scan) => sum + pages(scan), 0);
+ const first = found[0]!;
+ const sample = first.items.find(item => item.verdict.class !== 'local')!;
+ const preview = ['gbrain', 'repair', 'provenance', '--source', first.source_id, '--json'];
+ checks.push({ name: 'provenance_stamp_drift', status: 'warn', details,
+ message: `${total} page(s) carry provenance stamps or a trust marker that a write removed before stamps became server-owned, or would re-read above their stored tier `
+ + `(${found.map(scan => `${scan.source_id}: ${pages(scan)}`).join('; ')}; e.g. ${found.flatMap(scan => scan.items.filter(item => item.verdict.class !== 'local').slice(0, 3).map(item => `${scan.source_id}:${item.slug}`)).slice(0, 5).join(', ')})${bounded}. `
+ + `Preview the repair with gbrain repair provenance --source ${first.source_id}; it lists each page and writes nothing. Applying it only lowers trust.`,
+ fix: agentFix(preview, 'Lists each page with the stamps, marker and tier before and after; it writes nothing. Applying the repair is the user\'s call.',
+ 'provenance_stamp_drift', { ask_user: true, docs: DOCS,
+ user_message: `${total} page(s) (for example ${sample.slug}) lost the record of where they came from, so gbrain may trust them more than it should. `
+ + 'Should I show you the list and put the original record back? It only lowers trust, and you can undo each page in gbrain trust review.' }) });
+ } catch (error) {
+ checks.push(checkError('provenance_stamp_drift', 'check page history for provenance stamps and trust markers a write removed', error, { details: { docs: DOCS } }));
+ }
+ return checks;
+}
+
+export const provenanceStampDriftEntry: DoctorEntry = { name: 'provenance_stamp_drift', emits: ['provenance_stamp_drift'], run: runProvenanceStampDrift };
diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.ts
index 29b76d5d50..bd397e15ca 100644
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@ -115,6 +115,7 @@ import { plannerStatsEntry } from './checks/planner-stats.ts';
import { revisionBackfillEntry } from './checks/revision-backfill.ts';
import { beliefLedgerEntry } from './checks/belief-ledger.ts';
import { trustTiersEntry } from './checks/trust-tiers.ts';
+import { provenanceStampDriftEntry } from './checks/provenance-stamp-drift.ts';
import { trustScanEntry } from './checks/trust-scan.ts';
import { trustSourcesUnclaimedEntry } from './checks/trust-sources-unclaimed.ts';
import { trustReleaseUnpreviewedEntry } from './checks/trust-release-unpreviewed.ts';
@@ -271,6 +272,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [
revisionBackfillEntry,
beliefLedgerEntry,
trustTiersEntry,
+ provenanceStampDriftEntry,
trustScanEntry,
trustSourcesUnclaimedEntry,
trustReleaseUnpreviewedEntry,
diff --git a/src/commands/repair.ts b/src/commands/repair.ts
index 2c2bf5639b..80409d6454 100644
--- a/src/commands/repair.ts
+++ b/src/commands/repair.ts
@@ -190,7 +190,7 @@ const VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--ski
const KIND_FLAGS: Record<string, readonly string[]> = {
'--only': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--skip': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--diff': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--yes': ['frontmatter', 'conversation-labels', 'stuck-recovery', 'ghost-pages', 'legacy-twins', 'rename-identity', 'url-clone-fences'],
'--include-cross-entity': ['duplicate-facts'],
- '--slug': ['fences', 'file-drift', 'rename-identity', 'overwritten-edits', 'origin-twins', 'timeline-order'], '--from': ['rename-identity'], '--close': ['rename-identity'], '--prefer': ['file-drift'], '--request': ['file-drift'], '--all-drifted': ['file-drift'], '--class': ['file-drift', 'visibility'], '--since': ['file-drift', 'generations'],
+ '--slug': ['fences', 'file-drift', 'rename-identity', 'overwritten-edits', 'origin-twins', 'timeline-order', 'provenance'], '--from': ['rename-identity'], '--close': ['rename-identity'], '--prefer': ['file-drift'], '--request': ['file-drift'], '--all-drifted': ['file-drift'], '--class': ['file-drift', 'visibility'], '--since': ['file-drift', 'generations'],
'--held': ['file-drift', 'generations'], '--side': ['file-drift'], '--state': ['file-drift'], '--cursor': ['file-drift'], '--provenance': ['file-drift'],
'--keep': ['stuck-recovery'], '--request-id': ['stuck-recovery'],
'--older-than': ['receipt-compaction'], '--include-failures': ['receipt-compaction'], '--force': ['receipt-compaction'],
@@ -454,7 +454,7 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro
...(olderThan ? ['--older-than', olderThan] : []), ...(includeFailures ? ['--include-failures'] : []), ...(force ? ['--force'] : []),
...(afterPage !== undefined ? ['--after', String(afterPage)] : []), ...(day ? ['--day', day] : []),
...(kind === 'rename-identity' ? [...slugs.flatMap(slug => ['--slug', slug]), ...(from ? ['--from', from] : []), ...(close ? ['--close'] : [])] : []),
- ...(kind === 'origin-twins' || kind === 'timeline-order' ? slugs.flatMap(slug => ['--slug', slug]) : []),
+ ...(kind === 'origin-twins' || kind === 'timeline-order' || kind === 'provenance' ? slugs.flatMap(slug => ['--slug', slug]) : []),
...(generations ? generationsSelectionArgv(generations) : [])];
const custom = repairSpec(kind as RepairKind).consentText;
const text = custom ? { ...custom, why: `Preview ${expect}: ${custom.why}`, user_message: `${custom.user_message} (preview ${expect.slice(0, 12)}${keep ? `, keep ${keep}` : ''})` } : {
diff --git a/src/core/cycle/patterns.ts b/src/core/cycle/patterns.ts
index 55f9843039..842826a20d 100644
--- a/src/core/cycle/patterns.ts
+++ b/src/core/cycle/patterns.ts
@@ -968,7 +968,11 @@ async function writeGroundedPage(engine: BrainEngine, maintenance: MaintenanceAu
return result;
};
if (!derived) await (removedEntries.length ? engine.transaction(write) : write(engine));
- else await derivedMaintenanceTransaction(engine, derived, async tx => ({ result: await write(tx), rows: [{ table: 'pages' as const, id: snapshot.page.id, sourceId }] }));
+ else await derivedMaintenanceTransaction(engine, derived, async tx => {
+ const [row] = await tx.executeRaw<{ trust_tier: string | null }>('SELECT trust_tier FROM pages WHERE id = $1', [snapshot.page.id]);
+ const prior = row ? { slug, tier: storedTrustTier(row.trust_tier), revision: snapshot.revision } : undefined;
+ return { result: await write(tx), rows: [{ table: 'pages' as const, id: snapshot.page.id, sourceId, ...(prior ? { prior } : {}) }] };
+ });
}
/**
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index 4e6b9920ec..47a09a31b7 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -250,6 +250,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([
'sync_landing_gaps',
// #6712: live pages whose database-only edit an incremental sync overwrote without a hold (doctor/checks/overwritten-edits.ts).
'sync_overwritten_db_edits',
+ // #7891: provenance stamps and trust markers a write removed before #7892 (doctor/checks/provenance-stamp-drift.ts).
+ 'provenance_stamp_drift',
'unified_multimodal_coverage',
'unverified_extractions',
'voice_gate_health',
diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.ts
index 091d2328a1..3682b449df 100644
--- a/src/core/persistence/prepared-maintenance.ts
+++ b/src/core/persistence/prepared-maintenance.ts
@@ -33,7 +33,8 @@ import { assertPhysicalRoot } from './physical-root.ts';
import { isConnectorSourceKind } from './connector-identity.ts';
import { MaintenanceWriteWait } from './maintenance-wait.ts';
import { auditConflictsCommand, FILE_DRIFT_MESSAGE, liveFileDrift } from './drift-conflicts.ts';
-import { declaredWriteTrust, lowerToDerivedTier, readDerivationDeclaration, recordTaintEdges, type DerivationDeclaration } from '../trust/taint.ts';
+import { lowerToDerivedTier, readDerivationDeclaration, recordTaintEdges, type DerivationDeclaration } from '../trust/taint.ts';
+import { derivationWriteTrust, recordAgentPageLowering, storedPageTier } from '../trust/page-write.ts';
import { sameInstantTies } from '../facts/claim-ties.ts';
import { factPreimages, recordConsolidationGeneration } from '../generations/adapters/fact-rows.ts';
@@ -548,21 +549,27 @@ async function prepareFactFenceAdoption(unbounded: BrainEngine, row: WriteReques
* derived row when the publication changed no content column, and records
* the complete input edges (ENG-7). A consolidation's takes fence edit
* keeps the entity page's tier (page-prepare's fence-edit rule).
+ * #7918: a declaration that is present but unreadable publishes at `unknown`
+ * (fail closed) with no input edges. #7917: a page the publication lowered
+ * files a `lower_page` proposal the owner sees in `gbrain trust review`.
*/
export async function prepareMaintenanceMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig, clock?: ClaimPhaseClock): Promise<PreparedMutation> {
const prepared = await prepareMaintenanceKind(engine, row, config, clock);
+ const trust = derivationWriteTrust(row.intent);
+ if (!trust) return prepared;
const declaration = readDerivationDeclaration(row.intent?.derivation);
- if (!declaration) return prepared;
- const trust = declaredWriteTrust(declaration);
const consolidation = row.intent?.kind === 'managed_maintenance_consolidate';
return { ...prepared, trust, apply: async (tx, preimage) => {
+ const snapshot = consolidation ? null : await tx.readPageSnapshot(row.slug, { sourceId: row.source_id });
+ const prior = snapshot ? { tier: await storedPageTier(tx, row.source_id, row.slug), revision: snapshot.revision } : null;
const outcome = await prepared.apply(tx, preimage);
const [derived] = consolidation ? (outcome.take_id ? [{ table: 'takes' as const, id: Number(outcome.take_id) }] : [])
: (await tx.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [row.source_id, row.slug]))
.map(page => ({ table: 'pages' as const, id: Number(page.id) }));
if (derived) {
- await lowerToDerivedTier(tx, derived.table, [derived.id], trust);
- await recordTaintEdges(tx, { ...derived, sourceId: row.source_id }, declaration.inputs);
+ const lowered = await lowerToDerivedTier(tx, derived.table, [derived.id], trust);
+ if (declaration) await recordTaintEdges(tx, { ...derived, sourceId: row.source_id }, declaration.inputs);
+ if (lowered.length && prior?.tier) await recordAgentPageLowering(tx, row, { tier: prior.tier, revision: prior.revision });
}
return outcome;
} };
diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.ts
index 4005899c9f..75ec39513b 100644
--- a/src/core/persistence/preview-approval.ts
+++ b/src/core/persistence/preview-approval.ts
@@ -40,7 +40,7 @@ export const PREVIEW_APPROVAL_OP = 'repair-approval';
/** The default `purgeStaleCheckpoints` TTL; an older approved set may already be gone. */
export const APPROVAL_MAX_AGE_DAYS = 7;
-export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'atoms-restore' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'redacted-facts' | 'loop-facts' | 'ontology-facts' | 'facts-rehome' | 'consolidate-ties' | 'duplicate-facts' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'origin-twins' | 'receipt-compaction' | 'accepted-takes' | 'rename-identity' | 'overwritten-edits' | 'legacy-twins' | 'missing-tables' | 'segmented-mirror' | 'uncommitted-deletions' | 'visibility' | 'generations' | 'fact-claim-dates' | 'timeline-order';
+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'atoms-restore' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'redacted-facts' | 'loop-facts' | 'ontology-facts' | 'facts-rehome' | 'consolidate-ties' | 'duplicate-facts' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'origin-twins' | 'receipt-compaction' | 'accepted-takes' | 'rename-identity' | 'overwritten-edits' | 'legacy-twins' | 'missing-tables' | 'segmented-mirror' | 'uncommitted-deletions' | 'visibility' | 'generations' | 'fact-claim-dates' | 'timeline-order' | 'provenance';
export interface ApprovedSetKey {
command: PreviewApprovalCommand;
diff --git a/src/core/repair/core.ts b/src/core/repair/core.ts
index 0c3fd9f858..22335d049a 100644
--- a/src/core/repair/core.ts
+++ b/src/core/repair/core.ts
@@ -51,7 +51,7 @@ import { classifyItemFailure, ItemRun, type ItemFailure } from '../item-failure.
import type { ProgressReporter } from '../progress.ts';
import type { GenerationsSelection } from '../generations/repair.ts';
-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'conversation-labels', 'captured-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'duplicate-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'timeline-order', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'uncommitted-deletions', 'generations', 'fact-claim-dates'] as const;
+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'conversation-labels', 'captured-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'duplicate-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'timeline-order', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'uncommitted-deletions', 'generations', 'fact-claim-dates', 'provenance'] as const;
export type RepairKind = typeof REPAIR_KINDS[number];
export interface RepairScope { brain_id: string; source_ids: string[] }
diff --git a/src/core/repair/provenance.ts b/src/core/repair/provenance.ts
new file mode 100644
index 0000000000..25abda57e0
--- /dev/null
+++ b/src/core/repair/provenance.ts
@@ -0,0 +1,147 @@
+/**
+ * `gbrain repair provenance` (#7891, #7918): put back the provenance stamps and lowering markers that writes removed
+ * before #7892, and stamp the trust marker on classified pages whose file would re-read higher than the row.
+ * trust/provenance-drift.ts decides which pages and what each one gets; every change only lowers.
+ *
+ * - `restore` (class `remote`, or `ambiguous` with `--include-ambiguous`): the stamps restored, the lost cap stamped
+ * back as the `trust_tier` marker, the page lowered to min(stored, marker), and a `lower_page` proposal filed
+ * (`gbrain trust review` confirms or reverts it), through the owner page write `trust_owner_page` mode
+ * `restore_provenance` (trust/page-handlers.ts `restorePageProvenance`).
+ * - `restamp` (#7918): the stored tier stamped as the marker; the row keeps its tier (mode `repair_marker`).
+ * - Listed, never written: `needs_review` (a later local write also changed the stamp), `local` (the owner's own
+ * edit), `ambiguous` without the flag.
+ *
+ * Explicit-only and preview-bound: the preview lists each page with its revision and planned change under a hash and
+ * writes nothing but the approval checkpoint; `--apply --expect <hash> --yes` writes exactly that set, one owner page
+ * write per page, bound to the previewed revision and change (`preview_changed` when either moved). On a managed
+ * brain the write publishes the canonical file through the coordinator (Git stays the parent); on a repo-less brain
+ * the database is the record. Local CLI only. It never runs from `--all`, the remediation plan or an upgrade.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { OperationError, opError } from '../ops/contract.ts';
+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
+import { repairPageMarker, restorePageProvenance } from '../trust/page-handlers.ts';
+import { plannedDigest, readPageDrift, scanProvenanceDrift, type DriftItem } from '../trust/provenance-drift.ts';
+import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairListing, type RepairPlan, type RepairScope } from './core.ts';
+
+const DOCS = 'docs/guides/repair.md#provenance';
+
+interface Selection { source_ids: string[]; slugs: string[]; include_ambiguous: boolean }
+interface PlannedPage { source_id: string; slug: string; id: number; revision: string; action: 'restore' | 'restamp'; planned: string; summary: string }
+interface ProvenanceItem extends RepairItem { page: PlannedPage; hash: string; includeAmbiguous: boolean; last: boolean }
+
+function previewCommand(scope: RepairScope, selection: Selection): string {
+ return `gbrain repair provenance${scope.source_ids.length === 1 ? ` --source ${scope.source_ids[0]}` : ''}${selection.slugs.map(slug => ` --slug ${slug}`).join('')}`
+ + (selection.include_ambiguous ? ' --include-ambiguous' : '');
+}
+
+const sourcesOf = (engine: BrainEngine, scope: RepairScope) => engine.executeRaw<{ id: string; incarnation: string }>(
+ 'SELECT id, incarnation::text AS incarnation FROM sources WHERE id=ANY($1::text[]) ORDER BY id', [scope.source_ids]);
+
+const hashOf = async (engine: BrainEngine, scope: RepairScope, selection: Selection, pages: PlannedPage[]) =>
+ previewHash({ kind: 'provenance-v1', brain_id: scope.brain_id, sources: await sourcesOf(engine, scope), selection,
+ pages: pages.map(page => ({ source_id: page.source_id, id: page.id, revision: page.revision, action: page.action, planned: page.planned })) });
+
+const describe = (value: unknown) => value === null || value === undefined ? '(none)' : String(value);
+
+function summaryOf(item: DriftItem): string {
+ const { verdict } = item;
+ const restore = verdict.restore!;
+ const stamps = Object.entries(restore.stamps).map(([key, value]) => {
+ const live = verdict.changes.filter(change => change.key === key).at(-1)?.to;
+ return `${key} ${describe(live)} -> ${describe(value)}`;
+ });
+ return [...stamps, `trust_tier marker -> ${describe(restore.marker)}`, `tier ${item.tier} -> ${restore.tier}`].join('; ');
+}
+
+function writerDetail(item: DriftItem): string {
+ const change = item.verdict.changes.find(entry => entry.writer === item.verdict.writer) ?? item.verdict.changes[0];
+ return change ? `written by a ${change.writer} write${change.request_id ? ` (request ${change.request_id})` : ''}` : '';
+}
+
+/** Every page of the selection the repair would write or list, in id order. Read-only. */
+async function scan(engine: BrainEngine, scope: RepairScope, selection: Selection) {
+ const planned: PlannedPage[] = [];
+ const listing: RepairListing[] = [];
+ const residuals: Record<string, number> = { restore: 0, restamp: 0, ambiguous: 0, needs_review: 0, local: 0 };
+ for (const sourceId of scope.source_ids) {
+ const drift = await scanProvenanceDrift(engine, sourceId, { limit: Number.MAX_SAFE_INTEGER, includeAmbiguous: selection.include_ambiguous, slugs: selection.slugs });
+ for (const item of drift.items) {
+ const label = `${item.source_id}:${item.slug} (revision ${item.revision})`;
+ const { verdict } = item;
+ if (verdict.class === 'local') { residuals.local!++; listing.push({ item: label, class: 'local', detail: `the owner's own edit, never repaired; ${writerDetail(item)}` }); continue; }
+ if (verdict.class === 'needs_review') { residuals.needs_review!++; listing.push({ item: label, class: 'needs_review', detail: `${verdict.reason}; edit the page by hand` }); continue; }
+ if (!verdict.restore) {
+ residuals.ambiguous!++;
+ listing.push({ item: label, class: 'ambiguous', detail: `no recorded writer; previewed with --include-ambiguous only; ${writerDetail(item)}` });
+ continue;
+ }
+ const action = verdict.class === 'restamp' ? 'restamp' : 'restore';
+ residuals[action]!++;
+ const page: PlannedPage = { source_id: item.source_id, slug: item.slug, id: item.page_id, revision: item.revision, action, planned: plannedDigest(item), summary: summaryOf(item) };
+ planned.push(page);
+ listing.push({ item: label, class: action === 'restamp' ? 'restamp' : verdict.class, detail: action === 'restamp' ? page.summary : `${page.summary}; ${writerDetail(item)}` });
+ }
+ }
+ planned.sort((a, b) => a.id - b.id);
+ return { planned, listing, residuals };
+}
+
+function item(page: PlannedPage, hash: string, includeAmbiguous: boolean, last: boolean): ProvenanceItem {
+ return { cursor: { phase: 0, id: page.id }, source_id: page.source_id, slug: page.slug, chars: 0, action: page.summary, page, hash, includeAmbiguous, last };
+}
+
+/** The page still needs exactly the previewed change. */
+async function stillPlanned(engine: BrainEngine, page: PlannedPage, includeAmbiguous: boolean): Promise<'planned' | 'done' | 'moved'> {
+ const current = await readPageDrift(engine, page.source_id, page.slug, { includeAmbiguous });
+ if (!current || current.page_id !== page.id || !current.verdict.restore) return 'done';
+ return current.revision === page.revision && plannedDigest(current) === page.planned ? 'planned' : 'moved';
+}
+
+export const provenanceRepair: RepairHandler = {
+ kind: 'provenance',
+ async plan(engine, scope, after, opts): Promise<RepairPlan> {
+ const selection: Selection = { source_ids: scope.source_ids, slugs: [...new Set(opts?.slugs ?? [])].sort(), include_ambiguous: opts?.includeAmbiguous === true };
+ const command = previewCommand(scope, selection);
+ if (!opts?.apply) {
+ const { planned, listing, residuals } = await scan(engine, scope, selection);
+ const hash = await hashOf(engine, scope, selection, planned);
+ if (planned.length) await saveApprovedSet<PlannedPage & { selection: Selection }>(engine, { command: 'provenance', hash }, planned.map(page => ({ ...page, selection })));
+ return { items: planned.map((page, index) => item(page, hash, selection.include_ambiguous, index === planned.length - 1)), preview_hash: hash, residuals, listing };
+ }
+ if (opts.remote !== false) {
+ throw opError('permission_denied', 'gbrain repair provenance --apply runs only from the local CLI on the brain host.', `Run it there: ${command}`);
+ }
+ if (!opts.expect) {
+ throw new OperationError('invalid_params', 'gbrain repair provenance --apply writes only the set a preview printed.',
+ `Preview first: ${command} — show the user the listing, then run the apply command it prints: ${command} --apply --expect <preview-hash> --yes`, DOCS);
+ }
+ const expect = opts.expect;
+ const approved = (await loadApprovedSet<PlannedPage & { selection: Selection }>(engine, { command: 'provenance', hash: expect, previewCommand: command,
+ emptyHash: () => hashOf(engine, scope, selection, []) })).items;
+ const selectionKey = (value: Selection) => JSON.stringify([value.source_ids, value.slugs, value.include_ambiguous]);
+ if (approved.some(page => selectionKey(page.selection) !== selectionKey(selection))) throw previewChangedError(expect, command);
+ const pages: PlannedPage[] = [];
+ // A page an earlier run of this apply already repaired is done; any other page must still need exactly the previewed change.
+ for (const { selection: _selection, ...page } of approved) {
+ const state = await stillPlanned(engine, page, selection.include_ambiguous);
+ if (state === 'moved') throw previewChangedError(expect, command);
+ if (state === 'planned') pages.push(page);
+ }
+ if (!pages.length) await clearApprovedSet(engine, { command: 'provenance', hash: expect });
+ return { items: pages.map((page, index) => item(page, expect, selection.include_ambiguous, index === pages.length - 1)).filter(entry => afterCursor(entry.cursor, after)),
+ preview_hash: expect, residuals: {} };
+ },
+ async apply(ctx, entry): Promise<RepairItemOutcome> {
+ const { page, hash, includeAmbiguous, last } = entry as ProvenanceItem;
+ try {
+ if (await stillPlanned(ctx.engine, page, includeAmbiguous) !== 'planned') return { applied: false, outcome: 'changed_since_preview', reason: 'the page changed since the preview' };
+ const input = { sourceId: page.source_id, slug: page.slug, expectedRevision: page.revision, confirmation: { via: 'preview_hash' as const }, config: ctx.config };
+ const result = page.action === 'restamp' ? await repairPageMarker(ctx.engine, input)
+ : await restorePageProvenance(ctx.engine, { ...input, planned: page.planned, includeAmbiguous });
+ return { applied: true, outcome: page.action === 'restamp' ? 'restamped' : 'restored', detail: { tier: result.tier, prior_tier: result.prior_tier } };
+ } finally {
+ if (last) await clearApprovedSet(ctx.engine, { command: 'provenance', hash });
+ }
+ },
+};
diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.ts
index 37b76a93f3..bf15782277 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -84,6 +84,7 @@ import { urlCloneFencesRepair } from './url-clone-fences.ts';
import { segmentedMirrorRepair } from './segmented-mirror.ts';
import { uncommittedDeletionsRepair, UNCOMMITTED_DELETIONS_CONSENT_TEXT } from './uncommitted-deletions.ts';
import { factClaimDatesRepair } from './fact-claim-dates.ts';
+import { provenanceRepair } from './provenance.ts';
import { generationsRepair, generationsSelectionArgv, type GenerationsSelection } from '../generations/repair.ts';
import { restoreDaysHint } from '../generations/config.ts';
import { ERROR_CATALOGUE, catalogueError } from '../error-catalogue.ts';
@@ -555,6 +556,20 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {
+ 'Preview-bound and destructive: --apply --expect <hash> --yes recomputes the plan (preview_changed when it differs) and moves exactly the '
+ 'previewed rows. Runs only when named; never on upgrade.',
},
+ provenance: {
+ handler: provenanceRepair, embeds: 'effect', checks: ['provenance_stamp_drift'], explicit_only: true, preview_bound: true, consent: 'destructive',
+ consentText: {
+ what: 'Restore the previewed provenance stamps and lowering markers, and lower each listed page to match',
+ why: 'The preview listed each page whose source_kind, ingested_via or ingested_at a remote write rewrote, or whose lowering marker it removed, before those stamps were server-owned (#7892), and each classified page whose file would re-read above its stored tier.',
+ risk: 'Only the three stamps and the trust_tier marker change, and a page is only lowered, never raised; each lowered page gets a lower_page proposal that gbrain trust review confirms or reverts. A page that changed since the preview refuses the apply (preview_changed). Managed sources commit the file through the Git effect; undo with gbrain trust review or git revert.',
+ user_message: 'Restore where the previewed pages came from and lower their trust to match? Only their provenance stamps and trust marker change, and you can undo each one in gbrain trust review',
+ },
+ summary: 'Restore provenance stamps (source_kind, ingested_via, ingested_at) and lowering markers that writes removed before #7892, and stamp the '
+ + 'trust marker on classified pages whose file would re-read above their stored tier (#7891, #7918). Remote damage is repaired; unattributed '
+ + 'damage only with --include-ambiguous; the owner\'s own edits and pages a later local write also changed are listed, never written. '
+ + 'Each change only lowers, and a lowered page files a lower_page proposal for gbrain trust review. --slug <slug> narrows. Preview-bound and '
+ + 'destructive: --apply --expect <hash> --yes writes exactly the previewed pages through the owner page write; local CLI only; never on upgrade.',
+ },
'generations': {
handler: generationsRepair, embeds: 'effect', checks: ['generation_retirements', 'generation_held', 'generation_pending'], explicit_only: true, preview_bound: true, consent: 'destructive',
consentText: {
diff --git a/src/core/trust/page-handlers.ts b/src/core/trust/page-handlers.ts
index 51bed8e5ee..5317fa250f 100644
--- a/src/core/trust/page-handlers.ts
+++ b/src/core/trust/page-handlers.ts
@@ -18,6 +18,10 @@
* - #6550 marker repair (`repairPageMarker`, local CLI only): rewrite a page's
* `trust_tier: unknown` marker to its stored tier (removed at owner tiers);
* the row keeps its tier. trust/marker-repair.ts decides which pages.
+ * - #7891 provenance restore (`restorePageProvenance`, local CLI only): put back
+ * the provenance stamps a remote write rewrote and the lowering marker it
+ * removed (trust/provenance-drift.ts decides), lower the page to match, and
+ * file a `lower_page` proposal so the owner sees it in `gbrain trust review`.
*
* Every function here runs after the caller established the owner's
* confirmation (trust/confirm.ts); each re-checks the page revision it was
@@ -26,7 +30,8 @@
*/
import { randomUUID } from 'node:crypto';
import type { BrainEngine } from '../engine.ts';
-import { queueTierProjection } from './page-write.ts';
+import { queueTierProjection, recordAgentPageLowering } from './page-write.ts';
+import { plannedDigest, readPageDrift } from './provenance-drift.ts';
import type { GBrainConfig } from '../config.ts';
import type { OperationContext } from '../ops/contract.ts';
import { opError } from '../ops/contract.ts';
@@ -45,13 +50,15 @@ import {
decisionResult, registerTrustProposalHandler, transitionTrustProposal, type TrustProposalAction,
type TrustDecisionContext, type TrustDecisionResult, type TrustProposalRow,
} from './proposals.ts';
-import { OWNER_TIER_FLOOR, compareTrust, effectiveWriteTrust, storedTrustTier, type TrustTier, type WriteTrust } from './tier.ts';
+import { OWNER_TIER_FLOOR, compareTrust, effectiveWriteTrust, minTrust, storedTrustTier, type TrustTier, type WriteTrust } from './tier.ts';
import { propagateTierLowering } from './propagation.ts';
import { beliefStreamSlugs, lockedBeliefBatch } from '../belief/writers.ts';
import { markBeliefCommits } from '../belief/append.ts';
/** The journaled operation that publishes an owner page action on a managed brain. */
export const TRUST_OWNER_PAGE_OPERATION = 'trust_owner_page';
+/** The proposer a provenance restore's `lower_page` proposal names. */
+export const PROVENANCE_PROPOSER = 'provenance_repair';
/** Fence projections keep their own tiers when an owner action rewrites the page around them. */
const FENCE_TABLES = ['facts', 'takes', 'timeline_entries'] as const;
@@ -177,7 +184,7 @@ export interface PageActionInput {
}
export interface PageActionResult {
- status: 'confirmed' | 'reverted' | 'repaired' | 'unchanged';
+ status: 'confirmed' | 'reverted' | 'repaired' | 'restored' | 'unchanged';
ref: string;
tier: TrustTier;
prior_tier: TrustTier;
@@ -186,9 +193,12 @@ export interface PageActionResult {
}
type OwnerPageIntent = {
- mode: 'confirm' | 'revert' | 'repair_marker';
+ mode: 'confirm' | 'revert' | 'repair_marker' | 'restore_provenance';
expected_revision: string;
version_id?: number;
+ /** restore_provenance: the digest of the change the preview showed, and whether unattributed damage was included. */
+ planned?: string;
+ include_ambiguous?: boolean;
via: OwnerConfirmation['via'];
proposal?: PageActionInput['proposal'];
};
@@ -230,7 +240,9 @@ export async function confirmPage(engine: BrainEngine, input: PageActionInput):
/** #6550: the marker a repaired page carries: its stored tier, none at owner tiers (CEO-21 stamps none there). */
export const repairedMarker = (tier: TrustTier): TrustTier | null => compareTrust(tier, OWNER_TIER_FLOOR) >= 0 ? null : tier;
-const ACTION_NAMES: Record<OwnerPageIntent['mode'], string> = { confirm: 'its confirmation', revert: 'the revert', repair_marker: 'the marker repair' };
+const ACTION_NAMES: Record<OwnerPageIntent['mode'], string> = { confirm: 'its confirmation', revert: 'the revert', repair_marker: 'the marker repair', restore_provenance: 'the provenance restore' };
+/** Owner page modes only the trusted local CLI may run. */
+const LOCAL_ONLY_MODES: ReadonlyArray<OwnerPageIntent['mode']> = ['repair_marker', 'restore_provenance'];
/** #6550: rewrites the page's marker to `repairedMarker(stored tier)`, bound to the previewed revision; the row keeps its tier. */
export async function repairPageMarker(engine: BrainEngine, input: PageActionInput): Promise<PageActionResult & { marker: TrustTier | null }> {
@@ -244,6 +256,29 @@ export async function repairPageMarker(engine: BrainEngine, input: PageActionInp
return { status: 'repaired', ref, tier: state.tier, prior_tier: state.tier, marker };
}
+/** The markdown and tier the provenance restore writes for a page now, refused when it is not the previewed change. */
+async function plannedProvenanceRestore(engine: BrainEngine, state: PageTrustState, intent: Pick<OwnerPageIntent, 'planned' | 'include_ambiguous'>): Promise<{ content: string; tier: TrustTier }> {
+ const item = await readPageDrift(engine, state.sourceId, state.slug, { includeAmbiguous: intent.include_ambiguous === true });
+ const restore = item?.verdict.restore;
+ if (!item || !restore || item.verdict.class === 'restamp' || plannedDigest(item) !== intent.planned) throw changedSincePreview(pageRef(state.sourceId, state.slug), ACTION_NAMES.restore_provenance);
+ const { page } = state.snapshot;
+ return { content: serializeMarkdown(restore.frontmatter, page.compiled_truth ?? '', page.timeline ?? '', {
+ type: (page.type as PageType) ?? 'note', title: page.title ?? '', tags: state.snapshot.tags }), tier: minTrust(state.tier, restore.tier) };
+}
+
+/** #7891: restores the previewed provenance stamps and lowering marker, bound to the previewed revision and change; only lowers. */
+export async function restorePageProvenance(engine: BrainEngine, input: PageActionInput & { planned: string; includeAmbiguous?: boolean }): Promise<PageActionResult> {
+ const ref = pageRef(input.sourceId, input.slug);
+ const state = await readPageTrustState(engine, input.sourceId, input.slug);
+ if (!state) throw opError('page_not_found', `No live page ${ref}.`, 'Preview gbrain repair provenance again to see the current candidates.');
+ if (state.revision !== input.expectedRevision) throw changedSincePreview(ref, ACTION_NAMES.restore_provenance);
+ const intent: OwnerPageIntent = { mode: 'restore_provenance', expected_revision: input.expectedRevision, via: input.confirmation.via,
+ planned: input.planned, include_ambiguous: input.includeAmbiguous === true };
+ const { content, tier } = await plannedProvenanceRestore(engine, state, intent);
+ await publishOwnerPage(engine, input, intent, content, tier);
+ return { status: 'restored', ref, tier, prior_tier: state.tier };
+}
+
/** The tier a version restores: its snapshot tier, `unknown` for legacy versions. */
export const versionTier = (version: { trust_tier?: string | null }): TrustTier => storedTrustTier(version.trust_tier);
@@ -274,13 +309,29 @@ async function publishOwnerPage(engine: BrainEngine, input: PageActionInput, int
const { importFromContent } = await import('../import-file.ts');
const attribution = await attributionFor(engine, input.by);
const trust = ownerTrust(tier, intent.mode, intent.via);
+ // A repair mode on an unmanaged checkout renders the repaired row to the page's file in the same transaction (put_page's
+ // write-through), so a re-read of the checkout does not undo it; the file must still be the bytes read here.
+ const writeThrough = LOCAL_ONLY_MODES.includes(intent.mode) ? await import('../write-through.ts') : null;
+ const target = writeThrough ? await writeThrough.resolvePageWriteTarget(engine, input.slug, input.sourceId) : null;
+ const { existsSync, readFileSync } = await import('node:fs');
+ const fileBytes = target?.ok ? (existsSync(target.filePath) ? readFileSync(target.filePath, 'utf8') : null) : undefined;
await engine.transaction(tx => withWriteAttribution(tx, { ...attribution, trust }, () => withTrustPromotion(tx, tier, () =>
withTrustKeep(tx, FENCE_TABLES, async () => {
if ((await tx.readPageSnapshot(input.slug, { sourceId: input.sourceId }))?.revision !== input.expectedRevision) {
throw changedSincePreview(pageRef(input.sourceId, input.slug), ACTION_NAMES[intent.mode]);
}
// forceRechunk: the trust_tier marker is hash-ephemeral, so removing it alone would read as unchanged content.
+ const prior = intent.mode === 'restore_provenance' ? await readPageTrustState(tx, input.sourceId, input.slug) : null;
await importFromContent(tx, input.slug, markdown, { sourceId: input.sourceId, noEmbed: true, preserveGateMarkers: intent.mode !== 'revert', forceRechunk: true, allowEmptyOverwrite: intent.mode === 'revert' });
+ if (prior) await recordAgentPageLowering(tx, { operation: TRUST_OWNER_PAGE_OPERATION, source_id: input.sourceId, slug: input.slug }, { tier: prior.tier, revision: prior.revision }, PROVENANCE_PROPOSER);
+ if (writeThrough && target?.ok) {
+ const written = await writeThrough.writePageThrough(tx, input.slug, { sourceId: input.sourceId, expectedFileBytes: fileBytes ?? null });
+ if (written.skipped === 'file_changed') throw changedSincePreview(pageRef(input.sourceId, input.slug), ACTION_NAMES[intent.mode]);
+ if (!written.written && written.skipped !== 'disabled_by_config' && written.skipped !== 'url_clone') {
+ throw opError('unavailable', `The page file of ${pageRef(input.sourceId, input.slug)} could not be written (${written.skipped ?? written.error}); nothing was changed.`,
+ 'Fix the checkout (gbrain sources status), then preview the repair again.');
+ }
+ }
await closeProposal(tx, intent.proposal, input.by);
}))));
}
@@ -320,7 +371,7 @@ async function submitOwnerPage(engine: BrainEngine, input: PageActionInput, inte
export async function prepareTrustOwnerPageMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {
const intent = row.intent as unknown as OwnerPageIntent | null;
if (row.operation !== TRUST_OWNER_PAGE_OPERATION || !intent || !Object.hasOwn(ACTION_NAMES, intent.mode) || typeof intent.expected_revision !== 'string'
- || (row.authority.remote && (intent.mode === 'repair_marker' || !(row.authority.scopes ?? []).includes(MEMORY_CONFIRM_SCOPE)))) {
+ || (row.authority.remote && (LOCAL_ONLY_MODES.includes(intent.mode) || !(row.authority.scopes ?? []).includes(MEMORY_CONFIRM_SCOPE)))) {
throw opError('confirmation_required', 'This owner page action is not confirmed by the owner; nothing was changed.',
'Run the gbrain trust command on the brain host in an interactive terminal.');
}
@@ -339,7 +390,8 @@ export async function prepareTrustOwnerPageMutation(engine: BrainEngine, row: Wr
} else if (intent.mode === 'repair_marker') {
tier = state.tier;
content = markdownWithoutMarker(state.snapshot, repairedMarker(tier));
- } else content = markdownWithoutMarker(state.snapshot);
+ } else if (intent.mode === 'restore_provenance') ({ content, tier } = await plannedProvenanceRestore(engine, state, intent));
+ else content = markdownWithoutMarker(state.snapshot);
// The request keeps its own operation, so page-prepare stamps no CEO-21 marker and files no lower_page item for it.
const { preparePageMutation } = await import('../persistence/page-prepare.ts');
const page = await preparePageMutation(engine, row, config, { content, expectedRevision: intent.expected_revision, ...(tags ? { tags } : {}) });
@@ -347,6 +399,7 @@ export async function prepareTrustOwnerPageMutation(engine: BrainEngine, row: Wr
page.trust = ownerTrust(tier, intent.mode, intent.via);
page.apply = (tx, preimage) => withTrustPromotion(tx, tier, () => withTrustKeep(tx, FENCE_TABLES, async () => {
const outcome = await apply(tx, preimage);
+ if (intent.mode === 'restore_provenance') await recordAgentPageLowering(tx, row, { tier: state.tier, revision: state.revision }, PROVENANCE_PROPOSER);
await closeProposal(tx, intent.proposal, { kind: row.principal_kind as Principal['kind'], id: row.principal_id });
return { ...outcome, trust_action: intent.mode, trust_tier: tier };
}));
diff --git a/src/core/trust/page-write.ts b/src/core/trust/page-write.ts
index fae9260596..11b7908cdc 100644
--- a/src/core/trust/page-write.ts
+++ b/src/core/trust/page-write.ts
@@ -19,7 +19,10 @@
* is gated per row (CEO-27).
* - CEO-12: an agent write that replaces the body of a higher-tier page lowers
* the page and files one `lower_page` trust proposal per page (later edits
- * fold into it) with the prior owner version to revert to.
+ * fold into it) with the prior owner version to revert to. #7917: so does a
+ * derived page publication that lowers a page.
+ * - #7918: a derivation declaration that is present but unreadable (a malformed
+ * input, a missing origin) rates the write `unknown`, never the source default.
*/
import type { BrainEngine } from '../engine.ts';
import { queuePageProjection } from '../page-state/projections.ts';
@@ -40,11 +43,20 @@ export function isFenceEditWrite(row: Pick<WriteRequest, 'operation' | 'intent'>
return FENCE_EDIT_OPERATIONS.includes(row.operation) || row.intent?.kind === 'managed_facts_entity';
}
+/** The write carries a derivation declaration, readable or not. */
+const declaresDerivation = (intent: WriteRequest['intent'] | null | undefined) => intent?.derivation !== undefined && intent?.derivation !== null;
+
+/** The declared tier of a derived write; `unknown` when the declaration is present but unreadable (#7918), undefined when absent. */
+export function derivationWriteTrust(intent: WriteRequest['intent'] | null | undefined): WriteTrust | undefined {
+ if (!declaresDerivation(intent)) return undefined;
+ const derivation = readDerivationDeclaration(intent!.derivation);
+ return derivation ? declaredWriteTrust(derivation) : effectiveWriteTrust({ channel: 'unknown', origin: { channel: 'derivation_unreadable' } });
+}
+
/** The tier of one journaled page write, or undefined when the request's channel declares none. */
export function pageWriteTrust(row: Pick<WriteRequest, 'id' | 'operation' | 'authority' | 'intent'>, frontmatter: Record<string, unknown> | null | undefined): WriteTrust | undefined {
// A managed derived page (atoms, synthesis, concepts, chronicle) carries its derivation declaration (trust/taint.ts).
- const derivation = readDerivationDeclaration(row.intent?.derivation);
- const channel = derivation ? declaredWriteTrust(derivation) : requestChannelTrust(row);
+ const channel = derivationWriteTrust(row.intent) ?? requestChannelTrust(row);
if (!channel || isFenceEditWrite(row)) return channel;
const caps = frontmatterTrustCaps(frontmatter);
return caps.length ? effectiveWriteTrust({ channel: channel.tier, lowerTo: caps, origin: channel.origin ?? { channel: row.operation } }) : channel;
@@ -78,7 +90,7 @@ export async function storedPageTier(engine: BrainEngine, sourceId: string, slug
export function stampPageTrustMarker(row: Pick<WriteRequest, 'operation' | 'intent'>, frontmatter: Record<string, unknown>, trust: WriteTrust | undefined, stored: TrustTier | null,
storedFrontmatter?: Record<string, unknown> | null): void {
if (!trust || isFenceEditWrite(row)) return;
- if (!CONTENT_OPERATIONS.includes(row.operation) && !readDerivationDeclaration(row.intent?.derivation)) return;
+ if (!CONTENT_OPERATIONS.includes(row.operation) && !declaresDerivation(row.intent)) return;
const prior = stored && stored !== 'unknown' ? [stored] : frontmatterTrustCaps(storedFrontmatter);
const tier = minTrust(trust.tier, ...prior);
const stamped = stampTrustMarker(frontmatter, tier);
@@ -89,10 +101,13 @@ export function stampPageTrustMarker(row: Pick<WriteRequest, 'operation' | 'inte
* CEO-12, inside the publication transaction after the page write: when the
* write lowered a page's tier, file (or refresh) its `lower_page` proposal.
* `prior` is the tier and revision read under the page lock before the write.
+ * Content writes and derived page publications (#7917) file it; another writer
+ * that lowers a page on purpose names itself in `proposer`.
*/
-export async function recordAgentPageLowering(tx: BrainEngine, row: Pick<WriteRequest, 'operation' | 'source_id' | 'slug'>,
- prior: { tier: TrustTier; revision: string | null } | null): Promise<{ proposal_ref: string } | null> {
- if (!prior || !CONTENT_OPERATIONS.includes(row.operation)) return null;
+export async function recordAgentPageLowering(tx: BrainEngine, row: Pick<WriteRequest, 'operation' | 'source_id' | 'slug'> & { intent?: WriteRequest['intent'] | null },
+ prior: { tier: TrustTier; revision: string | null } | null, proposer?: string): Promise<{ proposal_ref: string } | null> {
+ const derived = !CONTENT_OPERATIONS.includes(row.operation) && declaresDerivation(row.intent);
+ if (!prior || !(proposer || CONTENT_OPERATIONS.includes(row.operation) || derived)) return null;
const snapshot = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });
const [page] = snapshot ? await tx.executeRaw<{ trust_tier: string }>('SELECT trust_tier FROM pages WHERE id = $1', [snapshot.page.id]) : [];
if (!snapshot || !page) return null;
@@ -111,7 +126,7 @@ export async function recordAgentPageLowering(tx: BrainEngine, row: Pick<WriteRe
const [version] = await tx.executeRaw<{ id: number }>(
'SELECT id FROM page_versions WHERE page_id = $1 AND trust_tier = $2 ORDER BY id DESC LIMIT 1', [pageId, prior.tier]);
const proposal = await insertTrustProposal(tx, {
- action: 'lower_page', sourceId: row.source_id, target: { table: 'pages', id: pageId }, proposer: `agent_page_edit:${row.operation}`,
+ action: 'lower_page', sourceId: row.source_id, target: { table: 'pages', id: pageId }, proposer: proposer ?? (derived ? `derived_page:${row.operation}` : `agent_page_edit:${row.operation}`),
before: { slug: row.slug, prior_tier: prior.tier, prior_revision: prior.revision, version_id: version ? Number(version.id) : null }, after,
});
if (!proposal.created) await updatePendingTrustProposalAfter(tx, proposal.id, after);
diff --git a/src/core/trust/provenance-drift.ts b/src/core/trust/provenance-drift.ts
new file mode 100644
index 0000000000..6c896f3e67
--- /dev/null
+++ b/src/core/trust/provenance-drift.ts
@@ -0,0 +1,274 @@
+/**
+ * #7891: pages whose provenance stamps (`source_kind`, `ingested_via`, `ingested_at`) a write rewrote, or whose
+ * lowering markers a write removed, before #7892 made those stamps server-owned on remote writes. Read-only; the
+ * doctor check `provenance_stamp_drift` and the explicit repair `gbrain repair provenance` both read it.
+ *
+ * Each live page's history is its `page_versions` rows in id order followed by the live row. A transition from one
+ * snapshot to the next was made by the older snapshot's `archived_write_request_id` (the live revision's own
+ * `revision_write_request_id` when the archive names none), classified by that request's `authority.remote`, or by its
+ * principal kind once receipt compaction removed the request: `remote`, `local`, or `unattributed` (no recorded writer,
+ * writes before write attribution). Only remote damage is repaired by default; unattributed damage is `ambiguous` and
+ * repaired only with `--include-ambiguous`; local changes are the owner's own edits and are reported, never repaired.
+ *
+ * - stamps_rewritten: a stamp key changed after the first snapshot, or the live stamp differs from the server-written
+ * `pages` column. The restored value is the trusted column when non-null, else the value just before the first
+ * remote (or ambiguous) change. A later local change of the same key makes the page `needs_review`.
+ * - marker_lost: a transition raised the page's lowest frontmatter cap (`frontmatterTrustCaps`), and the live page
+ * still caps above the lost cap while its stored tier is `unknown` or above it (a re-read would raise it). The repair
+ * stamps the lost cap back as the lower-only `trust_tier` marker.
+ * - marker_missing (#7918): a classified page whose stored tier is below the owner floor and whose live frontmatter
+ * caps above it, so a re-read of the page (a repository rebuild, a backfill) would raise it. The repair stamps the
+ * stored tier as the marker; the row keeps its tier.
+ *
+ * Every planned change only lowers: the marker through `stampTrustMarker`, the tier as min(stored, marker).
+ */
+import type { BrainEngine } from '../engine.ts';
+import { digest } from '../persistence/digest.ts';
+import { frontmatterTrustCaps, stampTrustMarker } from './channel.ts';
+import { OWNER_TIER_FLOOR, compareTrust, minTrust, storedTrustTier, type TrustTier } from './tier.ts';
+
+export const PROVENANCE_STAMP_KEYS = ['source_kind', 'ingested_via', 'ingested_at'] as const;
+export type ProvenanceStampKey = typeof PROVENANCE_STAMP_KEYS[number];
+export type DriftWriter = 'remote' | 'local' | 'unattributed';
+export type DriftClass = 'remote' | 'ambiguous' | 'local' | 'needs_review' | 'restamp';
+/** Pages scanned per source by the doctor check. */
+export const DRIFT_SCAN_LIMIT = 50_000;
+const BATCH = 500;
+const REMOTE_PRINCIPALS = ['oauth_client', 'legacy_token', 'local_stdio'];
+
+export interface DriftSnapshot { frontmatter: Record<string, unknown>; writer: DriftWriter; request_id: string | null }
+export interface DriftPageInput {
+ /** Oldest first; the last entry is the live row. `writer` is who wrote that snapshot (unused for the first). */
+ chain: DriftSnapshot[];
+ stored: TrustTier;
+ columns: Partial<Record<ProvenanceStampKey, string | null>>;
+}
+export interface DriftChange { key: ProvenanceStampKey | 'cap'; writer: DriftWriter; request_id: string | null; from: unknown; to: unknown }
+export interface DriftVerdict {
+ class: DriftClass;
+ /** Who made the damaging change (absent for `restamp`). */
+ writer?: DriftWriter;
+ marker_lost: boolean;
+ stamps_rewritten: boolean;
+ marker_missing: boolean;
+ changes: DriftChange[];
+ /** The restored stamps (`null` removes the key) and the marker the repair writes; absent for local and needs_review. */
+ restore?: { stamps: Partial<Record<ProvenanceStampKey, unknown>>; marker: TrustTier | null; tier: TrustTier; frontmatter: Record<string, unknown> };
+ reason?: string;
+}
+
+const lowestCap = (fm: Record<string, unknown>): TrustTier | null => {
+ const caps = frontmatterTrustCaps(fm);
+ return caps.length ? minTrust(caps[0]!, ...caps.slice(1)) : null;
+};
+/** a ranks above b, where null (no cap) ranks above every tier. */
+const capAbove = (a: TrustTier | null, b: TrustTier | null) => b !== null && (a === null || compareTrust(a, b) > 0);
+const normStamp = (key: ProvenanceStampKey, value: unknown): unknown => {
+ if (value === undefined || value === null || value === '') return null;
+ if (key === 'ingested_at') {
+ const at = new Date(value instanceof Date ? value : String(value));
+ return Number.isNaN(at.getTime()) ? String(value) : at.toISOString();
+ }
+ return typeof value === 'string' ? value : JSON.stringify(value);
+};
+
+/** The repair verdict for one page, or null when nothing drifted. Pure. */
+export function analyzePageDrift(input: DriftPageInput, opts: { includeAmbiguous?: boolean } = {}): DriftVerdict | null {
+ const { chain, stored } = input;
+ const live = chain[chain.length - 1]!.frontmatter;
+ const changes: DriftChange[] = [];
+ const restoredStamps: Partial<Record<ProvenanceStampKey, unknown>> = {};
+ let needsReview: string | undefined;
+ for (const key of PROVENANCE_STAMP_KEYS) {
+ const events: DriftChange[] = [];
+ for (let i = 1; i < chain.length; i++) {
+ const from = normStamp(key, chain[i - 1]!.frontmatter[key]);
+ const to = normStamp(key, chain[i]!.frontmatter[key]);
+ if (from !== to) events.push({ key, writer: chain[i]!.writer, request_id: chain[i]!.request_id, from: chain[i - 1]!.frontmatter[key] ?? null, to: chain[i]!.frontmatter[key] ?? null });
+ }
+ const column = normStamp(key, input.columns[key]);
+ const liveValue = normStamp(key, live[key]);
+ const firstDamage = events.findIndex(event => event.writer !== 'local');
+ const columnForged = column !== null && liveValue !== null && liveValue !== column;
+ if (firstDamage < 0 && !columnForged) { changes.push(...events.filter(event => event.writer === 'local')); continue; }
+ const before = firstDamage >= 0 ? events[firstDamage]!.from : undefined;
+ const target = column !== null ? input.columns[key]! : before ?? null;
+ if (normStamp(key, target) === liveValue) continue;
+ if (firstDamage >= 0) {
+ changes.push(...events);
+ if (events.slice(firstDamage + 1).some(event => event.writer === 'local')) needsReview = `a later local write also changed ${key}`;
+ } else changes.push({ key, writer: 'unattributed', request_id: null, from: input.columns[key] ?? null, to: live[key] ?? null });
+ restoredStamps[key] = target;
+ }
+ let lostCap: TrustTier | null = null;
+ for (let i = 1; i < chain.length; i++) {
+ const from = lowestCap(chain[i - 1]!.frontmatter);
+ const to = lowestCap(chain[i]!.frontmatter);
+ if (!capAbove(to, from)) continue;
+ changes.push({ key: 'cap', writer: chain[i]!.writer, request_id: chain[i]!.request_id, from, to });
+ if (chain[i]!.writer !== 'local' && lostCap === null) lostCap = from;
+ }
+ const damaging = changes.filter(change => change.writer !== 'local' && (change.key !== 'cap' || lostCap !== null));
+ const markerLost = lostCap !== null && capAbove(lowestCap(live), lostCap) && (stored === 'unknown' || compareTrust(stored, lostCap) > 0);
+ const stampsRewritten = Object.keys(restoredStamps).length > 0;
+ const classified = stored !== 'unknown' && compareTrust(stored, OWNER_TIER_FLOOR) < 0;
+ const markerMissing = classified && capAbove(lowestCap(live), stored);
+ if (!markerLost && !stampsRewritten) {
+ if (markerMissing) return { class: 'restamp', marker_lost: false, stamps_rewritten: false, marker_missing: true, changes, ...planRestore(live, {}, null, stored) };
+ return changes.some(change => change.writer === 'local')
+ ? { class: 'local', writer: 'local', marker_lost: false, stamps_rewritten: false, marker_missing: false, changes } : null;
+ }
+ const writer: DriftWriter = damaging.some(change => change.writer === 'remote') ? 'remote' : 'unattributed';
+ const verdict: DriftVerdict = { class: writer === 'remote' ? 'remote' : 'ambiguous', writer, marker_lost: markerLost, stamps_rewritten: stampsRewritten, marker_missing: markerMissing, changes };
+ if (needsReview) return { ...verdict, class: 'needs_review', reason: needsReview };
+ if (verdict.class === 'ambiguous' && !opts.includeAmbiguous) return verdict;
+ return { ...verdict, ...planRestore(live, restoredStamps, markerLost ? lostCap : null, stored) };
+}
+
+function planRestore(live: Record<string, unknown>, stamps: Partial<Record<ProvenanceStampKey, unknown>>, lostCap: TrustTier | null, stored: TrustTier): Pick<DriftVerdict, 'restore'> {
+ let frontmatter: Record<string, unknown> = { ...live };
+ for (const [key, value] of Object.entries(stamps)) {
+ if (value === null || value === undefined) delete frontmatter[key];
+ else frontmatter[key] = value;
+ }
+ const caps = [...frontmatterTrustCaps(frontmatter), ...frontmatterTrustCaps(live), ...(lostCap ? [lostCap] : []), ...(stored !== 'unknown' ? [stored] : [])];
+ const cap = caps.length ? minTrust(caps[0]!, ...caps.slice(1)) : null;
+ if (cap) frontmatter = stampTrustMarker(frontmatter, cap);
+ const marker = typeof frontmatter.trust_tier === 'string' ? frontmatter.trust_tier as TrustTier : null;
+ return { restore: { stamps, marker, tier: cap ? minTrust(stored, cap) : stored, frontmatter } };
+}
+
+export interface DriftCounts { remote: number; local: number; unattributed: number }
+export interface DriftItem { source_id: string; slug: string; page_id: number; revision: string; tier: TrustTier; verdict: DriftVerdict }
+export interface SourceDrift {
+ source_id: string; scanned: number; truncated: boolean; schema: 'current' | 'pre_attribution' | 'pre_trust';
+ marker_lost: DriftCounts; stamps_rewritten: DriftCounts; marker_missing: number; needs_review: number;
+ samples: Record<string, string[]>;
+ items: DriftItem[];
+}
+
+interface LiveRow {
+ id: number | string; slug: string; trust_tier: string | null; frontmatter: Record<string, unknown> | string | null; revision: string;
+ source_kind: string | null; ingested_via: string | null; ingested_at: string | Date | null; req: string | null; kind: string | null; remote: string | null;
+}
+interface VersionRow { page_id: number | string; frontmatter: Record<string, unknown> | string | null; req: string | null; kind: string | null; remote: string | null }
+
+const json = (value: Record<string, unknown> | string | null): Record<string, unknown> => typeof value === 'string' ? JSON.parse(value) as Record<string, unknown> : value ?? {};
+function writerOf(req: string | null, remote: string | null, kind: string | null): DriftWriter {
+ if (remote === 'true') return 'remote';
+ if (remote === 'false') return 'local';
+ if (!kind) return 'unattributed';
+ return REMOTE_PRINCIPALS.includes(kind) ? 'remote' : 'local';
+}
+
+async function columnsOf(engine: BrainEngine, table: string): Promise<Set<string>> {
+ const rows = await engine.executeRaw<{ column_name: string }>(
+ "SELECT column_name FROM information_schema.columns WHERE table_name = $1 AND table_schema = ANY(current_schemas(false))", [table]);
+ return new Set(rows.map(row => row.column_name));
+}
+
+/** Whether this brain has the columns the scan reads: trust tiers, then write attribution. */
+export async function driftSchema(engine: BrainEngine): Promise<SourceDrift['schema']> {
+ const pages = await columnsOf(engine, 'pages');
+ if (!pages.has('trust_tier')) return 'pre_trust';
+ const versions = await columnsOf(engine, 'page_versions');
+ return pages.has('revision_write_request_id') && versions.has('archived_write_request_id') ? 'current' : 'pre_attribution';
+}
+
+/** Reads one page's history the way the scan does; null when the page is gone. */
+export async function readPageDrift(engine: BrainEngine, sourceId: string, slug: string, opts: { includeAmbiguous?: boolean } = {}): Promise<DriftItem | null> {
+ const schema = await driftSchema(engine);
+ if (schema === 'pre_trust') return null;
+ const [row] = await liveRows(engine, schema, sourceId, { slug });
+ if (!row) return null;
+ const versions = await versionRows(engine, schema, [Number(row.id)]);
+ return itemOf(sourceId, row, versions, opts);
+}
+
+function liveRows(engine: BrainEngine, schema: SourceDrift['schema'], sourceId: string, at: { after?: number; slug?: string }): Promise<LiveRow[]> {
+ const attributed = schema === 'current';
+ return engine.executeRaw<LiveRow>(
+ `SELECT p.id, p.slug, p.trust_tier, p.frontmatter, p.knowledge_revision::text AS revision, p.source_kind, p.ingested_via, p.ingested_at,
+ ${attributed ? "p.revision_write_request_id::text AS req, p.revision_principal_kind AS kind, r.authority->>'remote' AS remote"
+ : 'NULL::text AS req, NULL::text AS kind, NULL::text AS remote'}
+ FROM pages p ${attributed ? 'LEFT JOIN persistence_requests r ON r.id = p.revision_write_request_id' : ''}
+ WHERE p.source_id = $1 AND p.deleted_at IS NULL AND ${at.slug !== undefined ? 'p.slug = $2' : 'p.id > $2'}
+ ORDER BY p.id LIMIT ${BATCH}`, [sourceId, at.slug ?? at.after ?? 0]);
+}
+
+function versionRows(engine: BrainEngine, schema: SourceDrift['schema'], pageIds: number[]): Promise<VersionRow[]> {
+ const attributed = schema === 'current';
+ return engine.executeRaw<VersionRow>(
+ `SELECT v.page_id, v.frontmatter,
+ ${attributed ? "v.archived_write_request_id::text AS req, v.archived_principal_kind AS kind, r.authority->>'remote' AS remote"
+ : 'NULL::text AS req, NULL::text AS kind, NULL::text AS remote'}
+ FROM page_versions v ${attributed ? 'LEFT JOIN persistence_requests r ON r.id = v.archived_write_request_id' : ''}
+ WHERE v.page_id = ANY($1::int[]) ORDER BY v.page_id, v.id`, [pageIds]);
+}
+
+function itemOf(sourceId: string, row: LiveRow, versions: VersionRow[], opts: { includeAmbiguous?: boolean }): DriftItem | null {
+ const chain: DriftSnapshot[] = versions.map((version, index) => {
+ const previous = versions[index - 1];
+ return { frontmatter: json(version.frontmatter), writer: previous ? writerOf(previous.req, previous.remote, previous.kind) : 'unattributed', request_id: previous?.req ?? null };
+ });
+ const last = versions[versions.length - 1];
+ const liveWriter = last && (last.req || last.kind) ? { writer: writerOf(last.req, last.remote, last.kind), request_id: last.req } : { writer: writerOf(row.req, row.remote, row.kind), request_id: row.req };
+ chain.push({ frontmatter: json(row.frontmatter), ...liveWriter });
+ const ingestedAt = row.ingested_at instanceof Date ? row.ingested_at.toISOString() : row.ingested_at;
+ const verdict = analyzePageDrift({ chain, stored: storedTrustTier(row.trust_tier),
+ columns: { source_kind: row.source_kind, ingested_via: row.ingested_via, ingested_at: ingestedAt } }, opts);
+ return verdict ? { source_id: sourceId, slug: row.slug, page_id: Number(row.id), revision: row.revision, tier: storedTrustTier(row.trust_tier), verdict } : null;
+}
+
+/** One source's drift, bounded to `limit` live pages in id order (`truncated` when more remain). Read-only. */
+export async function scanProvenanceDrift(engine: BrainEngine, sourceId: string, opts: { limit?: number; sampleSize?: number; includeAmbiguous?: boolean; slugs?: string[] } = {}): Promise<SourceDrift> {
+ const empty = (): DriftCounts => ({ remote: 0, local: 0, unattributed: 0 });
+ const schema = await driftSchema(engine);
+ const result: SourceDrift = { source_id: sourceId, scanned: 0, truncated: false, schema, marker_lost: empty(), stamps_rewritten: empty(), marker_missing: 0, needs_review: 0, samples: {}, items: [] };
+ if (schema === 'pre_trust') return result;
+ const limit = opts.limit ?? DRIFT_SCAN_LIMIT;
+ const sampleSize = opts.sampleSize ?? 20;
+ const sample = (bucket: string, slug: string) => { const list = result.samples[bucket] ??= []; if (list.length < sampleSize) list.push(slug); };
+ const record = (item: DriftItem) => {
+ const { verdict } = item;
+ result.items.push(item);
+ if (verdict.marker_missing) { result.marker_missing++; sample('marker_missing', item.slug); }
+ if (verdict.class === 'needs_review') { result.needs_review++; sample('needs_review', item.slug); }
+ const writer = verdict.writer;
+ if (!writer) return;
+ if (verdict.marker_lost) { result.marker_lost[writer]++; sample(`marker_lost.${writer}`, item.slug); }
+ if (verdict.stamps_rewritten) { result.stamps_rewritten[writer]++; sample(`stamps_rewritten.${writer}`, item.slug); }
+ if (verdict.class !== 'local') return;
+ if (verdict.changes.some(change => change.key === 'cap')) result.marker_lost.local++;
+ if (verdict.changes.some(change => change.key !== 'cap')) result.stamps_rewritten.local++;
+ sample('local', item.slug);
+ };
+ if (opts.slugs?.length) {
+ for (const slug of [...new Set(opts.slugs)].sort()) {
+ const item = await readPageDrift(engine, sourceId, slug, opts);
+ result.scanned++;
+ if (item) record(item);
+ }
+ return result;
+ }
+ for (let after = 0; ;) {
+ const rows = await liveRows(engine, schema, sourceId, { after });
+ if (!rows.length) return result;
+ const take = rows.slice(0, Math.max(0, limit - result.scanned));
+ const versions = await versionRows(engine, schema, take.map(row => Number(row.id)));
+ const byPage = new Map<number, VersionRow[]>();
+ for (const version of versions) { const list = byPage.get(Number(version.page_id)) ?? []; list.push(version); byPage.set(Number(version.page_id), list); }
+ for (const row of take) {
+ result.scanned++;
+ const item = itemOf(sourceId, row, byPage.get(Number(row.id)) ?? [], opts);
+ if (item) record(item);
+ }
+ if (take.length < rows.length || result.scanned >= limit) { result.truncated = take.length < rows.length || rows.length === BATCH; return result; }
+ if (rows.length < BATCH) return result;
+ after = Number(rows[rows.length - 1]!.id);
+ }
+}
+
+/** The digest of the change an item plans, for the preview hash and the write's re-check. */
+export const plannedDigest = (item: Pick<DriftItem, 'page_id' | 'revision' | 'verdict'>) =>
+ digest(['provenance-v1', item.page_id, item.revision, item.verdict.class, item.verdict.restore?.frontmatter ?? null, item.verdict.restore?.tier ?? null]);
diff --git a/src/core/trust/taint.ts b/src/core/trust/taint.ts
index 0f0abcc85f..218a156ce7 100644
--- a/src/core/trust/taint.ts
+++ b/src/core/trust/taint.ts
@@ -133,8 +133,11 @@ export async function lowerToDerivedTier(tx: Sql, table: TaintTable, ids: readon
return lowered;
}
-/** A row a derivation wrote, for the lowering and edge pass. */
-export interface DerivedRowRef { table: TaintTable; id: number; sourceId?: string | null }
+/**
+ * A row a derivation wrote, for the lowering and edge pass. `prior` (#7917): an existing page's slug and the tier and
+ * revision read before the write, so a page the derivation lowered files a `lower_page` proposal for the owner.
+ */
+export interface DerivedRowRef { table: TaintTable; id: number; sourceId?: string | null; prior?: { slug: string; tier: TrustTier; revision: string | null } }
/**
* An unmanaged deriver's write: one attributed maintenance transaction at the
@@ -148,6 +151,10 @@ export async function derivedMaintenanceTransaction<T>(engine: BrainEngine, deri
for (const row of rows) {
await lowerToDerivedTier(tx, row.table, [row.id], derivation.trust);
await recordTaintEdges(tx, row, derivation.inputs);
+ if (row.table !== 'pages' || !row.prior || !row.sourceId) continue;
+ const { recordAgentPageLowering } = await import('./page-write.ts');
+ await recordAgentPageLowering(tx, { operation: 'derived_maintenance', source_id: row.sourceId, slug: row.prior.slug }, row.prior,
+ `derived_page:${String(derivation.trust.origin?.channel ?? 'maintenance')}`);
}
return result;
}, derivation.trust);
diff --git a/test/maintenance-lowering-7917-7918.test.ts b/test/maintenance-lowering-7917-7918.test.ts
new file mode 100644
index 0000000000..bddb93a6c8
--- /dev/null
+++ b/test/maintenance-lowering-7917-7918.test.ts
@@ -0,0 +1,131 @@
+/**
+ * #7917 / #7918 part 2: a maintenance publication that lowers a page files a `lower_page` proposal, and a derivation
+ * declaration that is present but unreadable fails closed at `unknown`.
+ *
+ * 1. Protects: a declared maintenance write over a page the owner wrote (a patterns grounding repair outside the output
+ * prefix) lowers the page and files one pending `lower_page` proposal the owner sees in `gbrain trust review`, on a
+ * managed repository brain (the coordinator's maintenance publication) and on a repo-less brain (the unmanaged
+ * derived transaction). A maintenance write whose declaration is present but malformed publishes at `unknown`, the
+ * committed file carries the `unknown` marker, and the marker rule stamps it; it never falls back to the request's
+ * channel or the source default.
+ * 2. Fails when: a maintenance lowering files no proposal, or an unreadable declaration rates the write by its channel.
+ * 3. Runs on PGLite, and on Postgres when DATABASE_URL is set; repository-backed (managed) and repo-less brains. No
+ * embedding, no model calls.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { parseMarkdown } from '../src/core/markdown.ts';
+import { operationsByName } from '../src/core/operations.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { withTrustPromotion } from '../src/core/persistence/context.ts';
+import { maintenancePreflight, publishMaintenancePages } from '../src/core/persistence/prepared-maintenance.ts';
+import { stampPageTrustMarker } from '../src/core/trust/page-write.ts';
+import { declareDerivation, derivedMaintenanceTransaction } from '../src/core/trust/taint.ts';
+import { compareTrust, storedTrustTier } from '../src/core/trust/tier.ts';
+import { managedBrain, settleManagedGitEffects } from './helpers/managed-brain.ts';
+import { withManagedFixtureWrite } from './helpers/managed-e2e-fixture-write.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+
+const OWNER_PAGE = '---\ntitle: Acme Example\ntype: company\n---\nOwner notes.\n';
+const GROUNDED = '---\ntitle: Acme Example\ntype: company\n---\nOwner notes.\n\nA grounded line a derivation wrote.\n';
+const derivation = declareDerivation({ tier: 'agent_written', origin: { channel: 'derive:patterns' } }, []);
+const UNREADABLE = { tier: 'agent_written', origin: { channel: 'derive:patterns' }, inputs: [{ table: 'not_a_table', id: 1 }] };
+
+const tierOf = async (engine: BrainEngine, slug: string) => storedTrustTier(
+ (await engine.executeRaw<{ trust_tier: string }>('SELECT trust_tier FROM pages WHERE source_id = $1 AND slug = $2', ['default', slug]))[0]?.trust_tier);
+/** The owner's confirmation of a page (the fixture stands in for gbrain trust confirm). */
+const confirmTier = (engine: BrainEngine, slug: string, managed: boolean) => {
+ const raise = (tx: BrainEngine) => withTrustPromotion(tx, 'user_confirmed', () =>
+ tx.executeRaw("UPDATE pages SET trust_tier = 'operator_curated' WHERE source_id = 'default' AND slug = $1", [slug]));
+ return managed ? withManagedFixtureWrite(engine, ['default'], raise) : engine.transaction(raise);
+};
+const proposalsOf = (engine: BrainEngine, slug: string) => engine.executeRaw<{ action: string; proposer: string; status: string }>(
+ `SELECT tp.action, tp.proposer, tp.status FROM trust_proposals tp JOIN pages p ON tp.target_table = 'pages' AND tp.target_id = p.id
+ WHERE p.source_id = 'default' AND p.slug = $1 ORDER BY tp.id`, [slug]);
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+
+ describe(`[${backend}] #7917 #7918 managed maintenance publications (repository brain)`, () => {
+ const seedOwnerPage = async (ctx: Parameters<Parameters<typeof managedBrain>[0]>[0]['ctx'], slug: string) => {
+ await operationsByName.put_page.handler(ctx, { slug, content: OWNER_PAGE });
+ await settleManagedGitEffects(ctx.engine);
+ await confirmTier(ctx.engine, slug, true);
+ return (await ctx.engine.readPageSnapshot(slug, { sourceId: 'default' }))!;
+ };
+
+ test('a declared maintenance write that lowers an owner page files one pending lower_page proposal', () => managedBrain(async ({ engine, ctx }) => {
+ const slug = 'companies/acme-example';
+ const before = await seedOwnerPage(ctx, slug);
+ const prior = await tierOf(engine, slug);
+ expect(compareTrust(prior, 'agent_written')).toBeGreaterThan(0);
+ const authority = (await maintenancePreflight(engine, 'default'))!;
+ const [outcome] = await publishMaintenancePages(engine, authority, [{ slug, content: GROUNDED, expectedRevision: before.revision, derivation }]);
+ expect(outcome).not.toHaveProperty('error');
+ await settleManagedGitEffects(engine);
+ expect(await tierOf(engine, slug)).toBe('agent_written');
+ const proposals = await proposalsOf(engine, slug);
+ expect(proposals).toHaveLength(1);
+ expect(proposals[0]).toMatchObject({ action: 'lower_page', status: 'pending' });
+ expect(proposals[0]!.proposer).toStartWith('derived_page:');
+ }, { databaseUrl }), 120_000);
+
+ test('a present but unreadable declaration publishes at unknown and the file carries the unknown marker', () => managedBrain(async ({ engine, ctx, root }) => {
+ const slug = 'companies/acme-unreadable';
+ const before = await seedOwnerPage(ctx, slug);
+ const authority = (await maintenancePreflight(engine, 'default'))!;
+ const [outcome] = await publishMaintenancePages(engine, authority, [{ slug, content: GROUNDED, expectedRevision: before.revision, derivation: UNREADABLE as never }]);
+ expect(outcome).not.toHaveProperty('error');
+ await settleManagedGitEffects(engine);
+ expect(await tierOf(engine, slug)).toBe('unknown');
+ expect(parseMarkdown(readFileSync(join(root, `${slug}.md`), 'utf8'), slug).frontmatter.trust_tier).toBe('unknown');
+ expect((await proposalsOf(engine, slug)).map(p => p.action)).toEqual(['lower_page']);
+ }, { databaseUrl }), 120_000);
+ });
+
+ describe(`[${backend}] #7917 unmanaged derived transactions (repo-less brain)`, () => {
+ let pglite: PGLiteEngine;
+ let engine: BrainEngine;
+ let close: () => Promise<void> = async () => {};
+ beforeAll(async () => {
+ if (backend === 'pglite') { pglite = new PGLiteEngine(); await pglite.connect({}); await pglite.initSchema(); }
+ }, 120_000);
+ afterAll(async () => { if (backend === 'pglite') await pglite.disconnect(); else await close(); });
+ beforeEach(async () => {
+ if (backend === 'pglite') { await resetPgliteState(pglite); engine = pglite; }
+ else { await close(); ({ engine, close } = await isolatedPersistencePostgres(databaseUrl!)); }
+ }, 120_000);
+
+ test('a derived rewrite of an owner page lowers it and files one pending lower_page proposal', async () => {
+ const slug = 'companies/acme-repo-less';
+ await importFromContent(engine, slug, OWNER_PAGE, { sourceId: 'default', noEmbed: true });
+ await confirmTier(engine, slug, false);
+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;
+ const trust = { tier: 'agent_written' as const, origin: { channel: 'derive:patterns' } };
+ await derivedMaintenanceTransaction(engine, { trust, inputs: [] }, async tx => {
+ await importFromContent(tx, slug, GROUNDED, { sourceId: 'default', noEmbed: true, preserveGateMarkers: true });
+ return { result: undefined, rows: [{ table: 'pages' as const, id: Number(snapshot.page.id), sourceId: 'default',
+ prior: { slug, tier: 'operator_curated' as const, revision: snapshot.revision } }] };
+ });
+ expect(await tierOf(engine, slug)).toBe('agent_written');
+ const proposals = await proposalsOf(engine, slug);
+ expect(proposals).toHaveLength(1);
+ expect(proposals[0]).toMatchObject({ action: 'lower_page', status: 'pending', proposer: 'derived_page:derive:patterns' });
+ }, 120_000);
+ });
+}
+
+// Value: protects=the marker rule fails closed on an unreadable declaration; fails_when=the guard reads only well-formed declarations again; why_new=the managed case above covers the file, this pins the rule's own tier; seam=none; no_claim=none beyond protects
+describe('#7918 stampPageTrustMarker: an unreadable derivation declaration still stamps', () => {
+ test('a maintenance write carrying a malformed declaration stamps the write tier', () => {
+ const fm: Record<string, unknown> = {};
+ stampPageTrustMarker({ operation: 'submit_job', intent: { kind: 'managed_maintenance_page', derivation: UNREADABLE } } as never, fm,
+ { tier: 'unknown', origin: { channel: 'derivation_unreadable' } }, 'operator_curated');
+ expect(fm.trust_tier).toBe('unknown');
+ });
+});
diff --git a/test/provenance-drift-7891.test.ts b/test/provenance-drift-7891.test.ts
new file mode 100644
index 0000000000..6815e46580
--- /dev/null
+++ b/test/provenance-drift-7891.test.ts
@@ -0,0 +1,285 @@
+/**
+ * #7891 / #7918 part 1: doctor `provenance_stamp_drift` and `gbrain repair provenance`.
+ *
+ * 1. Protects: a page whose provenance stamps and lowering marker a remote write removed before #7892 is reported
+ * read-only by doctor; the repair previews it without writing anything, and `--apply --expect <hash> --yes` puts the
+ * stamps back, stamps the lost cap as the `trust_tier` marker (file and database on a repository brain, the database
+ * on a repo-less brain), lowers the page to it and files a `lower_page` proposal; a rerun previews nothing. The
+ * owner's own edit is listed and never written; an unattributed one only with `--include-ambiguous`. A classified
+ * page whose file would re-read above its stored tier gets that tier as its marker, and its row keeps its tier. Apply
+ * refuses without a preview hash and when the page moved after the preview.
+ * 2. Fails when: the repair writes during a preview, raises any tier, writes the owner's own edit, applies a plan the
+ * preview did not show, or the doctor check misses or miscounts the damage.
+ * 3. Runs on PGLite, and on Postgres when DATABASE_URL is set; a classic repository checkout, a repo-less brain, and a
+ * managed repository brain (the coordinator's owner page write and its Git effect). No embedding, no model calls.
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { parseMarkdown, serializePageToMarkdown } from '../src/core/markdown.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetGateway } from '../src/core/ai/gateway.ts';
+import { withTrustPromotion, withWriteAttribution } from '../src/core/persistence/context.ts';
+import type { WriteAttribution } from '../src/core/persistence/attribution.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { resolveRepairScope } from '../src/core/repair/core.ts';
+import { AUTO_REPAIR_REGISTRY, repairRunner } from '../src/core/repair/registry.ts';
+import { analyzePageDrift } from '../src/core/trust/provenance-drift.ts';
+import { provenanceStampDriftEntry } from '../src/commands/doctor/checks/provenance-stamp-drift.ts';
+import type { DoctorContext } from '../src/commands/doctor/context.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { managedBrain, settleManagedGitEffects } from './helpers/managed-brain.ts';
+import { operationsByName } from '../src/core/operations.ts';
+import { withManagedFixtureWrite } from './helpers/managed-e2e-fixture-write.ts';
+
+const STORED = { source_kind: 'webhook', ingested_via: 'webhook', ingested_at: '2026-01-02T03:04:05.000Z' };
+const stampsOf = (fm: Record<string, unknown>) => ({ source_kind: fm.source_kind, ingested_via: fm.ingested_via, ingested_at: fm.ingested_at });
+const logger = { info() {}, warn() {}, error() {} };
+type Writer = 'oauth_client' | 'local_cli' | null;
+
+for (const kind of testBackends()) {
+ for (const repo of [true, false]) {
+ describe(`#7891 provenance drift (${kind}, ${repo ? 'repository' : 'repo-less'} brain)`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ let tmpRoot: string;
+ let brainDir: string;
+
+ beforeAll(async () => {
+ if (kind === 'pglite') { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }
+ }, 120_000);
+ afterAll(async () => { if (kind === 'pglite') { await disposePersistenceConsumer(engine); await engine.disconnect(); } resetGateway(); });
+ beforeEach(async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { await disposePersistenceConsumer(engine); await resetPgliteState(engine as PGLiteEngine); }
+ resetGateway();
+ tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'gbrain-7891-'));
+ brainDir = path.join(tmpRoot, 'brain');
+ fs.mkdirSync(brainDir, { recursive: true });
+ if (repo) await engine.setConfig('sync.repo_path', brainDir);
+ else await engine.executeRaw("DELETE FROM config WHERE key = 'sync.repo_path'");
+ }, 120_000);
+ afterEach(async () => {
+ await disposePersistenceConsumer(engine);
+ if (kind === 'postgres') await close();
+ fs.rmSync(tmpRoot, { recursive: true, force: true });
+ });
+
+ const inHome = <T>(run: () => Promise<T>) => withEnv({ GBRAIN_HOME: path.join(tmpRoot, 'home') }, run);
+ const page = async (slug: string) => (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;
+ const fileOf = (slug: string) => path.join(brainDir, `${slug}.md`);
+ const writeFile = async (slug: string) => {
+ if (!repo) return;
+ const snapshot = await page(slug);
+ fs.mkdirSync(path.dirname(fileOf(slug)), { recursive: true });
+ fs.writeFileSync(fileOf(slug), serializePageToMarkdown(snapshot.page, snapshot.tags));
+ };
+ const tierOf = async (slug: string) => (await engine.executeRaw<{ trust_tier: string }>(
+ 'SELECT trust_tier FROM pages WHERE source_id = $1 AND slug = $2', ['default', slug]))[0]!.trust_tier;
+ const proposals = (slug: string) => engine.executeRaw<{ action: string; proposer: string; status: string }>(
+ `SELECT tp.action, tp.proposer, tp.status FROM trust_proposals tp JOIN pages p ON tp.target_table = 'pages' AND tp.target_id = p.id
+ WHERE p.source_id = 'default' AND p.slug = $1 ORDER BY tp.id`, [slug]);
+ const fixtureWrite = (attribution: WriteAttribution | null, write: (tx: BrainEngine) => Promise<void>) => engine.transaction(tx =>
+ attribution ? withWriteAttribution(tx, attribution, () => write(tx)) : write(tx));
+ /** A page as an ingestion capture left it: stamped external, at `tier`. */
+ const seed = async (slug: string, frontmatter: Record<string, unknown>, tier = 'unknown') => {
+ await fixtureWrite(null, async tx => {
+ await tx.putPage(slug, { type: 'note', title: 'Seeded', compiled_truth: 'Captured body', timeline: '', frontmatter,
+ source_kind: 'webhook', ingested_via: 'webhook' } as never);
+ await withTrustPromotion(tx, 'user_confirmed', () =>
+ tx.executeRaw('UPDATE pages SET trust_tier = $1, ingested_at = $4::timestamptz WHERE source_id = $2 AND slug = $3', [tier, 'default', slug, STORED.ingested_at]));
+ });
+ await writeFile(slug);
+ };
+ /** A write as one landed before #7892: it replaced the frontmatter, made by `writer` (null: no recorded writer). */
+ const rewrite = async (slug: string, frontmatter: Record<string, unknown>, writer: Writer) => {
+ const attribution = writer ? { requestId: randomUUID(), principal: { kind: writer, id: 'client-example' } } as WriteAttribution : null;
+ await fixtureWrite(attribution, async tx => {
+ await tx.createVersion(slug, { sourceId: 'default' });
+ await tx.putPage(slug, { type: 'note', title: 'Seeded', compiled_truth: 'Captured body, edited', timeline: '', frontmatter,
+ source_kind: 'webhook', ingested_via: 'webhook' } as never);
+ await tx.executeRaw('UPDATE pages SET ingested_at = $3::timestamptz WHERE source_id = $1 AND slug = $2', ['default', slug, STORED.ingested_at]);
+ });
+ await writeFile(slug);
+ };
+ const doctor = async () => (await provenanceStampDriftEntry.run({ engine, args: [], sourceIds: ['default'] } as unknown as DoctorContext) as Array<Record<string, any>>)[0]!;
+ const run = (apply: boolean, opts: Record<string, unknown> = {}) => inHome(async () =>
+ (await repairRunner(engine, { apply, logger })).run('provenance', await resolveRepairScope(engine, 'default'), { explicit: true, sourceFlag: 'default', ...opts }) as Promise<Record<string, any>>);
+ const refusal = async (go: () => Promise<unknown>): Promise<OperationError> => {
+ try { await go(); } catch (error) { if (error instanceof OperationError) return error; throw error; }
+ throw new Error('expected a refusal');
+ };
+
+ test('doctor and the preview report a remote write that dropped the stamps and the marker; nothing is written', async () => {
+ const slug = 'inbox/remote-drop';
+ await seed(slug, STORED);
+ await rewrite(slug, {}, 'oauth_client');
+ const check = await doctor();
+ expect(check.status).toBe('warn');
+ expect(check.details.sources[0]).toMatchObject({ source_id: 'default', marker_lost: { remote: 1 }, stamps_rewritten: { remote: 1 }, pages: 1 });
+ expect(check.fix.argv).toEqual(['gbrain', 'repair', 'provenance', '--source', 'default', '--json']);
+ expect(AUTO_REPAIR_REGISTRY.map(spec => spec.kind)).not.toContain('provenance');
+
+ const before = { revision: (await page(slug)).revision, tier: await tierOf(slug), file: repo ? fs.readFileSync(fileOf(slug), 'utf8') : null };
+ const dry = await run(false);
+ expect(dry.affected).toBe(1);
+ expect(dry.listing.map((entry: Record<string, string>) => [entry.class, entry.item.split(' ')[0]])).toEqual([['remote', `default:${slug}`]]);
+ expect(dry.listing[0].detail).toContain('ingested_via (none) -> webhook');
+ expect(dry.apply_command).toBe(`gbrain repair provenance --source default --apply --expect ${dry.preview_hash} --yes`);
+ expect({ revision: (await page(slug)).revision, tier: await tierOf(slug), file: repo ? fs.readFileSync(fileOf(slug), 'utf8') : null }).toEqual(before);
+ expect(await proposals(slug)).toEqual([]);
+ }, 120_000);
+
+ test('apply restores the stamps and the marker, lowers the page, files a lower_page proposal; a rerun previews nothing', async () => {
+ const slug = 'inbox/remote-restore';
+ await seed(slug, STORED);
+ await rewrite(slug, {}, 'oauth_client');
+ const dry = await run(false);
+ await run(true, { expect: dry.preview_hash });
+ const after = await page(slug);
+ expect(stampsOf(after.page.frontmatter)).toEqual(STORED);
+ expect(after.page.frontmatter.trust_tier).toBe('external_untrusted');
+ expect(after.page.compiled_truth).toContain('Captured body, edited');
+ expect(await tierOf(slug)).toBe('external_untrusted');
+ expect(await proposals(slug)).toEqual([{ action: 'lower_page', proposer: 'provenance_repair', status: 'pending' }]);
+ if (repo) {
+ const file = parseMarkdown(fs.readFileSync(fileOf(slug), 'utf8'), slug).frontmatter;
+ expect(stampsOf(file)).toEqual(STORED);
+ expect(file.trust_tier).toBe('external_untrusted');
+ }
+ expect((await run(false)).affected).toBe(0);
+ expect((await doctor()).status).toBe('ok');
+ }, 120_000);
+
+ test('apply refuses without a preview hash and when the page moved after the preview', async () => {
+ const slug = 'inbox/remote-moved';
+ await seed(slug, STORED);
+ await rewrite(slug, {}, 'oauth_client');
+ expect((await refusal(() => run(true))).code).toBe('invalid_params');
+ const dry = await run(false);
+ await rewrite(slug, { source_kind: 'put_page' }, 'oauth_client');
+ expect((await refusal(() => run(true, { expect: dry.preview_hash }))).code).toBe('preview_changed');
+ expect(await proposals(slug)).toEqual([]);
+ }, 120_000);
+
+ test('the owner\'s own edit is listed and never written', async () => {
+ const slug = 'inbox/local-drop';
+ await seed(slug, STORED);
+ await rewrite(slug, {}, 'local_cli');
+ expect((await doctor()).status).toBe('ok');
+ const dry = await run(false);
+ expect(dry.affected).toBe(0);
+ expect(dry.listing.map((entry: Record<string, string>) => entry.class)).toEqual(['local']);
+ }, 120_000);
+
+ test('an unattributed write is listed ambiguous and planned only with --include-ambiguous', async () => {
+ const slug = 'inbox/unattributed-drop';
+ await seed(slug, STORED);
+ await rewrite(slug, {}, null);
+ expect((await doctor()).status).toBe('warn');
+ const plain = await run(false);
+ expect(plain.affected).toBe(0);
+ expect(plain.listing.map((entry: Record<string, string>) => entry.class)).toEqual(['ambiguous']);
+ const wide = await run(false, { includeAmbiguous: true });
+ expect(wide.affected).toBe(1);
+ expect(wide.preview_hash).not.toBe(plain.preview_hash);
+ await run(true, { expect: wide.preview_hash, includeAmbiguous: true });
+ expect(stampsOf((await page(slug)).page.frontmatter)).toEqual(STORED);
+ expect(await tierOf(slug)).toBe('external_untrusted');
+ }, 120_000);
+
+ test('#7918: a classified page whose file would re-read higher gets its stored tier as the marker; the row keeps its tier', async () => {
+ const slug = 'inbox/derived-unmarked';
+ await seed(slug, {}, 'agent_written');
+ expect((await page(slug)).page.frontmatter.trust_tier).toBeUndefined();
+ const check = await doctor();
+ expect(check.status).toBe('warn');
+ expect(check.details.sources[0].marker_missing).toBe(1);
+ const dry = await run(false);
+ expect(dry.listing.map((entry: Record<string, string>) => entry.class)).toEqual(['restamp']);
+ await run(true, { expect: dry.preview_hash });
+ expect((await page(slug)).page.frontmatter.trust_tier).toBe('agent_written');
+ if (repo) expect(parseMarkdown(fs.readFileSync(fileOf(slug), 'utf8'), slug).frontmatter.trust_tier).toBe('agent_written');
+ expect(await tierOf(slug)).toBe('agent_written');
+ expect((await run(false)).affected).toBe(0);
+ }, 120_000);
+ });
+ }
+}
+
+for (const kind of testBackends()) {
+ const databaseUrl = kind === 'postgres' ? requirePostgresTestDatabase() : undefined;
+ describe(`#7891 provenance drift (${kind}, managed repository brain)`, () => {
+ test('apply publishes the restore through the coordinator: the file and the row carry the restored stamps and marker', () => managedBrain(async ({ engine, ctx, root }) => {
+ const slug = 'inbox/managed-restore';
+ await operationsByName.put_page.handler(ctx, { slug, content: '---\ntitle: Seeded\ntype: note\n---\nCaptured body\n' });
+ await settleManagedGitEffects(engine);
+ const seeded = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;
+ await operationsByName.put_page.handler(ctx, { slug, content: '---\ntitle: Seeded\ntype: note\n---\nCaptured body, edited\n', expected_revision: seeded.revision });
+ await settleManagedGitEffects(engine);
+ // The history a pre-#7892 remote write left (managed writes now server-own the stamps, so the fixture writes it):
+ // the archived version carries the capture's stamps and names a remote principal; the live row and file carry none.
+ await withManagedFixtureWrite(engine, ['default'], async tx => {
+ await tx.executeRaw(`UPDATE page_versions SET frontmatter = $2::jsonb, archived_write_request_id = NULL, archived_principal_kind = 'oauth_client'
+ WHERE id = (SELECT max(v.id) FROM page_versions v JOIN pages p ON p.id = v.page_id WHERE p.source_id = 'default' AND p.slug = $1)`, [slug, JSON.stringify(STORED)]);
+ await tx.executeRaw(`UPDATE pages SET frontmatter = '{}'::jsonb, source_kind = 'webhook', ingested_via = 'webhook', ingested_at = $2::timestamptz
+ WHERE source_id = 'default' AND slug = $1`, [slug, STORED.ingested_at]);
+ });
+ const live = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;
+ fs.writeFileSync(path.join(root, `${slug}.md`), serializePageToMarkdown(live.page, live.tags));
+ const repair = (apply: boolean, expect?: string) => (async () => (await repairRunner(engine, { apply, logger }))
+ .run('provenance', await resolveRepairScope(engine, 'default'), { explicit: true, sourceFlag: 'default', ...(expect ? { expect } : {}) }))() as Promise<Record<string, any>>;
+ const dry = await repair(false);
+ expect(dry.listing.map((entry: Record<string, string>) => entry.class)).toEqual(['remote']);
+ const fileBefore = fs.readFileSync(path.join(root, `${slug}.md`), 'utf8');
+ expect(fs.readFileSync(path.join(root, `${slug}.md`), 'utf8')).toBe(fileBefore);
+ await repair(true, dry.preview_hash);
+ await settleManagedGitEffects(engine);
+ const row = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!.page.frontmatter;
+ const file = parseMarkdown(fs.readFileSync(path.join(root, `${slug}.md`), 'utf8'), slug).frontmatter;
+ expect(stampsOf(row)).toEqual(STORED);
+ expect(stampsOf(file)).toEqual(STORED);
+ expect(row.trust_tier).toBe('external_untrusted');
+ expect(file.trust_tier).toBe('external_untrusted');
+ expect((await engine.executeRaw<{ trust_tier: string }>('SELECT trust_tier FROM pages WHERE source_id = $1 AND slug = $2', ['default', slug]))[0]!.trust_tier).toBe('external_untrusted');
+ expect((await repair(false)).affected).toBe(0);
+ }, { databaseUrl }), 120_000);
+ });
+}
+
+// Value: protects=the verdict rules (restore target, later local edits, lower-only planning); fails_when=a rule raises a tier or restores over an owner edit; why_new=the engine cases above seed one shape each; seam=none; no_claim=SQL reads (covered above)
+describe('#7891 analyzePageDrift', () => {
+ const snap = (frontmatter: Record<string, unknown>, writer: 'remote' | 'local' | 'unattributed' = 'local') => ({ frontmatter, writer, request_id: null });
+ const columns = { source_kind: null, ingested_via: null, ingested_at: null };
+
+ test('a stamp a remote write removed is restored from the snapshot before it, and the page is lowered to its cap', () => {
+ const verdict = analyzePageDrift({ chain: [snap({ ingested_via: 'webhook' }), snap({}, 'remote')], stored: 'unknown', columns })!;
+ expect(verdict).toMatchObject({ class: 'remote', marker_lost: true, stamps_rewritten: true });
+ expect(verdict.restore).toMatchObject({ stamps: { ingested_via: 'webhook' }, marker: 'external_untrusted', tier: 'external_untrusted' });
+ });
+ test('a later local edit of the same stamp makes the page needs_review, with no planned write', () => {
+ const verdict = analyzePageDrift({ chain: [snap({ ingested_via: 'webhook' }), snap({}, 'remote'), snap({ ingested_via: 'manual' }, 'local')], stored: 'unknown', columns })!;
+ expect(verdict.class).toBe('needs_review');
+ expect(verdict.restore).toBeUndefined();
+ });
+ test('the trusted column wins over the history, and the plan never lifts a cap the live page has', () => {
+ const verdict = analyzePageDrift({ chain: [snap({ source_kind: 'webhook' }), snap({ source_kind: 'put_page' }, 'remote')], stored: 'agent_written',
+ columns: { ...columns, source_kind: 'email' } })!;
+ expect(verdict.restore!.stamps).toEqual({ source_kind: 'email' });
+ expect(verdict.restore!.tier).toBe('external_untrusted');
+ });
+ test('a remote write that only lowered a stamp keeps the live cap', () => {
+ const verdict = analyzePageDrift({ chain: [snap({ source_kind: 'manual' }), snap({ source_kind: 'webhook' }, 'remote')], stored: 'unknown', columns })!;
+ expect(verdict.restore!.frontmatter.trust_tier).toBe('external_untrusted');
+ });
+ test('an unchanged history reports nothing', () => {
+ expect(analyzePageDrift({ chain: [snap({ ingested_via: 'webhook' }), snap({ ingested_via: 'webhook' }, 'remote')], stored: 'unknown', columns })).toBeNull();
+ });
+});