Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
GBRA-217: page writes carry an optional reason (write path, migration, get_versions replaced_because)
garrytan193fa52750eb
diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.tsindex 2587abc644..1539bd0aab 100644--- a/src/core/engine-sql/pages.ts+++ b/src/core/engine-sql/pages.ts@@ -999,6 +999,20 @@ const PAGE_VERSION_METADATA_COLUMNS = trustedSql('pv.id, pv.page_id, pv.frontmat/** Wave B: the reference columns of a segmented version, kept only on segmented rows so inline rows stay as they were. */const PAGE_VERSION_SEGMENTED_COLUMNS = trustedSql('pv.body_storage, pv.body_generation, pv.body_bytes, pv.content_hash');+/**+ * GBRA-217: a snapshot's `replaced_because` as a reader may see it. A trusted reader gets the stored reason. A reader+ * held to world-visible pages (`excludePrivate`) gets it only when the snapshot's successor is world-visible too (the+ * next snapshot of the page, or the live page, which the caller's own page predicate checks) and the successor was not+ * pruned (`successor_pruned`: its visibility can no longer be checked, so the reason is withheld). The successor is+ * read over every snapshot of the page, never only the rows the reader may see. Shared by get_versions and get_page as_of.+ */+export function replacedBecauseSql(pv: string, excludePrivate: boolean): string {+ if (!excludePrivate) return `${pv}.change_reason`;+ return `CASE WHEN ${pv}.change_reason IS NULL OR COALESCE(${pv}.successor_pruned, false) THEN NULL+ WHEN COALESCE((SELECT ${privateSnapshotFilterFragment('rb_next')} FROM page_versions rb_next+ WHERE rb_next.page_id = ${pv}.page_id AND rb_next.id > ${pv}.id ORDER BY rb_next.id LIMIT 1), true) THEN ${pv}.change_reason END`;+}+/*** Newest first (`pv.id` breaks snapshot_at ties). Scope, privacy and* re-derivation (a page a purge hid) predicates sit in WHERE, so `limit`@@ -1018,7 +1032,7 @@ export async function getVersions<B extends boolean = true>(const columns = opts?.includeBody === false ? PAGE_VERSION_METADATA_COLUMNS : PAGE_VERSION_COLUMNS;const limit = opts?.limit !== undefined ? sqlFragment`LIMIT ${opts.limit}` : sqlFragment``;const { rows } = await exec.run(sqlFragment`- SELECT ${columns}, ${PAGE_VERSION_SEGMENTED_COLUMNS} FROM page_versions pv+ SELECT ${columns}, ${PAGE_VERSION_SEGMENTED_COLUMNS}, ${trustedSql(replacedBecauseSql('pv', opts?.excludePrivate === true))} AS replaced_because FROM page_versions pvJOIN pages p ON p.id = pv.page_idWHERE p.slug = ${slug} ${scope}${privacy} AND ${trustedSql(rederiveHiddenSql('pages', 'p'))}diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex c4d30ed271..670323c770 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -128,6 +128,7 @@ export const CODES = {suggestion: 'Run the gbrain config set the drain report names on the brain host (gbrain doctor --only persistence_capacity --json prints it), then rerun the same gbrain sync; it resumes at the stored cursor.' },catalog_capacity_exceeded: { class: 'caller', summary: "The shared-skills catalog visible to this connection exceeds the delivery limits.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },catalog_unavailable: { class: 'retryable', summary: "Shared skill storage is not ready on this brain." },+ change_reason_rejected: { class: 'caller', summary: "The write's reason was refused before anything was admitted: it is longer than 500 characters, or it looks like it holds a secret.", why: 'A reason is kept in page history and, on a page that reaches Git, in the commit message, which a push makes permanent; it is checked before the write is journaled so no copy of a refused reason is stored anywhere.', reasons: ['reason_too_long', 'reason_contains_secret'], legacy_error: 'invalid_params', docs: 'docs/guides/page-history.md#reasons', suggestion: 'Shorten the reason, or remove the secret from it, and send the write again.' },changed_since_preview: { class: 'caller', summary: "The file changed after its repair was previewed, so nothing was written.", why: "A repair writes exactly the bytes the operator approved; it binds approval to the previewed file hash and refuses when the file moved on.", suggestion: 'Preview the repair again, review the new proposal, and approve its new hash.' },chronicle_skipped: { class: 'unavailable', summary: "Automatic event extraction (auto_chronicle) skipped or failed this page; `reason` says why and `fix`, when present, is the next step.", reasons: ['auto_chronicle_off', 'auto_chronicle_invalid', 'slug_bound_client', 'operation_bound_client', 'no_extract', 'history', 'not_yet_happened', 'too_short', 'dream_generated', 'page_body_segmented', 'no_write_decision', 'not_chronicle_shaped', 'already_extracted', 'superseded', 'daily_limit', 'judge_llm_unavailable', 'no_pricing', 'budget_exhausted', 'campaign_exhausted', 'judge_chat_error', 'judge_truncated', 'judge_parse_failed', 'malformed_proposal', 'publish_error', 'judge_refused', 'page_missing', 'no_events', 'future_dated', 'date_imprecise', 'no_chat_provider'], docs: 'docs/guides/life-chronicle.md#skip-and-failure-codes', suggestion: 'Read the receipt or doctor `auto_chronicle` check: its `why` explains the reason and its `fix`, when present, is the next step (paid fixes need the user\'s agreement).' },checkpoint_missing: { class: 'caller', summary: "The approved source plan is missing; do not restart from a different revision." },diff --git a/src/core/ops/admin.ts b/src/core/ops/admin.tsindex 5c8b7e5518..7ecb78cd50 100644--- a/src/core/ops/admin.ts+++ b/src/core/ops/admin.ts@@ -1,4 +1,4 @@-import { PAGE_MUTATION_PARAMS } from '../persistence/params.ts';+import { PAGE_MUTATION_PARAMS, REASON_PARAM } from '../persistence/params.ts';import { readPolicyOpts } from './context.ts';import { attributeVersions, canReadWriteAttribution } from './attribution.ts';import { GET_VERSIONS_DEFAULT_LIMIT, GET_VERSIONS_REMOTE_MAX_LIMIT, pagingLimit, reportVersionPage } from './read-paging.ts';@@ -202,7 +202,7 @@ const get_versions: Operation = {mutating: false,idempotent: true,outputRedaction: { exempt: 'full page version snapshots by slug; a page read governed by visibility like get_page (CEO-17)' },- description: `Page version history, newest snapshot first: metadata only (id, snapshot_at, title, type, tags, frontmatter) for the newest ${GET_VERSIONS_DEFAULT_LIMIT} versions by default. Pass include_body: true for each version's compiled_truth and timeline, and a larger limit (at most ${GET_VERSIONS_REMOTE_MAX_LIMIT} over MCP) for older versions. Trusted local and admin callers also get written_by and archived_by (who wrote each snapshot and whose write archived it). revert_version takes the id field.`,+ description: `Page version history, newest snapshot first: metadata only (id, snapshot_at, title, type, tags, frontmatter) for the newest ${GET_VERSIONS_DEFAULT_LIMIT} versions by default. Pass include_body: true for each version's compiled_truth and timeline, and a larger limit (at most ${GET_VERSIONS_REMOTE_MAX_LIMIT} over MCP) for older versions. Trusted local and admin callers also get written_by and archived_by (who wrote each snapshot and whose write archived it). replaced_because is the reason given for the write that replaced the snapshot (null when none was given). revert_version takes the id field.`,params: {slug: { type: 'string', required: true, description: 'Slug of the page whose version history to list.' },limit: { type: 'number', description: `Return only the newest N versions (a positive integer). Default ${GET_VERSIONS_DEFAULT_LIMIT}; MCP callers are capped at ${GET_VERSIONS_REMOTE_MAX_LIMIT}.` },@@ -230,7 +230,7 @@ const get_versions: Operation = {const metadata = page(await ctx.engine.getVersions(p.slug as string, { ...opts, includeBody: false })).map(v => { const { compiled_truth: _b, timeline: _t, ...rest } = v as typeof v & { compiled_truth?: unknown; timeline?: unknown }; return rest; });const sized = [];- for (const v of metadata) sized.push(await remoteVersionSize(ctx, v));+ for (const v of metadata) sized.push({ ...await remoteVersionSize(ctx, v), ...(ctx.remote === false ? {} : remoteReason(v)) });return canReadWriteAttribution(ctx) ? attributeVersions(ctx.engine, sized) : sized;}const plain = page(await ctx.engine.getVersions(p.slug as string, opts));@@ -241,12 +241,12 @@ const get_versions: Operation = {if (isSegmentedPage(v)) {const sized = await remoteVersionSize(ctx, v);const { compiled_truth: _b, timeline: _t, ...rest } = sized;- out.push({ ...rest, body_ref: { version_id: v.id, total_bytes: 'total_bytes' in sized ? sized.total_bytes : pageBodyBytes(v),+ out.push({ ...rest, ...(ctx.remote === false ? {} : remoteReason(v)), body_ref: { version_id: v.id, total_bytes: 'total_bytes' in sized ? sized.total_bytes : pageBodyBytes(v),read: { tool: 'get_page', arguments: { slug: p.slug, version_id: v.id, body: 'window' } } } });continue;}if (ctx.remote === false) { out.push(v); continue; }- out.push({ ...v, compiled_truth: sanitizeRemoteBody(v.compiled_truth),+ out.push({ ...v, compiled_truth: sanitizeRemoteBody(v.compiled_truth), ...remoteReason(v),...(typeof v.timeline === 'string' ? { timeline: sanitizeRemoteBody(v.timeline) } : {}) });}return out;@@ -255,6 +255,11 @@ const get_versions: Operation = {cliHints: { name: 'history', positional: ['slug'] },};+/** GBRA-217: a remote reader's `replaced_because` goes through the same sanitizer as the version bodies. */+function remoteReason(v: { replaced_because?: string | null }): { replaced_because?: string } {+ return typeof v.replaced_because === 'string' ? { replaced_because: sanitizeRemoteBody(v.replaced_because) } : {};+}+/*** A segmented version as a remote caller sees it: the size of its read projection (`total_bytes`, what get_page reports* for a segmented page), never the stored body_bytes, whose difference would say how much text the projection hides.@@ -276,6 +281,7 @@ const revert_version: Operation = {...PAGE_MUTATION_PARAMS,slug: { type: 'string', required: true, description: 'Slug of the page to revert.' },version_id: { type: 'number', required: true, description: 'Numeric version id to revert to, as returned by get_versions. Not a version NUMBER offset — pass the id field.' },+ reason: REASON_PARAM,},mutating: true,scope: 'write',diff --git a/src/core/ops/page-batch.ts b/src/core/ops/page-batch.tsindex 5218d801fc..cc4dc2f3dc 100644--- a/src/core/ops/page-batch.ts+++ b/src/core/ops/page-batch.ts@@ -1,6 +1,6 @@/** #6007: `put_pages` — the batch write path for remote agents (src/core/persistence/page-batch.ts). */import type { Operation } from './contract.ts';-import { WRITE_REQUEST_PARAM, WRITE_WAIT_PARAM, PAGE_MUTATION_PARAMS } from '../persistence/params.ts';+import { REASON_PARAM, WRITE_REQUEST_PARAM, WRITE_WAIT_PARAM, PAGE_MUTATION_PARAMS } from '../persistence/params.ts';import { PAGE_BATCH_MAX_BYTES, PAGE_BATCH_MAX_PAGES, submitPageBatch } from '../persistence/page-batch.ts';import { pageMutationSource } from '../persistence/page-mutations.ts';import { enforceSubagentSlugFence } from './context.ts';@@ -22,6 +22,7 @@ const put_pages: Operation = {allow_empty: { type: 'boolean', description: 'Allow emptying a non-empty page.' },allow_shrink: { type: 'boolean', description: 'Allow content under half a >256 KB page.' },drop_timeline: { type: 'boolean', description: 'Content without a Timeline section deletes its dated entries.' },+ reason: REASON_PARAM,},},},diff --git a/src/core/ops/page-edit.ts b/src/core/ops/page-edit.tsindex 793a27ad6a..7944991d84 100644--- a/src/core/ops/page-edit.ts+++ b/src/core/ops/page-edit.ts@@ -4,7 +4,7 @@import type { Operation } from './contract.ts';import { enforceClientSlugFence, enforceSubagentSlugFence, validatePageSlug } from './context.ts';import { pageMutationSource, submitPageMutation } from '../persistence/page-mutations.ts';-import { PAGE_MUTATION_PARAMS, WRITE_REQUEST_PARAM } from '../persistence/params.ts';+import { PAGE_MUTATION_PARAMS, REASON_PARAM, WRITE_REQUEST_PARAM } from '../persistence/params.ts';import { EDIT_PAGE_MAX_EDITS, parseEditWithin, parsePageEdits } from '../persistence/page-edit.ts';const edit_page: Operation = {@@ -37,6 +37,7 @@ const edit_page: Operation = {},source_id: PAGE_MUTATION_PARAMS.source_id,request_id: WRITE_REQUEST_PARAM,+ reason: REASON_PARAM,},mutating: true,scope: 'write',diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.tsindex 38b2ce653f..58b88dfc12 100644--- a/src/core/ops/pages.ts+++ b/src/core/ops/pages.ts@@ -1,6 +1,6 @@import { funnelPassThrough } from '../funnel.ts';import { suffixedSlugDryRun } from '../persistence/suffixed-slug.ts';-import { AGENT_CONTENT_PARAMS, PAGE_MUTATION_PARAMS, CAPTURE_EVENT_PARAMS, CAPTURE_CLI_PROVENANCE_PARAMS, WRITE_WAIT_PARAM } from '../persistence/params.ts';+import { AGENT_CONTENT_PARAMS, PAGE_MUTATION_PARAMS, CAPTURE_EVENT_PARAMS, CAPTURE_CLI_PROVENANCE_PARAMS, REASON_PARAM, WRITE_WAIT_PARAM } from '../persistence/params.ts';import { assertPurgeParams } from '../persistence/purge-params.ts';/*** Page CRUD operation cluster — pure move from operations.ts (v0.46.x@@ -342,6 +342,7 @@ const put_page: Operation = {allow_shrink: { type: 'boolean', required: false, description: 'Allow content under half a >256 KB page. To add text use append_page, not a re-put; a page over one request goes by begin_page_upload.', fullSurfaceOnly: true },drop_timeline: { type: 'boolean', required: false, description: 'No Timeline in content: delete its entries.', fullSurfaceOnly: true },wait_ms: WRITE_WAIT_PARAM,+ reason: REASON_PARAM,// v0.39.3.0 provenance write-through (WARN-8 + A1 + CV6). Optional fields// for trusted local callers (capture CLI, autopilot, dream cycle). Remote// MCP callers (ctx.remote !== false) have their values OVERRIDDEN withdiff --git a/src/core/page-state/version-types.ts b/src/core/page-state/version-types.tsindex 3e2177acc6..504be9cb73 100644--- a/src/core/page-state/version-types.ts+++ b/src/core/page-state/version-types.ts@@ -18,6 +18,12 @@ export interface PageVersion {/** Segmented versions: the referenced body's UTF-8 bytes. */body_bytes?: number;content_hash?: string | null;+ /**+ * GBRA-217: why the write that replaced this snapshot was made (`page_versions.change_reason`), as the reader may see it:+ * a remote reader gets it only when this snapshot's successor is world-visible and was not pruned. Absent from rows+ * read without the reason projection.+ */+ replaced_because?: string | null;id: number;page_id: number;compiled_truth: string;diff --git a/src/core/page-state/versions.ts b/src/core/page-state/versions.tsindex ff4b8903f8..96866c8b6d 100644--- a/src/core/page-state/versions.ts+++ b/src/core/page-state/versions.ts@@ -22,9 +22,10 @@ export async function createPageVersion(engine: BrainEngine, slug: string, sourcVALUES ($1,$2,$3::text::jsonb,$4::uuid,$5,$6,$7,$8::text::jsonb,$9,$10) RETURNING *`,[page.id, page.compiled_truth, JSON.stringify(page.frontmatter), revision, page.timeline, page.title, page.type, JSON.stringify(tags), page.deleted_at != null, page.source_path ?? null]);if (isLargePageBytes(Buffer.byteLength(page.compiled_truth ?? '', 'utf-8') + Buffer.byteLength(page.timeline ?? '', 'utf-8'))) {- await tx.executeRaw(`DELETE FROM page_versions WHERE page_id = $1 AND id IN (SELECT id FROM page_versions WHERE page_id = $1- AND octet_length(compiled_truth) + octet_length(COALESCE(timeline, '')) > $2 ORDER BY id DESC OFFSET $3)`,+ const pruned = await tx.executeRaw<{ id: number }>(`DELETE FROM page_versions WHERE page_id = $1 AND id IN (SELECT id FROM page_versions WHERE page_id = $1+ AND octet_length(compiled_truth) + octet_length(COALESCE(timeline, '')) > $2 ORDER BY id DESC OFFSET $3) RETURNING id`,[page.id, PAGE_INLINE_MAX_BYTES, LARGE_PAGE_VERSIONS_KEPT]);+ await markPrunedHistory(tx, page.id, pruned.map(row => Number(row.id)));}return { ...rows[0], snapshot_at: new Date(rows[0].snapshot_at) };};@@ -84,9 +85,22 @@ export async function pruneSegmentedVersions(tx: BrainEngine, pageId: number): Pcap AS (SELECT GREATEST($3::bigint, COALESCE(body_bytes, 0)) AS bytes FROM pages WHERE id = $1)DELETE FROM page_versions WHERE id IN (SELECT kept.id FROM kept, cap WHERE kept.rk > $2 OR kept.bytes > cap.bytes)RETURNING id`, [pageId, policy.versionsMaxPerPage, policy.versionsMaxPinnedBytes]);+ await markPrunedHistory(tx, pageId, deleted.map(row => Number((row as { id: number }).id)));return deleted.length;}+/**+ * GBRA-217: after a prune, the retained snapshot just before each pruned one has lost its successor (`successor_pruned`,+ * so a remote reader is never shown its reason: the successor's visibility can no longer be checked), and the page has+ * lost history (`version_history_gap_at`, read by valid-time answers).+ */+async function markPrunedHistory(tx: BrainEngine, pageId: number, pruned: number[]): Promise<void> {+ if (!pruned.length) return;+ await tx.executeRaw(`UPDATE page_versions SET successor_pruned = true WHERE page_id = $1 AND id IN (+ SELECT (SELECT max(k.id) FROM page_versions k WHERE k.page_id = $1 AND k.id < d.id) FROM unnest($2::int[]) AS d(id))`, [pageId, pruned]);+ await tx.executeRaw('UPDATE pages SET version_history_gap_at = now() WHERE id = $1', [pageId]);+}+/*** `revert_version` of a segmented page or version is not available until the* segment writer (Wave B PR 3): the version's body lives in segments, and thediff --git a/src/core/persistence/change-reason.ts b/src/core/persistence/change-reason.tsnew file mode 100644index 0000000000..9802e81dc7--- /dev/null+++ b/src/core/persistence/change-reason.ts@@ -0,0 +1,97 @@+/**+ * GBRA-217: a human reason on a page write. One canonical form for every source of a reason (a caller's+ * `reason` parameter, a Git `gbrain-reason:` trailer), admitted before the write request is journaled.+ *+ * Where it lands: the snapshot a write archives carries it (`page_versions.change_reason`, read back as+ * `replaced_because`), and a write whose file reaches Git carries it in the commit as a path-mapped+ * trailer `gbrain-reason: <path>: <text>`. A private page never puts its reason in a commit message, and+ * a repo-less brain keeps it in the database alone (`reason_recorded.git: 'no_repository'`).+ */+import { relative, sep } from 'node:path';+import { opError } from '../ops/contract.ts';+import { scanTextSpans } from '../secret-scan.ts';+import { privatePagesFilterFragment } from '../search/private-visibility.ts';+import type { GitCommitNote } from './effect-model.ts';+import { sourceCanonicalGit } from './git-door.ts';+import type { WriteRequest } from './model.ts';+import type { PreparedMutation } from './coordinator.ts';++export const CHANGE_REASON_MAX = 500;+export const CHANGE_REASON_OPERATIONS: readonly string[] = ['put_page', 'edit_page', 'revert_version'];+export const REASON_TRAILER_KEY = 'gbrain-reason';+const DOCS = 'docs/guides/page-history.md#reasons';++/** Tabs and line breaks become spaces, other control characters go, runs of spaces collapse; empty means absent. */+export function canonicalChangeReason(raw: unknown): string | null {+ if (typeof raw !== 'string') return null;+ const text = raw.replace(/[\t\n\r\u2028\u2029]/g, ' ').replace(/[\u0000-\u001f\u007f]/g, '').replace(/ {2,}/g, ' ').trim();+ return text || null;+}++/**+ * Admission: the canonical reason, or a refusal before anything is journaled. The value is never echoed: an over-long+ * reason is refused by its length, and a secret by the detector that matched.+ */+export function admitChangeReason(raw: unknown): string | null {+ if (raw === undefined || raw === null) return null;+ if (typeof raw !== 'string') throw opError('invalid_params', 'reason must be a string.', 'Pass reason as one line of text, or omit it.');+ const reason = canonicalChangeReason(raw);+ if (reason === null) return null;+ const length = [...reason].length;+ if (length > CHANGE_REASON_MAX) {+ throw opError('change_reason_rejected', `reason is ${length} characters after normalisation; the limit is ${CHANGE_REASON_MAX}. Nothing was written.`,+ `Shorten reason to ${CHANGE_REASON_MAX} characters or fewer and retry the same request.`, { reason: 'reason_too_long', docs: DOCS, legacy_error: 'invalid_params' });+ }+ const hit = scanTextSpans(reason).find(span => span.finding !== null);+ if (hit) {+ const offset = [...reason.slice(0, hit.start)].length;+ throw opError('change_reason_rejected', `reason contains what looks like a secret (${hit.finding!.pattern} at character ${offset}). Nothing was written.`,+ 'Remove the secret from reason and retry with a new request_id. A reason is stored in page history and can be pushed in a Git commit message.',+ { reason: 'reason_contains_secret', docs: DOCS, legacy_error: 'invalid_params' });+ }+ return reason;+}++/** The reason note for one path, merged into a note another preparer gave (a repair keeps its subject and trailer). */+export function withReasonNote(path: string, reason: string, base?: GitCommitNote): GitCommitNote {+ const trailer = `${REASON_TRAILER_KEY}: ${path}: ${reason}`;+ return base ? { ...base, trailers: [...(base.trailers ?? []), trailer] }+ : { subject: '', line: `${path}: ${reason}`, trailers: [trailer] };+}++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 }++/**+ * Wraps a page publication so the snapshot its apply archives carries the reason, and its file's commit note carries the+ * trailer when the page that results is world-visible. The snapshot rows are the ones this transaction created for the+ * page (the page lock is held), whichever writer path made them.+ */+export function withChangeReason(row: WriteRequest, prepared: PreparedMutation): PreparedMutation {+ const reason = CHANGE_REASON_OPERATIONS.includes(row.operation) ? canonicalChangeReason(row.intent?.reason) : null;+ if (!reason) return prepared;+ const apply = prepared.apply.bind(prepared);+ prepared.apply = async (tx, preimage) => {+ const pageId = preimage?.page.id ?? null;+ const [before] = pageId === null ? [] : await tx.executeRaw<{ last: number | string | null }>('SELECT max(id) AS last FROM page_versions WHERE page_id = $1', [pageId]);+ 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;+ 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';+ else if (!world) git = 'private';+ else {+ prepared.file.commit = withReasonNote(relative(prepared.file.root, prepared.file.path).split(sep).join('/'), reason, prepared.file.commit);+ git = await sourceCanonicalGit(tx, row.source_id) ? 'committed' : 'queued';+ }+ const recorded: ReasonRecorded = { reason, version: stamped.length > 0, git,+ ...(stamped.length ? {} : { version_why: prepared.observedRevision === null ? 'page_created' : 'no_change' }) };+ return { ...outcome, reason_recorded: recorded };+ };+ return prepared;+}+diff --git a/src/core/persistence/effect-git.ts b/src/core/persistence/effect-git.tsindex ee40f9c1a4..a8b668390b 100644--- a/src/core/persistence/effect-git.ts+++ b/src/core/persistence/effect-git.ts@@ -1,4 +1,4 @@-import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, statSync } from 'node:fs';+import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';import { basename, dirname, join, relative, resolve as resolvePath, sep } from 'node:path';import { execFileBounded } from '../brain-repo-durability.ts';import { gitDurabilityPolicy } from './git-durability-policy.ts';@@ -251,10 +251,25 @@ export function commitMessage(commitPaths: string[], noted: ReadonlyMap<string,const subject = commitPaths.length > 1 ? `gbrain: persist ${commitPaths.length} canonical memory updates`: commitText(noted.get(commitPaths[0]!)?.subject ?? '') || 'gbrain: persist canonical memory update';const body = commitPaths.length > 1 ? [...new Set([...noted.keys()].sort().map(path => commitText(noted.get(path)!.line)).filter(Boolean))] : [];- const trailers = [...new Set([...noted.keys()].sort().map(path => commitText(noted.get(path)!.trailer ?? '')).filter(Boolean))];+ const trailers = [...new Set([...noted.keys()].sort().flatMap(path => (noted.get(path)!.trailers ?? []).map(commitText)).filter(Boolean))];return [subject, ...(body.length ? [body.join('\n')] : []), ...(trailers.length ? [trailers.join('\n')] : [])];}+/** Over this many bytes a commit message goes through a file (`-F`): command lines are bounded (32 KiB on Windows). */+export const COMMIT_MESSAGE_ARG_BYTES = 8 * 1024;++/**+ * The git arguments that give a commit `paragraphs` as its message: `-m` per paragraph, or one `-F <file>` written in+ * `dir` once the message is large. Git joins `-m` paragraphs with a blank line, so both forms produce the same message.+ */+export function commitMessageArgs(paragraphs: string[], dir: string | (() => string)): string[] {+ const text = paragraphs.join('\n\n');+ if (Buffer.byteLength(text, 'utf-8') <= COMMIT_MESSAGE_ARG_BYTES) return paragraphs.flatMap(paragraph => ['-m', paragraph]);+ const file = join(typeof dir === 'string' ? dir : dir(), 'commit-message');+ writeFileSync(file, `${text}\n`, { mode: 0o600 });+ return ['-F', file];+}+/*** #5530: commit a group of single-file targets with one `commit --only`. The* caller owns the native worktree lock and has probed durability. Each@@ -346,8 +361,15 @@ export async function commitGitTargets(root: string, relativePaths: string[], siconst commitPaths = [...new Set(changed.map(c => c.path))];const noted = new Map<string, GitCommitNote>();for (const c of changed) { const note = notes?.get(c.requested); if (note && !noted.has(c.path)) noted.set(c.path, note); }- const message = commitMessage(commitPaths, noted).flatMap(paragraph => ['-m', paragraph]);- const result = await git(session, [...(commitPaths.some(path => removed.has(path)) ? NO_FSCACHE : []), 'commit', '--only', ...message, '--', ...commitPaths]);+ let messageDir: string | undefined;+ let result;+ try {+ const message = commitMessageArgs(commitMessage(commitPaths, noted), () => {+ mkdirSync(persistenceHome(), { recursive: true, mode: 0o700 });+ return messageDir = mkdtempSync(join(persistenceHome(), 'commit-message-'));+ });+ result = await git(session, [...(commitPaths.some(path => removed.has(path)) ? NO_FSCACHE : []), 'commit', '--only', ...message, '--', ...commitPaths]);+ } finally { if (messageDir) rmSync(messageDir, { recursive: true, force: true }); }const outcome = result.code === 0 ? { git: 'committed' } : gitFailure('Cannot commit the canonical Git target.',`git commit failed for ${commitPaths.length} file(s); a missing Git identity (user.name, user.email) in that checkout is one cause to check.`);for (const c of changed) results.set(c.requested, outcome);diff --git a/src/core/persistence/effect-journal.ts b/src/core/persistence/effect-journal.tsindex a0f0eae5a7..ac8119cc59 100644--- a/src/core/persistence/effect-journal.ts+++ b/src/core/persistence/effect-journal.ts@@ -43,7 +43,7 @@ export async function queuePublicationEffects(tx: BrainEngine, row: EffectRequesconst commit = prepared.file.commit;queue('git', { relative_path: relative(binding.local_path, prepared.file.path).split(sep).join('/'),expected_hash: prepared.file.content === null ? null : fileContentHash(prepared.file.content),- ...(opts.pushOnly ? { push_only: true } : commit ? { commit_subject: commit.subject, commit_line: commit.line, ...(commit.trailer ? { commit_trailer: commit.trailer } : {}) } : {}) });+ ...(opts.pushOnly ? { push_only: true } : commit ? { commit_subject: commit.subject, commit_line: commit.line, ...(commit.trailers?.length ? { commit_trailers: commit.trailers } : {}) } : {}) });if (!opts.pushOnly && outcome.persistence && typeof outcome.persistence === 'object') Object.assign(outcome.persistence, { git_state: 'queued' });}if (snapshot && !snapshot.page.deleted_at) {diff --git a/src/core/persistence/effect-model.ts b/src/core/persistence/effect-model.tsindex 3f402f5dcc..6736c81d7d 100644--- a/src/core/persistence/effect-model.ts+++ b/src/core/persistence/effect-model.ts@@ -23,15 +23,15 @@ export interface AppendedRange { start: number; end: number; sha256: string }* blank line, so `git log --format=%(trailers)` finds every repair commit.* Location only, never page text.*/-export interface GitCommitNote { subject: string; line: string; trailer?: string }+export interface GitCommitNote { subject: string; line: string; trailers?: string[] }const safe = (path: string) => path.replace(/[\u0000-\u001f\u007f]/g, '?');/** A fence-repaired file's note: `fenceRepairCommitSubject` alone, `<path> (<classes>)` as its line in a batched commit, trailer `gbrain-repair: invalid_fence <tier> high`. */export function fenceRepairCommit(path: string, classes: readonly string[], tier: FenceRepairReceipt['tier'] = 'deterministic'): GitCommitNote {- return { subject: fenceRepairCommitSubject(path, classes), line: `${safe(path)} (${classes.join(', ')})`, trailer: `gbrain-repair: invalid_fence ${tier} high` };+ return { subject: fenceRepairCommitSubject(path, classes), line: `${safe(path)} (${classes.join(', ')})`, trailers: [`gbrain-repair: invalid_fence ${tier} high`] };}/** #6377 a slug-conflict repair's note: `gbrain: repair frontmatter slug in <path>`, `<path> (frontmatter_slug_conflict)` in a batch, trailer from the receipt's tier and confidence. */export function contentRepairCommit(path: string, receipt: Pick<ContentRepairReceipt, 'tier' | 'confidence'>): GitCommitNote {- return { subject: contentRepairCommitSubject(path), line: `${safe(path)} (frontmatter_slug_conflict)`, trailer: contentRepairTrailer(receipt) };+ return { subject: contentRepairCommitSubject(path), line: `${safe(path)} (frontmatter_slug_conflict)`, trailers: [contentRepairTrailer(receipt)] };}/** `rule`: for `git_target_ignored`, the .gitignore rule that excludes the file (`<file>:<line>: <pattern>`). */export interface ParkedTarget { slug?: string; error_code: string; rule?: string }@@ -79,6 +79,8 @@ export interface PersistenceEffect {/** A single-file Git target's GitCommitNote, when its preparer gave one. */commit_subject?: string;commit_line?: string;+ /** One Git trailer line each (a repair's and a reason's). An effect an older release queued carries one `commit_trailer`. */+ commit_trailers?: string[];commit_trailer?: string;/** G2 (git-door.ts): the file was committed with its publication (a strict source); the effect only pushes. */push_only?: boolean;diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.tsindex ea21617124..918ae5e630 100644--- a/src/core/persistence/effects.ts+++ b/src/core/persistence/effects.ts@@ -317,8 +317,9 @@ async function singleFileGitTarget(engine: BrainEngine, effect: PersistenceEffec/** The commit metadata a single-file Git effect's preparer recorded, if any. */function gitCommitNote(effect: PersistenceEffect): GitCommitNote | undefined {- const { commit_subject: subject, commit_line: line, commit_trailer: trailer } = effect.data;- return typeof subject === 'string' && typeof line === 'string' ? { subject, line, ...(typeof trailer === 'string' ? { trailer } : {}) } : 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;}async function gitPage(engine: BrainEngine, effect: PersistenceEffect, binding: WorktreeBinding | null, opts: EffectWorkerOptions,diff --git a/src/core/persistence/git-door.ts b/src/core/persistence/git-door.tsindex 1574a98772..432625120c 100644--- a/src/core/persistence/git-door.ts+++ b/src/core/persistence/git-door.ts@@ -43,7 +43,7 @@ import { closeSync, copyFileSync, existsSync, linkSync, lstatSync, mkdirSync, mkimport { join, relative, resolve, sep } from 'node:path';import type { Notice } from '../agent-output.ts';import { OperationError, opError } from '../ops/contract.ts';-import { commitMessage, git, gitBytes, gitFailure, gitStepTimeoutMs, ignoredTargetError, reclaimAbandonedIndexLock, withSession, type GitSession } from './effect-git.ts';+import { commitMessage, commitMessageArgs, git, gitBytes, gitFailure, gitStepTimeoutMs, ignoredTargetError, reclaimAbandonedIndexLock, withSession, type GitSession } from './effect-git.ts';import type { GitCommitNote } from './effect-model.ts';import { persistenceHome } from './identity.ts';import { ignoreCandidates } from './ignore-rules.ts';@@ -322,7 +322,7 @@ async function doorCommit(session: GitSession, root: string, files: DoorFile[],const noted = new Map(changed.flatMap(target => target.note ? [[target.rel, target.note] as const] : []));const message = commitMessage(changed.map(target => target.rel), noted).map(stripspace).filter(Boolean);- const commit = await git(session, ['commit-tree', tree, '-p', head, ...message.flatMap(paragraph => ['-m', paragraph])]);+ const commit = await git(session, ['commit-tree', tree, '-p', head, ...commitMessageArgs(message, scratch)]);if (commit.code !== 0) throw gitFailure('Cannot commit the canonical Git target.',`git commit-tree failed for ${changed.length} file(s); a missing Git identity (user.name, user.email) in that checkout is one cause to check.`);const created = commit.stdout.trim();diff --git a/src/core/persistence/page-batch.ts b/src/core/persistence/page-batch.tsindex 4681bf86b3..b506fce341 100644--- a/src/core/persistence/page-batch.ts+++ b/src/core/persistence/page-batch.ts@@ -15,6 +15,7 @@ import { pageQuarantinedNotice } from '../quarantine.ts';import type { OperationContext } from '../ops/contract.ts';import { fenceNormalizedNotice, mergeFencesNormalized, type FencesNormalized } from '../fence-repair/report.ts';import { OperationError, opError } from '../ops/contract.ts';+import { admitChangeReason } from './change-reason.ts';import { admitWriteGroupInTransaction, type WriteAdmission } from './journal.ts';import { retryWriteAdmission } from './admission-retry.ts';import { declareDurablePersistence } from './protocol.ts';@@ -39,8 +40,8 @@ export const PAGE_BATCH_DEFAULT_WAIT_MS = 25_000;const PREPARE_CONCURRENCY = 8;/** Batch admission is one transaction over every page; it gets more than a single write's budget. */const BATCH_ADMISSION_BUDGET_MS = 30_000;-const PAGE_KEYS = new Set(['slug', 'content', 'expected_revision', 'allow_empty', 'allow_shrink', 'drop_timeline']);-interface BatchPage { slug: string; content: string; expected_revision?: unknown; allow_empty?: unknown; allow_shrink?: unknown; drop_timeline?: unknown }+const PAGE_KEYS = new Set(['slug', 'content', 'expected_revision', 'allow_empty', 'allow_shrink', 'drop_timeline', 'reason']);+interface BatchPage { slug: string; content: string; expected_revision?: unknown; allow_empty?: unknown; allow_shrink?: unknown; drop_timeline?: unknown; reason?: string }interface PageResult { index: number; slug: string; row?: WriteRequest; refusal?: OperationError; typeWarning?: PageTypeWarning | null; repeatOf?: number }interface BatchMarker { id: string; index: number; size: number; repeats?: number[] }@@ -60,7 +61,14 @@ function parsePages(value: unknown): BatchPage[] {if (typeof record.slug !== 'string' || !record.slug) throw invalid(`pages[${index}].slug must be a non-empty string; nothing was written.`, 'Give every page its slug, for example "notes/topic-name".');if (typeof record.content !== 'string') throw invalid(`pages[${index}].content must be a string; nothing was written.`, 'Pass the complete markdown page, frontmatter included, as content.');bytes += Buffer.byteLength(record.content);- return record as unknown as BatchPage;+ if (!Object.hasOwn(record, 'reason')) return record as unknown as BatchPage;+ const { reason: raw, ...rest } = record;+ let reason: string | null;+ try { reason = admitChangeReason(raw); } catch (error) {+ if (error instanceof OperationError) error.message = `pages[${index}] (${record.slug}): ${error.message} No page of this batch was written.`;+ throw error;+ }+ return (reason === null ? rest : { ...rest, reason }) as unknown as BatchPage;});if (bytes > PAGE_BATCH_MAX_BYTES) {throw invalid(`This batch carries ${bytes} bytes of content; the limit is ${PAGE_BATCH_MAX_BYTES} bytes per put_pages call. Nothing was written.`,@@ -83,7 +91,7 @@ function findRepeats(pages: BatchPage[]): Repeats {pages.forEach((page, index) => bySlug.set(page.slug.toLowerCase(), [...(bySlug.get(page.slug.toLowerCase()) ?? []), index]));const repeatOf: (number | undefined)[] = new Array(pages.length);const refusals = new Map<number, OperationError>();- const same = (a: BatchPage, b: BatchPage) => a.slug === b.slug && a.content === b.content && a.expected_revision === b.expected_revision && a.allow_empty === b.allow_empty && a.allow_shrink === b.allow_shrink;+ const same = (a: BatchPage, b: BatchPage) => a.slug === b.slug && a.content === b.content && a.expected_revision === b.expected_revision && a.allow_empty === b.allow_empty && a.allow_shrink === b.allow_shrink && a.reason === b.reason;for (const indexes of bySlug.values()) {if (indexes.length < 2) continue;const first = pages[indexes[0]!]!;@@ -125,7 +133,8 @@ function pageEntry(result: PageResult): Record<string, unknown> {...(outcome.embedding_state !== undefined ? { embedding_state: outcome.embedding_state } : {}), ...warning,...(outcome.fences_normalized ? { fences_normalized: outcome.fences_normalized } : {}),...(outcome.quarantined ? { quarantined: outcome.quarantined } : {}),- ...(outcome.timeline_rows_removed ? { timeline_rows_removed: outcome.timeline_rows_removed } : {}) };+ ...(outcome.timeline_rows_removed ? { timeline_rows_removed: outcome.timeline_rows_removed } : {}),+ ...(outcome.reason_recorded ? { reason_recorded: outcome.reason_recorded } : {}) };} catch (error) {if (!(error instanceof OperationError)) throw error;return { ...base, request_id: row.request_id, state: row.state, error: error.toJSON(), ...warning };@@ -213,6 +222,7 @@ async function preparePages(own: OperationContext, shared: OperationContext, batif (page.allow_empty !== undefined) params.allow_empty = page.allow_empty;if (page.allow_shrink !== undefined) params.allow_shrink = page.allow_shrink;if (page.drop_timeline !== undefined) params.drop_timeline = page.drop_timeline;+ if (page.reason !== undefined) params.reason = page.reason;try {prepared[index] = await preparePageAdmission(ctx, { operation: 'put_page', params,batch: { id: batchId, index, size: pages.length, requestId: pageBatchChildRequestId(batchId, index), ...(copies.length ? { repeats: copies } : {}) } });diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex df5428c676..dcfc0320b8 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -7,6 +7,7 @@ import { realpathSync } from 'node:fs';import { isAbsolute, join, relative, resolve, sep } from 'node:path';import type { OperationContext } from '../ops/contract.ts';import { OperationError } from '../ops/contract.ts';+import { admitChangeReason, CHANGE_REASON_OPERATIONS } from './change-reason.ts';import { VERSION } from '../../version.ts';import { ownerBuildMismatch } from './publication-failure.ts';import { enforceClientSlugFence, enforceSubagentSlugFence, isLegacyStoredPageSlug, normalizeSlugPrefix, parseSourceIdParam, requireWritablePage, validatePageSlug } from '../ops/context.ts';@@ -308,6 +309,11 @@ 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.+ 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;+ }const callerIntent = { ...p };delete callerIntent.request_id;if (prior) {diff --git a/src/core/persistence/params.ts b/src/core/persistence/params.tsindex 1be9870e13..95a792d18a 100644--- a/src/core/persistence/params.ts+++ b/src/core/persistence/params.ts@@ -34,6 +34,12 @@ import { WRITE_REQUEST_STATES, WRITE_HEALTH_REASONS, WRITE_HEALTH_ASSESSMENTS, W* Runtime validators belong in separate modules; importing OperationError here* creates a params -> contract -> verbs -> params initialization cycle.*/+/** GBRA-217: the human reason for a page write (docs/guides/page-history.md#reasons). */+export const REASON_PARAM: ParamDef = {+ type: 'string',+ description: 'Why this change, one line (max 500 chars); kept in page history.',+};+export const WRITE_REQUEST_PARAM: ParamDef = {type: 'string',description: 'Reuse only to retry.',diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.tsindex 249457062c..6a243c5c01 100644--- a/src/core/persistence/service.ts+++ b/src/core/persistence/service.ts@@ -9,6 +9,7 @@ import { enginePoolStats } from '../postgres-engine/pool-stats.ts';import { claimOwnerKind, isOneShotCommand } from './claim-phase.ts';import { noteDirectPoolLease } from '../direct-pool-profile.ts';import { preparePageMutation } from './page-prepare.ts';+import { withChangeReason } from './change-reason.ts';import { prepareSemanticPageMutation } from './semantic-pages.ts';import { getWriteRequestById, getWriteRequestProgress, receiptFor, type WriteRequestProgress } from './journal.ts';import { isTerminal, type WriteRequest } from './model.ts';@@ -110,8 +111,8 @@ export async function preparePersistedMutation(e: BrainEngine, row: WriteRequestif (['add_tag','remove_tag','add_timeline_entry'].includes(row.operation)) return prepareSemanticPageMutation(e, row, cfg);if (row.operation === 'add_link' || row.operation === 'remove_link') return (await import('./manual-links.ts')).prepareManualLinkMutation(e, row, cfg);if (row.operation === 'append_page') return (await import('./page-upload.ts')).withStagedBodyIf(e, row, async () => (await import('./page-append.ts')).prepareAppendMutation(e, row, cfg, signal, clock));- if (['put_page','capture','delete_page','restore_page','revert_version','edit_page'].includes(row.operation)) return preparePageMutation(e, row, cfg, undefined, signal,- { coordinated: await writeSwitchOn(e, 'single_write_group').catch(() => true), clock, boundedChunkWrites: true });+ if (['put_page','capture','delete_page','restore_page','revert_version','edit_page'].includes(row.operation)) return withChangeReason(row, await preparePageMutation(e, row, cfg, undefined, signal,+ { coordinated: await writeSwitchOn(e, 'single_write_group').catch(() => true), clock, boundedChunkWrites: true }));throw new OperationError('unsupported_mutation_protocol', 'No compatible mutation preparer is registered for this operation.', `Request ${row.request_id} (${row.operation}) was accepted by a gbrain version whose preparer this one lacks, so it has not run. Run gbrain upgrade on every host that serves this brain; the request stays journaled and resumes after the upgrade.`);}/**diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.tsindex 37227d57d5..e4bd78fa4b 100644--- a/src/core/schema-migrations/latest.generated.ts+++ b/src/core/schema-migrations/latest.generated.ts@@ -4,4 +4,4 @@// The highest schema migration version (migrate.ts LATEST_VERSION), importable without// loading the migrations themselves.-export const LATEST_SCHEMA_VERSION = 278;+export const LATEST_SCHEMA_VERSION = 279;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex ee27aee507..de4ae287ea 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -279,6 +279,7 @@ import { v275 } from './v275-rls-backfill-unguarded-tables.ts';import { v276 } from './v276-persistence-foreground-committed-index.ts';import { v277 } from './v277-function-search-path-pg-temp.ts';import { v278 } from './v278-writer-fence-fail-closed.ts';+import { v279 } from './v279-page-change-reasons.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -556,4 +557,5 @@ export const MIGRATIONS: Migration[] = [v276,v277,v278,+ v279,];diff --git a/src/core/schema-migrations/v279-page-change-reasons.ts b/src/core/schema-migrations/v279-page-change-reasons.tsnew file mode 100644index 0000000000..97f3e025bc--- /dev/null+++ b/src/core/schema-migrations/v279-page-change-reasons.ts@@ -0,0 +1,42 @@+import type { Migration } from './types.ts';++// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.+//+// GBRA-217: page history carries why a page changed (docs/guides/page-history.md).+// - page_versions.change_reason: the reason for the write that replaced this+// snapshot, mirrored from the write's Git trailer (`gbrain-reason: <path>: <text>`)+// or, on a page that never reaches Git, the database's own record of it.+// - page_versions.successor_pruned: set on a retained snapshot whose next+// snapshot was pruned, so a remote reader cannot check the successor's+// visibility and is never shown the reason (fails closed).+// - pages.version_history_gap_at: when the page last lost history (a prune, or+// a sync import that consumed more than one commit for its file).+// - reason_purge_tombstones: text-free (commit, path) pairs a purge found a+// claim in, so a later sync or re-import never brings that reason back.+// Nullable columns, no backfill; existing rows are never re-stamped. Fresh+// installs get these from this migration too (not src/schema.sql), so fresh and+// upgraded brains share column ordinals. The number is a placeholder restamped+// at the merge slot.+export const v279: Migration = {+ version: 279,+ name: 'page_change_reasons',+ idempotent: true,+ sql: `+ ALTER TABLE page_versions ADD COLUMN IF NOT EXISTS change_reason TEXT;+ ALTER TABLE page_versions ADD COLUMN IF NOT EXISTS successor_pruned BOOLEAN;+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS version_history_gap_at TIMESTAMPTZ;+ CREATE TABLE IF NOT EXISTS reason_purge_tombstones (+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,+ commit_sha TEXT NOT NULL,+ path TEXT NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (source_id, commit_sha, path)+ );+ DO $rls$ BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles pr WHERE pg_has_role(current_user, pr.oid, 'USAGE') AND (pr.rolbypassrls OR pr.rolsuper)) THEN+ ALTER TABLE reason_purge_tombstones ENABLE ROW LEVEL SECURITY;+ END IF;+ END $rls$;+ `,+};diff --git a/test/git-door-plumbing-gbra133.test.ts b/test/git-door-plumbing-gbra133.test.tsindex d8c4e0b014..0c95e4783d 100644--- a/test/git-door-plumbing-gbra133.test.ts+++ b/test/git-door-plumbing-gbra133.test.ts@@ -171,8 +171,8 @@ describe('G2 plumbing door commit', () => {test('the message and trailers are the porcelain path\'s, alone and in a group', async () => {const seed = { 'notes/a.md': 'a\n', 'notes/b.md': 'b\n', 'notes/c.md': 'c\n' };const notes: Record<string, GitCommitNote> = {- 'notes/a.md': { subject: 'gbrain: repair notes/a.md ', line: 'notes/a.md (invalid_fence)', trailer: 'gbrain-repair: invalid_fence deterministic high' },- 'notes/b.md': { subject: 'gbrain: repair notes/b.md', line: 'notes/b.md (frontmatter_slug_conflict)', trailer: 'gbrain-repair: frontmatter_slug_conflict deterministic high' },+ 'notes/a.md': { subject: 'gbrain: repair notes/a.md ', line: 'notes/a.md (invalid_fence)', trailers: ['gbrain-repair: invalid_fence deterministic high'] },+ 'notes/b.md': { subject: 'gbrain: repair notes/b.md', line: 'notes/b.md (frontmatter_slug_conflict)', trailers: ['gbrain-repair: frontmatter_slug_conflict deterministic high'] },};for (const paths of [['notes/a.md'], ['notes/c.md'], ['notes/a.md', 'notes/b.md', 'notes/c.md']]) {const porcelain = repo(seed), plumbing = repo(seed);diff --git a/test/page-change-reason-gbra217.test.ts b/test/page-change-reason-gbra217.test.tsnew file mode 100644index 0000000000..b97edcc7eb--- /dev/null+++ b/test/page-change-reason-gbra217.test.ts@@ -0,0 +1,140 @@+/**+ * GBRA-217: a page write carries an optional human reason.+ *+ * 1. Protects: the reason given for a write is stored on the snapshot that write archived and read back by get_versions+ * as `replaced_because`; each write result says where it was recorded (`reason_recorded`). On a repo-less brain (the+ * default keyless install) the database is the record: `git: 'no_repository'`, never a refusal.+ * 2. Fails when: a reason is lost or lands on the wrong snapshot, a refused reason (too long, a secret) is stored in any+ * journal row, the replay identity ignores the reason, or a remote reader is shown a reason whose successor snapshot+ * is private or was pruned.+ * 3. No new seam: the real put_page / edit_page / revert_version / put_pages / get_versions handlers over PGLite.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { operationsByName, OperationError, type OperationContext } from '../src/core/operations.ts';+import { canonicalChangeReason, CHANGE_REASON_MAX } from '../src/core/persistence/change-reason.ts';+import { resetGateway } from '../src/core/ai/gateway.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 120_000);+afterAll(async () => { await engine.disconnect(); resetGateway(); });+beforeEach(async () => { await resetPgliteState(engine); resetGateway(); });++function ctx(remote = false): OperationContext {+ return { engine, config: { engine: 'pglite' as const }, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote, sourceId: 'default' } as OperationContext;+}+const call = (name: string, params: Record<string, unknown>, remote = false) =>+ operationsByName[name]!.handler(ctx(remote), params) as Promise<Record<string, unknown>>;+const page = (body: string, extra = '') => `---\ntitle: Policy\ntype: note\n${extra}---\n\n${body}\n`;+const SLUG = 'policies/policy-4a-example';+const outcomeOf = (result: Record<string, unknown>) => (result.outcome ?? result) as Record<string, unknown>;+async function revision(slug = SLUG): Promise<string> {+ return String((await call('get_page', { slug, include_content: true })).revision);+}+async function versions(remote = false, slug = SLUG): Promise<Array<Record<string, unknown>>> {+ return await call('get_versions', { slug }, remote) as unknown as Array<Record<string, unknown>>;+}+async function journalHolds(text: string): Promise<boolean> {+ const rows = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM persistence_requests WHERE intent::text LIKE $1 OR outcome::text LIKE $1`, [`%${text}%`]);+ const effects = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM persistence_effects WHERE data::text LIKE $1`, [`%${text}%`]);+ return rows[0]!.n + effects[0]!.n > 0;+}++describe('page change reasons on a repo-less brain', () => {+ test('a reason lands on the snapshot its write archived; creation and a reasonless write are reported', async () => {+ const created = outcomeOf(await call('put_page', { slug: SLUG, content: page('Edition one.'), reason: 'First edition from the board.', wait_ms: 30_000 }));+ expect(created.reason_recorded).toEqual({ reason: 'First edition from the board.', version: false, version_why: 'page_created', git: 'no_repository' });++ const second = outcomeOf(await call('put_page', { slug: SLUG, content: page('Edition two.'), expected_revision: await revision(), reason: 'Client asked for\nthe 30-day window.', wait_ms: 30_000 }));+ expect(second.reason_recorded).toEqual({ reason: 'Client asked for the 30-day window.', version: true, git: 'no_repository' });++ await call('put_page', { slug: SLUG, content: page('Edition three.'), expected_revision: await revision(), wait_ms: 30_000 });+ const rows = await versions();+ expect(rows.map(row => row.replaced_because)).toEqual([null, 'Client asked for the 30-day window.']);+ const bodies = await call('get_versions', { slug: SLUG, include_body: true }) as unknown as Array<Record<string, unknown>>;+ expect(bodies.map(row => [row.compiled_truth, row.replaced_because])).toEqual([+ [expect.stringContaining('Edition two.'), null], [expect.stringContaining('Edition one.'), 'Client asked for the 30-day window.']]);+ });++ test('edit_page and revert_version carry their reasons', async () => {+ await call('put_page', { slug: SLUG, content: page('Refunds within 14 days.'), wait_ms: 30_000 });+ const edited = outcomeOf(await call('edit_page', { slug: SLUG, expected_revision: await revision(), edits: [{ old_text: '14 days', new_text: '30 days' }], reason: 'Policy update after review.' }));+ expect(edited.reason_recorded).toMatchObject({ reason: 'Policy update after review.', version: true, git: 'no_repository' });+ const [first] = await versions();+ const reverted = outcomeOf(await call('revert_version', { slug: SLUG, version_id: first!.id, expected_revision: await revision(), reason: 'Review was withdrawn.', wait_ms: 30_000 }));+ expect(reverted.reason_recorded).toMatchObject({ reason: 'Review was withdrawn.', version: true });+ expect((await versions()).map(row => row.replaced_because)).toEqual(['Review was withdrawn.', 'Policy update after review.']);+ });++ test('refused reasons write nothing and are kept in no journal row', async () => {+ const tooLong = 'é'.repeat(CHANGE_REASON_MAX + 1);+ const long = await call('put_page', { slug: SLUG, content: page('x'), reason: tooLong }).then(() => null, e => e);+ expect(long).toBeInstanceOf(OperationError);+ expect((long as OperationError).toJSON()).toMatchObject({ error: 'invalid_params', code: 'change_reason_rejected', reason: 'reason_too_long' });+ expect(JSON.stringify((long as OperationError).toJSON())).not.toContain('éééé');++ const secret = 'ghp_' + 'A1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6Q7r8';+ const leaked = await call('put_page', { slug: SLUG, content: page('x'), reason: `rotated token ${secret}` }).then(() => null, e => e);+ expect((leaked as OperationError).toJSON()).toMatchObject({ code: 'change_reason_rejected', reason: 'reason_contains_secret' });+ expect(JSON.stringify((leaked as OperationError).toJSON())).not.toContain(secret);+ expect(await journalHolds(secret)).toBe(false);+ expect(await journalHolds('éééé')).toBe(false);+ expect((await engine.executeRaw('SELECT 1 FROM pages WHERE slug = $1', [SLUG])).length).toBe(0);++ const batch = await call('put_pages', { request_id: crypto.randomUUID(), pages: [+ { slug: 'notes/a-example', content: page('a'), reason: 'fine' }, { slug: 'notes/b-example', content: page('b'), reason: `token ${secret}` }] }).then(() => null, e => e);+ expect((batch as OperationError).message).toContain('pages[1] (notes/b-example)');+ expect((await engine.executeRaw("SELECT 1 FROM pages WHERE slug LIKE 'notes/%'")).length).toBe(0);+ expect(await journalHolds(secret)).toBe(false);+ });++ 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 });+ await call('put_page', { slug: SLUG, content: page('one'), reason: 'same reason', request_id, wait_ms: 30_000 });+ const conflict = await call('put_page', { slug: SLUG, content: page('one'), reason: 'another reason', request_id, wait_ms: 30_000 }).then(() => null, e => e);+ expect(conflict).toBeInstanceOf(OperationError);+ });++ test('put_pages items carry their own reasons; equal repeats coalesce and different ones conflict', async () => {+ await call('put_pages', { request_id: crypto.randomUUID(), wait_ms: 30_000, pages: [{ slug: 'notes/a-example', content: page('a1') }, { slug: 'notes/b-example', content: page('b1') }] });+ const a = await revision('notes/a-example'), b = await revision('notes/b-example');+ const result = await call('put_pages', { request_id: crypto.randomUUID(), wait_ms: 30_000, pages: [+ { slug: 'notes/a-example', content: page('a2'), expected_revision: a, reason: 'reason a' },+ { slug: 'notes/b-example', content: page('b2'), expected_revision: b, reason: 'reason b' },+ { slug: 'notes/b-example', content: page('b2'), expected_revision: b, reason: 'reason b' }] });+ const entries = result.pages as Array<Record<string, unknown>>;+ expect(entries[0]!.reason_recorded).toMatchObject({ reason: 'reason a', version: true });+ expect((await versions(false, 'notes/b-example'))[0]!.replaced_because).toBe('reason b');+ const differ = await call('put_pages', { request_id: crypto.randomUUID(), wait_ms: 30_000, pages: [+ { slug: 'notes/c-example', content: page('c'), reason: 'one' }, { slug: 'notes/c-example', content: page('c'), reason: 'two' }] });+ expect((differ.pages as Array<Record<string, unknown>>).map(entry => entry.state)).toEqual(['refused', 'refused']);+ });++ test('a remote reader sees a reason only when the successor is world-visible and was not pruned', async () => {+ await call('put_page', { slug: SLUG, content: page('world one'), wait_ms: 30_000 });+ await call('put_page', { slug: SLUG, content: page('private draft', 'visibility: private\n'), expected_revision: await revision(), reason: 'private-time reason', wait_ms: 30_000 });+ await call('put_page', { slug: SLUG, content: page('world two'), expected_revision: await revision(), reason: 'published again', wait_ms: 30_000 });+ expect((await versions()).map(row => row.replaced_because)).toEqual(['published again', 'private-time reason']);+ const remote = await versions(true);+ expect(remote.map(row => row.replaced_because)).toEqual([null]);+ expect(JSON.stringify(remote)).not.toContain('private-time reason');++ await call('put_page', { slug: SLUG, content: page('world three'), expected_revision: await revision(), reason: 'third edition', wait_ms: 30_000 });+ expect((await versions(true))[0]!.replaced_because).toBe('third edition');+ await engine.executeRaw("UPDATE page_versions SET successor_pruned = true WHERE change_reason = 'third edition'");+ expect((await versions(true))[0]!.replaced_because).toBeNull();+ expect((await versions(false))[0]!.replaced_because).toBe('third edition');+ });++ test('canonicaliser bounds', () => {+ expect(canonicalChangeReason(' a\tb\r\nc\u0007 d ')).toBe('a b c d');+ expect(canonicalChangeReason(' \n ')).toBeNull();+ });+});