Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(extract_atoms): a captured session's atoms go only to its #6268 frozen source (#7846)

garrytane273de3c9d66
diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.md
index 8e7a38e28c..a66355ad32 100644
--- a/docs/architecture/key-files/core-cycle.md
+++ b/docs/architecture/key-files/core-cycle.md
@@ -23,7 +23,8 @@ 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; `countExtractAtomsBacklog` reads the same cap and counts a page whose partial row or checkpoint sits below it (`pageScanStateExclusionSql` / `managedAtomDiscoverySql` with the cap; #7391), so a drain, doctor and autopilot see it before any phase has released it, while counting itself writes nothing (`test/extract-atoms-raised-cap-drain-7391.test.ts`); 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`. Atoms of one item that resolve to one slug (a repeated title) publish once, the first kept (#7514: two items at one key failed the generation, managed `generation_live_conflict`, unmanaged a primary-key violation). A managed item whose atom write did not commit is a write failure (`atomWriteFailure`, `persistence/atom-maintenance.ts`): its `failures` entry carries `request_id`, `code`, and its strike, never a provider classification. 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.
+- `src/core/cycle/extract-atoms-source-routing.ts` — #7846 session source for extract_atoms. `keepAtomSourceTranscripts` resolves each session-corpus file through `resolveCorpusFileSource` (`context/corpus-source.ts`, the #6268 resolver the facts sweep uses): a file of the run's source is kept, a file of another source is counted under `corpus_source_other`, and a file with no usable evidence of its source is counted under the resolver's hold reason; nothing falls back to the run's source, and files outside the corpus pass. `withAtomSourceRouting` appends both counts to the phase summary and `details.source_routing` with the fix (`gbrain dream --source <id> --phase extract_atoms`, and `gbrain sweep --assign-corpus <source>` for unresolved and legacy holds, already-swept files included). Tests: `test/extract-atoms-session-source-7846.test.ts` (PGLite and Postgres).
+- `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) and keeps only the session-corpus files `extract-atoms-source-routing.ts` resolves to the run's source (#7846); the meeting transcripts dir is read only for `default`. 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`. Atoms of one item that resolve to one slug (a repeated title) publish once, the first kept (#7514: two items at one key failed the generation, managed `generation_live_conflict`, unmanaged a primary-key violation). A managed item whose atom write did not commit is a write failure (`atomWriteFailure`, `persistence/atom-maintenance.ts`): its `failures` entry carries `request_id`, `code`, and its strike, never a provider classification. 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/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 614f5caa65..aa94c23436 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -47,4 +47,4 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: link
src/core/search/evidence-delivery.ts 1733 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move)
src/commands/config.ts 1524 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal)
src/commands/mcp-expose.ts 1512 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts)
-src/core/behavior-change-notice.ts 1522 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row
+src/core/behavior-change-notice.ts 1524 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: +2 the #7846 extract_atoms session-source row (master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row
diff --git a/src/commands/sweep.ts b/src/commands/sweep.ts
index 36cf4353e3..ed98df1bb0 100644
--- a/src/commands/sweep.ts
+++ b/src/commands/sweep.ts
@@ -226,7 +226,7 @@ async function runAssignCorpus(engine: BrainEngine, args: string[]): Promise<voi
const dir = await sessionCorpusDir(engine);
const { assignCorpusSessions, listCorpusSourceHolds } = await import('../core/context/corpus-source.ts');
const sources = await engine.executeRaw<{ id: string }>('SELECT id FROM sources ORDER BY id LIMIT 2');
- const holds = listCorpusSourceHolds(dir, sources.length === 1);
+ const holds = listCorpusSourceHolds(dir, sources.length === 1, { includeIngested: true });
const sessions = holds.sessions.filter(s => onlySession === undefined || s === onlySession);
const apply = args.includes('--apply');
const assigned = apply ? assignCorpusSessions(dir, sessions, sourceId) : [];
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 2930eba00f..09b743c79e 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1324,6 +1324,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.479.0', id: 'v0_13_1_grandfather_retired', text: 'Upgrading a brain whose migration ledger never recorded v0.13.1 (one created by `gbrain init` before v0.60.412.0, or opened from a new GBRAIN_HOME) no longer writes `validate: false` into every page\'s frontmatter: `gbrain apply-migrations` records v0.13.1 complete and changes no page, so no content_hash moves and a repo brain\'s files and Git history stay as the user wrote them. The stamp only opted a page out of the BrainWriter validators, which never refuse a write, and out of `gbrain integrity` scans, so on such a brain those scans now include the pages a fresh brain would scan. A page that already carries `validate` keeps it, and a grandfather write an older gbrain left queued ends `conflict` without writing. Pages an older release stamped keep the stamp; their pre-stamp frontmatter is in `~/.gbrain/migrations/v0_13_1-rollback.jsonl` on the machine that ran it.' },
// #7617 / #7618 / #7644 / #7655 conversion. `since` is stamped at the merge slot.
{ since: '0.60.480.0', id: 'git_conversion_withhold_progress_push', text: '`gbrain sources canonical <source> --to git --apply` now converts a source with private pages instead of refusing: a private page whose committed file differs from it has the file\'s removal committed and stays in the database (`withhold` in the preview; before, the apply refused `git_conversion_blocked`), a private page whose file was removed by hand is withheld instead of deleted by the strict pass, and a private page whose committed file still equals it keeps that file in Git, as before. The apply prints a progress line on stderr at each phase and every 10 seconds, and prints a partial report on stdout when stopped by SIGTERM, SIGINT or SIGHUP (exit 143, 130 or 129). The source is git-canonical once `recordConversion` runs before strict_pass_2; the runtime report is authoritative: a stop before that leaves the source mixed, and a new preview lists what is left. Where the source pushes its commits, the apply pushes its own; a push that does not land is named in the receipt with the command that pushes now. One path Git cannot check no longer discards every adoption candidate, and holds clear only after the strict recheck passes.' },
+ // #7846 extract_atoms session source. `since` is stamped at the merge slot.
+ { since: 'TBD', id: 'extract_atoms_session_source_7846', text: 'Dream `extract_atoms` writes a captured session\'s atoms only into the source its session recorded (the `.src-<id>` name in the corpus `sourced/` folder, or the session\'s frozen record), never into `default`. Each source\'s run now reads the session corpus and keeps only its own sessions (`gbrain dream --source <id> --phase extract_atoms`); meeting transcripts stay with `default`. A session whose source never resolved, and a file written before sessions recorded their source on a brain with more than one source (already-swept ones included), is held until `gbrain sweep --assign-corpus <source>` previews and `--apply` maps it. The phase summary and `details.source_routing` count both. Atoms an earlier release already wrote into the wrong source are not moved (#7846).' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/context/corpus-source.ts b/src/core/context/corpus-source.ts
index 007a13bc48..ecc24ebfe1 100644
--- a/src/core/context/corpus-source.ts
+++ b/src/core/context/corpus-source.ts
@@ -309,8 +309,10 @@ export interface CorpusSourceHolds {
* Doctor/CLI view of the held files that only an operator mapping can
* release (a multi-source brain's legacy files and unresolved sessions).
* Engine-free; `soleSource` is the caller's `SELECT id FROM sources` answer.
+ * `includeIngested` (the operator mapping) also lists sessions the sweep already
+ * extracted: dream synthesis holds them too until their source is known (#7805).
*/
-export function listCorpusSourceHolds(corpusDir: string, soleSource: boolean): CorpusSourceHolds {
+export function listCorpusSourceHolds(corpusDir: string, soleSource: boolean, opts: { includeIngested?: boolean } = {}): CorpusSourceHolds {
const out: CorpusSourceHolds = { legacy_unstamped: 0, unresolved: 0, sessions: [] };
const spool = corpusSpoolDir(corpusDir);
const sessions = new Set<string>();
@@ -319,7 +321,7 @@ export function listCorpusSourceHolds(corpusDir: string, soleSource: boolean): C
try { names = readdirSync(dir); } catch { return; }
const present = new Set(names);
for (const name of names) {
- if (!name.endsWith('.txt') || present.has(name + '.ingested')) continue;
+ if (!name.endsWith('.txt') || (!opts.includeIngested && present.has(name + '.ingested'))) continue;
const sid = corpusFileSessionId(name);
if (readSessionSource(spool, sid)?.source_id) continue;
if (location === 'spool') {
diff --git a/src/core/cycle/extract-atoms-source-routing.ts b/src/core/cycle/extract-atoms-source-routing.ts
new file mode 100644
index 0000000000..217b8057eb
--- /dev/null
+++ b/src/core/cycle/extract-atoms-source-routing.ts
@@ -0,0 +1,76 @@
+/**
+ * #7846: extract_atoms writes a captured session's atoms only to the source
+ * #6268 froze for it, never to the source the cycle runs for.
+ *
+ * Every session-corpus file resolves through `resolveCorpusFileSource`, the
+ * resolver the facts sweep and dream synthesis use: a spool file's stamp, or
+ * its session's frozen record (an unresolved record with a cwd is frozen first
+ * from the brain's resolution chain, as the sweep does), and a top-level legacy
+ * file only with durable evidence of its source. A file of the cycle's source
+ * is extracted; a file of another source is skipped (`corpus_source_other`)
+ * and extracts when the phase runs for that source; a file with no evidence of
+ * its source is held with the resolver's reason until
+ * `gbrain sweep --assign-corpus <source>` maps its session. Nothing falls back
+ * to the cycle's source. Files outside the session corpus (the meeting
+ * transcripts dir) are not session captures and pass unchanged.
+ */
+import { basename, dirname, isAbsolute, relative, resolve } from 'node:path';
+import type { BrainEngine } from '../engine.ts';
+import type { PhaseResult } from '../cycle.ts';
+import { corpusSpoolDir } from '../context/corpus-segments.ts';
+import { resolveCorpusFileSource, type CorpusSourceHold } from '../context/corpus-source.ts';
+
+export interface AtomSourceRouting {
+ /** Corpus files of other sources, counted by the source each belongs to. */
+ corpus_source_other: Record<string, number>;
+ /** Corpus files with no usable evidence of their source, counted by the resolver's hold reason. */
+ held: Record<string, number>;
+}
+
+export const emptyAtomSourceRouting = (): AtomSourceRouting => ({ corpus_source_other: {}, held: {} });
+
+/** The holds an operator mapping releases: the session never recorded a source. */
+const MAPPABLE_HOLDS: ReadonlySet<CorpusSourceHold> = new Set(['corpus_source_unresolved', 'corpus_legacy_unstamped']);
+
+function corpusLocation(filePath: string, corpusDir: string): 'spool' | 'legacy' | null {
+ const root = resolve(corpusDir);
+ const file = resolve(filePath);
+ const rel = relative(root, file);
+ if (!rel || rel.startsWith('..') || isAbsolute(rel)) return null;
+ return dirname(file) === resolve(corpusSpoolDir(root)) ? 'spool' : 'legacy';
+}
+
+/** The transcripts this run may extract into `sourceId`; every other corpus file is counted in `routing`. */
+export async function keepAtomSourceTranscripts<T extends { filePath: string }>(engine: BrainEngine, transcripts: T[],
+ opts: { corpusDir: string; sourceId: string }, routing: AtomSourceRouting): Promise<T[]> {
+ const kept: T[] = [];
+ for (const t of transcripts) {
+ const location = corpusLocation(t.filePath, opts.corpusDir);
+ if (!location) { kept.push(t); continue; }
+ const owner = await resolveCorpusFileSource(engine, opts.corpusDir, basename(t.filePath), location);
+ if (!owner.ok) routing.held[owner.reason] = (routing.held[owner.reason] ?? 0) + 1;
+ else if (owner.sourceId !== opts.sourceId) routing.corpus_source_other[owner.sourceId] = (routing.corpus_source_other[owner.sourceId] ?? 0) + 1;
+ else kept.push(t);
+ }
+ return kept;
+}
+
+/** Names every corpus file the phase left out, with the command that extracts or releases it. */
+export function withAtomSourceRouting(result: PhaseResult, routing: AtomSourceRouting, sourceId: string): PhaseResult {
+ const others = Object.entries(routing.corpus_source_other).sort(([a], [b]) => a.localeCompare(b));
+ const held = Object.entries(routing.held).sort(([a], [b]) => a.localeCompare(b));
+ if (!others.length && !held.length) return result;
+ const otherCount = others.reduce((n, [, c]) => n + c, 0);
+ const heldCount = held.reduce((n, [, c]) => n + c, 0);
+ const fix = [
+ ...others.map(([id]) => `gbrain dream --source ${id} --phase extract_atoms`),
+ ...(held.some(([r]) => MAPPABLE_HOLDS.has(r as CorpusSourceHold)) ? ['gbrain sweep --assign-corpus <source>'] : []),
+ ];
+ const parts = [
+ ...(otherCount ? [`${otherCount} corpus file(s) belong to other sources (${others.map(([id, c]) => `${id}: ${c}`).join(', ')}) and extract only under their own source`] : []),
+ ...(heldCount ? [`${heldCount} held with no usable session source (${held.map(([r, c]) => `${r}: ${c}`).join(', ')})`] : []),
+ ];
+ process.stderr.write(`[extract_atoms] source ${sourceId}: ${parts.join('; ')}.${fix.length ? ` Fix: ${fix.join(' | ')}` : ''}\n`);
+ return { ...result, summary: `${result.summary}; ${parts.join('; ')}`,
+ details: { ...result.details, source_routing: { source_id: sourceId, ...routing, fix } } };
+}
diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.ts
index 534f15bf50..c8e5d2b5a7 100644
--- a/src/core/cycle/extract-atoms.ts
+++ b/src/core/cycle/extract-atoms.ts
@@ -51,7 +51,7 @@
// Budget: $0.30/source/run, key `cycle.extract_atoms.budget_usd`.
// Exceeded budget halts with PhaseStatus='warn' + partial result.
//
-// Source-scoped: opts.sourceId gates brain-global transcript discovery,
+// Source-scoped: opts.sourceId gates session-corpus transcripts (#7846),
// the discovery SQL (source_id = $1), the NOT EXISTS idempotency
// subquery (atom.source_id = $1), AND every putPage write
// ({sourceId} third arg). Pre-fix the putPage call was missing the
@@ -67,6 +67,7 @@ import type { ProgressReporter } from '../progress.ts';
import { chat as gatewayChat, withBudgetTracker } from '../ai/gateway.ts';
import { createGlobalLlmHaltTracker, haltedClassOf, providerContentBlockReason, type GlobalLlmErrorClass } from '../ai/errors.ts';
import { derivedWriteThrough, reportFileHolds } from './derived-write-through.ts';
+import { emptyAtomSourceRouting, keepAtomSourceTranscripts, withAtomSourceRouting } from './extract-atoms-source-routing.ts';
import { serializeMarkdown } from '../markdown.ts';
import { DEFAULT_EXTRACT_MAX_INPUT_CHARS, extractAtomsInput, inputTruncatedLine, recordPartialDisposition, releasePartialDispositions, resolveExtractAtomsInputCap, stampTranscriptTombstone, type ExtractAtomsInput, type ExtractAtomsItem } from './extract-atoms-input.ts';
import { commitExtractionPlan, readPageWatermark } from '../extraction-watermark.ts';
@@ -714,10 +715,12 @@ export async function runPhaseExtractAtoms(
// v0.41.2.1: config loader switched to loadConfigWithEngine() so the
// dream.* DB-plane merge from Phase 1 reaches this phase.
let transcripts: Array<{ filePath: string; content: string; contentHash: string; root?: { path: string; label: string } }> = opts._transcripts ?? [];
- // Configured transcript corpus paths are brain-global, so only default discovers them.
+ const sourceRouting = emptyAtomSourceRouting();
+ // Configured transcript paths are brain-global: every source walks the session
+ // corpus and keeps only the files #6268 resolves to it (#7846); the meeting
+ // transcripts dir stays default's.
if (
- sourceId === 'default'
- && transcripts.length === 0
+ transcripts.length === 0
&& opts.brainDir !== undefined
&& opts._transcripts === undefined
) {
@@ -734,10 +737,10 @@ export async function runPhaseExtractAtoms(
const corpusDir = dream?.synthesize?.session_corpus_dir;
const meetingDir = dream?.synthesize?.meeting_transcripts_dir;
if (corpusDir !== undefined) {
- const discovered = discoverTranscripts({
+ const discovered = await keepAtomSourceTranscripts(engine, discoverTranscripts({
corpusDir,
- meetingTranscriptsDir: meetingDir, selfCaptureSessionIds: claudeCliSelfSessionIds(), // #5820, as synthesize
- });
+ meetingTranscriptsDir: sourceId === 'default' ? meetingDir : undefined, selfCaptureSessionIds: claudeCliSelfSessionIds(), // #5820, as synthesize
+ }), { corpusDir, sourceId }, sourceRouting);
transcripts = discovered.map((d) => ({
filePath: d.filePath,
content: d.content,
@@ -872,7 +875,7 @@ export async function runPhaseExtractAtoms(
// Phase-level no-op: nothing to extract today.
if (work.length === 0 && transcripts.length === 0 && pages.length === 0) {
- return reportFileHolds({
+ return withAtomSourceRouting(reportFileHolds({
phase: 'extract_atoms',
status: 'skipped',
duration_ms: 0,
@@ -892,7 +895,7 @@ export async function runPhaseExtractAtoms(
budget_usd: DEFAULT_BUDGET_USD,
dry_run: opts.dryRun ?? false,
},
- }, atomFiles?.held, 'atom');
+ }, atomFiles?.held, 'atom'), sourceRouting, sourceId);
}
// 4. Per work-item: extract atoms via the configured extract_atoms model
@@ -1419,7 +1422,7 @@ export async function runPhaseExtractAtoms(
});
}
- return reportFileHolds({
+ return withAtomSourceRouting(reportFileHolds({
phase: 'extract_atoms',
// A phase that skipped every work item and produced nothing did not
// succeed, even though skips are not failures and leave failures[] empty.
@@ -1466,7 +1469,7 @@ export async function runPhaseExtractAtoms(
source_id: sourceId,
dry_run: opts.dryRun ?? false,
},
- }, atomFiles?.held, 'atom');
+ }, atomFiles?.held, 'atom'), sourceRouting, sourceId);
}
/**
diff --git a/test/e2e/extract-atoms-session-source-7846.test.ts b/test/e2e/extract-atoms-session-source-7846.test.ts
new file mode 100644
index 0000000000..e3a3e79f53
--- /dev/null
+++ b/test/e2e/extract-atoms-session-source-7846.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../extract-atoms-session-source-7846.test.ts'));
diff --git a/test/extract-atoms-session-source-7846.test.ts b/test/extract-atoms-session-source-7846.test.ts
new file mode 100644
index 0000000000..da33127d28
--- /dev/null
+++ b/test/extract-atoms-session-source-7846.test.ts
@@ -0,0 +1,173 @@
+/**
+ * #7846: extract_atoms writes each captured session's atoms only to the
+ * session's own frozen source (#6268: the `.src-<id>` spool stamp, else the
+ * session's `<sid>.source.json` record), never to the cycle's source.
+ *
+ * A brain with default plus two sources and a repo-less brain directory (no Git
+ * checkout; the sources table and the corpus records are the record): a session
+ * stamped to the cycle's source is extracted there; a session stamped, or frozen
+ * by its record, to another source is skipped and extracts only when the phase
+ * runs for that source; an unresolved session and legacy unstamped files (one
+ * the sweep already ingested) are held with the resolver's reason, and
+ * `gbrain sweep --assign-corpus <source> --apply` releases every one of them.
+ * Meeting transcripts stay default's. Before the fix every corpus transcript
+ * was extracted into default and no other source discovered any. Runs on PGLite
+ * and, with DATABASE_URL, Postgres.
+ */
+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { basename, join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runPhaseExtractAtoms } from '../src/core/cycle/extract-atoms.ts';
+import { runSweep } from '../src/commands/sweep.ts';
+import { CORPUS_UNRESOLVED_STAMP, ensureCorpusSpoolDir, sessionCorpusFileName } from '../src/core/context/corpus-segments.ts';
+import { freezeSessionSource } from '../src/core/context/corpus-source.ts';
+import type { GBrainConfig } from '../src/core/config.ts';
+import type { ChatOpts, ChatResult } from '../src/core/ai/gateway.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const backends = testBackends();
+const engines: BrainEngine[] = [];
+let dataDir: string;
+let closePostgres: (() => Promise<void>) | undefined;
+beforeAll(async () => {
+ dataDir = mkdtempSync(join(tmpdir(), 'gbrain-atoms-source-db-'));
+ if (backends.includes('pglite')) {
+ const engine = new PGLiteEngine();
+ await engine.connect({ database_path: dataDir });
+ await engine.initSchema();
+ engines.push(engine);
+ }
+ if (backends.includes('postgres')) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engines.push(pg.engine);
+ closePostgres = pg.close;
+ }
+}, 120_000);
+afterAll(async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ await closePostgres?.();
+ rmSync(dataDir, { recursive: true, force: true });
+});
+
+const QUOTE = 'we keep the quarterly plan in one place so every team reads the same numbers';
+
+function writeTranscript(path: string, topic: string): void {
+ writeFileSync(path, `[user]\n${QUOTE}. Today we covered ${topic}.\n\n${'[assistant]\nNoted, we will measure it for two weeks.\n\n'.repeat(60)}`);
+}
+
+interface Run { result: Awaited<ReturnType<typeof runPhaseExtractAtoms>>; read: string[] }
+
+describe('extract_atoms honors the session\'s frozen source (#7846)', () => {
+ test('each session is extracted only into its own source; held files are released by --assign-corpus', async () => {
+ for (const engine of engines) {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-atoms-source-'));
+ const corpus = join(dir, 'corpus');
+ const meetings = join(dir, 'meetings');
+ const brainDir = join(dir, 'brain');
+ for (const d of [corpus, meetings, brainDir, join(dir, 'claude')]) mkdirSync(d);
+ const tag = randomUUID().slice(0, 8);
+ const a = `source-a-${tag}`;
+ const b = `source-b-${tag}`;
+ const cleanup: string[] = [a, b];
+ try {
+ await withEnv({ GBRAIN_HOME: join(dir, 'home'), CLAUDE_CONFIG_DIR: join(dir, 'claude'), GBRAIN_SOURCE: undefined }, async () => {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ for (const id of [a, b]) await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [id]);
+ await engine.setConfig('dream.synthesize.session_corpus_dir', corpus);
+
+ const spool = ensureCorpusSpoolDir(corpus);
+ const own = sessionCorpusFileName('sess-own', 'default');
+ const stamped = sessionCorpusFileName('sess-stamped', b);
+ const recorded = sessionCorpusFileName('sess-recorded', CORPUS_UNRESOLVED_STAMP);
+ const unresolved = sessionCorpusFileName('sess-unresolved', CORPUS_UNRESOLVED_STAMP);
+ writeTranscript(join(spool, own), 'the shared planning calendar');
+ writeTranscript(join(spool, stamped), 'the client renewal terms');
+ writeTranscript(join(spool, recorded), 'the client onboarding checklist');
+ writeTranscript(join(spool, unresolved), 'the hiring loop');
+ writeTranscript(join(corpus, 'sess-legacy.txt'), 'the office move');
+ writeTranscript(join(corpus, 'sess-ingested.txt'), 'the budget review');
+ writeFileSync(join(corpus, 'sess-ingested.txt.ingested'), JSON.stringify({ ingested_at: '2026-01-01T00:00:00.000Z' }) + '\n');
+ writeTranscript(join(meetings, 'standup.txt'), 'the weekly standup');
+ expect(freezeSessionSource(corpus, 'sess-recorded', b, 'operator')?.source_id).toBe(b);
+
+ const extract = async (sourceId: string): Promise<Run> => {
+ const read: string[] = [];
+ const result = await runPhaseExtractAtoms(engine, {
+ sourceId, brainDir, _pages: [],
+ _loadConfig: () => ({ dream: { synthesize: { session_corpus_dir: corpus, meeting_transcripts_dir: meetings } } }) as unknown as GBrainConfig,
+ _chat: async (opts: ChatOpts): Promise<ChatResult> => {
+ const file = basename(/^Source: (.*)$/m.exec(String(opts.messages[0]?.content ?? ''))?.[1] ?? '');
+ read.push(file);
+ const text = JSON.stringify({ atoms: [{ title: `Atom of ${file}`, atom_type: 'insight', body: `A planning habit from ${file}.`,
+ source_quote: QUOTE, lesson: 'Keep one plan.', concepts: ['planning'], virality_score: 10, emotional_register: 'practical' }] });
+ return { text, blocks: [{ type: 'text', text }], stopReason: 'end',
+ usage: { input_tokens: 100, output_tokens: 50, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:claude-haiku-4-5', providerId: 'anthropic' } as ChatResult;
+ },
+ });
+ return { result, read: read.sort() };
+ };
+ const atomSources = async (): Promise<Record<string, string[]>> => {
+ const rows = await engine.executeRaw<{ source_id: string; title: string }>(
+ `SELECT source_id, title FROM pages WHERE type = 'atom' AND deleted_at IS NULL
+ AND source_id IN ('default', $1, $2) ORDER BY source_id`, [a, b]);
+ const out: Record<string, string[]> = {};
+ for (const r of rows) (out[r.title.replace(/^Atom of /, '')] ??= []).push(r.source_id);
+ return out;
+ };
+
+ const first = await extract('default');
+ expect(first.read).toEqual([own, 'standup.txt']);
+ expect(first.result.details.source_routing).toEqual({
+ source_id: 'default',
+ corpus_source_other: { [b]: 2 },
+ held: { corpus_legacy_unstamped: 2, corpus_source_unresolved: 1 },
+ fix: [`gbrain dream --source ${b} --phase extract_atoms`, 'gbrain sweep --assign-corpus <source>'],
+ });
+ expect(first.result.summary).toContain(`2 corpus file(s) belong to other sources (${b}: 2)`);
+ expect(first.result.summary).toContain('3 held with no usable session source');
+
+ const second = await extract(b);
+ expect(second.read).toEqual([recorded, stamped].sort());
+ expect(second.result.details.source_routing).toEqual({
+ source_id: b,
+ corpus_source_other: { default: 1 },
+ held: { corpus_legacy_unstamped: 2, corpus_source_unresolved: 1 },
+ fix: ['gbrain dream --source default --phase extract_atoms', 'gbrain sweep --assign-corpus <source>'],
+ });
+
+ const log = spyOn(console, 'log').mockImplementation(() => {});
+ try {
+ await runSweep(engine, ['--assign-corpus', a, '--apply', '--json']);
+ const out = JSON.parse(String(log.mock.calls.at(-1)?.[0]));
+ expect(out.assigned_sessions).toEqual(['sess-ingested', 'sess-legacy', 'sess-unresolved']);
+ } finally { log.mockRestore(); }
+
+ const third = await extract(a);
+ expect(third.read).toEqual(['sess-ingested.txt', 'sess-legacy.txt', unresolved].sort());
+ expect(third.result.details.source_routing).toEqual({
+ source_id: a, corpus_source_other: { default: 1, [b]: 2 }, held: {},
+ fix: ['gbrain dream --source default --phase extract_atoms', `gbrain dream --source ${b} --phase extract_atoms`],
+ });
+
+ expect(await atomSources()).toEqual({
+ [own]: ['default'], 'standup.txt': ['default'],
+ [recorded]: [b], [stamped]: [b],
+ 'sess-ingested.txt': [a], 'sess-legacy.txt': [a], [unresolved]: [a],
+ });
+ });
+ } finally {
+ await engine.executeRaw(`DELETE FROM pages WHERE type = 'atom'`);
+ for (const id of cleanup) await engine.executeRaw('DELETE FROM sources WHERE id = $1', [id]).catch(() => {});
+ rmSync(dir, { recursive: true, force: true });
+ }
+ }
+ }, 120_000);
+});