Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(concepts): unmanaged concept publication keeps file edits (W9F item 3)
time-attackc594a687aec1
diff --git a/docs/architecture/key-files/core-cycle-continued.md b/docs/architecture/key-files/core-cycle-continued.mdindex bc768c893a..ea4b46ef6f 100644--- a/docs/architecture/key-files/core-cycle-continued.md+++ b/docs/architecture/key-files/core-cycle-continued.md@@ -19,7 +19,7 @@ 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/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, then calls `writePageThrough` (which honours `sync.write_through=off`). Tests: `test/cycle/derived-write-through.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/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, then calls `writePageThrough` (which honours `sync.write_through=off`) and returns its result (`written`, `skipped`, `error`) so `publishClassicConcept` can surface a failed write. Tests: `test/cycle/derived-write-through.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, another writer owns it, or the page's file holds an edit the database has not imported (narrative, frontmatter, tags, type or title; formatting is ignored), 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. 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 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/docs/architecture/key-files/files-and-sync-2.md b/docs/architecture/key-files/files-and-sync-2.mdindex 456a89032a..b762aafe99 100644--- a/docs/architecture/key-files/files-and-sync-2.md+++ b/docs/architecture/key-files/files-and-sync-2.md@@ -9,4 +9,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/sync.ts` — Pure sync functions (manifest parsing, filtering, slug conversion). Exported `pruneDir(name: string): boolean` is the single source of truth for descent-time directory exclusion across walkers — blocks `node_modules` (no leading dot, so a naive walker would descend into it and inflate MISSING_OPEN counts via vendor packages), `vendor`/`dist`/`build`/`venv`, dot-prefix dirs, and `*.raw` sidecars — NOT `ops/`, which is ordinary user content (the bundled daily-task-manager stores `ops/tasks` there); `isSyncable` applies it per path segment, and `walkMarkdownFiles` in `src/commands/extract.ts` + `listTextFiles` in `src/core/cycle/transcript-discovery.ts` consult it BEFORE recursing to save the IO of walking thousands of vendor files. `manageGitignore` worktree discriminator matches the gitdir path segment (`/modules/<name>` = submodule, `/worktrees/<name>` = worktree, per Git's documented layout) so Conductor worktrees (first-class repos) get `.gitignore` management for storage-tiering. The sync-failure ledger (failure store, error classifier, the shared bookmark gate, and the doctor severity rule) lives in `src/core/sync-failure-ledger.ts`; `sync.ts` re-exports `classifyErrorCode`, `summarizeFailuresByCode`, `loadSyncFailures`, `unacknowledgedSyncFailures`, `acknowledgeSyncFailures`, `recordSyncFailures`, `decideSyncFailureSeverity`, `applySyncFailureGate`, and the `SyncFailure` type for backward-compatible imports — see its entry below. `isSyncable` factored through private `classifySync(path, opts): SyncableReason | null`; exported companion `unsyncableReason(path, opts)` returns the same tagged reason or null when syncable. `SYNC_SKIP_FILES` is a named export (the four canonical metafile basenames `schema.md`, `index.md`, `log.md`, `README.md`). `SyncableReason` union: `'metafile' | 'strategy' | 'pruned-dir' | 'include-glob-miss' | 'exclude-glob-hit' | 'malformed-path'`. Malformed filenames are TWO-TIER: `hasMalformedPathSegment` (ADMISSION — control chars on any path; square brackets on `.md`/`.mdx` paths only, so code-strategy lanes keep indexing `app/[id]/page.tsx` framework layouts) vs `isPoisonedPath` (DESTRUCTION — only the injection signature `](` or control chars; sync's row-DELETING lanes gate on this so a bare-bracket markdown row already in the DB survives reconcile while its file exists). `sanitizePathForDisplay` scrubs control bytes + caps length before echoing such paths. The un-syncable cleanup loop (`sweepUnsyncableModified` in `src/commands/sync/deletes.ts`) guards on `unsyncableReason(path)` being `'metafile'` OR `'pruned-dir'` so previously-indexed metafile pages AND deliberately put-created pages under pruned dirs survive every re-sync. Does NOT cover `manifest.deleted` (the upstream filter already strips metafiles). Pinned by `test/sync-isSyncable-shape.test.ts` (15 cases, duality contract) + `test/sync-metafile-skip.test.ts` (3 PGLite cases incl. the renamed `.md → .txt` negative). `pruneDir`: `pruneDir(name, parentDir?)` extended with optional `parentDir`. When provided, additionally rejects directories containing `.git` as a FILE — the git submodule gitfile pattern (regular repos have `.git` as a DIRECTORY; submodules as a file pointing into the parent's `.git/modules/`). Sync + extract walkers thread `parentDir` so the gitfile-as-FILE check fires per descend step. Best-effort: `statSync` failures fall through and treat as a normal dir. Prevents phantom imports from a worktree-with-submodules sync walking into submodule trees. Pinned by `test/sync-walker-submodule.test.ts`. The legacy failure ledger re-export is distinct from managed cursor-keyed mirrors: repeat managed observation does not inflate attempts, success clears only the matching cursor, and managed failures cannot be acknowledged or auto-skipped.-- `src/core/write-through.ts` — shared atomic disk write-through for the canonical ingestion path. `resolvePageWriteTarget(engine, slug, sourceId, { includeDeleted? })` (active rows by default; `includeDeleted: true` resolves a tombstone's recorded `source_path` for the purge remediation retry) is the exported single source of truth for the ONE file a (source, slug) pair lives in on disk: a source with its own `local_path` writes at that tree's ROOT (never nested under `.sources/`); a source without one nests under the host repo (`sync.repo_path`, default at root, non-default under `.sources/<id>/`) unless that path is another source's own working tree (leak guard → `source_repo_belongs_to_other_source`); the page's recorded `source_path` (or a contained absolute `file://` `source_uri`; a relative or host-only `file://` names no local file and is read as absent) is preferred over a slug-derived name so writes land in the file of record instead of minting a twin; and `isWriteTargetContained` rejects hostile rows escaping the tree (`path_escapes_source_root`). The ok-result also carries `sourcePathToBind` — the target expressed in the file scanner's `source_path` convention for the source's pinned `slug_root_mode` (or the mode its first sync would pin, via `scannerSlugRootMode`): GIT-ROOT-relative under `git-root` when the scan root sits inside a git repo, scan-root-relative under `source-root` and for non-git or git-root scan roots, so a put-born page binds the same form managed sync and delete-reconcile key on. Every recorded-path reader (write targets, takes, reconcile, audit, export restore, doctor) decodes with the same mode (`resolveSourceLocalFilePath(..., slugRootMode)`): under `source-root` the scope prefix is removed only from the legacy Git-root form whose remainder names the page slug, and basename rows resolve under the unstripped slug directory. The resolver is shared by `writePageThrough`, the facts fence writer (`src/core/facts/fence-write.ts`), and fence forget (`src/core/facts/forget.ts`) — the fence appends to the page's file, so all writers MUST compute the identical path or the fence lands in a file sync never reads back and the next extract_facts reconcile deletes the fence-owned DB rows. `writePageThrough(engine, slug, {sourceId?, frontmatterOverrides?, logger?})` resolves the target through it, re-reads the just-written DB row (`getPage`), renders it via `serializePageToMarkdown`, and writes the `.md` so the brain has a committable artifact that round-trips through `gbrain sync`. Rendering from the row keeps the serialized content consistent at write time. The fsync-backed `atomicWriteFileSync` stages and renames the file after required source-path bookkeeping; lock/lease checks run before publication. `put_page` holds the root lock before importing and invokes write-through inside its database transaction, so ordinary filesystem rejection rolls back existing content, tags, chunks, and versions. A crash or database COMMIT failure after rename can still leave canonical Markdown ahead of the index; this is not distributed ACID or a durable queue. Never throws — returns `WriteThroughResult { written, path?, skipped?: 'disabled_by_config' | 'no_repo_configured' | 'repo_not_found' | 'source_repo_belongs_to_other_source' | 'page_not_found_after_write' | 'path_escapes_source_root' | 'case_insensitive_collision', warning?, error? }` so the caller decides messaging + exit codes. `withNoRepoWriteThroughWarning(result, sourceId)` decorates an unwritten `no_repo_configured` result with `warning` (the write landed only in the database; bind the token/server to a git-backed source or configure `local_path`/`sync.repo_path`); `put_page` applies it for untrusted callers only (`ctx.remote !== false`), so local CLI responses and the `disabled_by_config` operator opt-out stay silent. `isWriteThroughDisabled` (shared with the fence lane, ~30s per-engine cache) honors the `sync.write_through` opt-out. Trust gating (subagent sandbox, dry-run) stays at the CALLER. On a durability-hardened repo (`isDurabilityHardened` — the gbrain post-commit hook is installed, i.e. the user ran `gbrain sources harden`), a successful write is best-effort COMMITTED via `commitWriteThroughFile` (path-limited `git commit -- <file>`, never sweeps unrelated edits; the hook then background-pushes) so write-through content reaches git instead of accumulating uncommitted forever; result carries `committed?: boolean`. Unhardened repos keep write-only behavior. `deletePageThrough(engine, slug, {sourceId?, target?, logger?})` is the delete-side sink (sole caller: the `delete_page` op): resolves the same target, unlinks the `.md`, and on a hardened repo best-effort commits the removal path-limited through the same helper with subject `gbrain: delete write-through <slug>`, reporting `committed?: boolean` on `DeleteThroughResult` (absent when unhardened or when the commit did not land — the unlink still stands; a never-committed page leaves nothing to commit, so no empty commit). Pinned by `test/delete-write-through-commit.test.ts`. Consumers: `put_page` op and `gbrain brainstorm/lsd --save` via `persistSavedIdea`. Pinned by `test/write-through.test.ts` + `test/write-through-commit.test.ts`. The `put_page` op is that deciding caller for direct writes: a skip outside the deliberate DB-only set (`no_repo_configured`/`disabled_by_config`/`subagent_sandbox`/`dry_run`) throws `storage_error` inside the import transaction, rolling back the page revision, tags, chunks and version snapshot instead of deleting a just-created row afterward.+- `src/core/write-through.ts` — shared atomic disk write-through for the canonical ingestion path. `resolvePageWriteTarget(engine, slug, sourceId, { includeDeleted? })` (active rows by default; `includeDeleted: true` resolves a tombstone's recorded `source_path` for the purge remediation retry) is the exported single source of truth for the ONE file a (source, slug) pair lives in on disk: a source with its own `local_path` writes at that tree's ROOT (never nested under `.sources/`); a source without one nests under the host repo (`sync.repo_path`, default at root, non-default under `.sources/<id>/`) unless that path is another source's own working tree (leak guard → `source_repo_belongs_to_other_source`); the page's recorded `source_path` (or a contained absolute `file://` `source_uri`; a relative or host-only `file://` names no local file and is read as absent) is preferred over a slug-derived name so writes land in the file of record instead of minting a twin; and `isWriteTargetContained` rejects hostile rows escaping the tree (`path_escapes_source_root`). The ok-result also carries `sourcePathToBind` — the target expressed in the file scanner's `source_path` convention for the source's pinned `slug_root_mode` (or the mode its first sync would pin, via `scannerSlugRootMode`): GIT-ROOT-relative under `git-root` when the scan root sits inside a git repo, scan-root-relative under `source-root` and for non-git or git-root scan roots, so a put-born page binds the same form managed sync and delete-reconcile key on. Every recorded-path reader (write targets, takes, reconcile, audit, export restore, doctor) decodes with the same mode (`resolveSourceLocalFilePath(..., slugRootMode)`): under `source-root` the scope prefix is removed only from the legacy Git-root form whose remainder names the page slug, and basename rows resolve under the unstripped slug directory. The resolver is shared by `writePageThrough`, the facts fence writer (`src/core/facts/fence-write.ts`), and fence forget (`src/core/facts/forget.ts`) — the fence appends to the page's file, so all writers MUST compute the identical path or the fence lands in a file sync never reads back and the next extract_facts reconcile deletes the fence-owned DB rows. `writePageThrough(engine, slug, {sourceId?, frontmatterOverrides?, logger?, expectedFileBytes?})` resolves the target through it, re-reads the just-written DB row (`getPage`), renders it via `serializePageToMarkdown`, and writes the `.md` so the brain has a committable artifact that round-trips through `gbrain sync`. Rendering from the row keeps the serialized content consistent at write time. The fsync-backed `atomicWriteFileSync` stages and renames the file after required source-path bookkeeping; lock/lease checks run before publication. `put_page` holds the root lock before importing and invokes write-through inside its database transaction, so ordinary filesystem rejection rolls back existing content, tags, chunks, and versions. A crash or database COMMIT failure after rename can still leave canonical Markdown ahead of the index; this is not distributed ACID or a durable queue. Never throws — returns `WriteThroughResult { written, path?, skipped?: 'disabled_by_config' | 'no_repo_configured' | 'repo_not_found' | 'source_repo_belongs_to_other_source' | 'page_not_found_after_write' | 'path_escapes_source_root' | 'case_insensitive_collision' | 'file_changed', warning?, error? }` (`file_changed`: the caller's `expectedFileBytes` preimage, null for absent, no longer matches the file under the source filesystem lock, so the file is left untouched) so the caller decides messaging + exit codes. `withNoRepoWriteThroughWarning(result, sourceId)` decorates an unwritten `no_repo_configured` result with `warning` (the write landed only in the database; bind the token/server to a git-backed source or configure `local_path`/`sync.repo_path`); `put_page` applies it for untrusted callers only (`ctx.remote !== false`), so local CLI responses and the `disabled_by_config` operator opt-out stay silent. `isWriteThroughDisabled` (shared with the fence lane, ~30s per-engine cache) honors the `sync.write_through` opt-out. Trust gating (subagent sandbox, dry-run) stays at the CALLER. On a durability-hardened repo (`isDurabilityHardened` — the gbrain post-commit hook is installed, i.e. the user ran `gbrain sources harden`), a successful write is best-effort COMMITTED via `commitWriteThroughFile` (path-limited `git commit -- <file>`, never sweeps unrelated edits; the hook then background-pushes) so write-through content reaches git instead of accumulating uncommitted forever; result carries `committed?: boolean`. Unhardened repos keep write-only behavior. `deletePageThrough(engine, slug, {sourceId?, target?, logger?})` is the delete-side sink (sole caller: the `delete_page` op): resolves the same target, unlinks the `.md`, and on a hardened repo best-effort commits the removal path-limited through the same helper with subject `gbrain: delete write-through <slug>`, reporting `committed?: boolean` on `DeleteThroughResult` (absent when unhardened or when the commit did not land — the unlink still stands; a never-committed page leaves nothing to commit, so no empty commit). Pinned by `test/delete-write-through-commit.test.ts`. Consumers: `put_page` op and `gbrain brainstorm/lsd --save` via `persistSavedIdea`. Pinned by `test/write-through.test.ts` + `test/write-through-commit.test.ts`. The `put_page` op is that deciding caller for direct writes: a skip outside the deliberate DB-only set (`no_repo_configured`/`disabled_by_config`/`subagent_sandbox`/`dry_run`) throws `storage_error` inside the import transaction, rolling back the page revision, tags, chunks and version snapshot instead of deleting a just-created row afterward.diff --git a/src/core/cycle/concept-publication.ts b/src/core/cycle/concept-publication.tsindex 8e0cabec69..8649e643a7 100644--- a/src/core/cycle/concept-publication.ts+++ b/src/core/cycle/concept-publication.ts@@ -8,7 +8,8 @@*/import type { BrainEngine, LinkBatchInput } from '../engine.ts';import type { Page } from '../types.ts';-import { serializeMarkdown, parseMarkdown } from '../markdown.ts';+import { serializeMarkdown, parseMarkdown, type ParsedMarkdown } from '../markdown.ts';+import { digest } from '../persistence/digest.ts';import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence, replaceOrInsertFactsFence, stripFactsFence } from '../facts-fence.ts';import { TAKES_FENCE_BEGIN, TAKES_FENCE_END, parseTakesFence, stripTakesFence } from '../takes-fence.ts';import { isDbOnly, loadStorageConfig } from '../storage-config.ts';@@ -24,8 +25,10 @@ import { writeDerivedPageThrough } from './derived-write-through.ts';export const CONCEPT_PRESERVATION_CODE = 'concept_preservation_hold';/** Codes that mean the page moved under a concurrent writer; the next run retries. */export const CONCEPT_DEFERRAL_CODES = new Set(['revision_conflict', 'page_identity_changed']);+/** Error code for a concept whose database row published but whose file write failed. */+export const CONCEPT_WRITE_THROUGH_FAILED_CODE = 'concept_write_through_failed';/** Codes that hold a concept until an operator imports or repairs its page. */-export const CONCEPT_HOLD_CODES = new Set(['source_changed', CONCEPT_PRESERVATION_CODE]);+export const CONCEPT_HOLD_CODES = new Set(['source_changed', CONCEPT_PRESERVATION_CODE, CONCEPT_WRITE_THROUGH_FAILED_CODE]);function conceptHoldError(message: string): Error { return Object.assign(new Error(message), { code: CONCEPT_PRESERVATION_CODE }); }@@ -153,28 +156,50 @@ export function stripFenceSections(body: string): string {.replace(/\n{3,}/g, '\n\n').trim();}-/** The page's markdown file, when it has one and write-through is not off: the fence writers write it first. */-async function conceptFile(engine: BrainEngine, slug: string, sourceId: string): Promise<Pick<Page, 'compiled_truth' | 'timeline'> | null> {+/**+ * The page's markdown file when write-through is not off: its raw bytes (null+ * when absent), which bind the later file write to this read, and, when it+ * exists, its parse. The fence writers write the file first.+ */+async function conceptFile(engine: BrainEngine, slug: string, sourceId: string): Promise<{ bytes: string | null; parsed: ParsedMarkdown | null } | null> {if (await isWriteThroughDisabled(engine)) return null;const target = await resolvePageWriteTarget(engine, slug, sourceId);- if (!target.ok || !existsSync(target.filePath)) return null;- const parsed = parseMarkdown(readFileSync(target.filePath, 'utf-8'), target.filePath);- return { compiled_truth: parsed.compiled_truth, timeline: parsed.timeline };+ if (!target.ok) return null;+ if (!existsSync(target.filePath)) return { bytes: null, parsed: null };+ const bytes = readFileSync(target.filePath, 'utf-8');+ return { bytes, parsed: parseMarkdown(bytes, target.filePath) };+}++/**+ * Whether the page's file holds the database row in every part publication+ * takes from the row: the narrative (fences aside, which publication carries+ * from the file), frontmatter, tags, type and title. Formatting differs+ * freely; any edit the database has not imported does not match.+ */+function fileHoldsPage(file: ParsedMarkdown, page: Page, tags: string[]): boolean {+ const owned = (p: { compiled_truth: string; type: string; title: string; frontmatter: Record<string, unknown> }, t: string[]) => digest({+ narrative: stripFenceSections(p.compiled_truth), type: p.type, title: p.title.trim(), frontmatter: p.frontmatter, tags: [...new Set(t)].sort(),+ });+ return owned({ ...file, type: file.typeExplicit ? file.type : page.type }, file.tags) === owned(page, tags);}/*** 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. The- * page's file is rewritten when it already has one (a stale file would- * otherwise be synced back over the new narrative) or when- * `cycle.synthesize_concepts.write_through` is on (#5041). `importPage`- * writes the composed markdown to the database. Returns the narrative now on- * the page (the next call's baseline).+ * since `baseline` (the narrative the synthesis started from), another+ * writer took it over, or its file holds an edit the database has not+ * imported (narrative, frontmatter or tags), nothing is written and the+ * concept is deferred (`revision_conflict`) to the next run; sync imports the+ * edit first. 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. The page's file is rewritten+ * when it already has one (a stale file would otherwise be synced back over+ * the new narrative) or when `cycle.synthesize_concepts.write_through` is on+ * (#5041). `importPage` writes the composed markdown to the database; the+ * file write is then bound to the bytes read under the lock, so an edit made+ * while the import ran is kept and the concept deferred, and a failed file+ * write holds the concept (`concept_write_through_failed`). 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,@@ -189,12 +214,25 @@ export async function publishClassicConcept(engine: BrainEngine, slug: string, sthrow Object.assign(new Error('The concept narrative changed during synthesis.'), { code: 'revision_conflict' });}const title = slug.split('/').pop()!.replace(/-/g, ' ');- const file = page ? await conceptFile(engine, slug, sourceId) : null;+ const file = await conceptFile(engine, slug, sourceId);+ const existing = page && file?.parsed ? file.parsed : null;+ if (existing && !fileHoldsPage(existing, page!, snapshot!.tags)) {+ throw Object.assign(new Error('The concept file holds an edit the database has not imported.'), { code: 'revision_conflict' });+ }const markdown = page- ? composeConceptRepublication({ ...page, ...file }, snapshot!.tags, synthesized, narrative)+ ? composeConceptRepublication({ ...page, ...(existing ? { compiled_truth: existing.compiled_truth, timeline: existing.timeline } : {}) },+ snapshot!.tags, synthesized, narrative): serializeMarkdown(synthesized, narrative, '', { type: 'concept', title, tags: [] });await opts.importPage(markdown);- if (file || opts.writeThrough) await writeDerivedPageThrough(engine, slug, sourceId);+ if (existing || opts.writeThrough) {+ const written = await writeDerivedPageThrough(engine, slug, sourceId, file ? { expectedFileBytes: file.bytes } : {});+ if (written.skipped === 'file_changed') {+ throw Object.assign(new Error('The concept file changed while the page was published; the edit was kept.'), { code: 'revision_conflict' });+ }+ if (written.error) {+ throw Object.assign(new Error(`The concept file was not written: ${written.error}`), { code: CONCEPT_WRITE_THROUGH_FAILED_CODE });+ }+ }return narrative;} finally {await lock.release();diff --git a/src/core/cycle/derived-write-through.ts b/src/core/cycle/derived-write-through.tsindex 4b321cf0c7..a92ff4d82c 100644--- a/src/core/cycle/derived-write-through.ts+++ b/src/core/cycle/derived-write-through.ts@@ -45,18 +45,21 @@ function gitIgnores(root: string, filePath: string): boolean {}/**- * Write one generated page's markdown file. Never throws; returns whether a- * file was written. Ignored and db_only targets are skipped on purpose.+ * Write one generated page's markdown file. Never throws; the result says+ * whether a file was written, why not, or the write error. Ignored and db_only+ * targets are skipped on purpose (`skipped: 'not_canonical'`).+ * `expectedFileBytes` binds the write to the file the caller read.*/-export async function writeDerivedPageThrough(engine: BrainEngine, slug: string, sourceId: string): Promise<boolean> {+export async function writeDerivedPageThrough(engine: BrainEngine, slug: string, sourceId: string,+ opts: { expectedFileBytes?: string | null } = {}): Promise<{ written: boolean; skipped?: string; error?: string }> {const target = await resolvePageWriteTarget(engine, slug, sourceId);- if (!target.ok) return false;+ if (!target.ok) return { written: false, skipped: target.skipped };let storage = null;try { storage = loadStorageConfig(target.writeRoot); } catch { /* unreadable gbrain.yml: sync reports it */ }- if ((storage && isDbOnly(slug, storage)) || gitIgnores(target.writeRoot, target.filePath)) return false;- const result = await writePageThrough(engine, slug, { sourceId });+ if ((storage && isDbOnly(slug, storage)) || gitIgnores(target.writeRoot, target.filePath)) return { written: false, skipped: 'not_canonical' };+ const result = await writePageThrough(engine, slug, { sourceId, expectedFileBytes: opts.expectedFileBytes });if (result.error) console.error(`[write-through] ${slug}: ${result.error}`);- return result.written;+ return result;}/**diff --git a/src/core/write-through.ts b/src/core/write-through.tsindex e0f0074fc8..d7146e13c1 100644--- a/src/core/write-through.ts+++ b/src/core/write-through.ts@@ -22,7 +22,7 @@ import { hasSourceFilesystemLock, withSourceFilesystemLock, assertSourceFilesyst* only does "row exists + repo is a real dir → render + atomic write".*/-import { existsSync, statSync, mkdirSync, unlinkSync, readdirSync } from 'fs';+import { existsSync, statSync, mkdirSync, unlinkSync, readdirSync, readFileSync } from 'fs';import { basename, dirname, isAbsolute, join, relative, resolve } from 'path';import { atomicWriteFileSync } from './atomic-write.ts';import type { BrainEngine } from './engine.ts';@@ -88,8 +88,11 @@ export interface WriteThroughResult {* (macOS/Windows default), the target directory already holds a* differently-cased entry that the FS folds onto this page's file, so* writing would silently clobber the OTHER slug's file (#2831) — refused.+ * - file_changed: the caller passed `expectedFileBytes` and the file on+ * disk no longer holds them (an edit landed after the caller read it) —+ * the edit is kept and nothing is written.*/- skipped?: 'disabled_by_config' | 'no_repo_configured' | 'repo_not_found' | 'source_repo_belongs_to_other_source' | 'page_not_found_after_write' | 'path_escapes_source_root' | 'case_insensitive_collision';+ skipped?: 'disabled_by_config' | 'no_repo_configured' | 'repo_not_found' | 'source_repo_belongs_to_other_source' | 'page_not_found_after_write' | 'path_escapes_source_root' | 'case_insensitive_collision' | 'file_changed';/** Caller-visible advisory when a permitted DB-only outcome is still risky. */warning?: string;/** Set when the render/write/rename itself threw (EACCES, ENOTDIR, disk full). */@@ -101,6 +104,13 @@ export interface WritePageThroughOpts {/** Merged over the page's own frontmatter at render time (e.g. provenance). */frontmatterOverrides?: Record<string, unknown>;logger?: WriteThroughLogger;+ /**+ * The file bytes the caller read before writing the database row (null:+ * the file was absent). Rechecked under the source filesystem lock right+ * before the rename; a file that changed since is left untouched+ * (`skipped: 'file_changed'`). Omitted: no preimage check.+ */+ expectedFileBytes?: string | null;}export function withNoRepoWriteThroughWarning<T extends { written: boolean; skipped?: string; warning?: string }>(result: T, sourceId: string, operation = 'put_page'): T {@@ -450,6 +460,11 @@ export async function writePageThrough(// EEXIST when the directory already exists (POSIX no-ops it). That aborts// the put_page / enrich / capture write-through whenever the prefix dir// already exists, silently leaving the DB and the .md file plane out of sync.+ if (opts.expectedFileBytes !== undefined+ && (existsSync(filePath) ? readFileSync(filePath, 'utf-8') : null) !== opts.expectedFileBytes) {+ return { written: false, skipped: 'file_changed' };+ }+assertSourceFilesystemActive();if (!existsSync(dir)) mkdirSync(dir, { recursive: true });diff --git a/test/cycle/concept-publication-file-recheck.test.ts b/test/cycle/concept-publication-file-recheck.test.tsnew file mode 100644index 0000000000..70f5ce9d07--- /dev/null+++ b/test/cycle/concept-publication-file-recheck.test.ts@@ -0,0 +1,125 @@+// W9F item 3: unmanaged concept publication binds its file write to the file+// it read under the page lock.+//+// Protects: on an unmanaged brain a narrative, frontmatter or tag edit made+// to a concept's markdown file (not yet imported) is never overwritten by+// `publishClassicConcept`; an edit that lands while the database import runs+// is kept too (the file write rechecks the bytes it read); both defer with+// `revision_conflict`, and the concept publishes once sync imports the edit.+// A file that differs only in formatting publishes on the first try, and a+// failed file write holds the concept instead of reporting success.+// Fails when: the publication compares only the database row with its+// baseline (the pre-fix behavior) and rewrites the file from the database,+// silently dropping the user's edit, or swallows a write-through failure.++import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { chmodSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { serializeMarkdown } from '../../src/core/markdown.ts';+import { publishClassicConcept } from '../../src/core/cycle/concept-publication.ts';+import { _resetWriteThroughCacheForTest, writePageThrough } from '../../src/core/write-through.ts';+import { resetPgliteState } from '../helpers/reset-pglite.ts';++const SLUG = 'concepts/launch-dates';+const BASELINE = 'Launch dates slip when nobody owns them.';+const SYNTHESIZED = 'SYNTHESIZED: launch dates need a single owner.';+let engine: PGLiteEngine;+let repo: string;+let file: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60000);++afterAll(async () => {+ await engine.disconnect();+});++const frontmatter = { synthesized_by: 'synthesize_concepts-v0.41', tier: 2, member_hash: 'h1', visibility: 'world' };++beforeEach(async () => {+ await resetPgliteState(engine);+ _resetWriteThroughCacheForTest();+ repo = mkdtempSync(join(tmpdir(), 'gbrain-concept-recheck-'));+ execFileSync('git', ['init', '-q'], { cwd: repo });+ await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [repo]);+ await importFromContent(engine, SLUG, serializeMarkdown(frontmatter, BASELINE, '', { type: 'concept', title: 'launch dates', tags: ['ops'] }), { noEmbed: true });+ const written = await writePageThrough(engine, SLUG, { sourceId: 'default' });+ expect(written.written).toBe(true);+ file = written.path!;+});++const importPage = (markdown: string) => importFromContent(engine, SLUG, markdown, { noEmbed: true });+const publish = (opts: { importPage?: (markdown: string) => Promise<unknown> } = {}) => publishClassicConcept(engine, SLUG, 'default',+ { ...frontmatter, member_hash: 'h2' }, SYNTHESIZED, BASELINE, { writeThrough: false, importPage: opts.importPage ?? importPage });+const codeOf = async (p: Promise<unknown>) => p.then(() => 'published', (err: { code?: string }) => err.code ?? String(err));++describe('publishClassicConcept file recheck (W9F item 3)', () => {+ test('a narrative edit made only to the file defers and survives', async () => {+ writeFileSync(file, readFileSync(file, 'utf-8').replace(BASELINE, `${BASELINE}\n\nUSER EDIT: the board owns launch dates.`));+ expect(await codeOf(publish())).toBe('revision_conflict');+ expect(readFileSync(file, 'utf-8')).toContain('USER EDIT: the board owns launch dates.');+ expect((await engine.getPage(SLUG))!.compiled_truth).toBe(BASELINE);+ });++ test('a frontmatter-only or tag-only edit to the file defers and survives', async () => {+ const original = readFileSync(file, 'utf-8');+ writeFileSync(file, original.replace('tier: 2', 'tier: 2\nowner: alice-example'));+ expect(await codeOf(publish())).toBe('revision_conflict');+ expect(readFileSync(file, 'utf-8')).toContain('owner: alice-example');++ writeFileSync(file, original.replace(' - ops', ' - ops\n - launch'));+ expect(await codeOf(publish())).toBe('revision_conflict');+ expect(readFileSync(file, 'utf-8')).toContain('- launch');+ });++ test('an edit landing while the database import runs is kept', async () => {+ const outcome = await codeOf(publish({+ importPage: async (markdown) => {+ const result = await importPage(markdown);+ writeFileSync(file, readFileSync(file, 'utf-8').replace(BASELINE, `${BASELINE} MID-IMPORT EDIT.`));+ return result;+ },+ }));+ expect(outcome).toBe('revision_conflict');+ expect(readFileSync(file, 'utf-8')).toContain('MID-IMPORT EDIT.');+ expect(readFileSync(file, 'utf-8')).not.toContain(SYNTHESIZED);+ });++ test('a formatting-only difference publishes on the first try', async () => {+ const original = readFileSync(file, 'utf-8');+ const reordered = original.replace('tier: 2\n', '').replace('member_hash: h1\n', 'member_hash: h1\ntier: 2\n')+ .replace(BASELINE, `\n\n${BASELINE}\n\n\n`);+ expect(reordered).not.toBe(original);+ writeFileSync(file, reordered);+ expect(await codeOf(publish())).toBe('published');+ expect(readFileSync(file, 'utf-8')).toContain(SYNTHESIZED);+ });++ test('a deferred concept publishes once sync imports the edit', async () => {+ writeFileSync(file, readFileSync(file, 'utf-8').replace(BASELINE, `${BASELINE} USER EDIT.`));+ expect(await codeOf(publish())).toBe('revision_conflict');+ await importFromContent(engine, SLUG, readFileSync(file, 'utf-8'), { noEmbed: true });+ const baseline = (await engine.getPage(SLUG))!.compiled_truth;+ await publishClassicConcept(engine, SLUG, 'default', { ...frontmatter, member_hash: 'h2' }, SYNTHESIZED, baseline,+ { writeThrough: false, importPage });+ expect(readFileSync(file, 'utf-8')).toContain(SYNTHESIZED);+ });++ test('a failed file write holds the concept instead of reporting success', async () => {+ const dir = join(repo, 'concepts');+ chmodSync(dir, 0o555);+ try {+ expect(await codeOf(publish())).toBe('concept_write_through_failed');+ } finally {+ chmodSync(dir, 0o755);+ }+ expect(readFileSync(file, 'utf-8')).toContain(BASELINE);+ });+});