Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(synthesis): defer publication at temporary outstanding write capacity (#6916)
time-attack2817ce5ca112
diff --git a/docs/architecture/key-files/core-cycle-continued.md b/docs/architecture/key-files/core-cycle-continued.mdindex 510ef7e8bf..10f4067407 100644--- a/docs/architecture/key-files/core-cycle-continued.md+++ b/docs/architecture/key-files/core-cycle-continued.md@@ -4,7 +4,7 @@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. `loadCommittedSynthesisOutputs` finds each child's committed output by canonicalizing the retained `brain_put_page` input (`parseWriteRequestId` for the request id, `journaledPageSlug` for the slug) before matching request id, source, incarnation, committed put_page, slug and revision (#6616); slug discovery (`collectChildPutPageSlugs`) and postprocessing share that set. 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`. #5575 I2: each output publishes with `derivation` from its transcript (`dream-taint.ts` `transcriptDerivation`; `meetingTranscriptsDir` in opts); a retained request replays the declaration it was admitted with. #6360: when the page moved after the child commit, a drift made only by committed local `managed_maintenance_page` requests (for example the next cycle's lint `created:` fix) over a body equal to the child's is adopted: the postprocess runs on the current snapshot under a request id that also binds that base revision (found again on replay among the later requests). Any other later write leaves the page alone as a `PostprocessConflict` (`withPostprocessConflicts`: phase `warn`, `details.postprocess_conflicts` with the read-only `gbrain get` fix); it is reported once (config `dream.synthesize.postprocess_conflicts`, 30-day memory) and does not block the cooldown stamp. #6757: the committed-outputs join (`COMMITTED_OUTPUT_REQUESTS_SQL`) compares `request_id` as a uuid within the source, served by `persistence_requests_request_id`. The phase loads it through `loadCommittedOutputsOrDefer`; a statement timeout there, or on an output's own `getWriteRequest`, defers the pass instead of failing it (`withPublishPending` with `details.postprocess_deferred`: phase warn, no cooldown stamp, no summary). Deferred and publish-pending outputs are carried by `synthesize-postprocess-deferral.ts` and finished by a later pass from the carried fields, with no child; `finishDeferredPostprocess` (run after the phase body by `runPhaseSynthesize`) finishes them when that pass returned before postprocessing. GBRA-130 A-4: outputs run as `ItemRun` items (`synthesize.postprocess`). A postprocess request that ended conflict, failed or cancelled, or whose retained intent no longer matches, is a `PostprocessConflict` (the request's `error_code`, else `recovery_required`; fix `gbrain write-request -- <id>`) dropped from the pending row; the summary names each slug and code. Other item errors let the rest run and the pass save, then fail the phase; run-scoped errors and `item_failures_systemic` stop it and record nothing. Pinned by `test/pathological/a4-synthesize-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. `loadCommittedSynthesisOutputs` finds each child's committed output by canonicalizing the retained `brain_put_page` input (`parseWriteRequestId` for the request id, `journaledPageSlug` for the slug) before matching request id, source, incarnation, committed put_page, slug and revision (#6616); slug discovery (`collectChildPutPageSlugs`) and postprocessing share that set. 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, whose admission gave up on database contention (`publicationHold` in `persistence/accepted-pending.ts`), or whose unadmitted request was refused `queue_capacity` by a positive principal or brain outstanding-request cap (`isWriteCapacityWait` + `outstandingCapacityOf`, no write receipt) exactly like the pending case: `publish_pending`, phase warn, no cooldown stamp, and the next cycle retries the same request id; a contended or capacity-blocked publish writes one stderr line. A zero cap, cumulative quotas, unknown capacity, a capacity refusal carrying a receipt and every other error fail the phase. Pinned by `test/managed-synthesis-postprocess.test.ts`. #5575 I2: each output publishes with `derivation` from its transcript (`dream-taint.ts` `transcriptDerivation`; `meetingTranscriptsDir` in opts); a retained request replays the declaration it was admitted with. #6360: when the page moved after the child commit, a drift made only by committed local `managed_maintenance_page` requests (for example the next cycle's lint `created:` fix) over a body equal to the child's is adopted: the postprocess runs on the current snapshot under a request id that also binds that base revision (found again on replay among the later requests). Any other later write leaves the page alone as a `PostprocessConflict` (`withPostprocessConflicts`: phase `warn`, `details.postprocess_conflicts` with the read-only `gbrain get` fix); it is reported once (config `dream.synthesize.postprocess_conflicts`, 30-day memory) and does not block the cooldown stamp. #6757: the committed-outputs join (`COMMITTED_OUTPUT_REQUESTS_SQL`) compares `request_id` as a uuid within the source, served by `persistence_requests_request_id`. The phase loads it through `loadCommittedOutputsOrDefer`; a statement timeout there, or on an output's own `getWriteRequest`, defers the pass instead of failing it (`withPublishPending` with `details.postprocess_deferred`: phase warn, no cooldown stamp, no summary). Deferred and publish-pending outputs are carried by `synthesize-postprocess-deferral.ts` and finished by a later pass from the carried fields, with no child; `finishDeferredPostprocess` (run after the phase body by `runPhaseSynthesize`) finishes them when that pass returned before postprocessing. GBRA-130 A-4: outputs run as `ItemRun` items (`synthesize.postprocess`). A postprocess request that ended conflict, failed or cancelled, or whose retained intent no longer matches, is a `PostprocessConflict` (the request's `error_code`, else `recovery_required`; fix `gbrain write-request -- <id>`) dropped from the pending row; the summary names each slug and code. Other item errors let the rest run and the pass save, then fail the phase; run-scoped errors and `item_failures_systemic` stop it and record nothing. Pinned by `test/pathological/a4-synthesize-postprocess.test.ts`.- `src/core/cycle/synthesize-postprocess-deferral.ts` — #6757: config row `dream.synthesize.postprocess_pending`, keyed by source and bound to its incarnation: each pending output (child request id, journaled and input slug, revision, job key, transcript path, content hash, seat, first write) and the source's consecutive deferred passes with the last read and its elapsed time. `isPostprocessReadTimeout` unwinds a cancelled cycle first, then accepts only SQLSTATE 57014 with the statement-timeout message (a user cancel is not deferred). `recordPostprocessPass` drops settled outputs, adds deferred and carried ones and resets the count on a pass that deferred nothing; `repeatedPostprocessDeferrals` lists sources at three or more for doctor `persistence_request_indexes`. The replay runs no child job and verifies a replayed output's quotes against the transcript as it is now, even when it grew after synthesis; a quote not found there goes to `unverified_claims` like any failed quote.Patterns, drift and the entries after them: [Core Cycle (patterns)](core-cycle-patterns.md).diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex ef9cf4530d..13b64a40b4 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -911,6 +911,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.307.0', text: '`gbrain search tune --apply` now writes before it reports: `--json` lists in `applied` and `revert_commands` only the changes that landed, adds per-item `results` (`applied`, `unsupported`, `failed`, `outcome_unknown`, `not_attempted`), `not_applied` and `apply_error`, and the text output marks a failed or unrecognized change with ✗ instead of ✓. The batch stops at the first write that does not land and the command exits non-zero; changes that already landed stay in place with their revert commands.' },{ since: '0.60.307.0', text: 'A worker registry directory that exists but cannot be listed (permission denied, or a file where the directory should be) now reads as unknown worker liveness instead of no workers. Doctor `queue_health` reports `worker_alive: null` with a liveness-unknown message and no start-a-worker fix, `legacy_job_authority` reports `live_workers: null`, `gbrain jobs supervisor status --json` reports `workers: null`, a submitted job\'s `queue_state` omits `worker_alive` and warns that liveness is unknown, `gbrain jobs stats` reports a wedge instead of `no_worker`, and the `migrate-embeddings` plan warns about an unknown worker count. Each names the errno and path in `worker_registry_errno` and `worker_registry_path`. A missing registry directory still means no workers.' },{ since: '0.60.307.0', text: '`gbrain sources attach` with an invalid source id now refuses with `invalid_params` (a caller error) and a fix that lists the existing ids (`gbrain sources list --json`), instead of an `internal_error`. Nothing is written in either case.' },+ { since: '0.60.307.0', text: 'On a managed brain, a dream synthesis output or summary whose publish is refused because the principal or brain outstanding-request cap (`persistence.limits.principal_outstanding`, `persistence.limits.brain_outstanding`) is full is now deferred like a pending publish: the phase warns with `publish_pending`, leaves the cooldown unstamped and the next cycle retries the same request, instead of failing the phase. A zero cap and cumulative quotas still fail it.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cycle/synthesize-postprocess.ts b/src/core/cycle/synthesize-postprocess.tsindex 9c8689b82d..7f8abecfa0 100644--- a/src/core/cycle/synthesize-postprocess.ts+++ b/src/core/cycle/synthesize-postprocess.ts@@ -7,6 +7,7 @@ import { opError } from '../ops/contract.ts';import { ItemRun } from '../item-failure.ts';import { readFix } from '../ops/op-fix.ts';import { publicationHold } from '../persistence/accepted-pending.ts';+import { isWriteCapacityWait, outstandingCapacityOf } from '../persistence/admission-retry.ts';import { authorizeStoredRequest } from '../persistence/authority.ts';import { digest } from '../persistence/digest.ts';import { getWriteRequest } from '../persistence/journal.ts';@@ -392,10 +393,20 @@ export function withPostprocessConflicts(conflicts: PostprocessConflict[], resul/*** A publish that is still pending after its wait (#5854) or whose admission* gave up on database contention without recording anything (#6051) is- * deferred, never failed: the next cycle derives the same request id. Every- * other error is rethrown. A contended publish writes one stderr line naming it.+ * deferred, never failed: the next cycle derives the same request id. So is+ * an unadmitted publish refused by a known positive outstanding-request cap+ * (`queue_capacity` with outstanding/limit counts, a principal or brain scope+ * and no write receipt): it waits for other writes to settle. A zero cap,+ * cumulative quotas, unknown capacity and a refusal carrying a receipt are+ * rethrown with every other error. A contended or capacity-blocked publish+ * writes one stderr line naming it.*/export function deferPublishOrThrow(error: unknown, what: string): void {+ const capacity = isWriteCapacityWait(error) && error.writeRequest == null ? outstandingCapacityOf(error) : null;+ if (capacity?.scope && capacity.limit !== null && capacity.limit > 0) {+ process.stderr.write(`[dream] synthesize: ${what} deferred, ${capacity.scope} outstanding write capacity is full (${capacity.outstanding}/${capacity.limit}); the next cycle admits it\n`);+ return;+ }const deferral = publicationHold(error);if (!deferral) throw error;if (deferral === 'contention') {diff --git a/test/managed-synthesis-postprocess.test.ts b/test/managed-synthesis-postprocess.test.tsindex b48e90fcb2..5f7c814842 100644--- a/test/managed-synthesis-postprocess.test.ts+++ b/test/managed-synthesis-postprocess.test.ts@@ -19,6 +19,7 @@ import { requestIndexesCheck } from '../src/commands/doctor/checks/persistence-rimport { PERSISTENCE_REQUEST_ID_INDEX } from '../src/core/persistence/schema.ts';import { buildIndexOnline } from '../src/core/schema-migrations/helpers.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { isTerminal as isTerminalRequest, type RequestState as PersistenceRequestState } from '../src/core/persistence/model.ts';import { configureGateway, resetGateway, __setChatTransportForTests, __setEmbedTransportForTests, __setDecideTransportForTests } from '../src/core/ai/gateway.ts';import { flushDecideWrites } from '../src/core/ai/decide/store.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';@@ -787,3 +788,156 @@ test('#6757: three deferred passes in a row put a line on doctor persistence_reqexpect(await requestIndexesCheck(engine)).toMatchObject({ status: 'ok', message: 'Request-table indexes are valid.' });});}, 180_000);++// A shared wait may leave admitted writes pending while later admissions hit an outstanding cap (#6916).+for (const scope of ['principal', 'brain'] as const) {+ test(`synthesis defers ${scope} outstanding admission and replays the same request IDs`, async () => {+ const { MaintenanceWriteWait } = await import('../src/core/persistence/maintenance-wait.ts');+ const { isWriteCapacityWait, outstandingCapacityOf } = await import('../src/core/persistence/admission-retry.ts');+ await fixture(async f => {+ const { engine, sourceId, root, calls } = f;+ const { ordinary, jobsBefore, spent } = await childCommittedOrdinaryCycle(f);+ const ready = await engine.executeRaw<{ slug: string }>(+ "SELECT slug FROM pages WHERE source_id=$1 AND slug LIKE 'wiki/personal/reflections/session%' ORDER BY slug", [sourceId]);+ expect(ready).toHaveLength(4);+ const children = await engine.executeRaw<{ state: string }>(+ "SELECT state FROM persistence_requests WHERE source_id=$1 AND operation='put_page' AND slug LIKE 'wiki/personal/reflections/session%'", [sourceId]);+ expect(children).toHaveLength(4);+ expect(children.every(r => r.state === 'committed')).toBe(true);+ const baseline = await engine.executeRaw<{ outstanding_count: number | string }>('SELECT outstanding_count FROM persistence_counters');+ expect(baseline.every(r => Number(r.outstanding_count) === 0)).toBe(true);+ await disposePersistenceConsumer(engine);+ const key = `persistence.limits.${scope}_outstanding`;+ const previous = await engine.getConfig(key);+ const events: unknown[] = [];+ let restoreWait: (() => void) | undefined;+ let msSpy: { mockRestore(): void } | undefined, observeSpy: { mockRestore(): void } | undefined, admitSpy: { mockRestore(): void } | undefined;+ const binding = await getWorktreeBinding(engine, sourceId);+ if (!binding) throw new Error('No worktree binding for publication barrier');+ const lock = await acquireWorktree(binding, 1000);+ if (!lock) throw new Error('Publication barrier was not acquired');+ try {+ restoreWait = __setMaintenanceWriteWaitForTests(300); // existing #5854 seam, same value+ const originalMs = MaintenanceWriteWait.prototype.ms;+ const originalObserve = MaintenanceWriteWait.prototype.observe;+ const originalAdmit = journal.admitWrite;+ msSpy = spyOn(MaintenanceWriteWait.prototype, 'ms').mockImplementation(function (this: InstanceType<typeof MaintenanceWriteWait>) {+ const ms = originalMs.call(this); events.push({ kind: 'wait_ms', ms }); return ms;+ });+ observeSpy = spyOn(MaintenanceWriteWait.prototype, 'observe').mockImplementation(function (this: InstanceType<typeof MaintenanceWriteWait>, row) {+ events.push({ kind: 'observe', request_id: row.request_id, state: row.state });+ return originalObserve.call(this, row);+ });+ admitSpy = spyOn(journal, 'admitWrite').mockImplementation(async (...args) => {+ const [eng, input] = args;+ try {+ const row = await originalAdmit(...args);+ if (eng === engine && input.sourceId === sourceId) events.push({ kind: 'admitted', request_id: row.request_id, slug: row.slug,+ state: row.state, counters: await engine.executeRaw('SELECT key,outstanding_count FROM persistence_counters ORDER BY key') });+ return row;+ } catch (error) {+ if (eng === engine && input.sourceId === sourceId) events.push({ kind: 'refusal', request_id: input.requestId, slug: input.slug,+ error: error instanceof Error ? { name: error.name, message: error.message } : String(error),+ code: error instanceof OperationError ? error.code : null, detail: error instanceof OperationError ? error.detail : null,+ classified: isWriteCapacityWait(error), capacity: error instanceof OperationError ? outstandingCapacityOf(error) : null,+ counters: await engine.executeRaw('SELECT key,outstanding_count FROM persistence_counters ORDER BY key') });+ throw error;+ }+ });+ await engine.setConfig(key, '2'); // this entirely disposable scratch DB only+ const report = await runPhaseSynthesize(engine, ordinary);+ // Only this retryable refusal is a hold: nothing is published or stamped early.+ expect(report.status).toBe('warn');+ expect(report.error).toBeUndefined();+ expect(report.details.pages_written).toBe(0);+ expect(report.details.publish_pending).toBe(4);+ expect(events.some(e => (e as { kind: string; ms?: number }).kind === 'wait_ms' && (e as { ms?: number }).ms === 0)).toBe(true);+ const rows = await engine.executeRaw<{ state: PersistenceRequestState }>(+ "SELECT state FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_maintenance_page'", [sourceId]);+ expect(rows).toHaveLength(2);+ const refused = events.filter(e => (e as { kind: string }).kind === 'refusal') as Array<{ code: string; detail: string; classified: boolean; capacity: { outstanding: number; limit: number; scope: string }; request_id: string }>;+ expect(refused).toHaveLength(2);+ expect(new Set(refused.map(row => row.request_id)).size).toBe(2);+ expect(events.filter(e => (e as { kind: string }).kind === 'admitted')).toHaveLength(2);+ for (const refusal of refused) {+ expect(refusal).toMatchObject({ code: 'queue_capacity', detail: 'outstanding=2 limit=2', classified: true, capacity: { outstanding: 2, limit: 2, scope } });+ expect(await engine.executeRaw('SELECT request_id FROM persistence_requests WHERE request_id=$1::uuid', [refusal.request_id])).toEqual([]);+ }+ expect(rows.every(r => !isTerminalRequest(r) && ['queued', 'running', 'recovering'].includes(r.state))).toBe(true);+ expect(await engine.getConfig('dream.synthesize.last_completion_ts')).toBeNull();+ for (const { slug } of ready) expect((await engine.readPageSnapshot(slug, { sourceId }))!.page.frontmatter.dream_generated).not.toBe(true);+ expect(calls()).toBe(spent);+ expect(await engine.executeRaw('SELECT id FROM minion_jobs ORDER BY id')).toEqual(jobsBefore);+ } finally {+ try {+ try { admitSpy?.mockRestore(); } finally { try { observeSpy?.mockRestore(); } finally { try { msSpy?.mockRestore(); } finally { restoreWait?.(); } } }+ } finally {+ try { if (previous === null) await engine.unsetConfig(key); else await engine.setConfig(key, previous); }+ finally { await lock.release(); }+ }+ // fixture-level finally disposes the consumer even if validation throws.+ }+ // Ordinary recovery only after actual barrier release; pending is not written.+ await disposePersistenceConsumer(engine);+ const retained = await engine.executeRaw<{ request_id: string }>(+ "SELECT request_id::text FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_maintenance_page' ORDER BY sequence", [sourceId]);+ const recovery = await runPhaseSynthesize(engine, ordinary);+ expect(recovery.status).toBe('ok');+ expect(calls()).toBe(spent);+ expect(await engine.executeRaw('SELECT id FROM minion_jobs ORDER BY id')).toEqual(jobsBefore);+ for (const { slug } of ready) expect((await engine.readPageSnapshot(slug, { sourceId }))!.page.frontmatter.dream_generated).toBe(true);+ for (const row of retained) expect(await engine.executeRaw('SELECT state FROM persistence_requests WHERE request_id=$1::uuid', [row.request_id])).toEqual([{ state: 'committed' }]);+ const refusedBeforeRelease = events.filter(e => (e as { kind: string }).kind === 'refusal') as Array<{ request_id: string }>;+ expect(refusedBeforeRelease).toHaveLength(2);+ // These IDs had NO row at refusal; ordinary replay must derive the SAME IDs, not allocate replacements.+ for (const refusal of refusedBeforeRelease) expect(await engine.executeRaw(+ 'SELECT state FROM persistence_requests WHERE request_id=$1::uuid', [refusal.request_id])).toEqual([{ state: 'committed' }]);+ expect((await engine.executeRaw<{ outstanding_count: number | string }>('SELECT outstanding_count FROM persistence_counters')).every(r => Number(r.outstanding_count) === 0)).toBe(true);+ expect(await engine.getConfig('dream.synthesize.last_completion_ts')).not.toBeNull();+ const stable = await engine.executeRaw('SELECT request_id::text,state FROM persistence_requests WHERE source_id=$1 ORDER BY sequence', [sourceId]);+ expect((await runPhaseSynthesize(engine, ordinary)).status).toBe('ok');+ expect(calls()).toBe(spent);+ expect(await engine.executeRaw('SELECT id FROM minion_jobs ORDER BY id')).toEqual(jobsBefore);+ expect(await engine.executeRaw('SELECT request_id::text,state FROM persistence_requests WHERE source_id=$1 ORDER BY sequence', [sourceId])).toEqual(stable);+ }, 4);+ }, 120_000); // original surrounding fixture cap, no enlargement+}++// Other refusal classes retain their original error and fail the phase.+test('synthesis preserves non-outstanding publication refusals', async () => {+ const { isWriteCapacityWait, outstandingCapacityOf } = await import('../src/core/persistence/admission-retry.ts');+ const { deferPublishOrThrow } = await import('../src/core/cycle/synthesize-postprocess.ts');+ const cases: Array<{ id: string; kind: string; code: string | null; message: string; detail: string | null; helper_expected: boolean; receipt_state?: string }> = [+ {"id": "generic-error", "kind": "Error", "code": null, "message": "Write capacity exhausted: principal outstanding requests.", "detail": "outstanding=2 limit=2", "helper_expected": false},+ {"id": "plain-object", "kind": "plain-object", "code": "queue_capacity", "message": "Write capacity exhausted: principal outstanding requests.", "detail": "outstanding=2 limit=2", "helper_expected": false},+ {"id": "generic-queue", "kind": "OperationError", "code": "queue_capacity", "message": "Generic capacity failure.", "detail": null, "helper_expected": false},+ {"id": "zero-principal-cap", "kind": "OperationError", "code": "queue_capacity", "message": "Write capacity exhausted: principal outstanding requests.", "detail": "outstanding=0 limit=0", "helper_expected": true},+ {"id": "zero-brain-cap", "kind": "OperationError", "code": "queue_capacity", "message": "Write capacity exhausted: brain outstanding requests.", "detail": "outstanding=0 limit=0", "helper_expected": true},+ {"id": "unknown-scope-structured", "kind": "OperationError", "code": "queue_capacity", "message": "Write capacity exhausted: unknown resource.", "detail": "outstanding=2 limit=2", "helper_expected": true},+ {"id": "intent-bytes", "kind": "OperationError", "code": "queue_capacity", "message": "Write capacity exhausted: principal intent bytes.", "detail": null, "helper_expected": false},+ {"id": "receipt-bytes", "kind": "OperationError", "code": "write_quota_exhausted", "message": "Reserved receipt bytes exhausted.", "detail": "persistence.limits.principal_terminal_bytes", "helper_expected": false},+ {"id": "lifetime", "kind": "OperationError", "code": "write_quota_exhausted", "message": "Permanent request IDs exhausted.", "detail": "persistence.limits.principal_lifetime_ids", "helper_expected": false},+ {"id": "permission", "kind": "OperationError", "code": "permission_denied", "message": "Write capacity exhausted: principal outstanding requests.", "detail": "outstanding=2 limit=2", "helper_expected": false},+ {"id": "storage", "kind": "OperationError", "code": "storage_error", "message": "Storage unavailable.", "detail": "disk_full", "helper_expected": false},+ {"id": "malformed-9", "kind": "OperationError", "code": "queue_capacity", "message": "Write capacity exhausted: principal outstanding requests.", "detail": "outstanding=-1 limit=2", "helper_expected": false},+ {"id": "malformed-10", "kind": "OperationError", "code": "queue_capacity", "message": "Write capacity exhausted: principal outstanding requests.", "detail": "outstanding=2 limit=2 trailing", "helper_expected": false},+ {"id": "malformed-11", "kind": "OperationError", "code": "queue_capacity", "message": "Write capacity exhausted: principal outstanding requests.", "detail": " outstanding=2 limit=2", "helper_expected": false},+ {"id": "malformed-12", "kind": "OperationError", "code": "queue_capacity", "message": "Write capacity exhausted: principal outstanding requests.", "detail": "outstanding=2", "helper_expected": false},+ {"id": "malformed-13", "kind": "OperationError", "code": "queue_capacity", "message": "Write capacity exhausted: principal outstanding requests.", "detail": "outstanding=2 limit=NaN", "helper_expected": false},+ {"id": "realcapacity-with-receipt-committed", "kind": "OperationError", "code": "queue_capacity", "message": "Write capacity exhausted: principal outstanding requests.", "detail": "outstanding=2 limit=2", "helper_expected": true, "receipt_state": "committed"},+ {"id": "realcapacity-with-receipt-queued", "kind": "OperationError", "code": "queue_capacity", "message": "Write capacity exhausted: principal outstanding requests.", "detail": "outstanding=2 limit=2", "helper_expected": true, "receipt_state": "queued"},+ {"id": "realcapacity-with-receipt-unknown", "kind": "OperationError", "code": "queue_capacity", "message": "Write capacity exhausted: principal outstanding requests.", "detail": "outstanding=2 limit=2", "helper_expected": true, "receipt_state": "unknown"},+ ];+ for (const item of cases) {+ let error: unknown;+ if (item.kind === 'plain-object') error = { code: item.code, message: item.message, detail: item.detail };+ else if (item.kind === 'Error') error = Object.assign(new Error(item.message), { detail: item.detail });+ else error = Object.assign(new OperationError(item.code as ConstructorParameters<typeof OperationError>[0], item.message, 'Inspect the refused publication.'), { detail: item.detail ?? undefined });+ if (item.receipt_state) Object.assign(error as object, { writeRequest: { request_id: '00000000-0000-4000-8000-000000000001', state: item.receipt_state } });+ expect(isWriteCapacityWait(error), item.id).toBe(item.helper_expected);+ if (item.id === 'unknown-scope-structured') expect(outstandingCapacityOf(error as OperationError).scope).toBeNull();+ let caught: unknown = Symbol('not-thrown');+ try { deferPublishOrThrow(error, 'refused-publication'); } catch (failure) { caught = failure; }+ expect(caught, item.id).toBe(error);+ }+});