Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(writer): ghost-page and fence_unrenderable receipts get their own terminal categories (#6696 C10)

garrytan7ba30ad9ed83
diff --git a/docs/architecture/key-files/managed-sync-bookkeeping.md b/docs/architecture/key-files/managed-sync-bookkeeping.md
index e44bba4ede..722beb2dd9 100644
--- a/docs/architecture/key-files/managed-sync-bookkeeping.md
+++ b/docs/architecture/key-files/managed-sync-bookkeeping.md
@@ -20,6 +20,6 @@ run, and the supersession of a checkpoint whose cursor another run replaced. The
- `src/core/persistence/sync-checkpoint-replaced.ts` — wave 16 (GBRA-79, #6513 comments): a managed-sync checkpoint whose cursor another run of the source replaced is superseded, not failed. `checkpointCursorReplaced` is the classification the shared validator (`sync-prepare.ts` `sourceSyncChecks` consumer) and the checkpoint's final locked compare-and-swap both apply before their own checks: a checkpoint intent whose durable cursor names another `runId` refuses `sync_cursor_replaced` (receipt state `conflict`, through `coordinator.ts` `conflictCode`); a page request whose cursor moved keeps `revision_conflict` (its run re-admits from the current cursor), a same-run index lag keeps `revision_conflict`, a missing manifest keeps `storage_error`. `checkpointSuperseded` recognizes that receipt in `sync-run.ts`: `settleFailedRequest` records no managed-sync failure for it and continues with the winning cursor as it stands (`currentCursor`, the same move the ENG-A7 admission guard makes when the cursor moves under it; the winner's run id, index and manifest are kept, nothing of it is cleared or advanced), and `retryFailedStart` never treats a checkpoint receipt as a page fault. Before, the loser's run recorded the conflict as a `managed-sync-failure` row, doctor reported it, and `--retry-failed` rediscovered from HEAD. Test: `test/managed-sync-checkpoint-replaced.test.ts` (replacement before validation on both engines; replacement from a second Postgres session between validation and the CAS; `--retry-failed` afterwards converts nothing; controls: index lag, missing manifest).
- `src/core/persistence/sync-knock-on.ts` — #6643: a sync page request that ended without committing only because another request of its sync did not commit (a knock-on). Cancellers stamp `error_detail` `{ origin: 'sync_knock_on', reason, root_request_id }` (survives compaction); pre-#6643 receipts match only their producers' exact messages (`LEGACY_KNOCK_ON_CANCEL_MESSAGES`, the never-admitted patterns, `EARLIER_PAGE_REFUSAL_MESSAGE`), never an operator cancel. `isSyncKnockOn` and `syncKnockOnSql` are one predicate (the SQL is never NULL, so `NOT` of it is safe in clause 3). `cursorFenceCause` reads the three causes of "cursor changed" (`run_replaced`, `window_dropped` only for a request the cursor recorded in `Cursor.dropped`, else `outside_fence`). `sync-run.ts` `recoverKnockOn` re-freezes the entry through `holdUnderGate` (budgets `sync.knock_on_refreeze_limit` per index, `sync.knock_on_run_limit` per invocation; past them `knock_on_exhausted` with `root_cause`), `reviveCheckpoint` re-assesses a refused checkpoint at the cursor's end, and `checkpoint-validation.ts` skips knock-ons of pre-#6643 cursors and the cursor's settled index ranges. `sync status` shows the cursor the recorded failure belongs to, `cursors`, and `checkpoint_blockers` (`listIncompleteSyncReceipts`).
-- `src/core/persistence/terminal-classify.ts` — #6650: `classifyTerminal` turns one terminal receipt (`failed` / `conflict` / `cancelled`, or any row still holding `recovery`) into a `TerminalVerdict` (category, code, origin, class, `safe_actions`, `needs_human`, `defect`, `historical`, `root_request_id`, one structured `action`) at read time; nothing is persisted. A recovery record outranks the code (`recovery_pending` / `recovery_blocked`); a knock-on is read through `isSyncKnockOn` (typed marker survives compaction) or the SQL twin `terminalKnockOnSql`; `storage_error` and `source_changed` route by their recorded origin or cause, and a row whose code and origin do not say what happened is `diagnosis_required` (read-only writer status, never a guessed fix). `TERMINAL_FIXED_IN` names the release that fixed a category; a row whose build (`error_detail.attempt.consumer_version`, else `admitter_version`) is older is historical. It also owns the supersession rule `repair/failed-writes.ts` reuses (`supersessionSql`, `supersessionOrderSql`, `dispositionOf`, `PAGE_REMOVAL_OPERATIONS`). Tests: `test/terminal-failures-6650.test.ts` (TS↔SQL twin parity included).
+- `src/core/persistence/terminal-classify.ts` — #6650: `classifyTerminal` turns one terminal receipt (`failed` / `conflict` / `cancelled`, or any row still holding `recovery`) into a `TerminalVerdict` (category, code, origin, class, `safe_actions`, `needs_human`, `defect`, `historical`, `root_request_id`, one structured `action`) at read time; nothing is persisted. A recovery record outranks the code (`recovery_pending` / `recovery_blocked`); a knock-on is read through `isSyncKnockOn` (typed marker survives compaction) or the SQL twin `terminalKnockOnSql`; `storage_error` and `source_changed` route by their recorded origin or cause, and a row whose code and origin do not say what happened is `diagnosis_required` (read-only writer status, never a guessed fix). A `source_changed` whose canonical file is missing is `canonical_file_missing` (a ghost page; its exit is the `gbrain repair ghost-pages` preview, never a sync retry), and an origin-less `fence_unrenderable` adoption refusal is its own defect category. `TERMINAL_FIXED_IN` names the release that fixed a category; a row whose build (`error_detail.attempt.consumer_version`, else `admitter_version`) is older is historical. It also owns the supersession rule `repair/failed-writes.ts` reuses (`supersessionSql`, `supersessionOrderSql`, `dispositionOf`, `PAGE_REMOVAL_OPERATIONS`). Tests: `test/terminal-failures-6650.test.ts` (TS↔SQL twin parity included), `test/terminal-classify-6696.test.ts`.
- `src/core/persistence/terminal-failures.ts` — #6650: the bounded readers over that classifier. `readTerminalFailureSummary` is one set-based aggregate (GROUPING SETS per source; `TERMINAL_STATEMENT_MS` 5 s statement and `TERMINAL_ACQUIRE_MS` 2 s connection deadlines; past either it returns `status: 'unknown'`, never an empty pile) splitting active blockers (recovery records plus the passed-in `checkpoint_blockers` of `sync-status.ts`, read by `readCheckpointBlockerMap`), unresolved rows (count, distinct slugs and intents, oldest age), historical rows (a later write superseded them, or older than `TERMINAL_FIXED_IN` via the SQL twin `TERMINAL_HISTORICAL_SQL`), 24 h and 7-day daily counts, categories and defect classes; archived sources are skipped. Thresholds `persistence.terminal_failures.window_days` (clamped to `persistence.receipt_retention_days`), `spike_factor`, `spike_min` (`readTerminalThresholds`, `validateTerminalConfigValue`, refused at `config set` by `commands/config/preparation-keys.ts`); `isSpike` against `sevenDayMedian`. `readTerminalFailures` is the drill-down (batches of 200, at most 2,000 rows scanned per call, a sequence cursor, verdict filters, `--group-by category` groups with an exact `drill_down` argv each). Consumers: doctor `persistence_terminal_failures` (`commands/doctor/checks/persistence-requests.ts`), `sync status` `terminal_failures` (`sync-status.ts`, `next` falls back to a recovery blocker's action), the `writer_failures` administration operation, and the admin `/metrics` gauges (`serve-http-metrics.ts` `renderTerminalFailureMetrics`, one aggregate per engine shared by scrapes for `TERMINAL_METRICS_TTL_MS` = 60 s via `cachedTerminalSummary`; never `/health`). Each source also reports `new_last_24h_older_builds` (rows and builds older than their class's fix), and doctor's spike message says an older write owner is producing them when they are most of the spike. Tests: `test/terminal-failures-6650.test.ts`, `test/sync-status-terminal-6650.test.ts`, `test/terminal-failure-metrics-6650.test.ts`, the CLI journey `test/agent-journey-terminal-failures-6650.test.ts`.
- `src/commands/sources-writer-failures.ts` — #6650: output of `gbrain sources writer failures <source> [--state all] [--group-by category] [--since Nd] [--limit N] [--before <cursor>] [--category|--code|--origin] [--json]`, dispatched by `persistence-admin.ts` as `writer_failures` (validated in `administration.ts` `writerFailuresQuery`, locally or through the resident owner). A table by default, one JSON document with `--json`; row and group `fix` / `inspect` actions are rendered for the CLI; a full page prints `truncated` with the exact next command. The operation is advertised to clients in the owner's `administration_extensions` (`ipc.ts`, `admin-contract.ts` `PERSISTENCE_ADMIN_EXTENSIONS`), never in the `administration` list an older client validates strictly, and `local-client.ts` delegates it only to an owner that lists it (`ownerAdministers`). Tests: `test/writer-failures-cli-6650.test.ts`.
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index b92e854ea5..d822bed6b3 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -35,6 +35,14 @@ To see every such receipt of a source at once, grouped with a fix per group:
([terminal write failures](troubleshooting.md#terminal-write-failures)).
Run recovery commands on the brain host unless the row says otherwise.
+Reading `persistence_requests` directly with SQL? Its `error_message` column
+holds only the short message (for `source_changed`, one line such as "The
+canonical file was removed outside coordinated publication."); the recovery
+command lives in the error's `suggestion` and is not stored there. Run
+`gbrain sources writer failures <source> --group-by category` (or
+`gbrain write-request <id> --json` for one row) instead: each group and each
+receipt carries its category and the exit, with the exact command.
+
Keep the original `request_id`. Unless a row says to use a new one, retry the
original write with the same ID after the fix, so the brain replays it instead
of making a duplicate.
@@ -44,6 +52,7 @@ of making a duplicate.
| Reason | Error code | What it means | Recovery |
| --- | --- | --- | --- |
| <a id="file_database_drift"></a>`file_database_drift` | `source_changed` | The page's canonical file and its database copy disagree, usually because the file was edited outside a coordinated write. Neither copy was overwritten. A file with no `type:` line keeps the stored type, and titles compare trimmed, so those alone do not cause this. | `gbrain sources reconcile <source> <slug> --brain <brain> --preview`, review the preview, resolve it, then `--apply <resolved-preview-file> --request-id <new uuid>`. Retry the original write with a **new** request ID. A page that records no file of its own (no `source_path`, typically written by an older release whose write-through also put `ingested_via` / `ingested_at` / `source_kind` in the file only) reconciles against the file at its slug path only when you add `--adopt-slug-path` to the preview; the refusal names the flag in that case, and apply records that file as the page's origin. See [repair a file/database disagreement](concurrent-writes.md#repair-a-filedatabase-disagreement). Many pages at once: `gbrain sources reconcile <source> --brain host --audit --conflicts` lists them and `gbrain repair file-drift` resolves them, preferring the file or the database copy ([file drift](repair.md#file-drift)). |
+| <a id="canonical_file_missing"></a>`canonical_file_missing` | `source_changed` | 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 and the deletion was never imported). A write to the page refuses with "The canonical file was removed outside coordinated publication." and nothing is written. A sync cannot import a file that is not there, so retrying the write or rerunning sync refuses the same way. `gbrain sources writer failures <source>` reports such receipts as category `canonical_file_missing`. | Decide which copy is right. If the file should exist, restore it at its recorded path and sync. If the page should go, preview the ghost-page repair with `gbrain repair ghost-pages --source <source>` (read-only) and apply it only after the user agrees; a soft-deleted page can be restored with `gbrain restore <slug> --force`. Reconciliation does not restore missing files. |
| <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. A 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. 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 `gbrain sync --source <id> --no-pull --full` (or the next sync that imports the file) imports its current content into the surviving page. For a purge, soft-delete instead. 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 --retry-failed`. |
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index facb321968..d0061fc116 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -561,6 +561,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
// #6650 L0 (convergence harness fixes). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
{ since: '0.60.223.0', text: 'On Linux, a `gbrain sync` started after another gbrain process on the same machine was killed no longer treats the dead process\'s heartbeat as a live write owner. Before, it refused to hand its catch-up to the running `gbrain serve` for up to 30 s and ran its own consumer next to it; now it hands the catch-up to the serve (or runs its own consumer when no serve is running). A waiter-only consumer deferring to the dead process promotes on its next check instead of after 60 s. A heartbeat row from another host or container, or from an older gbrain, keeps the time-only rule, as does every row where `/proc` is unavailable.' },
{ since: '0.60.223.0', text: 'On Linux, when the process holding write claims on this host is killed, another consumer on the same machine now reclaims those claims within about 5 s instead of waiting out their lease (up to `persistence.publication_ceiling_ms` plus about 65 s, so about 365 s by default). Only claims with no recovery record and no publication started are taken, the same guard an expired claim has. An owner that is alive, however slow, or on another host or container keeps its full lease.' },
+ // #6696 PR C (GBRA-93 lane C). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
+ { since: '0.60.223.0', text: '`gbrain sources writer failures`, `gbrain write-request`, `gbrain sync status` and doctor `persistence_terminal_failures` now report a write refused because its page\'s canonical file is missing (a ghost page) as category `canonical_file_missing`, whose fix previews `gbrain repair ghost-pages --source <id>`, instead of a sync retry that refuses the same way. A `fence_unrenderable` fact-fence adoption refusal is its own category, and one written by a build older than 0.60.218.0 (the release that stopped the adoption loop) counts as historical and no longer warns.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/persistence/terminal-classify.ts b/src/core/persistence/terminal-classify.ts
index 8ddf5fe13c..f8cc46b1d7 100644
--- a/src/core/persistence/terminal-classify.ts
+++ b/src/core/persistence/terminal-classify.ts
@@ -28,7 +28,7 @@ import { writeFailureDiagnostic } from './verb-errors.ts';
export type TerminalCategory =
| 'recovery_pending' | 'recovery_blocked'
| 'knock_on' | 'run_replaced' | 'outside_fence'
- | 'operator_cancelled' | 'caller_conflict' | 'file_conflict'
+ | 'operator_cancelled' | 'caller_conflict' | 'file_conflict' | 'canonical_file_missing' | 'fence_unrenderable'
| 'writer_guard' | 'database_refusal' | 'owner_exception' | 'legacy_publication_refusal'
| 'sync_fault' | 'transport' | 'caller_refusal' | 'gbrain_defect' | 'diagnosis_required';
@@ -81,6 +81,8 @@ export const TERMINAL_FIXED_IN = {
// #5974/#5982: a guard P0001 is classified (writer_coordinator_required, origin database_guard) and the misread is fixed;
// an unclassified "Publication failed (P0001)" receipt can only come from an older build.
legacy_publication_refusal: '0.60.40.0',
+ // #6657: a refused fact-fence adoption is no longer resubmitted every cycle and keeps its metadata.
+ fence_unrenderable: '0.60.218.0',
} as const satisfies Partial<Record<TerminalCategory, string>>;
/** The connection-loss texts `classifySyncFault` reads as `connection_lost`; POSIX-compatible, so readers match it in SQL (`~*`). */
@@ -88,7 +90,7 @@ export const CONNECTION_MESSAGE_PATTERN = 'ECONN|ETIMEDOUT|EPIPE|connection.*clo
/** The prefix of an unclassified database refusal written before #5974. */
export const LEGACY_PUBLICATION_PREFIX = 'Publication failed (P0001)';
-const DEFECTS = new Set<TerminalCategory>(['outside_fence', 'writer_guard', 'database_refusal', 'owner_exception', 'gbrain_defect']);
+const DEFECTS = new Set<TerminalCategory>(['outside_fence', 'writer_guard', 'database_refusal', 'owner_exception', 'gbrain_defect', 'fence_unrenderable']);
const FAULT_CODES = new Set(SYNC_FAULT_TABLE.map(rule => rule.code));
const escalateOf = (code: string) => SYNC_FAULT_TABLE.find(rule => rule.code === code)?.escalate ?? 'always';
@@ -169,6 +171,14 @@ function route(input: TerminalInput): Partial_ {
return { ...fromTable('knock_on', code, origin, syncRetry(source, `This page only waited on another page of the same sync${root ? ` (request ${root})` : ''}; a sync re-freezes it under a fresh request.`), 'knock_on'),
...(root ? { root_request_id: root } : {}) };
}
+ if (code === 'fence_unrenderable' && origin === null) {
+ return { category: 'fence_unrenderable', code, origin, class: 'page', safe_actions: ['none'], needs_human: true,
+ human_reason: 'The fact-fence adoption planner produced a fence that does not read back as its facts: a gbrain planning defect to report with the page slug and version.',
+ escalate: 'always: a build with the adoption fix wrote it',
+ action: { argv: ['gbrain', 'doctor', '--only', 'fence_integrity', '--json'], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'A legacy fact row was not adopted into its page\'s facts fence; the row stays active and searchable. Doctor fence_integrity lists the pages and reason classes, read-only.',
+ verify: { argv: failuresArgv(source) }, docs: 'docs/guides/write-refusals.md#fence_unrenderable' } };
+ }
if (origin === SYNC_CURSOR_FENCE_ORIGIN) {
const cause = cursorFenceCause(detail);
if (cause === 'outside_fence') return fromTable('outside_fence', code, origin, inspect(source, 'A sync request published outside the cursor that admitted it; writer status and sync status list the drains, read-only.',
@@ -227,6 +237,14 @@ function route(input: TerminalInput): Partial_ {
why: 'Previews both versions of the page and writes nothing; apply the resolved preview, then resubmit the write with a new request id.',
verify: { argv: failuresArgv(source) }, docs: 'docs/guides/write-refusals.md#file_database_drift' } };
}
+ if (known === 'canonical_file_missing') {
+ return { category: 'canonical_file_missing', code, origin: origin ?? known, class: 'page', safe_actions: ['repair'], needs_human: true,
+ human_reason: 'The page\'s canonical file is gone but the database page is still live (a ghost page); a person chooses to restore the file or remove the page.',
+ escalate: 'always: no sync can import a file that is not there',
+ action: { argv: ['gbrain', 'repair', 'ghost-pages', '--source', source], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Previews the live pages whose canonical file is missing and writes nothing; apply only after the user agrees, or restore the file and sync.',
+ verify: { argv: failuresArgv(source) }, docs: 'docs/guides/write-refusals.md#canonical_file_missing' } };
+ }
if (known === 'source_binding_changed' || known === 'unsafe_file_target') return diagnosis(input, code, known, `The write was refused source_changed (${known}).`);
return fromTable('sync_fault', code, origin ?? known, syncRetry(source, `The file changed under the write (${known}); a sync imports the current bytes.`), known === 'pinned_git_worktree_conflict' ? known : 'source_changed');
}
diff --git a/src/core/persistence/terminal-failures.ts b/src/core/persistence/terminal-failures.ts
index df8012d02b..44577879e4 100644
--- a/src/core/persistence/terminal-failures.ts
+++ b/src/core/persistence/terminal-failures.ts
@@ -72,6 +72,7 @@ const OLDER_THAN = (column: string, fixed: string) => `COALESCE(${column} ~ '^\\
export const TERMINAL_HISTORICAL_SQL: Readonly<Record<keyof typeof TERMINAL_FIXED_IN, (b: string) => string>> = {
knock_on: b => `(${b}.knock_on AND NOT ${b}.has_recovery AND ${OLDER_THAN(`${b}.build`, TERMINAL_FIXED_IN.knock_on)})`,
legacy_publication_refusal: b => `(NOT ${b}.has_recovery AND NOT ${b}.knock_on AND ${b}.routed_message = '${LEGACY_PUBLICATION_PREFIX}' AND ${b}.origin IS NULL AND ${b}.error_code IN ('storage_error','writer_coordinator_required'))`,
+ fence_unrenderable: b => `(NOT ${b}.has_recovery AND NOT ${b}.knock_on AND ${b}.origin IS NULL AND ${b}.error_code = 'fence_unrenderable' AND ${OLDER_THAN(`${b}.build`, TERMINAL_FIXED_IN.fence_unrenderable)})`,
};
const HISTORICAL_BY_BUILD = (b: string) => `COALESCE(${Object.values(TERMINAL_HISTORICAL_SQL).map(sql => sql(b)).join(' OR ')}, false)`;
const BUILD = (r: string) => `COALESCE(${r}.error_detail->'attempt'->>'consumer_version', ${r}.admitter_version)`;
diff --git a/test/terminal-classify-6696.test.ts b/test/terminal-classify-6696.test.ts
new file mode 100644
index 0000000000..d3f9070c33
--- /dev/null
+++ b/test/terminal-classify-6696.test.ts
@@ -0,0 +1,34 @@
+/**
+ * #6696 (PR C, C10): classifier follow-ups on the #6650 terminal-receipt classifier.
+ *
+ * Protects: a `source_changed` receipt whose canonical file is missing (a ghost page: the database page outlived its
+ * file) is its own category with the ghost repair exit instead of a sync retry that can never import a file that is not
+ * there; a `fence_unrenderable` adoption refusal written before the fix that stopped the loop (#6657) reads historical,
+ * while one from a fixed build stays an unresolved defect.
+ */
+import { describe, expect, test } from 'bun:test';
+import { classifyTerminal, TERMINAL_FIXED_IN, type TerminalInput } from '../src/core/persistence/terminal-classify.ts';
+
+const base: TerminalInput = { source_id: 'src', slug: 'projects/acme-example', operation: 'submit_job', state: 'conflict', error_code: null, error_detail: null,
+ recovery: null, blocked_reason: null, compacted: false };
+
+describe('classifyTerminal (#6696 C10)', () => {
+ test('a missing canonical file is its own category whose exit is the ghost-page repair, by message or recorded reason', () => {
+ const byMessage = classifyTerminal({ ...base, error_code: 'source_changed', error_message: 'The canonical file was removed outside coordinated publication.' })!;
+ const byReason = classifyTerminal({ ...base, error_code: 'source_changed', compacted: true, error_detail: { reason: 'canonical_file_missing' } })!;
+ for (const verdict of [byMessage, byReason]) {
+ expect(verdict).toMatchObject({ category: 'canonical_file_missing', code: 'source_changed', class: 'page', safe_actions: ['repair'], needs_human: true, defect: false });
+ expect(verdict.action.argv).toEqual(['gbrain', 'repair', 'ghost-pages', '--source', 'src']);
+ expect(verdict.action.verify?.argv).toEqual(['gbrain', 'sources', 'writer', 'failures', 'src', '--json']);
+ expect(verdict.action.docs).toBe('docs/guides/write-refusals.md#canonical_file_missing');
+ }
+ });
+
+ test('a fence_unrenderable refusal from a build before the adoption fix is historical; a newer one is an unresolved defect', () => {
+ const refusal = { ...base, state: 'failed', error_code: 'fence_unrenderable', error_message: 'The adopted fence row does not render its legacy fact.' };
+ expect(TERMINAL_FIXED_IN).toMatchObject({ fence_unrenderable: '0.60.218.0' });
+ expect(classifyTerminal({ ...refusal, build: '0.60.217.0' })).toMatchObject({ category: 'fence_unrenderable', historical: true, defect: true, fixed_in: '0.60.218.0' });
+ expect(classifyTerminal({ ...refusal, build: '0.60.218.0' })).toMatchObject({ category: 'fence_unrenderable', historical: false, defect: true });
+ expect(classifyTerminal({ ...refusal, build: '0.60.217.0' })!.action.argv).toEqual(['gbrain', 'doctor', '--only', 'fence_integrity', '--json']);
+ });
+});
diff --git a/test/terminal-failures-6650.test.ts b/test/terminal-failures-6650.test.ts
index 7faa0b52b0..62f7df09da 100644
--- a/test/terminal-failures-6650.test.ts
+++ b/test/terminal-failures-6650.test.ts
@@ -302,6 +302,8 @@ for (const kind of testBackends()) describe(`the aggregate, doctor and the drill
await seed({ slug: 'h4', state: 'failed', code: 'storage_error', message: 'Publication failed (P0001). Inspect owner diagnostics.' });
await seed({ slug: 'h5', state: 'failed', code: 'storage_error', message: 'Publication failed (P0001 in x: unknown). Inspect owner diagnostics.', detail: { origin: 'database_trigger', raiser: 'x' } });
await seed({ slug: 'h6', operation: 'submit_job', state: 'cancelled', code: 'cancelled', detail: knock, build: 'dev-build' });
+ await seed({ slug: 'h7', operation: 'submit_job', state: 'failed', code: 'fence_unrenderable', message: 'The adopted fence row does not render its legacy fact.', build: '0.60.217.0' });
+ await seed({ slug: 'h8', operation: 'submit_job', state: 'failed', code: 'fence_unrenderable', message: 'The adopted fence row does not render its legacy fact.', build: '0.60.218.0' });
const all = Object.values(TERMINAL_HISTORICAL_SQL).map(sql => sql('b')).join(' OR ');
const rows = await engine.executeRaw<{ slug: string; flag: boolean; state: string; error_code: string; error_message: string | null; error_detail: Record<string, unknown> | null; operation: string;
compacted: boolean; build: string | null }>(`SELECT b.*, (${all}) AS flag FROM (SELECT r.slug, r.state, r.error_code, r.error_message, r.error_detail, r.operation, r.compacted,
@@ -310,7 +312,7 @@ for (const kind of testBackends()) describe(`the aggregate, doctor and the drill
COALESCE(r.error_detail->'attempt'->>'consumer_version', r.admitter_version) AS build FROM persistence_requests r) b ORDER BY b.slug`);
const ts = rows.map(row => [row.slug, classifyTerminal({ ...base, ...row, recovery: null, blocked_reason: null })!.historical]);
expect(rows.map(row => [row.slug, row.flag])).toEqual(ts as never);
- expect(ts).toEqual([['h1', true], ['h2', false], ['h3', true], ['h4', true], ['h5', false], ['h6', false]]);
+ expect(ts).toEqual([['h1', true], ['h2', false], ['h3', true], ['h4', true], ['h5', false], ['h6', false], ['h7', true], ['h8', false]]);
});
test('the extracted supersession rule is the one failed-writes applies', async () => {