Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Label repairs on a brain without managed persistence edit the label lines of the page file too, instead of holding it (T1)
garrytan8891b07d4d6e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fe53922fc5..1714c902b7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,7 +20,7 @@ identifiers and attribution are available in the pre-removal Git revision- `src/core/persistence/page-prepare.ts`: a `managed_maintenance_page` write that carries `label_edit` publishes the canonical file's own bytes with only its label lines edited (`labelEditFile`), keeping its body when it reads as the write's body, and refuses instead of re-rendering when no line edit reads back as the write.- `src/core/persistence/prepared-maintenance.ts`: maintenance page publications carry `labelEdit`.- `src/core/repair/label-write.ts` (new): the label-only write door both repairs use (the maintenance door with `keep_trust` on a managed brain; the import under the page lock and `withTrustKeep` otherwise); `filesInCheckout` and `importAtRevision` moved here from `private-labels.ts`.-- `src/core/repair/visibility.ts`: page and fenced-fact items write through the label door instead of `put_page`; on a brain without managed persistence a page whose file sits in a checkout is held (`file_backed`) and a segmented page is held (`segmented_page`); new `--slug` selection (class `pages`), preview-bound, tighten-only.+- `src/core/repair/visibility.ts`: page and fenced-fact items write through the label door instead of `put_page`; on a brain without managed persistence a page whose file sits in a checkout gets the same label-line edit in that file, imported with its tier kept; a segmented page is held (`segmented_page`); new `--slug` selection (class `pages`), preview-bound, tighten-only.- `src/core/repair/private-labels.ts`: clears and restores carry their label edit, so the file loses or regains only those lines.- `src/core/trust/label-lowerings.ts` (new), `src/cli/commands/trust.ts`: `gbrain trust backfill --label-lowerings [--source ID] [--json]`, read-only.- Tests: `test/label-only-repairs.test.ts` (managed Git source and repo-less brain, PGLite and Postgres).diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.mdindex 772804ae61..1eaedf90b6 100644--- a/docs/architecture/key-files/core-persistence-continued.md+++ b/docs/architecture/key-files/core-persistence-continued.md@@ -42,4 +42,4 @@ The #6188 fence check and fence repair live in [fence repair](core-fence-repair.- `src/core/postgres-engine/reserved-transactions.ts` with `isPersistenceDeclaration` (`src/core/persistence/protocol.ts`) — BEGIN pipelining. `isPersistenceDeclaration` (GBRA-156) accepts exactly the `protocol.ts` declarations (transaction-local `set_config` calls and the brain row FOR SHARE). Admission, the FIFO claim, the effect claims and source guards, the receipt true-up, the single publication (`coordinator.ts`) and the consumer's lent lane transactions (`consumer.ts` `onLane`, through `reservedTransactions`) pass it as `TransactionOptions.pipelineFirst`, so behind a transaction-mode pooler the declaration goes out with BEGIN (one round trip less per transaction) while every later statement still waits for BEGIN's answer; if BEGIN fails, only the declaration has run, in autocommit, where it changes nothing. A reserved transaction gates every statement its body can reach, savepoint and nested-transaction bodies and `file()` included. A sync lane group's publication passes none: its begun mark must follow BEGIN's answer (`sync-lanes.ts` `awaitLaneBegin`). Tests: `test/persistence-pipeline-first.test.ts` (the predicate and the reviewed call sites), `test/e2e/pgbouncer-transaction-pipeline-6930.test.ts`.- `src/core/links-fence.ts` + `src/core/links-fence-projection.ts` — the `## Links` fence (G5): the markdown form of authored (manual) edges, `<!--- gbrain:links:begin -->` / `end` around `| to | type | source | valid_from | valid_until | context |`, one row per (to, type, source), source defaulting to `manual`; a reconciliation-managed provenance (`MANAGED_LINK_SOURCES`, exported here and re-exported by `ops/links.ts`), a bad date or a duplicate key is a skipped row with a warning. `parseLinksFence` (state `absent` / `parsed` / `malformed`), the deterministic `renderLinksFence` (rows sorted by key), `upsertLinksFenceRow` (omitted context and dates keep the stored ones; identical row = unchanged body), `removeLinksFenceRows` (leaves an empty fence), `replaceOrInsertLinksFence` (a `## Links` section at the end of compiled_truth, above an unclosed code block) and `maskLinksFence`, which `extractBodyLinks` applies so the fence cells are never also extracted as markdown, wikilink or bare-slug edges. A rewrite of a fence that parses with warnings throws `LinksFenceRewriteRefusal`. Cells use `escapeFenceCell` plus the same one-level marker encoding for `gbrain:links:*`. `projectLinksFence(tx, page, rows)` reconciles only what the page's fence owns: edges with origin_page_id = the page and origin_field `links_fence` (deleted, context-updated, inserted by key) and `manual` transitions with origin_page_id = the page, compared per row by (to, type, link_source, kind, date) and written with the row's source in `link_source`, then refreshes the touched relationships; a row whose target is not a live page in the source yields no edge. `linksFenceProjectionRows` returns null for an absent or malformed fence, so such a body changes no edge (an absent fence retires nothing, as for facts; unlike facts no held generation is recorded, so after a hand deletion of the whole section the database keeps edges git no longer has until `remove_link` or the G3 indexer), and drops rows typed with a link type the active pack does not declare. Callers: `prepareCanonicalProjections` (every projected page publication, quarantined and segmented-unread bodies excepted), `prepareAutomaticLinks` (put_page auto-links and the managed links maintenance, so `extract --stale` restores a lost fence edge) and `persistence/manual-links.ts`. Database-only manual edges (origin_field NULL) are never touched by any of them. Pinned by `test/links-fence.test.ts` and `test/managed-links-fence.test.ts`.- `src/core/persistence/source-lifecycle.ts` retire batches with `topology-transaction.ts` (#7702/#8905) — every `topologyTransaction` runs under `statement_timeout=5s` and `lock_timeout=1s` and maps SQLSTATE 57014/55P03 to `write_pending`, so a managed `remove` or `purge` first deletes the source's pages in batches of `SOURCE_RETIRE_BATCH_PAGES` (500; about 110 ms per batch with chunks and links on Postgres) under the native locks `withTopologyLocks` holds, each batch its own `topologyTransaction`. A batch re-checks the final transaction's preconditions (admin state, `lockTopologyRows`, the incarnation read before the locks, archived or `EXPIRED_ARCHIVE_SQL` due, no prior receipt other than this request's own admission, no `oauth_clients` reference, `assertTopologyRequestsSettled` from `topology-locks.ts`, `lockTopologyPrincipal`, and on the first batch `admitTopologyRetire` from `topology-receipts.ts`, which checks the receipt quotas at the largest receipt and records the admission) and, when one would refuse or replay, stops without deleting so the final transaction reports it, or throws that refusal before deleting; a batch that fails `write_pending` is retried at half the size (floor 1), so heavy pages still fit the bound; a refusal after some batches committed says how many pages that run already deleted; a dry run, a missing checkout, an unconfirmed operation and an admission-hooked call never batch. The final transaction's `sources` delete runs `removedSourceScrubCtes` (#9068: the source's retrieval and volunteer rows, and its slugs in eval candidates), so a run that stops after some batches leaves those rows until a retry commits. Each batch deletes inside `withCoordinatedWrite` with local-CLI attribution (the `pages` guard needs the source in `gbrain.write_sources`; only the final `sources` delete sets `gbrain.topology_change`). Committed batches are durable: a retry (same or new request_id) resumes, and the receipt's `pages_deleted` counts the pages deleted by the run that commits it. #8984: the first batch's transaction records the admission, a `persistence_topology_changes` row in state `recovering` with no recovery record, bound to the source incarnation it deletes from (`isRetireAdmission`); `recordTopologyChange` settles it `committed`, and a remove or purge that deletes that incarnation under another request, or any other lifecycle operation that commits a change to it (archive, restore, rebind, claim), settles it `failed` (`supersedeTopologyRetires`, which skips only the caller's own principal and request_id pair). A retry of the request_id against another incarnation (the source was removed and re-added) refuses `source_retire_superseded`, settles the admission `failed` and deletes nothing, also when a since-replaced CLI registration (another principal) admitted that request_id for a remove or purge, since idempotency is per principal; an admission bound to the current incarnation still resumes under the new registration; deactivation and graduation list an unsettled admission as a blocker that names its request_id and asks the user whether to finish it or keep what is left; an automatic expired-archive purge's admission (`expired_only` in its outcome) is left to the next automatic run with `needsUser: false`, and `sources writer status --json` lists the stopped and superseded requests (`topology_requests`). Tests: `test/source-retire-batched.test.ts` (PGLite), `test/e2e/source-retire-batched-postgres.test.ts` (60,000 pages), `test/source-retire-incarnation.test.ts` and `test/e2e/source-retire-incarnation-postgres.test.ts`.-- `src/core/persistence/label-edit.ts` + `src/core/repair/label-write.ts` (GST-2468) — the label-only page write of operator repairs (`repair visibility`, `repair private-labels`). `label-edit.ts`: `LABEL_KEYS` (visibility, access, confidentiality), `readLabelEdit` validates a `managed_maintenance_page` intent's `label_edit` (`set` plain-word values, `remove` keys), `spliceLabelLines` removes, replaces or appends label lines in a file's frontmatter text and declines (null) a block or multi-line value, a duplicate key or a file with no frontmatter block. `page-prepare.ts` `labelEditFile` uses it in `compareFileTarget` when the file matches the snapshot: the edited file (or its edited head over the write's body, for a fence row) must read back as the file the write would render, else the write refuses `invalid_params`; the file is never re-rendered under a label edit. `label-write.ts`: `writeLabelPage` publishes through the maintenance door with `keep_trust` and the edit on a managed brain, else `importAtRevision` (maintenance transaction, page lock, `withTrustKeep`); `filesInCheckout` names the unmanaged pages whose checkout file would undo a database-only write, which callers hold as `file_backed`.+- `src/core/persistence/label-edit.ts` + `src/core/repair/label-write.ts` (GST-2468) — the label-only page write of operator repairs (`repair visibility`, `repair private-labels`). `label-edit.ts`: `LABEL_KEYS` (visibility, access, confidentiality), `readLabelEdit` validates a `managed_maintenance_page` intent's `label_edit` (`set` plain-word values, `remove` keys), `spliceLabelLines` removes, replaces or appends label lines in a file's frontmatter text and declines (null) a block or multi-line value, a duplicate key or a file with no frontmatter block. `page-prepare.ts` `labelEditFile` uses it in `compareFileTarget` when the file matches the snapshot: the edited file (or its edited head over the write's body, for a fence row) must read back as the file the write would render, else the write refuses `invalid_params`; the file is never re-rendered under a label edit. `label-write.ts`: `writeLabelPage` publishes through the maintenance door with `keep_trust` and the edit on a managed brain, else `importAtRevision` (maintenance transaction, page lock, `withTrustKeep`); `filesInCheckout` names the unmanaged pages whose checkout file would undo a database-only write; for those, `writeLabelFile` applies `labelEditFile` to the file's own bytes (it must still hold the page, `ownerRepairFile`), imports it under `withTrustKeep` and writes it back through `writePageThrough` (`fileText`, preimage checked) in one transaction (`private-labels` still holds them as `file_backed`).diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex d9b067e4cc..4e97f9a578 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -88,9 +88,9 @@ item: its fence row). A file that cannot take the change without beingre-rendered (a label with a block value or a duplicate key, no frontmatterblock) is refused with nothing written; make that edit by hand. `--slug` is the operator's way to make one page private;a `put_page` that adds the label is an agent edit and lowers the page. On a brain-without managed persistence, a page whose file sits in its source's checkout is-held (`file_backed`) with the file edit to make, since a database-only write-would be undone by the next sync.+without managed persistence, a page whose file sits in its source's checkout gets+the same edit in that file and in the database together, so the next sync reads+the same page.The apply touches only the listed items and resumes after its last applieditem if it stops. Apply the window (or decide not to), then preview again fordiff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 6b9e75d701..9824eb5f74 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1535,7 +1535,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.676.0', id: 'opt_in_receipt_caps_gbra108', text: 'gbrain\'s own receipt bookkeeping no longer refuses, pauses or throttles writes by default: the cumulative caps on permanent request ids and reserved receipt bytes (`persistence.limits.{principal,brain}_{lifetime_ids,terminal_bytes}`, 2,000,000 / 8,000,000 ids and 16 GiB / 64 GiB before) apply only when set, so `write_quota_exhausted`, `write_quota_insufficient`, `write_capacity_backpressure`, `write_capacity_low` and a sync\'s `capacity_paused` happen only under a cap the operator chose. Instead, while receipts not yet compacted reserve more than `persistence.housekeeping.receipt_target_bytes` (default 8 GiB, 0 off; compacted receipts never count) and the retention is the default, the compaction pass also compacts settled page writes and refused maintenance and managed sync page writes older than 7 days (job receipts, a subagent\'s own page writes, connector writes and every other refusal keep their intent until the retention window), the `/metrics` `gbrain_write_capacity_*` gauges appear only for a cap that is set, and the retention pass no longer drops a caller\'s refused write that `gbrain repair failed-writes` could still replay (it waits until a later write resolves it, or `gbrain repair receipt-compaction --include-failures` drops it), and doctor `persistence_capacity` warns the host operator. A cap already set is unchanged; `gbrain config unset` removes one. On a brain several hosts write to, this holds once every host runs this version: an older gbrain still enforces its old caps and 30-day retention, and raising a cap as its refusal suggests turns the cap on for every host.' },{ since: '0.60.676.0', id: 'write_capacity_low_saved_gst2107', text: 'The `write_capacity_low` notice a write receipt carries now opens with "This write was saved" and its fix is the read-only `gbrain doctor --only persistence_capacity --json` (actor agent) instead of a `gbrain config set` cap raise for the user, so an agent reading the end of a successful write no longer reports it as refused. The one-more-year value doctor, the notice snapshot and `/metrics` recommend now uses the 7-day mean rate, so one bulk day is no longer projected for a year; days-to-exhaustion still uses the larger of the mean and the last 24 hours. A `write_quota_exhausted`, `write_quota_insufficient` or background-pause refusal names the same value doctor does instead of sizing the year from the latest 1,000 admissions.' },{ since: '0.60.676.0', id: 'ingest_backfill_409_recovery_gst2112', text: 'A `revision_backfill_pending` refusal (a write to a page the revision backfill has not reached, including the 409 a webhook capture to such a page gets from `POST /ingest`) now names the command that resumes the backfill, `gbrain apply-migrations --force-schema` on the brain host, instead of `gbrain apply-migrations --yes`, which does not resume it once the schema is current. A capture answered 409 stores and queues nothing, so its sender sends it again after the backfill; an `ingest_capture` job already queued for such a page goes straight to dead and is re-run with `gbrain jobs retry <id>`.' },- { since: 'TBD', id: 'label_only_operator_repairs_gst2468', text: '`gbrain repair visibility` and `gbrain repair private-labels` now write a page through a label-only door: the page keeps its trust tier, files no `lower_page` proposal, and its file changes only on the label lines (other keys, their order and the body are kept). Before, `repair visibility` wrote through `put_page`, which lowered the page to agent_written and re-rendered its frontmatter. On a brain without managed persistence, a page whose file sits in its source checkout is now held (`file_backed`) with the file edit to make, as `private-labels` already did. New `gbrain repair visibility --slug <page>` makes named pages private, preview first. New read-only `gbrain trust backfill --label-lowerings` lists `lower_page` proposals as label-only or content by proposer. A plain `put_page` still lowers as an agent edit.' },+ { since: 'TBD', id: 'label_only_operator_repairs_gst2468', text: '`gbrain repair visibility` and `gbrain repair private-labels` now write a page through a label-only door: the page keeps its trust tier, files no `lower_page` proposal, and its file changes only on the label lines (other keys, their order and the body are kept). Before, `repair visibility` wrote through `put_page`, which lowered the page to agent_written and re-rendered its frontmatter. On a brain without managed persistence, `repair visibility` edits the label lines of a page\'s file in its source checkout and imports it with the tier kept (`private-labels` still holds such a page as `file_backed`). New `gbrain repair visibility --slug <page>` makes named pages private, preview first. New read-only `gbrain trust backfill --label-lowerings` lists `lower_page` proposals as label-only or content by proposer. A plain `put_page` still lowers as an agent edit.' },{ since: '0.60.678.0', id: 'unmanaged_push_history_scan_8902', text: 'Four pushes from a checkout that is not a managed worktree now scan every local commit they publish for secrets, not only what they just wrote: the access-policy commit (`gbrain access rule` and the other policy writers), the durability-scaffolding commit of `gbrain sources harden`, `gbrain sources push`, and the first push of `gbrain bootstrap repo` (the whole history, since the remote has no such branch yet). A credential that a commit made with plain `git commit` added, even one a later commit removed, or one in a commit message, now refuses `publish_secret_found` naming the file, line, rule and commit (never the value), and nothing is pushed; history the scan cannot read in full refuses `publish_scan_unreadable`. The local commits stay where they are. `gbrain sources push` now pushes the exact commit it scanned, leased on the remote tip it read, and an allowlist (`.gbrain-scan-allow`) edit it commits itself still publishes; one a script committed is left for the user to review and push. Remove the value from the unpublished commits, or allowlist a false positive by fingerprint, then rerun.' },];diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex afb6489e6e..c08e3d1af6 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -277,7 +277,7 @@ async function frontmatterDriftWrite(engine: BrainEngine, slug: string, fileText* as `content`, the file the write would otherwise render; a label line that cannot be edited as a line refuses, so the* file is never re-rendered under a label edit.*/-function labelEditFile(slug: string, before: Buffer | FileBytes, content: string, edit: LabelEdit, snapshot: PageSnapshot, activePack?: ParseOpts['activePack']): string {+export function labelEditFile(slug: string, before: Buffer | FileBytes, content: string, edit: LabelEdit, snapshot: PageSnapshot, activePack?: ParseOpts['activePack']): string {const read = (text: string, file: boolean) => {const parsed = parseMarkdown(text, slug, { activePack });return digest(canonical({ ...parsed, frontmatter: withoutSafetyAssessments(parsed.frontmatter), type: file ? importedFileType(parsed, snapshot.page, false) : parsed.type }, parsed.tags));diff --git a/src/core/repair/label-write.ts b/src/core/repair/label-write.tsindex dd9d7f7728..ac036267e1 100644--- a/src/core/repair/label-write.ts+++ b/src/core/repair/label-write.ts@@ -4,9 +4,10 @@* and its canonical file changes only in the label lines (persistence/label-edit.ts):* - a managed brain publishes it through the maintenance door with keep_trust and the label edit (the Git door on a* repo source; a repo-less managed source writes the database only);- * - a brain without managed persistence imports it in a maintenance transaction under the page lock and withTrustKeep,- * database only (the default keyless install has no file to keep). A page there whose file sits in its source's- * checkout is held by the caller (`filesInCheckout`): the next sync or re-import would undo a database-only edit.+ * - a brain without managed persistence imports it in a maintenance transaction under the page lock and withTrustKeep:+ * database only when the page has no file (the default keyless install), and for a page whose file sits in its+ * source's checkout (`filesInCheckout`) the file's own bytes with only the label lines edited, imported and written+ * back in that transaction, so the next sync reads the same page (writeLabelFile).* An ordinary put_page, local or remote, stays an agent content write (trust/channel.ts): it is never used here.*/import type { BrainEngine } from '../engine.ts';@@ -16,6 +17,7 @@ import { maintenanceTransaction } from '../persistence/attribution.ts';import { withTrustKeep } from '../persistence/context.ts';import type { LabelEdit } from '../persistence/label-edit.ts';import { managedPersistenceEnabled } from '../persistence/ownership.ts';+import { labelEditFile } from '../persistence/page-prepare.ts';import { maintenancePreflight, publishMaintenancePage, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';const bounded = { timeoutMs: 120_000 };@@ -40,25 +42,52 @@ export async function filesInCheckout(engine: BrainEngine, pageIds: number[]): P* null when the page moved. `preview` names the command whose preview lists the page again.*/export async function importAtRevision(engine: BrainEngine, page: { source_id: string; slug: string }, revision: string, content: string, embed: boolean,- preview: string): Promise<string | null> {+ preview: string, afterImport?: (tx: BrainEngine) => Promise<void>): Promise<string | null> {return maintenanceTransaction(engine, async tx => {await tx.lockPageKeys([{ sourceId: page.source_id, slug: page.slug }]);if ((await tx.readPageSnapshot(page.slug, { sourceId: page.source_id }))?.revision !== revision) return null;const result = await withTrustKeep(tx, ['pages'], () => importFromContent(tx, page.slug, content, { sourceId: page.source_id, noEmbed: !embed, preserveGateMarkers: true }));if (result.status === 'error') throw opError('invalid_params', `${page.source_id}:${page.slug} was not written: ${result.error ?? 'the import refused it'}`,`Preview ${preview} again; the page is listed with its current state.`);+ await afterImport?.(tx);return (await tx.readPageSnapshot(page.slug, { sourceId: page.source_id }))?.revision ?? null;});}+/**+ * T1: an unmanaged page whose file sits in its source's checkout. The file must still hold the page (a file holding an+ * edit the database lacks refuses); its own bytes with only the label lines edited (labelEditFile, the managed brain's+ * splice) are imported under withTrustKeep at `revision` and written back with their preimage checked, in one+ * transaction, so the file and the row agree and the tier is kept. A recorded file that is gone writes the database only.+ */+async function writeLabelFile(engine: BrainEngine, page: { source_id: string; slug: string }, write: { revision: string; content: string; edit: LabelEdit; embed: boolean; preview: string }): Promise<string | null> {+ const ref = `${page.source_id}:${page.slug}`;+ const { ownerRepairFile } = await import('../trust/page-handlers.ts');+ const file = await ownerRepairFile(engine, page.source_id, page.slug);+ if (!file.ok) throw opError('source_changed', `${ref} was not written: its file in the source's checkout cannot take the label edit (${file.reason}).`,+ `If the file holds the newer edit, run gbrain sync --source ${page.source_id}; then preview ${write.preview} again.`);+ const before = file.target?.expectedFileBytes ?? null;+ const snapshot = before === null ? null : await engine.readPageSnapshot(page.slug, { sourceId: page.source_id });+ if (before === null || !snapshot) return importAtRevision(engine, page, write.revision, write.content, write.embed, write.preview);+ if (snapshot.revision !== write.revision) return null;+ const text = labelEditFile(page.slug, Buffer.from(before, 'utf8'), write.content, write.edit, snapshot);+ const { writePageThrough } = await import('../write-through.ts');+ return importAtRevision(engine, page, write.revision, text, write.embed, write.preview, async tx => {+ const written = await writePageThrough(tx, page.slug, { sourceId: page.source_id, expectedFileBytes: before, fileText: text });+ if (!written.written) throw opError('source_changed', `${ref} was not written: its file changed or could not be written (${written.skipped ?? written.error ?? 'unknown'}).`,+ `Preview ${write.preview} again; the page is listed with its current state.`);+ });+}+/*** One label-only page write at `revision`: the maintenance door on a managed brain (`authority`, from maintenancePreflight),* the import under the page lock otherwise. The revision it wrote; null when the page moved before an unmanaged import.*/export async function writeLabelPage(ctx: OperationContext, page: { source_id: string; slug: string }, write: { revision: string; content: string; edit: LabelEdit;- requestId: string; embed: boolean; preview: string }, authority?: MaintenanceAuthority | null): Promise<string | null> {+ requestId: string; embed: boolean; preview: string; /** The page has a file in its source's checkout (filesInCheckout). */ file?: boolean },+ authority?: MaintenanceAuthority | null): Promise<string | null> {const door = authority === undefined ? await maintenancePreflight(ctx.engine, page.source_id) : authority;- if (!door) return importAtRevision(ctx.engine, page, write.revision, write.content, write.embed, write.preview);+ if (!door) return write.file ? writeLabelFile(ctx.engine, page, write) : importAtRevision(ctx.engine, page, write.revision, write.content, write.embed, write.preview);await publishMaintenancePage(ctx.engine, door, page.slug, write.content, { expectedRevision: write.revision, requestId: write.requestId, keepTrust: true, labelEdit: write.edit });return (await ctx.engine.readPageSnapshot(page.slug, { sourceId: page.source_id }))?.revision ?? null;}diff --git a/src/core/repair/visibility.ts b/src/core/repair/visibility.tsindex 16a7be1d82..1f20dc3b56 100644--- a/src/core/repair/visibility.ts+++ b/src/core/repair/visibility.ts@@ -288,17 +288,14 @@ async function applyFactItem(ctx: Parameters<RepairHandler['apply']>[0], item: R/*** GST-2468: one item's page write is a label-only maintenance write (repair/label-write.ts): it keeps the page's trust* tier, files no lower_page proposal and changes only the label lines of the page's file (a fact item: its fence row).- * Null once written; the held outcome on a brain without managed persistence whose page has a file in its source's- * checkout (the database-only write would be undone from the file), or for a page stored in segments.+ * On a brain without managed persistence a page whose file sits in its source's checkout gets the same splice in that+ * file (label-write.ts writeLabelFile). Null once written; the held outcome for a page stored in segments.*/async function labelWrite(ctx: Parameters<RepairHandler['apply']>[0], item: RepairItem, snapshot: PageSnapshot, content: string, edit: LabelEdit): Promise<RepairItemOutcome | null> {if (isSegmentedPage(snapshot.page)) return { applied: false, outcome: 'segmented_page', reason: 'The page body is stored in segments; edit it by hand on the brain host.' };- const file = (await filesInCheckout(ctx.engine, [Number(snapshot.page.id)])).get(Number(snapshot.page.id));- if (file) return { applied: false, outcome: 'file_backed', detail: { path: file },- reason: `${item.source_id}:${snapshot.page.slug} has a file in its source's checkout (${file}); on a brain without managed persistence this repair writes only the database, `- + `so the next sync or re-import would undo it from the file. Make the change in that file (${edit.set.visibility ? `add visibility: ${edit.set.visibility}` : 'its facts row visibility: private'}), commit it, then run: gbrain sync --source ${item.source_id}` };+ const file = (await filesInCheckout(ctx.engine, [Number(snapshot.page.id)])).has(Number(snapshot.page.id));await writeLabelPage(ctx, item, { revision: snapshot.revision, content, edit, requestId: await repairRequestId(ctx, 'visibility', item, snapshot.revision),- embed: true, preview: 'gbrain repair visibility' });+ embed: true, preview: 'gbrain repair visibility', file });return null;}diff --git a/src/core/write-through.ts b/src/core/write-through.tsindex 54057cb934..9401416cff 100644--- a/src/core/write-through.ts+++ b/src/core/write-through.ts@@ -126,6 +126,8 @@ export interface WritePageThroughOpts {expectedFileBytes?: string | null;/** The caller commits the file itself (#8073: one commit per batch), so the hardened per-file commit is skipped. */deferCommit?: boolean;+ /** GST-2468: the exact file to write instead of the page rendered from its row (a label-only write keeps the file's own bytes). Inline pages only. */+ fileText?: string;}export function withNoRepoWriteThroughWarning<T extends { written: boolean; skipped?: string; warning?: string }>(result: T, sourceId: string, operation = 'put_page'): T {@@ -471,11 +473,11 @@ export async function writePageThrough(}const segmented = isSegmentedPage(writtenPage);- if (segmented && opts.inlineOnly) return { written: false, skipped: 'segmented_page' };+ if (segmented && (opts.inlineOnly || opts.fileText !== undefined)) return { written: false, skipped: 'segmented_page' };if (segmented && opts.frontmatterOverrides) {return { written: false, error: `page ${slug} is stored in segments, and its file is streamed as gbrain export writes it, without frontmatter overrides` };}- const md = segmented ? null : serializePageToMarkdown(writtenPage, await engine.getTags(slug, { sourceId }), {+ const md = segmented ? null : opts.fileText ?? serializePageToMarkdown(writtenPage, await engine.getTags(slug, { sourceId }), {frontmatterOverrides: opts.frontmatterOverrides,});// A segmented body alone over the cap is refused before its segments are streamed to measure the file.diff --git a/test/label-only-repairs.test.ts b/test/label-only-repairs.test.tsindex ad6b169049..b46cc074e0 100644--- a/test/label-only-repairs.test.ts+++ b/test/label-only-repairs.test.ts@@ -179,34 +179,55 @@ for (const backend of testBackends()) describe('[' + backend + '] label-only ope/** A repo-less brain (no managed persistence, no checkout: the default keyless install) is the database record. */for (const backend of testBackends()) describe('[' + backend + '] label-only operator repairs on a repo-less brain', () => {const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;- test('repair visibility --slug keeps the tier and files no proposal; a page whose file is in a checkout is held', async () => {+ test('repair visibility --slug keeps the tier and files no proposal', async () => {const home = mkdtempSync(join(tmpdir(), 'gbrain-label-repoless-'));try {await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);try {- await engine.executeRaw("INSERT INTO sources (id, name, local_path) VALUES ('source-b', 'source-b', $1) ON CONFLICT (id) DO NOTHING", [join(home, 'checkout')]);const seed = async (sourceId: string, slug: string) => {expect((await importFromContent(engine, slug, file(slug), { noEmbed: true, sourceId })).status).toBe('imported');await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => withTrustBackfill(tx, () =>tx.executeRaw("UPDATE pages SET trust_tier='operator_curated' WHERE source_id=$1 AND slug=$2", [sourceId, slug])), TEST_WRITE_ATTRIBUTION));};await seed('default', 'notes/plain-example');- await seed('source-b', 'notes/filed-example');- await engine.executeRaw("UPDATE pages SET source_path='notes/filed-example.md' WHERE source_id='source-b'");const { applied } = await previewApply(engine, ['visibility', '--source', 'default', '--slug', 'notes/plain-example']);expect(applied.applied).toBe(1);const [row] = await engine.executeRaw<{ tier: string; visibility: string }>("SELECT trust_tier::text AS tier, frontmatter->>'visibility' AS visibility FROM pages WHERE source_id='default' AND slug='notes/plain-example'");expect(row).toEqual({ tier: 'operator_curated', visibility: 'private' });expect(await proposals(engine)).toEqual([]);- const held = await previewApply(engine, ['visibility', '--source', 'source-b', '--slug', 'notes/filed-example']);- expect(held.applied.applied).toBe(0);- expect(held.applied.outcome_items).toEqual([expect.objectContaining({ item: 'source-b:notes/filed-example', outcome: 'file_backed' })]);- expect((await engine.executeRaw<{ v: string | null }>("SELECT frontmatter->>'visibility' AS v FROM pages WHERE source_id='source-b'"))[0]!.v).toBeNull();expect((await listLabelLowerings(engine)).counts.lower_page).toBe(0);} finally { await disposePersistenceConsumer(engine); await close(); }});} finally { rmSync(home, { recursive: true, force: true }); }}, 180_000);++ test('without managed persistence, a page whose file is in a checkout gets the same label-line splice in its file', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-label-checkout-'));+ try {+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);+ try {+ const slug = 'notes/filed-example', checkout = join(home, 'checkout');+ mkdirSync(join(checkout, 'notes'), { recursive: true });+ const before = file(slug);+ writeFileSync(join(checkout, slug + '.md'), before);+ await engine.executeRaw("INSERT INTO sources (id, name, local_path) VALUES ('source-b', 'source-b', $1) ON CONFLICT (id) DO NOTHING", [checkout]);+ expect((await importFromContent(engine, slug, before, { noEmbed: true, sourceId: 'source-b' })).status).toBe('imported');+ await engine.transaction(tx => withCoordinatedWrite(tx, ['source-b'], () => withTrustBackfill(tx, () =>+ tx.executeRaw("UPDATE pages SET trust_tier='operator_curated', source_path=$2 WHERE source_id='source-b' AND slug=$1", [slug, slug + '.md'])), TEST_WRITE_ATTRIBUTION));+ const { applied } = await previewApply(engine, ['visibility', '--source', 'source-b', '--slug', slug]);+ expect(applied.applied).toBe(1);+ const [row] = await engine.executeRaw<{ tier: string; frontmatter: Record<string, unknown> }>(+ "SELECT trust_tier::text AS tier, frontmatter FROM pages WHERE source_id='source-b' AND slug=$1", [slug]);+ expect(row!.tier).toBe('operator_curated');+ expect(row!.frontmatter.visibility).toBe('private');+ expect(row!.frontmatter.source_kind).toBe('email-example');+ expect(await proposals(engine)).toEqual([]);+ expect(readFileSync(join(checkout, slug + '.md'), 'utf8')).toBe(withLine(before, 'visibility: private'));+ } finally { await disposePersistenceConsumer(engine); await close(); }+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+ }, 180_000);});