Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

GBRA-217: close the adversarial-review findings on page change reasons

garrytan336074e580b9
diff --git a/docs/guides/page-history.md b/docs/guides/page-history.md
index 2cde438559..f3470bd6b5 100644
--- a/docs/guides/page-history.md
+++ b/docs/guides/page-history.md
@@ -25,7 +25,7 @@ on the starter surface can pass it too. On the CLI the same parameter is `--reas
A reason is one line of at most 500 characters. Tabs and line breaks become
spaces, other control characters are removed, and an empty reason counts as
none. It is checked before the write is accepted, so a refused reason leaves no
-copy anywhere:
+copy anywhere, except opt-in `serve --log-full-params` logging:
- longer than 500 characters: `change_reason_rejected` with reason
`reason_too_long` (the wire `error` is `invalid_params`), naming the length
@@ -68,7 +68,10 @@ Every write result says where its reason went in `reason_recorded`:
reason stays in gbrain's history but is in no commit. Nothing needs fixing,
and retrying the write would be wrong.
- `private`: the page is private, so its reason stays out of every commit
- message, group commits for other pages included.
+ message, group commits for other pages included. Visibility is checked when
+ the commit is made: a page that a later page in the same `put_pages` group
+ made private (through `derived_from`, for example) commits without its
+ reason, and so does a queued commit whose page a later write made private.
- `not_file_backed`: the page has no file (database-only), so the reason is in
gbrain's history only.
- `no_repository`: the brain has no Git repository (below).
@@ -197,16 +200,28 @@ reaches every copy of a reason that quotes the claim:
Purge refuses before it changes anything when it cannot read that history:
-- `reason_purge_scan_failed`: reading the trailers failed (a Git error or a
- timeout). Nothing was changed; wait, then run the same purge again.
+- `reason_purge_scan_failed`: reading the trailers failed: the source's folder
+ is missing or moved, `git` is not installed, Git refuses the repository (an
+ unsafe owner or a corrupt `.git/config`), or the read timed out. Nothing was
+ changed; fix the cause or wait, then run the same purge again.
- `reason_purge_scan_capped`: the history is longer than 200,000 commits. Your
agent asks you to choose: purge now and check only the newest commits, with
`--reason-scan-limit <n>` set to the number you pick, or stop. With a limit, a
reason in an older commit is not tombstoned and a re-import could store it
again; the receipt says so.
-On a source with no Git checkout there is no history to read, so purge redacts
-the database copies and never raises either refusal.
+A source counts as having no Git checkout only when it has no folder, or when
+Git itself says its folder is in no repository. Then there is no history to
+read, so purge redacts the database copies and never raises either refusal.
+
+`gbrain delete <slug> --purge` also reaches the purged page's own reasons. Before
+anything is deleted it reads every reason the page's versions and write
+receipts recorded, then removes them from the page's receipts and stored
+intents, and drops the commit line and trailers from every Git effect of the
+page, queued, failed or kept, with the same `purge_blocked_pending_recovery`
+refusal while one carrying a reason is being written. Its receipt checks both
+stores (`persistence_requests`, `persistence_effects`). Commits already in the
+repository keep their messages, as above.
## Choosing how to record a change
diff --git a/src/core/facts/purge-reasons.ts b/src/core/facts/purge-reasons.ts
index 973cf0107e..56ac2c88a1 100644
--- a/src/core/facts/purge-reasons.ts
+++ b/src/core/facts/purge-reasons.ts
@@ -7,6 +7,8 @@
*/
import type { BrainEngine } from '../engine.ts';
import { opError } from '../ops/contract.ts';
+import { REASON_TRAILER_KEY } from '../persistence/change-reason.ts';
+import type { IntentRedactionTarget } from '../persistence/intent-redaction.ts';
import { reasonScanCap, scanTrailersCarrying } from '../reason-trailers.ts';
import { claimNeedles } from './purge-verify.ts';
@@ -52,6 +54,7 @@ export async function recordReasonTombstones(tx: BrainEngine, input: { sourceId:
if (!plan.sourceRoot) return 0;
const recheck = await scanTrailersCarrying(plan.sourceRoot, [input.claim], { from: plan.head, limit: reasonScanCap('purge') });
if (recheck.status === 'failed') throw scanFailed(input.sourceId, input.rawId, recheck.detail);
+ if (recheck.status === 'no_repository') throw scanFailed(input.sourceId, input.rawId, 'the Git checkout scanned before the purge is gone');
const hits = [...plan.hits, ...(recheck.status === 'complete' ? recheck.hits : [])];
if (!hits.length) return 0;
return (await tx.executeRaw(`INSERT INTO reason_purge_tombstones(source_id, commit_sha, path)
@@ -59,6 +62,12 @@ export async function recordReasonTombstones(tx: BrainEngine, input: { sourceId:
[input.sourceId, hits.map(hit => hit.commit), hits.map(hit => hit.path)])).length;
}
+/** A Git effect a worker is running may have its commit message in flight: the purge waits for it. */
+const gitCommitRunning = (requestId: string) => opError('purge_blocked_pending_recovery', 'A Git commit that carries this content is being written, so nothing was purged.',
+ `Request ${requestId} has a Git effect running whose commit message quotes the purged content. Wait for it to finish, then retry the purge with the same request id.`,
+ { fix: { argv: ['gbrain', 'write-request', '--', requestId], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Shows the blocking write\'s state, read-only; retry the purge once it is final.' } });
+
/**
* Git effects of the source whose commit message would carry the claim: queued, failed and retained committed ones are
* redacted in place (`commit_line` becomes "[purged]", a carrying trailer is dropped); one a worker is running refuses
@@ -75,12 +84,7 @@ export async function redactGitEffectReasons(tx: BrainEngine, sourceId: string,
const data = { ...row.data };
const listed = Array.isArray(data.commit_trailers) ? data.commit_trailers : null;
if (!carries(data.commit_line) && !carries(data.commit_trailer) && !listed?.some(carries)) continue;
- if (row.state === 'running') {
- throw opError('purge_blocked_pending_recovery', 'A Git commit that carries this content is being written, so nothing was purged.',
- `Request ${row.request_id} has a Git effect running whose commit message quotes the claim. Wait for it to finish, then retry the purge with the same request id.`,
- { fix: { argv: ['gbrain', 'write-request', '--', row.request_id], consent: [], actor: 'agent', requires_exclusive: false,
- why: 'Shows the blocking write\'s state, read-only; retry the purge once it is final.' } });
- }
+ if (row.state === 'running') throw gitCommitRunning(row.request_id);
if (carries(data.commit_line)) data.commit_line = '[purged]';
if (carries(data.commit_trailer)) delete data.commit_trailer;
if (listed) {
@@ -92,3 +96,43 @@ export async function redactGitEffectReasons(tx: BrainEngine, sourceId: string,
}
return redacted;
}
+
+/**
+ * Page purge, inside its transaction and before the cascade: the page's own change reasons, those its snapshots carry and
+ * those its requests recorded (a creation's reason is on no snapshot). They join the claim needles for the slug's receipts.
+ */
+export async function pageChangeReasons(tx: BrainEngine, sourceId: string, slug: string, pageId: number): Promise<string[]> {
+ const rows = await tx.executeRaw<{ reason: string | null }>(`SELECT change_reason AS reason FROM page_versions WHERE page_id = $1
+ UNION SELECT intent->>'reason' FROM persistence_requests WHERE source_id = $2 AND slug = $3
+ UNION SELECT outcome->'reason_recorded'->>'reason' FROM persistence_requests WHERE source_id = $2 AND slug = $3`, [pageId, sourceId, slug]);
+ return [...new Set(rows.map(row => row.reason).filter((reason): reason is string => !!reason && reason !== '[purged]'))];
+}
+
+/** The slug's requests whose intent or outcome records a reason, compacted ones included (compaction keeps the outcome). */
+export async function requestsRecordingReasons(tx: BrainEngine, sourceId: string, slug: string): Promise<IntentRedactionTarget[]> {
+ return tx.executeRaw<IntentRedactionTarget>(`SELECT id::text AS id, principal_kind, principal_id FROM persistence_requests
+ WHERE source_id = $1 AND slug = $2 AND ((intent->>'reason') IS NOT NULL OR (outcome->'reason_recorded') IS NOT NULL) ORDER BY sequence LIMIT 10000`, [sourceId, slug]);
+}
+
+/**
+ * Page purge: every Git effect of the slug, in any state, loses its commit line and trailers (they name the page's reasons);
+ * a running one whose trailers carry a reason refuses `purge_blocked_pending_recovery`. Returns the effects stripped.
+ */
+export async function stripPageGitNotes(tx: BrainEngine, sourceId: string, slug: string): Promise<number> {
+ const rows = await tx.executeRaw<{ id: string; state: string; request_id: string; data: Record<string, unknown> }>(`SELECT e.id::text AS id, e.state, r.request_id::text AS request_id, e.data
+ FROM persistence_effects e JOIN persistence_requests r ON r.id = e.request_id
+ WHERE e.source_id = $1 AND e.kind = 'git' AND e.data->>'slug' = $2
+ AND ((e.data->'commit_line') IS NOT NULL OR (e.data->'commit_trailers') IS NOT NULL OR (e.data->'commit_trailer') IS NOT NULL) ORDER BY e.id FOR UPDATE OF e`, [sourceId, slug]);
+ const reasonTrailer = (value: unknown) => typeof value === 'string' && value.startsWith(`${REASON_TRAILER_KEY}:`);
+ let stripped = 0;
+ for (const row of rows) {
+ const { commit_line: _line, commit_trailers: listed, commit_trailer: legacy, ...data } = row.data;
+ if (row.state === 'running') {
+ if (reasonTrailer(legacy) || (Array.isArray(listed) && listed.some(reasonTrailer))) throw gitCommitRunning(row.request_id);
+ continue;
+ }
+ await tx.executeRaw('UPDATE persistence_effects SET data = $2::text::jsonb WHERE id = $1::bigint', [row.id, JSON.stringify(data)]);
+ stripped++;
+ }
+ return stripped;
+}
diff --git a/src/core/facts/purge-verify.ts b/src/core/facts/purge-verify.ts
index 1f5c61b996..b3ad2dc275 100644
--- a/src/core/facts/purge-verify.ts
+++ b/src/core/facts/purge-verify.ts
@@ -276,11 +276,20 @@ async function probeNamedRows(engine: BrainEngine, entry: InventoryEntry, source
}
/** W1 (BELIEF_LEDGER.md 6.5): a queued effect whose payload still carries the purged text would write it back after the purge. */
-async function effectPayloadReport(engine: BrainEngine, sourceId: string, needles: readonly string[], deadline: number, removed: number): Promise<StoreReport> {
+async function effectPayloadReport(engine: BrainEngine, sourceId: string, needles: readonly string[], deadline: number, removed: number,
+ page?: { slug: string; reasons: readonly string[] }): Promise<StoreReport> {
const list = needles.filter(Boolean).slice(0, 32);
- if (!list.length) return { store: 'persistence_effects', status: 'not_present' };
- const params: unknown[] = [sourceId, ...list.flatMap(n => [n.toLowerCase(), JSON.stringify(n).slice(1, -1).toLowerCase()])];
+ const reasons = (page?.reasons ?? []).filter(Boolean).slice(0, 32);
+ if (!list.length && !reasons.length) return { store: 'persistence_effects', status: 'not_present' };
+ const forms = (n: string) => [n.toLowerCase(), JSON.stringify(n).slice(1, -1).toLowerCase()];
+ const params: unknown[] = [sourceId, ...list.flatMap(forms)];
const ors = list.flatMap((_, i) => ['data', 'outcome', 'recovery'].map(c => textMatch(`COALESCE(e.${c}::text,'')`, 2 + i * 2)));
+ // GBRA-217: a purged page's reasons are searched in its own Git effects only (a short reason is not a claim).
+ if (page && reasons.length) {
+ const at = params.push(page.slug);
+ params.push(...reasons.flatMap(forms));
+ ors.push(`(e.kind = 'git' AND e.data->>'slug' = $${at} AND (${reasons.map((_, i) => textMatch('e.data', at + 1 + i * 2)).join(' OR ')}))`);
+ }
const sql = `SELECT 'effect:' || e.id || ' ' || e.kind || ' ' || e.state AS item FROM persistence_effects e WHERE e.source_id = $1 AND (${ors.join(' OR ')})`;
const counted = await boundedCount(engine, sql, params, deadline);
if ('unverified' in counted) return { store: 'persistence_effects', status: 'unverified', reason: counted.unverified, removed };
@@ -571,7 +580,7 @@ export async function verifyFactPurge(engine: BrainEngine, input: { target: Purg
}
/** In-process context a page purge keeps for its receipt (never journaled): the page's claims as probe needles, and row ids. */
-export interface PagePurgeContext { needles: string[]; factIds: number[]; pageId: number; paths: string[]; segmentShas: string[]; segmentClaims?: string[]; ledgerClaims?: string[]; ledger?: LedgerPurgeReport | null }
+export interface PagePurgeContext { needles: string[]; reasons?: string[]; factIds: number[]; pageId: number; paths: string[]; segmentShas: string[]; segmentClaims?: string[]; ledgerClaims?: string[]; ledger?: LedgerPurgeReport | null }
const outOfReach = (engine: BrainEngine): StoreReport[] => OUT_OF_REACH_RESIDUALS.map(r => ({ store: r.store, status: 'out_of_reach' as const,
detail: r.store === 'database_physical' ? `${r.detail}${engine.kind === 'pglite' ? ' PGLite has no autovacuum.' : ' On Postgres the operator runs VACUUM; WAL archives, replicas and PITR windows are outside gbrain.'}` : r.detail }));
@@ -632,13 +641,15 @@ export async function verifyPagePurge(engine: BrainEngine, input: { sourceId: st
await keyed('trust_proposals', `SELECT 1 FROM trust_proposals WHERE source_id=$1 AND ((target_table='pages' AND target_id=$2) OR (related_table='pages' AND related_id=$2)
OR (target_table='facts' AND target_id=ANY($3::bigint[])) OR (related_table='facts' AND related_id=ANY($3::bigint[])))`, [src, context.pageId, context.factIds]);
}
- const textChecks = needles.flatMap((n, i) => ['intent', 'outcome', 'error_detail', 'error_message'].map(c => `strpos(lower(COALESCE(${c}::text,'')),$${4 + i})>0`));
+ const reasons = context?.reasons ?? [];
+ const textAt = (list: readonly string[], from: number) => list.flatMap((n, i) => ['intent', 'outcome', 'error_detail', 'error_message'].map(c => `strpos(lower(COALESCE(${c}::text,'')),$${from + i})>0`));
+ const textChecks = textAt(needles, 4), reasonChecks = textAt(reasons, 4 + needles.length);
await keyed('persistence_requests', `SELECT 1 FROM persistence_requests WHERE source_id=$1 AND request_id<>$3::uuid AND (
- (slug=$2 AND intent IS NOT NULL AND state IN ('committed','conflict','failed','cancelled'))${textChecks.length ? ` OR ${textChecks.join(' OR ')}` : ''})`,
- [src, slug, input.requestId, ...needles.map(n => n.toLowerCase())]);
+ (slug=$2 AND intent IS NOT NULL AND state IN ('committed','conflict','failed','cancelled'))${textChecks.length ? ` OR ${textChecks.join(' OR ')}` : ''}${reasonChecks.length ? ` OR (slug=$2 AND (${reasonChecks.join(' OR ')}))` : ''})`,
+ [src, slug, input.requestId, ...needles.map(n => n.toLowerCase()), ...reasons.map(n => n.toLowerCase())]);
if (context) {
stores.push(...await ledgerReports(engine, src, context.ledgerClaims ?? needles, context.ledger, deadline));
- stores.push(await effectPayloadReport(engine, src, needles, deadline, removed.persistence_effects ?? 0));
+ stores.push(await effectPayloadReport(engine, src, needles, deadline, removed.persistence_effects ?? 0, { slug, reasons }));
}
stores.push(...await sweptInventoryReports(engine, new Set(stores.map(s => s.store)), src, needles, removed, deadline, false));
for (const entry of DELETION_INVENTORY) {
diff --git a/src/core/hardened-git.ts b/src/core/hardened-git.ts
index 25abfa0d66..9ae202ed8c 100644
--- a/src/core/hardened-git.ts
+++ b/src/core/hardened-git.ts
@@ -60,7 +60,7 @@ export function hardenedGitEnvironment(): NodeJS.ProcessEnv {
...safeDirectoryEnv([...operatorConfigSafeDirectories(), ...envSafeDirectories()]) };
}
-export type HardenedGitResult = { ok: true; stdout: Buffer } | { ok: false; reason: 'exit' | 'timeout' | 'too_large' | 'unavailable'; status?: number };
+export type HardenedGitResult = { ok: true; stdout: Buffer } | { ok: false; reason: 'exit' | 'timeout' | 'too_large' | 'unavailable'; status?: number; stderr?: string };
/**
* GBRA-217: the one `git log` gbrain runs in an untrusted checkout, the reason-trailer read (`reason-trailers.ts`). A
@@ -112,16 +112,19 @@ export function assertHardenedGitArgs(args: readonly string[]): void {
if (!ok) throw new Error(`hardened git refuses \`git ${args.slice(0, 2).join(' ')}\`: only filter-free plumbing may run in an untrusted checkout (see src/core/hardened-git.ts)`);
}
-/** Runs `git -C <root> <args>` synchronously under the hardening above, within `timeoutMs` and `maxBytes` of stdout. */
-export function hardenedGitSync(root: string, args: string[], limits: { timeoutMs: number; maxBytes: number }): HardenedGitResult {
+/**
+ * Runs `git -C <root> <args>` synchronously under the hardening above, within `timeoutMs` and `maxBytes` of stdout. With
+ * `stderr`, a nonzero exit carries Git's message, so a caller can tell one failure from another.
+ */
+export function hardenedGitSync(root: string, args: string[], limits: { timeoutMs: number; maxBytes: number; stderr?: boolean }): HardenedGitResult {
assertHardenedGitArgs(args);
const run = spawnSync('git', [...HARDENED_GIT_ARGS, '-C', root, ...args],
- { env: hardenedGitEnvironment(), stdio: ['ignore', 'pipe', 'ignore'], timeout: limits.timeoutMs, maxBuffer: limits.maxBytes, killSignal: 'SIGKILL' });
+ { env: hardenedGitEnvironment(), stdio: ['ignore', 'pipe', limits.stderr ? 'pipe' : 'ignore'], timeout: limits.timeoutMs, maxBuffer: limits.maxBytes, killSignal: 'SIGKILL' });
const code = (run.error as NodeJS.ErrnoException | undefined)?.code;
if (code === 'ETIMEDOUT') return { ok: false, reason: 'timeout' };
if (code === 'ENOBUFS') return { ok: false, reason: 'too_large' };
if (run.error) return { ok: false, reason: 'unavailable' };
- if (run.status !== 0) return { ok: false, reason: 'exit', ...(run.status === null ? {} : { status: run.status }) };
+ if (run.status !== 0) return { ok: false, reason: 'exit', ...(run.status === null ? {} : { status: run.status }), ...(limits.stderr && run.stderr ? { stderr: run.stderr.toString('utf8') } : {}) };
return { ok: true, stdout: run.stdout };
}
diff --git a/src/core/persistence/change-reason.ts b/src/core/persistence/change-reason.ts
index 2d05e81924..86ef643ecf 100644
--- a/src/core/persistence/change-reason.ts
+++ b/src/core/persistence/change-reason.ts
@@ -60,6 +60,46 @@ export function withReasonNote(path: string, reason: string, base?: GitCommitNot
: { subject: '', line: `${path}: ${reason}`, trailers: [trailer] };
}
+/** A note without what `withReasonNote` added: a reason-only note goes, a merged one keeps its own subject, line and trailers. */
+export function withoutReasonNote(note: GitCommitNote): GitCommitNote | undefined {
+ const key = `${REASON_TRAILER_KEY}: `;
+ const reasons = (note.trailers ?? []).filter(trailer => trailer.startsWith(key)).map(trailer => trailer.slice(key.length));
+ if (!reasons.length) return note;
+ if (note.subject === '' && reasons.includes(note.line)) return undefined;
+ const trailers = (note.trailers ?? []).filter(trailer => !trailer.startsWith(key));
+ return { subject: note.subject, line: note.line, ...(trailers.length ? { trailers } : {}) };
+}
+
+async function pageWorldVisible(engine: SqlEngine, sourceId: string, slug: string): Promise<boolean> {
+ const [page] = await engine.executeRaw<{ world: boolean }>(
+ `SELECT ${privatePagesFilterFragment('p')} AS world FROM pages p WHERE p.source_id = $1 AND p.slug = $2 AND p.deleted_at IS NULL`, [sourceId, slug]);
+ return page?.world === true;
+}
+
+/**
+ * The note a file commits with, checked against its page's visibility at commit time: a page that is not world-visible
+ * any more (a later member of its group, or a later write, made it private) commits without its reason.
+ */
+export async function visibleCommitNote(engine: SqlEngine, sourceId: string, slug: unknown, note: GitCommitNote | undefined): Promise<GitCommitNote | undefined> {
+ if (!note || typeof slug !== 'string' || withoutReasonNote(note) === note) return note;
+ return await pageWorldVisible(engine, sourceId, slug) ? note : withoutReasonNote(note);
+}
+
+/**
+ * A strict group, once every member has applied and before its one commit: each member's note checked as above, and a
+ * member whose reason is dropped reports `git: 'private'` on its receipt.
+ */
+export async function settleGroupCommitNotes(engine: SqlEngine, members: Array<{ row: Pick<WriteRequest, 'source_id' | 'slug'>; note: GitCommitNote | undefined; outcome: Record<string, unknown> }>): Promise<Array<GitCommitNote | undefined>> {
+ const notes: Array<GitCommitNote | undefined> = [];
+ for (const { row, note, outcome } of members) {
+ const visible = await visibleCommitNote(engine, row.source_id, row.slug, note);
+ const recorded = outcome.reason_recorded as ReasonRecorded | undefined;
+ if (visible !== note && recorded) outcome.reason_recorded = { ...recorded, git: 'private' };
+ notes.push(visible);
+ }
+ return notes;
+}
+
export type ReasonGit = 'committed' | 'queued' | 'superseded' | 'not_file_backed' | 'private' | 'no_repository' | 'none';
export interface ReasonRecorded { reason: string; version: boolean; version_why?: 'page_created' | 'no_change'; git: ReasonGit }
@@ -78,9 +118,7 @@ export function withChangeReason(row: WriteRequest, prepared: PreparedMutation):
const outcome = await apply(tx, preimage);
const stamped = pageId === null || prepared.noop ? [] : await tx.executeRaw<{ id: number }>(
'UPDATE page_versions SET change_reason = $2 WHERE page_id = $1 AND id > $3 RETURNING id', [pageId, reason, Number(before?.last ?? 0)]);
- const [page] = await tx.executeRaw<{ world: boolean }>(
- `SELECT ${privatePagesFilterFragment('p')} AS world FROM pages p WHERE p.source_id = $1 AND p.slug = $2 AND p.deleted_at IS NULL`, [row.source_id, row.slug]);
- const world = page?.world === true;
+ const world = await pageWorldVisible(tx, row.source_id, row.slug);
let git: ReasonGit;
if (!prepared.file) git = row.authority.databaseOnlyReason === 'no_repo_configured' ? 'no_repository' : world ? 'not_file_backed' : 'private';
else if (prepared.noop) git = 'none';
diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.ts
index 918ae5e630..451ad86640 100644
--- a/src/core/persistence/effects.ts
+++ b/src/core/persistence/effects.ts
@@ -48,6 +48,7 @@ import { EFFECT_FAULT_POINTS, faultPoint } from './fault-points.ts';
import { dispatchFactsBackstopEffect } from './effect-facts.ts';
import { runLinksEffect } from './effect-links.ts';
import { PARK_AFTER_FAILURES, WITHHELD_BY_MIRROR, type EffectRecovery, type GitCommitNote, type PersistenceEffect, type SkippedTarget } from './effect-model.ts';
+import { visibleCommitNote } from './change-reason.ts';
import { fileContentHash } from './large-file.ts';
import { isSyncMetafile, metafileIsPage, readMetafilePagesMode } from '../sync.ts';
import { diskMetafileHeads } from '../sync-metafile-pages.ts';
@@ -315,11 +316,15 @@ async function singleFileGitTarget(engine: BrainEngine, effect: PersistenceEffec
return relative(binding.local_path, path).split(sep).join('/');
}
-/** The commit metadata a single-file Git effect's preparer recorded, if any. */
-function gitCommitNote(effect: PersistenceEffect): GitCommitNote | undefined {
+/**
+ * The commit metadata a single-file Git effect's preparer recorded, if any; its reason only while the page is still
+ * world-visible (GBRA-217: a later write may have made it private since the effect was queued).
+ */
+async function gitCommitNote(engine: BrainEngine, effect: PersistenceEffect): Promise<GitCommitNote | undefined> {
const { commit_subject: subject, commit_line: line, commit_trailers: listed, commit_trailer: legacy } = effect.data;
const trailers = Array.isArray(listed) ? listed.filter((t): t is string => typeof t === 'string') : typeof legacy === 'string' ? [legacy] : [];
- return typeof subject === 'string' && typeof line === 'string' ? { subject, line, ...(trailers.length ? { trailers } : {}) } : undefined;
+ const note = typeof subject === 'string' && typeof line === 'string' ? { subject, line, ...(trailers.length ? { trailers } : {}) } : undefined;
+ return visibleCommitNote(engine, effect.source_id, effect.data.slug, note);
}
async function gitPage(engine: BrainEngine, effect: PersistenceEffect, binding: WorktreeBinding | null, opts: EffectWorkerOptions,
@@ -339,7 +344,7 @@ async function publishGitPage(engine: BrainEngine, effect: PersistenceEffect, bi
const root = binding.local_path;
if (!targetedWithdrawalEffect(effect) && !effect.data.source_scan) {
const target = await singleFileGitTarget(engine, effect, { ...binding, local_path: root }, attempt);
- if (target !== null) await completeEffect(engine, effect, await publishGitEffect(root, target, opts.signal, hardened, gitCommitNote(effect), undefined, owner));
+ if (target !== null) await completeEffect(engine, effect, await publishGitEffect(root, target, opts.signal, hardened, await gitCommitNote(engine, effect), undefined, owner));
return;
}
// Only a page walk reads snapshots; a single-file effect completes by its recorded hash.
@@ -393,7 +398,7 @@ async function publishGitPage(engine: BrainEngine, effect: PersistenceEffect, bi
await skipTarget(engine, effect, snapshot, 'withdrawal_not_mirrored');
return;
}
- const result = await publishGitEffect(root, relative(root, path).split(sep).join('/'), opts.signal, hardened, gitCommitNote(effect), undefined, owner);
+ const result = await publishGitEffect(root, relative(root, path).split(sep).join('/'), opts.signal, hardened, await gitCommitNote(engine, effect), undefined, owner);
if (result.reason === 'durability_not_enabled') await completeEffect(engine, effect, result);
else await finishPage(engine, effect, snapshot, result);
}
@@ -941,7 +946,8 @@ async function runEffectPass(engine: BrainEngine, config: GBrainConfig, opts: Ef
if (path !== null) targets.push({ effect, path, attempt });
} catch (error) { await recordFailure(engine, effect, error, opts.signal, attempt.target); }
}
- const notes = new Map(targets.flatMap(({ effect, path }) => { const note = gitCommitNote(effect); return note ? [[path, note] as const] : []; }));
+ const notes = new Map<string, GitCommitNote>();
+ for (const { effect, path } of targets) { const note = await gitCommitNote(engine, effect); if (note) notes.set(path, note); }
const outcomes = targets.length ? await commitGitTargets(binding.local_path, targets.map(t => t.path), opts.signal, notes,
{ writerLock: lock, onReclaim: () => { reclaimed = true; } }) : new Map();
const pending = unpushed.get(binding.local_path) ?? { binding, items: [] };
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.ts
index 7f4eaeafd3..298bcbd6a7 100644
--- a/src/core/persistence/group-publish.ts
+++ b/src/core/persistence/group-publish.ts
@@ -57,6 +57,7 @@ import { assertUnboundPublication, classifyUnboundPage } from './unbound-source.
import { boundPublication, declarePublication, publicationLeaseMs, publicationTransaction, type PublicationBound } from './publication-deadline.ts';
import { classifyMirrorPage, sourceMirrorReadOnly } from './mirror-read-only.ts';
import { commitThroughDoor, doorMarker, sourceCanonicalGit, strictChanged } from './git-door.ts';
+import { settleGroupCommitNotes } from './change-reason.ts';
import { assertNoPrivateCommit, declareStrictPublication } from './git-declared.ts';
import { authorizePageVisibility } from './page-visibility.ts';
import { withFilesystemPublication } from './filesystem-guard.ts';
@@ -416,7 +417,9 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr
if (lane) { timed.apply?.turn(); await faultPoint('lane:applied', { requestId: head.request_id, sourceId: head.source_id, operation: head.operation }); await awaitLaneTurn(tx, lane, rows); timed.apply?.turned(); }
// G2: one path-only commit for every member's file, in commit order, before the rows commit; a shared lease never reclaims an index lock.
if (strict && recorded.size) {
- const commit = await commitThroughDoor(binding.local_path!, [...recorded].map(([i, member]) => ({ path: member.record.path, planned: member.record.afterHash, note: prepared[i]!.file?.commit })), lane || joined ? undefined : lock,
+ // GBRA-217: notes are settled after every member applied, so a member a later one made private carries no reason.
+ const notes = await settleGroupCommitNotes(tx, [...recorded.keys()].map(i => ({ row: rows[i]!, note: prepared[i]!.file?.commit, outcome: outcomes[i]! })));
+ const commit = await commitThroughDoor(binding.local_path!, [...recorded].map(([i, member], n) => ({ path: member.record.path, planned: member.record.afterHash, note: notes[n] })), lane || joined ? undefined : lock,
paths => {
for (const [i, member] of recorded) {
const rel = relative(binding.local_path!, member.record.path).split(sep).join('/');
diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.ts
index dcfc0320b8..a95001b8bc 100644
--- a/src/core/persistence/page-mutations.ts
+++ b/src/core/persistence/page-mutations.ts
@@ -309,11 +309,12 @@ export async function preparePageAdmission(ctx: OperationContext,
() => assertPageRequestIdentity(ctx.engine, principal, requestId),
() => getWriteRequest(ctx.engine, principal, requestId),
]) as [unknown, WriteRequest | null];
- // GBRA-217: a reason is refused before anything is journaled; its canonical form joins the replay identity.
+ // GBRA-217: a reason is refused before anything is journaled; its canonical form joins the replay identity. An
+ // operation that records no reason never journals one a caller passed anyway.
if (CHANGE_REASON_OPERATIONS.includes(input.operation) && Object.hasOwn(p, 'reason')) {
const reason = admitChangeReason(p.reason);
if (reason === null) delete p.reason; else p.reason = reason;
- }
+ } else delete p.reason;
const callerIntent = { ...p };
delete callerIntent.request_id;
if (prior) {
diff --git a/src/core/persistence/page-purge.ts b/src/core/persistence/page-purge.ts
index 7e46f8cd24..08a60f72ad 100644
--- a/src/core/persistence/page-purge.ts
+++ b/src/core/persistence/page-purge.ts
@@ -54,6 +54,7 @@ import { rewrittenContentHash } from '../page-body/segment-rewrite.ts';
import { stagingNeedsTextSql } from '../page-body/schema.ts';
import { CLAIM_FORMS_BATCH, claimTextForms } from '../fence-shared.ts';
import type { PagePurgeContext } from '../facts/purge-verify.ts';
+import { pageChangeReasons, requestsRecordingReasons, stripPageGitNotes } from '../facts/purge-reasons.ts';
import { assertHeldPageKeys } from '../page-state/guards.ts';
import { noteBelief } from '../belief/ledger.ts';
import { appendPurgeIntent } from '../belief/purge-mirror.ts';
@@ -283,6 +284,7 @@ export async function purgePageInTransaction(tx: BrainEngine, row: WriteRequest,
const hashes = new Set<string>();
if (!retention) await tombstonePage(tx, sourceId, slug, page.id, snapshot, row.id, actor, { hash: storedHash, generation: Number(stored?.body_generation) }, hashes);
const { factRows, takeRows, needles } = await readPurgeClaims(tx, sourceId, slug, page.id);
+ const reasons = await pageChangeReasons(tx, sourceId, slug, page.id);
const segmentClaims = await readSegmentClaims(tx, sourceId, slug, page.id);
const factIds = factRows.map(f => Number(f.id)), takeIds = takeRows.map(t => Number(t.id));
const derivedFrom = await derivedRowsFrom(tx, [{ table: 'pages', id: page.id }, ...factIds.map(id => ({ table: 'facts', id })), ...takeIds.map(id => ({ table: 'takes', id }))]);
@@ -322,9 +324,13 @@ export async function purgePageInTransaction(tx: BrainEngine, row: WriteRequest,
// #6511 [R2]: the preparation sweep's targets, plus the tail past its ceiling and the rows pending at scan time, re-tested here.
const recheck = await lookup('tail_recheck', () => recheckRequestsCarrying(tx, sourceId, needles, prepared.sweep,
{ exclude: row.id, beforePending: () => faultPoint('purge:pending_recheck', { requestId: row.request_id, sourceId, operation: row.operation }) }));
- const forSlug = await lookup('slug_lookup', () => findRequestsForSlugs(tx, sourceId, [slug]));
+ const forSlug = await lookup('slug_lookup', async () => [...await findRequestsForSlugs(tx, sourceId, [slug]), ...reasons.length ? await requestsRecordingReasons(tx, sourceId, slug) : []]);
+ const own = new Set(forSlug.map(r => r.id));
const requests = [...new Map([...forSlug, ...prepared.sweep.targets, ...recheck.targets].map(r => [r.id, r])).values()];
- removed.persistence_requests = await lookup('redaction_read', () => redactRequestIntents(tx, requests, row.id, { skipPending: true, needles }));
+ // GBRA-217: the page's reasons are needles in its own requests only, so a short reason never redacts another page's receipt.
+ removed.persistence_requests = await lookup('redaction_read', async () => await redactRequestIntents(tx, requests.filter(r => own.has(r.id)), row.id,
+ { skipPending: true, needles: [...needles, ...reasons] }) + await redactRequestIntents(tx, requests.filter(r => !own.has(r.id)), row.id, { skipPending: true, needles }));
+ removed.persistence_effects = await stripPageGitNotes(tx, sourceId, slug);
const journalSweep = { scanned: prepared.sweep.scanned, ceiling: prepared.sweep.ceiling, watermark: prepared.sweep.watermark ?? null, batch: prepared.sweep.batch ?? 1,
tail: recheck.tail, pending_rechecked: recheck.pendingRechecked, complete: prepared.sweep.complete && recheck.complete };
const files = await tx.executeRaw<{ storage_path: string }>(`DELETE FROM files WHERE (page_id=$1 OR (page_slug=$2 AND (source_id=$3 OR source_id IS NULL)))
@@ -351,7 +357,7 @@ export async function purgePageInTransaction(tx: BrainEngine, row: WriteRequest,
scope: 'page', slug, purge_epoch: epoch, content_hashes: [...hashes], facts: mirrorFacts, takes: mirrorTakes, lifetimes });
const key = `${sourceId}:${row.request_id}`;
purgeContext.delete(key);
- purgeContext.set(key, { needles, factIds, pageId: page.id, paths, segmentShas: shas.slice(0, 4096), segmentClaims, ledgerClaims: inventory.claims, ledger });
+ purgeContext.set(key, { needles, reasons, factIds, pageId: page.id, paths, segmentShas: shas.slice(0, 4096), segmentClaims, ledgerClaims: inventory.claims, ledger });
while (purgeContext.size > PURGE_CONTEXT_LIMIT) purgeContext.delete(purgeContext.keys().next().value!);
return { status: 'purged', slug, source_id: sourceId, residuals: PURGE_RESIDUALS, journal_sweep: journalSweep, ...(retention ? { retention: true } : {}),
purge: { content_hash8: storedHash?.slice(0, 8) ?? null, tombstoned: hashes.size > 0, content_hashes_tombstoned: hashes.size, removed,
diff --git a/src/core/reason-trailers.ts b/src/core/reason-trailers.ts
index 688006fe26..99239c1252 100644
--- a/src/core/reason-trailers.ts
+++ b/src/core/reason-trailers.ts
@@ -159,17 +159,32 @@ export async function scanSyncReasons(engine: BrainEngine, input: { sourceId: st
return { status: read.status, gitRoot: repo.gitRoot, range, byPath: new Map(), malformed: 0, secrets: [], ...(read.status === 'failed' ? { detail: read.detail } : {}) };
}
+type GitTopLevel = { status: 'found'; gitRoot: string; scopePrefix: string } | { status: 'not_repository' } | { status: 'failed'; detail: string };
+
/**
- * The Git top level holding `sourceRoot` and the source's path under it (both real paths), or null when it is in no
- * Git repository (a plain folder source, a repo-less brain): such a source runs no scan.
+ * Where `sourceRoot` sits in Git: its top level and the source's path under it (both real paths); `not_repository` only
+ * when Git itself says the folder is in no repository (exit 128, "not a git repository"); anything else, a missing path,
+ * no `git`, an unsafe or corrupt repository, a timeout, is `failed`.
*/
-export function gitTopLevel(sourceRoot: string): { gitRoot: string; scopePrefix: string } | null {
+function locateGitTopLevel(sourceRoot: string): GitTopLevel {
let root: string;
- try { root = realpathSync(sourceRoot); } catch { return null; }
- const top = hardenedGitSync(root, ['rev-parse', '--show-toplevel'], { timeoutMs: 10_000, maxBytes: 64 * 1024 });
- if (!top.ok) return null;
- const gitRoot = realpathSync(top.stdout.toString('utf8').trim());
- return { gitRoot, scopePrefix: relative(gitRoot, root).split(sep).join('/') };
+ try { root = realpathSync(sourceRoot); } catch (error) { return { status: 'failed', detail: `source path unreadable: ${(error as NodeJS.ErrnoException).code ?? 'error'}` }; }
+ const top = hardenedGitSync(root, ['rev-parse', '--show-toplevel'], { timeoutMs: 10_000, maxBytes: 64 * 1024, stderr: true });
+ if (top.ok) {
+ const gitRoot = realpathSync(top.stdout.toString('utf8').trim());
+ return { status: 'found', gitRoot, scopePrefix: relative(gitRoot, root).split(sep).join('/') };
+ }
+ if (top.reason === 'exit' && top.status === 128 && /not a git repository/i.test(top.stderr ?? '')) return { status: 'not_repository' };
+ return { status: 'failed', detail: `git rev-parse --show-toplevel ${top.reason}${top.status === undefined ? '' : ` ${top.status}`}` };
+}
+
+/**
+ * Sync's view: the Git top level holding `sourceRoot`, or null when it is in no Git repository (a plain folder source,
+ * a repo-less brain) or Git cannot place it; such a pass runs no scan and imports as before.
+ */
+export function gitTopLevel(sourceRoot: string): { gitRoot: string; scopePrefix: string } | null {
+ const top = locateGitTopLevel(sourceRoot);
+ return top.status === 'found' ? { gitRoot: top.gitRoot, scopePrefix: top.scopePrefix } : null;
}
/** A file's path relative to the scan's Git top level, resolving its directory's real path (the file itself may be gone). */
@@ -218,10 +233,12 @@ const CACHE_TTL_MS = 10 * 60_000;
/**
* Managed sync prepares one request at a time, each naming its pass's range: the pass's scan runs once per process and
- * its later requests reuse it. A purge clears the cache, so the next request reads its new tombstones.
+ * its later requests reuse it. The key carries the source's purge epoch, which every fact purge bumps in the transaction
+ * that writes its tombstones, so a purge from any process makes the next request scan again and read them.
*/
-export function cachedSyncReasonScan(engine: BrainEngine, input: Parameters<typeof scanSyncReasons>[1]): Promise<SyncReasonScan | null> {
- const key = [input.sourceId, input.sourceRoot, input.from ?? '', input.to].join('\0');
+export async function cachedSyncReasonScan(engine: BrainEngine, input: Parameters<typeof scanSyncReasons>[1]): Promise<SyncReasonScan | null> {
+ const [source] = await engine.executeRaw<{ purge_epoch: string | number }>('SELECT purge_epoch FROM sources WHERE id = $1', [input.sourceId]);
+ const key = [input.sourceId, String(source?.purge_epoch ?? 0), input.sourceRoot, input.from ?? '', input.to].join('\0');
const hit = cache.get(key);
if (hit && Date.now() - hit.at < CACHE_TTL_MS) return hit.scan;
const scan = scanSyncReasons(engine, input);
@@ -241,24 +258,26 @@ export type PurgeTrailerScan =
/**
* A7: the commits on the first-parent line of HEAD (`from..HEAD` for a recheck) whose `gbrain-reason` trailer quotes one of
- * `needles` (case-insensitive), each with the path its trailer names: the touched path it prefixes, else the text before
- * its first ": ". Capped at the purge cap, or at `limit` when the user chose one (then older commits are not read).
+ * `needles` (case-insensitive, both canonicalised as a stored reason is: whitespace runs and control characters folded),
+ * each with the path its trailer names: the touched path it prefixes, else the text before its first ": ". Capped at
+ * the purge cap, or at `limit` when the user chose one (then older commits are not read).
*/
export async function scanTrailersCarrying(sourceRoot: string, needles: readonly string[], opts: { from?: string | null; limit?: number } = {}): Promise<PurgeTrailerScan> {
- const repo = gitTopLevel(sourceRoot);
- if (!repo) return { status: 'no_repository' };
+ const repo = locateGitTopLevel(sourceRoot);
+ if (repo.status === 'not_repository') return { status: 'no_repository' };
+ if (repo.status === 'failed') return { status: 'failed', detail: repo.detail };
const head = hardenedGitSync(repo.gitRoot, ['rev-parse', '--verify', '--quiet', 'HEAD^{commit}'], { timeoutMs: 10_000, maxBytes: 1024 });
if (!head.ok) return head.reason === 'exit' && head.status === 1 ? { status: 'complete', gitRoot: repo.gitRoot, head: null, hits: [], commits: 0, limited: false }
: { status: 'failed', detail: `git rev-parse ${head.reason}` };
const tip = head.stdout.toString('utf8').trim();
if (opts.from === tip) return { status: 'complete', gitRoot: repo.gitRoot, head: tip, hits: [], commits: 0, limited: false };
- const lowered = needles.map(needle => needle.toLowerCase()).filter(Boolean);
+ const lowered = needles.map(needle => canonicalChangeReason(needle)?.toLowerCase() ?? '').filter(Boolean);
const forms = pathForms(repo.scopePrefix);
const hits: Array<{ commit: string; path: string }> = [];
const cap = opts.limit ?? caps.purge;
const read = await readReasonTrailers(repo.gitRoot, opts.from ? `${opts.from}..${tip}` : tip, cap, commit => {
for (const value of commit.values) {
- const lower = value.toLowerCase();
+ const lower = canonicalChangeReason(value)?.toLowerCase() ?? '';
if (!lowered.some(needle => lower.includes(needle))) continue;
let best: { path: string; length: number } | null = null;
for (const path of commit.paths) for (const form of forms(path)) {
diff --git a/test/page-change-reason-gbra217.test.ts b/test/page-change-reason-gbra217.test.ts
index db26e98ef2..ee0e678824 100644
--- a/test/page-change-reason-gbra217.test.ts
+++ b/test/page-change-reason-gbra217.test.ts
@@ -93,6 +93,36 @@ for (const backend of testBackends()) describe(`[${backend}] page change reasons
expect(await journalHolds(secret)).toBe(false);
});
+ test('a reason passed to a page operation that takes none is dropped before the journal', async () => {
+ await call('put_page', { slug: SLUG, content: page('Edition one.'), wait_ms: 30_000 });
+ const marker = `stray-reason-marker-${run}`;
+ await call('add_tag', { slug: SLUG, tag: `tag-example-${run}`, reason: `${marker} on a tag`, expected_revision: await revision(), wait_ms: 30_000 });
+ await call('delete_page', { slug: SLUG, reason: `${marker} on a delete`, expected_revision: await revision(), wait_ms: 30_000 });
+ await call('restore_page', { slug: SLUG, reason: `${marker} on a restore`, expected_revision: String((await call('get_page', { slug: SLUG, include_deleted: true })).revision), wait_ms: 30_000 });
+ expect(await journalHolds(marker)).toBe(false);
+ });
+
+ test('a page purge leaves the page\'s reasons in no receipt, intent or effect, and its receipt checks both stores', async () => {
+ const marker = `purged-reason-marker-${run}`;
+ await call('put_page', { slug: SLUG, content: page('Edition one.'), reason: `${marker} at creation`, wait_ms: 30_000 });
+ await call('put_page', { slug: SLUG, content: page('Edition two.'), expected_revision: await revision(), reason: `${marker} on the second edition`, wait_ms: 30_000 });
+ await call('put_page', { slug: SLUG, content: page('Edition three.'), expected_revision: await revision(), wait_ms: 30_000 });
+ await engine.executeRaw(`UPDATE persistence_requests SET intent = NULL, compacted = true WHERE slug = $1 AND state = 'committed'`, [SLUG]);
+ expect(await journalHolds(marker)).toBe(true);
+ const done = await call('delete_page', { slug: SLUG, purge: true, expected_revision: await revision(), wait_ms: 30_000 });
+ expect(await journalHolds(marker)).toBe(false);
+ const stores = (done.receipt as { stores: Array<{ store: string; status: string }> }).stores;
+ expect(stores.filter(s => s.store === 'persistence_requests' || s.store === 'persistence_effects').map(s => s.status)).not.toContain('incomplete');
+ expect(stores.map(s => s.store)).toEqual(expect.arrayContaining(['persistence_requests', 'persistence_effects']));
+ // The receipt's check finds a reason still in one of the slug's receipts.
+ await call('put_page', { slug: SLUG, content: page('A new page.'), reason: `${marker} again`, wait_ms: 30_000 });
+ await engine.executeRaw(`UPDATE persistence_requests SET intent = NULL, compacted = true WHERE slug = $1 AND state = 'committed'`, [SLUG]);
+ const { verifyPagePurge } = await import('../src/core/facts/purge-verify.ts');
+ const recheck = await verifyPagePurge(engine, { sourceId: 'default', slug: SLUG, requestId: crypto.randomUUID(), removed: {}, blobsRemaining: [],
+ context: { needles: [], reasons: [`${marker} again`], factIds: [], pageId: 0, paths: [], segmentShas: [] } }) as { stores: Array<{ store: string; status: string }> };
+ expect(recheck.stores.find(s => s.store === 'persistence_requests')).toMatchObject({ status: 'incomplete' });
+ });
+
test('the canonical reason joins replay identity', async () => {
const request_id = crypto.randomUUID();
await call('put_page', { slug: SLUG, content: page('one'), reason: 'same reason', request_id, wait_ms: 30_000 });
diff --git a/test/page-change-reason-git-gbra217.test.ts b/test/page-change-reason-git-gbra217.test.ts
index e9e167277e..91a6e175ea 100644
--- a/test/page-change-reason-git-gbra217.test.ts
+++ b/test/page-change-reason-git-gbra217.test.ts
@@ -140,8 +140,65 @@ for (const backend of testBackends()) {
const versions = await call(ctx, 'get_versions', { slug: 'notes/private-example' }) as unknown as Array<Record<string, unknown>>;
expect(versions[0]!.replaced_because).toBe('private-only reason');
}, { databaseUrl, setup }), 120_000);
+
+ // A put_pages batch publishes as one group (one strict door commit) on Postgres only; on PGLite its members publish one
+ // at a time (persistence/consumer.ts executeOrGroup), so a strict member commits before the next one applies.
+ test.skipIf(strict && backend === 'pglite')(`${strict ? 'strict' : 'non-strict'}: a group that makes an earlier member private commits that member without its reason`, () => managedBrain(async ({ engine, ctx, root }) => {
+ if (strict) await strictSource(engine);
+ const origin = 'notes/origin-example', derived = 'notes/derived-example';
+ await call(ctx, 'put_pages', { request_id: randomUUID(), wait_ms: 30_000, pages: [
+ { slug: origin, content: page('o1') }, { slug: derived, content: page('d1', `derived_from: ${origin}\n`) }] });
+ await settleManagedGitEffects(engine);
+ await call(ctx, 'put_pages', { request_id: randomUUID(), wait_ms: 30_000, pages: [
+ { slug: derived, content: page('d2', `derived_from: ${origin}\n`), expected_revision: await revision(ctx, derived), reason: 'lineage-private reason' },
+ { slug: origin, content: page('o2', 'visibility: private\n'), expected_revision: await revision(ctx, origin) }] });
+ await settleManagedGitEffects(engine);
+ expect(raw(root, 'show', `HEAD:${derived}.md`)).toContain('d2');
+ expect(raw(root, 'log', '--all', '--format=%B')).not.toContain('lineage-private reason');
+ const versions = await call(ctx, 'get_versions', { slug: derived }) as unknown as Array<Record<string, unknown>>;
+ expect(versions[0]!.replaced_because).toBe('lineage-private reason');
+ }, { databaseUrl, setup }), 120_000);
}
+ test('non-strict: a later write that makes a queued page private commits it without its reason', () => managedBrain(async ({ engine, ctx, root }) => {
+ const origin = 'notes/origin-example', derived = 'notes/derived-example';
+ await call(ctx, 'put_pages', { request_id: randomUUID(), wait_ms: 30_000, pages: [
+ { slug: origin, content: page('o1') }, { slug: derived, content: page('d1', `derived_from: ${origin}\n`) }] });
+ await settleManagedGitEffects(engine);
+ await call(ctx, 'put_page', { slug: derived, content: page('d2', `derived_from: ${origin}\n`), expected_revision: await revision(ctx, derived), request_id: randomUUID(), reason: 'queued-then-private reason' });
+ await call(ctx, 'put_page', { slug: origin, content: page('o2', 'visibility: private\n'), expected_revision: await revision(ctx, origin), request_id: randomUUID() });
+ await settleManagedGitEffects(engine);
+ expect(raw(root, 'show', `HEAD:${derived}.md`)).toContain('d2');
+ expect(raw(root, 'log', '--all', '--format=%B')).not.toContain('queued-then-private reason');
+ }, { databaseUrl, setup }), 120_000);
+
+ test('non-strict: a page purge strips the page\'s reasons from every receipt and retained Git effect; the receipt checks both stores', () => managedBrain(async ({ engine, ctx }) => {
+ const marker = 'purged-git-reason-marker';
+ await call(ctx, 'put_page', { slug: SLUG, content: page('Edition one.'), request_id: randomUUID(), reason: `${marker} at creation` });
+ await settleManagedGitEffects(engine);
+ await call(ctx, 'put_page', { slug: SLUG, content: page('Edition two.'), expected_revision: await revision(ctx), request_id: randomUUID(), reason: `${marker} on the second edition` });
+ await settleManagedGitEffects(engine);
+ const carrying = async () => (await engine.executeRaw(`SELECT 1 FROM persistence_requests WHERE strpos(COALESCE(intent::text,'') || COALESCE(outcome::text,'') || COALESCE(error_detail::text,''), $1) > 0
+ UNION ALL SELECT 1 FROM persistence_effects WHERE strpos(data::text || COALESCE(outcome::text,''), $1) > 0`, [marker])).length;
+ expect(await engine.executeRaw(`SELECT 1 FROM persistence_effects WHERE kind = 'git' AND data->>'slug' = $1 AND strpos(data::text, $2) > 0`, [SLUG, marker])).not.toHaveLength(0);
+ const done = await call(ctx, 'delete_page', { slug: SLUG, purge: true, expected_revision: await revision(ctx), request_id: randomUUID(), wait_ms: 30_000 });
+ expect(await carrying()).toBe(0);
+ const stores = (done.receipt as { stores: Array<{ store: string; status: string }> }).stores;
+ expect(stores.filter(s => s.store === 'persistence_requests' || s.store === 'persistence_effects').map(s => s.status)).not.toContain('incomplete');
+
+ // The receipt's checks find a reason left behind: a Git effect of the slug still carrying one is incomplete.
+ const { declarePersistenceProtocol } = await import('../src/core/persistence/protocol.ts');
+ await engine.transaction(async tx => {
+ await declarePersistenceProtocol(tx);
+ await tx.executeRaw(`UPDATE persistence_effects SET data = data || $1::text::jsonb WHERE id = (SELECT min(id) FROM persistence_effects WHERE kind = 'git')`,
+ [JSON.stringify({ slug: SLUG, commit_line: `${SLUG}.md: ${marker} left behind` })]);
+ });
+ const { verifyPagePurge } = await import('../src/core/facts/purge-verify.ts');
+ const recheck = await verifyPagePurge(engine, { sourceId: 'default', slug: SLUG, requestId: randomUUID(), removed: {}, blobsRemaining: [],
+ context: { needles: [], reasons: [`${marker} left behind`], factIds: [], pageId: 0, paths: [], segmentShas: [] } }) as { stores: Array<{ store: string; status: string }> };
+ expect(recheck.stores.find(s => s.store === 'persistence_effects')).toMatchObject({ status: 'incomplete' });
+ }, { databaseUrl, setup }), 120_000);
+
test('non-strict: a superseded Git effect never lends its reason to the newer commit; its receipt says so', () => managedBrain(async ({ engine, ctx, root }) => {
await call(ctx, 'put_page', { slug: SLUG, content: page('Edition one.'), request_id: randomUUID() });
await settleManagedGitEffects(engine);
diff --git a/test/reason-trailers-gbra217.test.ts b/test/reason-trailers-gbra217.test.ts
index 8317d083c6..58a17cdb4d 100644
--- a/test/reason-trailers-gbra217.test.ts
+++ b/test/reason-trailers-gbra217.test.ts
@@ -16,7 +16,7 @@
import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
import { execFileSync } from 'node:child_process';
import { randomUUID } from 'node:crypto';
-import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { BrainEngine } from '../src/core/engine.ts';
@@ -361,6 +361,92 @@ describe('A7: purge reaches change reasons', () => {
__setReasonScanCapsForTests();
}
}), 120_000);
+ test('A-T7c: a moved checkout or a corrupt .git/config refuses before anything is deleted; a plain-folder source still purges', async () => inHome(async () => {
+ for (const engine of engines) {
+ const n = engines.indexOf(engine);
+ const claim = `Locker code is ${8100 + n}`;
+ const s = await classicSource(engine, { 'notes/a.md': page('A one.') });
+ await sync(engine, s);
+ write(s.root, { 'notes/a.md': page('A two.') });
+ commit(s.root, 'edit', [`notes/a.md: Changed once ${claim} was rotated.`]);
+ await sync(engine, s);
+ const id = await seedFact(engine, s.id, `people/locker-example-${n}`, claim);
+ const untouched = async () => {
+ expect(await engine.executeRaw('SELECT 1 FROM facts WHERE id = $1', [id])).toHaveLength(1);
+ expect((await reasonsOf(engine, s.id, 'notes/a')).reasons).toEqual([`Changed once ${claim} was rotated.`]);
+ expect(await engine.executeRaw('SELECT 1 FROM reason_purge_tombstones WHERE source_id = $1', [s.id])).toHaveLength(0);
+ };
+
+ renameSync(s.root, `${s.root}-moved`);
+ try {
+ const moved = await refusal(purge(engine, s.id, id));
+ expect(moved).toMatchObject({ code: 'reason_purge_scan_failed' });
+ await untouched();
+ } finally { renameSync(`${s.root}-moved`, s.root); }
+
+ const config = join(s.root, '.git', 'config');
+ const intact = readFileSync(config, 'utf8');
+ writeFileSync(config, `${intact}[core\n\tbroken = \n`);
+ try {
+ expect(gitTopLevel(s.root)).toBeNull();
+ const corrupt = await refusal(purge(engine, s.id, id));
+ expect(corrupt).toMatchObject({ code: 'reason_purge_scan_failed' });
+ await untouched();
+ } finally { writeFileSync(config, intact); }
+
+ const folder = join(home, `plain-source-${++serial}`);
+ write(folder, { 'notes/plain.md': page('Plain one.') });
+ const plainId = `rt-plain-${serial}`;
+ await engine.executeRaw(`INSERT INTO sources(id, name, local_path, config) VALUES ($1, $1, $2, '{}')`, [plainId, folder]);
+ const plainFact = await seedFact(engine, plainId, `people/plain-example-${n}`, claim);
+ const plain = await purge(engine, plainId, plainFact);
+ expect(plain.state).toBe('committed');
+ expect(plain.residuals.map((r: { store: string }) => r.store)).not.toContain('git_commit_messages');
+ expect(await engine.executeRaw('SELECT 1 FROM facts WHERE id = $1', [plainFact])).toHaveLength(0);
+ }
+ }), 180_000);
+ test('a purge while another process holds a cached scan of the range: its next request reads the tombstone, not the cached reason', async () => inHome(async () => {
+ // A second module instance is the managed sync worker's process: the purge cannot clear its cache.
+ const worker = await import(new URL('../src/core/reason-trailers.ts?sync-worker', import.meta.url).href) as typeof import('../src/core/reason-trailers.ts');
+ for (const engine of engines) {
+ const claim = `Safe combination is ${9300 + engines.indexOf(engine)}`;
+ const s = await classicSource(engine, { 'notes/a.md': page('A one.') });
+ await sync(engine, s);
+ const from = git(s.root, 'rev-parse', 'HEAD');
+ write(s.root, { 'notes/a.md': page('A two.') });
+ const to = commit(s.root, 'edit', [`notes/a.md: Changed once ${claim} was rotated.`]);
+ const range = { sourceId: s.id, sourceRoot: s.root, from, to };
+ const file = join(s.root, 'notes/a.md');
+ expect(worker.importHistoryFor(await worker.cachedSyncReasonScan(engine, range), file)).toEqual({ reason: `Changed once ${claim} was rotated.`, historyGap: false });
+ await sync(engine, s);
+ const id = await seedFact(engine, s.id, `people/safe-example-${engines.indexOf(engine)}`, claim);
+ expect((await purge(engine, s.id, id)).state).toBe('committed');
+ expect(worker.importHistoryFor(await worker.cachedSyncReasonScan(engine, range), file)).toEqual({ reason: null, historyGap: false });
+ worker.clearReasonScanCache();
+ }
+ }), 120_000);
+ test('a trailer whose spacing differs from the claim (double space, tab) is tombstoned, and a cold re-import does not restore it', async () => inHome(async () => {
+ for (const engine of engines) {
+ const n = engines.indexOf(engine);
+ const claim = `the secret project name ${n}`;
+ const s = await classicSource(engine, { 'notes/a.md': page('A one.') });
+ await sync(engine, s);
+ write(s.root, { 'notes/a.md': page('A two.') });
+ const pushed = commit(s.root, 'edit', [`notes/a.md: the secret\tproject name ${n}`]);
+ await sync(engine, s);
+ expect((await reasonsOf(engine, s.id, 'notes/a')).reasons).toEqual([claim]);
+ const id = await seedFact(engine, s.id, `people/spacing-example-${n}`, claim);
+ const done = await purge(engine, s.id, id);
+ expect(done.state).toBe('committed');
+ expect(await engine.executeRaw('SELECT commit_sha, path FROM reason_purge_tombstones WHERE source_id = $1', [s.id])).toEqual([{ commit_sha: pushed, path: 'notes/a.md' }]);
+ await importFromContent(engine, 'notes/a', page('A one.'), { noEmbed: true, sourceId: s.id });
+ await engine.executeRaw('UPDATE sources SET last_commit = NULL WHERE id = $1', [s.id]);
+ await sync(engine, s);
+ expect(await bodyOf(engine, s.id, 'notes/a')).toContain('A two.');
+ expect((await reasonsOf(engine, s.id, 'notes/a')).reasons.at(-1)).toBeNull();
+ expect(await engine.executeRaw('SELECT 1 FROM page_versions v JOIN pages p ON p.id = v.page_id WHERE p.source_id = $1 AND strpos(lower(v.change_reason), $2) > 0', [s.id, claim])).toHaveLength(0);
+ }
+ }), 120_000);
});
describe('A-T11: repo-less brains are first class', () => {