Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(dream): a clipped concept narrative never replaces a page, and failed narratives are bounded per member hash (#6260)
time-attackfc078f581586
diff --git a/docs/architecture/key-files/agent-bootstrap-continued.md b/docs/architecture/key-files/agent-bootstrap-continued.mdindex dba58250d6..f1b85780bb 100644--- a/docs/architecture/key-files/agent-bootstrap-continued.md+++ b/docs/architecture/key-files/agent-bootstrap-continued.md@@ -35,4 +35,4 @@- `src/core/bootstrap/verify.ts` + `status.ts` — verify is the definition of done: fail-soft check suite over the REAL write path (put_page op → write-through file under `brain/` → in-process sweep → graph floor via link tables → recall), the keyless magic-moment check (`## Facts` fence → zero-LLM reconciliation → world-visibility read-back), source_id collision resolution (as the one bootstrap subcommand holding an engine: a manifest `source_id` already registered to a DIFFERENT checkout → derives a stable `workspace-<8char-path-hash>`, persists it to agent.json, names the re-register steps — every consumer reads `manifest.source_id`), the `embedding_plane` check (keyed installs live-embed ONE probe string and compare the RETURNED width to the actual `content_chunks.embedding` width — a plane split is a named FAIL with the recovery command, keyless passes, a dead probe warns; runs BEFORE the roundtrip so a keyless-passing roundtrip can never certify a brain whose keyed writes all fail), token sweep, byte floors, secret scan, deny globs, repo privacy, hooks smoke (in-process IPC), capability report, first-run tour; snapshots kept last-5 under `<home>/bootstrap/`. status owns the ordered PHASES list (the runbook defers to it), artifact-first detection, install.jsonl, the runbook version-stamp skew check, and the support blob doctor/agents relay verbatim.- `src/core/bootstrap/template-repo.ts` + `scripts/generate-template-repo.ts` — deterministic public-template generation (render `--minimal` + placeholder manifest + stamped README); published only by the release workflow after diffing against the vendored tree.- `scripts/check-bootstrap-tag.sh` / `scripts/check-bootstrap-templates.sh` — CI guards: sanctioned distribution ref only (`latest-stable`; the release job advances it after assets publish) + runbook stamp == VERSION; template↔question-bank token bijection + placeholder-only assertion + offline generator↔vendored byte-diff + runbook-phase↔status.ts consistency. Both skip gracefully when their subjects are absent.-- `src/core/cycle/synthesize-concepts.ts` concept-quality addendum — a `concepts/<x>` page whose frontmatter lacks `synthesized_by: synthesize_concepts-*` belongs to a human or another writer: the phase checks it before any LLM spend, never rewrites it, and reports it in `details.skipped_human_owned` (pinned by `test/cycle/synthesize-concepts-human-owned.test.ts`). Concept refs are normalized before grouping (`conceptStemFor`: last path segment through `slugifySegment`, validated by `validatePageSlug`; one atom counts once per concept), so spelling variants share one page and no slug carries a space. Each page records `member_hash` (member atom slugs, titles and bodies without their `## Facts` / `## Takes` sections, which the prompt also omits, plus the synthesis model; a page still carrying the full-body hash whose inputs are unchanged is rehashed without a model call, `details.rehashed`; a narrative a `chat_fallback_chain` model wrote is hashed under that model, so the next cycle re-synthesizes it); an unchanged hash on an `llm` or `deterministic_tier` page is skipped without spend (`details.skipped_unchanged`), and a budget or error fallback never replaces an existing `llm` narrative (`details.kept_existing_narrative`); fallback pages retry next cycle. Pinned by `test/cycle/synthesize-concepts-identity.test.ts`. Eligible groups are processed deterministically by tier, descending atom count, then concept slug so the fixed LLM budget reaches the strongest evidence first regardless of database row order. Every page and phase receipt distinguishes `llm`, intended `deterministic_tier`, `budget_fallback`, and `error_fallback` synthesis modes. The narrative call's output cap is sized from the resolved `models.dream.synthesize` model via `resolveSynthMaxOutputTokens`: 500 for non-thinking models, the gateway's `THINKING_MODEL_MAX_OUTPUT_TOKENS` (no phase-private number — DeepSeek v4 truncates at 8192-class caps) when the gateway's shared `isThinkingModel` matches (name-matched Claude 5 or recipe-declared `thinking_by_default`; unknown providers count as non-thinking), so a tier-`reasoning` thinking model no longer spends the whole budget on reasoning and persists a template stub or truncated chain-of-thought as the concept narrative. Pinned by `test/cycle/synthesize-concepts-token-cap.test.ts`. Right after each concept page write the phase banks concept<->member-atom provenance edges through `engine.addLinksBatch` (`link_source: 'concept-provenance'`; `synthesized_from` concept->atom, `synthesizes` atom->concept; audit site `cycle.synthesize_concepts.provenance`), both endpoints scoped to the cycle's source, so the concept pages are graph-reachable (backlinks, relational recall, doctor `graph_signals_coverage`/`orphans`) even though the prompt forbids enumerating atoms in the body. The dedicated `link_source` keeps reconcile passes from pruning them; `ON CONFLICT DO NOTHING` makes re-runs the backfill; a failed or zero-row edge write lands in `link_warnings[]` (phase `warn`) — NOT in `failures[]`, which means "LLM-failed → template fallback" downstream and drives the rollup's `halt_delta`/`round_completed_delta` — and never aborts the page write. Atom discovery (the `type = 'atom'` scan) is scoped to the cycle source (`opts.sourceId ?? 'default'`) so same-slug atoms from other sources are never grouped into this source's concepts. Pinned by the `#4589` describe in `test/cycle/extract-atoms-synthesize-concepts.test.ts` and `test/cycle/synthesize-concepts-source-scope.test.ts`. The phase budget is `cycle.synthesize_concepts.budget_usd` (finite USD above 0, default 1.5; `config set` refuses other values, a stored invalid value keeps the default with a named-key warning, specs in `src/core/cycle/phase-config-values.ts`); groups refused at the cap are counted in the summary and `details.warnings`. Pinned by `test/cycle-synthesize-concepts-budget-config.test.ts`.+- `src/core/cycle/synthesize-concepts.ts` concept-quality addendum — a `concepts/<x>` page whose frontmatter lacks `synthesized_by: synthesize_concepts-*` belongs to a human or another writer: the phase checks it before any LLM spend, never rewrites it, and reports it in `details.skipped_human_owned` (pinned by `test/cycle/synthesize-concepts-human-owned.test.ts`). Concept refs are normalized before grouping (`conceptStemFor`: last path segment through `slugifySegment`, validated by `validatePageSlug`; one atom counts once per concept), so spelling variants share one page and no slug carries a space. Each page records `member_hash` (member atom slugs, titles and bodies without their `## Facts` / `## Takes` sections, which the prompt also omits, plus the synthesis model; a page still carrying the full-body hash whose inputs are unchanged is rehashed without a model call, `details.rehashed`; a narrative a `chat_fallback_chain` model wrote is hashed under that model, so the next cycle re-synthesizes it); an unchanged hash on an `llm` or `deterministic_tier` page is skipped without spend (`details.skipped_unchanged`), and a budget or error fallback never replaces an existing `llm` narrative (`details.kept_existing_narrative`); fallback pages retry next cycle. Pinned by `test/cycle/synthesize-concepts-identity.test.ts`. Eligible groups are processed deterministically by tier, descending atom count, then concept slug so the fixed LLM budget reaches the strongest evidence first regardless of database row order. Every page and phase receipt distinguishes `llm`, intended `deterministic_tier`, `budget_fallback`, and `error_fallback` synthesis modes. The narrative call's output cap is sized from the resolved `models.dream.synthesize` model via `resolveSynthMaxOutputTokens`: 500 for non-thinking models, the gateway's `THINKING_MODEL_MAX_OUTPUT_TOKENS` (no phase-private number — DeepSeek v4 truncates at 8192-class caps) when the gateway's shared `isThinkingModel` matches (name-matched Claude 5 or recipe-declared `thinking_by_default`; unknown providers count as non-thinking), so a tier-`reasoning` thinking model no longer spends the whole budget on reasoning and persists a template stub or truncated chain-of-thought as the concept narrative. Pinned by `test/cycle/synthesize-concepts-token-cap.test.ts`. Right after each concept page write the phase banks concept<->member-atom provenance edges through `engine.addLinksBatch` (`link_source: 'concept-provenance'`; `synthesized_from` concept->atom, `synthesizes` atom->concept; audit site `cycle.synthesize_concepts.provenance`), both endpoints scoped to the cycle's source, so the concept pages are graph-reachable (backlinks, relational recall, doctor `graph_signals_coverage`/`orphans`) even though the prompt forbids enumerating atoms in the body. The dedicated `link_source` keeps reconcile passes from pruning them; `ON CONFLICT DO NOTHING` makes re-runs the backfill; a failed or zero-row edge write lands in `link_warnings[]` (phase `warn`) — NOT in `failures[]`, which means "LLM-failed → template fallback" downstream and drives the rollup's `halt_delta`/`round_completed_delta` — and never aborts the page write. Atom discovery (the `type = 'atom'` scan) is scoped to the cycle source (`opts.sourceId ?? 'default'`) so same-slug atoms from other sources are never grouped into this source's concepts. Pinned by the `#4589` describe in `test/cycle/extract-atoms-synthesize-concepts.test.ts` and `test/cycle/synthesize-concepts-source-scope.test.ts`. The phase budget is `cycle.synthesize_concepts.budget_usd` (finite USD above 0, default 1.5; `config set` refuses other values, a stored invalid value keeps the default with a named-key warning, specs in `src/core/cycle/phase-config-values.ts`); groups refused at the cap are counted in the summary and `details.warnings`. Pinned by `test/cycle-synthesize-concepts-budget-config.test.ts`. A narrative whose stop reason is `length`, `refusal` or `content_filter` is a failure (template fallback for a new concept; an existing `llm` page and its `member_hash` stay), and failed narratives are bounded per concept and member hash by `cycle/concept-retry-bound.ts` (`ConceptRetryBound`, DB-only config key `dream.concepts.failed_attempts`, `MAX_CONCEPT_ATTEMPTS` = 3): a bounded concept is skipped before any spend into `details.skipped_retry_bound` until its members change, a narrative succeeds, or the key is unset (`test/cycle/synthesize-concepts-stop-reason.test.ts`).diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsvindex 392a377f76..5736436778 100644--- a/scripts/function-size-baseline.tsv+++ b/scripts/function-size-baseline.tsv@@ -36,7 +36,7 @@ src/core/cycle/extract-facts.ts runExtractFacts 505 seed: W5 baseline, refactorsrc/core/cycle/grade-takes.ts GradeTakesPhase.process 402 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/cycle/patterns.ts runPhasePatterns 310 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +7 fix wave 11 #6177: budget sizing call, submitted-reflection slice and the last_run record (logic in cycle/patterns-plan.ts)src/core/cycle/propose-takes.ts ProposeTakesPhase.process 429 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 #5958 (issue #5874): call_timeout_ms read and its per-page bound (phaseBoundedCallTimeout)-src/core/cycle/synthesize-concepts.ts runPhaseSynthesizeConcepts 477 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 #5490 review: a narrative a chat_fallback_chain model wrote is hashed under that model so the next cycle re-synthesizes it; +13 fix wave 9 lane P (D-N3): fence-stripped member hash with legacy-hash grandfathering, and the classic write moved to publishClassicConcept (concept-publication.ts); +3 (#5041): opt-in concept write-through hook and the import callback publishClassicConcept runs under the page lock; +6 #4907 (issue #4906): configured budget read, budget-capped counter, summary clause and details.warnings (message text in budgetWarnings); +4 fix wave 11 #6161: concept redirects in grouping and the skipped_deleted pre-check (logic in cycle/concept-redirects.ts)+src/core/cycle/synthesize-concepts.ts runPhaseSynthesizeConcepts 490 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 #5490 review: a narrative a chat_fallback_chain model wrote is hashed under that model so the next cycle re-synthesizes it; +13 fix wave 9 lane P (D-N3): fence-stripped member hash with legacy-hash grandfathering, and the classic write moved to publishClassicConcept (concept-publication.ts); +3 (#5041): opt-in concept write-through hook and the import callback publishClassicConcept runs under the page lock; +6 #4907 (issue #4906): configured budget read, budget-capped counter, summary clause and details.warnings (message text in budgetWarnings); +4 fix wave 11 #6161: concept redirects in grouping and the skipped_deleted pre-check (logic in cycle/concept-redirects.ts); +13 fix wave 12 #6260: a narrative stopped before the end is a counted failure, and the per-member-hash retry bound (state in cycle/concept-retry-bound.ts)src/core/cycle/synthesize.ts runPhaseSynthesizeInner 1047 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 #5854: publish_pending from postprocess, a pending summary publish deferred instead of failing the phase; +1 fix wave 11 #6160: oneshot_task_prefixes on the child job datasrc/core/facts/backstop.ts runPipelineBodyInner 358 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/import-file.ts importFromContent 812 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 wave 8 lane D1 #5158: key-order fallback equality and legacy-hash ordering; lowered to 807 (#5988: screen and sanity config peeled to core/import-screen.ts); +1 #6007: the prepared apply reports its written page and seal (PreparedImportApplied) so put_page skips a re-read and a second seal; +1 #5333: embed-skip transition defeats the unchanged fast paths (the stale-marker clear stays inside the sanity block); +3 #6188: Tier 1 fence step in place before the hidden-row merge (logic in fence-repair/import-step.ts)diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 273df8fcbd..d997a6f1a8 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -290,6 +290,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.103.0', text: 'Filtered vector search on Postgres runs pgvector iterative scans in relaxed_order, which keeps closer in-filter matches strict order dropped; `gbrain config set search.hnsw_iterative_scan strict_order` and a restart of serve and autopilot restore the old mode.' },{ since: '0.60.103.0', text: 'With retrieval feedback on, MCP search and query results carry one visible line with the answer id (`Rate after use: rate_answer { answer_id: "ans_…", rating: 1-5 }`), so hosts that hide `_meta` can still rate.' },{ since: '0.60.103.0', text: 'Imported transcript pages now also redact a password typed after a credential label (`password: …`, `login alice / …`) as `<REDACTED:labeled_credential>`; pages imported earlier are not rewritten, so run `gbrain transcripts audit-secrets --json` to list them (doctor `transcript_secret_exposure`).' },+ { since: 'WAVE12', text: 'Dream atom and concept extraction no longer accept a model answer that stopped at the output cap or was refused (claude-cli included): such an answer counts as a failure, never as "nothing to extract" or a new concept narrative. On a managed brain the failed atom batch keeps the page\'s earlier atoms and waits for an approved retry (`gbrain jobs submit extract-atoms-drain --params \'{"sourceId":"<id>","retryRequestId":"<request>"}\'`); a concept that fails 3 times on unchanged atoms is skipped until they change (`gbrain config unset dream.concepts.failed_attempts` retries it now).' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cycle/concept-retry-bound.ts b/src/core/cycle/concept-retry-bound.tsnew file mode 100644index 0000000000..62da554357--- /dev/null+++ b/src/core/cycle/concept-retry-bound.ts@@ -0,0 +1,63 @@+/**+ * #6260: bounded paid retries for a concept whose narrative keeps failing.+ *+ * A concept narrative that fails (a response stopped before the end, an empty+ * response, a per-concept model error) is not stamped with its member hash, so+ * the next pass pays for it again. The bound counts those failures per concept+ * and member hash in the DB-only config key `dream.concepts.failed_attempts`+ * (`{ "<source>:<concept slug>": { member_hash, attempts, at } }`): after+ * MAX_CONCEPT_ATTEMPTS failures on unchanged members the concept is skipped+ * before any spend until its members change, a narrative succeeds, or the+ * operator unsets the key.+ */+import type { BrainEngine } from '../engine.ts';++export const CONCEPT_FAILED_ATTEMPTS_KEY = 'dream.concepts.failed_attempts';+export const MAX_CONCEPT_ATTEMPTS = 3;++interface Entry { member_hash: string; attempts: number; at: string }++export class ConceptRetryBound {+ private dirty = false;+ private constructor(private readonly entries: Record<string, Entry>) {}++ static async load(engine: BrainEngine): Promise<ConceptRetryBound> {+ try {+ const parsed = JSON.parse((await engine.getConfig(CONCEPT_FAILED_ATTEMPTS_KEY)) ?? '{}') as unknown;+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return new ConceptRetryBound({});+ const entries: Record<string, Entry> = {};+ for (const [key, value] of Object.entries(parsed as Record<string, Partial<Entry>>)) {+ if (value && typeof value.member_hash === 'string' && Number.isSafeInteger(value.attempts)) {+ entries[key] = { member_hash: value.member_hash, attempts: value.attempts!, at: String(value.at ?? '') };+ }+ }+ return new ConceptRetryBound(entries);+ } catch {+ return new ConceptRetryBound({});+ }+ }++ exhausted(key: string, memberHash: string): boolean {+ const entry = this.entries[key];+ return !!entry && entry.member_hash === memberHash && entry.attempts >= MAX_CONCEPT_ATTEMPTS;+ }++ fail(key: string, memberHash: string): void {+ const prior = this.entries[key];+ this.entries[key] = { member_hash: memberHash, attempts: prior?.member_hash === memberHash ? prior.attempts + 1 : 1, at: new Date().toISOString() };+ this.dirty = true;+ }++ succeed(key: string): void {+ if (!(key in this.entries)) return;+ delete this.entries[key];+ this.dirty = true;+ }++ async save(engine: BrainEngine): Promise<void> {+ if (!this.dirty) return;+ await engine.setConfig(CONCEPT_FAILED_ATTEMPTS_KEY, JSON.stringify(this.entries)).catch((error: unknown) => {+ console.error(`[synthesize_concepts] could not record failed concept attempts: ${error instanceof Error ? error.message : String(error)}`);+ });+ }+}diff --git a/src/core/cycle/synthesize-concepts.ts b/src/core/cycle/synthesize-concepts.tsindex 5aebbb31d8..4267a4cf5c 100644--- a/src/core/cycle/synthesize-concepts.ts+++ b/src/core/cycle/synthesize-concepts.ts@@ -48,6 +48,7 @@ import {addManagedProvenanceLinks, CONCEPT_DEFERRAL_CODES, CONCEPT_HOLD_CODES, publishClassicConcept, publishManagedConcept, stripFenceSections,} from './concept-publication.ts';import { readPhaseConfigNumber, SYNTHESIZE_CONCEPTS_BUDGET_KEY, SYNTHESIZE_CONCEPTS_DEFAULT_BUDGET_USD } from './phase-config-values.ts';+import { ConceptRetryBound, MAX_CONCEPT_ATTEMPTS } from './concept-retry-bound.ts';// Miss policy for the shared resolver (`priceFor`: operator overrides, the// claude-cli → Anthropic sibling, canonical rows): assume Sonnet-tier@@ -338,6 +339,8 @@ export async function runPhaseSynthesizeConcepts(const keptExistingNarrative: string[] = [];const pricingOverrides = await loadPricingOverrides(engine);const pricingFallbackModels = new Set<string>();+ const retries = await ConceptRetryBound.load(engine); // #6260: bounded paid retries per member hash+ const skippedRetryBound: string[] = [];for (const group of atomGroups) {const conceptSlug = `concepts/${group.conceptSlug}`;// A concept page this phase did not write belongs to a human (or another@@ -383,6 +386,9 @@ export async function runPhaseSynthesizeConcepts(narrative = deterministicNarrative(group);synthesisMode = 'budget_fallback';budgetCapped++;+ } else if (retries.exhausted(`${opts.sourceId ?? 'default'}:${conceptSlug}`, memberHash)) {+ skippedRetryBound.push(conceptSlug);+ continue;} else {try {const result = await chat({@@ -414,14 +420,18 @@ export async function runPhaseSynthesizeConcepts(result.usage.output_tokens * pricing.output) /1_000_000;const text = result.text.trim();- if (text) {+ // #6260: a narrative stopped before the end never replaces a page or advances its member hash.+ const stopped = result.stopReason === 'length' || result.stopReason === 'refusal' || result.stopReason === 'content_filter';+ if (text && !stopped) {({ narrative, unverified: unverifiedClaims } = await groundConceptNarrative(engine, text, group));synthesisMode = 'llm';if (result.fallbackFrom) fallbackWriter = result.model;+ retries.succeed(`${opts.sourceId ?? 'default'}:${conceptSlug}`);} else {- failures.push({ concept: group.conceptSlug, error: 'empty model response' });+ failures.push({ concept: group.conceptSlug, error: stopped ? `output stopped before the end (stopReason=${result.stopReason})` : 'empty model response' });narrative = deterministicNarrative(group);synthesisMode = 'error_fallback';+ retries.fail(`${opts.sourceId ?? 'default'}:${conceptSlug}`, memberHash);}} catch (err) {const msg = err instanceof Error ? err.message : String(err);@@ -444,6 +454,7 @@ export async function runPhaseSynthesizeConcepts(if (llmHalt.lastClass() === 'rate_limit') continue;narrative = deterministicNarrative(group);synthesisMode = 'error_fallback';+ retries.fail(`${opts.sourceId ?? 'default'}:${conceptSlug}`, memberHash);}}} else {@@ -566,6 +577,7 @@ export async function runPhaseSynthesizeConcepts(// fires when concepts were actually written; rollup always fires so doctor// sees the phase ran.const warnings = budgetWarnings(budget.warning, budgetCapped, budgetCap);+ if (!opts.dryRun) await retries.save(engine);// Managed brains skip the receipt page (a legacy putPage), like extract_atoms;// the rollup row below still records the run for doctor.if (!opts.dryRun && !maintenance && conceptsWritten > 0) {@@ -614,6 +626,7 @@ export async function runPhaseSynthesizeConcepts((skippedUnchanged.length > 0 ? ` (${skippedUnchanged.length} unchanged)` : '') +(rehashed.length > 0 ? ` (${rehashed.length} rehashed without synthesis)` : '') +(keptExistingNarrative.length > 0 ? ` (${keptExistingNarrative.length} existing narrative(s) kept)` : '') ++ (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)` : ''),details: {@@ -630,6 +643,7 @@ export async function runPhaseSynthesizeConcepts(skipped_unchanged: skippedUnchanged,rehashed,kept_existing_narrative: keptExistingNarrative,+ skipped_retry_bound: skippedRetryBound,publication_deferred: publicationDeferred,publication_held: publicationHeld,...(abortedGlobalError ? { aborted_global_error: abortedGlobalError } : {}),diff --git a/test/cycle/synthesize-concepts-stop-reason.test.ts b/test/cycle/synthesize-concepts-stop-reason.test.tsnew file mode 100644index 0000000000..f456033d96--- /dev/null+++ b/test/cycle/synthesize-concepts-stop-reason.test.ts@@ -0,0 +1,87 @@+/**+ * #6260: synthesize_concepts reads the narrative's stop reason. A narrative+ * stopped by the output cap, a refusal or a content filter never replaces an+ * existing narrative and never advances the member hash; a new concept gets+ * the template fallback and is retried. Failures on unchanged members are+ * bounded: after MAX_CONCEPT_ATTEMPTS the concept is skipped before any spend+ * until its members change.+ *+ * Hermetic: PGLite + injected `_atoms` and `_chat`.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { runPhaseSynthesizeConcepts } from '../../src/core/cycle/synthesize-concepts.ts';+import { MAX_CONCEPT_ATTEMPTS } from '../../src/core/cycle/concept-retry-bound.ts';+import { resetPgliteState } from '../helpers/reset-pglite.ts';+import type { ChatResult } from '../../src/core/ai/gateway.ts';++let engine: PGLiteEngine;+beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.setConfig('models.dream.synthesize', 'anthropic:claude-sonnet-4-6');+}, 60000);+afterAll(async () => { await engine.disconnect(); });+beforeEach(async () => {+ await resetPgliteState(engine);+ await engine.setConfig('models.dream.synthesize', 'anthropic:claude-sonnet-4-6');+});++const atoms = (n = 5, extra = '') => Array.from({ length: n }, (_, i) => ({+ slug: `atoms/a${i}`, concept_refs: ['concepts/x'], body: `body ${i}${extra}`, title: `A${i}`,+}));++function chatWith(text: string, stopReason: ChatResult['stopReason'], counter: { calls: number }) {+ return async (): Promise<ChatResult> => {+ counter.calls++;+ return { text, blocks: [{ type: 'text', text }], stopReason,+ usage: { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'anthropic:claude-sonnet-4-6', providerId: 'anthropic' };+ };+}++async function concept() {+ const page = await engine.getPage('concepts/x', { sourceId: 'default' });+ return page && { body: page.compiled_truth, mode: page.frontmatter.synthesis_mode, hash: page.frontmatter.member_hash };+}++describe('synthesize_concepts stop reasons (#6260)', () => {+ test('an existing llm narrative survives a clipped answer with its body and member hash', async () => {+ const counter = { calls: 0 };+ await runPhaseSynthesizeConcepts(engine, { _atoms: atoms(), _chat: chatWith('A complete narrative about x.', 'end', counter) });+ const before = await concept();+ expect(before?.mode).toBe('llm');+ const changed = atoms(5, ' changed');+ const r = await runPhaseSynthesizeConcepts(engine, { _atoms: changed, _chat: chatWith('A clipped narr', 'length', counter) });+ expect(JSON.stringify(r.details.failures)).toContain('stopReason=length');+ const after = await concept();+ expect(after?.body).toBe(before?.body);+ expect(after?.hash).toBe(before?.hash);+ });++ for (const stop of ['length', 'refusal', 'content_filter'] as const) {+ test(`${stop}: a new concept gets the template fallback, and an end answer later writes the narrative`, async () => {+ const counter = { calls: 0 };+ await runPhaseSynthesizeConcepts(engine, { _atoms: atoms(), _chat: chatWith('Partial', stop, counter) });+ expect((await concept())?.mode).toBe('error_fallback');+ await runPhaseSynthesizeConcepts(engine, { _atoms: atoms(), _chat: chatWith('A complete narrative about x.', 'end', counter) });+ const page = await concept();+ expect(page?.mode).toBe('llm');+ expect(page?.body).toContain('A complete narrative about x.');+ });+ }++ test(`repeated clipped answers on unchanged members stop calling the model after ${MAX_CONCEPT_ATTEMPTS} attempts`, async () => {+ const counter = { calls: 0 };+ const chat = chatWith('Partial', 'length', counter);+ for (let i = 0; i < MAX_CONCEPT_ATTEMPTS + 2; i++) await runPhaseSynthesizeConcepts(engine, { _atoms: atoms(), _chat: chat });+ expect(counter.calls).toBe(MAX_CONCEPT_ATTEMPTS);+ const skipped = await runPhaseSynthesizeConcepts(engine, { _atoms: atoms(), _chat: chat });+ expect(skipped.details.skipped_retry_bound).toEqual(['concepts/x']);+ expect(counter.calls).toBe(MAX_CONCEPT_ATTEMPTS);+ // Changed members re-arm the concept.+ await runPhaseSynthesizeConcepts(engine, { _atoms: atoms(5, ' new'), _chat: chat });+ expect(counter.calls).toBe(MAX_CONCEPT_ATTEMPTS + 1);+ });+});