Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(concepts): member hash and prompt ignore fence sections; classic rewrite keeps the page fences (D-N3)
time-attack9aff6f34b9ae
diff --git a/docs/architecture/key-files/agent-bootstrap-continued.md b/docs/architecture/key-files/agent-bootstrap-continued.mdindex 624f311183..10de75b71f 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 plus the synthesis model; 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`.+- `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`.diff --git a/docs/architecture/key-files/core-cycle-continued.md b/docs/architecture/key-files/core-cycle-continued.mdindex fd856c81e1..4940833c5e 100644--- a/docs/architecture/key-files/core-cycle-continued.md+++ b/docs/architecture/key-files/core-cycle-continued.md@@ -18,6 +18,6 @@ Synthesis, patterns, consolidation and connector atom gating.- `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/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, holding the concept (`concept_preservation_hold`) when a fence is duplicated, unbalanced, unparseable or below the timeline sentinel. `addManagedProvenanceLinks` commits the concept-provenance edges inside a coordinated transaction. The phase keeps the private-first, provenance, then promotion order; revision races are deferred and holds reported in the phase details. Tests: `test/managed-writers-w3.test.ts`.+- `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, holding the concept (`concept_preservation_hold`) when a fence is duplicated, unbalanced, unparseable or below the timeline sentinel. `addManagedProvenanceLinks` commits the concept-provenance edges inside a coordinated transaction. 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 or another writer owns it, and otherwise composes the new narrative with the latest fences (from the page's file when it has one), so a take added during synthesis survives. `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 reported in the phase details. Tests: `test/managed-writers-w3.test.ts`.- `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/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsvindex fe8a0717e1..6bdb7184dd 100644--- a/scripts/function-size-baseline.tsv+++ b/scripts/function-size-baseline.tsv@@ -38,7 +38,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 303 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/cycle/propose-takes.ts ProposeTakesPhase.process 427 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)-src/core/cycle/synthesize-concepts.ts runPhaseSynthesizeConcepts 451 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+src/core/cycle/synthesize-concepts.ts runPhaseSynthesizeConcepts 464 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)src/core/cycle/synthesize.ts runPhaseSynthesizeInner 1046 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 phasesrc/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 808 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 sealdiff --git a/src/core/cycle/concept-publication.ts b/src/core/cycle/concept-publication.tsindex 0d939b7f2b..3e5883f930 100644--- a/src/core/cycle/concept-publication.ts+++ b/src/core/cycle/concept-publication.ts@@ -15,6 +15,10 @@ import { isDbOnly, loadStorageConfig } from '../storage-config.ts';import { publishMaintenancePage, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';import { withCoordinatedWrite } from '../persistence/context.ts';import { maintenanceAttribution } from '../persistence/attribution.ts';+import { existsSync, readFileSync } from 'node:fs';+import { acquirePageLock } from '../page-lock.ts';+import { importFromContent } from '../import-file.ts';+import { isWriteThroughDisabled, resolvePageWriteTarget } from '../write-through.ts';/** Error code for a concept held because republication could lose canonical material. */export const CONCEPT_PRESERVATION_CODE = 'concept_preservation_hold';@@ -135,3 +139,58 @@ function fenceBlock(body: string, begin: string, end: string): string | null {const stop = body.indexOf(end, start + begin.length);return stop === -1 ? null : body.slice(start, stop + end.length);}++/**+ * A page body without its `## Facts` / `## Takes` sections (each fence block+ * and its heading): the part of an atom or concept this phase reads as+ * narrative. The member hash, the synthesis prompt and the concurrent-change+ * check all use it, so a fact or take added to a page is not a narrative+ * change.+ */+export function stripFenceSections(body: string): string {+ return stripTakesFence(stripFactsFence(body ?? ''))+ .split('\n').filter((line) => !/^##\s+(?:facts|takes)\s*$/i.test(line.trim())).join('\n')+ .replace(/\n{3,}/g, '\n\n').trim();+}++/** The body and timeline a fence writer last wrote: the page's file when it has one, else the database row. */+async function canonicalConceptBody(engine: BrainEngine, slug: string, sourceId: string,+ page: Pick<Page, 'compiled_truth' | 'timeline'>): Promise<Pick<Page, 'compiled_truth' | 'timeline'>> {+ if (await isWriteThroughDisabled(engine)) return page;+ const target = await resolvePageWriteTarget(engine, slug, sourceId);+ if (!target.ok || !existsSync(target.filePath)) return page;+ const parsed = parseMarkdown(readFileSync(target.filePath, 'utf-8'), target.filePath);+ return { compiled_truth: parsed.compiled_truth, timeline: parsed.timeline };+}++/**+ * Publish one concept page on an unmanaged brain (D-N3). Under the page lock+ * the fence writers take, the page is re-read: when its narrative changed+ * since `baseline` (the narrative the synthesis started from) or another+ * writer took it over, nothing is written and the concept is deferred+ * (`revision_conflict`) to the next run. Otherwise the new narrative is+ * composed with the latest `## Facts` / `## Takes` fences, timeline, tags and+ * frontmatter, so a take or fact appended during synthesis survives. Returns+ * the narrative now on the page (the next call's baseline).+ */+export async function publishClassicConcept(engine: BrainEngine, slug: string, sourceId: string,+ synthesized: Record<string, unknown>, narrative: string, baseline: string, noEmbed: boolean): Promise<string> {+ const lock = await acquirePageLock(slug, { timeoutMs: 5_000 });+ if (!lock) throw Object.assign(new Error('The concept page is locked by another writer.'), { code: 'revision_conflict' });+ try {+ const snapshot = await engine.readPageSnapshot(slug, { sourceId });+ const page = snapshot?.page ?? null;+ if (stripFenceSections(page?.compiled_truth ?? '') !== stripFenceSections(baseline)+ || (page && !String(page.frontmatter?.synthesized_by ?? '').startsWith('synthesize_concepts'))) {+ throw Object.assign(new Error('The concept narrative changed during synthesis.'), { code: 'revision_conflict' });+ }+ const title = slug.split('/').pop()!.replace(/-/g, ' ');+ const markdown = page+ ? composeConceptRepublication({ ...page, ...await canonicalConceptBody(engine, slug, sourceId, page) }, snapshot!.tags, synthesized, narrative)+ : serializeMarkdown(synthesized, narrative, '', { type: 'concept', title, tags: [] });+ await importFromContent(engine, slug, markdown, { noEmbed, sourceId });+ return narrative;+ } finally {+ await lock.release();+ }+}diff --git a/src/core/cycle/synthesize-concepts.ts b/src/core/cycle/synthesize-concepts.tsindex b3497dcf76..06100821ff 100644--- a/src/core/cycle/synthesize-concepts.ts+++ b/src/core/cycle/synthesize-concepts.ts@@ -28,19 +28,15 @@ import { writeReceipt } from '../extract/receipt-writer.ts';import { upsertExtractRollup } from '../extract/rollup-writer.ts';import { chat as gatewayChat, isAvailable, isThinkingModel, THINKING_MODEL_MAX_OUTPUT_TOKENS } from '../ai/gateway.ts';import { createGlobalLlmHaltTracker, haltedClassOf, type GlobalLlmErrorClass } from '../ai/errors.ts';-// #2163: concept pages route through importFromContent (the same-// parse→chunk→embed pipeline put_page uses) instead of a bare engine.putPage,-// so they land in the retrieval surface (content_chunks + embeddings) where-// source-boost's 1.3× 'concepts/' weighting can actually reach them.-import { importFromContent } from '../import-file.ts';-import { serializeMarkdown } from '../markdown.ts';import { canonicalLookup, type ModelPricing } from '../model-pricing.ts';import { createHash } from 'node:crypto';import { slugifySegment } from '../sync.ts';import { validatePageSlug } from '../ops/context.ts';import { privatePagesFilterFragment, strictestVisibility, type Visibility } from '../search/private-visibility.ts';import { maintenancePreflight } from '../persistence/prepared-maintenance.ts';-import { addManagedProvenanceLinks, CONCEPT_DEFERRAL_CODES, CONCEPT_HOLD_CODES, publishManagedConcept } from './concept-publication.ts';+import {+ addManagedProvenanceLinks, CONCEPT_DEFERRAL_CODES, CONCEPT_HOLD_CODES, publishClassicConcept, publishManagedConcept, stripFenceSections,+} from './concept-publication.ts';const DEFAULT_BUDGET_USD = 1.5;// Canonical-miss policy — mirrors skillopt/preflight.ts's lookupPrice:@@ -300,6 +296,7 @@ export async function runPhaseSynthesizeConcepts(const publicationHeld: Array<{ concept: string; reason: string }> = [];const skippedHumanOwned: string[] = [];const skippedUnchanged: string[] = [];+ const rehashed: string[] = [];const keptExistingNarrative: string[] = [];for (const group of atomGroups) {const conceptSlug = `concepts/${group.conceptSlug}`;@@ -311,25 +308,36 @@ export async function runPhaseSynthesizeConcepts(skippedHumanOwned.push(conceptSlug);continue;}- // The narrative is a function of the member atoms, their strictest+ // The narrative is a function of the member atoms' narrative (their+ // `## Facts` / `## Takes` sections excluded, D-N3), their strictest// visibility and the model. When none changed and the page holds a real// narrative, there is nothing to spend or rewrite; a fallback page is retried,// and so is one a chat_fallback_chain model wrote (hashed under that model).- const hashFor = (model: string): string => createHash('sha256')- .update(JSON.stringify([model, group.visibility, group.atomSlugs.map((s, i) => [s, group.atomTitles[i], group.atomBodies[i]])+ const hashOf = (model: string, bodies: string[]): string => createHash('sha256')+ .update(JSON.stringify([model, group.visibility, group.atomSlugs.map((s, i) => [s, group.atomTitles[i], bodies[i]]).sort((a, b) => a[0].localeCompare(b[0]))])).digest('hex').slice(0, 16);+ const narrativeBodies = group.atomBodies.map(stripFenceSections);+ const hashFor = (model: string): string => hashOf(model, narrativeBodies);const memberHash = hashFor(synthModel);const priorMode = existing?.frontmatter?.synthesis_mode;- if (existing?.frontmatter?.member_hash === memberHash && (priorMode === 'llm' || priorMode === 'deterministic_tier')) {+ const realNarrative = priorMode === 'llm' || priorMode === 'deterministic_tier';+ if (existing?.frontmatter?.member_hash === memberHash && realNarrative) {skippedUnchanged.push(conceptSlug);continue;}- tierCounts[group.tier]++;+ // A page hashed by the pre-D-N3 formula (full atom bodies) whose inputs are+ // provably unchanged keeps its narrative: only the hash is rewritten, no spend.+ const grandfathered = realNarrative && existing?.frontmatter?.member_hash === hashOf(synthModel, group.atomBodies);+ if (!grandfathered) tierCounts[group.tier]++;let narrative: string;let synthesisMode: ConceptSynthesisMode;let fallbackWriter: string | undefined;- if (group.tier === 'T1' || group.tier === 'T2') {+ if (grandfathered) {+ narrative = existing!.compiled_truth;+ synthesisMode = priorMode as ConceptSynthesisMode;+ rehashed.push(conceptSlug);+ } else if (group.tier === 'T1' || group.tier === 'T2') {if (estimatedSpendUsd >= budgetCap) {narrative = deterministicNarrative(group);synthesisMode = 'budget_fallback';@@ -345,7 +353,7 @@ export async function runPhaseSynthesizeConcepts(`Concept slug: ${group.conceptSlug}\n` +`${group.atomTitles.length} atoms reference this concept.\n\n` +`Sample atom titles:\n${group.atomTitles.slice(0, 10).map((t) => ` - ${t}`).join('\n')}\n\n` +- `Sample atom bodies:\n${group.atomBodies+ `Sample atom bodies:\n${narrativeBodies.slice(0, 5).map((b, i) => `${i + 1}. ${b.slice(0, 500)}`).join('\n\n')}`,@@ -408,17 +416,16 @@ export async function runPhaseSynthesizeConcepts(keptExistingNarrative.push(conceptSlug);continue;}- synthesisModeCounts[synthesisMode]++;+ if (!grandfathered) synthesisModeCounts[synthesisMode]++;if (!opts.dryRun) {- const title = conceptSlug.slice('concepts/'.length);// #5525: tighten-only — a concept already private stays private.const prior = await engine.getPage(conceptSlug, { sourceId: opts.sourceId ?? 'default' });const visibility = strictestVisibility([group.visibility, prior?.frontmatter?.visibility === 'private' ? 'private' : 'world']);// #2163: serialize to markdown and import via the canonical pipeline so// the page is chunked (+ embedded when a provider is configured) —// mirrors put_page's isAvailable('embedding') → noEmbed gate.- const synthesizedAt = new Date().toISOString();+ const synthesizedAt = grandfathered ? String(existing!.frontmatter.synthesized_at ?? new Date().toISOString()) : new Date().toISOString();const synthesized = (pageVisibility: Visibility) => ({tier: group.tier,mention_count: group.atomTitles.length,@@ -432,25 +439,25 @@ export async function runPhaseSynthesizeConcepts(// Each managed publication is bound to the revision the narrative was// synthesized from, then to the previous publication's result.let conceptRevision = existingSnapshot?.revision ?? null;+ // Unmanaged: the narrative the page held when synthesis started; a+ // different narrative under the page lock defers the concept (D-N3).+ let baseline = existing?.compiled_truth ?? '';const publish = async (pageVisibility: Visibility): Promise<void> => {if (maintenance) {conceptRevision = await publishManagedConcept(engine, maintenance, conceptSlug, synthesized(pageVisibility), narrative,conceptRevision, opts.brainDir);return;}- await importFromContent(engine, conceptSlug, serializeMarkdown(synthesized(pageVisibility), narrative, '',- { type: 'concept', title: title.replace(/-/g, ' '), tags: [] }), {- noEmbed: !isAvailable('embedding'),- // #4416: target the cycle's resolved source, not the 'default' literal.- sourceId: opts.sourceId,- });+ // #4416: target the cycle's resolved source, not the 'default' literal.+ baseline = await publishClassicConcept(engine, conceptSlug, opts.sourceId ?? 'default', synthesized(pageVisibility), narrative,+ baseline, !isAvailable('embedding'));};- // A managed publication that lost a revision race or would lose canonical+ // A publication that lost a revision race or would lose canonical// material is recorded and skipped; any other error stops the phase.const publishOrRecord = async (pageVisibility: Visibility): Promise<boolean> => {try { await publish(pageVisibility); return true; } catch (err) {const code = (err as { code?: unknown }).code;- if (!maintenance || typeof code !== 'string') throw err;+ if (typeof code !== 'string') throw err;const reason = `${code}: ${(err as Error).message}`;if (CONCEPT_DEFERRAL_CODES.has(code)) publicationDeferred.push({ concept: group.conceptSlug, reason });else if (CONCEPT_HOLD_CODES.has(code)) publicationHeld.push({ concept: group.conceptSlug, reason });@@ -562,6 +569,7 @@ export async function runPhaseSynthesizeConcepts((linkWarnings.length > 0 ? ` (${linkWarnings.length} provenance-link warning(s))` : '') +(skippedHumanOwned.length > 0 ? ` (${skippedHumanOwned.length} human-owned page(s) left untouched)` : '') +(skippedUnchanged.length > 0 ? ` (${skippedUnchanged.length} unchanged)` : '') ++ (rehashed.length > 0 ? ` (${rehashed.length} rehashed without synthesis)` : '') +(keptExistingNarrative.length > 0 ? ` (${keptExistingNarrative.length} existing narrative(s) kept)` : '') +(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)` : ''),@@ -575,6 +583,7 @@ export async function runPhaseSynthesizeConcepts(link_warnings: linkWarnings,skipped_human_owned: skippedHumanOwned,skipped_unchanged: skippedUnchanged,+ rehashed,kept_existing_narrative: keptExistingNarrative,publication_deferred: publicationDeferred,publication_held: publicationHeld,diff --git a/test/cycle/synthesize-concepts-fences.test.ts b/test/cycle/synthesize-concepts-fences.test.tsnew file mode 100644index 0000000000..6c4bfdc8ae--- /dev/null+++ b/test/cycle/synthesize-concepts-fences.test.ts@@ -0,0 +1,145 @@+// D-N3: synthesize_concepts reads atoms and concept pages without their+// `## Facts` / `## Takes` sections.+//+// Protects: a fence-only edit to a member atom costs no model call; a real+// narrative, model or visibility change still re-synthesizes; a page hashed by+// the pre-fix formula is rehashed without a model call only while its inputs+// are unchanged; on an unmanaged brain a take added to the concept page while+// the model runs survives the rewrite, and a narrative changed during+// synthesis defers the concept instead of being overwritten.+// Fails when: the member hash covers full atom bodies (a take on an atom+// re-buys the concept), or the classic rewrite drops the page's fences.++import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { createHash } from 'node:crypto';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { runPhaseSynthesizeConcepts } from '../../src/core/cycle/synthesize-concepts.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { serializeMarkdown } from '../../src/core/markdown.ts';+import { parseTakesFence, upsertTakeRow } from '../../src/core/takes-fence.ts';+import { resetPgliteState } from '../helpers/reset-pglite.ts';+import type { ChatResult, ChatOpts } from '../../src/core/ai/gateway.ts';++const MODEL = 'anthropic:claude-sonnet-4-6';+let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 240000);++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+ await engine.setConfig('models.dream.synthesize', MODEL);+}, 120000);++function chat(text: string, calls: { n: number }, during?: () => Promise<void>): (o: ChatOpts) => Promise<ChatResult> {+ return async (o: ChatOpts) => {+ calls.n++;+ if (during) await during();+ return {+ text, blocks: [{ type: 'text', text }], stopReason: 'end',+ usage: { input_tokens: 100, output_tokens: 50, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: o.model ?? 'unset', providerId: 'test',+ };+ };+}++type Atom = { slug: string; title: string; body: string; concept_refs: string[]; visibility?: 'world' | 'private' };+const atoms = (bodies: string[] = ['b0', 'b1', 'b2', 'b3', 'b4']): Atom[] => bodies.map((body, i) => ({+ slug: `atoms/a${i}`, title: `A${i}`, body, concept_refs: ['flywheel'], visibility: 'world',+}));+const withTake = (body: string) => upsertTakeRow(body, { claim: 'Flywheels compound', kind: 'take', holder: 'brain', weight: 0.7, active: true }).body;+const run = (input: Atom[], calls: { n: number }, text = 'Narrative one.', during?: () => Promise<void>) =>+ runPhaseSynthesizeConcepts(engine, { _atoms: input, sourceId: 'default', _chat: chat(text, calls, during) });+const concept = () => engine.getPage('concepts/flywheel', { sourceId: 'default' });++describe('member hash ignores fence sections (D-N3)', () => {+ test('a fence-only edit to a member atom costs no model call', async () => {+ const calls = { n: 0 };+ await run(atoms(), calls);+ const fenced = atoms().map((a, i) => (i === 0 ? { ...a, body: withTake(a.body) } : a));+ const r = await run(fenced, calls);+ expect(calls.n).toBe(1);+ expect((r.details as Record<string, unknown>).skipped_unchanged).toEqual(['concepts/flywheel']);+ }, 120000);++ test('a narrative edit, a model change or a visibility change re-synthesizes', async () => {+ const calls = { n: 0 };+ await run(atoms(), calls);+ await run(atoms(['b0 edited', 'b1', 'b2', 'b3', 'b4']), calls);+ expect(calls.n).toBe(2);+ await engine.setConfig('models.dream.synthesize', 'anthropic:claude-opus-4-7');+ await run(atoms(['b0 edited', 'b1', 'b2', 'b3', 'b4']), calls);+ expect(calls.n).toBe(3);+ await run(atoms(['b0 edited', 'b1', 'b2', 'b3', 'b4']).map((a, i) => (i === 1 ? { ...a, visibility: 'private' as const } : a)), calls);+ expect(calls.n).toBe(4);+ }, 120000);+});++describe('pre-fix member hashes (D-N3 grandfathering)', () => {+ const legacyHash = (input: Atom[]) => createHash('sha256')+ .update(JSON.stringify([MODEL, 'world', input.map((a) => [a.slug, a.title, a.body]).sort((x, y) => x[0].localeCompare(y[0]))]))+ .digest('hex').slice(0, 16);+ const seedLegacy = async (hash: string) => {+ await importFromContent(engine, 'concepts/flywheel', serializeMarkdown({+ tier: 'T2', synthesis_mode: 'llm', member_hash: hash, synthesized_at: '2026-01-01T00:00:00.000Z',+ synthesized_by: 'synthesize_concepts-v0.41', visibility: 'world',+ }, 'Legacy narrative.', '', { type: 'concept', title: 'flywheel', tags: [] }), { noEmbed: true, sourceId: 'default' });+ };++ test('unchanged inputs are rehashed without a model call and keep the narrative', async () => {+ const fenced = atoms().map((a, i) => (i === 0 ? { ...a, body: withTake(a.body) } : a));+ await seedLegacy(legacyHash(fenced));+ const calls = { n: 0 };+ const r = await run(fenced, calls);+ expect(calls.n).toBe(0);+ expect((r.details as Record<string, unknown>).rehashed).toEqual(['concepts/flywheel']);+ const page = await concept();+ expect(page!.compiled_truth.trim()).toBe('Legacy narrative.');+ expect(page!.frontmatter.member_hash).not.toBe(legacyHash(fenced));+ await run(fenced, calls);+ expect(calls.n).toBe(0);+ }, 120000);++ test('changed inputs under a legacy hash re-synthesize', async () => {+ await seedLegacy(legacyHash(atoms()));+ const calls = { n: 0 };+ await run(atoms(['b0 edited', 'b1', 'b2', 'b3', 'b4']), calls);+ expect(calls.n).toBe(1);+ }, 120000);+});++describe('classic rewrite keeps the page fences (D-N3)', () => {+ test('a take appended to the concept page during synthesis survives the rewrite', async () => {+ const calls = { n: 0 };+ await run(atoms(), calls);+ const appendTake = async () => {+ const page = await concept();+ await importFromContent(engine, 'concepts/flywheel', serializeMarkdown(page!.frontmatter, withTake(page!.compiled_truth), '',+ { type: 'concept', title: page!.title, tags: [] }), { noEmbed: true, sourceId: 'default' });+ };+ await run(atoms(['b0 edited', 'b1', 'b2', 'b3', 'b4']), calls, 'Narrative two.', appendTake);+ const page = await concept();+ expect(page!.compiled_truth).toContain('Narrative two.');+ expect(parseTakesFence(page!.compiled_truth).takes.map((t) => t.claim)).toEqual(['Flywheels compound']);+ }, 120000);++ test('a narrative rewritten during synthesis defers the concept and is kept', async () => {+ const calls = { n: 0 };+ await run(atoms(), calls);+ const rewrite = async () => {+ const page = await concept();+ await importFromContent(engine, 'concepts/flywheel', serializeMarkdown(page!.frontmatter, 'Edited elsewhere.', '',+ { type: 'concept', title: page!.title, tags: [] }), { noEmbed: true, sourceId: 'default' });+ };+ const r = await run(atoms(['b0 edited', 'b1', 'b2', 'b3', 'b4']), calls, 'Narrative two.', rewrite);+ expect((r.details as { publication_deferred: Array<{ concept: string }> }).publication_deferred.map((d) => d.concept)).toEqual(['flywheel']);+ expect((await concept())!.compiled_truth.trim()).toBe('Edited elsewhere.');+ }, 120000);+});