Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): name the refusing trigger, table and a closed reason on managed publication failures (#6513)
garrytan8c0d9ba981e7
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.mdindex 141768d711..e1d4539b4a 100644--- a/docs/architecture/key-files/canonical-reconciliation.md+++ b/docs/architecture/key-files/canonical-reconciliation.md@@ -6,7 +6,7 @@- `src/core/persistence/reconcile-additive.ts` (#5974) — pure structural drift classifier over the complete file/database delta: inserted whole lines (two-pointer subsequence, CRLF-normalized; fence, heading and table insertions excluded) are `suggested`; an append-only `contacts` list, an allowlisted activity date moving forward, and one-sided ordinary fields are `auto`; policy/privacy/identity/tag changes and everything else are `review`. `--auto-additive` previews write `take_file` only for `auto` (and `suggested` with `--accept-suggested`), recorded as format-2 `auto_decisions` with an evidence digest that apply and owner preparation recheck. `--audit --classify` reports per-page verdicts and counts, never values; #5966 (W14 P1.7) adds the `slug_rule_mismatch` verdict (a legacy unstamped file of a slug the path cannot derive, fix: `gbrain repair frontmatter`) read from `readReconcileState`'s refusal (`detail: slug_rule_mismatch` once the wave-13 `reconcile-state.ts` hunk lands; until then an `invalid_params` refusal on a non-fixed-point slug).-- `src/core/persistence/publication-failure.ts` (#5974) — maps a P0001 from the managed-writer guard (which raises TABLE/SCHEMA, `managed_writer_guard:<branch>` and a JSON DETAIL) or another trigger to a bounded `error_detail` (origin, raiser, table, op, branch, relationship, stage, plus owner-only source ids and the attempt's build/host). Receipts expose only `publicFailureDetail`; `sources writer status` lists the full detail under `recent_failures`. #5929: `ownerExceptionFailure` (the coordinator `requestError` fallback) keeps an unexpected exception's class, errno and top `src/...:line` frame as `origin: owner_exception` (never its message), so `withAttempt` stamps the build; `publicFailureDetail` is an allow-list (origin, sqlstate, raiser, table, op, branch, relationship, stage, fence), so `error_class`/`errno`/`frame`, `sources` and `attempt` stay owner-only; `ownerBuildMismatch` drives the local `owner_build` receipt field (`ops/persistence.ts`) and the submit-time why/fix (`page-mutations.ts`), and `ownerExceptionLogText` the consumer log line.+- `src/core/persistence/publication-failure.ts` (#5974) — maps a P0001 from the managed-writer guard (which raises TABLE/SCHEMA, `managed_writer_guard:<branch>` and a JSON DETAIL) or another trigger to a bounded `error_detail` (origin, raiser, table, op, branch, relationship, stage, plus owner-only source ids and the attempt's build/host). Receipts expose only `publicFailureDetail`; `sources writer status` lists the full detail under `recent_failures`. #5929: `ownerExceptionFailure` (the coordinator `requestError` fallback) keeps an unexpected exception's class, errno and top `src/...:line` frame as `origin: owner_exception` (never its message), so `withAttempt` stamps the build; `publicFailureDetail` is an allow-list (origin, sqlstate, raiser, table, op, branch, relationship, reason, stage, fence), so `error_class`/`errno`/`frame`, `sources` and `attempt` stay owner-only; `ownerBuildMismatch` drives the local `owner_build` receipt field (`ops/persistence.ts`) and the submit-time why/fix (`page-mutations.ts`), and `ownerExceptionLogText` the consumer log line. Wave 16 (GBRA-79, #6513 comments): an untyped refusal carries a CLOSED `reason` (`PUBLICATION_REASONS`: `attribution_unclassified_table` and `trust_unclassified_table` from the two stamp triggers' own "is not classified for table" raise, `graduation_in_progress` from the engine-graduation fence, which raises SQLSTATE 55000 and which `databaseRefusal` now recognizes, else `unknown`); the message decides nothing on its own (the same text from another raiser, or the fence's text under P0001, is `unknown`), the public message names only the enum (`Publication failed (P0001 in <raiser>: <reason>)`), and no part of the message is stored, owner-side included (#5974's rule). `publicFailureDetail` passes `reason` only as a member of the enum, whatever a stored detail holds. The projection rides the managed failure (`sync-failures.ts` `ManagedSyncFailure.write_error_detail`, recorded with the failure and re-read from the pending receipt by `readManagedSyncFailures`; `publicationDetailText` appends ` raiser= table= reason=` to `formatManagedSyncFailure`, so the ledger mirror and doctor carry it) and `gbrain sync status --json` (`last_error.write_error_detail`, `last_error.detail` = the reason, which `classifySyncFault` refines by: `graduation_in_progress` is `connection` / retry / no human in `sync-fault-class.ts`). Tests: `test/publication-failure-reason-6513.test.ts` (mapping, privacy negatives, allow-list), `test/sync-status-failure-detail-6513.test.ts` (both engines, a real operator trigger).- `src/core/cycle/extract-atoms-page-state.ts` — derived page scan/failure state keyed by source incarnation, stable page identity and content hash. Compare-and-swap stamps never update canonical frontmatter. Reviewed reconciliation can carry matching state across removal of legacy bookkeeping fields. Atom item completion still waits for all atoms and provenance links; managed extraction uses journaled publication and a durable completion receipt after trusted local source-wide authority checks and, for filesystem publication, owner preflight.diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.mdindex bd2321da70..4244207684 100644--- a/docs/architecture/key-files/google-and-loops-continued.md+++ b/docs/architecture/key-files/google-and-loops-continued.md@@ -2,7 +2,7 @@[Subsystem index](../KEY_FILES.md) · [Previous entries](google-and-loops.md).-- `src/core/persistence/sync-failures.ts` — durable managed cursor/receipt diagnostics are the authority; JSONL is a compatibility mirror keyed by cursor and source/path. Failure observations deduplicate terminal receipts, retaining structured codes and attempts; success clears only its matching cursor. A failure records the cursor-selecting `syncOptions` and `processingOptions` of its run (falling back to its cursor's when read), and every local hint (the thrown failure line, the blocked report, the terminal write diagnostic and local doctor) renders the exact retry through `managedSyncRetryCommand` → `checkpointRetryCommand`; a failure recorded before options were kept says so instead of guessing. `sync --retry-failed` counts only failures of the cursor key its own options select (`managedSyncCursorKey`) and lists the others with their own retry command. Local CLI shows request/run/pinned target details, while remote doctor returns source-scoped aggregates without paths, raw messages or receipt IDs. Missing durable state warns rather than certifying health. Failed receipts cannot be acknowledged, auto-skipped or rewritten; explicit idle ordinary-source retry creates fresh admission, while approved company manifests remain pinned. Tests: `test/persistence-sync-failures.serial.test.ts`, `test/e2e/managed-sync-failures.test.ts`. #6402: an observation moves `updated_at`; a new target commit restarts `first_seen`/`attempts`; an `invalid_params` resume refusal is not recorded. #6288: after a managed sync succeeds, `clearSettledManagedSyncFailures` removes the source's rows under other cursor keys (a `--full` run's) whose cursor is done or gone and whose file the imported commit settles; `gbrain sync --source ID --acknowledge-managed REQUEST_ID_OR_PATH` (host CLI) removes only such rows, refusing others `managed_failure_unsettled` (`sync-managed-stale-failures.test.ts`).+- `src/core/persistence/sync-failures.ts` — durable managed cursor/receipt diagnostics are the authority; JSONL is a compatibility mirror keyed by cursor and source/path. Failure observations deduplicate terminal receipts, retaining structured codes and attempts; success clears only its matching cursor. A failure records the cursor-selecting `syncOptions` and `processingOptions` of its run (falling back to its cursor's when read), and every local hint (the thrown failure line, the blocked report, the terminal write diagnostic and local doctor) renders the exact retry through `managedSyncRetryCommand` → `checkpointRetryCommand`; a failure recorded before options were kept says so instead of guessing. `sync --retry-failed` counts only failures of the cursor key its own options select (`managedSyncCursorKey`) and lists the others with their own retry command. Local CLI shows request/run/pinned target details, while remote doctor returns source-scoped aggregates without paths, raw messages or receipt IDs. Missing durable state warns rather than certifying health. Failed receipts cannot be acknowledged, auto-skipped or rewritten; explicit idle ordinary-source retry creates fresh admission, while approved company manifests remain pinned. Tests: `test/persistence-sync-failures.serial.test.ts`, `test/e2e/managed-sync-failures.test.ts`. #6402: an observation moves `updated_at`; a new target commit restarts `first_seen`/`attempts`; an `invalid_params` resume refusal is not recorded. #6288: after a managed sync succeeds, `clearSettledManagedSyncFailures` removes the source's rows under other cursor keys (a `--full` run's) whose cursor is done or gone and whose file the imported commit settles; `gbrain sync --source ID --acknowledge-managed REQUEST_ID_OR_PATH` (host CLI) removes only such rows, refusing others `managed_failure_unsettled` (`sync-managed-stale-failures.test.ts`). Wave 16 (#6513 comments): a failure recorded from a receipt carries `write_error_detail`, the receipt's `publicFailureDetail` projection (origin, sqlstate, raiser, table, the closed `reason`; never message text), `readManagedSyncFailures` re-reads it from the pending receipt's `error_detail`, and `formatManagedSyncFailure` appends ` raiser= table= reason=` (`publicationDetailText`, identifiers only), so the ledger mirror, doctor and the blocked report name the refusing trigger; `sync status --json` surfaces it as `last_error.write_error_detail` with `last_error.detail` = the reason (`sync-status.ts`).- `src/commands/mcp-expose-probe.ts` — the health / occupancy probes `mcp-expose.ts` runs, peeled out behind a narrow `ProbeDeps` (`fetch`, `tcpProbe`, `lookup`, `now`, `sleep`, `healthIntervalMs`) rather than the whole resolved-deps bag: `tryFetch(d, url, timeoutMs)` (one bounded fetch, `redirect: 'manual'`, never throws → `FetchOutcome { res, unresolved }`), `probeHealth` (`res.ok` — the `verify.*` / `--status` bar), `probeOccupied` (an accepted TCP connect OR any HTTP answer — the foreign-listener bar), `pollHealth` (wall-clock budget from `d.now()`, per-probe timeout `min(1500, remaining)`, attempt cap `ceil(budget / healthIntervalMs)` as the frozen-clock backstop, `unresolved` = the LAST probe's verdict), `unresolvedDetail(dnsName)`, `defaultTcpProbe` (one `node:net` connect, socket destroyed on every outcome) and `defaultLookup` (local RFC 6761 `.invalid` rejection, otherwise `dns.promises.lookup`). The name-resolution verdict is the reason the module exists: Bun's `fetch` rejects an unresolvable host with the SAME error as a refused connection ("Unable to connect. Is the computer able to access the url?", code `ConnectionRefused`), so a message match alone never fires in production. After a rejection `nameUnresolved` takes `new URL(url).hostname`, skips IP literals (`isIP`) and `localhost`, and otherwise awaits `d.lookup(host)` raced against the probe's `timeoutMs` (a lookup that does not answer in time proves nothing; the race keeps a late rejection handled); `isUnresolvedLookupError` classifies the lookup rejection by `code` — `ENOTFOUND`, `EAI_AGAIN`, `EAI_NONAME`, `EAI_NODATA`, `DNS_ENOTFOUND` (a resolver outage counts: the verdict is about THIS host) — or by those tokens in its message, and the fetch-message regex (`ENOTFOUND|getaddrinfo|EAI_AGAIN|failed to resolve|Unable to connect.*resolve`) is OR-ed in afterwards as the secondary hint. Tests inject a fake fetch, TCP probe and resolver (`test/mcp-expose.test.ts`; the fixture's default `lookup` resolves every name, reserved-name and label-boundary cases do not query external DNS, and the real `defaultLookup` resolves localhost). `statusOnlyHealthDetail(port)` reads this host's live status-only marker for the port so `verify.local` reads "status-only (<reason>)" instead of a timeout or "no answer".- `src/core/tailscale.ts` — Tailscale helpers with an injected exec seam (`CommandRunner = (argv, { inherit?, timeoutMs?, stdoutToStderr? }) => Promise<CommandResult>` where `CommandResult = { status, stdout, stderr }` and `status: null` means killed at the timeout or never spawned; `defaultCommandRunner` on `Bun.spawn` — at `timeoutMs` it sends SIGTERM and, when the child has still not exited `SIGKILL_GRACE_MS` (3s) later, SIGKILL, so a child that ignores SIGTERM never hangs the caller; both timers are cleared in a `finally` — also the runner `serve-service.ts` types against; `stdoutToStderr` sends an inherited child's stdout to fd 2 so `--json` stdout stays pure): `parseTailscaleStatus` (`BackendState` — `Running`, `NeedsLogin`, `NeedsMachineAuth`, `NoState`, `Stopped`; `Self.DNSName`, `CertDomains`, and `funnelCapable`: true/false from `Self.CapMap` keys or `Self.Capabilities` entries carrying any Funnel form — `funnel` (`NodeAttrFunnel`), `https://tailscale.com/cap/funnel-ports` with or without its `?ports=` query, or the legacy `https://tailscale.com/cap/funnel` — null when both are absent), `publicUrlFromDnsName` (strip trailing dot, lowercase, `https://`), `TAILSCALE_BINARY_CANDIDATES` + `findTailscaleBinary` (`Bun.which`, then the macOS app bundle, Homebrew and `/usr/bin` paths; the candidate list doubles as `mcp-expose.ts`'s allowlist for a binary path recorded in a receipt) + `isSystemTailscaleBinary(binary, realpath = realpathSync)` (true when the path is a candidate literally or resolves to one through symlinks; an unresolvable path is false — `mcp-expose.ts` puts `sudo` in front of the binary only when this holds), `tailscaleInstallPlan(platform, hasBrew)`, `tailscaleLoginArgv(platform, user, binary)` → `{ setOperator?, up }` (Linux: `sudo <bin> set --operator=<user>` then a flagless `sudo <bin> up` — a flagged `up` trips the CLI's settings-revert check on a node with non-default prefs; macOS: `<bin> up`), `tailscaleManualLoginCommand(binary = 'tailscale')` (the Linux login the operator runs themselves when gbrain refuses to `sudo` a non-system binary — `sudo <bin> set --operator=$USER && sudo <bin> up` with the DISCOVERED path shell-quoted through `shellQuote`, because a binary outside sudo's `secure_path` is exactly that case) and `TAILSCALE_ACCEPT_DNS_COMMAND` (`tailscale set --accept-dns=true`, the MagicDNS-off remedy) — both keep their tailscale flag literals in this module so the flag-registry scan of `mcp-expose.ts` never sees them, `tailscaleServeArgv(port, { funnel })` (`serve --bg` / `funnel --bg`) + `tailscaleServeOffArgv({ funnel })` (`serve|funnel --https=443 --set-path=/ off` — `--set-path=/` scopes `off` to OUR `/` mount; without it the CLI removes every mount under `:443` and, when more than one exists, prompts interactively — with stdin ignored the prompt reads EOF and the command exits 0 having removed nothing; never `serve reset`), `parseServeStatusStrict` (the only serve-status parser, fail-closed: background `Web` handlers, `Foreground[<session>].Web` handlers marked `foreground: true`, and `TCP['443'].TCPForward` as a non-proxy root handler; an empty document / `{}` / `null` is the legitimately empty view, but non-JSON, an array or a scalar returns `null` so `mcp-expose.ts`'s `readServeView` can tell "could not read" from "nothing configured") + `findProxiedHandler(view, port)`, `classifyTailscaleError(stderr)` (Funnel rule before the HTTPS rule; the HTTPS rule matches certificate vocabulary, never a bare `https://` URL: `funnel_not_enabled` | `https_not_enabled` | `needs_operator` | `needs_login` | `daemon_not_running` | `unknown`), and the admin/KB URL constants (`TAILSCALE_ADMIN_DNS_URL`, `TAILSCALE_ADMIN_ACL_URL`, `TAILSCALE_FUNNEL_KB_URL` = `https://tailscale.com/kb/1223/funnel`, `TAILSCALE_DOWNLOAD_URL`). The parsers and argv builders are pure; the injectable `which` / `fileExists` / runner defaults touch `existsSync`, `process.env.PATH` and `process.platform`, and tests replace them. Note `tailscale status --json` exits 0 in every `BackendState` (only the human-readable form exits 1 when logged out), and `serve`/`funnel` wait interactively rather than failing when HTTPS certificates or the Funnel attribute are off — which is why `mcp-expose.ts` pre-checks before starting them.diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.mdindex ce5a879ab4..940fa3c0b6 100644--- a/docs/guides/sync-unblock-runbook.md+++ b/docs/guides/sync-unblock-runbook.md@@ -103,6 +103,7 @@ Every hold and error has three fields, from one table| `database_contention` | connection | retry | no | three reruns in a row stop on it || `write_capacity` | connection | retry | no | writer status shows the cap held by requests that never settle || `storage_error` | connection | retry | no | the same error after a rerun (then it is not a dropped connection) |+| `graduation_in_progress` | connection | retry | no | gbrain migrate --status --json reports no running move and the fence still refuses || `preparation_systemic` | systemic | upgrade, retry | yes | always || `drain_stalled` | systemic | none | yes | always || `recovery_required` | systemic | none | yes | always |diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 75235d2d63..27beda8ce3 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -37,7 +37,7 @@ of making a duplicate.| Reason | Error code | What it means | Recovery || --- | --- | --- | --- || `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). |-| <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. | 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. |+| <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`. || `physical_root_device_changed` | `recovery_required` | The checkout's filesystem device number changed while everything else matches, which macOS can do after a reboot. When the owner token, brain, worktree, root, inode and a non-zero birth time all match and the caller can verify database ownership, the write path re-stamps ownership by itself and the write proceeds. This refusal means the automatic re-stamp could not be verified; the suggestion says why. | Do a deliberate self-transfer: `gbrain sources writer status <source>` (note `admin_state`), then `gbrain sources writer transfer prepare <source> --self-transfer --admin-intent writer_transfer_prepare --expected-state <admin_state>`, then `gbrain sources writer transfer accept <source> --path <root> --expected-epoch <epoch> --manifest <digest from prepare> --self-transfer --admin-intent writer_transfer_accept --expected-state <fresh admin_state>`. Retry the original write with the **same** request ID. Never delete ownership marker files. || `physical_root_directory_changed` | `recovery_required` | The directory at the checkout's recorded path is not the one the owner stamped: its inode changed, or its birth time differs from the stamp by more than 1 µs, while the owner token, brain, worktree, root and device all still match. A checkout deleted and recreated at the same path (restore from backup, rebuilt container, Migration Assistant copy) looks like this. A birth time within 1 µs of the stamp is accepted (#6501: APFS reports a new directory's birth time tens of nanoseconds apart across processes); a stamp of `0` against a filesystem that now reports a birth time, or a damaged stamp, still refuses. | If the checkout was recreated at its recorded path, do a deliberate relocated-root self-transfer: `gbrain sources writer status <source>` (note `admin_state`), then `gbrain sources writer transfer prepare <source> --self-transfer --confirm-relocated-root --admin-intent writer_transfer_prepare --expected-state <admin_state>`, then `gbrain sources writer transfer accept <source> --path <root> --expected-epoch <epoch> --manifest <digest from prepare> --self-transfer --confirm-relocated-root --admin-intent writer_transfer_accept --expected-state <fresh admin_state>`. `writer status --json` prints the commands filled in. Retry the original write with the **same** request ID. Never delete ownership marker files. |diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex d26a37d5d4..b15dd49a37 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -475,6 +475,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.182.0', text: 'On a multimodal install, plain `gbrain embed --stale` now runs the image sweep (`--images`) before its text pass and reports it as `images` in `--json`; `gbrain embed --stale --images` works on managed brains, finds an image page with no recorded `source_path` by its slug, and exits non-zero naming the path it tried when no candidate has a file (it used to exit 0); the folded sweep only reports fileless pages. Doctor gains `image_embedding_coverage`.' },// wave 16 (GBRA-79). `since` is provisional at the branch VERSION; the integrator restamps it at the merge slot.{ since: '0.60.183.0', text: 'A managed sync checkpoint whose cursor another run of the same source replaced (a `--retry-failed` rediscovery or a newer sync) now refuses `sync_cursor_replaced` (receipt state `conflict`) instead of `revision_conflict`, the run that awaited it records no managed-sync failure for it and goes on with the winning cursor, and `--retry-failed` no longer treats the superseded checkpoint as a page fault; `gbrain doctor` stops reporting such a checkpoint as an unresolved sync failure. A same-run index lag still reports `revision_conflict` and a missing manifest `storage_error`.' },+ { since: '0.60.183.0', text: 'A write a database trigger gbrain does not know refuses now carries a closed `reason` in its public failure detail (`attribution_unclassified_table`, `trust_unclassified_table`, `graduation_in_progress`, or `unknown`), its stored message reads `Publication failed (P0001 in <raiser>: <reason>). Inspect owner diagnostics.`, and the engine-graduation fence (SQLSTATE 55000) is recognized as `graduation_in_progress` with a retry-later message instead of an owner-exception `storage_error`. The managed sync failure a run records, the failure ledger, `gbrain doctor` and `gbrain sync status --json` (`last_error.write_error_detail`, `last_error.detail`) now name the raiser, table and reason that only the receipt named before; the trigger\'s message text stays on the brain host (`gbrain write-request <id> --json`).' },{ since: '0.60.183.0', text: 'Managed sync bookkeeping recorded under a source incarnation the source no longer has (a source re-pointed at a new checkout, or removed and added again) is now retirable: `gbrain repair managed-sync-orphans --source <id>` lists such cursor and failure rows as `incarnation_retired` and local ledger rows whose durable failure row is gone as `mirror_only`, and a successful sync prunes a source\'s stale mirror rows. `gbrain doctor` names them with the repair even when no current failure is visible; `gbrain doctor --fast` (no database) now reports mirrored managed rows as `warn` "could not be verified" instead of `fail` (a better fast score is less certainty, not recovery; the engine-backed check stays authoritative), while old unmanaged file failures keep their severity. `gbrain sync status` reports only a cursor a current sync can select: an old-incarnation cursor is `cursor: null` with `last_error.code: cursor_incarnation_retired` and the repair preview as `next`, instead of a resumable cursor whose `next` selected nothing.' },];diff --git a/src/core/persistence/publication-failure.ts b/src/core/persistence/publication-failure.tsindex 0c7ca6beea..8102eb7a04 100644--- a/src/core/persistence/publication-failure.ts+++ b/src/core/persistence/publication-failure.ts@@ -11,6 +11,13 @@ import type { Action } from '../agent-output.ts';* branch and the source relationship. Page text, SQL and row values never are.*/export type PublicationStage = 'preparation' | 'publication' | 'after_file_publication';+/**+ * #6513 (wave 16 G3.5): the public `reason` of a refusal gbrain classifies by its raiser and SQLSTATE. A CLOSED enum:+ * an operator trigger can interpolate a row value at its message prefix, so nothing derived from the message is kept,+ * publicly or owner-side (#5974's rule: fixed identifiers only).+ */+export const PUBLICATION_REASONS = ['attribution_unclassified_table', 'trust_unclassified_table', 'graduation_in_progress', 'unknown'] as const;+export type PublicationReason = typeof PUBLICATION_REASONS[number];export interface PublicationFailureDetail {origin: 'database_guard' | 'database_trigger' | 'database';sqlstate: string;@@ -19,6 +26,8 @@ export interface PublicationFailureDetail {op?: string;branch?: string;relationship?: string;+ /** Closed enum (`PUBLICATION_REASONS`) for a refusal without a typed code; absent on the typed guard/trigger refusals. */+ reason?: PublicationReason;/** Owner-only: source identifiers can name private sources. */sources?: { target: string | null; old: string | null; allowed: string[] };stage?: PublicationStage;@@ -64,17 +73,39 @@ function guardDetail(raw: unknown): Pick<PublicationFailureDetail, 'op' | 'relat...(target || old || allowed.length ? { sources: { target, old, allowed } } : {}) };}+/** graduation-schema.ts: the engine-graduation fence refuses with SQLSTATE 55000, not P0001. */+const GRADUATION_SQLSTATE = '55000';+const GRADUATION_RAISER = 'gbrain_graduation_fence';+const UNCLASSIFIED_TABLE: Record<string, PublicationReason> = { gbrain_stamp_write_attribution: 'attribution_unclassified_table', gbrain_stamp_trust_tier: 'trust_unclassified_table' };+/**+ * The closed reason of an untyped refusal: a known raiser's own fixed text (attribution-schema.ts / trust/schema.ts+ * "is not classified for table"), the graduation fence by its SQLSTATE and raiser, else `unknown`. The message decides+ * nothing on its own: the same text from another raiser, or the fence's text under P0001, is `unknown`.+ */+function publicationReason(sqlstate: string, raiser: string | undefined, message: string): PublicationReason {+ if (sqlstate === GRADUATION_SQLSTATE) return raiser === GRADUATION_RAISER ? 'graduation_in_progress' : 'unknown';+ const unclassified = raiser ? UNCLASSIFIED_TABLE[raiser] : undefined;+ return unclassified && message.startsWith(`${raiser} is not classified for table`) ? unclassified : 'unknown';+}+/** Null when the error is not a database refusal this module recognizes. */export function databaseRefusal(error: unknown): PublicationFailure | null {if (error instanceof OperationError || !error || typeof error !== 'object') return null;const e = error as Record<string, unknown>;const sqlstate = typeof e.code === 'string' && /^[0-9A-Z]{5}$/.test(e.code) ? e.code : null;- if (sqlstate !== 'P0001') return null;+ if (sqlstate !== 'P0001' && sqlstate !== GRADUATION_SQLSTATE) return null;const where = typeof e.where === 'string' ? e.where : '';const raiser = ident(/PL\/pgSQL function (?:[A-Za-z_][A-Za-z0-9_]*\.)?([A-Za-z_][A-Za-z0-9_]*)[( ]/.exec(where)?.[1]);const table = ident(e.table_name ?? e.table);const constraint = typeof (e.constraint_name ?? e.constraint) === 'string' ? String(e.constraint_name ?? e.constraint) : '';const message = typeof e.message === 'string' ? e.message : '';+ if (sqlstate === GRADUATION_SQLSTATE) {+ const reason = publicationReason(sqlstate, raiser, message);+ return { code: 'storage_error', detail: { origin: raiser ? 'database_trigger' : 'database', sqlstate, ...(raiser ? { raiser } : {}), ...(table ? { table } : {}), reason },+ message: reason === 'graduation_in_progress'+ ? `Publication was refused by the engine graduation fence (${sqlstate} in ${raiser}: ${reason}): this brain is being moved between engines; retry once gbrain migrate --status --json reports the run finished.`+ : `Publication failed (${sqlstate}${raiser ? ` in ${raiser}` : ''}: ${reason}). Inspect owner diagnostics.` };+ }if (message.startsWith(PURGED_PREFIX)) return { code: 'purged_content', message: `${message.slice(PURGED_PREFIX.length).trim()}. Nothing was committed.`,detail: { origin: 'database_trigger', sqlstate, ...(raiser ? { raiser } : {}), ...(table ? { table } : {}) } };if (message.startsWith(GUARD_PREFIX) || constraint.startsWith('managed_writer_guard')) {@@ -90,8 +121,9 @@ export function databaseRefusal(error: unknown): PublicationFailure | null {...guardDetail(e.detail) },message: `The trust-tier guard refused a write${table ? ` on ${table}` : ''}: raising a tier needs the owner's confirmation. Nothing was committed.` };}- return { code: 'storage_error', message: `Publication failed (P0001${raiser ? ` in ${raiser}` : ''}). Inspect owner diagnostics.`,- detail: { origin: raiser ? 'database_trigger' : 'database', sqlstate, ...(raiser ? { raiser } : {}), ...(table ? { table } : {}) } };+ const reason = publicationReason(sqlstate, raiser, message);+ return { code: 'storage_error', message: `Publication failed (P0001${raiser ? ` in ${raiser}` : ''}: ${reason}). Inspect owner diagnostics.`,+ detail: { origin: raiser ? 'database_trigger' : 'database', sqlstate, ...(raiser ? { raiser } : {}), ...(table ? { table } : {}), reason } };}const ERRNO = /^[A-Za-z0-9_]{1,40}$/;@@ -161,12 +193,14 @@ export function withAttempt(failure: PublicationFailure, stage: PublicationStage* reason and problem classes; its row numbers stay owner-side (they can* number rows a remote caller never saw).*/-const PUBLIC_DETAIL_KEYS: ReadonlySet<string> = new Set(['origin', 'sqlstate', 'raiser', 'table', 'op', 'branch', 'relationship', 'stage', 'fence']);+const PUBLIC_DETAIL_KEYS: ReadonlySet<string> = new Set(['origin', 'sqlstate', 'raiser', 'table', 'op', 'branch', 'relationship', 'reason', 'stage', 'fence']);export function publicFailureDetail(detail: unknown): Record<string, unknown> | undefined {if (!detail || typeof detail !== 'object' || Array.isArray(detail)) return undefined;// #5929: an allow-list, so a key added to a stored detail is owner-only unless it is listed here.- const rest = Object.fromEntries(Object.entries(detail).filter(([key]) => PUBLIC_DETAIL_KEYS.has(key)));+ // #6513: `reason` is public only as a member of the closed enum, whatever a stored detail holds under that key.+ const rest = Object.fromEntries(Object.entries(detail).filter(([key, value]) => PUBLIC_DETAIL_KEYS.has(key)+ && (key !== 'reason' || (PUBLICATION_REASONS as readonly unknown[]).includes(value))));if ((rest as { origin?: unknown }).origin === 'fence') {const { rows: _rows, issues, ...fence } = ((rest as unknown as FenceFailureDetail).fence ?? {}) as FenceFailureDetail['fence'];const publicIssues = Array.isArray(issues) ? issues.map(({ row: _row, ...issue }) => issue) : undefined;diff --git a/src/core/persistence/sync-failures.ts b/src/core/persistence/sync-failures.tsindex 49b2820ae4..4aa69b5313 100644--- a/src/core/persistence/sync-failures.ts+++ b/src/core/persistence/sync-failures.ts@@ -7,6 +7,7 @@ import type { SyncCursorOptions } from './sync-prepare.ts';import { resolveManagedSyncContext, syncGit, syncGitPath } from './sync-discovery.ts';import { readGitHold } from './sync-holds.ts';import { pruneMirrorOnlyManagedFailures } from './managed-sync-orphans.ts';+import { publicFailureDetail } from './publication-failure.ts';export interface ManagedSyncFailure {source_id: string;@@ -26,6 +27,8 @@ export interface ManagedSyncFailure {/** The cursor-selecting options of the failed run; absent on failures recorded before they were kept. */syncOptions?: SyncCursorOptions;processingOptions?: Partial<SyncProcessingOptions>;+ /** #6513: the receipt's public failure detail (`publicFailureDetail`: fixed identifiers and the closed `reason`), when the receipt stored one. */+ write_error_detail?: Record<string, unknown>;}export async function recordManagedSyncFailure(engine: BrainEngine, value: Omit<ManagedSyncFailure, 'first_seen' | 'attempts'> & { first_seen?: string }): Promise<{ failure: ManagedSyncFailure; ledgerRecorded: boolean }> {@@ -142,12 +145,12 @@ export async function acknowledgeManagedSyncFailures(engine: BrainEngine, run: Mexport async function readManagedSyncFailures(engine: BrainEngine, sourceIds?: string[]): Promise<ManagedSyncFailure[]> {const rows = await engine.executeRaw<{ cursor_key: string; value: { sourceId: string; incarnation: string; runId: string; index: number; target: string; pending?: { requestId: string };syncOptions: SyncCursorOptions | null; processingOptions: Partial<SyncProcessingOptions> | null };- receipt: Pick<WriteRequest, 'state' | 'request_id' | 'error_code' | 'error_message'> | null; failure: ManagedSyncFailure | null; path: string | null; updated_at: string }>(`+ receipt: Pick<WriteRequest, 'state' | 'request_id' | 'error_code' | 'error_message' | 'error_detail'> | null; failure: ManagedSyncFailure | null; path: string | null; updated_at: string }>(`SELECT c.fingerprint AS cursor_key,jsonb_build_object('sourceId',s.id,'incarnation',s.incarnation,'runId',c.completed_keys->0->>'runId','index',c.completed_keys->0->'index','target',c.completed_keys->0->>'target','syncOptions',c.completed_keys->0->'syncOptions','processingOptions',c.completed_keys->0->'processingOptions','pending',jsonb_build_object('requestId',c.completed_keys->0->'pending'->>'requestId')) AS value,- CASE WHEN r.id IS NULL THEN NULL ELSE jsonb_build_object('state',r.state,'request_id',r.request_id,'error_code',r.error_code,'error_message',r.error_message) END AS receipt,+ CASE WHEN r.id IS NULL THEN NULL ELSE jsonb_build_object('state',r.state,'request_id',r.request_id,'error_code',r.error_code,'error_message',r.error_message,'error_detail',r.error_detail) END AS receipt,f.completed_keys->0 AS failure,m.completed_keys->((c.completed_keys->0->>'index')::int)->>'path' AS path,c.updated_atFROM op_checkpoints cJOIN sources s ON s.id=c.completed_keys->0->>'sourceId' AND s.incarnation::text=c.completed_keys->0->>'incarnation'@@ -161,8 +164,12 @@ export async function readManagedSyncFailures(engine: BrainEngine, sourceIds?: sconst failures: ManagedSyncFailure[] = rows.map(row => {const c = row.value, r = row.receipt;const options = { ...(c.syncOptions ? { syncOptions: c.syncOptions } : {}), ...(c.processingOptions ? { processingOptions: c.processingOptions } : {}) };- if (row.failure && (!r || !['failed', 'conflict', 'cancelled'].includes(r.state) || row.failure.request_id === r.request_id)) return { ...options, ...row.failure };- return { ...options, source_id: c.sourceId, source_incarnation: c.incarnation, path: row.path ?? '<checkpoint>', code: r?.error_code ?? 'sync_incomplete',+ // #6513: the pending receipt's bounded public detail rides the failure it belongs to (the row's own copy, when recorded, is the same projection).+ const detail = r?.error_detail ? publicFailureDetail(r.error_detail) : undefined;+ if (row.failure && (!r || !['failed', 'conflict', 'cancelled'].includes(r.state) || row.failure.request_id === r.request_id)) {+ return { ...options, ...(detail && row.failure.request_id === r?.request_id ? { write_error_detail: detail } : {}), ...row.failure };+ }+ return { ...options, ...(detail ? { write_error_detail: detail } : {}), source_id: c.sourceId, source_incarnation: c.incarnation, path: row.path ?? '<checkpoint>', code: r?.error_code ?? 'sync_incomplete',message: r?.error_message ?? 'The durable sync cursor is unfinished; resume the accepted run.', request_id: c.pending?.requestId ?? null,run_id: c.runId, target: c.target, cursor_key: row.cursor_key, phase: r ? 'receipt' : 'resume', state: r?.state ?? 'unfinished',observation_id: c.pending?.requestId ?? `${c.runId}:${c.index}`, first_seen: new Date(row.updated_at).toISOString(), attempts: 1 };@@ -177,7 +184,13 @@ export async function readManagedSyncFailures(engine: BrainEngine, sourceIds?: sexport function formatManagedSyncFailure(failure: ManagedSyncFailure): string {const clean = (value: string) => value.replace(/[\x00-\x1f\x7f-\x9f]/g, ' ').slice(0, 1000);- return `source=${clean(failure.source_id)} path=${clean(failure.path)} code=${clean(failure.code)}: ${clean(failure.message)} request=${failure.request_id ?? '<not-admitted>'} run=${failure.run_id} target=${failure.target ?? '<undiscovered>'}`;+ return `source=${clean(failure.source_id)} path=${clean(failure.path)} code=${clean(failure.code)}: ${clean(failure.message)} request=${failure.request_id ?? '<not-admitted>'} run=${failure.run_id} target=${failure.target ?? '<undiscovered>'}${publicationDetailText(failure.write_error_detail)}`;+}+const IDENT = /^[A-Za-z_][A-Za-z0-9_.:-]{0,79}$/;+/** #6513: the fixed identifiers of a public failure detail (`raiser`, `table`) and its closed `reason`, as ` key=value` text; nothing else of it. */+export function publicationDetailText(detail: Record<string, unknown> | undefined): string {+ if (!detail) return '';+ return (['raiser', 'table', 'reason'] as const).map(key => typeof detail[key] === 'string' && IDENT.test(detail[key] as string) ? ` ${key}=${detail[key]}` : '').join('');}/** The retry for one managed failure: same source and recorded cursor-selecting options, or an honest note when they were not recorded. */diff --git a/src/core/persistence/sync-fault-class.ts b/src/core/persistence/sync-fault-class.tsindex b05b5af5c6..00d21b4447 100644--- a/src/core/persistence/sync-fault-class.ts+++ b/src/core/persistence/sync-fault-class.ts@@ -70,6 +70,8 @@ export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [{ code: 'database_contention', class: 'connection', safe_actions: ['retry'], needs_human: false, escalate: 'three reruns in a row stop on it' },{ code: 'write_capacity', class: 'connection', safe_actions: ['retry'], needs_human: false, escalate: 'writer status shows the cap held by requests that never settle' },{ code: 'storage_error', class: 'connection', safe_actions: ['retry'], needs_human: false, escalate: 'the same error after a rerun (then it is not a dropped connection)' },+ // #6513: the engine-graduation fence (SQLSTATE 55000) refuses every write until the move finishes; the cursor and manifest stand.+ { code: 'graduation_in_progress', class: 'connection', safe_actions: ['retry'], needs_human: false, escalate: 'gbrain migrate --status --json reports no running move and the fence still refuses' },// Systemic class: a retry alone changes nothing.{ code: 'preparation_systemic', class: 'systemic', safe_actions: ['upgrade', 'retry'], needs_human: true, escalate: 'always', human_reason: 'Several writes could not finish preparing: the write owner is the likely cause. Writer status names it; fix, restart or upgrade it.' },{ code: 'drain_stalled', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always', human_reason: 'The write at the head of the source is wedged in its owner; restart the owner process writer status names.' },diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex ec7b99e29d..b46363813e 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -48,6 +48,7 @@ import { frozenImageIntent, sameImageBytes } from './sync-image.ts';import { fenceReceiptLocation } from '../fence-repair/refusal.ts';import { managedSyncWriteDiagnostic, writeWaitOf } from './sync-write-diagnostic.ts';import { checkpointSuperseded } from './sync-checkpoint-replaced.ts';+import { publicFailureDetail } from './publication-failure.ts';import { fileChangedAfterAdmission, headCommittedBytes, originFaultHold, pageChangeProof, pageChangedHold, pinnedWorktreeConflict, receiptPageFaultHold, worktreeDirtyHold } from './sync-page-fault.ts';import { faultPoint } from './fault-points.ts';import { pipelined } from '../page-state/transactions.ts';@@ -714,7 +715,7 @@ async function settleFailedRequest(engine: BrainEngine, input: { cursor: Cursor;request_id: pending.requestId, run_id: cursor.runId, target: cursor.target, cursor_key: key,syncOptions: cursor.syncOptions ?? syncOptions, processingOptions: cursor.processingOptions ?? processingOptions,phase: pending.intent.kind === 'managed_sync_checkpoint' ? 'checkpoint' : 'receipt', state: done.state, observation_id: pending.requestId,- first_seen: new Date(done.completed_at ?? done.updated_at).toISOString() });+ first_seen: new Date(done.completed_at ?? done.updated_at).toISOString(), ...(done.error_detail ? { write_error_detail: publicFailureDetail(done.error_detail) } : {}) });// #5762: the hint is built after the failed transaction, from a fresh read of the request indexes.const hint = done.error_code === CHECKPOINT_VALIDATION_TIMEOUT && !remote ? await checkpointTimeoutHint(engine,{ requestId: pending.requestId, sourceId: cursor.sourceId, processingOptions: pending.intent.processingOptions, syncOptions: pending.intent.syncOptions ?? syncOptions, repoPath: pending.intent.repoPath ?? input.run.repoPath }) : null;diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.tsindex acff386811..8ecb6f4411 100644--- a/src/core/persistence/sync-status.ts+++ b/src/core/persistence/sync-status.ts@@ -51,8 +51,11 @@ export interface SyncStatusHold extends SyncFaultVerdict {export interface SyncStatusError extends SyncFaultVerdict {code: string;+ /** A refinement of `code`: a lane fault (`cancelled`), or #6513 the closed `reason` of a database refusal. */detail?: string;message: string;+ /** #6513: the receipt's public failure detail (origin, sqlstate, raiser, table, the closed reason; never message text). */+ write_error_detail?: Record<string, unknown>;slug?: string;path?: string;request_id?: string;@@ -136,11 +139,13 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string): Proconst repairable = records.filter(record => contentHoldDisposition(record, auto).action === 'repair').length;const failures = (await readManagedSyncFailures(engine, [sourceId])).filter(failure => failure.code !== 'sync_incomplete');const failure = failures[0];- const laneFault = failure?.code === 'cancelled' ? laneFaultInMessage(failure.message) : null;+ const reason = typeof failure?.write_error_detail?.reason === 'string' ? failure.write_error_detail.reason : null;+ const laneFault = (failure?.code === 'cancelled' ? laneFaultInMessage(failure.message) : null) ?? reason;const retired = failure || header ? null : await retiredCursorStands(engine, sourceId, source.incarnation);const repairPreview: Action = { argv: ['gbrain', 'repair', 'managed-sync-orphans', '--source', sourceId], consent: [], actor: 'agent', requires_exclusive: false,why: 'Previews the sync bookkeeping nothing current can resume or clear (an old incarnation\'s cursor and failure rows, stale mirror rows) with the hash its --apply takes; writes nothing.' };- const lastError: SyncStatusError | null = failure ? { code: failure.code, ...(laneFault ? { detail: laneFault } : {}), message: failure.message, path: failure.path, phase: failure.phase, first_seen: failure.first_seen, attempts: failure.attempts,+ const lastError: SyncStatusError | null = failure ? { code: failure.code, ...(laneFault ? { detail: laneFault } : {}), message: failure.message, ...(failure.write_error_detail ? { write_error_detail: failure.write_error_detail } : {}),+ path: failure.path, phase: failure.phase, first_seen: failure.first_seen, attempts: failure.attempts,...(failure.request_id ? { request_id: failure.request_id } : {}), ...classifySyncFault({ code: failure.code, detail: laneFault, message: failure.message }) }: retired ? { code: 'cursor_incarnation_retired', message: `An unfinished sync cursor of ${sourceId} was recorded under an incarnation the source no longer has; no current sync selects it, and it says nothing about whether the current files are imported. `+ `Retire it with ${repairPreview.argv!.join(' ')} (preview, then --apply with the printed hash).`, phase: 'resume', first_seen: retired.first_seen, attempts: 1, ...classifySyncFault({ code: 'cursor_incarnation_retired' }) } : null;diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 7fa8b198a5..9705d354e4 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -140,6 +140,7 @@ test/sync-full-untracked-import-5459.test.tstest/sync-group-member-order.test.tstest/sync-legacy-holds.test.tstest/sync-staged-catchup.test.ts+test/sync-status-failure-detail-6513.test.tstest/sync-waiver-budget.test.tstest/sync-waiver-run-imports.test.tstest/takes-vector-lifecycle-5885.serial.test.tsdiff --git a/test/publication-failure-reason-6513.test.ts b/test/publication-failure-reason-6513.test.tsnew file mode 100644index 0000000000..b3902fb45a--- /dev/null+++ b/test/publication-failure-reason-6513.test.ts@@ -0,0 +1,87 @@+/**+ * Wave 16 G3.5 ([R13], #6513 comments, media-corpus): a database refusal's public+ * `reason` is a CLOSED enum mapped from known raiser / SQLSTATE combinations.+ * `PUBLIC_DETAIL_KEYS` is a key allow-list, not a value sanitizer, and an+ * operator trigger can interpolate a row value at the message prefix, so no+ * message-derived identifier ever reaches a public projection.+ *+ * - `gbrain_stamp_write_attribution` "not classified for table" → `attribution_unclassified_table`;+ * `gbrain_stamp_trust_tier` "not classified for table" → `trust_unclassified_table`;+ * the real graduation fence (SQLSTATE 55000 from `gbrain_graduation_fence`, which+ * `databaseRefusal` ignored before) → `graduation_in_progress`, classified retry / no human;+ * anything else → `unknown`, and a synthetic P0001 carrying the fence's text stays `unknown`.+ * - nothing of the message is kept, owner-side included (#5974's pinned rule); `publicFailureDetail`+ * drops any `reason` outside the enum, however it was stored.+ * - the purged / guard / trust-raise prefixes keep their codes and gain no reason.+ */+import { expect, test } from 'bun:test';+import { PUBLICATION_REASONS, databaseRefusal, publicFailureDetail } from '../src/core/persistence/publication-failure.ts';+import { classifySyncFault } from '../src/core/persistence/sync-fault-class.ts';++const PRIVATE = 'private_person_example_42';+const pg = (fields: Record<string, unknown>) => Object.assign(new Error(String(fields.message ?? '')), fields);+const raise = (raiser: string, message: string, extra: Record<string, unknown> = {}) =>+ pg({ code: 'P0001', message, where: `PL/pgSQL function ${raiser}() line 7 at RAISE`, table_name: 'pages', severity: 'ERROR', ...extra });+const leak = (value: unknown) => JSON.stringify(value).includes(PRIVATE);++test('the reason enum is closed and covers the three known raisers; everything else is unknown', () => {+ expect([...PUBLICATION_REASONS].sort()).toEqual(['attribution_unclassified_table', 'graduation_in_progress', 'trust_unclassified_table', 'unknown']);+ const attribution = databaseRefusal(raise('gbrain_stamp_write_attribution', 'gbrain_stamp_write_attribution is not classified for table pages'))!;+ expect(attribution).toMatchObject({ code: 'storage_error', detail: { origin: 'database_trigger', sqlstate: 'P0001', raiser: 'gbrain_stamp_write_attribution', table: 'pages', reason: 'attribution_unclassified_table' } });+ expect(attribution.message).toBe('Publication failed (P0001 in gbrain_stamp_write_attribution: attribution_unclassified_table). Inspect owner diagnostics.');+ const trust = databaseRefusal(raise('gbrain_stamp_trust_tier', 'gbrain_stamp_trust_tier is not classified for table facts', { table_name: 'facts' }))!;+ expect(trust).toMatchObject({ code: 'storage_error', detail: { raiser: 'gbrain_stamp_trust_tier', table: 'facts', reason: 'trust_unclassified_table' } });+ // A known raiser with another message is not that reason.+ expect(databaseRefusal(raise('gbrain_stamp_write_attribution', `${PRIVATE}: refused`))!.detail).toMatchObject({ raiser: 'gbrain_stamp_write_attribution', reason: 'unknown' });+ // The same message text under a raiser the map does not know is unknown too.+ expect(databaseRefusal(raise('operator_hook', 'gbrain_stamp_write_attribution is not classified for table pages'))!.detail).toMatchObject({ raiser: 'operator_hook', reason: 'unknown' });+});++test('an unknown operator trigger: reason unknown, and no part of its message is kept anywhere', () => {+ for (const message of [`${PRIVATE}: refused`, `"${PRIVATE}": refused`, `${PRIVATE}\nline two\r\n\x1b[31mred`, `${PRIVATE}_${'x'.repeat(500)}`]) {+ const failure = databaseRefusal(raise('operator_hook', message))!;+ expect(failure.code).toBe('storage_error');+ expect(failure.message).toBe('Publication failed (P0001 in operator_hook: unknown). Inspect owner diagnostics.');+ expect(failure.detail).toMatchObject({ origin: 'database_trigger', sqlstate: 'P0001', raiser: 'operator_hook', table: 'pages', reason: 'unknown' });+ // #5974's rule stands: the stored (owner-only) detail keeps fixed identifiers only, so the prefix is kept nowhere.+ expect(leak(failure)).toBe(false);+ expect(failure.detail).toEqual({ origin: 'database_trigger', sqlstate: 'P0001', raiser: 'operator_hook', table: 'pages', reason: 'unknown' });+ expect(publicFailureDetail(failure.detail)).toEqual({ origin: 'database_trigger', sqlstate: 'P0001', raiser: 'operator_hook', table: 'pages', reason: 'unknown' });+ }+ // No raiser at all (a bare RAISE outside plpgsql): origin database, reason unknown, no prefix leak.+ const bare = databaseRefusal(pg({ code: 'P0001', message: `${PRIVATE}: refused` }))!;+ expect(bare.message).toBe('Publication failed (P0001: unknown). Inspect owner diagnostics.');+ expect(publicFailureDetail(bare.detail)).toEqual({ origin: 'database', sqlstate: 'P0001', reason: 'unknown' });+});++test('the real graduation fence (55000) is recognised as graduation_in_progress and classified retry; a P0001 with its text is not', () => {+ const real = databaseRefusal(pg({ code: '55000', message: 'graduation_in_progress: this database is fenced by gbrain engine graduation run 0b6f0c3a-1111-4222-8333-944455556666; writes are refused until the run grants it authority',+ hint: 'Run: gbrain migrate --status --json', where: 'PL/pgSQL function gbrain_graduation_fence() line 5 at RAISE', table_name: 'pages' }))!;+ expect(real).toMatchObject({ code: 'storage_error', detail: { origin: 'database_trigger', sqlstate: '55000', raiser: 'gbrain_graduation_fence', table: 'pages', reason: 'graduation_in_progress' } });+ expect(real.message).toContain('graduation_in_progress');+ expect(real.message).not.toContain('0b6f0c3a');+ expect(publicFailureDetail(real.detail)).toEqual({ origin: 'database_trigger', sqlstate: '55000', raiser: 'gbrain_graduation_fence', table: 'pages', reason: 'graduation_in_progress' });+ expect(classifySyncFault({ code: 'storage_error', detail: 'graduation_in_progress' })).toMatchObject({ safe_actions: ['retry'], needs_human: false });+ // The same text as a P0001 from another raiser, or a 55000 from another raiser, is unknown.+ expect(databaseRefusal(raise('operator_hook', 'graduation_in_progress: this database is fenced by gbrain engine graduation run x'))!.detail).toMatchObject({ sqlstate: 'P0001', reason: 'unknown' });+ expect(databaseRefusal(pg({ code: '55000', message: 'graduation_in_progress: spoofed', where: 'PL/pgSQL function operator_hook() line 1 at RAISE' }))!.detail).toMatchObject({ sqlstate: '55000', raiser: 'operator_hook', reason: 'unknown' });+ // Any other SQLSTATE is still not a database refusal this module names.+ expect(databaseRefusal(pg({ code: '55P03', message: 'lock timeout' }))).toBeNull();+ expect(databaseRefusal(pg({ code: '23505', message: 'duplicate key' }))).toBeNull();+});++test('publicFailureDetail never adds keys and never passes a reason outside the enum, whatever was stored', () => {+ const stored = { origin: 'database_trigger', sqlstate: 'P0001', raiser: 'operator_hook', table: 'pages', reason: PRIVATE, message_prefix: `${PRIVATE}: refused`, sources: { target: 'private-source' }, attempt: { consumer_version: '1', consumer_host_id: 'h' }, extra: PRIVATE };+ expect(publicFailureDetail(stored)).toEqual({ origin: 'database_trigger', sqlstate: 'P0001', raiser: 'operator_hook', table: 'pages' });+ expect(publicFailureDetail({ origin: 'database', sqlstate: 'P0001', reason: 'unknown' })).toEqual({ origin: 'database', sqlstate: 'P0001', reason: 'unknown' });+ expect(publicFailureDetail({ origin: 'database', sqlstate: 'P0001', reason: 42 })).toEqual({ origin: 'database', sqlstate: 'P0001' });+ expect(publicFailureDetail({ origin: 'owner_exception', error_class: 'TypeError', frame: 'src/x.ts:1' })).toEqual({ origin: 'owner_exception' });+});++test('the typed prefixes keep their codes and gain no reason', () => {+ expect(databaseRefusal(raise('gbrain_purge_guard', 'purged_content: the page holds purged content'))).toMatchObject({ code: 'purged_content' });+ expect(databaseRefusal(raise('gbrain_purge_guard', 'purged_content: x'))!.detail).not.toHaveProperty('reason');+ expect(databaseRefusal(raise('gbrain_require_managed_writer', 'writer_coordinator_required: outside', { constraint_name: 'managed_writer_guard:source_scope' }))).toMatchObject({ code: 'writer_coordinator_required', detail: { branch: 'source_scope' } });+ expect(databaseRefusal(raise('gbrain_stamp_trust_tier', 'trust_raise_refused: needs confirmation'))).toMatchObject({ code: 'trust_raise_refused' });+ expect(databaseRefusal(raise('gbrain_stamp_trust_tier', 'trust_raise_refused: needs confirmation'))!.detail).not.toHaveProperty('reason');+});diff --git a/test/sync-status-failure-detail-6513.test.ts b/test/sync-status-failure-detail-6513.test.tsnew file mode 100644index 0000000000..71b7c09acd--- /dev/null+++ b/test/sync-status-failure-detail-6513.test.ts@@ -0,0 +1,103 @@+/**+ * Wave 16 G3.5 ([R13], #6513 comments, media-corpus): when a managed sync page+ * publication is refused by a database trigger gbrain does not know, the+ * failure the run records, the local ledger mirror, `gbrain sync status --json`+ * and the receipt all carry the bounded public detail (origin, sqlstate,+ * raiser, table, the closed `reason`), and none of them, nor the stored+ * receipt row, carries the trigger's message text. Before, the failure row and the status said only+ * `storage_error: Publication failed (P0001 in <raiser>). Inspect owner+ * diagnostics.`; the receipt's `write_error_detail` was the one place that+ * named the raiser and table.+ *+ * On PGLite and Postgres: an operator trigger on `pages` raises a P0001 whose+ * message starts with an identifier-shaped private token.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { join } from 'node:path';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { formatManagedSyncFailure, readManagedSyncFailures } from '../src/core/persistence/sync-failures.ts';+import { readSyncStatus } from '../src/core/persistence/sync-status.ts';+import { receiptFor } from '../src/core/persistence/journal.ts';+import type { WriteRequest } from '../src/core/persistence/model.ts';+import { loadSyncFailures } from '../src/core/sync-failure-ledger.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { withEnv } from './helpers/with-env.ts';++const PRIVATE = 'private_person_example_42';+const home = mkdtempSync(join(tmpdir(), 'gbrain-6513-detail-'));+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;+const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_SOURCE: undefined, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+beforeAll(async () => {+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }+}, 120_000);+afterAll(async () => {+ await withEnv(env, async () => { for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); } });+ await closePostgres?.(); rmSync(home, { recursive: true, force: true });+});++async function fixture(engine: BrainEngine) {+ const id = `det-${randomUUID().slice(0, 12)}`, root = join(home, id);+ mkdirSync(root); git(root, 'init', '-q');+ writeFileSync(join(root, 'a.md'), `---\ntitle: a\n---\nObservation a for the refused publication.\n`);+ git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'content');+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [id, root]);+ await claimWorktree(engine, id, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ return { id, root, opts: { sourceId: id, noPull: true, noEmbed: true, noExtract: true, explicitProcessing: [] } };+}+const leak = (value: unknown) => JSON.stringify(value, (_key, v) => typeof v === 'bigint' ? String(v) : v).includes(PRIVATE);+const PUBLIC = { origin: 'database_trigger', sqlstate: 'P0001', raiser: 'operator_hook_example', table: 'pages', reason: 'unknown', stage: 'publication' };++test('an unknown trigger refusal: failure row, ledger mirror, sync status and receipt carry raiser/table/reason, never the message text', async () => withEnv(env, async () => {+ for (const engine of engines) {+ rmSync(join(home, 'sync-failures.jsonl'), { force: true });+ const f = await fixture(engine);+ await engine.executeRaw(`CREATE OR REPLACE FUNCTION operator_hook_example() RETURNS trigger LANGUAGE plpgsql AS $$+ BEGIN IF NEW.source_id = '${f.id}' THEN RAISE EXCEPTION '${PRIVATE}: refused by an operator hook' USING TABLE = TG_TABLE_NAME; END IF; RETURN NEW; END $$`);+ await engine.executeRaw('DROP TRIGGER IF EXISTS operator_hook_example ON pages');+ await engine.executeRaw('CREATE TRIGGER operator_hook_example BEFORE INSERT ON pages FOR EACH ROW EXECUTE FUNCTION operator_hook_example()');+ try {+ const result = await performManagedSync(engine, f.opts);+ expect(result).toMatchObject({ status: 'blocked_by_failures', failureCodes: [{ code: 'storage_error', count: 1 }] });+ const failure = result.failures![0]!;+ expect(failure).toMatchObject({ code: 'storage_error', path: 'a.md', phase: 'receipt', write_error_detail: PUBLIC });+ expect(failure.message).toBe('Publication failed (P0001 in operator_hook_example: unknown). Inspect owner diagnostics.');+ expect(leak(result)).toBe(false);+ const formatted = formatManagedSyncFailure(failure);+ expect(formatted).toContain('raiser=operator_hook_example table=pages reason=unknown');+ expect(formatted).not.toContain(PRIVATE);+ // The durable failure row and the local ledger mirror.+ const [read] = await readManagedSyncFailures(engine, [f.id]);+ expect(read).toMatchObject({ code: 'storage_error', write_error_detail: PUBLIC });+ const mirrored = loadSyncFailures().filter(row => row.source_id === f.id);+ expect(mirrored).toHaveLength(1);+ expect(mirrored[0]!.error).toContain('raiser=operator_hook_example table=pages reason=unknown');+ expect(leak(mirrored)).toBe(false);+ // sync status: last_error.detail is the reason, write_error_detail the bounded public detail; the verdict is unchanged for storage_error.+ const status = await readSyncStatus(engine, f.id);+ expect(status.last_error).toMatchObject({ code: 'storage_error', detail: 'unknown', write_error_detail: PUBLIC, class: 'connection', safe_actions: ['retry'], needs_human: false });+ expect(leak(status)).toBe(false);+ // The receipt: the public projection matches, and the stored row (owner-only detail included) holds no part of the message.+ const [row] = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE request_id=$1::uuid', [failure.request_id]);+ expect(receiptFor(row!)).toMatchObject({ state: 'failed', write_error: 'storage_error', write_error_detail: PUBLIC });+ expect(leak(row)).toBe(false);+ expect(row!.error_detail).toMatchObject({ ...PUBLIC, attempt: { consumer_version: expect.any(String) } });+ } finally {+ await engine.executeRaw('DROP TRIGGER IF EXISTS operator_hook_example ON pages');+ await engine.executeRaw('DROP FUNCTION IF EXISTS operator_hook_example()');+ }+ }+}), 240_000);