Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
P2.9 (#5756): honor a pack's explicit extractable: false for legacy-floor atom types
garrytanca8230a1d386
diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.mdindex 8a720210a3..cad21806bd 100644--- a/docs/architecture/key-files/core-cycle.md+++ b/docs/architecture/key-files/core-cycle.md@@ -21,7 +21,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.ts` — the extract_atoms lens phase: mines eligible pages into `atoms/<date>/<stem>-<hash>` pages. 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. 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, `retireStaleAtoms` soft-deletes that source's atoms from earlier extractions (other or provisional `source_hash`) that this extraction did not re-produce. 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. 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.serial.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, `retireStaleAtoms` soft-deletes that source's atoms from earlier extractions (other or provisional `source_hash`) that this extraction did not re-produce. 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/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 46ff6c0eea..83c466decc 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -442,6 +442,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.176.0', text: '`gbrain projections drain` (and the migration drain) no longer loops on one queue row whose revision does not match its page: the row is re-keyed to the page\'s current revision and rebuilt in the same pass, or deleted when the page is already projected or belongs to a dead source incarnation, always as a compare-and-set on the exact row listed so a newer queued row survives. A page whose content changes while it is being rebuilt appears once under `failed` with a `revision_conflict:` reason and stays queued for the next run; `--json` may now list such rows where the command used to hang.' },{ since: '0.60.176.0', text: '`gbrain extract-conversation-facts` now sends every eligible turn of a conversation page to the extractor in bounded windows: a window closes at 30 messages or when its rendered text, header included, would exceed 6,500 characters, and the next turn opens a new window instead of being cut off; a turn too long for one window is split at sentence boundaries with its speaker and timestamp repeated; the 31st reply of a 31-turn group is extracted as its own window instead of being dropped. A dense page therefore takes more extractor calls than before, under the same cost cap. Pages already stamped complete from clipped input are not re-extracted automatically; to recompute them run `gbrain extract-conversation-facts --source <id> --force` (narrowed to one page with its slug option, or the whole source after a `--dry-run` preview of the window count), which spends model calls.' },{ since: '0.60.176.0', text: 'Fact extraction on explicit lanes (sync import, put_page) now measures same-page rewordings: when a page is re-extracted and a new claim sits within cosine 0.85 of a fact the same page produced earlier without changing a number, date, amount or negation, the run counts it as `would_dedup_same_page` and prints one stderr line naming the matched fact id. Nothing is dropped or expired; the counter exists so the rule\'s false-positive rate can be measured before any automatic dedup ships.' },+ { since: '0.60.176.0', text: 'The atom-extraction phase (`extract_atoms`) now honors a schema pack that declares one of the built-in extractable types (meeting, source, article, video, book, original) as `extractable: false`, the way facts extraction already did: such pages are no longer mined into atoms. gbrain-base declares meeting and source extractable and is unchanged; on gbrain-recommended, `source` pages stop being atom-extracted. A pack that does not mention a built-in type keeps it extractable.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.tsindex 069793e234..876492a832 100644--- a/src/core/cycle/extract-atoms.ts+++ b/src/core/cycle/extract-atoms.ts@@ -155,11 +155,13 @@ const PAGE_SCAN_STATE_EXCLUSION_SQL = `AND NOT EXISTS ()`;/**- * Pure allowlist policy: the legacy floor UNION the pack's `extractable: true`- * types, MINUS synthesis outputs. Exported for unit tests; keep I/O-free.+ * Pure allowlist policy: the legacy floor (minus floor types the pack declares not extractable, #5756: the floor+ * covers only types the pack is silent about) UNION the pack's `extractable: true` types, MINUS synthesis outputs.+ * Exported for unit tests; keep I/O-free.*/-export function unionExtractableTypes(packExtractable: Iterable<string>): string[] {+export function unionExtractableTypes(packExtractable: Iterable<string>, packExcluded: Iterable<string> = []): string[] {const types = new Set<string>(LEGACY_EXTRACTABLE_TYPES);+ for (const t of packExcluded) types.delete(t);for (const t of packExtractable) types.add(t);for (const t of SYNTHESIS_OUTPUT_TYPES) types.delete(t);return [...types];@@ -173,17 +175,17 @@ export function unionExtractableTypes(packExtractable: Iterable<string>): string* back to the legacy floor.*/async function resolveExtractableTypes(): Promise<string[]> {- let packExtractable: Iterable<string> = [];+ let packExtractable: Iterable<string> = [], packExcluded: Iterable<string> = [];try {const { loadConfig } = await import('../config.ts');const { loadActivePack } = await import('../schema-pack/load-active.ts');- const { extractableTypesFromPack } = await import('../schema-pack/extractable.ts');+ const { extractableTypesFromPack, nonExtractableTypesFromPack } = await import('../schema-pack/extractable.ts');const resolved = await loadActivePack({ cfg: loadConfig(), remote: false });- packExtractable = extractableTypesFromPack(resolved.manifest);+ packExtractable = extractableTypesFromPack(resolved.manifest); packExcluded = nonExtractableTypesFromPack(resolved.manifest);} catch {// Pack unavailable (test seams, bootstrap) — legacy floor only.}- return unionExtractableTypes(packExtractable);+ return unionExtractableTypes(packExtractable, packExcluded);}export interface ExtractAtomsOpts {diff --git a/src/core/schema-pack/extractable.ts b/src/core/schema-pack/extractable.tsindex 7950bf2d59..41df2c1943 100644--- a/src/core/schema-pack/extractable.ts+++ b/src/core/schema-pack/extractable.ts@@ -53,6 +53,23 @@ export function extractableTypesFromPack();}+/**+ * Page types the pack declares and does NOT mark extractable (#5756). The+ * manifest schema reads an omitted flag as `false`, so a declared type+ * without `extractable: true` is a pack decision; a type the pack never+ * declares is not in this set, which is how the legacy floor in+ * cycle/extract-atoms.ts stays for types a pack is silent about.+ */+export function nonExtractableTypesFromPack(+ pack: Pick<SchemaPackManifest, 'page_types'>,+): Set<string> {+ return new Set(+ pack.page_types+ .filter(pt => !isExtractable(pt.extractable))+ .map(pt => pt.name),+ );+}+/*** Convenience predicate: is this type facts-extractable per the* active pack? Avoids creating a Set on every call when the callerdiff --git a/test/pack-extractable-floor-5756.serial.test.ts b/test/pack-extractable-floor-5756.serial.test.tsnew file mode 100644index 0000000000..4ea7a4a2b0--- /dev/null+++ b/test/pack-extractable-floor-5756.serial.test.ts@@ -0,0 +1,83 @@+/**+ * #5756 (wave 15 P2.9, S half): a schema pack that declares a legacy-floor+ * type as not extractable (`extractable: false`) removes it from atom+ * extraction. The floor (meeting, source, article, video, book, original)+ * applies only to types the active pack is silent about, so gbrain-base+ * (meeting/source declared true, the rest undeclared) is unchanged, while+ * gbrain-recommended's `source: extractable: false` now holds for atoms the+ * way it already did for facts (facts/eligibility.ts).+ *+ * Serial: selects the active pack through GBRAIN_SCHEMA_PACK.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { withEnv } from './helpers/with-env.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { countExtractAtomsBacklog, discoverExtractablePages, unionExtractableTypes } from '../src/core/cycle/extract-atoms.ts';++const LEGACY = ['meeting', 'source', 'article', 'video', 'book', 'original'];++describe('unionExtractableTypes honors an explicit pack exclusion (#5756)', () => {+ test('a floor type the pack declares not extractable is removed; silent floor types stay', () => {+ const r = unionExtractableTypes(['note'], ['source', 'book']);+ expect(r).not.toContain('source');+ expect(r).not.toContain('book');+ for (const t of ['meeting', 'article', 'video', 'original', 'note']) expect(r).toContain(t);+ });++ test('a pack that is silent about every floor type keeps the whole floor', () => {+ const r = unionExtractableTypes(['note'], []);+ for (const t of LEGACY) expect(r).toContain(t);+ });++ test('excluding a non-floor type is a no-op and synthesis outputs stay excluded either way', () => {+ const r = unionExtractableTypes(['concept', 'atom', 'note'], ['writing', 'concept']);+ expect(r).toContain('note');+ for (const t of ['concept', 'atom', 'writing']) expect(r).not.toContain(t);+ for (const t of LEGACY) expect(r).toContain(t);+ });++ test('nonExtractableTypesFromPack names the declared types whose extractable flag resolves to false', async () => {+ const { nonExtractableTypesFromPack, extractableTypesFromPack } = await import('../src/core/schema-pack/extractable.ts');+ const pack = { page_types: [+ { name: 'source', extractable: false },+ { name: 'meeting', extractable: true },+ { name: 'statute', extractable: { prompt_template: 'fidelity' } },+ { name: 'person', extractable: false },+ ] } as never;+ expect([...nonExtractableTypesFromPack(pack)].sort()).toEqual(['person', 'source']);+ expect([...extractableTypesFromPack(pack)].sort()).toEqual(['meeting', 'statute']);+ });+});++describe('discovery under the active pack (#5756)', () => {+ let engine: PGLiteEngine;+ const prose = (n: string) => `A durable statement about ${n}, recorded in prose with enough context to extract. `.repeat(10);++ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ });+ afterAll(async () => { await engine.disconnect(); });+ beforeEach(async () => {+ await engine.executeRaw('DELETE FROM pages');+ await engine.putPage('sources/example-statute', { type: 'source', title: 'Example statute', compiled_truth: prose('the statute') } as never);+ await engine.putPage('meetings/example-sync', { type: 'meeting', title: 'Example sync', compiled_truth: prose('the sync') } as never);+ });++ const slugs = async () => (await discoverExtractablePages(engine, 'default')).map(p => p.slug).sort();++ test('gbrain-base (source declared extractable) discovers both pages', async () => {+ await withEnv({ GBRAIN_SCHEMA_PACK: 'gbrain-base' }, async () => {+ expect(await slugs()).toEqual(['meetings/example-sync', 'sources/example-statute']);+ expect(await countExtractAtomsBacklog(engine, 'default')).toBe(2);+ });+ });++ test('gbrain-recommended (source: extractable false) discovers and counts only the meeting', async () => {+ await withEnv({ GBRAIN_SCHEMA_PACK: 'gbrain-recommended' }, async () => {+ expect(await slugs()).toEqual(['meetings/example-sync']);+ expect(await countExtractAtomsBacklog(engine, 'default')).toBe(1);+ });+ });+});