Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(synthesize_concepts): an accepted concept publication still pending after its wait is reported pending, not a phase failure (#7547)
garrytana0621647c049
diff --git a/docs/architecture/key-files/core-cycle-patterns.md b/docs/architecture/key-files/core-cycle-patterns.mdindex 815b63d71e..b03e9eaea0 100644--- a/docs/architecture/key-files/core-cycle-patterns.md+++ b/docs/architecture/key-files/core-cycle-patterns.md@@ -22,7 +22,7 @@ Patterns, drift reports and the cycle modules listed after them.- `src/core/cycle/triage-rescue.ts` — THE dream triage gate (`passesTriageGate`) + the verified-segment rescue (`applyTriageRescue`). Rescue fires only for scores in `[floor, threshold)` (floor inclusive; at/above threshold is the plain gate's job) with content_type in the buried-signal allowlist (default mixed/reflection/idea/strategy/people — never routine/technical) and ≥ minSegments of the judge's own segments verifying as normalized transcript substrings (`normForGrounding`, ≥40 chars, deduped by normalized quote — repetition is not more evidence). $0 — no LLM calls; fabricated segments cannot fire it; works on cached verdicts (gate-time only). Fail-closed on every malformed shape (null score, missing/short/non-string segments), never throws. `minSegments: 0` is the kill switch (gate degenerates to the plain threshold). ONE-GATE RULE: `runTriagePass` (report construction — `worth`/`rescued`/telemetry/dry-run), the synthesize fan-out, and `dream retriage` (reconcile-queue cancels + `--audit-rejects` sampling) all read this predicate — a second hand-rolled `score >= threshold` check is how an operator sweep cancels exactly the jobs the rescue admitted. Config: `dream.triage.rescue_floor` / `rescue_min_segments` / `rescue_content_types`. Pinned by `test/cycle-triage-rescue.test.ts` + the rescue suites in `test/cycle-synthesize-triage.test.ts` / `test/dream-retriage.test.ts`. System One S7: a decide verdict (`model` starting with `DECIDE_VERDICT_PREFIX`) is gated against the S7 slot threshold (the optional fifth argument) and never enters the rescue band.- `src/core/cycle/derived-write-through.ts` — opt-in markdown write-through for generated pages on an unmanaged brain (#5041). `cycle.extract_atoms.write_through` / `cycle.synthesize_concepts.write_through` (off by default; `true`/`1`/`yes`/`on`) make `derivedWriteThrough` return a hook (null when off, managed or dry run): `extract_atoms` writes each item's atoms after the completion flip and removes the files of atoms it retired; `synthesize_concepts` writes through `publishClassicConcept`, which also rewrites a concept that already has a file whatever the key says. Creating the hook writes up to 200 generated pages per run that have no file yet (`source_path` NULL; pending atoms excluded), so enabling the key backfills. `writeDerivedPageThrough` keeps a page database-only when its target is ignored by git or sits in a declared `storage.db_only` directory (`derivedFileTarget`), replaces an existing file only when `replaceableFile` (`facts/file-body-guard.ts`) finds it equal to the page or one of its recent page_versions rows, then calls `writePageThrough` bound to the bytes compared and returns its result (`written`, `skipped`, `error`) so `publishClassicConcept` can surface a failed write. #8073: every file write and retired-file unlink is uncommitted (`deferCommit`) and the batch (an item's atoms plus its retired atoms' files, the backfill, or one concept) commits once through the shared-checkout door `commitPathsLocked` (`git/commit-push.ts`) under the source filesystem lock, naming only the batch's paths that exist or are tracked; a directory that is not a Git checkout, or whose checkout lookup fails (`classifyGitCheckout` `unknown`), has nothing to commit. A refused commit leaves a file whose change HEAD already holds (another writer's locked commit swept it from the ledger) as committed, restores each other file still holding the bytes the batch wrote (`WriteThroughResult.content`; prior bytes, or removed), clears the `source_path` the write bound so the next backfill rewrites it, and returns a typed `DerivedCommitFailure` (`{code, message, paths, kept}`); the hook then writes nothing more that run and the phases report `details.write_through_failed` with `warn` (`reportDerivedWriteThrough`), while `writeDerivedPageThrough` returns it as `error` so the concept is held. Each file written or removed is also recorded in the door's pending ledger (`notePending`) right after the write, so a crash before the commit leaves it for the next `commitPathsLocked` in that checkout to sweep (ledger paths inside the source root that still differ from HEAD; only paths gbrain wrote are recorded). The dream reverse-write (`writeDreamPageFile`, `removeDreamPageFile`, `reverseWriteDreamRefs`) commits the same way: one batch per `reverseWriteDreamRefs` call (committed in a `finally`, so an abort still commits what it wrote) and one per summary write or retired-file removal; a refused commit rolls the files back and returns or pushes a `write_through_failed` hold, which the phases report through their existing `file_holds`. A checkout carrying a canonical owner marker commits through `commitAndPush`'s named-paths-only path (`commitManagedPaths`), and paths git ignores are left uncommitted. Tests: `test/cycle/derived-write-through-commit.test.ts` (with the `derivedWriteSeams.beforeCommit` crash fault point) and `test/cycle/dream-reverse-write-commit.test.ts` (PGLite and Postgres). A retired atom's file is removed under the same filter and comparison, the unlink rechecking the bytes under the source filesystem lock. A file holding an edit the database lacks (or an unindexed file at a backfilled page's path) is left as it is and listed in the hook's `held`, which both phases report as `details.file_holds` (`file_database_drift`) with a `warn` status. Tests: `test/cycle/derived-write-through.test.ts`, `test/pathological/d10-derived-atom-file-overwrite.test.ts`, `test/pathological/d11-derived-retired-atom-unlink.test.ts`. #6982: `writeDreamPageFile` is the dream reverse-write (synthesize, patterns, the cycle summary): nothing with `sync.write_through` off, for an owned url clone or a `storage.db_only` slug; the path is `resolvePageWriteTarget`'s (recorded source_path), falling back to the caller's brainDir layout when the source has no root or its root is missing; the file is replaced only when `replaceableFile` (facts/file-body-guard.ts) finds nothing in it the database lacks and, once the replacement is staged, still holds the compared bytes right before the rename, else the result carries the `file_database_drift` hold. It writes directly (not `writePageThrough`/`atomicWriteFileSync`) because a checkout a subagent tool write claimed through the coordinator refuses those with `writer_coordinator_required`. `reportFileHolds` lists every phase's holds in `details.file_holds` and turns ok into warn.-- `src/core/cycle/concept-publication.ts` — managed `synthesize_concepts` publication: `publishManagedConcept` publishes through `publishMaintenancePage` (a concept with a recorded `source_path` republishes to its file unless a `db_only` tier covers it; new concepts are database-only), and `composeConceptRepublication` keeps an existing concept's facts/takes fences, timeline, tags and other frontmatter (a timeline the replacement writes itself is dropped, `test/cycle/concept-publication-timeline.test.ts`), holding the concept (`concept_preservation_hold`) when a fence is duplicated, unbalanced, unparseable or below the timeline sentinel. `replaceConceptProvenanceLinks` banks the concept-provenance edges and retires the edges of atoms that left the group in one transaction (coordinated on a managed brain), only while the concept is at the revision its publication produced (GBRA-161 PR 5, C-4). On an unmanaged brain `publishClassicConcept` writes under the page lock the fence writers take: it re-reads the page, defers (`revision_conflict`) when the narrative changed since synthesis started, another writer owns it, or the page's canonical file holds anything the database lacks (`replaceableFile`: body, fences, timeline, frontmatter, tags, type or title equal to neither the page nor a recent page_versions row; formatting is ignored; this also covers an unindexed file at a new concept's path, and the message names the page with `file_database_drift`), and otherwise composes the new narrative with the database's latest fences, timeline, tags and frontmatter, so a take added during synthesis survives (`test/pathological/d12-concept-stale-fences.test.ts`, `d13-concept-occupied-path.test.ts`). The file write after `importPage` passes the bytes read under the lock as `expectedFileBytes`, so an edit landing during the import is kept and the concept deferred; a failed file write holds the concept (`concept_write_through_failed`) instead of reporting success (W9F item 3, `test/cycle/concept-publication-file-recheck.test.ts`). `stripFenceSections` is the shared narrative view. Tests: `test/cycle/synthesize-concepts-fences.test.ts`. The phase keeps the private-first, provenance, then promotion order; revision races are deferred and holds rep... (line truncated to 2000 chars)+- `src/core/cycle/concept-publication.ts` — managed `synthesize_concepts` publication: `publishManagedConcept` publishes through `publishMaintenancePage` (a concept with a recorded `source_path` republishes to its file unless a `db_only` tier covers it; new concepts are database-only), and `composeConceptRepublication` keeps an existing concept's facts/takes fences, timeline, tags and other frontmatter (a timeline the replacement writes itself is dropped, `test/cycle/concept-publication-timeline.test.ts`), holding the concept (`concept_preservation_hold`) when a fence is duplicated, unbalanced, unparseable or below the timeline sentinel. `replaceConceptProvenanceLinks` banks the concept-provenance edges and retires the edges of atoms that left the group in one transaction (coordinated on a managed brain), only while the concept is at the revision its publication produced (GBRA-161 PR 5, C-4). On an unmanaged brain `publishClassicConcept` writes under the page lock the fence writers take: it re-reads the page, defers (`revision_conflict`) when the narrative changed since synthesis started, another writer owns it, or the page's canonical file holds anything the database lacks (`replaceableFile`: body, fences, timeline, frontmatter, tags, type or title equal to neither the page nor a recent page_versions row; formatting is ignored; this also covers an unindexed file at a new concept's path, and the message names the page with `file_database_drift`), and otherwise composes the new narrative with the database's latest fences, timeline, tags and frontmatter, so a take added during synthesis survives (`test/pathological/d12-concept-stale-fences.test.ts`, `d13-concept-occupied-path.test.ts`). The file write after `importPage` passes the bytes read under the lock as `expectedFileBytes`, so an edit landing during the import is kept and the concept deferred; a failed file write holds the concept (`concept_write_through_failed`) instead of reporting success (W9F item 3, `test/cycle/concept-publication-file-recheck.test.ts`). `stripFenceSections` is the shared narrative view. A publication the writer holds (accepted and still pending after its wait, or not admitted on contention) is reported in `details.publication_pending` (status warn, no completed round) instead of failing the phase (`test/cycle/synthesize-concepts-accepted-pending.test.ts`). Tests: `test/cycle/synthesize-concepts-fences.test.ts`. The phase keeps the private-first, provenance, then promotion order; revision races are deferred and holds rep... (line truncated to 2000 chars)- `src/core/cycle/connector-atoms.ts` — the connector atom setting (#5856). `CONNECTOR_ATOM_PAGES_KEY` (`cycle.extract_atoms.connector_pages`, on when unset; `connectorAtomPagesEnabled` treats only false/0/off/no as opted out) gates `CONNECTOR_ATOM_PAGE_TYPES` (`email`, `meeting`) of sources whose `config.kind` is a connector kind (`CONNECTOR_SOURCE_KINDS`). `connectorAtomExclusionSql` returns the `pages p` predicate atom discovery and the backlog count append (empty unless opted out), so the routine cycle, `dream --drain` and autopilot auto-drain extract connector mail and calendar pages under the auto-drain budget until the user opts out. Other page types of a connector source and every checkout-backed page are unaffected. Tests: `test/connector-atom-pages.test.ts`, `test/autopilot-auto-drain-dispatch.test.ts`, and the `atom_drain_default_on` / `atom_drain_opted_out` cases of `test/helpers/managed-connector-job-contract.ts`, run by `test/managed-connector-job-contract.test.ts` and its Postgres twin `test/e2e/managed-connector-job-contract.test.ts`.diff --git a/src/core/cycle/concept-writes.ts b/src/core/cycle/concept-writes.tsindex d9bef69049..6af9dc7b4b 100644--- a/src/core/cycle/concept-writes.ts+++ b/src/core/cycle/concept-writes.ts@@ -16,6 +16,7 @@ import { isAvailable } from '../ai/gateway.ts';// source-boost's 1.3× 'concepts/' weighting can actually reach them.import { importFromContent } from '../import-file.ts';import type { ConceptRetryBound } from './concept-retry-bound.ts';+import { publicationHold } from '../persistence/accepted-pending.ts';import {conceptProvenanceCovers, replaceConceptProvenanceLinks, CONCEPT_DEFERRAL_CODES, CONCEPT_HOLD_CODES, publishClassicConcept, publishManagedConcepts,} from './concept-publication.ts';@@ -51,6 +52,8 @@ export interface ConceptWriterDeps {retries: ConceptRetryBound;publicationDeferred: Array<{ concept: string; reason: string }>;publicationHeld: Array<{ concept: string; reason: string }>;+ /** Publications the writer holds (publicationHold): a pending one commits under its request, a contended one is admitted next run. */+ publicationPending: Array<{ concept: string; reason: string }>;linkWarnings: Array<{ concept: string; warning: string }>;/** Called once per concept whose publication steps all landed. */written: () => void;@@ -58,13 +61,15 @@ export interface ConceptWriterDeps {export function conceptWriter(deps: ConceptWriterDeps) {const { engine, maintenance, sourceId: src } = deps;- // A publication that lost a revision race or would lose canonical- // material is recorded and skipped; any other error stops the phase.+ // A publication that lost a revision race, would lose canonical material or+ // is held by the writer (#7547: accepted and still pending, or not admitted+ // on contention) is recorded and skipped; any other error stops the phase.const recorded = (write: ConceptWrite, err: unknown): false => {const code = (err as { code?: unknown }).code;if (typeof code !== 'string') throw err;const reason = `${code}: ${(err as Error).message}`;- if (CONCEPT_DEFERRAL_CODES.has(code)) deps.publicationDeferred.push({ concept: write.concept, reason });+ if (publicationHold(err)) deps.publicationPending.push({ concept: write.concept, reason });+ else if (CONCEPT_DEFERRAL_CODES.has(code)) deps.publicationDeferred.push({ concept: write.concept, reason });else if (CONCEPT_HOLD_CODES.has(code)) deps.publicationHeld.push({ concept: write.concept, reason });else throw err;return false;diff --git a/src/core/cycle/synthesize-concepts.ts b/src/core/cycle/synthesize-concepts.tsindex d9e0722978..3327025b2e 100644--- a/src/core/cycle/synthesize-concepts.ts+++ b/src/core/cycle/synthesize-concepts.ts@@ -326,6 +326,7 @@ export async function runPhaseSynthesizeConcepts(// a held concept cannot be republished without losing canonical material.const publicationDeferred: Array<{ concept: string; reason: string }> = [];const publicationHeld: Array<{ concept: string; reason: string }> = [];+ const publicationPending: Array<{ concept: string; reason: string }> = [];const skippedHumanOwned: string[] = [];const skippedDeleted: string[] = [];const skippedUnchanged: string[] = [];@@ -345,7 +346,7 @@ export async function runPhaseSynthesizeConcepts(opts.progress?.tick(1, `${conceptsWritten} concepts`);};const writer = conceptWriter({ engine, maintenance, sourceId: src, importSourceId: opts.sourceId, brainDir: opts.brainDir, writeThrough: conceptFiles !== null,- retries, publicationDeferred, publicationHeld, linkWarnings, written: countWritten });+ retries, publicationDeferred, publicationHeld, publicationPending, linkWarnings, written: countWritten });for (const group of atomGroups) {const conceptSlug = `concepts/${group.conceptSlug}`;// A concept page this phase did not write belongs to a human (or another@@ -561,14 +562,15 @@ export async function runPhaseSynthesizeConcepts(kind: 'concepts',source_id: opts.sourceId ?? 'default',cost_delta: estimatedSpendUsd,- round_completed_delta: failures.length === 0 && publicationDeferred.length === 0 && publicationHeld.length === 0 ? 1 : 0,+ round_completed_delta: failures.length === 0 && publicationDeferred.length === 0 && publicationHeld.length === 0 && publicationPending.length === 0 ? 1 : 0,halt_delta: failures.length > 0 ? 1 : 0, halt_reason: 'item_error',});}return reportDerivedWriteThrough({phase: 'synthesize_concepts',- status: failures.length > 0 || linkWarnings.length > 0 || publicationDeferred.length > 0 || publicationHeld.length > 0 || skippedFileDrift.length > 0 ? 'warn' : 'ok',+ status: failures.length > 0 || linkWarnings.length > 0 || publicationDeferred.length > 0 || publicationHeld.length > 0 || publicationPending.length > 0+ || skippedFileDrift.length > 0 ? 'warn' : 'ok',duration_ms: 0,summary:`synthesize_concepts: ${conceptsWritten} concepts ` +@@ -583,6 +585,7 @@ export async function runPhaseSynthesizeConcepts((skippedRetryBound.length > 0 ? ` (${skippedRetryBound.length} skipped after ${MAX_CONCEPT_ATTEMPTS} failed attempts on unchanged members)` : '') +(publicationDeferred.length > 0 ? ` (${publicationDeferred.length} publication(s) deferred: page changed, retried next run)` : '') +(publicationHeld.length > 0 ? ` (${publicationHeld.length} publication(s) held: existing page needs import/repair)` : '') ++ (publicationPending.length > 0 ? ` (${publicationPending.length} publication(s) held by the writer (pending or contended), finished later or retried next run)` : '') +(skippedFileDrift.length > 0 ? ` (${skippedFileDrift.length} skipped before synthesis: canonical file differs from the database; ${driftActions.join('; ')})` : ''),details: {concepts_written: conceptsWritten,@@ -605,6 +608,7 @@ export async function runPhaseSynthesizeConcepts(folded_spellings: foldedSpellings,publication_deferred: publicationDeferred,publication_held: publicationHeld,+ publication_pending: publicationPending,...(abortedGlobalError ? { aborted_global_error: abortedGlobalError } : {}),estimated_spend_usd: estimatedSpendUsd,budget_usd: budgetCap,diff --git a/test/cycle/synthesize-concepts-accepted-pending.test.ts b/test/cycle/synthesize-concepts-accepted-pending.test.tsnew file mode 100644index 0000000000..06b2672473--- /dev/null+++ b/test/cycle/synthesize-concepts-accepted-pending.test.ts@@ -0,0 +1,68 @@+/**+ * #7547: a concept publication the owner accepted but has not committed by the+ * end of its wait is progress, not a phase failure.+ *+ * Protects: synthesize_concepts on a managed brain records the accepted,+ * still-pending publication (`details.publication_pending`, status warn, no+ * completed round, no halt) instead of throwing `write_pending` and failing+ * the phase; the write keeps its request, commits later, and the next run+ * reuses it without a model call.+ * Fails when: the phase rethrows `write_pending` (or reports the concept+ * written before it commits).+ * Why new: managed-phase-matrix covers a publication that commits within the wait only.+ */+import { afterEach, expect, test } from 'bun:test';+import type { ChatResult } from '../../src/core/ai/gateway.ts';+import { runPhaseSynthesizeConcepts } from '../../src/core/cycle/synthesize-concepts.ts';+import { __setMaintenanceWriteWaitForTests } from '../../src/core/persistence/maintenance-wait.ts';+import { installFaultHook } from '../../src/core/persistence/fault-points.ts';+import { waitForWrite } from '../../src/core/persistence/service.ts';+import type { WriteRequest } from '../../src/core/persistence/model.ts';+import { managedBrain } from '../helpers/managed-brain.ts';+import { testWaitMs } from '../helpers/wait-for.ts';++const MODEL = 'anthropic:claude-sonnet-4-6';+const CONCEPT = 'concepts/storage-example';+const ATOMS = [0, 1, 2, 3, 4].map(i => ({ slug: `atoms/storage-${i}`, concept_refs: [CONCEPT], body: `Atom ${i} about storage.`, title: `storage atom ${i}` }));++afterEach(() => { installFaultHook(undefined); });++test('#7547: a concept publication still pending after its wait is recorded as pending, commits later, and is not re-bought', async () => {+ await managedBrain(async ({ engine, root }) => {+ await engine.setConfig('models.dream.synthesize', MODEL);+ let calls = 0;+ const chat = async (): Promise<ChatResult> => {+ calls++;+ const text = 'A complete narrative about this concept.';+ return { text, blocks: [{ type: 'text', text }], stopReason: 'end', usage: { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: MODEL, providerId: 'anthropic' };+ };+ const run = () => runPhaseSynthesizeConcepts(engine, { _atoms: ATOMS, _chat: chat, brainDir: root });++ let release!: () => void;+ const stalled = new Promise<void>(resolve => { release = resolve; });+ installFaultHook(async point => { if (point === 'consumer:prepared') await stalled; });+ const restore = __setMaintenanceWriteWaitForTests(testWaitMs(300));+ try {+ const first = await run();+ expect(first.status).toBe('warn');+ expect(first.details).toMatchObject({ concepts_written: 0, failures: [] });+ expect((first.details.publication_pending as Array<{ concept: string; reason: string }>).map(p => [p.concept, p.reason.split(':')[0]]))+ .toEqual([['storage-example', 'write_pending']]);+ const [rollup] = await engine.executeRaw<{ rounds: number; halts: number }>(+ "SELECT COALESCE(sum(round_completed_count),0)::int AS rounds, COALESCE(sum(halt_count),0)::int AS halts FROM extract_rollup_7d WHERE kind='concepts'");+ expect(rollup).toEqual({ rounds: 0, halts: 0 });+ } finally { release(); restore(); }++ const open = await engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE source_id='default' AND state NOT IN ('committed','failed','cancelled')");+ expect(open.length).toBeGreaterThan(0);+ for (const row of open) expect((await waitForWrite(engine, row, { engine: engine.kind }, testWaitMs(20_000))).state).toBe('committed');+ expect((await engine.getPage(CONCEPT, { sourceId: 'default' }))?.frontmatter?.synthesis_mode).toBe('llm');++ const second = await run();+ expect(calls).toBe(1);+ expect(second.details.skipped_unchanged).toEqual([CONCEPT]);+ expect(second.details.provenance_restored).toEqual([CONCEPT]);+ }, { setup: async ({ engine }) => {+ for (const atom of ATOMS) await engine.putPage(atom.slug, { type: 'note', title: atom.title, compiled_truth: atom.body, timeline: '', frontmatter: {} });+ } });+}, 120_000);