Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

sync: a legacy page's database-only grandfather stamp is no drift, an unknown-side hold no longer says the database changed, and a pending import never tells the caller to start a sync

garrytan570b75eeda35
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 6e4f7cfddb..8ea8292c74 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -55,7 +55,7 @@ of making a duplicate.
| <a id="canonical_file_missing"></a>`canonical_file_missing` | `source_changed` (a caller write; maintenance refuses before admission) | The page's recorded canonical file is gone while its database page is still live (a ghost page: the file was moved or deleted outside gbrain). A caller write refuses with "The canonical file was removed outside coordinated publication." and nothing is written; retrying it refuses the same way. A maintenance write (fact-fence adoption, enrichment, `dream`) is refused before admission: no request id, no receipt (before #6696 each cycle settled a `conflict` receipt). `gbrain sources writer failures <source>` reports such receipts as category `canonical_file_missing`. Neither copy was changed. | Decide which copy is right. If the file should exist, restore it at its recorded path and preview the page with `gbrain sources reconcile <source> <slug> --brain host --preview`, or sync. If the page should go, preview the ghost-page repair with `gbrain repair ghost-pages --source <source>` (read-only; it prints the apply command with its hash) and apply it with `--apply --expect <hash> --yes` only after the user agrees; a soft-deleted page can be restored with `gbrain restore <slug> --force` until the autopilot purge 72 h later. `gbrain pages ghosts --source <source>` and doctor `ghost_pages` list them, doctor `maintenance_write_drift` lists held-back maintenance writes. See [ghost pages](repair.md#ghost-pages). |
| <a id="refusal_breaker"></a>`refusal_breaker` | the code of the earlier refusals | The same maintenance write (same source, slug, page revision, planner and intent) was refused `persistence.maintenance.refusal_breaker_threshold` times (default 3; `0` turns it off) in the last 24 hours, so maintenance submits nothing for it instead of adding another receipt (#6696). It is tried again once the page, the planner or the write changes, or when the oldest refusal is 24 hours old. | Read the last refusal with `gbrain write-request -- <request_id>` (named in the message) and fix what it names. Doctor `maintenance_write_drift` lists every held-back write with its exit. |
| <a id="canonical_file_absent"></a>`canonical_file_absent` | `source_changed` (`restore_page` / `gbrain restore`) | On a brain without managed persistence, a restore that writes no file (`sync.write_through` off, a sandbox, a database-only source) of a soft-deleted page whose recorded file is no longer among the files sync imports (#6609). A plain restore would be undone by the next `gbrain sync --full`, so nothing was restored. Not retryable; the fix asks the user. | Ask the user. To keep the page with its file: put the file back at its recorded path, commit it and `gbrain sync --source <source>`. To keep it database-only: `gbrain restore <slug> --source-id <source> --detach` (MCP `restore_page` with `detach: true`), which forgets the recorded file and stamps `database_only_reason='detached'`. See [restoring a page whose file is gone](../storage-tiering.md#restoring-a-page-whose-file-is-gone). |
-| <a id="pending_import"></a>`pending_import` | `source_changed` (detail `file_database_drift`, reason `pending_import`) | The page's canonical file holds a change committed through Git (another agent's commit, a pull) that managed sync has not imported yet: the file on disk is exactly the blob `HEAD` holds for its path and not the one the source's last imported commit holds. The message is "The canonical file holds a committed Git change that sync has not imported yet." Nothing was overwritten. Since #6693 the receipt records origin `pending_import`; a write refused because sync holds the file records origin `sync_held` (see [held files](#held-files-and-content-refusals)). | A `remember` needs nothing from the caller: its `fix.next` is `wait`, the fact is kept in the receipt, and the first managed sync that imports the file (any outcome, a partial run included) makes one replay attempt on the original caller's lane with the fact's original `valid_from` and expiry (the sync result's `replayedRemembers` counts examined, replayed, waiting, skipped, remaining; at most 50 per run and 30 s). Do not save the fact again. A remember refused while sync held its file is replayed the same way once the repaired file is imported. A replay that is refused (authority revoked, page rewritten) stays listed by `gbrain repair failed-writes --source <source>` for a person. Any other write (`put_page`, `add_timeline_entry`) is never replayed automatically, because its body would replace the imported change: run `gbrain sync --source <source> --no-pull` on the brain host (the refusal's fix), read the page again and resubmit with a new request ID. An uncommitted hand edit still refuses `file_database_drift` and needs reconcile. |
+| <a id="pending_import"></a>`pending_import` | `source_changed` (detail `file_database_drift`, reason `pending_import`) | The page's canonical file holds a change committed through Git (another agent's commit, a pull) that managed sync has not imported yet: the file on disk is exactly the blob `HEAD` holds for its path and not the one the source's last imported commit holds. The message is "The canonical file holds a committed Git change that sync has not imported yet." Nothing was overwritten. Since #6693 the receipt records origin `pending_import`; a write refused because sync holds the file records origin `sync_held` (see [held files](#held-files-and-content-refusals)). | A `remember` needs nothing from the caller: its `fix.next` is `wait`, the fact is kept in the receipt, and the first managed sync that imports the file (any outcome, a partial run included) makes one replay attempt on the original caller's lane with the fact's original `valid_from` and expiry (the sync result's `replayedRemembers` counts examined, replayed, waiting, skipped, remaining; at most 50 per run and 30 s). Do not save the fact again. A remember refused while sync held its file is replayed the same way once the repaired file is imported. A replay that is refused (authority revoked, page rewritten) stays listed by `gbrain repair failed-writes --source <source>` for a person. Any other write (`put_page`, `add_timeline_entry`) is never replayed automatically, because its body would replace the imported change: wait for the source's running sync owner (`gbrain serve`, autopilot or a sync job) to import the commit, which the refusal's read-only fix `gbrain sync status --source <source> --json` shows, then read the page again and resubmit with a new request ID. Neither refusal tells the caller to start a sync, because a second sync beside a running owner competes with it; when status shows no owner running, ask the user to sync the source on its host. An uncommitted hand edit still refuses `file_database_drift` and needs reconcile. |
| <a id="shared_origin"></a>`shared_origin` | `source_changed` (purge, or a delete whose survivor changed); a soft delete commits with `write_through.skipped: shared_origin` | Two live pages of one source recorded the same canonical file (a duplicate-origin twin: the shared file renders one of them, so a delete of either used to refuse `file_database_drift`, reconcile refused "Several pages claim the recorded canonical file" and every managed sync refused `page_identity_changed`). A soft delete (`gbrain delete <slug> --source-id <id> --expected-revision <rev>`) of a page whose file another live page records now keeps the file and publishes database-only: the selected database page is hidden; the file and the surviving page remain. This does not erase that file's contents. The receipt's `write_through.warning` says so and names the surviving slug to the trusted local owner, or to a remote writer whose grant and visibility cover that slug; other remote writers read a generic "another page of this source records the same file". Sync's census and both origin guards apply one rule: a live page wins over tombstones, several live pages refuse, a single tombstone may be reused, several tombstones stay ambiguous. An owner purge (`--purge`) of a shared-origin page refuses with this reason: a purge tombstones the content source-wide and a same-content survivor would refuse `purged_content` on its next import. The 72 h retention purge (the autopilot purge phase, `gbrain pages purge-deleted --older-than 72h --yes`) of such a page once it is soft-deleted writes no tombstone, so it removes the page row, its chunks, links and facts database-only and leaves the file and the surviving page untouched (#7311); a census that changed under it defers to the next run, which re-reads the claimants and, when the tombstone now owns the file alone, purges it normally, file included. A delete whose surviving claimant changed between preparation and publication (the file moved or removed, a survivor deleted or re-pointed) refuses and never removes the file as a fallback. | Delete the page that should not own the file; the kept file still holds whatever text it had, so edit it first if it holds the deleted page's text, then import its current content into the surviving page with `gbrain repair file-drift --source <id> --slug <surviving-slug> --prefer file` (preview, then the apply command it prints) and `gbrain sync --source <id> --no-pull`. Sync does not overwrite a surviving page that differs from the file: it holds it [`file_drift`](#file_drift), whose fix leads with the same command. For a purge of a live page, soft-delete it instead; a soft-deleted one is removed by the retention purge (a tombstone an older release parked after its refusals is retried once by the first purge run after the upgrade). After a `source_changed` on a changed survivor, submit the delete again with a new `request_id`; it re-reads the file's claimants. |
| <a id="writer-coordinator-required"></a>`database_guard` or `database_trigger` | `writer_coordinator_required` (or `storage_error` for another trigger) | A database trigger refused a row while a write was being prepared or published, so nothing was committed and any canonical file already replaced was restored. With `database_guard`, a gbrain process wrote a row its publication does not own (another source, an unresolvable source, or a source checkpoint/topology change outside owner administration). This is a gbrain defect or a version mismatch between gbrain processes sharing the database, not a content conflict. The receipt's `write_error_detail` names the table, operation, guard branch, source relationship and stage; it never contains page text or source names. For another trigger it also carries a closed `reason`: `attribution_unclassified_table` or `trust_unclassified_table` (a gbrain stamp trigger met a table it is not built for: a version mismatch), `graduation_in_progress` (the engine-graduation fence, SQLSTATE 55000, refuses writes until the move finishes: retry later), or `unknown` (an operator trigger gbrain does not know; its message text stays on the brain host). The same `reason`, raiser and table appear on the managed sync failure (`gbrain doctor`, the failure ledger) and in `gbrain sync status --json` `last_error.write_error_detail`. | On the brain host run `gbrain sources writer status --probe --json`. Its `recent_failures[].error_detail` adds the source ids and the gbrain build and host that ran the attempt (`attempt.consumer_version`). If that build differs from `gbrain --version`, upgrade or restart every gbrain process that shares the database (serve, autopilot, sync jobs), then retry with a **new** request ID. If the builds match, report `error_detail` on the gbrain issue tracker. Never force-write, edit SQL or disable the guard. |
| `ambiguous_source_path` | `page_identity_changed` | A source registered at a Git subfolder `<sub>` has a page whose stored path `<sub>/<file>` could mean either `<file>` in the source directory (the older Git-root spelling) or `<sub>/<file>` inside a folder of the source that repeats its name, and both files exist. Sync refuses instead of guessing. See [sources in a Git subfolder](multi-source-brains.md#sources-in-a-git-subfolder). | Rename or move one of the two files, commit, then `gbrain sync --source <source> --no-pull`. |
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index d242d15751..a4a3de3f69 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1190,6 +1190,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.411.0', text: '`gbrain doctor` no longer counts a check that did not finish within the run\'s budget as a warning in `health_score` or the category scores. The report counts those checks in `unknown_count`, a category with no finished check is listed in `unknown_scores` instead of scoring 100, and the status stays at warnings, never healthy. `derived_visibility` now runs as its own check right after the cheap incident checks, so it no longer waits on the wave checks\' budget.' },
// #7236 (GBRA-151). `since` is stamped at the merge slot.
{ since: '0.60.414.0', text: 'An autopilot tick reads the brain health aggregate once (it used to read it twice), and on Postgres the read is bounded at 120 s. A read that runs out reports `health_degraded` (an NDJSON event under `--json`) and the tick runs with an unknown score: no healthy sleep, no score-forced full cycle before the hourly floor, the base interval, and `brain_score: null`. The timeout is not counted as a failed cycle.' },
+ // Side-unknown file_drift holds and the pending-import fix (GBRA-133). `since` is stamped at the merge slot.
+ { since: 'TBD', id: 'legacy_validate_stamp_drift', text: 'A page an older gbrain imported, whose database copy carries the v0.13.1 grandfather stamp `validate: false` that its file lacks, is no longer held `file_drift` when its file is committed again: sync compares and imports such a file the way a page write already did (#6429), so the first sync records the page and a later commit imports, and the page keeps the stamp. A `file_drift` hold that has no import record now says it cannot tell whether the file or the database changed, instead of saying the page changed in the database. Holds already open are re-screened as before (`gbrain sources retry-held <source>`).' },
+ { since: 'TBD', id: 'pending_import_owner_safe_fix', text: 'A write refused because its page\'s file holds a committed Git change sync has not imported yet (`pending_import`) no longer tells the caller to run `gbrain sync --source <source> --no-pull`. A running sync owner (`gbrain serve`, autopilot or a sync job) imports the commit on its own, and a second sync beside it competes with that owner. The fix of every such refusal, `put_page` included, is now the read-only `gbrain sync status --source <source> --json`, and the frozen `remember` refusal carries that fix too.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index 912936752a..7ec0ce81fa 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -11,7 +11,7 @@ import { readFileSync, statSync, lstatSync } from 'fs';
import { basename, extname, resolve } from 'path';
import { createHash } from 'crypto';
import type { BrainEngine, FileSpec } from './engine.ts';
-import { classifyImportHold, parseMarkdown, resolveParsedSubtype, type ParseOpts, type ParsedMarkdown } from './markdown.ts';
+import { classifyImportHold, keepGrandfatherStamp, parseMarkdown, resolveParsedSubtype, type ParseOpts, type ParsedMarkdown } from './markdown.ts';
import { CODE_FILE_MAX_BYTES, isLargePageBytes } from './page-size-policy.ts';
import { importSizeLimit, MAX_FILE_SIZE, screenImportContent, settleContentDisposition, stripGateOwnedMarkers, type ContentRefusal, type FenceScreen } from './import-screen.ts';
import type { WriteGateAssessment, WriteGateInput } from './write-gate.ts';
@@ -482,6 +482,7 @@ export async function importFromContent(
parsed.type = existing.type;
}
resolveParsedSubtype(parsed, existing);
+ keepGrandfatherStamp(parsed.frontmatter, existing);
// Alias-footgun visibility: an explicit frontmatter `type:` that is an
// ALIAS of a canonical pack type (or entirely undeclared) is stored
// literally and never re-normalized — different agents can silently file
diff --git a/src/core/markdown.ts b/src/core/markdown.ts
index e5588d99b0..4a5a916e17 100644
--- a/src/core/markdown.ts
+++ b/src/core/markdown.ts
@@ -501,6 +501,16 @@ export function resolveParsedSubtype(
if (parsed.inferredSubtype?.type === parsed.type) parsed.frontmatter.subtype = parsed.inferredSubtype.name;
}
+/**
+ * #6429: the v0.13.1 grandfather stamped `validate: false` into the database; on an unmanaged brain that path never wrote
+ * the file, so the file lacks a key the database carries. The mechanical stamp authors nothing (grandfather.ts): a file
+ * without a `validate:` key keeps the stored stamp. GBRA-133: import and sync compare and store it the same way as the
+ * write guard, so a legacy page carrying the stamp is not a database edit sync cannot place.
+ */
+export function keepGrandfatherStamp(frontmatter: Record<string, unknown>, existing?: { frontmatter?: Record<string, unknown> | null } | null): void {
+ if (!Object.hasOwn(frontmatter, 'validate') && existing?.frontmatter?.validate === false) frontmatter.validate = false;
+}
+
/**
* #5988 hold codes: deterministic content refusals. Ingestion holds the one
* file and keeps going instead of failing the whole sync. Defined once here;
diff --git a/src/core/persistence/align-stored.ts b/src/core/persistence/align-stored.ts
index 160594a206..728e4c5eb8 100644
--- a/src/core/persistence/align-stored.ts
+++ b/src/core/persistence/align-stored.ts
@@ -1,12 +1,13 @@
-import { resolveParsedSubtype, type ParsedMarkdown } from '../markdown.ts';
+import { keepGrandfatherStamp, resolveParsedSubtype, type ParsedMarkdown } from '../markdown.ts';
/**
* Aligns a canonical file's parse with what its import over `stored` keeps (#1035, #5521): a file without an explicit
* `type:` (or whose type was only inferred from its path, #6605) keeps the stored type, and the subtype is resolved
- * against that type, so the stored subtype is kept too. Import does the same, in this order. The write guard
+ * against that type, so the stored subtype is kept too, and so is the grandfather stamp (#6429). Import does the same, in this order. The write guard
* (page-prepare.ts) and reconcile (reconcile-state.ts, reconcile-prepare.ts) share it.
*/
export function alignWithStored(parsed: ParsedMarkdown, stored: { type: string; frontmatter?: Record<string, unknown> | null }, inferred: boolean): void {
if (inferred || !parsed.typeExplicit) parsed.type = stored.type as ParsedMarkdown['type'];
resolveParsedSubtype(parsed, stored);
+ keepGrandfatherStamp(parsed.frontmatter, stored);
}
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 1ce68175e1..2403634ed6 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -205,10 +205,6 @@ function importedFileType(parsed: ParsedMarkdown, page: Pick<Page, 'type' | 'fro
// without an explicit `subtype:` keeps the stored subtype (or none); the import still stamps it.
delete parsed.inferredSubtype;
alignWithStored(parsed, page, inferred);
- // #6429: the v0.13.1 grandfather stamped `validate: false` into the database; on an unmanaged brain that path
- // never wrote the file, so the file lacks a key the database carries. The mechanical stamp authors nothing
- // (grandfather.ts): a file without a `validate:` key keeps the stored stamp, and the next coordinated write publishes it.
- if (!Object.hasOwn(parsed.frontmatter, 'validate') && page.frontmatter?.validate === false) parsed.frontmatter.validate = false;
return parsed.type;
}
/** The withdrawal ledger readPageSnapshot overlaid the snapshot's body with, for a segmented body read under it. */
diff --git a/src/core/persistence/pending-import.ts b/src/core/persistence/pending-import.ts
index 36c5da8742..be4e5100ce 100644
--- a/src/core/persistence/pending-import.ts
+++ b/src/core/persistence/pending-import.ts
@@ -22,7 +22,7 @@ import type { BrainEngine } from '../engine.ts';
import type { Action } from '../agent-output.ts';
import { gitChildEnv } from '../git-env.ts';
import { opError, type OperationError } from '../ops/contract.ts';
-import { PENDING_IMPORT_MESSAGE } from './verb-errors.ts';
+import { PENDING_IMPORT_MESSAGE, PENDING_IMPORT_OWNER } from './verb-errors.ts';
export const PENDING_IMPORT = 'pending_import';
/** #6693: the receipt origin of a write refused because sync holds the page's file (heldFileRefusal). */
@@ -92,7 +92,10 @@ export async function committedPendingImport(engine: BrainEngine, sourceId: stri
}
}
-/** The refusal: nothing was overwritten; a remember waits for its replay, any other write is resubmitted after the next sync. */
+/**
+ * The refusal: nothing was overwritten; a remember waits for its replay, any other write is resubmitted after the next sync.
+ * GBRA-133: neither fix starts a sync; both read the status, so no caller puts a second sync owner beside a running one.
+ */
export function pendingImportRefusal(row: { source_id: string; slug: string; operation?: string }, remote: boolean): OperationError {
const status = ['gbrain', 'sync', 'status', '--source', row.source_id, '--json'];
const remember = row.operation === 'remember';
@@ -100,9 +103,9 @@ export function pendingImportRefusal(row: { source_id: string; slug: string; ope
? { argv: status, consent: [], actor: 'provider', requires_exclusive: false, verify: { argv: status }, docs: 'docs/guides/write-refusals.md#pending_import',
why: `The fact is kept in this request's receipt and queued for one automatic replay attempt by the first managed sync that imports the file; do not save it again. `
+ `This read-only status shows when the source has synced; until the replay commits, gbrain repair failed-writes --source ${row.source_id} lists the fact (a replay that is refused stays there for a person to replay).` }
- : { argv: ['gbrain', 'sync', '--source', row.source_id, '--no-pull', '--json'], consent: [], actor: remote ? 'host_admin' : 'agent', requires_exclusive: false,
+ : { argv: status, consent: [], actor: remote ? 'host_admin' : 'agent', requires_exclusive: false,
verify: { argv: status }, docs: 'docs/guides/write-refusals.md#pending_import',
- why: 'Imports the committed change on the brain host; then read the page again and resubmit the intended write with a new request_id.' };
+ why: `${PENDING_IMPORT_OWNER.replace('<source>', row.source_id)} Once it has, read the page again and resubmit the intended write with a new request_id.` };
return opError('source_changed', PENDING_IMPORT_MESSAGE,
`Nothing was overwritten. The canonical file of ${row.slug} in source ${row.source_id} holds a change committed through Git that managed sync has not imported yet, `
+ (remember ? 'so this remember was refused and kept: the first sync that imports the file makes one replay attempt, with its original date and authority.'
diff --git a/src/core/persistence/sync-fault-class.ts b/src/core/persistence/sync-fault-class.ts
index 21d87ece8a..edc14df62c 100644
--- a/src/core/persistence/sync-fault-class.ts
+++ b/src/core/persistence/sync-fault-class.ts
@@ -57,8 +57,8 @@ export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [
escalate: `${ESCALATE_AFTER} with no edit in the last ${HOLD_ESCALATE_MS / 3_600_000} h: the uncommitted edit is abandoned`, human_reason: 'An uncommitted edit of the file has sat in the checkout for a day without being committed; find out who made it and commit or restore it.' },
{ code: 'concurrent_write', class: 'page', safe_actions: ['reconcile'], needs_human: true, escalate: 'always: the file and the database page diverge',
human_reason: 'The Git file and the database page both changed; a person chooses which version wins (gbrain sources reconcile <source> <slug> --preview shows both and writes nothing).' },
- { code: 'file_drift', class: 'page', safe_actions: ['reconcile'], needs_human: true, escalate: 'always: the page changed in the database since its file was last imported',
- human_reason: 'The database page moved since sync last imported its file, and importing would replace it; a person chooses which version wins (gbrain repair file-drift --source <source> --slug <slug> --prefer database|file previews it and writes nothing until applied).' },
+ { code: 'file_drift', class: 'page', safe_actions: ['reconcile'], needs_human: true, escalate: 'always: importing the file would replace a database version of the page that sync cannot trace to an import of it',
+ human_reason: 'Importing the file would replace a database version of the page that sync cannot trace to an import of the file; a person chooses which version wins (gbrain repair file-drift --source <source> --slug <slug> --prefer database|file previews it and writes nothing until applied).' },
{ code: 'preparation_stalled', class: 'page', safe_actions: ['retry', 'upgrade'], needs_human: false,
escalate: `${ESCALATE_AFTER}, or writer status names a step that never finishes`, human_reason: 'The write owner cannot finish preparing this file; writer status names the step, fix or report it.' },
// Flip lane C: the database ended the write's statements (SQLSTATE 57014) persistence.max_preparation_attempts times; like
diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.ts
index 2a59c219aa..40bc34820d 100644
--- a/src/core/persistence/sync-holds.ts
+++ b/src/core/persistence/sync-holds.ts
@@ -774,8 +774,11 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'c
: `page ${slug} changed in the database${record.meta.page_revision ? ` (revision ${record.meta.page_revision})` : ''}`;
const preview = (prefer: 'database' | 'file') => ['gbrain', 'repair', 'file-drift', '--source', source, '--slug', slug, '--prefer', prefer];
const verify = { argv: ['gbrain', 'sources', 'status', source, '--json'] };
- const held = `${by} since ${record.path} was last imported, so sync held the file instead of overwriting the database version (${record.meta.sides === 'database' && !record.meta.side ? 'the file did not change in Git'
- : fileDriftSide(record.meta) === 'both' ? 'the file changed too' : 'no import record says which side changed'}). `;
+ const side = fileDriftSide(record.meta);
+ const held = side === 'unknown' && !record.meta.competing_request_id
+ ? `Page ${slug} differs from ${record.path} and has no import record to tell whether the file or the database changed, so sync held the file instead of overwriting the database version. `
+ : `${by} since ${record.path} was last imported, so sync held the file instead of overwriting the database version (${record.meta.sides === 'database' && !record.meta.side ? 'the file did not change in Git'
+ : side === 'both' ? 'the file changed too' : 'no import record says whether the file changed too'}). `;
const decide = 'Decide with the user which version wins, run the apply command the preview prints, then sync again. The rest of the source is not blocked.';
// #6517: a shared-origin delete kept the file for this surviving page, and its receipt names importing the file.
const shared = record.meta.shared_origin === true;
diff --git a/src/core/persistence/sync-page-fault.ts b/src/core/persistence/sync-page-fault.ts
index e0664cb733..6fbd5ecd14 100644
--- a/src/core/persistence/sync-page-fault.ts
+++ b/src/core/persistence/sync-page-fault.ts
@@ -147,10 +147,13 @@ function base(entry: HoldEntry, slug: string, pageId: number | null, code: 'conc
export function fileDriftHold(entry: HoldEntry, slug: string, pageId: number | null, intent: Pick<SyncIntent, 'content' | 'blobOid'>,
observed: { sides: 'database' | 'both' | 'unknown'; revision: string | null; proof: PageChangeProof | null; sharedOrigin: boolean }): HeldEntry {
const by = observed.proof ? `${observed.proof.operation} request ${observed.proof.request_id} wrote page ${slug} straight to the database` : `page ${slug} changed in the database`;
- const file = observed.sides === 'database' ? 'its file did not change in Git' : observed.sides === 'both' ? 'its file changed too'
- : 'there is no import record to tell which side changed';
+ const file = observed.sides === 'database' ? 'its file did not change in Git' : 'its file changed too';
+ // GBRA-133: with no import record and no database write on record, nothing shows the database side changed.
+ const held = observed.sides === 'unknown' && !observed.proof
+ ? `page ${slug} differs from its file and has no import record to tell whether the file or the database changed`
+ : `${by} since the file was last imported and ${observed.sides === 'unknown' ? 'there is no import record to tell whether the file changed too' : file}`;
return base(entry, slug, pageId, 'file_drift',
- `${entry.path}: ${by} since the file was last imported and ${file}, so sync held the import instead of overwriting the database version; the rest of the source synced.`,
+ `${entry.path}: ${held}, so sync held the import instead of overwriting the database version; the rest of the source synced.`,
intent.content ?? null, intent.blobOid, { sides: observed.sides, ...(observed.sides !== 'database' ? { side: observed.sides } : {}), ...(observed.revision ? { page_revision: observed.revision } : {}),
...(observed.proof ? { competing_request_id: observed.proof.request_id, competing_operation: observed.proof.operation } : {}),
...(observed.sharedOrigin ? { shared_origin: true as const } : {}) });
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index 68c5ae768d..f95f7a4b07 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -15,7 +15,7 @@ import { matchTrustAllowRule, type TrustAllowRule } from '../trust/allow-rules.t
import { importFromContent, importCodeFile, verifyPageReadable } from '../import-file.ts';
import { screenImportContent, screenNormalized, type ContentRefusal, type ImportScreenResult, type ImportSanityConfig } from '../import-screen.ts';
import { ContentSanityBlockError } from '../content-sanity.ts';
-import { parseMarkdown, resolveParsedSubtype, serializePageToMarkdown, type ParseOpts } from '../markdown.ts';
+import { keepGrandfatherStamp, parseMarkdown, resolveParsedSubtype, serializePageToMarkdown, type ParseOpts } from '../markdown.ts';
import { resolveSlugForPath, slugifyPath, isCodeFilePath, isImageFilePath } from '../sync.ts';
import { prepareManagedSyncImage } from './sync-image.ts';
import { SOURCE_CONFIG_OBJECT_SQL } from '../source-config-sql.ts';
@@ -875,6 +875,7 @@ async function prepareSyncMutation(unbounded: BrainEngine, row: WriteRequest, _c
}
const parsed = parseMarkdown(p.content, `${row.slug}.md`, { activePack });
resolveParsedSubtype(parsed, base?.page);
+ keepGrandfatherStamp(parsed.frontmatter, base?.page);
const tags = [...new Set([...(base?.tags ?? []), ...ready.parsedPage.tags])].sort();
const renderedPage = { ...(base ? withoutBody(base.page) : { id: 0, source_id: row.source_id, created_at: new Date(), updated_at: new Date() }), ...ready.parsedPage } as Page;
if (renamed && parsedInput.typeExplicit !== true) renderedPage.type = parsedInput.type;
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 8e30b5fec3..a51707caa8 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -463,7 +463,7 @@ async function freezeEntryOnce(engine: BrainEngine, cursor: Cursor, key: string,
// #6712 PR 1: an import whose page moved since its file was last imported runs only as a proven no-op (sync-prescreen.ts).
if (entry.drift && !occupantRebound && content !== null && snapshot && !(image ? sameImageBytes(imageBytes, snapshot.page)
: await sameContentAtOrigin(engine, cursor, entry, key, snapshot, content, rawHash, lineEndingOnly, run.signal) || await sameContentAtOrigin(engine, cursor, entry, key, snapshot, driftBaselineContent(cursor.gitRoot, entry), null, false, run.signal, true))) {
- if (!holdsOn) throw syncRunRefusal('file_drift', 'An import would overwrite a database version of the page that sync never saw.', retry, `Page ${slug} in source ${cursor.sourceId} changed in the database since ${entry.path} was last imported, and the file differs from it, so the run stopped before admitting it (sync.holds=fail).`);
+ if (!holdsOn) throw syncRunRefusal('file_drift', 'An import would overwrite a database version of the page that sync never saw.', retry, `Page ${slug} in source ${cursor.sourceId} ${entry.drift === 'unknown' ? `differs from ${entry.path} and has no import record to tell whether the file or the database changed` : `changed in the database since ${entry.path} was last imported, and the file differs from it`}, so the run stopped before admitting it (sync.holds=fail).`);
const proof = await pageChangeProof(engine, { sourceId: cursor.sourceId, incarnation: cursor.incarnation, pageId, expectedRevision: null }); assertActive();
return { hold: fileDriftHold(entry, slug, pageId, frozenIntent, { sides: entry.drift, revision: snapshot.revision, proof, sharedOrigin: await sharedOriginSurvivor(engine, cursor.sourceId, entry.sourcePath) }) };
}
diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.ts
index 4ae6135a67..9e3bfb1597 100644
--- a/src/core/persistence/verb-errors.ts
+++ b/src/core/persistence/verb-errors.ts
@@ -25,6 +25,13 @@ const HELD_FILE = /^(?:The canonical file is held by sync|A file held by sync) \
/** #6858: the receipt prefix of a write `gbrain repair stuck-recovery --keep disk` abandoned: its canonical file was kept as edited on disk. */
export const KEEP_DISK_ABANDONED_PREFIX = 'Publication abandoned by gbrain repair stuck-recovery --keep disk';
export const PENDING_IMPORT_MESSAGE = 'The canonical file holds a committed Git change that sync has not imported yet.';
+/**
+ * GBRA-133: who imports a pending commit. Every pending-import refusal says this instead of naming a sync to run: an agent
+ * that started one beside a live serve put a second sync owner on the source.
+ */
+export const PENDING_IMPORT_OWNER = 'Do not start a sync for it: the source\'s running sync owner (gbrain serve, autopilot or a sync job) imports the commit on its next pass, '
+ + 'and a second sync beside it competes with that owner. Read-only: gbrain sync status --source <source> --json shows when the source has imported it; '
+ + 'if it shows no owner running, ask the user to sync the source on its host.';
/** #7364: `row` names the hold row the refusal read (its source and incarnation, still location-free), so a refusal naming a row that `sources retry-held` does not list shows which. */
export function heldFileMessage(kind: 'drift' | 'occupied', code: string, row?: { sourceId: string; incarnation: string }): string {
@@ -63,7 +70,8 @@ export function writeFailureDiagnostic(code: string, message?: string | null): {
};
if (message === PENDING_IMPORT_MESSAGE) return {
reason: 'pending_import', message: 'A committed Git change to the page\'s file has not been imported yet; neither copy was overwritten.',
- suggestion: 'A refused remember is replayed once by the first managed sync that imports the file; do not save it again. Any other write: after the next gbrain sync --source <source> --no-pull, read the page again and resubmit with a new request_id.',
+ suggestion: `A refused remember is kept and replayed once by the first managed sync that imports the file; do not save it again. ${PENDING_IMPORT_OWNER}`
+ + ' Any other write: once that import shows, read the page again and resubmit with a new request_id.',
};
if (['Newer working-tree bytes and the current page disagree with this pinned Git import.',
'Newer code file bytes disagree with the pinned import.', 'Canonical sanitization cannot overwrite newer working-tree bytes.'].includes(message ?? '')) return {
@@ -203,6 +211,8 @@ export async function runMemoryWrite<T>(run: () => Promise<T>): Promise<T> {
// #6188: the frozen v1 code stays; the fence refusal's reason, location and issues ride along additively.
if (error.canonicalCode === 'invalid_fence') Object.assign(frozen, { reason: error.reason, fence: error.fence, fenceIssues: error.fenceIssues });
if (error.withdrawn) frozen.withdrawn = error.withdrawn;
+ // GBRA-133: a pending import keeps its read-only status fix (a remember's renders `next: wait`), additively.
+ if (frozen.detail === 'pending_import' && error.fix) Object.assign(frozen, { docs: error.docs, fix: error.fix });
throw frozen;
}
// #5575: the frozen wire code stays invalid_params; the envelope's canonical code is purged_content.
diff --git a/test/remember-pending-import.test.ts b/test/remember-pending-import.test.ts
index b87ca7f779..5eafda0748 100644
--- a/test/remember-pending-import.test.ts
+++ b/test/remember-pending-import.test.ts
@@ -14,6 +14,10 @@ import { parseFactsFence } from '../src/core/facts-fence.ts';
import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
import { submitRememberMutation } from '../src/core/persistence/memory-mutations.ts';
import { lostCallerWrites, replayImportedRemembers } from '../src/core/repair/failed-writes.ts';
+import { pendingImportRefusal } from '../src/core/persistence/pending-import.ts';
+import { readDrainHolder, withDrainLease } from '../src/core/persistence/sync-lease.ts';
+import { PENDING_IMPORT_MESSAGE, runMemoryWrite, writeFailureDiagnostic } from '../src/core/persistence/verb-errors.ts';
+import type { SyncResult } from '../src/commands/sync.ts';
import { managedBrain } from './helpers/managed-brain.ts';
import { durableGitRepo, git } from './helpers/git-publication.ts';
@@ -121,10 +125,36 @@ describe('#6693 remember onto a page whose file awaits import', () => {
const error = await refused(() => submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(), expected_revision: revision,
content: '---\ntype: person\ntitle: Owner\n---\n\nReplaced body.\n' } }));
expect(error.reason).toBe('pending_import');
- expect(error.fix?.argv).toEqual(['gbrain', 'sync', '--source', 'default', '--no-pull', '--json']);
+ expect(error.fix?.argv).toEqual(['gbrain', 'sync', 'status', '--source', 'default', '--json']);
expect((await lastReceipt(engine, 'put_page')).error_detail?.origin).toBe('pending_import');
expect((await sync(engine, root)).replayedRemembers).toBeUndefined();
expect(readFileSync(file(root), 'utf8')).toContain('Committed by another agent.');
expect(readFileSync(file(root), 'utf8')).not.toContain('Replaced body.');
}, { setup }), 120_000);
+ // GBRA-133: an agent followed a refusal that named `gbrain sync --source <source> --no-pull` while serve was running and put a
+ // second sync owner beside it. With a serve holding the source's drain lease, no pending-import surface names a sync to start.
+ test('while a serve owns the source, no pending-import refusal tells the caller to start a sync', () => managedBrain(async ({ engine, ctx, root }) => {
+ await seed(ctx);
+ edit(root, 'The cron writer committed this line.');
+ git(root, 'add', '--', `${slug}.md`); git(root, 'commit', '-q', '-m', 'cron writer commit');
+ const revision = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!.revision;
+ const startsSync = (surface: unknown) => JSON.stringify(surface).match(/gbrain sync(?! status)\b|"gbrain","sync","(?!status")/g) ?? [];
+ const view = (error: unknown) => { const e = error as { message?: string; suggestion?: string; why?: string; fix?: unknown; reason?: string; detail?: string };
+ return { message: e.message, suggestion: e.suggestion, why: e.why, fix: e.fix }; };
+ await withDrainLease(engine, 'default', { holder: { kind: 'serve', id: 'serve-example' } }, async () => {
+ expect((await readDrainHolder(engine, 'default'))?.kind).toBe('serve');
+ const remember = { fact: 'Owner prefers written updates', entity: slug, provenance: 'test', visibility: 'world' as const };
+ const cli = await refused(() => runMemoryWrite(() => submitRememberMutation(ctx, remember))) as { detail?: string; fix?: { argv?: string[] } };
+ expect(cli.detail).toBe('pending_import');
+ expect(cli.fix?.argv).toEqual(['gbrain', 'sync', 'status', '--source', 'default', '--json']);
+ const direct = await refused(() => submitRememberMutation(ctx, remember));
+ const put = await refused(() => submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(), expected_revision: revision,
+ content: '---\ntype: person\ntitle: Owner\n---\n\nReplaced body.\n' } }));
+ expect([direct.reason, put.reason]).toEqual(['pending_import', 'pending_import']);
+ const surfaces = [view(cli), view(direct), view(put), writeFailureDiagnostic('source_changed', PENDING_IMPORT_MESSAGE),
+ ...[false, true].flatMap(remote => ['remember', 'put_page'].map(operation => view(pendingImportRefusal({ source_id: 'default', slug, operation }, remote))))];
+ for (const surface of surfaces) expect(startsSync(surface)).toEqual([]);
+ return {} as SyncResult;
+ });
+ }, { setup }), 120_000);
});
diff --git a/test/sync-legacy-validate-stamp-gbra133.test.ts b/test/sync-legacy-validate-stamp-gbra133.test.ts
new file mode 100644
index 0000000000..203ae6df26
--- /dev/null
+++ b/test/sync-legacy-validate-stamp-gbra133.test.ts
@@ -0,0 +1,76 @@
+/**
+ * GBRA-133: a legacy page (imported by an older gbrain, so it has no import record) whose database copy carries the
+ * v0.13.1 grandfather stamp `validate: false` that its file never had. The stamp is mechanical (grandfather.ts) and a
+ * coordinated write keeps it for a file without a `validate:` key (#6429, page-prepare.ts). Before the fix sync's import
+ * comparison did not: the legacy sweep could not record the page, and the next commit to its file was held file_drift of
+ * unknown side, although only the file had changed.
+ *
+ * Protects: the sweep records such a page; a later commit to its file imports instead of holding, and the page keeps the
+ * stamp; a page whose database copy really differs (a body edit) is still held.
+ */
+import { describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { drainProjections } from '../src/core/page-state/projections.ts';
+import { readGitHold, SYNC_IMPORT_PROVENANCE_OP } from '../src/core/persistence/sync-holds.ts';
+import { MANAGED_SYNC_PASS_OP } from '../src/core/persistence/sync-pass-row.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const commit = (root: string, message: string) => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); };
+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };
+const NAMES = ['stamped', 'edited', 'plain'];
+const setup = ({ root }: { root: string }) => {
+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');
+ for (const name of NAMES) writeFileSync(join(root, `notes/${name}.md`), `---\ntype: concept\ntitle: notes/${name}\n---\n\nThe committed body of notes/${name}.\n`);
+ commit(root, 'notes');
+};
+
+/** The synced pages as an older gbrain left them: no import record and no pass row; the grandfather stamp as v0.13.1's UPDATE wrote it. */
+async function legacyPages(engine: BrainEngine, stamped: string[], dbEdited: string[]): Promise<void> {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ try {
+ const cols = 'source_id, slug, type, title, compiled_truth, timeline, frontmatter, content_hash, source_path';
+ const rows = await engine.executeRaw<Record<string, unknown>>(`SELECT ${cols} FROM pages WHERE source_id='default'`);
+ await engine.executeRaw("DELETE FROM pages WHERE source_id='default'");
+ for (const row of rows) await engine.executeRaw(`INSERT INTO pages(${cols}) VALUES($1,$2,$3,$4,$5,$6,$7::jsonb,$8,$9)`,
+ [row.source_id, row.slug, row.type, row.title, row.compiled_truth, row.timeline, JSON.stringify(row.frontmatter), row.content_hash, row.source_path]);
+ for (const slug of stamped) await engine.executeRaw("UPDATE pages SET frontmatter = jsonb_set(COALESCE(frontmatter, '{}'::jsonb), '{validate}', 'false'::jsonb) WHERE source_id='default' AND slug=$1", [slug]);
+ for (const slug of dbEdited) await engine.executeRaw("UPDATE pages SET compiled_truth = compiled_truth || ' A database edit.' WHERE source_id='default' AND slug=$1", [slug]);
+ } finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }
+ await engine.executeRaw('DELETE FROM op_checkpoints WHERE op IN ($1,$2)', [SYNC_IMPORT_PROVENANCE_OP, MANAGED_SYNC_PASS_OP]);
+ while ((await drainProjections(engine, { limit: 100 })).rebuilt > 0);
+}
+
+const incarnationOf = async (engine: BrainEngine) => (await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'"))[0]!.incarnation;
+const page = async (engine: BrainEngine, slug: string) => (await engine.executeRaw<{ compiled_truth: string; frontmatter: Record<string, unknown> }>(
+ "SELECT compiled_truth, frontmatter FROM pages WHERE source_id='default' AND slug=$1", [slug]))[0]!;
+
+describe('GBRA-133 legacy page with the database-only grandfather stamp', () => {
+ test('a commit to its file imports instead of holding file_drift, and the page keeps validate: false', () => managedBrain(async ({ engine, root }) => {
+ await performManagedSync(engine, { ...OPTS, repoPath: root });
+ await legacyPages(engine, ['notes/stamped', 'notes/edited'], ['notes/edited']);
+ await performManagedSync(engine, { ...OPTS, repoPath: root });
+ for (const name of NAMES) writeFileSync(join(root, `notes/${name}.md`), readFileSync(join(root, `notes/${name}.md`), 'utf8') + '\nA line the cron writer added.\n');
+ commit(root, 'cron writer');
+ await performManagedSync(engine, { ...OPTS, repoPath: root });
+
+ const incarnation = await incarnationOf(engine);
+ expect(await readGitHold(engine, 'default', incarnation, 'notes/stamped.md')).toBeNull();
+ const stamped = await page(engine, 'notes/stamped');
+ expect(stamped.compiled_truth).toContain('A line the cron writer added.');
+ expect(stamped.frontmatter.validate).toBe(false);
+ expect(readFileSync(join(root, 'notes/stamped.md'), 'utf8')).not.toContain('validate');
+ expect(await readGitHold(engine, 'default', incarnation, 'notes/plain.md')).toBeNull();
+ expect((await page(engine, 'notes/plain')).compiled_truth).toContain('A line the cron writer added.');
+ // A database copy that really moved off the file is still held, and keeps its edit.
+ const held = await readGitHold(engine, 'default', incarnation, 'notes/edited.md');
+ expect(held).toMatchObject({ code: 'file_drift', meta: { side: 'unknown' } });
+ // With no import record and no database write on record, the hold does not claim the database changed.
+ expect(held!.message).toBe('notes/edited.md: page notes/edited differs from its file and has no import record to tell whether the file or the database changed, so sync held the import instead of overwriting the database version; the rest of the source synced.');
+ expect((await page(engine, 'notes/edited')).compiled_truth).toContain('A database edit.');
+ }, { setup }), 120_000);
+});