Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

#6712 PR 4b: fold the pass stamp into writeback imports (GBRA-108 option A)

garrytan6d5d50a6086e
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.md
index 4fb18d3138..3d1e7154e4 100644
--- a/docs/architecture/key-files/canonical-reconciliation.md
+++ b/docs/architecture/key-files/canonical-reconciliation.md
@@ -26,7 +26,7 @@
- `src/core/persistence/sync-pass-readers.ts` — the pass row as the former cursor readers see it (#6712 PR 4b, design §3.7): doctor's movement, git-holds and terminal-failure checks, the drain backlog (`readManagedSyncBacklog`), the blocked-run reader and `sources status` read a non-company source's pass row through `readPassReadings` (`passHealth` plus the checkout HEAD from a hardened `rev-parse` on this host; no checkout means `head: null` and the recorded converged target is trusted). `passResumeArgs` is the plain sync that continues the pass, with the open episode's inherited options; `passStopCode` and `passStuckSince` name a stuck pass. Company sources and unretired legacy cursors keep their cursor arm in each reader. Tests: `test/sync-pass-readers-6712.test.ts`, `test/sync-pass-reader-gaps-6712.test.ts`.
- `src/core/persistence/sync-pass-apply.ts` — what a live pass round does besides admitting one-sided imports and deletes (#6712 PR 4b, design v3.2 §2.5–§2.7, §3.1, §5): holds with side and state for the two-sided and deleted rows (`file_drift` with `side`, `tombstone_edited`, `purged_differs`, `file_gone`), the `settle_mismatch` hold after three passes at one level, arm-1 adoption of a record without a revision on `fileSame`, the bounded legacy sweep (500 per round) that records equal legacy pages on the first full round, the mass-delete valve (one `sync-deletes-withheld` record; imports and the stamp proceed), `keep_db` admission (200 per pass), deletion-marker retirement in full rounds, and the remote ending (`reconcile_host_required`: one-sided work commits, drift stays unsettled with no hold). Entry points: `applyPassRound`, `finishPassApply`, `summarizeRound`. Tests: `test/sync-pass-completion-6712.test.ts`.
- `src/core/persistence/sync-pass-episode.ts` — pass episodes and cost (#6712 PR 4b, design §6, §7): `episodeClosure` closes an episode by inclusion or at the configured selection (a narrower episode never stamps `chunker_version`; a widened one releases its extra paths), `passCostDecision` defers paid embedding when the envelope is unknown or spent, and `reservePassCost` writes one `sync-pass-cost` row per admitted group (fingerprint `<source>:<incarnation>:<episode_or_pass_id>:<group_id>`, insert-once) inside the group's admission transaction, so a kill keeps the reservation and a replay adds nothing. Tests: `test/sync-pass-completion-6712.test.ts`.
-- `src/core/persistence/sync-pass-status.ts` — the live `convergence` block of `gbrain sync status` (#6712 PR 4b, design §9, `dry_run: false`): built from the pass row (one primary-key read), the withheld-delete record and `syncAdmissionStatus`, plus `passStatusState`, which keeps a source off `synced` while its newest pass is open or ended unconverged (reasons `pass_unfinished`, `not_converged`, `settle_mismatch`, `deletes_withheld`, `selection_scoped`, `admission_paused`). Tests: `test/sync-pass-completion-6712.test.ts`.
+- `src/core/persistence/sync-pass-status.ts` — the live `convergence` block of `gbrain sync status` (#6712 PR 4b, design §9, `dry_run: false`): built from the pass row (one primary-key read), the withheld-delete record and `syncAdmissionStatus`, plus `passStatusState`, which keeps a source off `synced` while its newest pass is open or ended unconverged (reasons `pass_unfinished`, `not_converged`, `settle_mismatch`, `deletes_withheld`, `selection_scoped`, `admission_paused`, and `writeback_failed`: a writeback the stamp recorded in `converged.writeback` whose Git effect failed or parked, next step `gbrain sources writer retry-effects --dry-run`). Tests: `test/sync-pass-completion-6712.test.ts`, `test/sync-pass-writeback-fold-6712.test.ts`.
- `src/core/persistence/sync-markers.ts` — the deletion marker and the withheld mass-delete record of a managed Git source (#6712 PR 4b). `writeOriginDeletedMarker` runs in the transaction of every page-row deletion of a managed source (`page-purge.ts`, the purge-mirror replay; `test/page-row-deleters-guard-6712.test.ts` refuses any other deleter) and writes `sync-origin-deleted` (`<source>:<incarnation>:<origin>`, value `{kind:'deleted', blob_oids, page_id, slug}` from the import record) only when it can matter: the origin is in the `last_commit` tree (hardened `ls-tree`) or a file backs it on disk, no other live page records it, and the source is bound and not a company brain; an unreadable checkout counts as present. `retireOriginDeletedMarker` is compare-and-delete on the value read. `writeDeletesWithheld` / `readDeletesWithheld` / `clearDeletesWithheld` keep one `sync-deletes-withheld` record per incarnation (`{target, count, reconcilable, ratio, set_hash, samples≤20}`, `deleteSetHash`: sha256 over the sorted NUL-joined set). Seam: `purge:marker_written`.
- `src/commands/doctor/checks/managed-sync-convergence.ts` — doctor `managed_sync_convergence` (#6712 PR 4a, `deep` tier): the convergence shadow's counts for each managed source this host owns; always `ok` (informational), read-only. Tests: `test/doctor-managed-sync-convergence.test.ts`.
- `src/core/persistence/file-claims.ts` — the recorded-origin census shared by reconcile and the shared-origin delete (#6517): `fileClaimCandidatesQuery` (the paged same-name query and its binds, built per platform so every bound placeholder is referenced (#6659: an unreferenced bind failed every Windows `delete_page` with 42P18), 100 rows per batch below the source's highest page id, served by the v219 name indexes; `source_path` in any spelling or a `file:` URI; tombstones excluded) and `findLiveFileClaimants`, realpath deciding each candidate. In `page-prepare.ts`, a `delete_page` whose file another live page records (`prepareFileTarget` with `sharedOrigin`, before the byte comparison) owns no file: a soft delete publishes database-only with receipt `write_through.skipped: 'shared_origin'` and a warning ("hidden … does not erase", the `gbrain repair file-drift --source <id> --slug <survivor> --prefer file` that imports the kept file into the survivor; #6712 PR 1: sync holds a survivor that differs from the file `file_drift`, and that hold's fix leads with the same command), `validate` re-runs the census under the publication guards (`validateSharedOrigin`: the file moved or removed, or a different claimant set, refuses `source_changed` and never removes the file), and the surviving slug is named only when `slugDisclosable` (authority.ts: the local owner, or a remote writer whose prefix grant, delegated namespace and visibility cover it). A purge of a shared-origin page refuses and names the soft delete. Tests: `test/page-prepare-shared-origin-6517.test.ts`, `test/sync-origin-live-wins-6517.test.ts`, `test/e2e/managed-sync-shared-origin-6517.test.ts`.
diff --git a/src/commands/sync/operator.ts b/src/commands/sync/operator.ts
index c577641b3c..c5ef71c70a 100644
--- a/src/commands/sync/operator.ts
+++ b/src/commands/sync/operator.ts
@@ -202,6 +202,7 @@ export function syncStatusHeadline(status: Pick<SyncStatus, 'source_id' | 'state
case 'deletes_withheld': return `Source ${status.source_id} is blocked: sync withheld a mass delete; the rest of the source is synced.`;
case 'selection_scoped': return `Source ${status.source_id} is synced at a narrower selection; the plain sync runs the configured one.`;
case 'admission_paused': return `Source ${status.source_id} is resumable: sync.admission pauses what sync admits.`;
+ case 'writeback_failed': return `Source ${status.source_id} is blocked: the Git effect of a file sync rewrote failed and is parked; the checkout lags the brain.`;
}
}
diff --git a/src/core/persistence/checkpoint-validation.ts b/src/core/persistence/checkpoint-validation.ts
index 055f52a3cc..0cb0d7aa6d 100644
--- a/src/core/persistence/checkpoint-validation.ts
+++ b/src/core/persistence/checkpoint-validation.ts
@@ -96,9 +96,12 @@ export const OPEN_PASS_WORK_SQL = `(SELECT r.request_id::text AS request_id FROM
* `persistence_requests_recovery`. Returns the blocking request id, or null. A statement timeout is the typed
* `checkpoint_validation_timeout`, as clause 1 of the cursor validation.
*/
-export async function findOpenPassWork(tx: Pick<BrainEngine, 'executeRaw'>, worktreeId: string, selfRequestId: string): Promise<string | null> {
+export async function findOpenPassWork(tx: Pick<BrainEngine, 'executeRaw'>, worktreeId: string, selfRequestId: string,
+ /** A writeback's folded stamp: its own recovery record is the file publication's journal, which its commit resolves. */
+ ownRecovery = false): Promise<string | null> {
try {
- const [row] = await tx.executeRaw<{ request_id: string }>(OPEN_PASS_WORK_SQL, [worktreeId, selfRequestId]);
+ const [row] = await tx.executeRaw<{ request_id: string }>(ownRecovery ? OPEN_PASS_WORK_SQL.replace('r.recovery IS NOT NULL LIMIT 1', 'r.recovery IS NOT NULL AND r.request_id<>$2::uuid LIMIT 1') : OPEN_PASS_WORK_SQL,
+ [worktreeId, selfRequestId]);
return row?.request_id ?? null;
} catch (error) {
const failure = error as { code?: string; message?: string };
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index 908c02c99d..0550a08764 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -78,6 +78,11 @@ interface PreparedMutationBase {
*/
postimage?: PageSnapshot | null;
validate?(tx: BrainEngine): Promise<void>;
+ /**
+ * #6712 PR 4b: runs in the publication transaction right after its effects are queued, so it sees the request's own
+ * Git effect (a writeback import's folded pass stamp, sync-pass-fold.ts); it may add to the outcome. Absent for every other write.
+ */
+ afterEffects?(tx: BrainEngine, outcome: Record<string, unknown>): Promise<void>;
/** #5575: the tier and origin of the rows apply writes; absent: the request's channel tier (trust/channel.ts). */
trust?: WriteTrust;
/**
@@ -534,6 +539,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr
decoratePublicationOutcome(row, prepared, outcome, final, files.length, skill);
await recordPublicationFenceTrend(tx, row, outcome);
await timePublicationStep('effects', row.slug, () => queuePublicationEffects(tx, row, final, outcome, prepared));
+ if (prepared.afterEffects) await withCoordinatedWrite(tx, [row.source_id], () => prepared.afterEffects!(tx, outcome), publicationAttribution(row, prepared.trust));
await hooks.boundary?.('before_commit', row);
const committed = await completeWrite(tx, current, 'committed', outcome, undefined, current);
transactionBodyCompleted = true;
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.ts
index 2fc9370bb4..52bea98492 100644
--- a/src/core/persistence/group-publish.ts
+++ b/src/core/persistence/group-publish.ts
@@ -91,7 +91,7 @@ export function singleWrite(row: Pick<WriteRequest, 'operation' | 'intent'>): bo
/** Whether a prepared member can share a group transaction. */
export function groupable(row: WriteRequest, prepared: PreparedMutation): boolean {
- if ((row.target_kind ?? 'page') !== 'page' || prepared.target === 'skill_bundle' || prepared.sourceExclusive || prepared.exclusiveSources?.length) return false;
+ if ((row.target_kind ?? 'page') !== 'page' || prepared.target === 'skill_bundle' || prepared.sourceExclusive || prepared.exclusiveSources?.length || prepared.afterEffects) return false;
if (syncMember(row)) return !prepared.file && typeof prepared.validate === 'function';
// A streamed file (large-file.ts) is staged before its publication transaction, which only publishMutation does.
if (isStreamedContent(prepared.file?.content)) return false;
diff --git a/src/core/persistence/sync-classify.ts b/src/core/persistence/sync-classify.ts
index 115d026645..224035ab8e 100644
--- a/src/core/persistence/sync-classify.ts
+++ b/src/core/persistence/sync-classify.ts
@@ -183,7 +183,7 @@ export function classifySyncPath(s: SyncPathState): SyncClassified {
/** Why a pass is not idle (v3.2 §2.2); empty = idle. A hold-only round runs when `rescreen_due_hold` is the only reason. */
export type SyncIdleBlocker = 'no_converged_state' | 'target_moved' | 'open_episode' | 'owed_tail' | 'retry_row' | 'not_converged_streak' | 'mismatch_streak'
- | 'fingerprint_changed' | 'request_newer' | 'open_at_stamp_finished' | 'working_change' | 'full_round_due' | 'rescreen_due_hold';
+ | 'fingerprint_changed' | 'request_newer' | 'open_at_stamp_finished' | 'writeback_open' | 'working_change' | 'full_round_due' | 'rescreen_due_hold';
export interface SyncPassKindInput {
converged: { target: string; parserFp: string; pack: string | null; selectionFp: string; passesSinceFull: number; lastFullAt: number } | null;
@@ -193,6 +193,8 @@ export interface SyncPassKindInput {
requestNewer: boolean;
/** Some request or effect recorded in `converged.open_at_stamp` is no longer open (or the set overflowed its cap). */
openAtStampFinished: boolean;
+ /** A writeback recorded in `converged.writeback` has a Git effect that has not committed (queued, running, failed or parked). */
+ writebackOpen?: boolean;
/** Working mode: the stat cache saw a change. */
workingChange: boolean;
rescreenDueHold: boolean;
@@ -221,6 +223,7 @@ export function syncPassKind(input: SyncPassKindInput): { kind: 'idle' | 'hold_o
if (input.mismatchStreak > 0) blockers.push('mismatch_streak');
if (input.requestNewer) blockers.push('request_newer');
if (input.openAtStampFinished) blockers.push('open_at_stamp_finished');
+ if (input.writebackOpen) blockers.push('writeback_open');
if (input.workingChange) blockers.push('working_change');
if (input.rescreenDueHold) blockers.push('rescreen_due_hold');
const kind = !blockers.length ? 'idle' : blockers.every(b => b === 'rescreen_due_hold') ? 'hold_only' : 'full';
diff --git a/src/core/persistence/sync-pass-batch.ts b/src/core/persistence/sync-pass-batch.ts
index bf23ee00ea..e4cf2afc99 100644
--- a/src/core/persistence/sync-pass-batch.ts
+++ b/src/core/persistence/sync-pass-batch.ts
@@ -77,8 +77,9 @@ export function passRequestId(passId: string, path: string, level: string | null
* The converged watermark a pass records (design v3.2 §2.2): the worktree's highest request `sequence`, and the requests
* (`r:<id>`) and Git effects (`e:<id>`) still open, at most `cap` (null above it: no idle until a full round re-reads).
*/
-export async function readConvergedWatermark(tx: Pick<BrainEngine, 'executeRaw'>, scope: { worktreeId: string; sourceId: string; incarnation: string }, selfRequestId: string | null, cap: number):
- Promise<{ request_hwm: string; open_at_stamp: string[] | null }> {
+export async function readConvergedWatermark(tx: Pick<BrainEngine, 'executeRaw'>, scope: { worktreeId: string; sourceId: string; incarnation: string }, selfRequestId: string | null, cap: number,
+ /** `converged.writeback` (sync-pass-row.ts): a folded writeback stamp's own write, and the prior stamp's list, of which the uncommitted stay. */
+ writeback?: { own?: string; prior?: readonly string[] }): Promise<{ request_hwm: string; open_at_stamp: string[] | null; writeback?: string[] }> {
// The worktree's requests and the incarnation's worktree-less ones (writes admitted with sync.write_through=false).
const [hwm] = await tx.executeRaw<{ hwm: string | null }>(`SELECT GREATEST((SELECT max(sequence) FROM persistence_requests WHERE worktree_id=$1::uuid),
(SELECT max(sequence) FROM persistence_requests WHERE worktree_id IS NULL AND source_id=$2 AND source_incarnation=$3::uuid))::text AS hwm`, [scope.worktreeId, scope.sourceId, scope.incarnation]);
@@ -87,7 +88,11 @@ export async function readConvergedWatermark(tx: Pick<BrainEngine, 'executeRaw'>
AND request_id IS DISTINCT FROM $2::uuid LIMIT $3)
UNION ALL (SELECT 'e:'||e.id::text FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id
WHERE r.worktree_id=$1::uuid AND e.kind='git' AND e.state IN ('queued','running') LIMIT $3)`, [scope.worktreeId, selfRequestId, cap + 1, scope.sourceId, scope.incarnation]);
- return { request_hwm: hwm?.hwm ?? '0', open_at_stamp: open.length > cap ? null : open.map(row => row.id) };
+ // The prior list's writebacks whose Git effect has not committed (queued, running, failed or parked) stay listed.
+ const carried = writeback?.prior?.length ? (await tx.executeRaw<{ id: string }>(`SELECT DISTINCT e.request_id::text AS id FROM persistence_effects e
+ WHERE e.request_id = ANY($1::uuid[]) AND e.kind='git' AND e.state<>'committed'`, [writeback.prior])).map(row => row.id) : [];
+ const listed = [...new Set([...(writeback?.own ? [writeback.own] : []), ...carried])];
+ return { request_hwm: hwm?.hwm ?? '0', open_at_stamp: open.length > cap ? null : open.map(row => row.id), ...(listed.length ? { writeback: listed } : {}) };
}
/** A round batch's entry: the discovery shape plus the level `L` it was classified at (the request identity's third part). */
diff --git a/src/core/persistence/sync-pass-fold.ts b/src/core/persistence/sync-pass-fold.ts
index 0d8b9fdb12..5bc217fdc5 100644
--- a/src/core/persistence/sync-pass-fold.ts
+++ b/src/core/persistence/sync-pass-fold.ts
@@ -8,7 +8,11 @@
* (`last_commit`, the slug-root pin) still where the pass found it; and no refused checkpoint of the source that no later
* checkpoint superseded (#6834): the stamp path's checkpoint request supersedes it, a folded stamp would leave it listed;
* - `U_db` as the checkpoint records it: the converged watermark and `open_at_stamp` (`readConvergedWatermark`), read in
- * the same transaction; this import publishes no file, so no Git effect of its own is left out of them;
+ * the same transaction. A writeback (the import rewrites its file; GBRA-108, option A) folds through the coordinator's
+ * post-effects hook (`afterEffects`), after its Git effect is queued: that effect is in `open_at_stamp` and the import is
+ * recorded in `converged.writeback`, so the source is not idle until the effect commits (sync-pass.ts `passIdleProbe`), a
+ * failed or parked one blocks `sync status` (`writeback_failed`), and its own recovery record (the file publication's
+ * journal, which this commit resolves) is not open work;
* - since the round's mark (S1), every change the level reads is this round's own write (sync-pass-confirm.ts
* `proveConfirm`, with this request's uncommitted page admitted): exactly one page per import of the round, the pages
* past S1's largest id the round's new ones, the counts S1's plus the round's new pages and records, and no hold at S1
@@ -21,7 +25,12 @@
* there (a validation timeout, a lost race) rolls back to it and skips the stamp, as one it cannot prove is skipped. A publication that rolls back takes the stamp with it; one that commits leaves the stamp and the pages
* consistent for the next run.
*/
+import { realpathSync } from 'node:fs';
+import { join, relative, sep } from 'node:path';
import type { BrainEngine } from '../engine.ts';
+import { hardenedGitSync } from '../hardened-git.ts';
+import { fileContentHash } from './large-file.ts';
+import { readBlobBytes, readTreeBlobs } from './sync-blobs.ts';
import type { PreparedMutation } from './coordinator.ts';
import type { WriteRequest } from './model.ts';
import { syncLockId } from '../db-lock.ts';
@@ -46,11 +55,21 @@ export interface PassFold {
obligations?: ManagedSyncPassValue['obligations'];
}
-/** `prepared` (the round's last import) with the stamp folded into its apply; a file write keeps the stamp path. */
+/**
+ * `prepared` (the round's last import) with the stamp folded into its publication: into its apply, or, for a writeback
+ * (the import rewrites its file), into its post-effects hook, so the stamp sees and records the import's own Git effect.
+ */
export function foldPassCheckpoint<T extends PreparedMutation>(prepared: T, input: { row: WriteRequest; p: SyncIntent; root: string }): T {
- if (prepared.file || prepared.noop) return prepared;
- const apply = prepared.apply.bind(prepared);
+ if (prepared.noop) return prepared;
prepared.sourceExclusive = true;
+ if (prepared.file) {
+ prepared.afterEffects = async (tx, outcome) => {
+ const skipped = await foldedStamp(tx, input, outcome, input.row.id);
+ Object.assign(outcome, skipped ? { pass_stamp_skipped: skipped } : { pass_stamp: 'folded' });
+ };
+ return prepared;
+ }
+ const apply = prepared.apply.bind(prepared);
prepared.apply = async (tx, preimage) => {
const outcome = await apply(tx, preimage);
const skipped = await foldedStamp(tx, input, outcome);
@@ -59,11 +78,42 @@ export function foldPassCheckpoint<T extends PreparedMutation>(prepared: T, inpu
return prepared;
}
+/**
+ * The round after a folded writeback stamp, when HEAD left the stamp's target (durability on: the import's Git effect
+ * committed meanwhile): whether `from..head` changes exactly the files of the stamp's writebacks (`converged.writeback`),
+ * each to the bytes its import wrote (the Git effect's `expected_hash`), with every one of those effects committed. Then
+ * the level at HEAD is the one the stamp proved plus the pass's own bytes, and the pass ends on its stamp; anything else
+ * reads the level in full.
+ */
+export async function ownWritebackCommit(engine: Pick<BrainEngine, 'executeRaw'>, input: { gitRoot: string; localPath: string; from: string; writeIds: readonly string[] }): Promise<boolean> {
+ if (!input.writeIds.length) return false;
+ const git = (args: string[]) => { const out = hardenedGitSync(input.gitRoot, args, { timeoutMs: 10_000, maxBytes: 1024 * 1024 }); return out.ok ? out.stdout.toString('utf8') : null; };
+ const head = git(['rev-parse', '--verify', '--quiet', 'HEAD^{commit}'])?.trim();
+ const changed = head && head !== input.from ? git(['diff-tree', '-r', '-z', '--no-renames', input.from, head]) : null;
+ if (!head || changed === null) return false;
+ const effects = await engine.executeRaw<{ path: string | null; hash: string | null; state: string }>(`SELECT data->>'relative_path' AS path, data->>'expected_hash' AS hash, state
+ FROM persistence_effects WHERE request_id = ANY($1::uuid[]) AND kind='git'`, [input.writeIds]);
+ if (!effects.length || effects.some(effect => effect.state !== 'committed' || !effect.path || !effect.hash)) return false;
+ const root = realpathSync(input.localPath);
+ const want = new Map(effects.map(effect => [relative(input.gitRoot, join(root, effect.path!)).split(sep).join('/'), effect.hash!]));
+ // `:<mode> <mode> <oid> <oid> <status>\0<path>\0` per changed path: each must be a file of `want`, now a blob.
+ const fields = changed.split('\0'), blobs = new Map<string, string>();
+ for (let i = 0; i + 1 < fields.length; i += 2) {
+ const [, mode, , oid] = fields[i]!.split(' ');
+ if (!mode?.startsWith('100') || !oid || !want.has(fields[i + 1]!)) return false;
+ blobs.set(fields[i + 1]!, oid);
+ }
+ if (blobs.size !== want.size) return false;
+ const sized = readTreeBlobs(input.gitRoot, head, [...blobs.keys()]);
+ const bytes = readBlobBytes(input.gitRoot, [...sized.values()]);
+ return [...blobs].every(([path, oid]) => { const content = sized.get(path)?.oid === oid && bytes.get(oid); return !!content && fileContentHash(content) === want.get(path); });
+}
+
/** Publishes the stamp in `tx` when its checks hold; else why not (`error`: a statement failed, rolled back to the savepoint). */
-async function foldedStamp(tx: BrainEngine, input: { row: WriteRequest; p: SyncIntent; root: string }, outcome: Record<string, unknown>): Promise<string | null> {
+async function foldedStamp(tx: BrainEngine, input: { row: WriteRequest; p: SyncIntent; root: string }, outcome: Record<string, unknown>, writeback?: string): Promise<string | null> {
await tx.executeRaw('SAVEPOINT gbrain_pass_stamp_fold');
try {
- const skipped = await provenStamp(tx, input, outcome);
+ const skipped = await provenStamp(tx, input, outcome, writeback);
await tx.executeRaw(skipped ? 'ROLLBACK TO SAVEPOINT gbrain_pass_stamp_fold' : 'RELEASE SAVEPOINT gbrain_pass_stamp_fold');
return skipped;
} catch {
@@ -72,15 +122,15 @@ async function foldedStamp(tx: BrainEngine, input: { row: WriteRequest; p: SyncI
}
}
-async function provenStamp(tx: BrainEngine, { row, p, root }: { row: WriteRequest; p: SyncIntent; root: string }, outcome: Record<string, unknown>): Promise<string | null> {
+async function provenStamp(tx: BrainEngine, { row, p, root }: { row: WriteRequest; p: SyncIntent; root: string }, outcome: Record<string, unknown>, writeback?: string): Promise<string | null> {
const stamp = p.stamp!, fold = stamp.fold!, postgres = tx.kind === 'postgres';
const scope = { worktreeId: row.worktree_id!, sourceId: row.source_id, incarnation: row.source_incarnation };
await faultPoint('sync:pass_fold', { requestId: row.request_id, writeId: row.id, sourceId: row.source_id });
const [lease, pass, blocker, watermark, sources, proof, refused] = await pipelined(tx, [
() => tx.executeRaw('SELECT 1 FROM gbrain_cycle_locks WHERE id=$1 AND acquisition_token=$2::uuid AND ttl_expires_at > now() FOR SHARE', [syncLockId(row.source_id), stamp.leaseToken]),
() => readPassRow(tx, row.source_id, stamp.incarnation),
- () => findOpenPassWork(tx, row.worktree_id!, row.request_id),
- () => readConvergedWatermark(tx, scope, row.request_id, OPEN_AT_STAMP_CAP),
+ () => findOpenPassWork(tx, row.worktree_id!, row.request_id, !!writeback),
+ () => readConvergedWatermark(tx, scope, row.request_id, OPEN_AT_STAMP_CAP, writeback ? { own: writeback } : undefined),
() => tx.executeRaw(`SELECT last_commit, config->>'slug_root_mode' AS mode FROM sources WHERE id=$1 AND incarnation=$2::uuid`, [row.source_id, row.source_incarnation]),
() => proveConfirm(tx, { sourceId: row.source_id, incarnation: row.source_incarnation, passId: p.passId!, base: fold.base, postgres, self: row.id }),
() => tx.executeRaw(`SELECT 1 FROM persistence_requests r WHERE r.source_id=$1 AND r.slug='__managed_sync_checkpoint__' AND r.intent IS NOT NULL AND NOT r.compacted
@@ -100,6 +150,10 @@ async function provenStamp(tx: BrainEngine, { row, p, root }: { row: WriteReques
if (!countsMatch(fold.base, proof, { pages: fold.pages + fold.newPages, newRecords: fold.newRecords })) return 'counts';
if (!await passWritesMatched(tx, { kind: postgres ? 'postgres' : 'pglite', sourceId: row.source_id, incarnation: row.source_incarnation, pack: stamp.pack, scope: fold.scope,
slugMode: p.slugMode, episodeFullId: fold.episodeFullId, ids: proof.pages })) return 'unsettled';
- await publishPassStamp(tx, row, p, root, async () => {}, fold.obligations ? { value: { ...pass.value, obligations: fold.obligations } } : pass, { changed: stamp.changed + (outcome.noop === true ? 0 : 1), watermark, ...(emptyScope === undefined ? {} : { emptyScope }) });
+ // A prior stamp's open writebacks (rare) are carried on: the watermark is read again with them.
+ const prior = pass.value.obligations.converged?.writeback;
+ const read = prior?.length ? await readConvergedWatermark(tx, scope, row.request_id, OPEN_AT_STAMP_CAP, { own: writeback, prior }) : watermark;
+ await publishPassStamp(tx, row, p, root, async () => {}, fold.obligations ? { value: { ...pass.value, obligations: fold.obligations } } : pass,
+ { changed: stamp.changed + (outcome.noop === true ? 0 : 1), watermark: read, ...(emptyScope === undefined ? {} : { emptyScope }) });
return null;
}
diff --git a/src/core/persistence/sync-pass-row.ts b/src/core/persistence/sync-pass-row.ts
index 70301b4aa6..b82e2cc233 100644
--- a/src/core/persistence/sync-pass-row.ts
+++ b/src/core/persistence/sync-pass-row.ts
@@ -49,6 +49,11 @@ export interface PassConverged {
request_hwm: string;
/** Requests and Git effects open on settled paths at the stamp (design §2.2), at most `OPEN_AT_STAMP_CAP`; null when the cap overflowed (no idle). */
open_at_stamp: string[] | null;
+ /**
+ * #6712 PR 4b: the write ids of the writeback imports whose Git effect a stamp recorded open (the folded stamp's own, and
+ * any an earlier stamp carried that has not committed). Until each effect commits the source is not idle; absent: none.
+ */
+ writeback?: string[];
parser_fp: string;
pack: string | null;
selection_fp: string;
diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.ts
index 989b30e4a8..1e702e75a4 100644
--- a/src/core/persistence/sync-pass-run.ts
+++ b/src/core/persistence/sync-pass-run.ts
@@ -32,7 +32,7 @@ import { OPEN_AT_STAMP_CAP, passFingerprint, readPassRow, SYNC_ORIGIN_DELETED_OP
import { readSyncAdmission, type SyncAdmission } from './sync-admission.ts';
import { faultPoint } from './fault-points.ts';
import { passFoldBase, passIdleProbe, readShadowLevel, workingIdleChange, type PassLevelCache, type ShadowLevel, type ShadowPath } from './sync-pass.ts';
-import type { PassFold } from './sync-pass-fold.ts';
+import { ownWritebackCommit, type PassFold } from './sync-pass-fold.ts';
import { loopYield } from './sync-yield.ts';
import { recallWorkingStatCache, rememberWorkingStatCache, SyncTreeReadIncomplete } from './sync-git-stream.ts';
import { syncPassKind } from './sync-classify.ts';
@@ -393,7 +393,7 @@ async function pinPass(engine: BrainEngine, input: SyncPassInput, lease: NonNull
head, parserFp, pack, selectionFp, now: started, openEpisode: !!episode, owedTail: tail !== null, retryRow: retry.length > 0,
notConvergedStreak: obligations.not_converged_streak, mismatchStreak: Object.keys(obligations.mismatch).length,
requestNewer: probe?.newer === true, openAtStampFinished: !!converged && (converged.open_at_stamp === null || (probe?.stillOpen ?? 0) < converged.open_at_stamp.length),
- workingChange: working.changed, rescreenDueHold: holds.some(hold => holdRescreenDue(hold, retry.includes(hold.path))), full: opts.full === true });
+ writebackOpen: probe?.writebackOpen === true, workingChange: working.changed, rescreenDueHold: holds.some(hold => holdRescreenDue(hold, retry.includes(hold.path))), full: opts.full === true });
// Design §2.6: a withheld mass delete is applied by a full round once the owner host's env valve allows it.
const valveOpen = !remote && !!obligations.deletes_withheld && massReconcileAllowed();
// Design §4: keep_db writes the previous pass deferred (`keep_db_pending`: its cap, or write capacity) are owed to this pass, so it is
@@ -497,7 +497,7 @@ async function stampUnchangedPass(engine: BrainEngine, input: SyncPassInput, rou
// Holds on paths that left the level go with it here too, as a stamp releases them.
for (const path of level.releasableHolds) await clearGitHold(tx, { sourceId, incarnation, path, observedAt: startedAt });
await recordPassFenceTrend(tx, { worktreeId: context.binding.worktree_id, sourceId, passId, since: converged?.request_hwm ?? null });
- const watermark = await readConvergedWatermark(tx, { worktreeId: context.binding.worktree_id, sourceId, incarnation }, null, OPEN_AT_STAMP_CAP);
+ const watermark = await readConvergedWatermark(tx, { worktreeId: context.binding.worktree_id, sourceId, incarnation }, null, OPEN_AT_STAMP_CAP, { prior: converged?.writeback });
value.obligations.converged = { target: head, at, ...watermark, parser_fp: parserFp, pack, selection_fp: selectionFp,
last_full_at: kind === 'full' || !converged ? at : converged.last_full_at, passes_since_full: kind === 'full' || !converged ? 0 : converged.passes_since_full + 1 };
Object.assign(value.obligations, { not_converged_streak: 0, mismatch: {}, stuck_since: null });
@@ -754,6 +754,9 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
// The previous round's level is done with: dropped before the next one is read, so a large source holds one level, not two.
lastLevel = null;
await faultPoint('sync:round_start', { sourceId, round });
+ // A folded writeback stamp whose Git effect moved HEAD by exactly the pass's own bytes ends the pass on that stamp.
+ if (folded && mode === 'committed' && await ownWritebackCommit(engine, { gitRoot: context.gitRoot, localPath: context.binding.local_path ?? context.root, from: folded.head,
+ writeIds: value.obligations.converged?.writeback ?? [] })) return synced(true);
const levelInput = { sourceId, context, workingTree: mode === 'working',
pass: { noSchemaPack: processingOptions.noSchemaPack, episodeFullId: episode?.full_id ?? null, retryConsumed: round > 1 ? retryConsumed : undefined, exclude: opts.exclude, includeHidden: opts.includeHidden, strategy: opts.strategy, bootstrap: markersOwed(),
slugMode: value.obligations.slug_mode, cache: levelCache, passId, recorded: applied.recorded } };
diff --git a/src/core/persistence/sync-pass-status.ts b/src/core/persistence/sync-pass-status.ts
index 04bcd100e6..d9bf41851e 100644
--- a/src/core/persistence/sync-pass-status.ts
+++ b/src/core/persistence/sync-pass-status.ts
@@ -52,22 +52,26 @@ export async function passConvergence(engine: Pick<BrainEngine, 'executeRaw'>, i
duration_ms: t.duration_ms, timings_ms: t.timings_ms, last_full_at: o.converged?.last_full_at ?? null };
}
-export type PassStatusReason = 'pass_unfinished' | 'not_converged' | 'settle_mismatch' | 'deletes_withheld' | 'selection_scoped' | 'admission_paused';
+export type PassStatusReason = 'pass_unfinished' | 'not_converged' | 'settle_mismatch' | 'deletes_withheld' | 'selection_scoped' | 'admission_paused' | 'writeback_failed';
-/** The state the newest pass puts the source in (design §9): never `synced` while it is open or ended unconverged. Null: nothing to add. */
-export function passStatusState(row: PassRow, withheld: DeletesWithheld | null, now = Date.now()): ['synced' | 'resumable' | 'blocked', PassStatusReason] | null {
+/**
+ * The state the newest pass puts the source in (design §9): never `synced` while it is open or ended unconverged, or while a
+ * writeback its stamp recorded (`converged.writeback`) has a failed or parked Git effect (`writebackFailed`: that request). Null: nothing to add.
+ */
+export function passStatusState(row: PassRow, withheld: DeletesWithheld | null, writebackFailed: string | null = null, now = Date.now()): ['synced' | 'resumable' | 'blocked', PassStatusReason] | null {
const t = row.value.telemetry;
if (t.outcome === 'open' || (t.outcome === 'resumable' && t.stop_reason !== 'not_converged' && t.stop_reason !== 'admission_paused')) return ['resumable', 'pass_unfinished'];
if (t.stop_reason === 'admission_paused') return ['resumable', 'admission_paused'];
if (t.stop_reason === 'not_converged' || (row.value.obligations.not_converged_streak ?? 0) > 0) return ['resumable', 'not_converged'];
if (passHealth(row, { now, stalledMs: Number.POSITIVE_INFINITY }).reason === 'settle_mismatch') return ['resumable', 'settle_mismatch'];
+ if (writebackFailed) return ['blocked', 'writeback_failed'];
if (withheld) return ['blocked', 'deletes_withheld'];
if (t.outcome === 'synced' && t.stop_reason === 'selection_scoped') return ['synced', 'selection_scoped'];
return null;
}
/** The next step for a pass reason (`resume`: the plain sync's arguments). */
-export function passStatusNext(sourceId: string, reason: PassStatusReason, row: PassRow, resume: string[]): Action {
+export function passStatusNext(sourceId: string, reason: PassStatusReason, row: PassRow, resume: string[], writebackFailed: string | null = null): Action {
const verify = { argv: ['gbrain', 'sync', 'status', '--source', sourceId, '--json'] };
const sync: Action = { argv: ['gbrain', 'sync', ...resume], consent: [], actor: 'agent', requires_exclusive: false, verify, why: '' };
switch (reason) {
@@ -84,6 +88,10 @@ export function passStatusNext(sourceId: string, reason: PassStatusReason, row:
return { argv: ['gbrain', 'config', 'set', 'sync.admission', 'normal'], consent: [], actor: 'user', requires_exclusive: false, verify,
user_message: `sync.admission pauses what sync admits for ${sourceId}; restore it with gbrain config set sync.admission normal when the pause is over.`,
why: 'The pause is the owner\'s setting; it is never lifted automatically.' };
+ case 'writeback_failed':
+ return { argv: ['gbrain', 'sources', 'writer', 'retry-effects', sourceId, '--request-id', writebackFailed ?? '<id>', '--dry-run'], consent: [], actor: 'agent', requires_exclusive: false, verify,
+ user_message: `The Git effect of a file sync rewrote in ${sourceId} (request ${writebackFailed}) failed and is parked, so the checkout does not hold what the brain holds. Fix the cause doctor's parked_effects names, then retry it with the same command without --dry-run.`,
+ why: 'The preview names the parked effect and what a retry runs (read-only); until it commits, the source is never idle.' };
case 'selection_scoped':
return { ...sync, why: 'The last pass converged at a narrower selection and did not advance last_commit; the plain sync runs the configured selection.' };
default:
diff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.ts
index facf2c17bc..04d751e156 100644
--- a/src/core/persistence/sync-pass.ts
+++ b/src/core/persistence/sync-pass.ts
@@ -1121,7 +1121,7 @@ export async function idleTickProbe(engine: BrainEngine, input: { sourceId: stri
const newer = probe.newer, pending = probe.pending;
const kind = syncPassKind({ converged: converged ? { target: converged.target, parserFp: '', pack: null, selectionFp: '', passesSinceFull: 0, lastFullAt: Date.now() } : null,
head: head ?? '', parserFp: '', pack: null, selectionFp: '', now: Date.now(), openEpisode: false, owedTail: false, retryRow: false, notConvergedStreak: 0, mismatchStreak: 0,
- requestNewer: newer, openAtStampFinished: pending && !input.assumeConverged, workingChange: false, rescreenDueHold: false, full: false });
+ requestNewer: newer, openAtStampFinished: pending && !input.assumeConverged, writebackOpen: probe.writebackOpen && !input.assumeConverged, workingChange: false, rescreenDueHold: false, full: false });
timings.total = total();
return { idle: kind.kind === 'idle', reasons: kind.blockers, timings_ms: timings, rows: (newer ? 1 : 0) + (pending ? 1 : 0) + (row ? 1 : 0) };
}
@@ -1131,11 +1131,11 @@ export async function idleTickProbe(engine: BrainEngine, input: { sourceId: stri
* worktree is newer than the converged watermark (a range on the unique `sequence` index; `requestHwm` overrides the
* row's), whether any request is open (`persistence_requests_pending`), and how many of the ids recorded in
* `converged.open_at_stamp` are still open (`r:<request>` requests, `e:<effect>` Git effects; `openAtStamp` null reads the
- * row's, so the probe needs no earlier read of the row).
+ * row's, so the probe needs no earlier read of the row), and whether a writeback in `converged.writeback` has an uncommitted Git effect.
*/
export async function passIdleProbe(engine: Pick<BrainEngine, 'executeRaw'>, input: { sourceId: string; incarnation: string; worktreeId: string;
- requestHwm: string | number | null; openAtStamp: readonly string[] | null }): Promise<{ passRow: Record<string, unknown> | null; newer: boolean; pending: boolean; stillOpen: number }> {
- const [probe] = await engine.executeRaw<{ pass_row: Record<string, unknown> | null; newer: boolean; pending: boolean; still_open: number | string }>(`WITH pass AS (
+ requestHwm: string | number | null; openAtStamp: readonly string[] | null }): Promise<{ passRow: Record<string, unknown> | null; newer: boolean; pending: boolean; stillOpen: number; writebackOpen: boolean }> {
+ const [probe] = await engine.executeRaw<{ pass_row: Record<string, unknown> | null; newer: boolean; pending: boolean; still_open: number | string; writeback_open: boolean }>(`WITH pass AS (
SELECT completed_keys->0 AS value FROM op_checkpoints WHERE op=$1 AND fingerprint=$2),
stamp AS (SELECT unnest(COALESCE($5::text[], ARRAY(SELECT jsonb_array_elements_text(CASE WHEN jsonb_typeof(value->'obligations'->'converged'->'open_at_stamp')='array'
THEN value->'obligations'->'converged'->'open_at_stamp' ELSE '[]'::jsonb END) FROM pass))) AS id)
@@ -1146,9 +1146,11 @@ export async function passIdleProbe(engine: Pick<BrainEngine, 'executeRaw'>, inp
(SELECT count(*) FROM persistence_requests WHERE state IN ('queued','running','recovering') AND (worktree_id = $4 OR worktree_id IS NULL AND source_id = $6 AND source_incarnation = $7::uuid)
AND 'r:'||request_id::text IN (SELECT id FROM stamp))
+ (SELECT count(*) FROM persistence_effects e JOIN persistence_requests r ON r.id = e.request_id
- WHERE r.worktree_id = $4 AND e.kind = 'git' AND e.state IN ('queued','running') AND 'e:'||e.id::text IN (SELECT id FROM stamp)) AS still_open`,
+ WHERE r.worktree_id = $4 AND e.kind = 'git' AND e.state IN ('queued','running') AND 'e:'||e.id::text IN (SELECT id FROM stamp)) AS still_open,
+ EXISTS (SELECT 1 FROM persistence_effects e WHERE e.kind = 'git' AND e.state <> 'committed' AND e.request_id IN (SELECT id::uuid FROM pass,
+ jsonb_array_elements_text(CASE WHEN jsonb_typeof(value->'obligations'->'converged'->'writeback')='array' THEN value->'obligations'->'converged'->'writeback' ELSE '[]'::jsonb END) AS w(id))) AS writeback_open`,
[MANAGED_SYNC_PASS_OP, `${input.sourceId}:${input.incarnation}`, input.requestHwm, input.worktreeId, input.openAtStamp ? [...input.openAtStamp] : null, input.sourceId, input.incarnation]);
- return { passRow: probe?.pass_row ?? null, newer: probe?.newer === true, pending: probe?.pending === true, stillOpen: Number(probe?.still_open ?? 0) };
+ return { passRow: probe?.pass_row ?? null, newer: probe?.newer === true, pending: probe?.pending === true, stillOpen: Number(probe?.still_open ?? 0), writebackOpen: probe?.writeback_open === true };
}
/**
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index 83c910ad50..d1badd2df4 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -542,7 +542,8 @@ export async function publishPassStamp(tx: BrainEngine, row: WriteRequest, p: Sy
await recordPassFenceTrend(tx, { worktreeId: row.worktree_id!, sourceId: row.source_id, passId: p.passId!, since: pass.value.obligations.converged?.request_hwm ?? null });
for (const path of stamp.releasedHolds) await releaseHold(tx, path);
if (stamp.retryTaken.length) await clearGitHoldRetryPaths(tx, row.source_id, stamp.incarnation, stamp.retryTaken);
- const watermark = read.watermark ?? await readConvergedWatermark(tx, { worktreeId: row.worktree_id!, sourceId: row.source_id, incarnation: row.source_incarnation }, row.request_id, OPEN_AT_STAMP_CAP);
+ const watermark = read.watermark ?? await readConvergedWatermark(tx, { worktreeId: row.worktree_id!, sourceId: row.source_id, incarnation: row.source_incarnation }, row.request_id, OPEN_AT_STAMP_CAP,
+ { prior: pass.value.obligations.converged?.writeback });
const value: ManagedSyncPassValue = structuredClone(pass.value);
const at = new Date().toISOString(), prior = value.obligations.converged;
value.obligations.converged = { target: p.target, at, ...watermark, ...(stamp.rescreen ? { open_at_stamp: null } : {}),
diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.ts
index 8c00b1df59..05cab3478e 100644
--- a/src/core/persistence/sync-status.ts
+++ b/src/core/persistence/sync-status.ts
@@ -156,7 +156,7 @@ export type SyncStatusState = 'synced' | 'resumable' | 'blocked';
export const SYNC_STATUS_REASONS = ['nothing_pending', 'held_by_design', 'cursor_unfinished', 'live_job', 'last_error', 'holds_actionable', 'recovery_pending', 'request_pending',
'status_unknown', 'needs_human', 'head_blocked', 'recovery_blocked',
// #6712 PR 4b (design v3.2 §9): the live pass's reasons.
- 'pass_unfinished', 'not_converged', 'settle_mismatch', 'deletes_withheld', 'selection_scoped', 'admission_paused'] as const;
+ 'pass_unfinished', 'not_converged', 'settle_mismatch', 'deletes_withheld', 'selection_scoped', 'admission_paused', 'writeback_failed'] as const;
export type SyncStatusReason = typeof SYNC_STATUS_REASONS[number];
export type SyncStatusRead = { status: 'read' } | { status: 'not_read'; fix: Action };
/** The bound of each default probe (the oldest blocker, the recovery records). */
@@ -251,8 +251,11 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, opts
// #6712 PR 4b (design §9): the pass row and the withheld-delete record ride the source read (primary-key probes), so the plain status keeps its statement budget.
const admissionSql = syncAdmissionSettingSql(4);
const [source] = await engine.executeRaw<{ incarnation: string; pass_value: PassRow['value'] | null; pass_updated_at: Date | string | null; withheld: DeletesWithheld | null;
- admission_stored: string | null; admission_row_value: string | null; admission_set_at: string | null }>(
- `SELECT s.incarnation::text AS incarnation, p.completed_keys->0 AS pass_value, p.updated_at AS pass_updated_at, w.completed_keys->0 AS withheld, ${admissionSql.columns} FROM sources s
+ admission_stored: string | null; admission_row_value: string | null; admission_set_at: string | null; writeback_failed: string | null }>(
+ `SELECT s.incarnation::text AS incarnation, p.completed_keys->0 AS pass_value, p.updated_at AS pass_updated_at, w.completed_keys->0 AS withheld, ${admissionSql.columns},
+ (SELECT r.request_id::text FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id WHERE e.kind='git' AND e.state='failed'
+ AND e.request_id IN (SELECT id::uuid FROM jsonb_array_elements_text(CASE WHEN jsonb_typeof(p.completed_keys->0->'obligations'->'converged'->'writeback')='array'
+ THEN p.completed_keys->0->'obligations'->'converged'->'writeback' ELSE '[]'::jsonb END) AS w(id)) ORDER BY e.id LIMIT 1) AS writeback_failed FROM sources s
LEFT JOIN op_checkpoints p ON p.op=$2 AND p.fingerprint=s.id||':'||s.incarnation::text
LEFT JOIN op_checkpoints w ON w.op=$3 AND w.fingerprint=s.id||':'||s.incarnation::text
${admissionSql.joins}
@@ -296,7 +299,7 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, opts
// #6712 PR 4b (design §9): the pass row (one primary-key read) and the withheld-delete record make the live `convergence` block.
const passRow: PassRow | null = source.pass_value && source.pass_updated_at ? { value: source.pass_value, updated_at: new Date(source.pass_updated_at).toISOString() } : null;
const withheld = passRow ? source.withheld : null;
- const passState = passRow ? passStatusState(passRow, withheld) : null;
+ const passState = passRow ? passStatusState(passRow, withheld, source.writeback_failed) : null;
const resume = !header && passRow ? passResumeArgs(sourceId, passRow) : managedSyncResumeArgs({ sourceId, processingOptions: header?.processingOptions, syncOptions: header?.syncOptions });
const human = holds.find(hold => hold.needs_human) ?? (lastError?.needs_human ? lastError : undefined);
// #6643: a knock-on or a superseded run is not a failure of its page: the resume re-freezes the entry.
@@ -334,7 +337,7 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, opts
const [state, stateReason] = statusState({ human: !!human, oldest, recovery, liveJob: liveJob !== null, unfinished, lastError: !!lastError, actionable: actionable.length > 0, holds: holds.length > 0, pass: passState });
const admission = await syncAdmissionStatus(engine, sourceId, source.incarnation,
{ stored: source.admission_stored, row_value: source.admission_row_value, set_at: source.admission_set_at });
- const passNext = passRow && passState && passState[1] === stateReason ? passStatusNext(sourceId, passState[1], passRow, resume) : null;
+ const passNext = passRow && passState && passState[1] === stateReason ? passStatusNext(sourceId, passState[1], passRow, resume, source.writeback_failed) : null;
return { source_id: sourceId, run_id: header?.runId ?? null,
cursor: header ? { index: Number(header.index), total: Number(header.total), pinned_target: header.target ?? null, last_advance_at: p ? new Date(p.lastAt).toISOString() : null, done: !!header.done } : null,
committed_last_10m: Number(committed?.n ?? 0), ...estimate, live_job_id: liveJob, holds, identity_downgrades: await withIdentityRemedies(engine, await listIdentityDowngrades(engine, [sourceId])), last_error: lastError, needs_human: !!human, ...(human ? { human_reason: human.human_reason } : {}),
diff --git a/test/e2e/fold-hook-noop-6712-postgres.test.ts b/test/e2e/fold-hook-noop-6712-postgres.test.ts
new file mode 100644
index 0000000000..270a82e28f
--- /dev/null
+++ b/test/e2e/fold-hook-noop-6712-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../fold-hook-noop-6712.test.ts'));
diff --git a/test/e2e/sync-pass-writeback-fold-6712-postgres.test.ts b/test/e2e/sync-pass-writeback-fold-6712-postgres.test.ts
new file mode 100644
index 0000000000..a8013962a4
--- /dev/null
+++ b/test/e2e/sync-pass-writeback-fold-6712-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../sync-pass-writeback-fold-6712.test.ts'));
diff --git a/test/fixtures/fold-hook-noop-6712.json b/test/fixtures/fold-hook-noop-6712.json
new file mode 100644
index 0000000000..1ad6144b9f
--- /dev/null
+++ b/test/fixtures/fold-hook-noop-6712.json
@@ -0,0 +1,265 @@
+{
+ "pglite": {
+ "put_page": [
+ "BEGIN",
+ "SELECT set_config('gbrain.persistence_protocol','2',true),set_config('synchronous_commit','on',true), set_config('lock_timeout',$1,true),set_config('statement_timeout',$2,true),(SELECT brain_id::text FROM persistence_brain WHERE singleton=1 FOR SHARE) AS brain",
+ "SELECT owner_host_id,owner_epoch,state FROM persistence_worktrees WHERE id=$1::uuid FOR SHARE",
+ "SELECT s.source_id,s.source_incarnation,s.worktree_id,s.relative_path, s.topology_generation::text AS topology_generation,w.owner_host_id,w.owner_epoch::text AS owner_epoch,w.state, h.local_path,h.coordination_path,h.git_durability FROM persistence_source_bindings s JOIN persistence_worktrees w ON w.id=s.worktree_id LEFT JOIN persistence_host_bindings h ON h.worktree_id=w.id AND h.host_id=$2::uuid WHERE s.source_id=$1",
+ "SELECT incarnation,archived FROM sources WHERE id=$1 FOR SHARE",
+ "SELECT lane,revoked_at,grant_ceiling FROM persistence_local_writers WHERE id=$1::uuid FOR SHARE",
+ "INSERT INTO persistence_counters(key) SELECT k FROM unnest($1::text[]) WITH ORDINALITY AS u(k,n) ORDER BY n ON CONFLICT DO NOTHING",
+ "SELECT * FROM persistence_counters WHERE key=ANY($1::text[]) ORDER BY key COLLATE \"C\" FOR UPDATE",
+ "UPDATE persistence_requests SET publication_started=true WHERE id=$1::uuid RETURNING *",
+ "SELECT p.source_id,p.source_incarnation,s.local_path AS source_root, h.local_path AS worktree_root,b.relative_path FROM shared_skill_packs p JOIN sources s ON s.id=p.source_id AND s.incarnation=p.source_incarnation LEFT JOIN persistence_source_bindings b ON b.source_id=p.source_id AND b.source_incarnation=p.source_incarnation LEFT JOIN persistence_host_bindings h ON h.worktree_id=b.worktree_id AND h.host_id=$1::uuid",
+ "SELECT incarnation FROM sources WHERE id=$1 FOR SHARE",
+ "INSERT INTO page_write_guards(source_incarnation,slug) SELECT incarnation,$2 FROM sources WHERE id=$1 ON CONFLICT DO NOTHING",
+ "SELECT g.slug FROM page_write_guards g JOIN sources s ON s.incarnation=g.source_incarnation WHERE s.id=$1 AND g.slug=$2 FOR UPDATE OF g",
+ "SELECT id FROM pages WHERE source_id=$1 AND slug=$2 FOR UPDATE",
+ "WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.source_id=$2 ORDER BY (p.slug=$1) DESC, (p.source_id=$3) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, wd.snapshot_withdrawals, wd.snapshot_global_purges, CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb OR (wd.snapshot_global_purges->>'count')::int > 0 THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_body, CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb OR (wd.snapshot_global_purges->>'count')::int > 0 THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_timeline FROM chosen p CROSS JOIN LATERAL (SELECT COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true) ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at FROM fact_purges WHERE source_id=p.source_id AND subject=p.slug GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals, (SELECT jsonb_build_object('count',count(*),'latest',max(g.purged_at)) FROM fact_purges g WHERE g.source_id=p.source_id AND g.subject='*' ) AS snapshot_global_purges) wd",
+ "SELECT COALESCE(config->>'mirror_read_only','false')='true' AS read_only FROM sources WHERE id=$1 FOR SHARE",
+ "SELECT b.brain_id,prev.*, CASE WHEN b.brain_id IS NOT NULL THEN concat(set_config('gbrain.write_sources',$1,true), set_config('gbrain.write_request',CASE WHEN prev.s2<>'' THEN prev.s1 ELSE $2 END,true), set_config('gbrain.write_principal_kind',CASE WHEN prev.s2<>'' THEN prev.s2 ELSE $3 END,true), set_config('gbrain.write_principal_id',CASE WHEN prev.s2<>'' THEN prev.s3 ELSE $4 END,true), CASE WHEN $5::text<>'' THEN concat( set_config('gbrain.write_trust_tier',CASE WHEN (CASE prev.s4 WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END)>0 AND (CASE prev.s4 WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END)<(CASE $5::text WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) THEN prev.s4 ELSE $5::text END,true), set_config('gbrain.write_origin',CASE WHEN $6::text<>'' THEN $6::text ELSE prev.s5 END,true)) END) END AS applied FROM (SELECT COALESCE(current_setting('gbrain.write_sources',true),'') AS s0,COALESCE(current_setting('gbrain.write_request',true),'') AS s1,COALESCE(current_setting('gbrain.write_principal_kind',true),'') AS s2,COALESCE(current_setting('gbrain.write_principal_id',true),'') AS s3,COALESCE(current_setting('gbrain.write_trust_tier',true),'') AS s4,COALESCE(current_setting('gbrain.write_origin',true),'') AS s5 OFFSET 0) prev LEFT JOIN persistence_brain b ON b.singleton=1",
+ "SELECT q.*, (SELECT COALESCE(json_agg(json_build_object('enabled', b.enabled)), '[]'::json) FROM persistence_brain b WHERE b.singleton = 1) AS managed_rows, current_setting('plan_cache_mode') AS plan_mode_prev, set_config('plan_cache_mode', CASE WHEN q.coverage IS NOT NULL AND q.coverage <> 'coverage.stopped' THEN 'force_generic_plan' ELSE current_setting('plan_cache_mode') END, true) FROM (SELECT s.incarnation::text AS incarnation, s.purge_epoch, (SELECT e.event_type FROM belief_events e WHERE e.source_id = s.id AND e.subject_kind = 'coverage' AND e.subject_key = $2 AND e.source_incarnation = s.incarnation AND e.event_type <> 'coverage.restored' ORDER BY e.id DESC LIMIT 1) AS coverage, (s.purge_epoch > 0 OR EXISTS (SELECT 1 FROM fact_purges WHERE source_id = s.id) OR EXISTS (SELECT 1 FROM take_purges WHERE source_id = s.id) OR EXISTS (SELECT 1 FROM page_purges WHERE source_id = s.id)) AS purges FROM sources s WHERE s.id = $1) q",
+ "SELECT id, slug, source_path, deleted_at FROM pages WHERE source_id=$1 AND slug=$2",
+ "INSERT INTO pages (source_id, slug, type, page_kind, title, compiled_truth, timeline, frontmatter, content_hash, updated_at, effective_date, effective_date_source, import_filename, chunker_version, source_path, source_kind, source_uri, ingested_via, ingested_at, contextual_retrieval_mode, corpus_generation) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, now(), $10, $11, $12, $13::smallint, $14, $15, $16, $17, $18, $19, $20) ON CONFLICT (source_id, slug) DO UPDATE SET contextual_retrieval_mode = EXCLUDED.contextual_retrieval_mode, corpus_generation = EXCLUDED.corpus_generation, type = EXCLUDED.type, page_kind = EXCLUDED.page_kind, title = EXCLUDED.title, compiled_truth = EXCLUDED.compiled_truth, timeline = EXCLUDED.timeline, frontmatter = EXCLUDED.frontmatter, content_hash = EXCLUDED.content_hash, updated_at = now(), deleted_at = NULL, effective_date = COALESCE(EXCLUDED.effective_date, pages.effective_date), effective_date_source = COALESCE(EXCLUDED.effective_date_source, pages.effective_date_source), import_filename = COALESCE(EXCLUDED.import_filename, pages.import_filename), chunker_version = CASE WHEN pages.compiled_truth IS NOT DISTINCT FROM EXCLUDED.compiled_truth AND pages.timeline IS NOT DISTINCT FROM EXCLUDED.timeline THEN pages.chunker_version WHEN pages.chunker_version < 0 OR (CASE WHEN pages.body_storage = 'segmented' THEN pages.body_flags->>'has_protected' IS DISTINCT FROM 'false' ELSE (COALESCE(pages.compiled_truth, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->' OR COALESCE(pages.timeline, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->') END) OR COALESCE(EXCLUDED.compiled_truth, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->' OR COALESCE(EXCLUDED.timeline, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->' THEN -1 ELSE LEAST(COALESCE(pages.chunker_version, 0), 3) END, source_path = COALESCE(EXCLUDED.source_path, pages.source_path), database_only_reason = CASE WHEN EXCLUDED.source_path IS NOT NULL AND pages.database_only_reason IN ('detached', 'origin_twin') THEN NULL ELSE pages.database_only_reason END, source_kind = COALESCE(EXCLUDED.source_kind, pages.source_kind), source_uri = COALESCE(EXCLUDED.source_uri, pages.source_uri), ingested_via = COALESCE(EXCLUDED.ingested_via, pages.ingested_via), ingested_at = COALESCE(EXCLUDED.ingested_at, pages.ingested_at) RETURNING knowledge_revision, text_projection_revision, id, source_id, slug, type, title, compiled_truth, timeline, frontmatter, content_hash, created_at, updated_at, effective_date, effective_date_source, import_filename, source_kind, source_uri, ingested_via, ingested_at",
+ "DELETE FROM content_chunks WHERE page_id = (SELECT id FROM pages WHERE slug = $1 AND source_id = $2)",
+ "DELETE FROM page_aliases WHERE source_id=$1 AND slug=$2 AND origin='frontmatter'",
+ "DELETE FROM page_aliases WHERE source_id = $1 AND slug = $2 AND origin IN ('declared','subject')",
+ "SELECT key, value FROM config WHERE key IN ('search_embedding_column', 'embedding_columns', 'embedding_model')",
+ "INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, \"embedding\", model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image, embedding_pending_since, projected_byte_start, projected_byte_end) SELECT $1::int, c.chunk_index, c.chunk_text, c.chunk_source, c.embedding::vector, c.model, c.token_count, CASE WHEN c.embedding IS NULL THEN NULL ELSE now() END, CASE WHEN c.embedding IS NULL THEN NULL ELSE md5(c.chunk_text) END, c.embedding_input_hash, c.language, c.symbol_name, c.symbol_type, c.start_line, c.end_line, c.parent_symbol_path, c.doc_comment, c.symbol_name_qualified, c.modality, c.embedding_image::vector, CASE WHEN c.embedding IS NULL THEN now() ELSE NULL END, c.projected_byte_start, c.projected_byte_end FROM jsonb_to_recordset($2::text::jsonb) AS c(chunk_index int, chunk_text text, chunk_source text, embedding text, model text, token_count int, embedding_input_hash text, language text, symbol_name text, symbol_type text, start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text, modality text, embedding_image text, projected_byte_start bigint, projected_byte_end bigint) ON CONFLICT (page_id, chunk_index) DO UPDATE SET chunk_text = EXCLUDED.chunk_text, chunk_source = EXCLUDED.chunk_source, \"embedding\" = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.\"embedding\" WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.\"embedding\" WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.\"embedding\" ELSE content_chunks.\"embedding\" END, model = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.model WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.model WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.model ELSE content_chunks.model END, token_count = EXCLUDED.token_count, embedded_at = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text AND EXCLUDED.\"embedding\" IS NULL THEN NULL WHEN content_chunks.\"embedding\" IS NULL AND EXCLUDED.\"embedding\" IS NOT NULL THEN EXCLUDED.embedded_at WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_at ELSE content_chunks.embedded_at END, embedded_text_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedded_text_hash WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.embedded_text_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_text_hash ELSE content_chunks.embedded_text_hash END, embedding_input_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedding_input_hash WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.embedding_input_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedding_input_hash ELSE content_chunks.embedding_input_hash END, language = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.language ELSE COALESCE(EXCLUDED.language, content_chunks.language) END, symbol_name = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name ELSE COALESCE(EXCLUDED.symbol_name, content_chunks.symbol_name) END, symbol_type = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_type ELSE COALESCE(EXCLUDED.symbol_type, content_chunks.symbol_type) END, start_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.start_line ELSE COALESCE(EXCLUDED.start_line, content_chunks.start_line) END, end_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.end_line ELSE COALESCE(EXCLUDED.end_line, content_chunks.end_line) END, parent_symbol_path = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.parent_symbol_path ELSE COALESCE(EXCLUDED.parent_symbol_path, content_chunks.parent_symbol_path) END, doc_comment = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.doc_comment ELSE COALESCE(EXCLUDED.doc_comment, content_chunks.doc_comment) END, symbol_name_qualified = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name_qualified ELSE COALESCE(EXCLUDED.symbol_name_qualified, content_chunks.symbol_name_qualified) END, modality = EXCLUDED.modality, projected_byte_start = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.projected_byte_start ELSE COALESCE(EXCLUDED.projected_byte_start, content_chunks.projected_byte_start) END, projected_byte_end = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.projected_byte_end ELSE COALESCE(EXCLUDED.projected_byte_end, content_chunks.projected_byte_end) END, embedding_image = COALESCE(EXCLUDED.embedding_image, content_chunks.embedding_image), embedding_pending_since = CASE WHEN EXCLUDED.\"embedding\" IS NOT NULL THEN NULL WHEN content_chunks.\"embedding\" IS NULL THEN COALESCE(content_chunks.embedding_pending_since, now()) WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN now() ELSE content_chunks.embedding_pending_since END",
+ "SELECT id, slug, source_path, deleted_at FROM pages WHERE source_id=$1 AND slug=$2",
+ "SELECT local_path, config->>'slug_root_mode' AS mode FROM sources WHERE id=$1",
+ "SELECT pg_advisory_xact_lock(hashtextextended($1, 0))",
+ "SELECT slug, source_path FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND source_path=ANY($2::text[]) AND id<>$3 ORDER BY slug",
+ "UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2 AND source_path IS NULL RETURNING id",
+ "UPDATE pages SET database_only_reason=NULL WHERE source_id=$1 AND slug=$2 AND source_path=$3 AND database_only_reason='origin_twin'",
+ "UPDATE pages SET source_kind=$3,ingested_via=$4,ingested_at=$5::timestamptz WHERE source_id=$1 AND slug=$2",
+ "SELECT f.id, f.row_num, f.fact, f.visibility, f.trust_tier FROM facts f WHERE f.source_id = $1 AND f.source_markdown_slug = $2 AND f.row_num IS NOT NULL AND f.expired_at IS NULL AND (COALESCE(f.source, '') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num = f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer, fact text, visibility text) WHERE n.row_num = f.row_num AND n.fact = f.fact AND n.visibility = f.visibility) AND (CASE f.trust_tier WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) ORDER BY f.row_num FOR UPDATE",
+ "UPDATE facts f SET expired_at=COALESCE(expired_at,now()),row_num=NULL WHERE source_id=$1 AND source_markdown_slug=$2 AND row_num IS NOT NULL AND (COALESCE(f.source,'') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num=f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer,fact text,visibility text) WHERE n.row_num=f.row_num AND n.fact=f.fact AND n.visibility=f.visibility)",
+ "DELETE FROM timeline_entries t USING jsonb_to_recordset($2::text::jsonb) AS d(id integer,date date,source text,summary text,detail text,removed boolean) WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=d.id AND t.date=d.date AND t.source=d.source AND t.summary=d.summary AND t.detail=d.detail RETURNING t.date::text AS date, d.removed",
+ "UPDATE timeline_entries t SET detail=r.next FROM jsonb_to_recordset($2::text::jsonb) AS r(id integer,detail text,next text) WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=r.id AND t.detail=r.detail",
+ "SELECT k.row_num FROM takes k JOIN jsonb_to_recordset($2::text::jsonb) AS n(row_num integer,claim text,kind text,holder text) ON n.row_num=k.row_num WHERE k.page_id=$1 AND (k.claim,k.kind,k.holder) IS DISTINCT FROM (n.claim,n.kind,n.holder) ORDER BY k.row_num LIMIT $3",
+ "DELETE FROM takes WHERE page_id=$1 AND row_num=ANY($2::integer[])",
+ "WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.source_id=$2 AND p.deleted_at IS NULL ORDER BY (p.slug=$1) DESC, (p.source_id=$3) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, wd.snapshot_withdrawals, wd.snapshot_global_purges, CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb OR (wd.snapshot_global_purges->>'count')::int > 0 THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_body, CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb OR (wd.snapshot_global_purges->>'count')::int > 0 THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_timeline FROM chosen p CROSS JOIN LATERAL (SELECT COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true) ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at FROM fact_purges WHERE source_id=p.source_id AND subject=p.slug GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals, (SELECT jsonb_build_object('count',count(*),'latest',max(g.purged_at)) FROM fact_purges g WHERE g.source_id=p.source_id AND g.subject='*' ) AS snapshot_global_purges) wd",
+ "SAVEPOINT gbrain_nested_1",
+ "SELECT value FROM config WHERE key = $1 FOR SHARE",
+ "SELECT q.*, (SELECT COALESCE(json_agg(json_build_object('enabled', b.enabled)), '[]'::json) FROM persistence_brain b WHERE b.singleton = 1) AS managed_rows, current_setting('plan_cache_mode') AS plan_mode_prev, set_config('plan_cache_mode', CASE WHEN q.coverage IS NOT NULL AND q.coverage <> 'coverage.stopped' THEN 'force_generic_plan' ELSE current_setting('plan_cache_mode') END, true) FROM (SELECT s.incarnation::text AS incarnation, s.purge_epoch, (SELECT e.event_type FROM belief_events e WHERE e.source_id = s.id AND e.subject_kind = 'coverage' AND e.subject_key = $2 AND e.source_incarnation = s.incarnation AND e.event_type <> 'coverage.restored' ORDER BY e.id DESC LIMIT 1) AS coverage, (s.purge_epoch > 0 OR EXISTS (SELECT 1 FROM fact_purges WHERE source_id = s.id) OR EXISTS (SELECT 1 FROM take_purges WHERE source_id = s.id) OR EXISTS (SELECT 1 FROM page_purges WHERE source_id = s.id)) AS purges FROM sources s WHERE s.id = $1) q",
+ "DELETE FROM wanted_links w WHERE w.origin_page_id = $1 AND w.producer IN (SELECT jsonb_array_elements_text(($2::jsonb)->'producers')) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset(($2::jsonb)->'rows') AS v(producer text, ref_kind text, target_source_id text, target_ref text) WHERE v.producer = w.producer AND v.ref_kind = w.ref_kind AND v.target_source_id = w.target_source_id AND v.target_ref = w.target_ref)",
+ "SELECT from_page_id, to_page_id, link_type FROM links WHERE (origin_page_id = $1 OR (origin_page_id IS NULL AND from_page_id = $1)) AND link_type = ANY($2::text[]) UNION SELECT from_page_id, to_page_id, link_type FROM link_transitions WHERE origin_page_id = $1 UNION SELECT from_page_id, to_page_id, link_type FROM link_relationships WHERE from_page_id = $1 AND scope = 'all'",
+ "SELECT 1 FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(from_slug text, to_slug text, from_source_id text, to_source_id text) LEFT JOIN pages f ON f.slug=v.from_slug AND f.source_id=v.from_source_id AND f.deleted_at IS NULL LEFT JOIN pages t ON t.slug=v.to_slug AND t.source_id=v.to_source_id AND t.deleted_at IS NULL WHERE f.id IS NULL OR t.id IS NULL LIMIT 1",
+ "SELECT l.id, f.slug from_slug, t.slug to_slug, f.source_id from_source_id, t.source_id to_source_id, l.link_type, l.link_source, o.slug origin_slug, o.source_id origin_source_id, l.context, l.origin_field FROM links l JOIN pages f ON f.id=l.from_page_id JOIN pages t ON t.id=l.to_page_id LEFT JOIN pages o ON o.id=l.origin_page_id WHERE (l.link_source=ANY($2::text[]) OR ($3::boolean AND l.link_source IS NULL)) AND (l.origin_page_id=$1 OR (l.origin_page_id IS NULL AND l.from_page_id=$1 AND (l.link_source IN ('markdown','wikilink-resolved') OR l.link_source IS NULL)))",
+ "DELETE FROM link_transitions WHERE origin_page_id = $1 AND producer = ANY($2::text[])",
+ "SELECT from_page_id, to_page_id, link_type FROM links WHERE (origin_page_id = $1 OR (origin_page_id IS NULL AND from_page_id = $1)) AND link_type = ANY($2::text[]) UNION SELECT from_page_id, to_page_id, link_type FROM link_transitions WHERE origin_page_id = $1 UNION SELECT from_page_id, to_page_id, link_type FROM link_relationships WHERE from_page_id = $1 AND scope = 'all'",
+ "RELEASE SAVEPOINT gbrain_nested_1",
+ "WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.source_id=$2 ORDER BY (p.slug=$1) DESC, (p.source_id=$3) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, wd.snapshot_withdrawals, wd.snapshot_global_purges, CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb OR (wd.snapshot_global_purges->>'count')::int > 0 THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_body, CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb OR (wd.snapshot_global_purges->>'count')::int > 0 THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_timeline FROM chosen p CROSS JOIN LATERAL (SELECT COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true) ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at FROM fact_purges WHERE source_id=p.source_id AND subject=p.slug GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals, (SELECT jsonb_build_object('count',count(*),'latest',max(g.purged_at)) FROM fact_purges g WHERE g.source_id=p.source_id AND g.subject='*' ) AS snapshot_global_purges) wd",
+ "UPDATE pages SET chunker_version=$5, text_projection_revision=CASE WHEN knowledge_revision=$4::uuid THEN knowledge_revision ELSE text_projection_revision END, search_vector=CASE WHEN knowledge_revision=$4::uuid THEN setweight(to_tsvector('english',gbrain_fts_input(COALESCE(title,''))),'A') || setweight(to_tsvector('english',gbrain_fts_input(left($3::text,65536))),'C') ELSE search_vector END WHERE source_id=$1 AND slug=$2 RETURNING id",
+ "SELECT set_config('gbrain.write_sources',$1,true),set_config('gbrain.write_request',$2,true),set_config('gbrain.write_principal_kind',$3,true),set_config('gbrain.write_principal_id',$4,true),set_config('gbrain.write_trust_tier',$5,true),set_config('gbrain.write_origin',$6,true)",
+ "SELECT h.local_path FROM persistence_host_bindings h JOIN persistence_worktrees w ON w.id=h.worktree_id AND w.owner_host_id=h.host_id WHERE w.id=$1::uuid",
+ "SELECT value FROM config WHERE key = $1",
+ "SELECT 1 FROM chronicle_page_state WHERE source_id=$1 AND page_id=$2 AND state='extracted' AND cardinality(event_hashes) > 0 LIMIT 1",
+ "INSERT INTO persistence_effects (request_id,kind,revision,data,source_id,source_incarnation,worktree_id) SELECT $1::uuid,t.e->>'kind',$2::uuid,t.e->'data',$3,$4::uuid,$5::uuid FROM jsonb_array_elements($6::text::jsonb) WITH ORDINALITY AS t(e,n) WHERE NOT (COALESCE((t.e->>'gated')::boolean,false) AND EXISTS (SELECT 1 FROM config WHERE key IN ('auto_link',$7) AND lower(btrim(value,E' \\t\\r\\n')) IN ('false','0','no','off'))) ORDER BY t.n ON CONFLICT(request_id,kind) DO NOTHING RETURNING kind",
+ "WITH effects AS (SELECT COALESCE(SUM(octet_length(data::text)+octet_length(kind)+1024),0) AS bytes, COALESCE(bool_or(state<>'committed'),false) AS unfinished FROM persistence_effects WHERE request_id=$1::uuid), done AS (UPDATE persistence_requests SET state=$2,outcome=$3::text::jsonb, error_code=$4,error_message=$5,error_detail=COALESCE($8::text::jsonb,error_detail),completed_at=now(),updated_at=now(),claim_expires_at=NULL,blocked_reason=NULL, consumer_version=CASE WHEN $2='committed' THEN $6 ELSE consumer_version END, consumer_host_id=CASE WHEN $2='committed' THEN $7::uuid ELSE consumer_host_id END, consumer_segment_reader=CASE WHEN $2='committed' THEN true ELSE consumer_segment_reader END, published_at=CASE WHEN $2='committed' THEN now() ELSE published_at END, preparation_attempts=CASE WHEN $2='committed' THEN 0 ELSE preparation_attempts END, terminal_reservation=CASE WHEN (SELECT unfinished FROM effects) THEN terminal_reservation ELSE LEAST(terminal_reservation,$12::bigint+(SELECT bytes FROM effects)) END WHERE id=$1::uuid AND $9::bigint+(SELECT bytes FROM effects)<=terminal_reservation RETURNING *), released AS (UPDATE persistence_counters c SET outstanding_count=c.outstanding_count-1,intent_bytes=c.intent_bytes-$11, terminal_bytes=c.terminal_bytes-LEAST($13::bigint-done.terminal_reservation,c.terminal_bytes) FROM done WHERE c.key=ANY($10::text[])), clamped AS (INSERT INTO config(key,value) SELECT 'persistence.true_up.clamped',k.n::text FROM (SELECT count(*) FROM persistence_counters c, done WHERE c.key=ANY($10::text[]) AND $13::bigint-done.terminal_reservation>c.terminal_bytes) AS k(n) WHERE k.n>0 ON CONFLICT (key) DO UPDATE SET value=(CASE WHEN config.value ~ '^[0-9]+$' THEN config.value::bigint ELSE 0 END+EXCLUDED.value::bigint)::text) SELECT done.*, EXISTS (SELECT 1 FROM fact_purges WHERE source_id=done.source_id) AS purge_has_facts, EXISTS (SELECT 1 FROM page_purges WHERE source_id=done.source_id) AS purge_has_pages FROM done",
+ "COMMIT"
+ ],
+ "canonical_import": [
+ "BEGIN",
+ "SELECT set_config('gbrain.persistence_protocol','2',true),set_config('synchronous_commit','on',true), set_config('lock_timeout',$1,true),set_config('statement_timeout',$2,true),(SELECT brain_id::text FROM persistence_brain WHERE singleton=1 FOR SHARE) AS brain",
+ "SELECT owner_host_id,owner_epoch,state FROM persistence_worktrees WHERE id=$1::uuid FOR SHARE",
+ "SELECT s.source_id,s.source_incarnation,s.worktree_id,s.relative_path, s.topology_generation::text AS topology_generation,w.owner_host_id,w.owner_epoch::text AS owner_epoch,w.state, h.local_path,h.coordination_path,h.git_durability FROM persistence_source_bindings s JOIN persistence_worktrees w ON w.id=s.worktree_id LEFT JOIN persistence_host_bindings h ON h.worktree_id=w.id AND h.host_id=$2::uuid WHERE s.source_id=$1",
+ "SELECT id FROM sources WHERE id=$1 FOR UPDATE",
+ "SELECT incarnation,archived FROM sources WHERE id=$1 FOR SHARE",
+ "SELECT lane,revoked_at,grant_ceiling FROM persistence_local_writers WHERE id=$1::uuid FOR SHARE",
+ "INSERT INTO persistence_counters(key) SELECT k FROM unnest($1::text[]) WITH ORDINALITY AS u(k,n) ORDER BY n ON CONFLICT DO NOTHING",
+ "SELECT * FROM persistence_counters WHERE key=ANY($1::text[]) ORDER BY key COLLATE \"C\" FOR UPDATE",
+ "SELECT * FROM persistence_requests WHERE id=$1::uuid FOR UPDATE",
+ "SELECT p.source_id,p.source_incarnation,s.local_path AS source_root, h.local_path AS worktree_root,b.relative_path FROM shared_skill_packs p JOIN sources s ON s.id=p.source_id AND s.incarnation=p.source_incarnation LEFT JOIN persistence_source_bindings b ON b.source_id=p.source_id AND b.source_incarnation=p.source_incarnation LEFT JOIN persistence_host_bindings h ON h.worktree_id=b.worktree_id AND h.host_id=$1::uuid",
+ "SELECT incarnation FROM sources WHERE id=$1 FOR SHARE",
+ "INSERT INTO page_write_guards(source_incarnation,slug) SELECT incarnation,$2 FROM sources WHERE id=$1 ON CONFLICT DO NOTHING",
+ "SELECT g.slug FROM page_write_guards g JOIN sources s ON s.incarnation=g.source_incarnation WHERE s.id=$1 AND g.slug=$2 FOR UPDATE OF g",
+ "SELECT id FROM pages WHERE source_id=$1 AND slug=$2 FOR UPDATE",
+ "WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.source_id=$2 ORDER BY (p.slug=$1) DESC, (p.source_id=$3) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, wd.snapshot_withdrawals, wd.snapshot_global_purges, CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb OR (wd.snapshot_global_purges->>'count')::int > 0 THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_body, CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb OR (wd.snapshot_global_purges->>'count')::int > 0 THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_timeline FROM chosen p CROSS JOIN LATERAL (SELECT COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true) ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at FROM fact_purges WHERE source_id=p.source_id AND subject=p.slug GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals, (SELECT jsonb_build_object('count',count(*),'latest',max(g.purged_at)) FROM fact_purges g WHERE g.source_id=p.source_id AND g.subject='*' ) AS snapshot_global_purges) wd",
+ "SELECT enabled FROM persistence_brain WHERE singleton=1 FOR SHARE",
+ "SELECT local_path FROM sources WHERE id=$1 FOR SHARE",
+ "SELECT s.source_id,s.source_incarnation,s.worktree_id,s.relative_path, s.topology_generation::text AS topology_generation,w.owner_host_id,w.owner_epoch::text AS owner_epoch,w.state, h.local_path,h.coordination_path,h.git_durability FROM persistence_source_bindings s JOIN persistence_worktrees w ON w.id=s.worktree_id LEFT JOIN persistence_host_bindings h ON h.worktree_id=w.id AND h.host_id=$2::uuid WHERE s.source_id=$1",
+ "SELECT id,slug,source_path,deleted_at FROM pages WHERE source_id=$1 AND source_path=ANY($2::text[])",
+ "SELECT b.brain_id,prev.*, CASE WHEN b.brain_id IS NOT NULL THEN concat(set_config('gbrain.write_sources',$1,true), set_config('gbrain.write_request',CASE WHEN prev.s2<>'' THEN prev.s1 ELSE $2 END,true), set_config('gbrain.write_principal_kind',CASE WHEN prev.s2<>'' THEN prev.s2 ELSE $3 END,true), set_config('gbrain.write_principal_id',CASE WHEN prev.s2<>'' THEN prev.s3 ELSE $4 END,true), CASE WHEN $5::text<>'' THEN concat( set_config('gbrain.write_trust_tier',CASE WHEN (CASE prev.s4 WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END)>0 AND (CASE prev.s4 WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END)<(CASE $5::text WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) THEN prev.s4 ELSE $5::text END,true), set_config('gbrain.write_origin',CASE WHEN $6::text<>'' THEN $6::text ELSE prev.s5 END,true)) END) END AS applied FROM (SELECT COALESCE(current_setting('gbrain.write_sources',true),'') AS s0,COALESCE(current_setting('gbrain.write_request',true),'') AS s1,COALESCE(current_setting('gbrain.write_principal_kind',true),'') AS s2,COALESCE(current_setting('gbrain.write_principal_id',true),'') AS s3,COALESCE(current_setting('gbrain.write_trust_tier',true),'') AS s4,COALESCE(current_setting('gbrain.write_origin',true),'') AS s5 OFFSET 0) prev LEFT JOIN persistence_brain b ON b.singleton=1",
+ "SELECT q.*, (SELECT COALESCE(json_agg(json_build_object('enabled', b.enabled)), '[]'::json) FROM persistence_brain b WHERE b.singleton = 1) AS managed_rows, current_setting('plan_cache_mode') AS plan_mode_prev, set_config('plan_cache_mode', CASE WHEN q.coverage IS NOT NULL AND q.coverage <> 'coverage.stopped' THEN 'force_generic_plan' ELSE current_setting('plan_cache_mode') END, true) FROM (SELECT s.incarnation::text AS incarnation, s.purge_epoch, (SELECT e.event_type FROM belief_events e WHERE e.source_id = s.id AND e.subject_kind = 'coverage' AND e.subject_key = $2 AND e.source_incarnation = s.incarnation AND e.event_type <> 'coverage.restored' ORDER BY e.id DESC LIMIT 1) AS coverage, (s.purge_epoch > 0 OR EXISTS (SELECT 1 FROM fact_purges WHERE source_id = s.id) OR EXISTS (SELECT 1 FROM take_purges WHERE source_id = s.id) OR EXISTS (SELECT 1 FROM page_purges WHERE source_id = s.id)) AS purges FROM sources s WHERE s.id = $1) q",
+ "SELECT key,value FROM config WHERE key IN ('search_embedding_column','embedding_columns','embedding_model','embedding_dimensions','contextual_retrieval.mode') ORDER BY key",
+ "SELECT c.chunk_index, c.embedding_input_hash, p.contextual_retrieval_mode, c.embedding_image IS NULL AND c.embedding_multimodal IS NULL AND c.embedded_text_hash = md5(c.chunk_text) AS text_only, c.embedding IS NULL AND c.embedding_image IS NULL AND c.embedding_multimodal IS NULL AND c.embedding_input_hash IS NULL AND c.embedded_text_hash IS NULL AS unembedded FROM content_chunks c JOIN pages p ON p.id = c.page_id WHERE p.source_id = $1 AND p.slug = $2",
+ "SELECT key, value FROM config WHERE key IN ('search_embedding_column', 'embedding_columns')",
+ "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.projected_byte_start, cc.projected_byte_end, (cc.\"embedding\" IS NULL) AS embedding_is_null , cc.\"embedding\" AS embedding FROM content_chunks cc JOIN pages p ON p.id = cc.page_id LEFT JOIN page_body_manifest m ON cc.occurrence_id IS NOT NULL AND m.page_id = cc.page_id AND m.occurrence_id = cc.occurrence_id AND m.staging_id IS NULL AND m.gen_from <= p.body_generation AND (m.gen_to IS NULL OR m.gen_to > p.body_generation) WHERE p.slug = $1 AND p.source_id = $2 AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE AND (cc.body_generation IS NULL OR cc.body_generation <= p.body_generation)) AND p.chunker_version >= 4 ORDER BY m.byte_start, cc.local_ordinal, cc.chunk_index",
+ "INSERT INTO page_versions (page_id,compiled_truth,frontmatter,knowledge_revision,timeline,title,type,tags,is_deleted,source_path) VALUES ($1,$2,$3::text::jsonb,$4::uuid,$5,$6,$7,$8::text::jsonb,$9,$10) RETURNING *",
+ "SELECT id, slug, source_path, deleted_at FROM pages WHERE source_id=$1 AND slug=$2",
+ "SELECT local_path, config->>'slug_root_mode' AS mode FROM sources WHERE id=$1",
+ "INSERT INTO pages (source_id, slug, type, page_kind, title, compiled_truth, timeline, frontmatter, content_hash, updated_at, effective_date, effective_date_source, import_filename, chunker_version, source_path, source_kind, source_uri, ingested_via, ingested_at, contextual_retrieval_mode, corpus_generation) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, now(), $10, $11, $12, $13::smallint, $14, $15, $16, $17, $18, $19, $20) ON CONFLICT (source_id, slug) DO UPDATE SET contextual_retrieval_mode = EXCLUDED.contextual_retrieval_mode, corpus_generation = EXCLUDED.corpus_generation, type = EXCLUDED.type, page_kind = EXCLUDED.page_kind, title = EXCLUDED.title, compiled_truth = EXCLUDED.compiled_truth, timeline = EXCLUDED.timeline, frontmatter = EXCLUDED.frontmatter, content_hash = EXCLUDED.content_hash, updated_at = now(), deleted_at = NULL, effective_date = COALESCE(EXCLUDED.effective_date, pages.effective_date), effective_date_source = COALESCE(EXCLUDED.effective_date_source, pages.effective_date_source), import_filename = COALESCE(EXCLUDED.import_filename, pages.import_filename), chunker_version = CASE WHEN pages.compiled_truth IS NOT DISTINCT FROM EXCLUDED.compiled_truth AND pages.timeline IS NOT DISTINCT FROM EXCLUDED.timeline THEN pages.chunker_version WHEN pages.chunker_version < 0 OR (CASE WHEN pages.body_storage = 'segmented' THEN pages.body_flags->>'has_protected' IS DISTINCT FROM 'false' ELSE (COALESCE(pages.compiled_truth, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->' OR COALESCE(pages.timeline, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->') END) OR COALESCE(EXCLUDED.compiled_truth, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->' OR COALESCE(EXCLUDED.timeline, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->' THEN -1 ELSE LEAST(COALESCE(pages.chunker_version, 0), 3) END, source_path = COALESCE(EXCLUDED.source_path, pages.source_path), database_only_reason = CASE WHEN EXCLUDED.source_path IS NOT NULL AND pages.database_only_reason IN ('detached', 'origin_twin') THEN NULL ELSE pages.database_only_reason END, source_kind = COALESCE(EXCLUDED.source_kind, pages.source_kind), source_uri = COALESCE(EXCLUDED.source_uri, pages.source_uri), ingested_via = COALESCE(EXCLUDED.ingested_via, pages.ingested_via), ingested_at = COALESCE(EXCLUDED.ingested_at, pages.ingested_at) RETURNING knowledge_revision, text_projection_revision, id, source_id, slug, type, title, compiled_truth, timeline, frontmatter, content_hash, created_at, updated_at, effective_date, effective_date_source, import_filename, source_kind, source_uri, ingested_via, ingested_at",
+ "DELETE FROM content_chunks WHERE page_id = (SELECT id FROM pages WHERE slug = $1 AND source_id = $2)",
+ "DELETE FROM page_aliases WHERE source_id=$1 AND slug=$2 AND origin='frontmatter'",
+ "DELETE FROM page_aliases WHERE source_id = $1 AND slug = $2 AND origin IN ('declared','subject')",
+ "SELECT key, value FROM config WHERE key IN ('search_embedding_column', 'embedding_columns', 'embedding_model')",
+ "INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, \"embedding\", model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image, embedding_pending_since, projected_byte_start, projected_byte_end) SELECT $1::int, c.chunk_index, c.chunk_text, c.chunk_source, c.embedding::vector, c.model, c.token_count, CASE WHEN c.embedding IS NULL THEN NULL ELSE now() END, CASE WHEN c.embedding IS NULL THEN NULL ELSE md5(c.chunk_text) END, c.embedding_input_hash, c.language, c.symbol_name, c.symbol_type, c.start_line, c.end_line, c.parent_symbol_path, c.doc_comment, c.symbol_name_qualified, c.modality, c.embedding_image::vector, CASE WHEN c.embedding IS NULL THEN now() ELSE NULL END, c.projected_byte_start, c.projected_byte_end FROM jsonb_to_recordset($2::text::jsonb) AS c(chunk_index int, chunk_text text, chunk_source text, embedding text, model text, token_count int, embedding_input_hash text, language text, symbol_name text, symbol_type text, start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text, modality text, embedding_image text, projected_byte_start bigint, projected_byte_end bigint) ON CONFLICT (page_id, chunk_index) DO UPDATE SET chunk_text = EXCLUDED.chunk_text, chunk_source = EXCLUDED.chunk_source, \"embedding\" = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.\"embedding\" WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.\"embedding\" WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.\"embedding\" ELSE content_chunks.\"embedding\" END, model = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.model WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.model WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.model ELSE content_chunks.model END, token_count = EXCLUDED.token_count, embedded_at = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text AND EXCLUDED.\"embedding\" IS NULL THEN NULL WHEN content_chunks.\"embedding\" IS NULL AND EXCLUDED.\"embedding\" IS NOT NULL THEN EXCLUDED.embedded_at WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_at ELSE content_chunks.embedded_at END, embedded_text_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedded_text_hash WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.embedded_text_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_text_hash ELSE content_chunks.embedded_text_hash END, embedding_input_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedding_input_hash WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.embedding_input_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedding_input_hash ELSE content_chunks.embedding_input_hash END, language = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.language ELSE COALESCE(EXCLUDED.language, content_chunks.language) END, symbol_name = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name ELSE COALESCE(EXCLUDED.symbol_name, content_chunks.symbol_name) END, symbol_type = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_type ELSE COALESCE(EXCLUDED.symbol_type, content_chunks.symbol_type) END, start_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.start_line ELSE COALESCE(EXCLUDED.start_line, content_chunks.start_line) END, end_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.end_line ELSE COALESCE(EXCLUDED.end_line, content_chunks.end_line) END, parent_symbol_path = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.parent_symbol_path ELSE COALESCE(EXCLUDED.parent_symbol_path, content_chunks.parent_symbol_path) END, doc_comment = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.doc_comment ELSE COALESCE(EXCLUDED.doc_comment, content_chunks.doc_comment) END, symbol_name_qualified = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name_qualified ELSE COALESCE(EXCLUDED.symbol_name_qualified, content_chunks.symbol_name_qualified) END, modality = EXCLUDED.modality, projected_byte_start = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.projected_byte_start ELSE COALESCE(EXCLUDED.projected_byte_start, content_chunks.projected_byte_start) END, projected_byte_end = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.projected_byte_end ELSE COALESCE(EXCLUDED.projected_byte_end, content_chunks.projected_byte_end) END, embedding_image = COALESCE(EXCLUDED.embedding_image, content_chunks.embedding_image), embedding_pending_since = CASE WHEN EXCLUDED.\"embedding\" IS NOT NULL THEN NULL WHEN content_chunks.\"embedding\" IS NULL THEN COALESCE(content_chunks.embedding_pending_since, now()) WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN now() ELSE content_chunks.embedding_pending_since END",
+ "UPDATE pages SET database_only_reason=NULL WHERE source_id=$1 AND slug=$2 AND database_only_reason='unbound_source'",
+ "WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.source_id=$2 ORDER BY (p.slug=$1) DESC, (p.source_id=$3) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, wd.snapshot_withdrawals, wd.snapshot_global_purges, CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb OR (wd.snapshot_global_purges->>'count')::int > 0 THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_body, CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb OR (wd.snapshot_global_purges->>'count')::int > 0 THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_timeline FROM chosen p CROSS JOIN LATERAL (SELECT COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true) ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at FROM fact_purges WHERE source_id=p.source_id AND subject=p.slug GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals, (SELECT jsonb_build_object('count',count(*),'latest',max(g.purged_at)) FROM fact_purges g WHERE g.source_id=p.source_id AND g.subject='*' ) AS snapshot_global_purges) wd",
+ "SELECT f.id, f.row_num, f.fact, f.visibility, f.trust_tier FROM facts f WHERE f.source_id = $1 AND f.source_markdown_slug = $2 AND f.row_num IS NOT NULL AND f.expired_at IS NULL AND (COALESCE(f.source, '') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num = f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer, fact text, visibility text) WHERE n.row_num = f.row_num AND n.fact = f.fact AND n.visibility = f.visibility) AND (CASE f.trust_tier WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) ORDER BY f.row_num FOR UPDATE",
+ "UPDATE facts f SET expired_at=COALESCE(expired_at,now()),row_num=NULL WHERE source_id=$1 AND source_markdown_slug=$2 AND row_num IS NOT NULL AND (COALESCE(f.source,'') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num=f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer,fact text,visibility text) WHERE n.row_num=f.row_num AND n.fact=f.fact AND n.visibility=f.visibility)",
+ "DELETE FROM timeline_entries t USING jsonb_to_recordset($2::text::jsonb) AS d(id integer,date date,source text,summary text,detail text,removed boolean) WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=d.id AND t.date=d.date AND t.source=d.source AND t.summary=d.summary AND t.detail=d.detail RETURNING t.date::text AS date, d.removed",
+ "UPDATE timeline_entries t SET detail=r.next FROM jsonb_to_recordset($2::text::jsonb) AS r(id integer,detail text,next text) WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=r.id AND t.detail=r.detail",
+ "SELECT k.row_num FROM takes k JOIN jsonb_to_recordset($2::text::jsonb) AS n(row_num integer,claim text,kind text,holder text) ON n.row_num=k.row_num WHERE k.page_id=$1 AND (k.claim,k.kind,k.holder) IS DISTINCT FROM (n.claim,n.kind,n.holder) ORDER BY k.row_num LIMIT $3",
+ "DELETE FROM takes WHERE page_id=$1 AND row_num=ANY($2::integer[])",
+ "UPDATE pages SET chunker_version=$5, text_projection_revision=CASE WHEN knowledge_revision=$4::uuid THEN knowledge_revision ELSE text_projection_revision END, search_vector=CASE WHEN knowledge_revision=$4::uuid THEN setweight(to_tsvector('english',gbrain_fts_input(COALESCE(title,''))),'A') || setweight(to_tsvector('english',gbrain_fts_input(left($3::text,65536))),'C') ELSE search_vector END WHERE source_id=$1 AND slug=$2 RETURNING id",
+ "SELECT COALESCE((completed_keys->0->>'count')::int,0) AS count FROM op_checkpoints WHERE op=$1 AND fingerprint=$2",
+ "INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb) ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()",
+ "SAVEPOINT gbrain_pass_stamp_fold",
+ "SELECT 1 FROM gbrain_cycle_locks WHERE id=$1 AND acquisition_token=$2::uuid AND ttl_expires_at > now() FOR SHARE",
+ "SELECT completed_keys->0 AS value, updated_at FROM op_checkpoints WHERE op=$1 AND fingerprint=$2",
+ "(SELECT r.request_id::text AS request_id FROM persistence_requests r WHERE r.worktree_id=$1::uuid AND r.recovery IS NOT NULL LIMIT 1) UNION ALL (SELECT r.request_id::text FROM persistence_requests r WHERE r.worktree_id=$1::uuid AND r.state IN ('queued','running','recovering') AND r.request_id<>$2::uuid AND r.intent->>'kind' IN ('managed_sync_import','managed_sync_delete','managed_sync_checkpoint') LIMIT 1) LIMIT 1",
+ "SELECT GREATEST((SELECT max(sequence) FROM persistence_requests WHERE worktree_id=$1::uuid), (SELECT max(sequence) FROM persistence_requests WHERE worktree_id IS NULL AND source_id=$2 AND source_incarnation=$3::uuid))::text AS hwm",
+ "(SELECT 'r:'||request_id::text AS id FROM persistence_requests WHERE state IN ('queued','running','recovering') AND (worktree_id=$1::uuid OR worktree_id IS NULL AND source_id=$4 AND source_incarnation=$5::uuid) AND request_id IS DISTINCT FROM $2::uuid LIMIT $3) UNION ALL (SELECT 'e:'||e.id::text FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id WHERE r.worktree_id=$1::uuid AND e.kind='git' AND e.state IN ('queued','running') LIMIT $3)",
+ "SELECT last_commit, config->>'slug_root_mode' AS mode FROM sources WHERE id=$1 AND incarnation=$2::uuid",
+ "WITH x AS MATERIALIZED (SELECT txid_snapshot_xmin(txid_current_snapshot()) AS now_lo, txid_snapshot_xmax(txid_current_snapshot()) AS hi, age(($4::bigint % 4294967296)::text::xid) AS lo_age), pg AS (SELECT count(*) FILTER (WHERE p.source_path IS NOT NULL)::int AS n, COALESCE(jsonb_agg(jsonb_build_array(p.id::text, EXISTS (SELECT 1 FROM persistence_requests r WHERE r.id=p.revision_write_request_id AND r.source_id=$1 AND (r.id=$6::uuid OR r.state='committed' AND r.intent->>'passId'=$5 AND r.outcome->>'revision'=p.knowledge_revision::text)), p.knowledge_revision::text)) FILTER (WHERE NOT age(p.xmin) > x.lo_age), '[]'::jsonb) AS changed FROM pages p, x WHERE p.source_id=$1), oc AS (SELECT o.op, count(*)::int AS n, jsonb_agg(jsonb_build_array(o.op, o.fingerprint, o.completed_keys->0->>'revision', o.completed_keys->0->>'run_id')) FILTER (WHERE NOT age(o.xmin) > x.lo_age) AS changed FROM op_checkpoints o, x WHERE o.op = ANY($2::text[]) AND (o.fingerprint = $3 OR starts_with(o.fingerprint, $3 || ':')) GROUP BY o.op) SELECT x.now_lo::text AS xmin, (x.hi - $4::bigint)::float8 AS span, pg.n AS pages, pg.changed AS pages_changed, (SELECT COALESCE(jsonb_object_agg(op, n), '{}'::jsonb) FROM oc) AS ops, (SELECT COALESCE(jsonb_agg(c), '[]'::jsonb) FROM oc, jsonb_array_elements(COALESCE(oc.changed, '[]'::jsonb)) c) AS ops_changed, (SELECT COALESCE(jsonb_agg(fingerprint), '[]'::jsonb) FROM op_checkpoints WHERE op='sync-hold' AND starts_with(fingerprint, $3 || ':')) AS holds FROM x, pg",
+ "SELECT 1 FROM persistence_requests r WHERE r.source_id=$1 AND r.slug='__managed_sync_checkpoint__' AND r.intent IS NOT NULL AND NOT r.compacted AND r.operation='submit_job' AND r.intent->>'kind'='managed_sync_checkpoint' AND r.state IN ('failed','conflict','cancelled') AND NOT EXISTS (SELECT 1 FROM persistence_requests c WHERE (c.source_id=r.source_id AND c.slug=r.slug AND c.sequence>r.sequence AND ( (c.digest=r.digest AND c.state IN ('committed','failed','queued','running','recovering')) OR (c.state IN ('committed','queued','running','recovering') AND (c.operation IN ('delete_page','purge_page') OR r.operation='put_page')) OR (r.slug='__managed_sync_checkpoint__' AND r.operation='submit_job' AND c.state='committed' AND c.operation='submit_job' AND COALESCE((SELECT k.intent->>'kind' FROM persistence_requests k WHERE k.id=r.id),'managed_sync_checkpoint')='managed_sync_checkpoint' AND COALESCE(c.intent->>'kind','managed_sync_checkpoint')='managed_sync_checkpoint') OR (r.operation='put_page' AND c.state='failed' AND c.operation='put_page' AND COALESCE(NOT (c.intent ? 'kind'), false))))) LIMIT 1",
+ "SELECT p.id, p.slug, p.source_path, p.knowledge_revision::text AS revision, p.deleted_at IS NOT NULL AS deleted, p.revision_write_request_id::text AS request_id, c.fingerprint IS NOT NULL AS has_record, c.origin IS NOT DISTINCT FROM p.source_path AS rec_origin_same, CASE WHEN c.origin IS DISTINCT FROM p.source_path THEN c.origin END AS rec_origin, c.blob_oid AS rec_blob_oid, c.disk_blob_oid IS NOT DISTINCT FROM c.blob_oid AS rec_disk_same, CASE WHEN c.disk_blob_oid IS DISTINCT FROM c.blob_oid THEN c.disk_blob_oid END AS rec_disk_blob_oid, c.revision IS NULL AS rec_revision_null, NULLIF(c.revision, p.knowledge_revision::text) AS rec_revision, CASE WHEN c.parser IS DISTINCT FROM $4::jsonb THEN c.parser::text END AS rec_parser, c.parser = $4::jsonb AS rec_parser_expected, c.full_episode AS rec_full_episode, c.working AS rec_working FROM pages p LEFT JOIN (SELECT fingerprint, completed_keys->0->>'origin' AS origin, completed_keys->0->>'blob_oid' AS blob_oid, completed_keys->0->>'disk_blob_oid' AS disk_blob_oid, completed_keys->0->>'revision' AS revision, completed_keys->0->'parser' AS parser, completed_keys->0->>'full_episode' AS full_episode, (completed_keys->0->'working')::text AS working FROM op_checkpoints WHERE op=$2) c ON c.fingerprint=$3||p.id::text WHERE p.source_id=$1 AND p.source_path IS NOT NULL AND p.id = ANY($5::bigint[]) ORDER BY p.id",
+ "SELECT p.id::text AS id, r.intent->>'level' AS level, r.intent->>'path' AS path FROM pages p JOIN persistence_requests r ON r.id=p.revision_write_request_id WHERE p.source_id=$1 AND p.id = ANY($2::bigint[])",
+ "UPDATE sources SET last_commit=$3,last_sync_at=now(), config=jsonb_set(( WITH RECURSIVE root_layers(value, depth) AS ( SELECT COALESCE(config, '{}'::jsonb), 0 UNION ALL SELECT (value #>> '{}')::jsonb, depth + 1 FROM root_layers WHERE depth < 10 AND jsonb_typeof(value) = 'string' AND (value #>> '{}') IS JSON ), root(value) AS ( SELECT value FROM root_layers ORDER BY depth DESC LIMIT 1 ), fragment_seeds(ordinality, value) AS ( SELECT 0::bigint, value FROM root WHERE jsonb_typeof(value) = 'object' UNION ALL SELECT item.ordinality, item.value FROM root, LATERAL jsonb_array_elements( CASE WHEN jsonb_typeof(root.value) = 'array' THEN root.value ELSE '[]'::jsonb END ) WITH ORDINALITY AS item(value, ordinality) ), fragment_layers(ordinality, value, depth) AS ( SELECT ordinality, value, 0 FROM fragment_seeds UNION ALL SELECT ordinality, (value #>> '{}')::jsonb, depth + 1 FROM fragment_layers WHERE depth < 10 AND jsonb_typeof(value) = 'string' AND (value #>> '{}') IS JSON ), fragments AS ( SELECT DISTINCT ON (ordinality) ordinality, value FROM fragment_layers ORDER BY ordinality, depth DESC ) SELECT COALESCE( jsonb_object_agg(entry.key, entry.value ORDER BY fragments.ordinality), '{}'::jsonb ) FROM fragments CROSS JOIN LATERAL jsonb_each( CASE WHEN jsonb_typeof(fragments.value) = 'object' THEN fragments.value ELSE '{}'::jsonb END ) AS entry(key, value) ),'{slug_root_mode}',to_jsonb(CASE WHEN $6::boolean THEN COALESCE(config->>'slug_root_mode',$5::text) ELSE $5::text END)), newest_content_at=(SELECT MAX(updated_at) FROM pages WHERE source_id=$1 AND deleted_at IS NULL) WHERE id=$1 AND incarnation=$2::uuid AND (last_commit IS NOT DISTINCT FROM $4 OR last_commit=$3) AND ($6::boolean OR config->>'slug_root_mode' IS NULL OR config->>'slug_root_mode'=$5) RETURNING id",
+ "INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES ($1, $2, jsonb_build_array(jsonb_strip_nulls(jsonb_build_object('run_id',$3::text,'at',now(),'changed',$4::int,'extract',$5::boolean,'since',$6::text))), now()) ON CONFLICT (op,fingerprint) DO UPDATE SET updated_at=now(), completed_keys=CASE WHEN jsonb_array_length(op_checkpoints.completed_keys)>=16 THEN (op_checkpoints.completed_keys-0)||EXCLUDED.completed_keys ELSE op_checkpoints.completed_keys||EXCLUDED.completed_keys END",
+ "SELECT intent->>'path' AS path, outcome->'fences_normalized' AS fences FROM persistence_requests WHERE worktree_id=$1::uuid AND source_id=$2 AND sequence > $3::bigint AND state='committed' AND intent->>'kind'='managed_sync_import' AND intent->>'passId' IS NOT NULL AND jsonb_typeof(outcome->'fences_normalized')='array' ORDER BY sequence",
+ "INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES($1,$2,jsonb_build_array($3::text::jsonb),now()) ON CONFLICT (op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys, updated_at=now() WHERE $4::boolean OR op_checkpoints.completed_keys->0->>'lease_token'=$5 RETURNING 1",
+ "RELEASE SAVEPOINT gbrain_pass_stamp_fold",
+ "SELECT set_config('gbrain.write_sources',$1,true),set_config('gbrain.write_request',$2,true),set_config('gbrain.write_principal_kind',$3,true),set_config('gbrain.write_principal_id',$4,true),set_config('gbrain.write_trust_tier',$5,true),set_config('gbrain.write_origin',$6,true)",
+ "SELECT value FROM config WHERE key = $1",
+ "SELECT 1 FROM chronicle_page_state WHERE source_id=$1 AND page_id=$2 AND state='extracted' AND cardinality(event_hashes) > 0 LIMIT 1",
+ "WITH effects AS (SELECT COALESCE(SUM(octet_length(data::text)+octet_length(kind)+1024),0) AS bytes, COALESCE(bool_or(state<>'committed'),false) AS unfinished FROM persistence_effects WHERE request_id=$1::uuid), done AS (UPDATE persistence_requests SET state=$2,outcome=$3::text::jsonb, error_code=$4,error_message=$5,error_detail=COALESCE($8::text::jsonb,error_detail),completed_at=now(),updated_at=now(),claim_expires_at=NULL,blocked_reason=NULL, consumer_version=CASE WHEN $2='committed' THEN $6 ELSE consumer_version END, consumer_host_id=CASE WHEN $2='committed' THEN $7::uuid ELSE consumer_host_id END, consumer_segment_reader=CASE WHEN $2='committed' THEN true ELSE consumer_segment_reader END, published_at=CASE WHEN $2='committed' THEN now() ELSE published_at END, preparation_attempts=CASE WHEN $2='committed' THEN 0 ELSE preparation_attempts END, terminal_reservation=CASE WHEN (SELECT unfinished FROM effects) THEN terminal_reservation ELSE LEAST(terminal_reservation,$12::bigint+(SELECT bytes FROM effects)) END WHERE id=$1::uuid AND $9::bigint+(SELECT bytes FROM effects)<=terminal_reservation RETURNING *), released AS (UPDATE persistence_counters c SET outstanding_count=c.outstanding_count-1,intent_bytes=c.intent_bytes-$11, terminal_bytes=c.terminal_bytes-LEAST($13::bigint-done.terminal_reservation,c.terminal_bytes) FROM done WHERE c.key=ANY($10::text[])), clamped AS (INSERT INTO config(key,value) SELECT 'persistence.true_up.clamped',k.n::text FROM (SELECT count(*) FROM persistence_counters c, done WHERE c.key=ANY($10::text[]) AND $13::bigint-done.terminal_reservation>c.terminal_bytes) AS k(n) WHERE k.n>0 ON CONFLICT (key) DO UPDATE SET value=(CASE WHEN config.value ~ '^[0-9]+$' THEN config.value::bigint ELSE 0 END+EXCLUDED.value::bigint)::text) SELECT done.*, EXISTS (SELECT 1 FROM fact_purges WHERE source_id=done.source_id) AS purge_has_facts, EXISTS (SELECT 1 FROM page_purges WHERE source_id=done.source_id) AS purge_has_pages FROM done",
+ "COMMIT"
+ ]
+ },
+ "postgres": {
+ "put_page": [
+ "begin",
+ "SELECT set_config('idle_in_transaction_session_timeout',$3,true),set_config('gbrain.persistence_protocol','2',true),set_config('synchronous_commit','on',true), set_config('lock_timeout',$1,true),set_config('statement_timeout',$2,true),(SELECT brain_id::text FROM persistence_brain WHERE singleton=1 FOR SHARE) AS brain",
+ "SELECT owner_host_id,owner_epoch,state FROM persistence_worktrees WHERE id=$1::uuid FOR SHARE",
+ "SELECT s.source_id,s.source_incarnation,s.worktree_id,s.relative_path, s.topology_generation::text AS topology_generation,w.owner_host_id,w.owner_epoch::text AS owner_epoch,w.state, h.local_path,h.coordination_path,h.git_durability FROM persistence_source_bindings s JOIN persistence_worktrees w ON w.id=s.worktree_id LEFT JOIN persistence_host_bindings h ON h.worktree_id=w.id AND h.host_id=$2::uuid WHERE s.source_id=$1",
+ "UPDATE persistence_requests r SET publication_started=true FROM unnest($1::uuid[],$2::uuid[]) AS t(id,token) WHERE r.id=t.id AND r.execution_token=t.token AND r.state='running' RETURNING r.id",
+ "SELECT COALESCE(config->>'mirror_read_only','false')='true' AS read_only FROM sources WHERE id=$1 FOR SHARE",
+ "SELECT incarnation FROM sources WHERE id=$1 FOR SHARE",
+ "INSERT INTO page_write_guards(source_incarnation,slug) VALUES ($1::uuid,$2) ON CONFLICT DO NOTHING",
+ "SELECT slug FROM page_write_guards WHERE source_incarnation=$1::uuid AND slug=$2 FOR UPDATE",
+ "SELECT id FROM pages WHERE source_id=$1 AND slug=$2 FOR UPDATE",
+ "SELECT h.local_path FROM persistence_host_bindings h JOIN persistence_worktrees w ON w.id=h.worktree_id AND w.owner_host_id=h.host_id WHERE w.id=$1::uuid",
+ "SELECT incarnation,archived FROM sources WHERE id=$1 FOR SHARE",
+ "SELECT lane,revoked_at,grant_ceiling FROM persistence_local_writers WHERE id=$1::uuid FOR SHARE",
+ "SELECT p.source_id,p.source_incarnation,s.local_path AS source_root, h.local_path AS worktree_root,b.relative_path FROM shared_skill_packs p JOIN sources s ON s.id=p.source_id AND s.incarnation=p.source_incarnation LEFT JOIN persistence_source_bindings b ON b.source_id=p.source_id AND b.source_incarnation=p.source_incarnation LEFT JOIN persistence_host_bindings h ON h.worktree_id=b.worktree_id AND h.host_id=$1::uuid",
+ "WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.source_id=$2 ORDER BY (p.slug=$1) DESC, (p.source_id=$3) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, wd.snapshot_withdrawals, wd.snapshot_global_purges, CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb OR (wd.snapshot_global_purges->>'count')::int > 0 THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_body, CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb OR (wd.snapshot_global_purges->>'count')::int > 0 THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_timeline FROM chosen p CROSS JOIN LATERAL (SELECT COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true) ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at FROM fact_purges WHERE source_id=p.source_id AND subject=p.slug GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals, (SELECT jsonb_build_object('count',count(*),'latest',max(g.pur",
+ "SELECT b.brain_id,prev.*, CASE WHEN b.brain_id IS NOT NULL THEN concat(set_config('gbrain.write_sources',$1,true), set_config('gbrain.write_request',CASE WHEN prev.s2<>'' THEN prev.s1 ELSE $2 END,true), set_config('gbrain.write_principal_kind',CASE WHEN prev.s2<>'' THEN prev.s2 ELSE $3 END,true), set_config('gbrain.write_principal_id',CASE WHEN prev.s2<>'' THEN prev.s3 ELSE $4 END,true), CASE WHEN $5::text<>'' THEN concat( set_config('gbrain.write_trust_tier',CASE WHEN (CASE prev.s4 WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END)>0 AND (CASE prev.s4 WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END)<(CASE $5::text WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) THEN prev.s4 ELSE $5::text END,true), set_config('gbrain.write_origin',CASE WHEN $6::text<>'' THEN $6::text ELSE prev.s5 END,true)) END) END AS applied FROM (SELECT COALESCE(current_setting('gbrain.write_sources',true),'') AS s0,COALESCE(current_setting('gbrain.write_request',true),'') AS s1,COALESCE(current_setting('gbrain.write_principal_kind',true),'') AS s2,COALESCE(current_setting('gbrain.write_principal_id',true),'') AS s3,COALESCE(current_setting('gbrain.write_trust_tier',true),'') AS s4,COALESCE(current_setting('gbrain.write_origin',true),'') AS s5 OFFSET 0) prev LEFT JOIN persistence_brain b ON b.singleton=1",
+ "SELECT q.*, (SELECT COALESCE(json_agg(json_build_object('enabled', b.enabled)), '[]'::json) FROM persistence_brain b WHERE b.singleton = 1) AS managed_rows, current_setting('plan_cache_mode') AS plan_mode_prev, set_config('plan_cache_mode', CASE WHEN q.coverage IS NOT NULL AND q.coverage <> 'coverage.stopped' THEN 'force_generic_plan' ELSE current_setting('plan_cache_mode') END, true) FROM (SELECT s.incarnation::text AS incarnation, s.purge_epoch, (SELECT e.event_type FROM belief_events e WHERE e.source_id = s.id AND e.subject_kind = 'coverage' AND e.subject_key = $2 AND e.source_incarnation = s.incarnation AND e.event_type <> 'coverage.restored' ORDER BY e.id DESC LIMIT 1) AS coverage, (s.purge_epoch > 0 OR EXISTS (SELECT 1 FROM fact_purges WHERE source_id = s.id) OR EXISTS (SELECT 1 FROM take_purges WHERE source_id = s.id) OR EXISTS (SELECT 1 FROM page_purges WHERE source_id = s.id)) AS purges FROM sources s WHERE s.id = $1) q",
+ "DELETE FROM content_chunks WHERE page_id = (SELECT id FROM pages WHERE slug = $1 AND source_id = $2)",
+ "DELETE FROM page_aliases WHERE source_id = $1 AND slug = $2 AND origin IN ('declared','subject')",
+ "SELECT id, slug, source_path, deleted_at FROM pages WHERE source_id=$1 AND slug=$2",
+ "DELETE FROM page_aliases WHERE source_id=$1 AND slug=$2 AND origin='frontmatter'",
+ "INSERT INTO pages (source_id, slug, type, page_kind, title, compiled_truth, timeline, frontmatter, content_hash, updated_at, effective_date, effective_date_source, import_filename, chunker_version, source_path, source_kind, source_uri, ingested_via, ingested_at, contextual_retrieval_mode, corpus_generation) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, now(), $10, $11, $12, $13::smallint, $14, $15, $16, $17, $18, $19, $20) ON CONFLICT (source_id, slug) DO UPDATE SET contextual_retrieval_mode = EXCLUDED.contextual_retrieval_mode, corpus_generation = EXCLUDED.corpus_generation, type = EXCLUDED.type, page_kind = EXCLUDED.page_kind, title = EXCLUDED.title, compiled_truth = EXCLUDED.compiled_truth, timeline = EXCLUDED.timeline, frontmatter = EXCLUDED.frontmatter, content_hash = EXCLUDED.content_hash, updated_at = now(), deleted_at = NULL, effective_date = COALESCE(EXCLUDED.effective_date, pages.effective_date), effective_date_source = COALESCE(EXCLUDED.effective_date_source, pages.effective_date_source), import_filename = COALESCE(EXCLUDED.import_filename, pages.import_filename), chunker_version = CASE WHEN pages.compiled_truth IS NOT DISTINCT FROM EXCLUDED.compiled_truth AND pages.timeline IS NOT DISTINCT FROM EXCLUDED.timeline THEN pages.chunker_version WHEN pages.chunker_version < 0 OR (CASE WHEN pages.body_storage = 'segmented' THEN pages.body_flags->>'has_protected' IS DISTINCT FROM 'false' ELSE (COALESCE(pages.compiled_truth, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->' OR COALESCE(pages.timeline, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->') END) OR COALESCE(EXCLUDED.compiled_truth, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->' OR COALESCE(EXCLUDED.timeline, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->' THEN -1 ELSE LEAST(COALESCE(pages.chunker_versio",
+ "SELECT key, value FROM config WHERE key IN ('search_embedding_column', 'embedding_columns', 'embedding_model')",
+ "INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, \"embedding\", model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image, embedding_pending_since, projected_byte_start, projected_byte_end) SELECT $1::int, c.chunk_index, c.chunk_text, c.chunk_source, c.embedding::vector, c.model, c.token_count, CASE WHEN c.embedding IS NULL THEN NULL ELSE now() END, CASE WHEN c.embedding IS NULL THEN NULL ELSE md5(c.chunk_text) END, c.embedding_input_hash, c.language, c.symbol_name, c.symbol_type, c.start_line, c.end_line, c.parent_symbol_path, c.doc_comment, c.symbol_name_qualified, c.modality, c.embedding_image::vector, CASE WHEN c.embedding IS NULL THEN now() ELSE NULL END, c.projected_byte_start, c.projected_byte_end FROM jsonb_to_recordset($2::text::jsonb) AS c(chunk_index int, chunk_text text, chunk_source text, embedding text, model text, token_count int, embedding_input_hash text, language text, symbol_name text, symbol_type text, start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text, modality text, embedding_image text, projected_byte_start bigint, projected_byte_end bigint) ON CONFLICT (page_id, chunk_index) DO UPDATE SET chunk_text = EXCLUDED.chunk_text, chunk_source = EXCLUDED.chunk_source, \"embedding\" = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.\"embedding\" WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.\"embedding\" WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.\"embedding\" ELSE content_chunks.\"embedding\"",
+ "SELECT id, slug, source_path, deleted_at FROM pages WHERE source_id=$1 AND slug=$2",
+ "UPDATE pages SET source_kind=$3,ingested_via=$4,ingested_at=$5::timestamptz WHERE source_id=$1 AND slug=$2",
+ "SELECT f.id, f.row_num, f.fact, f.visibility, f.trust_tier FROM facts f WHERE f.source_id = $1 AND f.source_markdown_slug = $2 AND f.row_num IS NOT NULL AND f.expired_at IS NULL AND (COALESCE(f.source, '') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num = f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer, fact text, visibility text) WHERE n.row_num = f.row_num AND n.fact = f.fact AND n.visibility = f.visibility) AND (CASE f.trust_tier WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) ORDER BY f.row_num FOR UPDATE",
+ "SELECT local_path, config->>'slug_root_mode' AS mode FROM sources WHERE id=$1",
+ "UPDATE facts f SET expired_at=COALESCE(expired_at,now()),row_num=NULL WHERE source_id=$1 AND source_markdown_slug=$2 AND row_num IS NOT NULL AND (COALESCE(f.source,'') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num=f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer,fact text,visibility text) WHERE n.row_num=f.row_num AND n.fact=f.fact AND n.visibility=f.visibility)",
+ "DELETE FROM timeline_entries t USING jsonb_to_recordset($2::text::jsonb) AS d(id integer,date date,source text,summary text,detail text,removed boolean) WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=d.id AND t.date=d.date AND t.source=d.source AND t.summary=d.summary AND t.detail=d.detail RETURNING t.date::text AS date, d.removed",
+ "UPDATE timeline_entries t SET detail=r.next FROM jsonb_to_recordset($2::text::jsonb) AS r(id integer,detail text,next text) WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=r.id AND t.detail=r.detail",
+ "SELECT pg_advisory_xact_lock(hashtextextended($1, 0))",
+ "SELECT k.row_num FROM takes k JOIN jsonb_to_recordset($2::text::jsonb) AS n(row_num integer,claim text,kind text,holder text) ON n.row_num=k.row_num WHERE k.page_id=$1 AND (k.claim,k.kind,k.holder) IS DISTINCT FROM (n.claim,n.kind,n.holder) ORDER BY k.row_num LIMIT $3",
+ "DELETE FROM takes WHERE page_id=$1 AND row_num=ANY($2::integer[])",
+ "SELECT slug, source_path FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND source_path=ANY($2::text[]) AND id<>$3 ORDER BY slug",
+ "UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2 AND source_path IS NULL RETURNING id",
+ "UPDATE pages SET database_only_reason=NULL WHERE source_id=$1 AND slug=$2 AND source_path=$3 AND database_only_reason='origin_twin'",
+ "WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.source_id=$2 AND p.deleted_at IS NULL ORDER BY (p.slug=$1) DESC, (p.source_id=$3) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, wd.snapshot_withdrawals, wd.snapshot_global_purges, CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb OR (wd.snapshot_global_purges->>'count')::int > 0 THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_body, CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb OR (wd.snapshot_global_purges->>'count')::int > 0 THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_timeline FROM chosen p CROSS JOIN LATERAL (SELECT COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true) ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at FROM fact_purges WHERE source_id=p.source_id AND subject=p.slug GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals, (SELECT jsonb_build_object('count',co",
+ "savepoint s0",
+ "SELECT value FROM config WHERE key = $1 FOR SHARE",
+ "SELECT q.*, (SELECT COALESCE(json_agg(json_build_object('enabled', b.enabled)), '[]'::json) FROM persistence_brain b WHERE b.singleton = 1) AS managed_rows, current_setting('plan_cache_mode') AS plan_mode_prev, set_config('plan_cache_mode', CASE WHEN q.coverage IS NOT NULL AND q.coverage <> 'coverage.stopped' THEN 'force_generic_plan' ELSE current_setting('plan_cache_mode') END, true) FROM (SELECT s.incarnation::text AS incarnation, s.purge_epoch, (SELECT e.event_type FROM belief_events e WHERE e.source_id = s.id AND e.subject_kind = 'coverage' AND e.subject_key = $2 AND e.source_incarnation = s.incarnation AND e.event_type <> 'coverage.restored' ORDER BY e.id DESC LIMIT 1) AS coverage, (s.purge_epoch > 0 OR EXISTS (SELECT 1 FROM fact_purges WHERE source_id = s.id) OR EXISTS (SELECT 1 FROM take_purges WHERE source_id = s.id) OR EXISTS (SELECT 1 FROM page_purges WHERE source_id = s.id)) AS purges FROM sources s WHERE s.id = $1) q",
+ "SELECT from_page_id, to_page_id, link_type FROM links WHERE (origin_page_id = $1 OR (origin_page_id IS NULL AND from_page_id = $1)) AND link_type = ANY($2::text[]) UNION SELECT from_page_id, to_page_id, link_type FROM link_transitions WHERE origin_page_id = $1 UNION SELECT from_page_id, to_page_id, link_type FROM link_relationships WHERE from_page_id = $1 AND scope = 'all'",
+ "SELECT 1 FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(from_slug text, to_slug text, from_source_id text, to_source_id text) LEFT JOIN pages f ON f.slug=v.from_slug AND f.source_id=v.from_source_id AND f.deleted_at IS NULL LEFT JOIN pages t ON t.slug=v.to_slug AND t.source_id=v.to_source_id AND t.deleted_at IS NULL WHERE f.id IS NULL OR t.id IS NULL LIMIT 1",
+ "SELECT l.id, f.slug from_slug, t.slug to_slug, f.source_id from_source_id, t.source_id to_source_id, l.link_type, l.link_source, o.slug origin_slug, o.source_id origin_source_id, l.context, l.origin_field FROM links l JOIN pages f ON f.id=l.from_page_id JOIN pages t ON t.id=l.to_page_id LEFT JOIN pages o ON o.id=l.origin_page_id WHERE (l.link_source=ANY($2::text[]) OR ($3::boolean AND l.link_source IS NULL)) AND (l.origin_page_id=$1 OR (l.origin_page_id IS NULL AND l.from_page_id=$1 AND (l.link_source IN ('markdown','wikilink-resolved') OR l.link_source IS NULL)))",
+ "DELETE FROM wanted_links w WHERE w.origin_page_id = $1 AND w.producer IN (SELECT jsonb_array_elements_text(($2::jsonb)->'producers')) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset(($2::jsonb)->'rows') AS v(producer text, ref_kind text, target_source_id text, target_ref text) WHERE v.producer = w.producer AND v.ref_kind = w.ref_kind AND v.target_source_id = w.target_source_id AND v.target_ref = w.target_ref)",
+ "DELETE FROM link_transitions WHERE origin_page_id = $1 AND producer = ANY($2::text[])",
+ "SELECT from_page_id, to_page_id, link_type FROM links WHERE (origin_page_id = $1 OR (origin_page_id IS NULL AND from_page_id = $1)) AND link_type = ANY($2::text[]) UNION SELECT from_page_id, to_page_id, link_type FROM link_transitions WHERE origin_page_id = $1 UNION SELECT from_page_id, to_page_id, link_type FROM link_relationships WHERE from_page_id = $1 AND scope = 'all'",
+ "WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.source_id=$2 ORDER BY (p.slug=$1) DESC, (p.source_id=$3) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, wd.snapshot_withdrawals, wd.snapshot_global_purges, CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb OR (wd.snapshot_global_purges->>'count')::int > 0 THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_body, CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb OR (wd.snapshot_global_purges->>'count')::int > 0 THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_timeline FROM chosen p CROSS JOIN LATERAL (SELECT COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true) ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at FROM fact_purges WHERE source_id=p.source_id AND subject=p.slug GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals, (SELECT jsonb_build_object('count',count(*),'latest',max(g.pur",
+ "UPDATE pages SET chunker_version=$5, text_projection_revision=CASE WHEN knowledge_revision=$4::uuid THEN knowledge_revision ELSE text_projection_revision END, search_vector=CASE WHEN knowledge_revision=$4::uuid THEN setweight(to_tsvector('english',gbrain_fts_input(COALESCE(title,''))),'A') || setweight(to_tsvector('english',gbrain_fts_input(left($3::text,65536))),'C') ELSE search_vector END WHERE source_id=$1 AND slug=$2 RETURNING id",
+ "SELECT value FROM config WHERE key = $1",
+ "SELECT 1 FROM chronicle_page_state WHERE source_id=$1 AND page_id=$2 AND state='extracted' AND cardinality(event_hashes) > 0 LIMIT 1",
+ "INSERT INTO persistence_effects (request_id,kind,revision,data,source_id,source_incarnation,worktree_id) SELECT $1::uuid,t.e->>'kind',$2::uuid,t.e->'data',$3,$4::uuid,$5::uuid FROM jsonb_array_elements($6::text::jsonb) WITH ORDINALITY AS t(e,n) WHERE NOT (COALESCE((t.e->>'gated')::boolean,false) AND EXISTS (SELECT 1 FROM config WHERE key IN ('auto_link',$7) AND lower(btrim(value,E' \\t\\r\\n')) IN ('false','0','no','off'))) ORDER BY t.n ON CONFLICT(request_id,kind) DO NOTHING RETURNING kind",
+ "SELECT set_config('gbrain.write_sources',$1,true),set_config('gbrain.write_request',$2,true),set_config('gbrain.write_principal_kind',$3,true),set_config('gbrain.write_principal_id',$4,true),set_config('gbrain.write_trust_tier',$5,true),set_config('gbrain.write_origin',$6,true)",
+ "INSERT INTO persistence_counters(key) SELECT k FROM unnest($1::text[]) WITH ORDINALITY AS u(k,n) ORDER BY n ON CONFLICT DO NOTHING",
+ "SELECT * FROM persistence_counters WHERE key=ANY($1::text[]) ORDER BY key COLLATE \"C\" FOR UPDATE",
+ "WITH m AS ( SELECT * FROM unnest($1::uuid[],$2::uuid[],$3::text[],$4::bigint[],$5::text[],$8::bigint[]) AS m(id,token,outcome,need,principal_key,retained) ), e AS ( SELECT request_id,SUM(octet_length(data::text)+octet_length(kind)+1024) AS bytes,bool_or(state<>'committed') AS unfinished FROM persistence_effects WHERE request_id=ANY($1::uuid[]) GROUP BY request_id ), prior AS ( SELECT r.id,r.terminal_reservation FROM persistence_requests r JOIN m ON m.id=r.id ), done AS ( UPDATE persistence_requests r SET state='committed',outcome=m.outcome::jsonb,error_code=NULL,error_message=NULL, completed_at=now(),updated_at=now(),claim_expires_at=NULL,blocked_reason=NULL, consumer_version=$6,consumer_host_id=$7::uuid,consumer_segment_reader=true,published_at=now(),preparation_attempts=0, terminal_reservation=CASE WHEN COALESCE(e.unfinished,false) THEN r.terminal_reservation ELSE LEAST(r.terminal_reservation,m.retained+COALESCE(e.bytes,0)) END FROM m LEFT JOIN e ON e.request_id=m.id WHERE r.id=m.id AND r.execution_token=m.token AND r.state='running' AND m.need+COALESCE(e.bytes,0)<=r.terminal_reservation RETURNING r.*,m.principal_key ), d AS ( SELECT k.key,count(*) AS n,SUM(done.intent_bytes) AS bytes,SUM(prior.terminal_reservation-done.terminal_reservation) AS freed FROM done JOIN prior ON prior.id=done.id CROSS JOIN LATERAL (VALUES ('brain'),(done.principal_key)) AS k(key) GROUP BY k.key ), released AS ( UPDATE persistence_counters c SET outstanding_count=c.outstanding_count-d.n,intent_bytes=c.intent_bytes-d.bytes, terminal_bytes=c.terminal_bytes-LEAST(d.freed,c.terminal_bytes) FROM d WHERE c.key=d.key ), clamped AS (INSERT INTO config(key,value) SELECT 'persistence.true_up.clamped',k.n::text FROM (SELECT count(*) FROM d JOIN persistence_counters c ON c.key=d.key WHERE d.freed>c.terminal_bytes) AS k(n) WHE",
+ "commit"
+ ],
+ "canonical_import": [
+ "begin",
+ "SELECT set_config('idle_in_transaction_session_timeout',$3,true),set_config('gbrain.persistence_protocol','2',true),set_config('synchronous_commit','on',true), set_config('lock_timeout',$1,true),set_config('statement_timeout',$2,true),(SELECT brain_id::text FROM persistence_brain WHERE singleton=1 FOR SHARE) AS brain",
+ "SELECT owner_host_id,owner_epoch,state FROM persistence_worktrees WHERE id=$1::uuid FOR SHARE",
+ "SELECT s.source_id,s.source_incarnation,s.worktree_id,s.relative_path, s.topology_generation::text AS topology_generation,w.owner_host_id,w.owner_epoch::text AS owner_epoch,w.state, h.local_path,h.coordination_path,h.git_durability FROM persistence_source_bindings s JOIN persistence_worktrees w ON w.id=s.worktree_id LEFT JOIN persistence_host_bindings h ON h.worktree_id=w.id AND h.host_id=$2::uuid WHERE s.source_id=$1",
+ "SELECT id FROM sources WHERE id=$1 FOR UPDATE",
+ "SELECT incarnation,archived FROM sources WHERE id=$1 FOR SHARE",
+ "SELECT lane,revoked_at,grant_ceiling FROM persistence_local_writers WHERE id=$1::uuid FOR SHARE",
+ "INSERT INTO persistence_counters(key) SELECT k FROM unnest($1::text[]) WITH ORDINALITY AS u(k,n) ORDER BY n ON CONFLICT DO NOTHING",
+ "SELECT * FROM persistence_counters WHERE key=ANY($1::text[]) ORDER BY key COLLATE \"C\" FOR UPDATE",
+ "SELECT * FROM persistence_requests WHERE id=$1::uuid FOR UPDATE",
+ "SELECT p.source_id,p.source_incarnation,s.local_path AS source_root, h.local_path AS worktree_root,b.relative_path FROM shared_skill_packs p JOIN sources s ON s.id=p.source_id AND s.incarnation=p.source_incarnation LEFT JOIN persistence_source_bindings b ON b.source_id=p.source_id AND b.source_incarnation=p.source_incarnation LEFT JOIN persistence_host_bindings h ON h.worktree_id=b.worktree_id AND h.host_id=$1::uuid",
+ "SELECT incarnation FROM sources WHERE id=$1 FOR SHARE",
+ "INSERT INTO page_write_guards(source_incarnation,slug) SELECT incarnation,$2 FROM sources WHERE id=$1 ON CONFLICT DO NOTHING",
+ "SELECT g.slug FROM page_write_guards g JOIN sources s ON s.incarnation=g.source_incarnation WHERE s.id=$1 AND g.slug=$2 FOR UPDATE OF g",
+ "SELECT id FROM pages WHERE source_id=$1 AND slug=$2 FOR UPDATE",
+ "WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.source_id=$2 ORDER BY (p.slug=$1) DESC, (p.source_id=$3) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, wd.snapshot_withdrawals, wd.snapshot_global_purges, CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb OR (wd.snapshot_global_purges->>'count')::int > 0 THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_body, CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb OR (wd.snapshot_global_purges->>'count')::int > 0 THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_timeline FROM chosen p CROSS JOIN LATERAL (SELECT COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true) ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at FROM fact_purges WHERE source_id=p.source_id AND subject=p.slug GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals, (SELECT jsonb_build_object('count',count(*),'latest',max(g.pur",
+ "SELECT enabled FROM persistence_brain WHERE singleton=1 FOR SHARE",
+ "SELECT local_path FROM sources WHERE id=$1 FOR SHARE",
+ "SELECT s.source_id,s.source_incarnation,s.worktree_id,s.relative_path, s.topology_generation::text AS topology_generation,w.owner_host_id,w.owner_epoch::text AS owner_epoch,w.state, h.local_path,h.coordination_path,h.git_durability FROM persistence_source_bindings s JOIN persistence_worktrees w ON w.id=s.worktree_id LEFT JOIN persistence_host_bindings h ON h.worktree_id=w.id AND h.host_id=$2::uuid WHERE s.source_id=$1",
+ "SELECT id,slug,source_path,deleted_at FROM pages WHERE source_id=$1 AND source_path=ANY($2::text[])",
+ "SELECT b.brain_id,prev.*, CASE WHEN b.brain_id IS NOT NULL THEN concat(set_config('gbrain.write_sources',$1,true), set_config('gbrain.write_request',CASE WHEN prev.s2<>'' THEN prev.s1 ELSE $2 END,true), set_config('gbrain.write_principal_kind',CASE WHEN prev.s2<>'' THEN prev.s2 ELSE $3 END,true), set_config('gbrain.write_principal_id',CASE WHEN prev.s2<>'' THEN prev.s3 ELSE $4 END,true), CASE WHEN $5::text<>'' THEN concat( set_config('gbrain.write_trust_tier',CASE WHEN (CASE prev.s4 WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END)>0 AND (CASE prev.s4 WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END)<(CASE $5::text WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) THEN prev.s4 ELSE $5::text END,true), set_config('gbrain.write_origin',CASE WHEN $6::text<>'' THEN $6::text ELSE prev.s5 END,true)) END) END AS applied FROM (SELECT COALESCE(current_setting('gbrain.write_sources',true),'') AS s0,COALESCE(current_setting('gbrain.write_request',true),'') AS s1,COALESCE(current_setting('gbrain.write_principal_kind',true),'') AS s2,COALESCE(current_setting('gbrain.write_principal_id',true),'') AS s3,COALESCE(current_setting('gbrain.write_trust_tier',true),'') AS s4,COALESCE(current_setting('gbrain.write_origin',true),'') AS s5 OFFSET 0) prev LEFT JOIN persistence_brain b ON b.singleton=1",
+ "SELECT q.*, (SELECT COALESCE(json_agg(json_build_object('enabled', b.enabled)), '[]'::json) FROM persistence_brain b WHERE b.singleton = 1) AS managed_rows, current_setting('plan_cache_mode') AS plan_mode_prev, set_config('plan_cache_mode', CASE WHEN q.coverage IS NOT NULL AND q.coverage <> 'coverage.stopped' THEN 'force_generic_plan' ELSE current_setting('plan_cache_mode') END, true) FROM (SELECT s.incarnation::text AS incarnation, s.purge_epoch, (SELECT e.event_type FROM belief_events e WHERE e.source_id = s.id AND e.subject_kind = 'coverage' AND e.subject_key = $2 AND e.source_incarnation = s.incarnation AND e.event_type <> 'coverage.restored' ORDER BY e.id DESC LIMIT 1) AS coverage, (s.purge_epoch > 0 OR EXISTS (SELECT 1 FROM fact_purges WHERE source_id = s.id) OR EXISTS (SELECT 1 FROM take_purges WHERE source_id = s.id) OR EXISTS (SELECT 1 FROM page_purges WHERE source_id = s.id)) AS purges FROM sources s WHERE s.id = $1) q",
+ "SELECT key,value FROM config WHERE key IN ('search_embedding_column','embedding_columns','embedding_model','embedding_dimensions','contextual_retrieval.mode') ORDER BY key",
+ "SELECT c.chunk_index, c.embedding_input_hash, p.contextual_retrieval_mode, c.embedding_image IS NULL AND c.embedding_multimodal IS NULL AND c.embedded_text_hash = md5(c.chunk_text) AS text_only, c.embedding IS NULL AND c.embedding_image IS NULL AND c.embedding_multimodal IS NULL AND c.embedding_input_hash IS NULL AND c.embedded_text_hash IS NULL AS unembedded FROM content_chunks c JOIN pages p ON p.id = c.page_id WHERE p.source_id = $1 AND p.slug = $2",
+ "SELECT key, value FROM config WHERE key IN ('search_embedding_column', 'embedding_columns')",
+ "-- chunk-visibility-ok: whether any chunk row of a segmented body exists, no row is returned SELECT has_table_privilege('page_body_manifest', 'SELECT') AS readable, NOT has_table_privilege('page_body_manifest', 'SELECT') AND (EXISTS (SELECT 1 FROM content_chunks WHERE body_generation IS NOT NULL) OR EXISTS (SELECT 1 FROM content_chunks WHERE occurrence_id IS NOT NULL)) AS segmented",
+ "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.projected_byte_start, cc.projected_byte_end, (cc.\"embedding\" IS NULL) AS embedding_is_null , cc.\"embedding\" AS embedding FROM content_chunks cc JOIN pages p ON p.id = cc.page_id LEFT JOIN page_body_manifest m ON cc.occurrence_id IS NOT NULL AND m.page_id = cc.page_id AND m.occurrence_id = cc.occurrence_id AND m.staging_id IS NULL AND m.gen_from <= p.body_generation AND (m.gen_to IS NULL OR m.gen_to > p.body_generation) WHERE p.slug = $1 AND p.source_id = $2 AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE AND (cc.body_generation IS NULL OR cc.body_generation <= p.body_generation)) AND p.chunker_version >= 4 ORDER BY m.byte_start, cc.local_ordinal, cc.chunk_index",
+ "INSERT INTO page_versions (page_id,compiled_truth,frontmatter,knowledge_revision,timeline,title,type,tags,is_deleted,source_path) VALUES ($1,$2,$3::text::jsonb,$4::uuid,$5,$6,$7,$8::text::jsonb,$9,$10) RETURNING *",
+ "DELETE FROM content_chunks WHERE page_id = (SELECT id FROM pages WHERE slug = $1 AND source_id = $2)",
+ "DELETE FROM page_aliases WHERE source_id = $1 AND slug = $2 AND origin IN ('declared','subject')",
+ "SELECT id, slug, source_path, deleted_at FROM pages WHERE source_id=$1 AND slug=$2",
+ "DELETE FROM page_aliases WHERE source_id=$1 AND slug=$2 AND origin='frontmatter'",
+ "SELECT local_path, config->>'slug_root_mode' AS mode FROM sources WHERE id=$1",
+ "INSERT INTO pages (source_id, slug, type, page_kind, title, compiled_truth, timeline, frontmatter, content_hash, updated_at, effective_date, effective_date_source, import_filename, chunker_version, source_path, source_kind, source_uri, ingested_via, ingested_at, contextual_retrieval_mode, corpus_generation) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, now(), $10, $11, $12, $13::smallint, $14, $15, $16, $17, $18, $19, $20) ON CONFLICT (source_id, slug) DO UPDATE SET contextual_retrieval_mode = EXCLUDED.contextual_retrieval_mode, corpus_generation = EXCLUDED.corpus_generation, type = EXCLUDED.type, page_kind = EXCLUDED.page_kind, title = EXCLUDED.title, compiled_truth = EXCLUDED.compiled_truth, timeline = EXCLUDED.timeline, frontmatter = EXCLUDED.frontmatter, content_hash = EXCLUDED.content_hash, updated_at = now(), deleted_at = NULL, effective_date = COALESCE(EXCLUDED.effective_date, pages.effective_date), effective_date_source = COALESCE(EXCLUDED.effective_date_source, pages.effective_date_source), import_filename = COALESCE(EXCLUDED.import_filename, pages.import_filename), chunker_version = CASE WHEN pages.compiled_truth IS NOT DISTINCT FROM EXCLUDED.compiled_truth AND pages.timeline IS NOT DISTINCT FROM EXCLUDED.timeline THEN pages.chunker_version WHEN pages.chunker_version < 0 OR (CASE WHEN pages.body_storage = 'segmented' THEN pages.body_flags->>'has_protected' IS DISTINCT FROM 'false' ELSE (COALESCE(pages.compiled_truth, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->' OR COALESCE(pages.timeline, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->') END) OR COALESCE(EXCLUDED.compiled_truth, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->' OR COALESCE(EXCLUDED.timeline, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->' THEN -1 ELSE LEAST(COALESCE(pages.chunker_versio",
+ "SELECT key, value FROM config WHERE key IN ('search_embedding_column', 'embedding_columns', 'embedding_model')",
+ "INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, \"embedding\", model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image, embedding_pending_since, projected_byte_start, projected_byte_end) SELECT $1::int, c.chunk_index, c.chunk_text, c.chunk_source, c.embedding::vector, c.model, c.token_count, CASE WHEN c.embedding IS NULL THEN NULL ELSE now() END, CASE WHEN c.embedding IS NULL THEN NULL ELSE md5(c.chunk_text) END, c.embedding_input_hash, c.language, c.symbol_name, c.symbol_type, c.start_line, c.end_line, c.parent_symbol_path, c.doc_comment, c.symbol_name_qualified, c.modality, c.embedding_image::vector, CASE WHEN c.embedding IS NULL THEN now() ELSE NULL END, c.projected_byte_start, c.projected_byte_end FROM jsonb_to_recordset($2::text::jsonb) AS c(chunk_index int, chunk_text text, chunk_source text, embedding text, model text, token_count int, embedding_input_hash text, language text, symbol_name text, symbol_type text, start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text, modality text, embedding_image text, projected_byte_start bigint, projected_byte_end bigint) ON CONFLICT (page_id, chunk_index) DO UPDATE SET chunk_text = EXCLUDED.chunk_text, chunk_source = EXCLUDED.chunk_source, \"embedding\" = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.\"embedding\" WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.\"embedding\" WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.\"embedding\" ELSE content_chunks.\"embedding\"",
+ "UPDATE pages SET database_only_reason=NULL WHERE source_id=$1 AND slug=$2 AND database_only_reason='unbound_source'",
+ "WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.source_id=$2 ORDER BY (p.slug=$1) DESC, (p.source_id=$3) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, wd.snapshot_withdrawals, wd.snapshot_global_purges, CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb OR (wd.snapshot_global_purges->>'count')::int > 0 THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_body, CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb OR (wd.snapshot_global_purges->>'count')::int > 0 THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_timeline FROM chosen p CROSS JOIN LATERAL (SELECT COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true) ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at FROM fact_purges WHERE source_id=p.source_id AND subject=p.slug GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals, (SELECT jsonb_build_object('count',count(*),'latest',max(g.pur",
+ "UPDATE pages SET chunker_version=$5, text_projection_revision=CASE WHEN knowledge_revision=$4::uuid THEN knowledge_revision ELSE text_projection_revision END, search_vector=CASE WHEN knowledge_revision=$4::uuid THEN setweight(to_tsvector('english',gbrain_fts_input(COALESCE(title,''))),'A') || setweight(to_tsvector('english',gbrain_fts_input(left($3::text,65536))),'C') ELSE search_vector END WHERE source_id=$1 AND slug=$2 RETURNING id",
+ "SELECT COALESCE((completed_keys->0->>'count')::int,0) AS count FROM op_checkpoints WHERE op=$1 AND fingerprint=$2",
+ "INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb) ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()",
+ "SELECT f.id, f.row_num, f.fact, f.visibility, f.trust_tier FROM facts f WHERE f.source_id = $1 AND f.source_markdown_slug = $2 AND f.row_num IS NOT NULL AND f.expired_at IS NULL AND (COALESCE(f.source, '') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num = f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer, fact text, visibility text) WHERE n.row_num = f.row_num AND n.fact = f.fact AND n.visibility = f.visibility) AND (CASE f.trust_tier WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) ORDER BY f.row_num FOR UPDATE",
+ "UPDATE facts f SET expired_at=COALESCE(expired_at,now()),row_num=NULL WHERE source_id=$1 AND source_markdown_slug=$2 AND row_num IS NOT NULL AND (COALESCE(f.source,'') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num=f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer,fact text,visibility text) WHERE n.row_num=f.row_num AND n.fact=f.fact AND n.visibility=f.visibility)",
+ "DELETE FROM timeline_entries t USING jsonb_to_recordset($2::text::jsonb) AS d(id integer,date date,source text,summary text,detail text,removed boolean) WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=d.id AND t.date=d.date AND t.source=d.source AND t.summary=d.summary AND t.detail=d.detail RETURNING t.date::text AS date, d.removed",
+ "UPDATE timeline_entries t SET detail=r.next FROM jsonb_to_recordset($2::text::jsonb) AS r(id integer,detail text,next text) WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=r.id AND t.detail=r.detail",
+ "SELECT k.row_num FROM takes k JOIN jsonb_to_recordset($2::text::jsonb) AS n(row_num integer,claim text,kind text,holder text) ON n.row_num=k.row_num WHERE k.page_id=$1 AND (k.claim,k.kind,k.holder) IS DISTINCT FROM (n.claim,n.kind,n.holder) ORDER BY k.row_num LIMIT $3",
+ "DELETE FROM takes WHERE page_id=$1 AND row_num=ANY($2::integer[])",
+ "SAVEPOINT gbrain_pass_stamp_fold",
+ "SELECT 1 FROM gbrain_cycle_locks WHERE id=$1 AND acquisition_token=$2::uuid AND ttl_expires_at > now() FOR SHARE",
+ "SELECT completed_keys->0 AS value, updated_at FROM op_checkpoints WHERE op=$1 AND fingerprint=$2",
+ "(SELECT r.request_id::text AS request_id FROM persistence_requests r WHERE r.worktree_id=$1::uuid AND r.recovery IS NOT NULL LIMIT 1) UNION ALL (SELECT r.request_id::text FROM persistence_requests r WHERE r.worktree_id=$1::uuid AND r.state IN ('queued','running','recovering') AND r.request_id<>$2::uuid AND r.intent->>'kind' IN ('managed_sync_import','managed_sync_delete','managed_sync_checkpoint') LIMIT 1) LIMIT 1",
+ "SELECT GREATEST((SELECT max(sequence) FROM persistence_requests WHERE worktree_id=$1::uuid), (SELECT max(sequence) FROM persistence_requests WHERE worktree_id IS NULL AND source_id=$2 AND source_incarnation=$3::uuid))::text AS hwm",
+ "SELECT last_commit, config->>'slug_root_mode' AS mode FROM sources WHERE id=$1 AND incarnation=$2::uuid",
+ "SET LOCAL jit = off",
+ "WITH x AS MATERIALIZED (SELECT txid_snapshot_xmin(txid_current_snapshot()) AS now_lo, txid_snapshot_xmax(txid_current_snapshot()) AS hi, age(($4::bigint % 4294967296)::text::xid) AS lo_age), pg AS (SELECT count(*) FILTER (WHERE p.source_path IS NOT NULL)::int AS n, COALESCE(jsonb_agg(jsonb_build_array(p.id::text, EXISTS (SELECT 1 FROM persistence_requests r WHERE r.id=p.revision_write_request_id AND r.source_id=$1 AND (r.id=$6::uuid OR r.state='committed' AND r.intent->>'passId'=$5 AND r.outcome->>'revision'=p.knowledge_revision::text)), p.knowledge_revision::text)) FILTER (WHERE NOT age(p.xmin) > x.lo_age), '[]'::jsonb) AS changed FROM pages p, x WHERE p.source_id=$1), oc AS (SELECT o.op, count(*)::int AS n, jsonb_agg(jsonb_build_array(o.op, o.fingerprint, o.completed_keys->0->>'revision', o.completed_keys->0->>'run_id')) FILTER (WHERE NOT age(o.xmin) > x.lo_age) AS changed FROM op_checkpoints o, x WHERE o.op = ANY($2::text[]) AND (o.fingerprint = $3 OR starts_with(o.fingerprint, $3 || ':')) GROUP BY o.op) SELECT x.now_lo::text AS xmin, (x.hi - $4::bigint)::float8 AS span, pg.n AS pages, pg.changed AS pages_changed, (SELECT COALESCE(jsonb_object_agg(op, n), '{}'::jsonb) FROM oc) AS ops, (SELECT COALESCE(jsonb_agg(c), '[]'::jsonb) FROM oc, jsonb_array_elements(COALESCE(oc.changed, '[]'::jsonb)) c) AS ops_changed, (SELECT COALESCE(jsonb_agg(fingerprint), '[]'::jsonb) FROM op_checkpoints WHERE op='sync-hold' AND starts_with(fingerprint, $3 || ':')) AS holds FROM x, pg",
+ "SELECT 1 FROM persistence_requests r WHERE r.source_id=$1 AND r.slug='__managed_sync_checkpoint__' AND r.intent IS NOT NULL AND NOT r.compacted AND r.operation='submit_job' AND r.intent->>'kind'='managed_sync_checkpoint' AND r.state IN ('failed','conflict','cancelled') AND NOT EXISTS (SELECT 1 FROM persistence_requests c WHERE (c.source_id=r.source_id AND c.slug=r.slug AND c.sequence>r.sequence AND ( (c.digest=r.digest AND c.state IN ('committed','failed','queued','running','recovering')) OR (c.state IN ('committed','queued','running','recovering') AND (c.operation IN ('delete_page','purge_page') OR r.operation='put_page')) OR (r.slug='__managed_sync_checkpoint__' AND r.operation='submit_job' AND c.state='committed' AND c.operation='submit_job' AND COALESCE((SELECT k.intent->>'kind' FROM persistence_requests k WHERE k.id=r.id),'managed_sync_checkpoint')='managed_sync_checkpoint' AND COALESCE(c.intent->>'kind','managed_sync_checkpoint')='managed_sync_checkpoint') OR (r.operation='put_page' AND c.state='failed' AND c.operation='put_page' AND COALESCE(NOT (c.intent ? 'kind'), false))))) LIMIT 1",
+ "(SELECT 'r:'||request_id::text AS id FROM persistence_requests WHERE state IN ('queued','running','recovering') AND (worktree_id=$1::uuid OR worktree_id IS NULL AND source_id=$4 AND source_incarnation=$5::uuid) AND request_id IS DISTINCT FROM $2::uuid LIMIT $3) UNION ALL (SELECT 'e:'||e.id::text FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id WHERE r.worktree_id=$1::uuid AND e.kind='git' AND e.state IN ('queued','running') LIMIT $3)",
+ "SELECT p.id, p.slug, p.source_path, p.knowledge_revision::text AS revision, p.deleted_at IS NOT NULL AS deleted, p.revision_write_request_id::text AS request_id, c.fingerprint IS NOT NULL AS has_record, c.origin IS NOT DISTINCT FROM p.source_path AS rec_origin_same, CASE WHEN c.origin IS DISTINCT FROM p.source_path THEN c.origin END AS rec_origin, c.blob_oid AS rec_blob_oid, c.disk_blob_oid IS NOT DISTINCT FROM c.blob_oid AS rec_disk_same, CASE WHEN c.disk_blob_oid IS DISTINCT FROM c.blob_oid THEN c.disk_blob_oid END AS rec_disk_blob_oid, c.revision IS NULL AS rec_revision_null, NULLIF(c.revision, p.knowledge_revision::text) AS rec_revision, CASE WHEN c.parser IS DISTINCT FROM $4::jsonb THEN c.parser::text END AS rec_parser, c.parser = $4::jsonb AS rec_parser_expected, c.full_episode AS rec_full_episode, c.working AS rec_working FROM pages p LEFT JOIN (SELECT fingerprint, completed_keys->0->>'origin' AS origin, completed_keys->0->>'blob_oid' AS blob_oid, completed_keys->0->>'disk_blob_oid' AS disk_blob_oid, completed_keys->0->>'revision' AS revision, completed_keys->0->'parser' AS parser, completed_keys->0->>'full_episode' AS full_episode, (completed_keys->0->'working')::text AS working FROM op_checkpoints WHERE op=$2) c ON c.fingerprint=$3||p.id::text WHERE p.source_id=$1 AND p.source_path IS NOT NULL AND p.id = ANY($5::bigint[]) ORDER BY p.id",
+ "SELECT p.id::text AS id, r.intent->>'level' AS level, r.intent->>'path' AS path FROM pages p JOIN persistence_requests r ON r.id=p.revision_write_request_id WHERE p.source_id=$1 AND p.id = ANY($2::bigint[])",
+ "UPDATE sources SET last_commit=$3,last_sync_at=now(), config=jsonb_set(( WITH RECURSIVE root_layers(value, depth) AS ( SELECT COALESCE(config, '{}'::jsonb), 0 UNION ALL SELECT (value #>> '{}')::jsonb, depth + 1 FROM root_layers WHERE depth < 10 AND jsonb_typeof(value) = 'string' AND (value #>> '{}') IS JSON ), root(value) AS ( SELECT value FROM root_layers ORDER BY depth DESC LIMIT 1 ), fragment_seeds(ordinality, value) AS ( SELECT 0::bigint, value FROM root WHERE jsonb_typeof(value) = 'object' UNION ALL SELECT item.ordinality, item.value FROM root, LATERAL jsonb_array_elements( CASE WHEN jsonb_typeof(root.value) = 'array' THEN root.value ELSE '[]'::jsonb END ) WITH ORDINALITY AS item(value, ordinality) ), fragment_layers(ordinality, value, depth) AS ( SELECT ordinality, value, 0 FROM fragment_seeds UNION ALL SELECT ordinality, (value #>> '{}')::jsonb, depth + 1 FROM fragment_layers WHERE depth < 10 AND jsonb_typeof(value) = 'string' AND (value #>> '{}') IS JSON ), fragments AS ( SELECT DISTINCT ON (ordinality) ordinality, value FROM fragment_layers ORDER BY ordinality, depth DESC ) SELECT COALESCE( jsonb_object_agg(entry.key, entry.value ORDER BY fragments.ordinality), '{}'::jsonb ) FROM fragments CROSS JOIN LATERAL jsonb_each( CASE WHEN jsonb_typeof(fragments.value) = 'object' THEN fragments.value ELSE '{}'::jsonb END ) AS entry(key, value) ),'{slug_root_mode}',to_jsonb(CASE WHEN $6::boolean THEN COALESCE(config->>'slug_root_mode',$5::text) ELSE $5::text END)), newest_content_at=(SELECT MAX(updated_at) FROM pages WHERE source_id=$1 AND deleted_at IS NULL) WHERE id=$1 AND incarnation=$2::uuid AND (last_commit IS NOT DISTINCT FROM $4 OR last_commit=$3) AND ($6::boolean OR config->>'slug_root_mode' IS NULL OR config->>'sl",
+ "INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES ($1, $2, jsonb_build_array(jsonb_strip_nulls(jsonb_build_object('run_id',$3::text,'at',now(),'changed',$4::int,'extract',$5::boolean,'since',$6::text))), now()) ON CONFLICT (op,fingerprint) DO UPDATE SET updated_at=now(), completed_keys=CASE WHEN jsonb_array_length(op_checkpoints.completed_keys)>=16 THEN (op_checkpoints.completed_keys-0)||EXCLUDED.completed_keys ELSE op_checkpoints.completed_keys||EXCLUDED.completed_keys END",
+ "SELECT intent->>'path' AS path, outcome->'fences_normalized' AS fences FROM persistence_requests WHERE worktree_id=$1::uuid AND source_id=$2 AND sequence > $3::bigint AND state='committed' AND intent->>'kind'='managed_sync_import' AND intent->>'passId' IS NOT NULL AND jsonb_typeof(outcome->'fences_normalized')='array' ORDER BY sequence",
+ "INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES($1,$2,jsonb_build_array($3::text::jsonb),now()) ON CONFLICT (op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys, updated_at=now() WHERE $4::boolean OR op_checkpoints.completed_keys->0->>'lease_token'=$5 RETURNING 1",
+ "RELEASE SAVEPOINT gbrain_pass_stamp_fold",
+ "SELECT set_config('gbrain.write_sources',$1,true),set_config('gbrain.write_request',$2,true),set_config('gbrain.write_principal_kind',$3,true),set_config('gbrain.write_principal_id',$4,true),set_config('gbrain.write_trust_tier',$5,true),set_config('gbrain.write_origin',$6,true)",
+ "SELECT value FROM config WHERE key = $1",
+ "SELECT 1 FROM chronicle_page_state WHERE source_id=$1 AND page_id=$2 AND state='extracted' AND cardinality(event_hashes) > 0 LIMIT 1",
+ "WITH effects AS (SELECT COALESCE(SUM(octet_length(data::text)+octet_length(kind)+1024),0) AS bytes, COALESCE(bool_or(state<>'committed'),false) AS unfinished FROM persistence_effects WHERE request_id=$1::uuid), done AS (UPDATE persistence_requests SET state=$2,outcome=$3::text::jsonb, error_code=$4,error_message=$5,error_detail=COALESCE($8::text::jsonb,error_detail),completed_at=now(),updated_at=now(),claim_expires_at=NULL,blocked_reason=NULL, consumer_version=CASE WHEN $2='committed' THEN $6 ELSE consumer_version END, consumer_host_id=CASE WHEN $2='committed' THEN $7::uuid ELSE consumer_host_id END, consumer_segment_reader=CASE WHEN $2='committed' THEN true ELSE consumer_segment_reader END, published_at=CASE WHEN $2='committed' THEN now() ELSE published_at END, preparation_attempts=CASE WHEN $2='committed' THEN 0 ELSE preparation_attempts END, terminal_reservation=CASE WHEN (SELECT unfinished FROM effects) THEN terminal_reservation ELSE LEAST(terminal_reservation,$12::bigint+(SELECT bytes FROM effects)) END WHERE id=$1::uuid AND $9::bigint+(SELECT bytes FROM effects)<=terminal_reservation RETURNING *), released AS (UPDATE persistence_counters c SET outstanding_count=c.outstanding_count-1,intent_bytes=c.intent_bytes-$11, terminal_bytes=c.terminal_bytes-LEAST($13::bigint-done.terminal_reservation,c.terminal_bytes) FROM done WHERE c.key=ANY($10::text[])), clamped AS (INSERT INTO config(key,value) SELECT 'persistence.true_up.clamped',k.n::text FROM (SELECT count(*) FROM persistence_counters c, done WHERE c.key=ANY($10::text[]) AND $13::bigint-done.terminal_reservation>c.terminal_bytes) AS k(n) WHERE k.n>0 ON CONFLICT (key) DO UPDATE SET value=(CASE WHEN config.value ~ '^[0-9]+$' THEN config.value::bigint ELSE 0 END+EXCLUDED.value::bigint)::text) SELECT done.*, EXISTS (SELECT 1 FROM fact_purges WHERE source_id=done.source_id) AS purge_has_facts, EXISTS (SELECT 1 FROM page",
+ "commit"
+ ]
+ }
+}
diff --git a/test/fold-hook-noop-6712.test.ts b/test/fold-hook-noop-6712.test.ts
new file mode 100644
index 0000000000..acf446687c
--- /dev/null
+++ b/test/fold-hook-noop-6712.test.ts
@@ -0,0 +1,112 @@
+/**
+ * #6712 PR 4b: the post-effects hook (coordinator.ts `PreparedMutation.afterEffects`) runs only for a pass's writeback
+ * import that carries the folded stamp. Every other write publishes exactly as before the hook existed.
+ *
+ * Protects: the publication transaction of a `put_page` and of a canonical one-file import whose stamp folds into its
+ * apply runs the same SQL statements, in the same order, as the golden sequence recorded on the commit before the hook
+ * (da413e41a; test/fixtures/fold-hook-noop-6712.json). Statements are the publication's own round trips (begin to
+ * commit), captured through the statement seam (PGLite: `countPgliteStatements`; Postgres: the `GBRAIN_SQL_TRACE` wire
+ * trace), with whitespace collapsed and the per-call statement timeout masked. A hook that adds, drops or reorders a
+ * statement for any other write fails here.
+ *
+ * PGLite here; Postgres through test/e2e/fold-hook-noop-6712-postgres.test.ts.
+ * CAPTURE_FOLD_NOOP=1 rewrites the fixture for the engine under test (only ever from the pre-hook commit).
+ */
+import { describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { admitWrite } from '../src/core/persistence/journal.ts';
+import { preparePageAdmission } from '../src/core/persistence/page-mutations.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { countPgliteStatements, readSqlTrace, type StatementRecord } from './helpers/statement-counter.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { waitFor } from './helpers/wait-for.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const FIXTURE = join(import.meta.dir, 'fixtures', 'fold-hook-noop-6712.json');
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const commit = (root: string, message: string) => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); };
+const note = (title: string, body: string) => `---\ntype: concept\ntitle: ${title}\n---\n\n${body}\n`;
+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };
+const setup = ({ root }: { root: string }) => {
+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');
+ for (const slug of ['a', 'b']) writeFileSync(join(root, `notes/${slug}.md`), note(`notes/${slug}`, `The committed body of notes/${slug}.`));
+ commit(root, 'notes');
+};
+
+const normalize = (sql: string) => sql.replace(/\s+/g, ' ').trim().replace(/statement_timeout = \d+/gi, 'statement_timeout = N');
+const isStatement = (record: StatementRecord) => record.kind === 'execute' || record.kind === 'simple';
+/** The committed transaction (begin to commit on one connection) one of whose statements `marks`, normalized. */
+function transactionOf(records: StatementRecord[], marks: (sql: string) => boolean): string[] {
+ const open = new Map<number, string[]>();
+ for (const record of [...records].sort((a, b) => a.t - b.t)) {
+ if (!isStatement(record)) continue;
+ const sql = normalize(record.sql), lower = sql.toLowerCase();
+ if (lower === 'begin' || lower.startsWith('begin;')) { open.set(record.conn, [sql]); continue; }
+ const group = open.get(record.conn);
+ if (!group) continue;
+ group.push(sql);
+ if (lower !== 'commit' && lower !== 'rollback') continue;
+ open.delete(record.conn);
+ if (lower === 'commit' && group.some(marks)) return group;
+ }
+ throw new Error(`no committed transaction carried the marked statement among ${records.length} records`);
+}
+
+/** Runs `act` and returns its statement records (PGLite: the datastore seam; Postgres: the wire trace in `trace`). */
+async function recorded(engine: BrainEngine, trace: string, act: () => Promise<void>, marks: (sql: string) => boolean): Promise<string[]> {
+ if (engine.kind === 'pglite') {
+ const counter = countPgliteStatements(engine as PGLiteEngine);
+ try { await act(); } finally { counter.stop(); }
+ return transactionOf(counter.records, marks);
+ }
+ const started = performance.timeOrigin + performance.now();
+ await act();
+ const ended = performance.timeOrigin + performance.now();
+ for (let i = 0; ; i++) {
+ try { return transactionOf(readSqlTrace(trace).filter(record => record.t >= started && record.t <= ended), marks); }
+ catch (error) { if (i >= 50) throw error; }
+ await Bun.sleep(100);
+ }
+}
+
+async function sequences(engine: BrainEngine, ctx: Parameters<typeof preparePageAdmission>[0], root: string, trace: string): Promise<Record<string, string[]>> {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ writeFileSync(join(root, 'notes/a.md'), note('notes/a', 'A committed change of notes/a.')); commit(root, 'change a, canonical');
+ const canonicalImport = await recorded(engine, trace, async () => { expect((await performManagedSync(engine, OPTS)).status).toBe('synced'); },
+ sql => sql === 'SAVEPOINT gbrain_pass_stamp_fold');
+ const putPage = await recorded(engine, trace, async () => {
+ const prepared = await preparePageAdmission(ctx, { operation: 'put_page', params: { slug: 'notes/new', request_id: randomUUID(), content: note('notes/new', 'An agent page.') } });
+ const { request_id } = await admitWrite(engine, prepared.admission!);
+ await waitFor(async () => (await engine.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE request_id=$1::uuid', [request_id]))[0]?.state === 'committed',
+ { timeoutMs: 30_000, label: 'the put_page commits' });
+ }, sql => sql.startsWith('INSERT INTO persistence_effects ('));
+ await disposePersistenceConsumer(engine);
+ return { put_page: putPage, canonical_import: canonicalImport };
+}
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? process.env.DATABASE_URL : undefined;
+ describe(`#6712 PR 4b post-effects hook is a no-op for other writes (${backend})`, () => {
+ test('a put_page and a canonical folded import publish the statements they published before the hook', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-fold-noop-')), trace = join(home, 'trace.jsonl');
+ try {
+ let got: Record<string, string[]> = {};
+ await withEnv(backend === 'postgres' ? { GBRAIN_SQL_TRACE: trace, GBRAIN_SQL_TRACE_LABEL: 'fold-noop' } : {}, () =>
+ managedBrain(async ({ engine, ctx, root }) => { got = await sequences(engine, ctx, root, trace); }, { ...(databaseUrl ? { databaseUrl } : {}), setup }));
+ const golden = existsSync(FIXTURE) ? JSON.parse(readFileSync(FIXTURE, 'utf8')) as Record<string, Record<string, string[]>> : {};
+ if (process.env.CAPTURE_FOLD_NOOP === '1') { mkdirSync(join(import.meta.dir, 'fixtures'), { recursive: true }); writeFileSync(FIXTURE, `${JSON.stringify({ ...golden, [backend]: got }, null, 1)}\n`); }
+ expect(got.put_page!.length).toBeGreaterThan(5);
+ expect(got.canonical_import!.length).toBeGreaterThan(5);
+ expect(got).toEqual(process.env.CAPTURE_FOLD_NOOP === '1' ? got : golden[backend]!);
+ } finally { rmSync(home, { recursive: true, force: true }); }
+ }, 180_000);
+ });
+}
diff --git a/test/sync-pass-fold-6712.test.ts b/test/sync-pass-fold-6712.test.ts
index 340afddb82..2651888d91 100644
--- a/test/sync-pass-fold-6712.test.ts
+++ b/test/sync-pass-fold-6712.test.ts
@@ -6,9 +6,10 @@
* - fold engages: a one-file commit whose file is already canonical (no writeback) publishes exactly one request carrying
* the stamp, its import, which folds it (`pass_stamp: folded`); no separate checkpoint request. A fold that quietly
* stops engaging costs this shape a second level and a checkpoint publication per commit (#6858 at 57 ms: 17.7 s -> 21.8 s).
- * - fold declines a writeback: a one-file commit whose file is not canonical is rewritten by its import (`file_written`), so
- * `foldPassCheckpoint` keeps the stamp path (sync-pass-fold.ts `prepared.file`): the import carries the fold offer and
- * publishes alone, and its own checkpoint request follows.
+ * - fold engages for a writeback (GBRA-108, option A): a one-file commit whose file is not canonical is rewritten by its
+ * import (`file_written`), which folds the stamp exactly once through its post-effects hook (sync-pass-fold.ts,
+ * coordinator.ts `afterEffects`), with no separate checkpoint request; the stamp records the import in
+ * `converged.writeback` (test/sync-pass-writeback-fold-6712.test.ts covers what that keeps busy).
* - fold probe 1: the last import's publication fails after its folded stamp ran (`publication:before_commit`): the stamp
* rolls back with it, so the checkpoint and the pass row stay where they were, and later runs converge.
* - fold probe 2: a hold at the target when the last import publishes: the import publishes alone (`pass_stamp_skipped`),
@@ -96,7 +97,7 @@ for (const backend of testBackends()) {
expect(await bodyOf(engine, 'notes/a')).toContain('A committed change of notes/a.');
}), 120_000);
- test('fold declines a writeback: a one-file commit whose import rewrites its file keeps the checkpoint request', () => brain(async ({ engine, root }) => {
+ test('fold engages for a writeback: a one-file commit whose import rewrites its file folds exactly once, no separate stamp request', () => brain(async ({ engine, root }) => {
expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
const after = await lastSequence(engine);
writeFileSync(join(root, 'notes/a.md'), '---\ntitle: notes/a\n---\nA committed change of notes/a.\n'); commit(root, 'change a, not canonical');
@@ -105,8 +106,12 @@ for (const backend of testBackends()) {
"SELECT intent->>'kind' AS kind, slug, state, intent->'stamp' ? 'fold' AS offered, outcome->>'pass_stamp' AS stamp, outcome->>'pass_stamp_skipped' AS skipped, outcome FROM persistence_requests WHERE sequence > $1 AND intent ? 'stamp' ORDER BY sequence", [after]);
expect((stamped[0]?.outcome as { persistence?: { file_written?: boolean } } | undefined)?.persistence?.file_written).toBe(true);
expect(stamped.map(({ outcome, ...row }) => row)).toEqual([
- { kind: 'managed_sync_import', slug: 'notes/a', state: 'committed', offered: true, stamp: null, skipped: null },
- { kind: 'managed_sync_checkpoint', slug: '__managed_sync_checkpoint__', state: 'committed', offered: false, stamp: null, skipped: null }]);
+ { kind: 'managed_sync_import', slug: 'notes/a', state: 'committed', offered: true, stamp: 'folded', skipped: null }]);
+ const head = git(root, 'rev-parse', 'HEAD');
+ expect(await checkpoint(engine)).toEqual({ last_commit: head, converged: head });
+ const [row] = await engine.executeRaw<{ request_id: string }>("SELECT id::text AS request_id FROM persistence_requests WHERE sequence > $1 AND intent->>'kind'='managed_sync_import'", [after]);
+ const [pass] = await engine.executeRaw<{ writeback: string[] | null }>("SELECT completed_keys->0->'obligations'->'converged'->'writeback' AS writeback FROM op_checkpoints WHERE op='managed-sync-pass'");
+ expect(pass!.writeback).toEqual([row!.request_id]);
}), 120_000);
test('fold probe 1: a failed publication of the last import rolls its folded stamp back; later runs converge', () => brain(async ({ engine, root }) => {
diff --git a/test/sync-pass-writeback-fold-6712.test.ts b/test/sync-pass-writeback-fold-6712.test.ts
new file mode 100644
index 0000000000..9a2eab4c77
--- /dev/null
+++ b/test/sync-pass-writeback-fold-6712.test.ts
@@ -0,0 +1,211 @@
+/**
+ * #6712 PR 4b (GBRA-108, option A): a writeback import carries the pass's folded stamp. The stamp publishes in the import's
+ * own transaction through the post-effects hook (coordinator.ts `afterEffects`, sync-pass-fold.ts), right after the import's
+ * Git effect is queued, and records that effect in the pass row (`converged.writeback`): the source is not idle until the
+ * effect commits.
+ *
+ * Protects:
+ * - a parked writeback effect keeps every following tick non-idle, and each of those passes converges without re-importing;
+ * - a kill between the publication commit and the Git effect (the effect left queued, as a dead process leaves it): the next
+ * tick is not idle; once the effect runs, the commit holds the writeback bytes, the next tick converges and then idles;
+ * - durability on: the writeback folds (no checkpoint request), the Git effect commits exactly the bytes the import wrote,
+ * the next tick converges at that commit and the one after is idle;
+ * - a writeback whose Git effect fails for good shows in doctor (`parked_effects`) and in `sync status` (blocked,
+ * `writeback_failed`), never as an idle, healthy source.
+ *
+ * PGLite here; Postgres through test/e2e/sync-pass-writeback-fold-6712-postgres.test.ts.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { checkParkedEffects } from '../src/commands/doctor/checks/parked-effects.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import { startPersistenceConsumer } from '../src/core/persistence/service.ts';
+import { MANAGED_SYNC_PASS_OP } from '../src/core/persistence/sync-pass-row.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { readSyncStatus } from '../src/core/persistence/sync-status.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { waitFor } from './helpers/wait-for.ts';
+
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const commit = (root: string, message: string) => { git(root, 'add', '-A'); git(root, 'commit', '-qm', message); };
+const note = (title: string, body: string) => `---\ntype: concept\ntitle: ${title}\n---\n\n${body}\n`;
+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };
+const setup = ({ root }: { root: string }) => {
+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');
+ git(root, 'config', 'user.name', 'Example'); git(root, 'config', 'user.email', '[email protected]');
+ for (const slug of ['a', 'b']) writeFileSync(join(root, `notes/${slug}.md`), note(`notes/${slug}`, `The committed body of notes/${slug}.`));
+ commit(root, 'notes');
+};
+/** A one-file commit whose file is not canonical: its import rewrites it (a writeback). */
+const writebackCommit = (root: string) => { writeFileSync(join(root, 'notes/a.md'), '---\ntitle: notes/a\n---\nA committed change of notes/a.\n'); commit(root, 'change a, not canonical'); };
+const lastSequence = async (engine: BrainEngine) => Number((await engine.executeRaw<{ s: number }>('SELECT COALESCE(max(sequence),0) AS s FROM persistence_requests'))[0]!.s);
+/** The newest import of notes/a and its Git effect. */
+async function writebackEffect(engine: BrainEngine): Promise<{ request_id: string; write_id: string; effect_id: string; state: string; data: Record<string, unknown> } | undefined> {
+ return (await engine.executeRaw<{ request_id: string; write_id: string; effect_id: string; state: string; data: Record<string, unknown> }>(
+ `SELECT r.request_id::text AS request_id, r.id::text AS write_id, e.id::text AS effect_id, e.state, e.data FROM persistence_requests r JOIN persistence_effects e ON e.request_id=r.id AND e.kind='git'
+ WHERE r.slug='notes/a' AND r.intent->>'kind'='managed_sync_import' ORDER BY r.sequence DESC LIMIT 1`))[0];
+}
+const effectSettled = (engine: BrainEngine) => waitFor(async () => ['committed', 'failed'].includes((await writebackEffect(engine))?.state ?? ''),
+ { timeoutMs: 60_000, label: 'the writeback Git effect settles' });
+/** An effect-row update as the persistence writer makes it (protocol 2, which the writer guard requires). */
+const asWriter = (engine: BrainEngine, sql: string, params: unknown[] = []) => engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('gbrain.persistence_protocol','2',true)");
+ await tx.executeRaw(sql, params);
+});
+/** Parks the writeback's Git effect as five consecutive failures leave it (effects.ts `parkEffectTarget`). */
+const park = (engine: BrainEngine, effectId: string) => asWriter(engine, `UPDATE persistence_effects SET state='failed', error_code='targets_parked',
+ data=data||jsonb_build_object('parked', jsonb_build_array(jsonb_build_object('slug','notes/a','error_code','git_unavailable'))) WHERE id=$1`, [effectId]);
+/** One sync tick: its status and the pass kind it recorded (`idle` only when it read nothing). */
+async function tick(engine: BrainEngine): Promise<{ status: string; kind: string }> {
+ const result = await performManagedSync(engine, OPTS);
+ const [row] = await engine.executeRaw<{ kind: string }>("SELECT completed_keys->0->'telemetry'->>'kind' AS kind FROM op_checkpoints WHERE op=$1", [MANAGED_SYNC_PASS_OP]);
+ return { status: result.status as string, kind: row!.kind };
+}
+const lastCommit = async (engine: BrainEngine) => (await engine.executeRaw<{ c: string | null }>("SELECT last_commit AS c FROM sources WHERE id='default'"))[0]!.c;
+/** The requests of this pass that carried the stamp, with how each published it. */
+const stamped = (engine: BrainEngine, after: number) => engine.executeRaw<{ kind: string; stamp: string | null }>(
+ "SELECT intent->>'kind' AS kind, outcome->>'pass_stamp' AS stamp FROM persistence_requests WHERE sequence > $1 AND intent ? 'stamp' ORDER BY sequence", [after]);
+const enableDurability = (engine: BrainEngine) => engine.executeRaw("UPDATE persistence_host_bindings SET git_durability='enabled'");
+
+afterEach(() => installFaultHook(undefined));
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? process.env.DATABASE_URL : undefined;
+ const brain = (run: Parameters<typeof managedBrain>[0]) => managedBrain(run, { ...(databaseUrl ? { databaseUrl } : {}), setup });
+
+ describe(`#6712 PR 4b writeback folds its stamp, its Git effect keeps the source busy (${backend})`, () => {
+ test('a parked writeback effect keeps every next tick non-idle; each pass converges without importing again', () => brain(async ({ engine, root }) => {
+ expect((await tick(engine)).status).toBe('first_sync');
+ writebackCommit(root);
+ expect((await tick(engine)).status).toBe('synced');
+ await effectSettled(engine);
+ const effect = (await writebackEffect(engine))!;
+ await park(engine, effect.effect_id);
+ const imports = await lastSequence(engine);
+ expect([await tick(engine), await tick(engine)].map(t => t.kind === 'idle')).toEqual([false, false]);
+ expect((await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_requests WHERE sequence > $1 AND intent->>'kind'='managed_sync_import'", [imports]))[0]!.n).toBe(0);
+ }), 180_000);
+
+ test('a kill between the publication commit and the Git effect: not idle meanwhile; the effect runs, the source converges, nothing is lost', () => brain(async ({ engine, root }) => {
+ expect((await tick(engine)).status).toBe('first_sync');
+ await enableDurability(engine);
+ const from = git(root, 'rev-parse', 'HEAD');
+ writebackCommit(root);
+ const target = git(root, 'rev-parse', 'HEAD');
+ // The process dies right after the import's publication commits: its Git effect stays queued, unclaimed.
+ installFaultHook(async (point, detail) => {
+ if (point !== 'publication:after_commit' || !detail.requestId) return;
+ await asWriter(engine, `UPDATE persistence_effects SET next_attempt_at=now()+interval '1 hour'
+ WHERE request_id=(SELECT id FROM persistence_requests WHERE request_id=$1::uuid) AND kind='git' AND state='queued'`, [detail.requestId]);
+ });
+ expect((await tick(engine)).status).toBe('synced');
+ installFaultHook(undefined);
+ expect((await writebackEffect(engine))!.state).toBe('queued');
+ expect(git(root, 'rev-parse', 'HEAD')).toBe(target);
+ expect((await tick(engine)).kind).not.toBe('idle');
+ expect((await tick(engine)).kind).not.toBe('idle');
+ // The owner comes back: the queued effect runs.
+ await asWriter(engine, "UPDATE persistence_effects SET next_attempt_at=now() WHERE kind='git' AND state='queued'");
+ startPersistenceConsumer(engine, { engine: engine.kind }).wake(true);
+ await effectSettled(engine);
+ expect((await writebackEffect(engine))!.state).toBe('committed');
+ const head = git(root, 'rev-parse', 'HEAD');
+ expect(head).not.toBe(target);
+ expect(git(root, 'rev-parse', `${head}^`)).toBe(target);
+ expect(git(root, 'show', `${head}:notes/a.md`)).toBe(readFileSync(join(root, 'notes/a.md'), 'utf8').trimEnd());
+ expect(git(root, 'diff', '--name-only', target, head)).toBe('notes/a.md');
+ expect(from).not.toBe(target);
+ const converge = await tick(engine);
+ expect(converge.kind).not.toBe('idle');
+ expect(await lastCommit(engine)).toBe(head);
+ expect((await tick(engine)).kind).toBe('idle');
+ expect((await engine.getPage('notes/a', { sourceId: 'default' }))?.compiled_truth).toContain('A committed change of notes/a.');
+ }), 180_000);
+
+ test('durability on: the writeback folds, its effect commits exactly the bytes written, the next tick converges and the one after idles', () => brain(async ({ engine, root }) => {
+ expect((await tick(engine)).status).toBe('first_sync');
+ await enableDurability(engine);
+ writebackCommit(root);
+ const target = git(root, 'rev-parse', 'HEAD'), after = await lastSequence(engine);
+ expect((await tick(engine)).status).toBe('synced');
+ expect(await stamped(engine, after)).toEqual([{ kind: 'managed_sync_import', stamp: 'folded' }]);
+ await effectSettled(engine);
+ const effect = (await writebackEffect(engine))!;
+ expect(effect.state).toBe('committed');
+ const head = git(root, 'rev-parse', 'HEAD');
+ expect(git(root, 'rev-parse', `${head}^`)).toBe(target);
+ expect(git(root, 'diff', '--name-only', target, head)).toBe('notes/a.md');
+ expect(git(root, 'show', `${head}:notes/a.md`)).toBe(readFileSync(join(root, 'notes/a.md'), 'utf8').trimEnd());
+ const converge = await tick(engine);
+ expect(await lastCommit(engine)).toBe(head);
+ expect(converge.status === 'up_to_date' && converge.kind === 'idle').toBe(false);
+ expect(await tick(engine)).toEqual({ status: 'up_to_date', kind: 'idle' });
+ }), 180_000);
+
+ test('durability on, the effect commits before the confirm round: HEAD moved by exactly the pass\'s bytes ends the pass on its stamp, no level read', () => brain(async ({ engine, root }) => {
+ expect((await tick(engine)).status).toBe('first_sync');
+ await enableDurability(engine);
+ writebackCommit(root);
+ const target = git(root, 'rev-parse', 'HEAD'), after = await lastSequence(engine);
+ const reads: number[] = [];
+ installFaultHook(async (point, detail) => {
+ if (point === 'sync:level_read') reads.push(detail.round as number);
+ if (point !== 'sync:round_start' || (detail.round as number) < 2) return;
+ startPersistenceConsumer(engine, { engine: engine.kind }).wake(true);
+ await effectSettled(engine);
+ });
+ expect((await tick(engine)).status).toBe('synced');
+ installFaultHook(undefined);
+ expect(reads).toEqual([1]);
+ expect(await stamped(engine, after)).toEqual([{ kind: 'managed_sync_import', stamp: 'folded' }]);
+ const head = git(root, 'rev-parse', 'HEAD');
+ expect(git(root, 'rev-parse', `${head}^`)).toBe(target);
+ expect(await lastCommit(engine)).toBe(target);
+ expect((await tick(engine)).kind).not.toBe('idle');
+ expect(await lastCommit(engine)).toBe(head);
+ expect(await tick(engine)).toEqual({ status: 'up_to_date', kind: 'idle' });
+ }), 180_000);
+
+ test('durability on, a foreign commit lands beside the effect\'s: the confirm round reads in full and imports it', () => brain(async ({ engine, root }) => {
+ expect((await tick(engine)).status).toBe('first_sync');
+ await enableDurability(engine);
+ writebackCommit(root);
+ const reads: number[] = [];
+ installFaultHook(async (point, detail) => {
+ if (point === 'sync:level_read') reads.push(detail.round as number);
+ if (point !== 'sync:round_start' || detail.round !== 2) return;
+ startPersistenceConsumer(engine, { engine: engine.kind }).wake(true);
+ await effectSettled(engine);
+ writeFileSync(join(root, 'notes/b.md'), note('notes/b', 'A foreign change of notes/b.'));
+ commit(root, 'foreign change of b');
+ });
+ expect((await tick(engine)).status).toBe('synced');
+ installFaultHook(undefined);
+ expect(reads.slice(0, 2)).toEqual([1, 2]);
+ expect(await lastCommit(engine)).toBe(git(root, 'rev-parse', 'HEAD'));
+ expect((await engine.getPage('notes/b', { sourceId: 'default' }))?.compiled_truth).toContain('A foreign change of notes/b.');
+ }), 180_000);
+
+ test('a writeback whose Git effect fails for good shows in doctor and in sync status, never as an idle, healthy source', () => brain(async ({ engine, root }) => {
+ expect((await tick(engine)).status).toBe('first_sync');
+ writebackCommit(root);
+ expect((await tick(engine)).status).toBe('synced');
+ await effectSettled(engine);
+ const effect = (await writebackEffect(engine))!;
+ await park(engine, effect.effect_id);
+ const doctor = await checkParkedEffects(engine, ['default']);
+ expect(doctor.status).toBe('warn');
+ expect(JSON.stringify(doctor.details)).toContain(effect.request_id);
+ const status = await readSyncStatus(engine, 'default', { detail: false });
+ expect({ state: status.state, reason: status.reason }).toEqual({ state: 'blocked', reason: 'writeback_failed' });
+ expect(JSON.stringify(status.next)).toContain('retry-effects');
+ expect((await tick(engine)).kind).not.toBe('idle');
+ const again = await readSyncStatus(engine, 'default', { detail: false });
+ expect({ state: again.state, reason: again.reason }).toEqual({ state: 'blocked', reason: 'writeback_failed' });
+ }), 180_000);
+ });
+}