Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(synthesize): adopt maintenance-only drift after the child commit; other edits warn once (#6360)
time-attack50e310e6a5be
diff --git a/docs/architecture/key-files/core-cycle-continued.md b/docs/architecture/key-files/core-cycle-continued.mdindex ddeb012035..71e3982ee0 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. 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.+- `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`. #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.- `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`. #6177: `cycle/patterns-plan.ts` — every child records `dream.patterns.last_run` (`{duration_ms, reflections, at, outcome, budget_skips}`, DB-only state; `config set` refuses it, `config unset` resets it) and pure `planPatternsRun` sizes an in-cycle run from it (1.25× margin; a timeout halves the next submission; no usable history → first batch of max(25, min_evidence); 3 budget skips or a 7-day-old record → a min_evidence probe; below min_evidence → skip `insufficient_cycle_budget` with `cause: budget_below_recent_runtime` before any submit); the newest n reflections are submitted; direct runs (no deadline) keep full size. Guide: `docs/guides/dream-patterns.md`; tests `test/cycle-patterns-plan.test.ts`. Quarantined claim records store the run's reflection list once per page in `unverified_claim_sources` and reference it (`cycle/pattern-claim-sources.ts`: `withClaimSources`, `resolveClaimSources` recovers every path); before submitting the child the phase de-duplicates pages still carrying inline lists (`dedupePatternClaimSources`, frontmatter-only maintenance writes) and skips as `pattern_claims_pending`, with no child and no model call, while any rewrite is held (`test/cycle-patterns-quote-verify.test.ts`, `test/managed-maintenance.test.ts`). #5575 ENG-3 partition: `gatherReflections` reads each reflection's `trust_tier` (`ReflectionRef.taint`, never in the submission key); `runPhasePatterns` runs the owner pass (`runPatternsPass`) over every non-external reflection and, when the external_untrusted reflections reach `min_evidence` on their own, a separate pass with watermark `<evidence key>.external`; `details.reflections_external`, `details.external_pass`, and `patterns_written` sums both. Each pass's outputs are written back (grounding publish or `importFromContent`, provenance stamp) at `patternsDerivation(submitted)` with edges to that pass's reflections. Pinned by `test/trust-taint-dream.test.ts`. #6302 Part A [R17]: completed `brain_add_timeline_entry` calls of the child are counted (`countChildTimelineAppends`) and reported as `details.appended_unverified` and in the summary; they get no quote verification or provenance stamp (Part B, grounding appended entries, is deferred). #6296: `recordPatternsLastRun` maps a `dead` child whose error is `timeout exceeded` / `wall-clock timeout exceeded` to `timeout`.- `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.diff --git a/src/core/cycle/synthesize-postprocess.ts b/src/core/cycle/synthesize-postprocess.tsindex 925835c599..f9cfdf9568 100644--- a/src/core/cycle/synthesize-postprocess.ts+++ b/src/core/cycle/synthesize-postprocess.ts@@ -1,6 +1,6 @@import type { BrainEngine } from '../engine.ts';import { throwIfAborted } from '../abort-check.ts';-import { serializePageToMarkdown } from '../markdown.ts';+import { parseMarkdown, serializePageToMarkdown } from '../markdown.ts';import type { Action } from '../agent-output.ts';import { opError } from '../ops/contract.ts';import { readFix } from '../ops/op-fix.ts';@@ -19,6 +19,28 @@ import { emptyQuoteVerifyStats, groundSource, isDreamOwnedPage, resolveVerifyPriinterface OutputRef { slug: string; source_id: string; raw_source?: string; seat?: string; first_write_at?: Date; }interface RetainedOutput { job_id: number | bigint; job_key: string; request: WriteRequest; }+/** #6360: a retained output a later non-maintenance write moved; it is left alone and reported once. */+export interface PostprocessConflict { slug: string; source_id: string; request_id: string; message: string; fix: Action; }++export const POSTPROCESS_CONFLICTS_KEY = 'dream.synthesize.postprocess_conflicts';+const CONFLICT_MEMORY_MS = 30 * 86_400_000;++const sameBody = (content: unknown, page: { compiled_truth: string; timeline?: string | null }, slug: string) => {+ if (typeof content !== 'string') return false;+ const child = parseMarkdown(content, slug);+ return child.compiled_truth.trim() === page.compiled_truth.trim() && (child.timeline ?? '').trim() === (page.timeline ?? '').trim();+};++/** Committed-or-pending requests on the output page after the child's put_page, oldest first. */+async function laterRequests(engine: BrainEngine, output: WriteRequest): Promise<WriteRequest[]> {+ return engine.executeRaw<WriteRequest>(+ `SELECT * FROM persistence_requests+ WHERE source_id=$1 AND source_incarnation=$2 AND slug=$3 AND sequence > $4+ AND state IN ('queued','running','recovering','committed')+ ORDER BY sequence`, [output.source_id, output.source_incarnation, output.slug, output.sequence]);+}++const localMaintenance = (r: WriteRequest) => r.operation === 'submit_job' && r.intent?.kind === 'managed_maintenance_page' && r.authority?.remote === false;const writerStatusFix = (sourceId: string, why: string): Action => readFix(why, { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] });@@ -36,8 +58,10 @@ export async function postprocessManagedSynthesis(const stats = emptyQuoteVerifyStats();const writtenRefs: OutputRef[] = [];const finalizedRefs: OutputRef[] = [];+ const conflicts: PostprocessConflict[] = [];let pending = 0;- if (!refs.length) return { writtenRefs, finalizedRefs, stats, pending };+ if (!refs.length) return { writtenRefs, finalizedRefs, stats, pending, conflicts };+ const reported = await readReportedConflicts(engine);const outputs = await engine.executeRaw<RetainedOutput>(`SELECT t.job_id,j.idempotency_key AS job_key,row_to_json(p) AS requestFROM subagent_tool_executions t JOIN minion_jobs j ON j.id=t.job_id@@ -66,10 +90,37 @@ export async function postprocessManagedSynthesis({ fix: writerStatusFix(ref.source_id, `Shows source ${ref.source_id}'s committed and pending maintenance requests, read-only.`) });}const finalizedRef = { ...ref, raw_source: path };- const key = digest({ kind: 'synthesis-postprocess-v1', source: authority.writer.sourceIncarnation,- slug: ref.slug, job: output.job_key, output: output.request.id, revision, transcript: transcript.contentHash });- const requestId = `${key.slice(0, 8)}-${key.slice(8, 12)}-4${key.slice(13, 16)}-a${key.slice(17, 20)}-${key.slice(20, 32)}`;- const prior = await getWriteRequest(engine, authority.writer.principal, requestId);+ // #6360: a postprocess adopted onto a maintenance-only drift binds its base revision too.+ const postprocessId = (base: string) => {+ const key = digest({ kind: 'synthesis-postprocess-v1', source: authority.writer.sourceIncarnation,+ slug: ref.slug, job: output.job_key, output: output.request.id, revision, transcript: transcript.contentHash, ...(base === revision ? {} : { base }) });+ return `${key.slice(0, 8)}-${key.slice(8, 12)}-4${key.slice(13, 16)}-a${key.slice(17, 20)}-${key.slice(20, 32)}`;+ };+ let base = revision;+ let requestId = postprocessId(base);+ let prior = await getWriteRequest(engine, authority.writer.principal, requestId);+ let snapshot: Awaited<ReturnType<BrainEngine['readPageSnapshot']>> = null;+ if (!prior) {+ snapshot = await engine.readPageSnapshot(ref.slug, { sourceId: ref.source_id });+ if (!snapshot || snapshot.revision !== revision) {+ const later = await laterRequests(engine, output.request);+ const ours = later.find(r => localMaintenance(r) && typeof r.intent?.expected_revision === 'string'+ && r.request_id === postprocessId(r.intent.expected_revision as string));+ if (ours) {+ base = ours.intent!.expected_revision as string;+ requestId = ours.request_id;+ prior = await getWriteRequest(engine, authority.writer.principal, requestId);+ } else if (snapshot && later.filter(r => r.state === 'committed').every(localMaintenance) && sameBody(output.request.intent?.content, snapshot.page, ref.slug)) {+ base = snapshot.revision;+ requestId = postprocessId(base);+ } else {+ if (!reported.has(requestId)) conflicts.push({ slug: ref.slug, source_id: ref.source_id, request_id: requestId,+ message: `Page ${ref.slug} in source ${ref.source_id} changed after the synthesis child committed revision ${revision}, so postprocessing left it alone and did not verify or stamp it. Review the page; this output is not retried.`,+ fix: readFix(`Shows page ${ref.slug} as it is now, read-only.`, { argv: ['gbrain', 'get', '--source', ref.source_id, '--', ref.slug] }) });+ continue;+ }+ }+ }if (prior) {await authorizeStoredRequest(engine, prior);if (prior.state === 'committed') { finalizedRefs.push(finalizedRef); continue; }@@ -78,19 +129,14 @@ export async function postprocessManagedSynthesis(await authorizeStoredRequest(engine, output.request);let content: string;if (prior) {- if (prior.intent?.kind !== 'managed_maintenance_page' || prior.intent.expected_revision !== revision || typeof prior.intent.content !== 'string') {+ if (prior.intent?.kind !== 'managed_maintenance_page' || prior.intent.expected_revision !== base || typeof prior.intent.content !== 'string') {throw opError('recovery_required', 'The retained synthesis postprocessing intent is unavailable.',- `Postprocess request ${prior.request_id} for ${ref.slug} in source ${ref.source_id} exists, but its retained intent does not match revision ${revision}. Inspect it in writer status; do not resubmit under a new request.`,+ `Postprocess request ${prior.request_id} for ${ref.slug} in source ${ref.source_id} exists, but its retained intent does not match revision ${base}. Inspect it in writer status; do not resubmit under a new request.`,{ fix: writerStatusFix(ref.source_id, `Shows request ${prior.request_id} and any recovery it holds, read-only.`) });}content = prior.intent.content;} else {- const snapshot = await engine.readPageSnapshot(ref.slug, { sourceId: ref.source_id });- if (!snapshot || snapshot.revision !== revision) {- throw opError('revision_conflict', 'The synthesis output changed after the child committed.',- `Page ${ref.slug} in source ${ref.source_id} changed after the synthesis child committed revision ${revision}, so postprocessing left it alone. Review the page; the next synthesis run processes fresh output.`,- { fix: readFix(`Shows page ${ref.slug} as it is now, read-only.`, { argv: ['gbrain', 'get', '--source', ref.source_id, '--', ref.slug] }) });- }+ if (!snapshot) throw new Error(`synthesis postprocess: no snapshot for ${ref.slug}`);const firstDate = snapshot.page.frontmatter.dream_created_cycle_date || snapshot.page.frontmatter.dream_cycle_date || opts.cycleDate;const since = ref.first_write_at ?? opts.sinceByTranscript.get(transcript.filePath);let page = isDreamOwnedPage(snapshot.page, since) ? { ...snapshot.page, frontmatter: { ...snapshot.page.frontmatter, dream_generated: true,@@ -115,7 +161,7 @@ export async function postprocessManagedSynthesis(const derivation = prior ? readDerivationDeclaration(prior.intent?.derivation) ?? undefined: await transcriptDerivation(engine, transcript, opts.meetingTranscriptsDir).then(d => declareDerivation(d.trust, d.inputs));try {- await publishMaintenancePage(engine, authority, ref.slug, content, { requestId, expectedRevision: revision, derivation });+ await publishMaintenancePage(engine, authority, ref.slug, content, { requestId, expectedRevision: base, derivation });} catch (error) {deferPublishOrThrow(error, `${ref.slug} (request ${requestId})`);pending++;@@ -125,7 +171,34 @@ export async function postprocessManagedSynthesis(finalizedRefs.push(finalizedRef);await new Promise(resolve => setTimeout(resolve, 0));}- return { writtenRefs, finalizedRefs, stats, pending };+ if (conflicts.length) await rememberConflicts(engine, reported, conflicts);+ return { writtenRefs, finalizedRefs, stats, pending, conflicts };+}++async function readReportedConflicts(engine: BrainEngine): Promise<Map<string, string>> {+ try {+ const parsed = JSON.parse(await engine.getConfig(POSTPROCESS_CONFLICTS_KEY) ?? '{}') as Record<string, unknown>;+ const cutoff = Date.now() - CONFLICT_MEMORY_MS;+ return new Map(Object.entries(parsed).filter((e): e is [string, string] => typeof e[1] === 'string' && Date.parse(e[1]) > cutoff));+ } catch { return new Map(); }+}++async function rememberConflicts(engine: BrainEngine, reported: Map<string, string>, conflicts: PostprocessConflict[]): Promise<void> {+ const at = new Date().toISOString();+ for (const c of conflicts) reported.set(c.request_id, at);+ await engine.setConfig(POSTPROCESS_CONFLICTS_KEY, JSON.stringify(Object.fromEntries(reported)));+}++/**+ * #6360: outputs a later non-maintenance write moved are terminal (retrying+ * cannot help), so the phase warns once per output instead of failing every+ * cycle, and the cooldown still stamps.+ */+export function withPostprocessConflicts(conflicts: PostprocessConflict[], result: PhaseResult): PhaseResult {+ if (!conflicts.length) return result;+ return { ...result, status: result.status === 'fail' ? 'fail' : 'warn',+ summary: `${result.summary}; ${conflicts.length} output page(s) changed after the child committed and were left alone`,+ details: { ...result.details, postprocess_conflicts: conflicts } };}/**diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.tsindex e7671911ea..8e87c2698f 100644--- a/src/core/cycle/synthesize.ts+++ b/src/core/cycle/synthesize.ts@@ -1,7 +1,7 @@import { observationDateLine, observationDateRule } from '../ai/date-grounding.ts';import { isConsumerDateGroundingOn } from '../facts/extract.ts';import { maintenancePreflight, publishMaintenancePage, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';-import { deferPublishOrThrow, postprocessManagedSynthesis, withPublishPending } from './synthesize-postprocess.ts';+import { deferPublishOrThrow, postprocessManagedSynthesis, withPostprocessConflicts, withPublishPending, type PostprocessConflict } from './synthesize-postprocess.ts';/*** Synthesize phase (v0.23; #4152 two-stage cascade) — conversation-to-brain* pipeline. Cheap-model triage gates frontier-model synthesis:@@ -1149,6 +1149,7 @@ async function runPhaseSynthesizeInner(// switch: dream.synthesize.quote_verify=false.let quoteVerifyStats: QuoteVerifyStats | null = null;let publishPending = 0;+ let postprocessConflicts: PostprocessConflict[] = [];const sinceByTranscript = await loadChildWriteEpochs(engine, childIds, jobRawSource, verifySince);const grounding = config.quoteVerify ? await resolveGroundingDecide(engine) : undefined;if (maintenance) {@@ -1157,6 +1158,7 @@ async function runPhaseSynthesizeInner(writtenRefs = processed.writtenRefs;finalizedRefs = processed.finalizedRefs;publishPending = processed.pending;+ postprocessConflicts = processed.conflicts;quoteVerifyStats = config.quoteVerify ? processed.stats : null;} else if (config.quoteVerify && writtenRefs.length > 0) {const transcriptsForVerify = new Map<string, TranscriptForVerify>(worthProcessing.map(t => [t.filePath, { content: t.content }]));@@ -1353,7 +1355,7 @@ async function runPhaseSynthesizeInner(const turnsSamples = childOutcomes.filter((o): o is { jobId: number; status: string; turns: number } => typeof o.turns === 'number',);- return withPublishPending(publishPending, ok(`${submittedTranscripts} transcript(s) synthesized in ${(ms / 1000).toFixed(1)}s${deferralSuffix}`, {+ return withPostprocessConflicts(postprocessConflicts, withPublishPending(publishPending, ok(`${submittedTranscripts} transcript(s) synthesized in ${(ms / 1000).toFixed(1)}s${deferralSuffix}`, {transcripts_discovered: transcripts.length,transcripts_processed: submittedTranscripts,pages_written: writtenSlugs.length,@@ -1420,7 +1422,7 @@ async function runPhaseSynthesizeInner(// child counters + triage pass usage). cost_usd null when unpriced.spend: spendBlock,},- }));+ })));} catch (e) {return failed(makeError('InternalError', 'SYNTH_PHASE_FAIL', e instanceof Error ? (e.message || 'synthesize phase threw') : String(e),e instanceof OperationError ? e.suggestion : undefined), e instanceof OperationError ? { error_code: e.code } : {});diff --git a/test/managed-synthesis-postprocess.test.ts b/test/managed-synthesis-postprocess.test.tsindex d0e5cf3704..252fa15d28 100644--- a/test/managed-synthesis-postprocess.test.ts+++ b/test/managed-synthesis-postprocess.test.ts@@ -282,24 +282,83 @@ test('unfinished synthesis refuses an intervening user revision rather than adopconst bytes = readFileSync(path, 'utf8');const spent = calls();const replay = await runPhaseSynthesize(engine, opts);- expect(replay.status).toBe('fail');+ // #6360: a user revision is a per-page warn, not a phase failure every cycle.+ expect(replay.status).toBe('warn');expect(calls()).toBe(spent);expect((await engine.readPageSnapshot(slug, { sourceId }))!.revision).toBe(snapshot.revision);expect(readFileSync(path, 'utf8')).toBe(bytes);});}, 120_000);-test('a revision_conflict phase failure keeps the suggestion that names the slug (#6242)', async () => {+test('a revision_conflict output keeps the suggestion that names the slug (#6242, #6360)', async () => {await fixture(async ({ engine, sourceId, opts, edit }) => {await interruptAfterChild(engine, sourceId, opts);const slug = await outputSlug(engine, sourceId);await edit(slug);const replay = await runPhaseSynthesize(engine, opts);- expect(replay.status).toBe('fail');- expect(replay.error?.code).toBe('SYNTH_PHASE_FAIL');- expect(replay.details.error_code).toBe('revision_conflict');- expect(replay.error?.hint).toContain(slug);- expect(replay.error?.hint).toContain(sourceId);+ expect(replay.status).toBe('warn');+ const [conflict] = replay.details.postprocess_conflicts as Array<{ slug: string; message: string; fix: { argv: string[] } }>;+ expect(conflict.slug).toBe(slug);+ expect(conflict.message).toContain(slug);+ expect(conflict.message).toContain(sourceId);+ expect(conflict.fix.argv).toEqual(['gbrain', 'get', '--source', sourceId, '--', slug]);+ expect(replay.details.pages_written).toBe(0);+ expect(await engine.getConfig('dream.synthesize.last_completion_ts')).toBeTruthy();+ const again = await runPhaseSynthesize(engine, opts);+ expect(again.status).toBe('ok');+ expect(again.details.postprocess_conflicts).toBeUndefined();+ });+}, 120_000);++/** A local maintenance write that only adds `created:` to the child's page, as the next cycle's lint fix does (#6360). */+async function maintenanceFrontmatterDrift(engine: BrainEngine, sourceId: string, slug: string) {+ const { maintenancePreflight, publishMaintenancePage } = await import('../src/core/persistence/prepared-maintenance.ts');+ const { serializePageToMarkdown } = await import('../src/core/markdown.ts');+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId }))!;+ const authority = (await maintenancePreflight(engine, sourceId))!;+ const content = serializePageToMarkdown({ ...snapshot.page, frontmatter: { ...snapshot.page.frontmatter, created: '2026-09-20' } }, snapshot.tags);+ await publishMaintenancePage(engine, authority, slug, content, { expectedRevision: snapshot.revision });+ await disposePersistenceConsumer(engine);+}++test('a maintenance-only frontmatter drift after the child commit is adopted (#6360)', async () => {+ await fixture(async ({ engine, sourceId, opts, calls }) => {+ await interruptAfterChild(engine, sourceId, opts);+ const slug = await outputSlug(engine, sourceId);+ await maintenanceFrontmatterDrift(engine, sourceId, slug);+ const spent = calls();+ const recovered = await runPhaseSynthesize(engine, opts);+ expect(recovered.status).toBe('ok');+ expect(calls()).toBe(spent);+ expect(recovered.details.pages_written).toBe(1);+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId }))!;+ expect(snapshot.page.frontmatter.dream_generated).toBe(true);+ expect(String(snapshot.page.frontmatter.created)).toContain('2026-09-20');+ expect(snapshot.page.compiled_truth).not.toContain('"an entirely invented');+ await disposePersistenceConsumer(engine);+ const replay = await runPhaseSynthesize(engine, opts);+ expect(replay.status).toBe('ok');+ expect(replay.details.pages_written).toBe(0);+ expect((await engine.readPageSnapshot(slug, { sourceId }))!.revision).toBe(snapshot.revision);+ });+}, 120_000);++test('a user put_page that only changes frontmatter is still refused, not adopted (#6360)', async () => {+ await fixture(async ({ engine, sourceId, opts }) => {+ await interruptAfterChild(engine, sourceId, opts);+ const slug = await outputSlug(engine, sourceId);+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId }))!;+ const ctx = { engine, sourceId, remote: false as const, config: { engine: engine.kind, embedding_disabled: true },+ dryRun: false, logger: { info() {}, warn() {}, error() {} } };+ const { serializePageToMarkdown } = await import('../src/core/markdown.ts');+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(), expected_revision: snapshot.revision,+ content: serializePageToMarkdown({ ...snapshot.page, frontmatter: { ...snapshot.page.frontmatter, created: '2026-09-20' } }, snapshot.tags) } });+ await disposePersistenceConsumer(engine);+ const moved = (await engine.readPageSnapshot(slug, { sourceId }))!;+ const replay = await runPhaseSynthesize(engine, opts);+ expect(replay.status).toBe('warn');+ expect((replay.details.postprocess_conflicts as unknown[]).length).toBe(1);+ expect((await engine.readPageSnapshot(slug, { sourceId }))!.revision).toBe(moved.revision);});}, 120_000);