Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
refactor(dream): our own implementation of the #6059 fix (#6059)
time-attackd6fde2a67bd2
diff --git a/docs/architecture/key-files/core-cycle-continued.md b/docs/architecture/key-files/core-cycle-continued.mdindex 71baf3b08d..bc768c893a 100644--- a/docs/architecture/key-files/core-cycle-continued.md+++ b/docs/architecture/key-files/core-cycle-continued.md@@ -4,10 +4,10 @@Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.Synthesis, patterns, consolidation and connector atom gating.-- `src/core/cycle/synthesize-postprocess.ts` — Managed synthesis quote repair and provenance stamping publish together through a deterministic maintenance request bound to the source incarnation, transcript hash, child output, and original committed page revision. The immutable committed receipt is the completion checkpoint: later runs skip finalized output rather than repairing user edits. Pending work replays its retained intent under the original revision and existing authority/file guards; missing provenance fails closed. A publish still `write_pending` after the job's shared maintenance wait is deferred, never written or finalized: `withPublishPending` turns the phase result into `warn` with `publish_pending` and `SYNTH_PUBLISH_DEFERRED` ("publish deferred (writer busy); finishes next cycle, no action needed"), `synthesize.ts` leaves `dream.synthesize.last_completion_ts` unstamped, and the next ordinary cycle resumes the same deterministic request id. Runs the same claim verification as the unmanaged path (`groundSource` + `resolveVerifyPrior` + `verifyDreamPage` from `synthesize-verify.ts`, scoped by the ref's `first_write_at`, else the child write epochs passed as `sinceByTranscript`) and stamps the dream provenance fields only on dream-owned pages (`isDreamOwnedPage`); the published page reconciles its automatic links like an ordinary put_page (`page-prepare.ts` treats `managed_maintenance_page` intents as auto-linked); the unmanaged path retains its fail-open behavior. Covered by `test/managed-synthesis-postprocess.test.ts` and its PostgreSQL E2E wrapper. The optional `grounding` pass (System One S8) runs after `verifyDreamPage` and before `publishMaintenancePage`, so the published revision never carries a unit S8 quarantined; pinned by `test/decide/writepath-phase.serial.test.ts`. The postprocess stamps the transcript's `seat` next to `raw_source` on dream-owned output. `deferPublishOrThrow` defers an output or summary publish that is still pending or whose admission gave up on database contention (`maintenancePublicationDeferral`, one stderr line per contended publish) exactly like the pending case: `publish_pending`, phase warn, no cooldown stamp; every other error fails the phase. Pinned by `test/managed-synthesis-postprocess.test.ts`.+- `src/core/cycle/synthesize-postprocess.ts` — Managed synthesis quote repair and provenance stamping publish together through a deterministic maintenance request bound to the source incarnation, transcript hash, child output, and original committed page revision. The immutable committed receipt is the completion checkpoint: later runs skip finalized output rather than repairing user edits. Pending work replays its retained intent under the original revision and existing authority/file guards; missing provenance fails closed. A publish still `write_pending` after the job's shared maintenance wait is deferred, never written or finalized: `withPublishPending` turns the phase result into `warn` with `publish_pending` and `SYNTH_PUBLISH_DEFERRED` ("publish deferred (writer busy); finishes next cycle, no action needed"), `synthesize.ts` leaves `dream.synthesize.last_completion_ts` unstamped, and the next ordinary cycle resumes the same deterministic request id. Runs the same claim verification as the unmanaged path (`groundSource` + `resolveVerifyPrior` + `verifyDreamPage` from `synthesize-verify.ts`, scoped by the ref's `first_write_at`, else the child write epochs passed as `sinceByTranscript`) and stamps the dream provenance fields only on dream-owned pages (`isDreamOwnedPage`); the published page reconciles its automatic links like an ordinary put_page (`page-prepare.ts` treats `managed_maintenance_page` intents as auto-linked); the unmanaged path retains its fail-open behavior. Covered by `test/managed-synthesis-postprocess.test.ts` and its PostgreSQL E2E wrapper. The optional `grounding` pass (System One S8) runs after `verifyDreamPage` and before `publishMaintenancePage`, so the published revision never carries a unit S8 quarantined; pinned by `test/decide/writepath-phase.serial.test.ts`. The postprocess stamps the transcript's `seat` next to `raw_source` on dream-owned output. `deferPublishOrThrow` defers an output or summary publish that is still pending or whose admission gave up on database contention (`publicationHold` in `persistence/accepted-pending.ts`, one stderr line per contended publish) exactly like the pending case: `publish_pending`, phase warn, no cooldown stamp; every other error fails the phase. Pinned by `test/managed-synthesis-postprocess.test.ts`.-- `src/core/cycle/patterns.ts` — Patterns phase: cross-session theme detection over reflections within `dream.patterns.lookback_days` (default 30). Names a pattern only when ≥`dream.patterns.min_evidence` (default 3) reflections support it. Reflection excerpts use the shared UTF-16-safe truncator; a raw `.slice(0, 600)` can split an emoji pair and make Postgres reject the subagent job's JSONB payload. Single Sonnet subagent; same allow-list path as synthesize (imports `loadAllowedSlugPrefixes` + `loadOutputRoot` from synthesize.ts — the reflections lookup, prompt slug templates, and allow-list all honor `dream.synthesize.output_root`, default 'wiki'). Subagent job/wait timeouts are config keys `dream.patterns.subagent_timeout_ms` / `dream.patterns.subagent_wait_timeout_ms` (defaults 30/35 min, mirroring the `dream.synthesize.*` pair). The phase status reflects the child outcome: non-`completed` outcome with zero writes → `fail` (error code `PATTERNS_CHILD_<OUTCOME>`); non-`completed` with partial writes → `warn`. Runs AFTER `extract` so the graph is fresh. The fan-out sets `require_writes: true` so an all-writes-failed child dead-letters instead of reporting completed. Budget clamping: clamped to the remaining parent-job budget via `clampSubagentBudgets` when the cycle threads `deadlineAtMs` — the clamp template synthesize.ts reuses; `MIN_PATTERNS_SUBAGENT_BUDGET_MS` gates an honest skip, and `CYCLE_DEADLINE_RESERVE_MS` is re-exported here from its base-phase.ts home. Evidence watermark: a `completed` child stamps the newest consumed reflection `updated_at` into the state row `dream.patterns.last_evidence_ts` (never `now()`; fail/warn/timeout paths don't stamp, so a dead child retries next tick), and a later run skips `no_new_evidence` while no reflection in the window is newer — autopilot's hourly global tick becomes a free skip until a reflection actually changes; an absent/unparseable stamp fails open; `--once` bypasses the gate but a completed forced run still stamps. Managed local evidence is source-incarnation-scoped and live/non-private; unchanged evidence coalesces the admitted child request instead of inventing a remote maintenance grant. Maintenance runs (the only keyed patterns runs) consult the paid-loop breaker before submission and skip with `dream_breaker_tripped`. A managed grounding publish or provenance stamp that is accepted-but-pending or rolled back by admission contention is deferred (`maintenancePublicationDeferral`): the page is excluded from `patterns_written` and verification, counted in `publish_deferred`, the phase returns `warn`, and the evidence watermark stays unstamped so the next cycle retries; other publication errors still fail. Pages the child wrote under `dream.patterns.output_slug_prefix` get the dream-output identity stamp (`dream_generated`, `dream_cycle_date`, `dream_created_cycle_date`) before the reverse-write: through `stampMaintenancePage` on a managed brain, through `stampDreamProvenance` (`dream-provenance.ts`) otherwise. A pattern page also gets `seat` when every input reflection carries the same seat, and none otherwise; the managed submission key digests the reflections without their seats. Quote grounding (`groundPatternPages`, `dream.quote_verify`, default on): right after the subagent's writes and before provenance stamping, pattern pages are checked against the full reflection pages with `verifyBody(…, { checks: 'quotes' })`; failing units move to frontmatter `unverified_claims`, `quote_verified_at` marks the page, and pages a crashed run left without it are verified on the next run. Write-back goes through `publishMaintenancePage` on managed brains, else `importFromContent`. Phase details carry `quote_verify` counts. Pinned by `test/cycle-patterns-quote-verify.test.ts`.-- `src/core/cycle/publication-deferral.ts` — `maintenancePublicationDeferral(error)` classifies a managed maintenance publication failure as `pending` (an accepted, non-terminal `write_pending` receipt) or `contention` (`storage_error` with detail `database_contention` and no receipt), else null. Patterns and drift catch it only around publication: drift returns `partial` with `reports_written: 0` and `publish_deferred: 1` and names the reason in its detail. Permission refusals, other storage errors and terminal receipts are never deferred.+- `src/core/cycle/patterns.ts` — Patterns phase: cross-session theme detection over reflections within `dream.patterns.lookback_days` (default 30). Names a pattern only when ≥`dream.patterns.min_evidence` (default 3) reflections support it. Reflection excerpts use the shared UTF-16-safe truncator; a raw `.slice(0, 600)` can split an emoji pair and make Postgres reject the subagent job's JSONB payload. Single Sonnet subagent; same allow-list path as synthesize (imports `loadAllowedSlugPrefixes` + `loadOutputRoot` from synthesize.ts — the reflections lookup, prompt slug templates, and allow-list all honor `dream.synthesize.output_root`, default 'wiki'). Subagent job/wait timeouts are config keys `dream.patterns.subagent_timeout_ms` / `dream.patterns.subagent_wait_timeout_ms` (defaults 30/35 min, mirroring the `dream.synthesize.*` pair). The phase status reflects the child outcome: non-`completed` outcome with zero writes → `fail` (error code `PATTERNS_CHILD_<OUTCOME>`); non-`completed` with partial writes → `warn`. Runs AFTER `extract` so the graph is fresh. The fan-out sets `require_writes: true` so an all-writes-failed child dead-letters instead of reporting completed. Budget clamping: clamped to the remaining parent-job budget via `clampSubagentBudgets` when the cycle threads `deadlineAtMs` — the clamp template synthesize.ts reuses; `MIN_PATTERNS_SUBAGENT_BUDGET_MS` gates an honest skip, and `CYCLE_DEADLINE_RESERVE_MS` is re-exported here from its base-phase.ts home. Evidence watermark: a `completed` child stamps the newest consumed reflection `updated_at` into the state row `dream.patterns.last_evidence_ts` (never `now()`; fail/warn/timeout paths don't stamp, so a dead child retries next tick), and a later run skips `no_new_evidence` while no reflection in the window is newer — autopilot's hourly global tick becomes a free skip until a reflection actually changes; an absent/unparseable stamp fails open; `--once` bypasses the gate but a completed forced run still stamps. Managed local evidence is source-incarnation-scoped and live/non-private; unchanged evidence coalesces the admitted child request instead of inventing a remote maintenance grant. Maintenance runs (the only keyed patterns runs) consult the paid-loop breaker before submission and skip with `dream_breaker_tripped`. A managed grounding publish or provenance stamp that is accepted-but-pending or rolled back by admission contention is held (`publishOrHold`): a held page is not provenance-stamped, it is left out of `patterns_written` and of `verifyMaintenanceOutputs` (only for refs in the cycle's own source, so a ref in another source is always verified), `publish_deferred` counts held pages, the phase returns `warn`, and the evidence watermark stays unstamped so the next cycle retries; other publication errors still fail. `groundPatternPages` holds only when its caller passes the `heldSlugs` set; direct callers keep the throwing behavior. Pages the child wrote under `dream.patterns.output_slug_prefix` get the dream-output identity stamp (`dream_generated`, `dream_cycle_date`, `dream_created_cycle_date`) before the reverse-write: through `stampMaintenancePage` on a managed brain, through `stampDreamProvenance` (`dream-provenance.ts`) otherwise. A pattern page also gets `seat` when every input reflection carries the same seat, and none otherwise; the managed submission key digests the reflections without their seats. Quote grounding (`groundPatternPages`, `dream.quote_verify`, default on): right after the subagent's writes and before provenance stamping, pattern pages are checked against the full reflection pages with `verifyBody(…, { checks: 'quotes' })`; failing units move to frontmatter `unverified_claims`, `quote_verified_at` marks the page, and pages a crashed run left without it are verified on the next run. Write-back goes through `publishMaintenancePage` on managed brains, else `importFromContent`. Phase details carry `quote_verify` counts. Pinned by `test/cycle-patterns-quote-verify.test.ts`.+- `src/core/cycle/drift.ts` report publication (#6052): a managed drift report whose publish is held (`publishOrHold`) is not linked in the detail, `reports_written` is 0 and `publish_deferred` 1, the detail names the hold (accepted and still publishing, or not admitted under database contention), and the phase is `partial`; every other publish error still throws.- `src/core/cycle/phases/consolidate.ts` — the consolidate phase: clusters facts per page and promotes the best claim into a take. Take identity for the upsert lookup is `(page_id, claim)` restricted to rows this phase authors (`kind='fact' AND holder='self'`) — `since_date` is NOT identity (it derives from MIN(valid_from) of the cluster and moves whenever extract_facts re-inserts, which degraded the lookup into duplicate INSERTs); deliberately NOT filtered on `active` (a superseded take still owns its claim — skipping it would resurrect a retired claim via the INSERT path); `ORDER BY id` keeps the pick deterministic across pre-existing duplicate rows. A resolved take is immutable — its id is reused for consolidation but the row is left untouched. Managed local consolidation passes the cycle source ID, publishes take, contributing facts and validity changes atomically. Retired/resolved matching takes produce a durable skipped receipt; semantic intent excludes vectors/timestamps/cache metadata, while a genuine newer fact/page snapshot changes request identity. Only live world-visible evidence is promoted; private facts remain private.diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.mdindex bb70a6a14d..e29899fd96 100644--- a/docs/architecture/key-files/core-persistence-continued.md+++ b/docs/architecture/key-files/core-persistence-continued.md@@ -21,7 +21,7 @@ Managed connector ingestion, connector item holds, sync checkpoint validation an- `src/core/persistence/checkpoint-validation.ts` — the managed sync checkpoint's incomplete-receipt validation (#5762): `INCOMPLETE_SYNC_RECEIPT_SQL` is three `LIMIT 1` probes (recovery; an open page receipt of the run; a non-committed page receipt with no committed sibling at its index) served by `persistence_requests_recovery`, `persistence_requests_sync_run_open` and `persistence_requests_sync_run_committed`, with the same result as the former single predicate. `findIncompleteSyncReceipt` returns the blocking receipt's request id and maps only this statement's 57014 statement timeout to the terminal, non-transient `checkpoint_validation_timeout`. `readRequestIndexStates` reads each index as valid, missing, INVALID or building (Postgres `pg_stat_progress_create_index`); `formatCheckpointTimeoutHint` / `checkpointTimeoutHint` is the one formatter for the three-state hint and the filled retry (`gbrain sync --source <id> --no-pull --retry-failed` plus the cursor-selecting options the checkpoint intent records in `syncOptions` and the saved processing flags), used by the sync summary and `get_write_request`. Tests: `test/persistence-sync-checkpoint-validation.test.ts`, `test/e2e/persistence-request-indexes-postgres.test.ts`.- `src/core/persistence/noop-kernel.ts` — the #5470 no-op kernel. `inspectUnchanged` takes a preparer's `PreparedMutation` for an unadmitted `screeningRequest` and returns `contentUnchanged`, `projectionWorkRequired` (safe-chunk fence, text projection behind the knowledge revision, embedded page without a contextual mode), `metadataWorkRequired` (source path) and `observedRevision`; bound pages also need local file bytes equal to the serialized page. Callers run the preparer's own `validate` before counting a skip. An optional `waive` list (#5751) lets a caller skip two admit reasons its no-op publication can never resolve, a pending contextual-mode stamp and file bytes that differ from the prepared content (never a missing file); the result lists each waiver applied in `waived`; only managed working-tree sync entries pass it. Used by connector sync, `import-mutations.ts`, and `sync-run.ts` (working-tree and company-profile entries; renames and overlays always admit). Tests: `test/noop-kernel-paths.test.ts`, `test/connector-wave3.test.ts`.- `src/core/persistence/sync-waivers.ts` — managed-sync no-op waivers (#5470, #5984). `waiveNoopEntry` screens a frozen, unadmitted entry: an unchanged import (`unchangedSyncImport`, moved here from `sync-run.ts`, with the #5751 working-tree kernel waivers) or a delete whose page is already soft-deleted at the entry's frozen `expected_revision` with its file absent (never an unowned deletion or a rename). A candidate runs `validateSyncAuthority` first (a revoked grant throws before any waiver), then commits in one transaction with a fixed lock order: page guard (`lockPageKeys`), then the managed-sync cursor row `FOR UPDATE`; it re-reads the snapshot (and, for deletes, the origin and file absence) and refuses while `UNFINISHED_PAGE_REQUEST_SQL` finds an unfinished request for the page by slug, page id or a `renameFrom` naming it. That lookup is three `LIMIT 1` branches served by `persistence_requests_pending`, `persistence_requests_recovery` and the database-only pending index (EXPLAIN pinned in `test/persistence-managed-sync.test.ts`). A cursor that moved meanwhile is adopted instead of waived again, so `waived` counts only increment in the winning transaction. `GBRAIN_SYNC_WAIVE_NOOP=0` admits every entry. Tests: `test/persistence-managed-sync.test.ts` (#5984 waiver cases), `test/persistence-sync-legacy-files-5751.test.ts`.-- `src/core/persistence/accepted-pending.ts` — `acceptedPendingReceipt(error)`: the shared test for an accepted, not yet committed write, used by managed atom publication, extract_atoms, managed import and the connector budget.+- `src/core/persistence/accepted-pending.ts` — `acceptedPendingReceipt(error)`: the shared test for an accepted, not yet committed write, used by managed atom publication, extract_atoms, managed import and the connector budget. `publicationHold(error)` returns `pending` for such a receipt or `contention` for an OperationError `storage_error` with detail `database_contention` and no receipt (admission rolled back, nothing recorded), else null — never from a message, a terminal receipt, a contention error carrying a receipt or a permission refusal; `publishOrHold(fn)` runs one publication and returns null on commit, the hold when there is one, and rethrows anything else. Used by the patterns, drift and synthesize dream phases.- `src/core/persistence/connector-checkpoint-migration.ts` — migration 176 and orphan cleanup. The newest committed checkpoint receipt per source incarnation (found by slug, so a compacted one is still seen and re-walks) is copied to the stable key with `INSERT … ON CONFLICT DO NOTHING`; state rows are seeded; the cutoff is stored in `op_checkpoints` (`op=managed-connector-migration`, fingerprint `v2-cutoff`, excluded from the checkpoint purge). `orphanConnectorCheckpoints` keeps rows touched after the start, rows any registered source (archived included) can load, and rows referenced by a non-terminal request or a pending set; timestamps bind as text. `gbrain repair connector-checkpoints` (`src/core/repair/connector-checkpoints.ts`) and the `connector_checkpoints` doctor check reuse it with a 7-day floor. `connector-reset.ts` guards `gbrain sync --reset-checkpoint` to connector sources.- `src/core/persistence/fault-points.ts` — named crash seams for the persistence gate. `faultPoint(point, detail)` is a no-op unless a gate worker installed a hook with `installFaultHook`; production never does. Seams: `publication:<boundary>` (the five `PublicationHooks.boundary` names, routed through `withFaultPoints` in `publishMutation`), `effect:<kind>:mid` for every `EffectKind` in `completeEffect` (after the side effect, before its completion is recorded; `EFFECT_FAULT_POINTS` is a `Record<EffectKind, FaultPoint>`), `effect_recovery:before_clear` (`effect-recovery.ts`), `publication_recovery:before_clear` (`recoverPublication`), `sync:mid_checkpoint` (after each committed cursor step in `sync-run.ts` `saveCursor`) and `consumer:prepared` (between preparing a claimed request and publishing it). Used by `scripts/persistence/crash-robot.ts`.- `src/core/persistence/graduation-target.ts` — engine graduation target side. `resolveTargetRoutes` reads the URL from `--url` or the `--url-env` variable and resolves the DDL route once (explicit `GBRAIN_DIRECT_DATABASE_URL`, else the Supabase direct derivation, else the main URL); `connectTargetEngines` hands that route to the connection manager as an explicit override, so no session-pooler fallback is chosen for the run. `targetIdentity` hashes host, port, database and user, never the password; `redactTargetUrl` is the only display form. `probeTarget` runs read-only probes in `BEGIN READ ONLY` sessions on both routes (server version, `vector` with halfvec, CREATE privilege, `session_replication_role` permission inside a savepoint, table ownership, seed-only emptiness, existing embedding columns, the role's superuser and BYPASSRLS standing and the auto-RLS event trigger and its function owner); `targetProbeBlockers` (non-superuser targets get the exact SQL a DBA runs for `vector`, BYPASSRLS and the event trigger) and `assertTargetReachable` turn a probe into plan blockers and typed refusals. `crossCheckRoutes` proves both routes reach one database with a transaction-scoped advisory lock keyed by a fresh nonce, read back from `pg_locks` through the other route. Tests: `test/graduation-target.test.ts`.diff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsvindex 9667a37fb0..33d2344512 100644--- a/scripts/serial-files.tsv+++ b/scripts/serial-files.tsv@@ -83,7 +83,6 @@ test/cycle-lock-release-diagnostic.serial.test.ts R1 R1: mutates process.env (GBtest/cycle-lock-steal.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_CYCLE_LOCK_REFRESH_MS)test/cycle-patterns-completed-outcome.serial.test.ts R2 R2: mock.module(../src/core/ai/gateway.ts, ../src/core/cycle/synthesize.ts, ../src/core/minions/wait-for-completion.ts) replaces modules for every file in the processtest/cycle-patterns-evidence-gate.serial.test.ts R2 R2: mock.module(../src/core/ai/gateway.ts, ../src/core/cycle/synthesize.ts, ../src/core/minions/wait-for-completion.ts) replaces modules for every file in the process-test/cycle-publication-deferral.serial.test.ts R2 R2: mock.module replaces paid child and maintenance publication boundaries for every file in the processtest/cycle-pglite-lock-ordering.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)test/cycle-start-recovery-throw.serial.test.ts R2 R2: mock.module(../src/core/minions/queue.ts) replaces modules for every file in the processtest/cycle/cycle-sync-uncommitted-warn.serial.test.ts R2 R2: mock.module(../../src/commands/sync.ts) replaces modules for every file in the process@@ -125,6 +124,7 @@ test/doctor-revision-backfill-journey.serial.test.ts global-state global-state:test/dream-drain-failure-summary.serial.test.ts R2 R2: mock.module(../src/core/cycle/extract-atoms-drain.ts) replaces modules for every file in the processtest/dream-owner-id-threading.serial.test.ts R2 R2: mock.module(../src/core/cycle.ts) replaces modules for every file in the processtest/dream-postgres.serial.test.ts global-state global-state: spyOn process.exit, console.error+test/dream-publication-hold.serial.test.ts R2 R2: mock.module(../src/core/ai/gateway.ts, ../src/core/cycle/synthesize-concepts.ts, ../src/core/cycle/synthesize.ts, ../src/core/persistence/prepared-maintenance.ts, ../src/core/minions/wait-for-completion.ts) replaces modules for every file in the processtest/dream-synthesize-chunking.serial.test.ts R1 R1: mutates process.env (ANTHROPIC_API_KEY)test/embed-backfill-cli-admission.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; R4: PGLiteEngine without an afterAll disconnect; patches process stdout/stderr/consoletest/embed-exit-code-3037.serial.test.ts global-state global-state: binds local servers/portsdiff --git a/src/core/cycle/drift.ts b/src/core/cycle/drift.tsindex 7cff261fff..d06a66c120 100644--- a/src/core/cycle/drift.ts+++ b/src/core/cycle/drift.ts@@ -31,7 +31,7 @@ import type { DreamPhaseResult } from './auto-think.ts';import { maintenancePreflight, publishMaintenancePage } from '../persistence/prepared-maintenance.ts';import { serializeMarkdown } from '../markdown.ts';import { maintenanceTransaction } from '../persistence/attribution.ts';-import { maintenancePublicationDeferral } from './publication-deferral.ts';+import { publishOrHold, type PublicationHold } from '../persistence/accepted-pending.ts';export interface DriftPhaseOpts {brainDir?: string;@@ -363,7 +363,7 @@ export async function runPhaseDrift(const driftedCount = judged.filter(j => j.verdict.drifted).length;let reportSlug: string | undefined;- let publicationDeferred: 'pending' | 'contention' | null = null;+ let reportHold: PublicationHold | null = null;if (judged.length > 0) {reportSlug = `reports/drift-${cycleDate}`;// Report-only v1: the report page is the ONLY write this phase makes.@@ -372,14 +372,12 @@ export async function runPhaseDrift(// upsert the same slug).if (maintenance) {const snapshot = await engine.readPageSnapshot(reportSlug, { sourceId: 'default' });- try {- await publishMaintenancePage(engine, maintenance, reportSlug, serializeMarkdown({ report_type: 'drift' }, buildReportBody(judged, config, modelId), '',- { type: 'note', title: `Drift report ${cycleDate}`, tags: [] }), { expectedRevision: snapshot?.revision ?? null, file: false });- } catch (error) {- publicationDeferred = maintenancePublicationDeferral(error);- if (!publicationDeferred) throw error;- reportSlug = undefined;- }+ const report = serializeMarkdown({ report_type: 'drift' }, buildReportBody(judged, config, modelId), '',+ { type: 'note', title: `Drift report ${cycleDate}`, tags: [] });+ // #6052: a held report is not on the page yet, so it is neither linked nor counted as written.+ reportHold = await publishOrHold(() => publishMaintenancePage(engine, maintenance, reportSlug!, report,+ { expectedRevision: snapshot?.revision ?? null, file: false }));+ if (reportHold) reportSlug = undefined;} else {await maintenanceTransaction(engine, tx => tx.putPage(reportSlug!, {type: 'note',@@ -393,7 +391,8 @@ export async function runPhaseDrift(const detail =`judged ${judged.length}/${candidates.length} candidates: ${driftedCount} drifted` +(reportSlug ? ` → ${reportSlug}` : '') +- (publicationDeferred ? ` (publication deferred: ${publicationDeferred === 'pending' ? 'accepted report still publishing' : 'admission contended; retry next cycle'})` : '') ++ (reportHold === 'pending' ? ' (report accepted, still publishing)' : '') ++ (reportHold === 'contention' ? ' (report not admitted: database contention; the next cycle writes it)' : '') +(budgetExhausted ? ' (budget exhausted)' : '') +(failed > 0 ? ` (${failed} judge failure(s))` : '') +`. Cumulative cost: $${meter.totalSpent.toFixed(4)} / $${config.budgetUsd.toFixed(2)}` +@@ -402,7 +401,7 @@ export async function runPhaseDrift(return {name: 'drift',status: judged.length > 0- ? (budgetExhausted || failed > 0 || publicationDeferred ? 'partial' : 'complete')+ ? (budgetExhausted || failed > 0 || reportHold !== null ? 'partial' : 'complete')// Zero judged: budget capped before any judge ran → partial (capped,// not broken); otherwise every judge call failed → failed.: (budgetExhausted ? 'partial' : 'failed'),@@ -412,8 +411,8 @@ export async function runPhaseDrift(judged: judged.length,drifted: driftedCount,failed,- reports_written: reportSlug ? 1 : 0,- publish_deferred: publicationDeferred ? 1 : 0,+ reports_written: Number(reportSlug !== undefined),+ publish_deferred: Number(reportHold !== null),},duration_ms: Date.now() - start,};diff --git a/src/core/cycle/patterns.ts b/src/core/cycle/patterns.tsindex 9491fd8853..bda339ef86 100644--- a/src/core/cycle/patterns.ts+++ b/src/core/cycle/patterns.ts@@ -48,7 +48,7 @@ import { normalizeModelId } from '../model-id.ts';import { throwIfAborted } from '../abort-check.ts';import { resolveCycleDate } from './cycle-date.ts';import { dreamBreakerRefusal, loadDreamBreaker } from './dream-breaker.ts';-import { maintenancePublicationDeferral } from './publication-deferral.ts';+import { publishOrHold } from '../persistence/accepted-pending.ts';export interface PatternsPhaseOpts {brainDir: string;@@ -362,19 +362,20 @@ export async function runPhasePatterns(throwIfAborted(opts.signal, '[dream] patterns output');const writtenRefs = await collectChildPutPageSlugs(engine, [job.id], cycleSourceId);- const { quoteVerify, deferred: deferredSlugs } = await stampPatternOutputs(engine, maintenance, writtenRefs, reflections, config, cycleSourceId, cycleDate, opts.signal);- const finalizedRefs = writtenRefs.filter(ref => !deferredSlugs.has(ref.slug));- const reverseWriteCount = maintenance ? (finalizedRefs.length ? await verifyMaintenanceOutputs(engine, maintenance, finalizedRefs) : 0)+ // #6052: `finalized` leaves out outputs whose managed publication is held (pending or contended); `held` counts them.+ const { quoteVerify, finalized, held } = await stampPatternOutputs(engine, maintenance, writtenRefs, reflections, config, cycleSourceId, cycleDate, opts.signal);+ const reverseWriteCount = maintenance ? await verifyMaintenanceOutputs(engine, maintenance, finalized): await reverseWriteRefs(engine, opts.brainDir, writtenRefs, cycleSourceId, opts.signal);-- const details = patternOutputDetails(reflections.length, finalizedRefs.length, reverseWriteCount, outcome, job.id, deferredSlugs.size, quoteVerify);+ const details = { reflections_considered: reflections.length, patterns_written: finalized.length,+ ...(quoteVerify ? { quote_verify: quoteVerify } : {}), reverse_write_count: reverseWriteCount, publish_deferred: held,+ child_outcome: outcome, job_id: job.id };// #2782: the phase status must reflect the child outcome. Pre-fix this// returned status:ok even when the subagent timed out (e.g. no// subagent-capable worker slot free for the whole wait window) and zero// pattern pages were written — a silent no-op for days.if (outcome !== 'completed') {- if (finalizedRefs.length === 0) {+ if (finalized.length === 0) {return {phase: 'patterns',status: 'fail',@@ -396,15 +397,13 @@ export async function runPhasePatterns(phase: 'patterns',status: 'warn',duration_ms: 0,- summary: `${finalizedRefs.length} pattern page(s) written but subagent job ${job.id} ended '${outcome}'`,+ summary: `${finalized.length} pattern page(s) written but subagent job ${job.id} ended '${outcome}'`,details,};}-- if (deferredSlugs.size) {- return { phase: 'patterns', status: 'warn', duration_ms: 0,- summary: `${finalizedRefs.length} pattern page(s) finalized; ${deferredSlugs.size} publication(s) deferred (writer busy); retry next cycle`, details };- }+ // A held output is unfinished: warn and leave the evidence watermark unstamped so the next cycle retries.+ if (held > 0) return { phase: 'patterns', status: 'warn', duration_ms: 0, details,+ summary: `${finalized.length} pattern page(s) written; ${held} publication(s) held by the writer (pending or contended), retried next cycle` };// #4879: stamp the EVIDENCE watermark (not now()) only on a completed// child — fail/warn/timeout above must retry next tick. A reflection@@ -442,12 +441,6 @@ export async function runPhasePatterns(// ── Config ────────────────────────────────────────────────────────────-function patternOutputDetails(reflections: number, finalized: number, reverseWrites: number, outcome: MinionJobStatus | 'timeout',- jobId: number, deferred: number, quoteVerify: { pages: number; quarantined: number; repaired: number } | null) {- return { reflections_considered: reflections, patterns_written: finalized, ...(quoteVerify ? { quote_verify: quoteVerify } : {}),- reverse_write_count: reverseWrites, child_outcome: outcome, job_id: jobId, publish_deferred: deferred };-}-interface PatternsConfig {enabled: boolean;lookbackDays: number;@@ -642,37 +635,31 @@ When done, briefly list the pattern slugs you wrote/updated in your final messag*//*** Quote-ground the pattern outputs (and pages a crashed run left unverified), then stamp provenance on the- * outputs. Returns the grounding counts (null when dream.quote_verify is off) and the slugs whose managed- * publication was deferred (pending or contended), which are neither stamped nor counted as finalized.+ * outputs. Returns the grounding counts (null when dream.quote_verify is off), the written refs whose managed+ * publications all landed, and the number of pages whose publication is held for a later cycle.*/async function stampPatternOutputs(engine: BrainEngine, maintenance: MaintenanceAuthority | null, written: Array<{ slug: string; source_id: string }>,reflections: ReflectionRef[], config: { outputSlugPrefix: string; sourceSlugPrefix: string }, sourceId: string, cycleDate: string, signal?: AbortSignal) {- const deferred = new Set<string>();- const quoteVerify = await groundPatternPages(engine, maintenance, written, reflections, config.outputSlugPrefix, sourceId, cycleDate, signal, deferred);- const outputs = written.filter(ref => ref.slug.startsWith(`${config.outputSlugPrefix}/`) && !deferred.has(ref.slug));- for (const slug of await stampProvenance(engine, maintenance, outputs, cycleDate, config.sourceSlugPrefix, sharedSeat(reflections), signal)) deferred.add(slug);- return { quoteVerify, deferred };+ const heldSlugs = new Set<string>();+ const quoteVerify = await groundPatternPages(engine, maintenance, written, reflections, config.outputSlugPrefix, sourceId, cycleDate, signal, heldSlugs);+ await stampProvenance(engine, maintenance, written.filter(ref => ref.slug.startsWith(`${config.outputSlugPrefix}/`)), cycleDate, config.sourceSlugPrefix, sharedSeat(reflections), signal, heldSlugs);+ // Holds are recorded for this cycle's source only, so a ref in any other source is never excused from verification.+ const finalized = written.filter(ref => ref.source_id !== sourceId || !heldSlugs.has(ref.slug));+ return { quoteVerify, finalized, held: heldSlugs.size };}async function stampProvenance(engine: BrainEngine, maintenance: MaintenanceAuthority | null,- refs: Array<{ slug: string; source_id: string }>, cycleDate: string, sourceSlugPrefix: string, seat: string | undefined, signal?: AbortSignal): Promise<Set<string>> {+ refs: Array<{ slug: string; source_id: string }>, cycleDate: string, sourceSlugPrefix: string, seat: string | undefined, signal: AbortSignal | undefined,+ heldSlugs: Set<string>): Promise<void> {const reason = `derived from reflections under ${sourceSlugPrefix}/; raw traces live on the cited reflection pages`;// A pattern earns a seat only while its reflections share one, so a pattern without one drops a seat an earlier run stamped.- const deferred = new Set<string>();- if (!maintenance) {- await stampDreamProvenance(engine, refs.map(ref => ({ ...ref, raw_trace_exempt_reason: reason, seat: seat ?? null })), cycleDate, signal);- return deferred;- }+ if (!maintenance) return stampDreamProvenance(engine, refs.map(ref => ({ ...ref, raw_trace_exempt_reason: reason, seat: seat ?? null })), cycleDate, signal);for (const ref of refs) {throwIfAborted(signal, '[dream] patterns provenance');- try {- await stampMaintenancePage(engine, maintenance, ref.slug, cycleDate, undefined, reason, seat ?? null);- } catch (error) {- if (!maintenancePublicationDeferral(error)) throw error;- deferred.add(ref.slug);- }+ // A page whose grounding publish is held must not be stamped over the pending revision.+ if (heldSlugs.has(ref.slug)) continue;+ if (await publishOrHold(() => stampMaintenancePage(engine, maintenance, ref.slug, cycleDate, undefined, reason, seat ?? null))) heldSlugs.add(ref.slug);}- return deferred;}// ── Quote grounding ──────────────────────────────────────────────────@@ -683,10 +670,12 @@ async function stampProvenance(engine: BrainEngine, maintenance: MaintenanceAuth* its evidence). A failing claim unit leaves the body for frontmatter* `unverified_claims`; `quote_verified_at` marks a checked page, so a page a* crashed run left behind is verified by the next run. Kill switch:- * dream.quote_verify (default on). Returns null when disabled.+ * dream.quote_verify (default on). Returns null when disabled. With `heldSlugs`+ * a managed publish that is pending or contended (publicationHold) is recorded+ * there and the loop moves on; without it every publish error propagates.*/export async function groundPatternPages(engine: BrainEngine, maintenance: MaintenanceAuthority | null, refs: Array<{ slug: string; source_id: string }>,- reflections: ReflectionRef[], outputSlugPrefix: string, sourceId: string, cycleDate: string, signal?: AbortSignal, deferred?: Set<string>):+ reflections: ReflectionRef[], outputSlugPrefix: string, sourceId: string, cycleDate: string, signal?: AbortSignal, heldSlugs?: Set<string>):Promise<{ pages: number; quarantined: number; repaired: number } | null> {const { dreamQuoteVerifyEnabled, groundSource, verifyBody } = await import('./synthesize-verify.ts');if (!await dreamQuoteVerifyEnabled(engine)) return null;@@ -720,12 +709,9 @@ export async function groundPatternPages(engine: BrainEngine, maintenance: Maintconst content = serializePageToMarkdown(page, snapshot.tags);if (maintenance) {const { publishMaintenancePage } = await import('../persistence/prepared-maintenance.ts');- try {- await publishMaintenancePage(engine, maintenance, slug, content, { expectedRevision: snapshot.revision });- } catch (error) {- if (!deferred || !maintenancePublicationDeferral(error)) throw error;- deferred.add(slug);- }+ const publish = () => publishMaintenancePage(engine, maintenance, slug, content, { expectedRevision: snapshot.revision });+ if (!heldSlugs) await publish();+ else if (await publishOrHold(publish)) heldSlugs.add(slug);} else {const [{ importFromContent }, { isAvailable }] = await Promise.all([import('../import-file.ts'), import('../ai/gateway.ts')]);await importFromContent(engine, slug, content, { noEmbed: !isAvailable('embedding'), sourceId });diff --git a/src/core/cycle/publication-deferral.ts b/src/core/cycle/publication-deferral.tsdeleted file mode 100644index 82dc20c772..0000000000--- a/src/core/cycle/publication-deferral.ts+++ /dev/null@@ -1,13 +0,0 @@-import { OperationError } from '../ops/contract.ts';-import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';--/** Publication waits and confirmed admission rollback are not dream failures.- * Never infer deferral from a message, a generic storage error, or a terminal- * receipt: those must still reach the phase's normal failure path.- */-export function maintenancePublicationDeferral(error: unknown): 'pending' | 'contention' | null {- if (acceptedPendingReceipt(error)) return 'pending';- if (error instanceof OperationError && error.code === 'storage_error' &&- error.detail === 'database_contention' && !error.writeRequest) return 'contention';- return null;-}diff --git a/src/core/cycle/synthesize-postprocess.ts b/src/core/cycle/synthesize-postprocess.tsindex ff21956bfa..1dc3153719 100644--- a/src/core/cycle/synthesize-postprocess.ts+++ b/src/core/cycle/synthesize-postprocess.ts@@ -4,13 +4,13 @@ import { serializePageToMarkdown } from '../markdown.ts';import type { Action } from '../agent-output.ts';import { opError } from '../ops/contract.ts';import { readFix } from '../ops/op-fix.ts';+import { publicationHold } from '../persistence/accepted-pending.ts';import { authorizeStoredRequest } from '../persistence/authority.ts';import { digest } from '../persistence/digest.ts';import { getWriteRequest } from '../persistence/journal.ts';import type { WriteRequest } from '../persistence/model.ts';import { publishMaintenancePage, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';import { writeResponse } from '../persistence/service.ts';-import { maintenancePublicationDeferral } from './publication-deferral.ts';import type { PhaseResult } from '../cycle.ts';import type { DiscoveredTranscript } from './transcript-discovery.ts';import { emptyQuoteVerifyStats, groundSource, isDreamOwnedPage, resolveVerifyPrior, verifyDreamPage, type GroundedSource, type GroundingPass } from './synthesize-verify.ts';@@ -127,7 +127,7 @@ export async function postprocessManagedSynthesis(* other error is rethrown. A contended publish writes one stderr line naming it.*/export function deferPublishOrThrow(error: unknown, what: string): void {- const deferral = maintenancePublicationDeferral(error);+ const deferral = publicationHold(error);if (!deferral) throw error;if (deferral === 'contention') {process.stderr.write(`[dream] synthesize: ${what} deferred, write admission blocked by database contention; the next cycle admits it\n`);diff --git a/src/core/persistence/accepted-pending.ts b/src/core/persistence/accepted-pending.tsindex 8ef846aed5..8e4cbfe916 100644--- a/src/core/persistence/accepted-pending.ts+++ b/src/core/persistence/accepted-pending.ts@@ -11,3 +11,34 @@ export function acceptedPendingReceipt(error: unknown): WriteReceipt | null {if (!(error instanceof OperationError) || error.code !== 'write_pending' || !error.writeRequest) return null;return isTerminalWriteState(error.writeRequest.state) ? null : error.writeRequest;}++/** Why a maintenance publication may finish on a later run instead of failing this one (#6052). */+export type PublicationHold = 'pending' | 'contention';++/**+ * #6052: two publication failures are progress, not phase failures. An+ * accepted, non-terminal receipt still publishes under its request id; an+ * admission that ran out of budget on database contention (admission-retry.ts)+ * confirmed no receipt and recorded nothing, so the next run re-admits the same+ * intent. Read from structured fields of a real OperationError only — never+ * from a message, a generic storage_error, a contention error that carries a+ * receipt, a terminal receipt or a permission refusal.+ */+export function publicationHold(error: unknown): PublicationHold | null {+ if (acceptedPendingReceipt(error)) return 'pending';+ if (error instanceof OperationError && error.code === 'storage_error' && error.detail === 'database_contention'+ && error.writeRequest == null) return 'contention';+ return null;+}++/** Run one publication: null once it commits, its hold when it can finish later; every other error is rethrown. */+export async function publishOrHold(publish: () => Promise<unknown>): Promise<PublicationHold | null> {+ try {+ await publish();+ } catch (error) {+ const hold = publicationHold(error);+ if (hold === null) throw error;+ return hold;+ }+ return null;+}diff --git a/test/cycle-publication-deferral.serial.test.ts b/test/cycle-publication-deferral.serial.test.tsdeleted file mode 100644index 206ca75a17..0000000000--- a/test/cycle-publication-deferral.serial.test.ts+++ /dev/null@@ -1,136 +0,0 @@-import { afterAll, beforeAll, beforeEach, describe, expect, mock, test } from 'bun:test';-import { mkdtempSync, rmSync } from 'node:fs';-import { tmpdir } from 'node:os';-import { join } from 'node:path';-import { PGLiteEngine } from '../src/core/pglite-engine.ts';-import { OperationError } from '../src/core/ops/contract.ts';-import { resetPgliteState } from './helpers/reset-pglite.ts';-import { retryWriteAdmission } from '../src/core/persistence/admission-retry.ts';--// Only the paid child and maintenance boundary are replaced. Phase selection,-// evidence, jobs, watermark and drift report construction use the real engine.-let publishError: unknown;-let stampCalls = 0;-let publishCalls = 0;-let verified = 0;-let childStatus = 'completed';-const maintenance = { writer: { sourceId: 'default' } };-mock.module('../src/core/ai/gateway.ts', () => ({ probeChatModel: () => ({ ok: true }) }));-mock.module('../src/core/cycle/synthesize-concepts.ts', () => ({ resolveSynthMaxOutputTokens: () => 4096 }));-mock.module('../src/core/persistence/prepared-maintenance.ts', () => ({- maintenancePreflight: async () => maintenance,- stampMaintenancePage: async () => { stampCalls++; if (publishError) throw publishError; },- publishMaintenancePage: async () => { publishCalls++; if (publishError) throw publishError; return {}; },- verifyMaintenanceOutputs: async () => { verified++; return 1; },-}));-mock.module('../src/core/cycle/synthesize.ts', () => ({- loadAllowedSlugPrefixes: async () => ['wiki/personal/patterns/*'],- loadOutputRoot: async () => 'wiki',- runSubagentsInline: async () => undefined,-}));-mock.module('../src/core/minions/wait-for-completion.ts', () => ({- TimeoutError: class TimeoutError extends Error {},- waitForCompletionRenewing: async (_queue: unknown, jobId: number, opts?: { renew?: () => Promise<void> }) => {- await opts?.renew?.();- await engine.executeRaw(`INSERT INTO subagent_tool_executions (job_id, message_idx, tool_use_id, tool_name, input, output, status)- VALUES ($1, 0, 'fixture-tool', 'brain_put_page', '{"slug":"wiki/personal/patterns/example"}'::jsonb, '{}'::jsonb, 'complete')`, [jobId]);- return { id: jobId, status: childStatus };- },-}));-const { runPhasePatterns } = await import('../src/core/cycle/patterns.ts');-const { runPhaseDrift } = await import('../src/core/cycle/drift.ts');-let engine: PGLiteEngine;-let schemaVersion: string;-const scratch = mkdtempSync(join(tmpdir(), 'gbrain-publication-deferral-'));-const STAMP_KEY = 'dream.patterns.last_evidence_ts';-beforeAll(async () => {- engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();- schemaVersion = (await engine.getConfig('version'))!;-}, 60_000);-afterAll(async () => { await engine.disconnect(); rmSync(scratch, { recursive: true, force: true }); });-beforeEach(async () => {- await resetPgliteState(engine);- await engine.setConfig('version', schemaVersion);- publishError = undefined; stampCalls = 0; publishCalls = 0; verified = 0; childStatus = 'completed';- await engine.setConfig('models.dream.patterns', 'anthropic:claude-sonnet-4-6');- await engine.setConfig('models.drift', 'anthropic:claude-sonnet-4-6');- for (let i = 0; i < 3; i++) await engine.putPage(`wiki/personal/reflections/example-${i}`, {- type: 'note', title: `Reflection ${i}`, compiled_truth: 'A recurring synthetic theme.',- });- const page = await engine.putPage('people/alice-example', { type: 'person', title: 'Alice Example', compiled_truth: 'Example person.' });- await engine.addTakesBatch([{ page_id: page.id, row_num: 1, claim: 'Careful operator', kind: 'take', holder: 'brain', weight: 0.6 }]);- await engine.addTimelineEntriesBatch([{ slug: page.slug, date: '2030-01-15', source: 'meeting', summary: 'Changed roles' }]);-});-async function contention(): Promise<unknown> {- try { await retryWriteAdmission('00000000-0000-4000-a000-000000000001', async () => { throw Object.assign(new Error('synthetic SQL lock'), { code: '55P03' }); }, 0); }- catch (error) { return error; }- throw new Error('Admission must fail');-}-function pending(terminal = false): OperationError {- const error = new OperationError('write_pending', 'Accepted publication is pending.', 'Read its receipt.');- error.writeRequest = { request_id: '00000000-0000-4000-a000-000000000002',- state: terminal ? 'failed' : 'queued', retry_after_ms: terminal ? null : 1000 };- return error;-}-const runDrift = () => runPhaseDrift(engine, { dryRun: false, forceEnabled: true, cycleDate: '2030-01-20',- auditPath: join(scratch, 'drift.jsonl'), judge: async () => ({ drifted: true, confidence: 0.9, reasoning: 'Changed evidence.' }) });--describe('managed dream publication deferral (#6052)', () => {- for (const fault of ['contention', 'pending'] as const) {- test(`patterns defers ${fault} without advancing evidence or verifying unfinished output`, async () => {- publishError = fault === 'contention' ? await contention() : pending();- const result = await runPhasePatterns(engine, { brainDir: scratch, dryRun: false, once: true });- expect(result.error).toBeUndefined();- expect(result.status).toBe('warn');- expect(result.details.publish_deferred).toBe(1);- expect(result.details.patterns_written).toBe(0);- expect(result.details.child_outcome).toBe('completed');- expect(result.error).toBeUndefined();- expect(verified).toBe(0);- expect(await engine.getConfig(STAMP_KEY)).toBeNull();- publishError = undefined;- const resumed = await runPhasePatterns(engine, { brainDir: scratch, dryRun: false, once: true });- expect(resumed.status).toBe('ok');- expect(await engine.getConfig(STAMP_KEY)).not.toBeNull();- });- test(`drift defers ${fault} without claiming a published report`, async () => {- publishError = fault === 'contention' ? await contention() : pending();- const result = await runDrift();- expect(result.status).toBe('partial');- expect(result.totals?.publish_deferred).toBe(1);- expect(result.totals?.reports_written).toBe(0);- expect(result.totals?.judged).toBe(1);- expect(result.detail).toContain('publication deferred');- expect(result.detail).not.toContain(' → reports/');- expect(await engine.getPage('reports/drift-2030-01-20')).toBeNull();- });- }- test('patterns defers a pending quote-grounding publish and skips stamping that page', async () => {- await engine.putPage('wiki/personal/patterns/example', { type: 'note', title: 'Example pattern', compiled_truth: 'A recurring synthetic theme.' });- publishError = pending();- const result = await runPhasePatterns(engine, { brainDir: scratch, dryRun: false, once: true });- expect(result.status).toBe('warn');- expect(result.details.publish_deferred).toBe(1);- expect(result.details.patterns_written).toBe(0);- expect(publishCalls).toBe(1);- expect(stampCalls).toBe(0);- expect(verified).toBe(0);- expect(await engine.getConfig(STAMP_KEY)).toBeNull();- });- test('a failed patterns child remains a failure even if its partial output is pending', async () => {- childStatus = 'failed'; publishError = pending();- const result = await runPhasePatterns(engine, { brainDir: scratch, dryRun: false, once: true });- expect(result.status).toBe('fail');- expect(result.error?.code).toBe('PATTERNS_CHILD_FAILED');- expect(await engine.getConfig(STAMP_KEY)).toBeNull();- });- for (const error of [new OperationError('storage_error', 'A real storage failure.', ''),- new OperationError('permission_denied', 'Revoked writer.', ''), pending(true),- new OperationError('write_pending', 'No accepted receipt.', '')]) {- test(`does not defer ${error.message}`, async () => {- publishError = error;- expect((await runPhasePatterns(engine, { brainDir: scratch, dryRun: false, once: true })).status).toBe('fail');- await expect(runDrift()).rejects.toBe(error);- });- }-});diff --git a/test/dream-publication-hold.serial.test.ts b/test/dream-publication-hold.serial.test.tsnew file mode 100644index 0000000000..fe844032e5--- /dev/null+++ b/test/dream-publication-hold.serial.test.ts@@ -0,0 +1,215 @@+/**+ * #6052: a managed dream publication that is accepted-but-pending, or whose+ * admission rolled back under database contention, is held for a later cycle+ * instead of failing the patterns or drift phase. Anything else still fails.+ *+ * Serial (R2): mock.module replaces the paid child, the chat gateway and the+ * managed publication boundary (prepared-maintenance.ts) for the whole process.+ * The engine, job queue, evidence watermark, take/timeline evidence, drift+ * candidate selection, report building and the hold classifier are real; the+ * contention error is produced by the real admission retry.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, mock, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { OperationError } from '../src/core/ops/contract.ts';+import { retryWriteAdmission } from '../src/core/persistence/admission-retry.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';++const PATTERN_A = 'wiki/personal/patterns/acme-example-rhythm';+const PATTERN_B = 'wiki/personal/patterns/acme-example-drift';+const WATERMARK = 'dream.patterns.last_evidence_ts';++/** Per-slug failure each mocked publication throws; a slug absent here publishes. */+const failures = new Map<string, unknown>();+const calls = { publish: [] as string[], stamp: [] as string[], verify: [] as string[][] };+let childWrites: string[] = [];+let childOutcome = 'completed';++const failFor = (slug: string) => {+ const error = failures.get(slug);+ if (error !== undefined) throw error;+};++mock.module('../src/core/ai/gateway.ts', () => ({ probeChatModel: () => ({ ok: true }) }));+mock.module('../src/core/cycle/synthesize-concepts.ts', () => ({ resolveSynthMaxOutputTokens: () => 2048 }));+mock.module('../src/core/cycle/synthesize.ts', () => ({+ loadAllowedSlugPrefixes: async () => ['wiki/personal/patterns/*'],+ loadOutputRoot: async () => 'wiki',+ runSubagentsInline: async () => undefined,+}));+mock.module('../src/core/persistence/prepared-maintenance.ts', () => ({+ maintenancePreflight: async () => ({ writer: { sourceId: 'default' } }),+ publishMaintenancePage: async (_engine: unknown, _authority: unknown, slug: string) => { calls.publish.push(slug); failFor(slug); return {}; },+ stampMaintenancePage: async (_engine: unknown, _authority: unknown, slug: string) => { calls.stamp.push(slug); failFor(slug); },+ verifyMaintenanceOutputs: async (_engine: unknown, _authority: unknown, refs: Array<{ slug: string }>) => {+ calls.verify.push(refs.map(ref => ref.slug));+ return refs.length;+ },+}));+mock.module('../src/core/minions/wait-for-completion.ts', () => ({+ TimeoutError: class TimeoutError extends Error {},+ waitForCompletionRenewing: async (_queue: unknown, jobId: number, opts?: { renew?: () => Promise<void> }) => {+ await opts?.renew?.();+ for (const [i, slug] of childWrites.entries()) {+ await engine.executeRaw(`INSERT INTO subagent_tool_executions (job_id, message_idx, tool_use_id, tool_name, input, output, status)+ VALUES ($1, $2, $3, 'brain_put_page', $4::text::jsonb, '{}'::jsonb, 'complete')`, [jobId, i, `write-${i}`, JSON.stringify({ slug })]);+ }+ return { id: jobId, status: childOutcome };+ },+}));++const { runPhasePatterns } = await import('../src/core/cycle/patterns.ts');+const { runPhaseDrift } = await import('../src/core/cycle/drift.ts');++let engine: PGLiteEngine;+let version: string;+const brainDir = mkdtempSync(join(tmpdir(), 'gbrain-publication-hold-'));++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ version = (await engine.getConfig('version'))!;+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+ rmSync(brainDir, { recursive: true, force: true });+});++beforeEach(async () => {+ await resetPgliteState(engine);+ await engine.setConfig('version', version);+ await engine.setConfig('models.dream.patterns', 'anthropic:claude-sonnet-4-6');+ await engine.setConfig('models.drift', 'anthropic:claude-sonnet-4-6');+ failures.clear();+ calls.publish = []; calls.stamp = []; calls.verify = [];+ childWrites = [PATTERN_A];+ childOutcome = 'completed';+ for (const day of ['01', '02', '03']) {+ await engine.putPage(`wiki/personal/reflections/2031-04-${day}`, { type: 'note', title: `Reflection ${day}`, compiled_truth: 'Weekly planning keeps slipping.' });+ }+ const person = await engine.putPage('people/alice-example', { type: 'person', title: 'Alice Example', compiled_truth: 'Placeholder person.' });+ await engine.addTakesBatch([{ page_id: person.id, row_num: 1, claim: 'Prefers async updates', kind: 'take', holder: 'brain', weight: 0.7 }]);+ await engine.addTimelineEntriesBatch([{ slug: person.slug, date: '2031-04-10', source: 'meeting', summary: 'Asked for a weekly sync' }]);+});++const pendingReceipt = (state = 'queued') => {+ const error = new OperationError('write_pending', 'Publication accepted.', 'Poll the receipt.');+ error.writeRequest = { request_id: '7a1c0d2e-0000-4000-8000-00000000c0de', state: state as never, retry_after_ms: state === 'queued' ? 500 : null };+ return error;+};++async function admissionContention(): Promise<unknown> {+ const lockTimeout = async () => { throw Object.assign(new Error('lock wait'), { code: '55P03' }); };+ return retryWriteAdmission('7a1c0d2e-0000-4000-8000-00000000beef', lockTimeout, 0).then(+ () => { throw new Error('admission unexpectedly succeeded'); },+ (error: unknown) => error,+ );+}++const patterns = () => runPhasePatterns(engine, { brainDir, dryRun: false, once: true });+const drift = () => runPhaseDrift(engine, {+ dryRun: false, forceEnabled: true, cycleDate: '2031-04-14', auditPath: join(brainDir, 'drift-audit.jsonl'),+ judge: async () => ({ drifted: true, confidence: 0.8, reasoning: 'Evidence moved.' }),+});++describe('patterns phase holds unfinished managed publications (#6052)', () => {+ test('a pending provenance stamp warns, skips verification of that page and leaves the watermark; the next cycle finishes', async () => {+ failures.set(PATTERN_A, pendingReceipt());+ const held = await patterns();+ expect(held.status).toBe('warn');+ expect(held.error).toBeUndefined();+ expect(held.details).toMatchObject({ patterns_written: 0, publish_deferred: 1, child_outcome: 'completed' });+ expect(calls.verify).toEqual([[]]);+ expect(await engine.getConfig(WATERMARK)).toBeNull();++ failures.clear();+ const next = await patterns();+ expect(next.status).toBe('ok');+ expect(next.details).toMatchObject({ patterns_written: 1, publish_deferred: 0 });+ expect(await engine.getConfig(WATERMARK)).not.toBeNull();+ });++ test('a contended grounding publish is not stamped and does not block a sibling page', async () => {+ childWrites = [PATTERN_A, PATTERN_B];+ for (const slug of childWrites) {+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: 'Planning slips every week.' });+ }+ failures.set(PATTERN_B, await admissionContention());+ const held = await patterns();+ expect(held.status).toBe('warn');+ expect(held.details).toMatchObject({ patterns_written: 1, publish_deferred: 1 });+ expect(calls.publish).toContain(PATTERN_B);+ expect(calls.stamp).toEqual([PATTERN_A]);+ expect(calls.verify).toEqual([[PATTERN_A]]);+ expect(await engine.getConfig(WATERMARK)).toBeNull();+ });++ test('a failed child with only held output is still a failure', async () => {+ childOutcome = 'failed';+ failures.set(PATTERN_A, pendingReceipt());+ const result = await patterns();+ expect(result.status).toBe('fail');+ expect(result.error?.code).toBe('PATTERNS_CHILD_FAILED');+ expect(await engine.getConfig(WATERMARK)).toBeNull();+ });+});++describe('drift phase holds an unfinished report (#6052)', () => {+ test('pending: partial, nothing counted as written, no report link', async () => {+ failures.set('reports/drift-2031-04-14', pendingReceipt('running'));+ const result = await drift();+ expect(result.status).toBe('partial');+ expect(result.totals).toMatchObject({ judged: 1, reports_written: 0, publish_deferred: 1 });+ expect(result.detail).toContain('report accepted, still publishing');+ expect(result.detail).not.toContain('→');+ });++ test('contention: partial, and the detail says the next cycle writes it', async () => {+ failures.set('reports/drift-2031-04-14', await admissionContention());+ const result = await drift();+ expect(result.status).toBe('partial');+ expect(result.totals).toMatchObject({ reports_written: 0, publish_deferred: 1 });+ expect(result.detail).toContain('database contention');+ });++ test('control: a published report completes and is linked', async () => {+ const result = await drift();+ expect(result.status).toBe('complete');+ expect(result.totals).toMatchObject({ reports_written: 1, publish_deferred: 0 });+ expect(result.detail).toContain('→ reports/drift-2031-04-14');+ });+});++describe('errors that are not holds still fail both phases (#6052)', () => {+ const contentionWithReceipt = () => {+ const error = new OperationError('storage_error', 'Contended after admission.', 'Poll the receipt.');+ error.detail = 'database_contention';+ error.writeRequest = pendingReceipt().writeRequest;+ return error;+ };+ const cases: Array<[string, () => unknown]> = [+ ['permission_denied', () => new OperationError('permission_denied', 'Writer grant revoked.', '')],+ ['storage_error without contention detail', () => new OperationError('storage_error', 'Disk full.', '')],+ ['contention that already carries a receipt', contentionWithReceipt],+ ['write_pending with a terminal receipt', () => pendingReceipt('failed')],+ ['write_pending with no receipt', () => new OperationError('write_pending', 'No receipt.', '')],+ ['a plain Error naming database_contention', () => new Error('storage_error: database_contention')],+ ['a look-alike object that is not an OperationError', () => ({ code: 'write_pending', writeRequest: { state: 'queued' } })],+ ];+ for (const [label, make] of cases) {+ test(label, async () => {+ const error = make();+ failures.set(PATTERN_A, error);+ failures.set('reports/drift-2031-04-14', error);+ const result = await patterns();+ expect(result.status).toBe('fail');+ expect(await engine.getConfig(WATERMARK)).toBeNull();+ await expect(drift()).rejects.toBe(error);+ });+ }+});