Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(atoms): date page-derived atoms by their source page's content date (#6720)

garrytan65a9d60742e6
diff --git a/docs/.wave18-fragments/lane3.md b/docs/.wave18-fragments/lane3.md
index cc1d79da5a..570bb42e51 100644
--- a/docs/.wave18-fragments/lane3.md
+++ b/docs/.wave18-fragments/lane3.md
@@ -34,3 +34,24 @@ Lane 3 branch: capy/wave18-lane3. Each section names the target file, the place
### CHANGELOG.md (wave entry, Fixed)
- Pinning a question no longer makes doctor warn about an undeclared `question` page type on the default schema pack (#6742). `gbrain-base-v2` is now 1.4.0.
+
+## #6720 atom pages inherit the source page's content date
+
+### src/core/behavior-change-notice.ts (append to BEHAVIOR_CHANGES)
+
+```ts
+ { since: '<WAVE>', text: 'A page-derived atom now carries its source page\'s content date as frontmatter `date` (the source\'s stored `effective_date`, else the same precedence import uses), so its `effective_date` is the date of the conversation or note it came from instead of the extraction run (#6720); `extracted_at` stays the processing stamp and transcript-derived atoms are unchanged. Atoms extracted before this release keep their run dates until re-extracted (`gbrain dream --phase extract_atoms` with `--force` re-pays the model); a preview-first backfill repair is planned.' },
+```
+
+### CHANGELOG.md (wave entry, Fixed; credit)
+
+- Atoms extracted from a page are dated by that page's content date, not by when extraction ran, so date filters and recency ranking over atoms work (#6720). Existing atoms are not backfilled in this release. Contributed by @javieraldape (idea from #6737).
+
+### PR body
+
+- `Supersedes #6737` (reimplemented: helper peeled into `src/core/cycle/atom-source-date.ts` instead of a module-size ratchet raise; single source-page fetch before inference kept).
+- Deferred: #6720 backfill of existing atom dates, a preview-first repair, next wave.
+
+### scripts/module-size-limits.tsv
+
+- No row change: `src/core/cycle/extract-atoms.ts` is 1653 of its 1654 ceiling after this commit.
diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.md
index 63f63671c7..0217f62ff7 100644
--- a/docs/architecture/key-files/core-cycle.md
+++ b/docs/architecture/key-files/core-cycle.md
@@ -22,7 +22,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/cycle/extract-atoms-budget-notice.ts` — #6425: `drainBudgetNotice(result)` renders the `atom_drain_budget` notice a `budget`-stopped drain carries in `gbrain dream --drain --json` (spend, per-run cap, pages left; paid fix `gbrain config set cycle.extract_atoms.budget_usd <USD>`, verify `gbrain config get`), and `usd` formats the amounts for the stderr stop line. Dynamically imported by `dream.ts` so its notice-rendering imports stay out of the CLI flag scan. Tests: `test/dream-drain-failure-summary.serial.test.ts`.
- `src/core/cycle/extract-atoms-input.ts` — #6503 the input cap and the partial disposition. `resolveExtractAtomsInputCap` reads `cycle.extract_atoms.max_input_chars` (floor 1000; the older `max_source_chars`, floor 500, loses when both are set; default 50 000) before discovery. `extractAtomsInput(item, cap)` binds the cut once: paste-stripped for a transcript (#5812), UTF-8-safe, with `truncated` measured on the text the cap applied to. A page item also takes its stored `extract_atoms` watermark (`src/core/extraction-watermark.ts`, large pages A7): when the body still starts with the watermarked prefix the model reads only the appended text (its newest `cap` characters when longer), which is still partial input, so the same disposition below applies; `inputTruncatedLine` is null for a complete tail read (not counted, no stderr) and names the window otherwise, and the phase commits the plan once the item's writes committed (a pending managed batch keeps the old watermark). A cut item is extracted once from its head and gets a partial disposition instead of a completion: `input_truncated` counts it on the phase result (and the drain sums it into `input_truncated`, with one `[drain]` line), `inputTruncatedLine` is written to stderr naming the knob, the head atoms publish, no completion stamp is written and nothing is retired. `recordPartialDisposition` stores the cap under (content hash, cap) in `extract_atoms_page_state` / `extract_atoms_transcript_state.partial_input_chars` (migration v240; the page row is pinned to the identity discovery read), and on a managed brain the origin carries `partialInputChars`, which enters the run key, keeps the completion's checkpoint `partial`, skips the page-state stamp and the retirement, and marks the completion outcome `status: 'partial'`. Discovery and the backlog count skip a partial row like a tombstone (`PAGE_SCAN_STATE_EXCLUSION_SQL`, `tombstonedTranscriptsForHashes`, the partial checkpoint); `releasePartialDispositions` runs before discovery with the current cap and clears the rows and checkpoints a raised cap supersedes, so the item is eligible again with zero model calls in between; a content change is a new row. Resumed and budget-skipped items are not counted. `stampTranscriptTombstone` (v146) lives here too. Tests: `test/extract-atoms-input-truncated-6503.test.ts` (PGLite and Postgres, page and transcript, managed and unmanaged).
-- `src/core/cycle/extract-atoms.ts` — the extract_atoms lens phase: mines eligible pages into `atoms/<date>/<stem>-<hash>` pages. The input cap, the cut and the partial disposition of a cut item are in `extract-atoms-input.ts` (#6503). Transcript input is paste-stripped before the cut (#5812); discovery skips self-captures (#5820). Discovery and the backlog count append `connectorAtomExclusionSql` (`connector-atoms.ts`), so connector `email`/`meeting` pages stay out only when `cycle.extract_atoms.connector_pages` is false. The type allowlist is `unionExtractableTypes(packExtractable, packExcluded)`: the legacy floor (meeting, source, article, video, book, original) minus the floor types the active pack declares not extractable (`nonExtractableTypesFromPack`, #5756; a declared type without `extractable: true` is a pack decision, an undeclared type keeps the floor), plus the pack's `extractable: true` types, minus synthesis outputs; gbrain-base is unchanged, gbrain-recommended's `source: false` now holds for atoms as it did for facts. Pinned by `test/pack-extractable-floor-5756.test.ts`. A drain attempt passes `opts.attempt` (`budgetTracker`, `writeWait`) so its batches share one budget and one maintenance publish wait. Eligibility reads source-incarnation/page/full-hash-keyed derived scan state; scan and failure markers do not mutate canonical frontmatter. Managed extraction checks source-wide local authority and owner readiness before provider work, admits outputs plus a completion request together, and replays retained output without another model call. A failed managed batch is retried by the next run instead (#6325, `resumeManagedAtoms` in `persistence/atom-maintenance.ts`); an origin held after `MAX_DETERMINISTIC_FAILURES` (now defined in `extract-atoms-page-state.ts`, re-exported here) is skipped with no model call and counted in `details.held_failed`, never in `failures`. Managed atom files keep provisional source hashes; only the source-incarnation/page/full-hash durable completion receipt excludes an item from discovery and backlog counts. Unmanaged atom completion flips and their cardinality check share a transaction after provenance links persist, so a partial match rolls back and stays retryable. A page-derived atom upserts at its locator-folded slug, else a compatible legacy title-only slug; when both miss, the source page's live bound atoms are loaded once per page per run and exactly one JS-lowercased title match is adopted (a case-only title change never mints a duplicate; zero or several matches mint the new slug). Response parsing lives in `extract-atoms-parse.ts`. An undated source dates its atoms by the source page's creation date (`undated` for transcripts), never the run date. After an unmanaged item completes (`completeUnmanagedItem`), `retireStaleAtoms` soft-deletes that source's atoms from earlier extractions (other or provisional `source_hash`) that this extraction did not re-produce; a cut item neither completes nor retires. Hard `opts.signal` (chat call, pacing, checks before each item and commit) leaves no strike, receipt or rollup; soft `opts.stopSignal` stops before the next item.
+- `src/core/cycle/extract-atoms.ts` — the extract_atoms lens phase: mines eligible pages into `atoms/<date>/<stem>-<hash>` pages. The input cap, the cut and the partial disposition of a cut item are in `extract-atoms-input.ts` (#6503). Transcript input is paste-stripped before the cut (#5812); discovery skips self-captures (#5820). Discovery and the backlog count append `connectorAtomExclusionSql` (`connector-atoms.ts`), so connector `email`/`meeting` pages stay out only when `cycle.extract_atoms.connector_pages` is false. The type allowlist is `unionExtractableTypes(packExtractable, packExcluded)`: the legacy floor (meeting, source, article, video, book, original) minus the floor types the active pack declares not extractable (`nonExtractableTypesFromPack`, #5756; a declared type without `extractable: true` is a pack decision, an undeclared type keeps the floor), plus the pack's `extractable: true` types, minus synthesis outputs; gbrain-base is unchanged, gbrain-recommended's `source: false` now holds for atoms as it did for facts. Pinned by `test/pack-extractable-floor-5756.test.ts`. A drain attempt passes `opts.attempt` (`budgetTracker`, `writeWait`) so its batches share one budget and one maintenance publish wait. Eligibility reads source-incarnation/page/full-hash-keyed derived scan state; scan and failure markers do not mutate canonical frontmatter. Managed extraction checks source-wide local authority and owner readiness before provider work, admits outputs plus a completion request together, and replays retained output without another model call. A failed managed batch is retried by the next run instead (#6325, `resumeManagedAtoms` in `persistence/atom-maintenance.ts`); an origin held after `MAX_DETERMINISTIC_FAILURES` (now defined in `extract-atoms-page-state.ts`, re-exported here) is skipped with no model call and counted in `details.held_failed`, never in `failures`. Managed atom files keep provisional source hashes; only the source-incarnation/page/full-hash durable completion receipt excludes an item from discovery and backlog counts. Unmanaged atom completion flips and their cardinality check share a transaction after provenance links persist, so a partial match rolls back and stays retryable. A page-derived atom upserts at its locator-folded slug, else a compatible legacy title-only slug; when both miss, the source page's live bound atoms are loaded once per page per run and exactly one JS-lowercased title match is adopted (a case-only title change never mints a duplicate; zero or several matches mint the new slug). Response parsing lives in `extract-atoms-parse.ts`. An undated source dates its atoms by the source page's creation date (`undated` for transcripts), never the run date. A page-derived atom's frontmatter `date` is the source page's content date (`atom-source-date.ts`: the stored `effective_date`, else `computeEffectiveDate`), read with the input before the model call, so classic import and managed publication store that `effective_date` (source `date`) and `extracted_at` stays the processing stamp; transcript-derived atoms carry no `date`. After an unmanaged item completes (`completeUnmanagedItem`), `retireStaleAtoms` soft-deletes that source's atoms from earlier extractions (other or provisional `source_hash`) that this extraction did not re-produce; a cut item neither completes nor retires. Hard `opts.signal` (chat call, pacing, checks before each item and commit) leaves no strike, receipt or rollup; soft `opts.stopSignal` stops before the next item.
Managed completion admits revision-pinned `managed_atom_delete` children alongside replacement pages, removes canonical files through the page deletion path, and commits its checkpoint only after every publication and retirement commits.
Both paths prevent LLM-chosen titles that drift between extractions from piling up.
Atom identity: page-derived atoms fold the source-page slug into the slug hash (8 chars, NUL-separated) so two same-date pages emitting the same title get DISTINCT slugs; the source CONTENT hash is deliberately NOT folded (a reworded source still upserts rather than duping); transcript atoms keep the legacy title-only 6-char hash. `resolvePageAtomSlug` adopts a legacy-slug atom with a compatible binding in place on re-extraction (upgrade idempotency — no migration, no duplicate), while `assertAtomImportBinding` fail-closed refuses to reuse a slug bound to a DIFFERENT source locator. Both share `isCompatibleAtomBinding(frontmatter, sourcePageSlug)` — the ONE definition of compatible: bound to THIS source page, or carrying no `source_slug`/`source_path` at all (pre-binding-era adoption, not a clobber); a `source_path`-bound legacy transcript atom or a different `source_slug` is a different origin, and a non-atom page squatting on the slug is refused. `source_quote` is verified at extraction time against the exact `truncateUtf8` prompt prefix the model saw (`locateQuote` advances by full code points): located quotes persist original characters + [start,end) offsets + `source_quote_verified`; unlocatable quotes are dropped with the atom kept. Edges write before the completion flip; per-item drain failures stay typed (bounded, sanitized, reconcilable). Transcript items carry the same failure-count/tombstone machinery as pages, in the `extract_atoms_transcript_state` table (keyed `(source_id, file_path, content_hash)`, 16-char hash prefix, so an edit is a new row): `recordItemFailureCount` counts a transcript's malformed output or prompt-level provider block (`providerContentBlockReason`; never feeds the outage halt) toward `MAX_DETERMINISTIC_FAILURES`, a zero-yield transcript tombstones immediately (as pages do), and `tombstonedTranscriptsForHashes` is the batch read-side gate mirroring `atomsExistingForHashes` (fail-open on error). Reported as `tombstoned_transcripts` (paths), separate from the page-slug `tombstoned_for_failures`. Malformed managed output requires a newly approved protected-job retry identity; publication retry reuses retained output and original/current grants.
diff --git a/src/core/cycle/atom-source-date.ts b/src/core/cycle/atom-source-date.ts
new file mode 100644
index 0000000000..3cfb0a5c89
--- /dev/null
+++ b/src/core/cycle/atom-source-date.ts
@@ -0,0 +1,24 @@
+/**
+ * #6720: the content date a page-derived atom inherits from its source page.
+ *
+ * Read with the extraction input, before the model call, and serialized as
+ * the atom's frontmatter `date`, so classic import and managed publication
+ * (including a retained-output retry) store the same `effective_date`
+ * instead of the extraction run time. The stored projection wins; a legacy
+ * page without one is dated by the same precedence chain import uses.
+ * Transcript-derived atoms have no source page and get no date.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { Page } from '../types.ts';
+import { computeEffectiveDate } from '../effective-date.ts';
+
+export async function atomSourceDate(engine: Pick<BrainEngine, 'getConfig'>, page: Page | null): Promise<string | null> {
+ if (!page) return null;
+ if (page.effective_date) return new Date(page.effective_date).toISOString();
+ const { date } = computeEffectiveDate({
+ slug: page.slug, frontmatter: page.frontmatter ?? {}, filename: page.slug.split('/').pop(),
+ createdAt: new Date(page.created_at), updatedAt: new Date(page.updated_at),
+ timeZone: (await engine.getConfig('brain.timezone')) ?? undefined,
+ });
+ return date ? date.toISOString() : null;
+}
diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.ts
index 4f61f08521..aa6c8fc426 100644
--- a/src/core/cycle/extract-atoms.ts
+++ b/src/core/cycle/extract-atoms.ts
@@ -85,6 +85,7 @@ import { slugifySegment } from '../sync.ts';
import { resolveAlias, resolveTierDefault } from '../model-config.ts';
import { isMissingSchemaObject, warnOncePerProcess } from '../utils.ts';
import { utcDate } from './cycle-date.ts';
+import { atomSourceDate } from './atom-source-date.ts';
import { normalizeForGrounding } from './synthesize-verify.ts';
import type { TranscriptPageIndex } from '../transcripts/discover.ts';
import { managedAtomSession, readAtomOrigin, resumeManagedAtoms, publishManagedAtoms, MANAGED_ATOM_DISCOVERY_SQL, type AtomOrigin } from '../persistence/atom-maintenance.ts';
@@ -1086,8 +1087,10 @@ export async function runPhaseExtractAtoms(
const { promptContent, truncated } = input;
try {
const origin: AtomOrigin | null = managed ? { ...await readAtomOrigin(engine, managed, item), ...(truncated ? { partialInputChars: maxInputChars } : {}) } : null;
+ const sourcePage = item.kind === 'page' ? await engine.getPage(item.slug, { sourceId }) : null;
+ const contentDate = await atomSourceDate(engine, sourcePage); // #6720: captured with the input, before inference
const visibility = origin?.visibility ?? effectiveVisibility(item.kind === 'transcript' ? { kind: 'transcript' } // #5525
- : { kind: 'page', page: await engine.getPage(item.slug, { sourceId }) });
+ : { kind: 'page', page: sourcePage });
throwIfAborted(opts.signal, 'extract_atoms');
const resumed = !opts.dryRun && managed && origin ? await resumeManagedAtoms(engine, managed, origin) : 'run';
if (resumed === 'done') { duplicatesSkipped++; continue; }
@@ -1173,7 +1176,6 @@ export async function runPhaseExtractAtoms(
// write below). Page-kind items only — transcripts are files, not
// pages, so there is no from-endpoint to link.
const provenanceLinks: LinkBatchInput[] = [];
- const sourcePage = item.kind === 'page' ? await engine.getPage(item.slug, { sourceId }) : null;
const undatedDate = sourcePage?.created_at ? utcDate(new Date(sourcePage.created_at)) : 'undated';
for (const atom of atoms) {
const srcRef = item.kind === 'transcript' ? item.filePath : item.slug;
@@ -1226,6 +1228,7 @@ export async function runPhaseExtractAtoms(
{
atom_type: atom.atom_type,
...originFrontmatter,
+ ...(contentDate ? { date: contentDate } : {}),
// Provisional until the whole item's atoms persist (see above).
source_hash: `pending:${hash16}`,
visibility, ...(origin ? { managed_extraction: true } : {}),
diff --git a/test/extract-atoms-source-date.test.ts b/test/extract-atoms-source-date.test.ts
new file mode 100644
index 0000000000..a6726c16eb
--- /dev/null
+++ b/test/extract-atoms-source-date.test.ts
@@ -0,0 +1,85 @@
+/**
+ * #6720: a page-derived atom inherits its source page's content date.
+ *
+ * Protects: date filters and recency ranking over atoms. The atom writer
+ * stamped only `extracted_at`, so canonical import dated every atom at
+ * the extraction run (`created_at` fallback). The source date is captured
+ * with the extraction input, before the model call, and serialized into the
+ * atom's frontmatter `date`, so classic import and managed publication
+ * (test/helpers/managed-atoms-contract.ts) store the same date.
+ * Regression: dropping the stamp, reading the date after inference, or
+ * borrowing a date for a transcript-derived atom (no source page).
+ * Model calls go through the `_chat` seam; persistence is real PGLite.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { configureGateway, resetGateway, type ChatResult } from '../src/core/ai/gateway.ts';
+import { runPhaseExtractAtoms } from '../src/core/cycle/extract-atoms.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+
+let engine: PGLiteEngine;
+beforeAll(async () => {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+afterAll(async () => { await engine?.disconnect(); resetGateway(); });
+
+const reply = (): ChatResult => ({
+ text: '[{"title":"Exit criteria lesson","atom_type":"insight","body":"Clear exit criteria keep pilots from stalling."}]',
+ blocks: [], stopReason: 'end', model: 'anthropic:claude-haiku-4-5', providerId: 'anthropic',
+ usage: { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 },
+});
+const body = 'The pilot needs clear exit criteria before it starts. '.repeat(40);
+
+async function onlyAtom(sourceId: string) {
+ const rows = await engine.executeRaw<{ slug: string }>("SELECT slug FROM pages WHERE source_id=$1 AND type='atom'", [sourceId]);
+ expect(rows).toHaveLength(1);
+ return (await engine.getPage(rows[0]!.slug, { sourceId }))!;
+}
+
+describe('#6720 atom content dates', () => {
+ for (const fx of [
+ { id: 'filename', slug: 'meetings/2026-07-09-review', fm: '', legacy: false, date: '2026-07-09T00:00:00.000Z' },
+ { id: 'frontmatter-date', slug: 'notes/2026-07-09-review', fm: 'date: 2026-05-04\n', legacy: false, date: '2026-05-04T00:00:00.000Z' },
+ { id: 'legacy-no-projection', slug: 'meetings/2026-04-02-review', fm: '', legacy: true, date: '2026-04-02T00:00:00.000Z' },
+ ]) {
+ test(`a page-derived atom carries the source page's ${fx.id} date, captured before the model call`, async () => {
+ const sourceId = `atom-date-${fx.id}`;
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
+ await importFromContent(engine, fx.slug, `---\ntype: source\ntitle: Review\n${fx.fm}---\n${body}`, { sourceId, noEmbed: true });
+ // A same-slug page in another source with another date must never leak in.
+ await engine.putPage(fx.slug, { type: 'source', title: 'Other source', compiled_truth: body, effective_date: new Date('2026-01-01'), effective_date_source: 'date' });
+ if (fx.legacy) await engine.executeRaw('UPDATE pages SET effective_date=NULL, effective_date_source=NULL WHERE source_id=$1 AND slug=$2', [sourceId, fx.slug]);
+ const page = (await engine.getPage(fx.slug, { sourceId }))!;
+ const result = await runPhaseExtractAtoms(engine, {
+ sourceId, _transcripts: [], _pages: [{ slug: page.slug, content: page.compiled_truth, contentHash: page.content_hash! }],
+ _chat: async () => {
+ await engine.executeRaw('UPDATE pages SET effective_date=$3 WHERE source_id=$1 AND slug=$2', [sourceId, fx.slug, new Date('2026-09-01')]);
+ return reply();
+ },
+ });
+ expect(result.details?.atoms_extracted).toBe(1);
+ const atom = await onlyAtom(sourceId);
+ expect(atom.frontmatter.source_slug).toBe(fx.slug);
+ expect(atom.frontmatter.date).toBe(fx.date);
+ expect(new Date(atom.effective_date!).toISOString()).toBe(fx.date);
+ expect(atom.effective_date_source).toBe('date');
+ expect(new Date(atom.frontmatter.extracted_at as string).getTime()).toBeGreaterThan(Date.parse('2026-10-01'));
+ }, 60_000);
+ }
+
+ test('a transcript-derived atom has no source page and borrows no date', async () => {
+ const sourceId = 'atom-date-transcript';
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
+ const result = await runPhaseExtractAtoms(engine, {
+ sourceId, _pages: [], _transcripts: [{ filePath: '/fake/2026-07-09-call.txt', content: body, contentHash: 'ab'.repeat(32) }],
+ _chat: async () => reply(),
+ });
+ expect(result.details?.atoms_extracted).toBe(1);
+ const atom = await onlyAtom(sourceId);
+ expect(atom.frontmatter.date).toBeUndefined();
+ expect(atom.effective_date_source).not.toBe('date');
+ }, 60_000);
+});
diff --git a/test/helpers/managed-atoms-contract.ts b/test/helpers/managed-atoms-contract.ts
index 6753708a6e..2033a912e8 100644
--- a/test/helpers/managed-atoms-contract.ts
+++ b/test/helpers/managed-atoms-contract.ts
@@ -39,7 +39,9 @@ export async function exerciseManagedAtoms(engine: BrainEngine, scenario: Case):
await disposePersistenceConsumer(engine);
await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
- await engine.putPage('notes/example', { type: 'source', title: 'Example', compiled_truth: 'A private project record. '.repeat(40), frontmatter: { visibility: 'private' } }, { sourceId });
+ const contentDate = '2026-07-09T15:45:00.000Z'; // #6720: page-derived atoms inherit it, transcript-derived ones never do
+ await engine.putPage('notes/example', { type: 'source', title: 'Example', compiled_truth: 'A private project record. '.repeat(40),
+ frontmatter: { visibility: 'private', date: contentDate }, effective_date: new Date(contentDate), effective_date_source: 'date' }, { sourceId });
const page = (await engine.getPage('notes/example', { sourceId }))!;
const transcript = scenario.startsWith('transcript') ? join(home, 'meeting.txt') : null;
if (transcript) writeFileSync(transcript, page.compiled_truth);
@@ -177,7 +179,8 @@ export async function exerciseManagedAtoms(engine: BrainEngine, scenario: Case):
expect(await worker.getHandler('extract-atoms-drain')!(job)).toMatchObject({ replayed: true, model_rerun: false });
await runPhaseExtractAtoms(engine, opts);
expect(calls).toBe(expectedCalls);
- expect(await engine.executeRaw("SELECT id FROM pages WHERE source_id=$1 AND type='atom'", [sourceId])).toHaveLength(1);
+ const retainedAtoms = await engine.executeRaw<{ date: string | null }>("SELECT frontmatter->>'date' AS date FROM pages WHERE source_id=$1 AND type='atom'", [sourceId]);
+ expect(retainedAtoms).toEqual([{ date: transcript ? null : contentDate }]);
const [unchanged] = await engine.executeRaw<{ state: string; outcome: unknown }>('SELECT state,outcome FROM persistence_requests WHERE request_id=$1::uuid', [receipt.request_id]);
expect(unchanged).toEqual(original);
expect(await readState()).toEqual([{ content_hash: page.content_hash!, fail_count: scenario === 'malformed_retry_failure' ? 2 : scenario.startsWith('malformed_retry') ? 1 : 0, tombstoned: true }]);
@@ -255,6 +258,10 @@ export async function exerciseManagedAtoms(engine: BrainEngine, scenario: Case):
expect(atoms).toHaveLength(scenario === 'zero_yield' || scenario === 'malformed' ? 0 : 1);
if (atoms.length) {
expect(atoms[0].visibility).toBe('private');
+ const atom = (await engine.getPage(atoms[0].slug, { sourceId }))!;
+ expect(atom.frontmatter.date).toBe(transcript ? undefined : contentDate);
+ if (!transcript) expect(new Date(atom.effective_date!).toISOString()).toBe(contentDate);
+ if (root && !transcript) expect(readFileSync(join(root, `${atoms[0].slug}.md`), 'utf8')).toContain(contentDate);
expect(await engine.executeRaw('SELECT c.id FROM content_chunks c JOIN pages p ON p.id=c.page_id WHERE p.source_id=$1 AND p.slug=$2', [sourceId, atoms[0].slug])).not.toHaveLength(0);
if (!transcript) expect(await engine.executeRaw('SELECT l.id FROM links l JOIN pages f ON f.id=l.from_page_id JOIN pages t ON t.id=l.to_page_id WHERE f.source_id=$1 AND t.source_id=$1 AND f.slug=$2 AND t.slug=$3', [sourceId, page.slug, atoms[0].slug])).toHaveLength(1);
if (root) expect(readFileSync(join(root, `${atoms[0].slug}.md`), 'utf8')).toContain('visibility: private');