Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(extract): keep the reserved type key out of extract receipt frontmatter (#7058)
garrytan6ba459867b1d
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.mdindex 70e4192579..118584669e 100644--- a/docs/architecture/key-files/graph-and-facts.md+++ b/docs/architecture/key-files/graph-and-facts.md@@ -94,7 +94,7 @@ rejection of serve-only flags before a brain opens.- `src/core/extract-frontmatter.ts` — `resolveIncludeFrontmatter(engine, explicit?)`: the single answer for "extract `related:`/`sources:` frontmatter link edges too?" (`autopilot.incremental_extract_include_frontmatter`; explicit flag > file plane > DB plane via `isConfigTruthy` > false, fail-closed on an unreadable config table). Resolved INSIDE the shared helpers — `extractLinksForSlugs` and `extractStaleFromDB` default `opts.includeFrontmatter` through it, the same in-helper pattern as `isGlobalBasenameEnabled` — so sync's inline extract, the GitHub/Google source inline extracts, the `extract_stale` minion, `gbrain maintain`, the cycle's extract phase and `gbrain extract --stale` (flag absent → configured knob) all agree; no caller passes a literal `false`. Pinned by `test/extract-include-frontmatter-config.serial.test.ts` (resolver precedence + a source-text guard on the call sites + a PGLite link-row test through `extractLinksForSlugs`).-- `src/core/extract/receipt-writer.ts` + `src/core/extract/rollup-writer.ts` + `src/commands/extract-status.ts` + `src/commands/extract-explain.ts` + `src/commands/extract-benchmark.ts` + `src/core/schema-pack/scaffold-extractable.ts` — unified extract operator surface. Every shipped extractor (deterministic `facts.conversation` in `src/commands/extract-conversation-facts.ts` + three LLM-backed cycle phases at `src/core/cycle/{extract-atoms,synthesize-concepts,propose-takes,extract-facts}.ts`) writes ONE receipt page per run (`writeReceipt`) + UPSERTs a row to `extract_rollup_7d` (`upsertExtractRollup`). Receipt slug `extracts/{date}/{kind}/{source_id}/{run_id_short}/round-{N}.md`; frontmatter stamps BOTH `type: extract_receipt` AND `dream_generated: true` (belt+suspenders against extraction-loop guard drift). `extract_receipt` joins `ALL_PAGE_TYPES` in `src/core/types.ts`; `extracts/` prefix gets a 0.3x source-boost demote in `src/core/search/source-boost.ts`. Migration v104 adds `extract_rollup_7d (kind, source_id, day, cost_usd, halt_count, eval_pass_count, eval_fail_count, round_completed_count, rollup_write_failures, updated_at)` with PK `(kind, source_id, day)` + `idx_extract_rollup_7d_day`. Rollup writes best-effort with process-scoped error-dedup so transient DB failures bump `rollup_write_failures` instead of crashing the cycle. Migration v239 adds `halt_reasons JSONB NOT NULL DEFAULT '{}'` (DDL only, no backfill): `classifyRunStop({ error })` takes `true` (an unclassified halt) or one word of the closed `HALT_REASONS` vocabulary (`provider_auth`, `provider_billing`, `provider_rate_limit`, `provider_model_not_found`, `no_pricing`, `integrity_guard`, `item_error`; a budget or deadline cap is an expected stop, never a reason), and the same UPSERT increments that key with bound parameters (`$N::text`, `jsonb_set`). `unknown` is never stored: the doctor read computes it as `halt_count - sum(halt_reasons)` (`haltReasonsWithUnknown`), so pre-v239 rows and older writers on the same day stay consistent. A brain whose schema is behind v239 loses rollup rows (one stderr line names `migrations_pending` and `gbrain apply-migrations --yes --no-autopilot-install`) and never throws. `extract_health` doctor check reads last 7 days, warns at halt-rate > 10% AND when rollup_write_failures > 0, lists `halt_reasons` and `top_halt_reason` per kind and names the top reason in the warn line (`atoms=42.9%, last halt 1d ago (top reason: item_error ×3)`); pre-v104 brains report `ok`. Pinned by `test/extract-rollup-halt-reasons-5495.test.ts` (both engines). CLI: `gbrain extract status [--source-id ID] [--kind X] [--verbose] [--json]` (7-day rollup, sorted halt_rate desc + cost desc, top-5 + "more rows" hint, stable `schema_version: 1`); `gbrain extract --explain <kind>` (resolution chain pack-declared vs built-in cycle phase, prompt_template + fixture_corpus paths with `✓`/`(missing)`, last 7d rollup); `gbrain extract benchmark --pack X --kind Y` (loads pack fixture corpus through strict path validation — rejects absolute paths, `..` traversal, null bytes, AND symlinks resolving outside pack root; ships as a stub-reporter). `src/core/schema-pack/manifest-v1.ts` widens `extractable` from `z.boolean()` to `z.union([z.boolean(), ExtractableSpecSchema])` (carries `prompt_template`, `fixture_corpus`, `eval_dimensions`, `benchmark_min_recall`, plus reserved `verifier_path` — parses but refuses at runtime); `extractableSpecsFromPack` + `getExtractableSpec` + `refuseVerifierPathInV042` in `src/core/schema-pack/extractable.ts`; `gbrain schema scaffold-extractable <type> --pack <pack>` declares the type extractable, generates 5 placeholder fixtures + a prompt template stub under `packs/<pack>/{fixtures,prompts}/extract/`, refuses to overwrite without `--force`. Pinned by `test/extractable-spec-widening.test.ts` (22), `test/extract/receipt-writer.test.ts` (12, canonical PGLite block R3+R4), `test/extract/benchmark.test.ts` (17), `test/extract/status.test.ts` (15), `test/schema-pack/scaffold-extractable.test.ts` (15, privacy guards), `test/doctor-extract-health.test.ts` (8).+- `src/core/extract/receipt-writer.ts` + `src/core/extract/rollup-writer.ts` + `src/commands/extract-status.ts` + `src/commands/extract-explain.ts` + `src/commands/extract-benchmark.ts` + `src/core/schema-pack/scaffold-extractable.ts` — unified extract operator surface. Every shipped extractor (deterministic `facts.conversation` in `src/commands/extract-conversation-facts.ts` + three LLM-backed cycle phases at `src/core/cycle/{extract-atoms,synthesize-concepts,propose-takes,extract-facts}.ts`) writes ONE receipt page per run (`writeReceipt`) + UPSERTs a row to `extract_rollup_7d` (`upsertExtractRollup`). Receipt slug `extracts/{date}/{kind}/{source_id}/{run_id_short}/round-{N}.md`; page `type` `extract_receipt` (not a frontmatter key) AND frontmatter `dream_generated: true` (belt+suspenders vs loop-guard drift). `extract_receipt` joins `ALL_PAGE_TYPES` in `src/core/types.ts`; `extracts/` prefix gets a 0.3x source-boost demote in `src/core/search/source-boost.ts`. Migration v104 adds `extract_rollup_7d (kind, source_id, day, cost_usd, halt_count, eval_pass_count, eval_fail_count, round_completed_count, rollup_write_failures, updated_at)` with PK `(kind, source_id, day)` + `idx_extract_rollup_7d_day`. Rollup writes best-effort with process-scoped error-dedup so transient DB failures bump `rollup_write_failures` instead of crashing the cycle. Migration v239 adds `halt_reasons JSONB NOT NULL DEFAULT '{}'` (DDL only, no backfill): `classifyRunStop({ error })` takes `true` (an unclassified halt) or one word of the closed `HALT_REASONS` vocabulary (`provider_auth`, `provider_billing`, `provider_rate_limit`, `provider_model_not_found`, `no_pricing`, `integrity_guard`, `item_error`; a budget or deadline cap is an expected stop, never a reason), and the same UPSERT increments that key with bound parameters (`$N::text`, `jsonb_set`). `unknown` is never stored: the doctor read computes it as `halt_count - sum(halt_reasons)` (`haltReasonsWithUnknown`), so pre-v239 rows and older writers on the same day stay consistent. A brain whose schema is behind v239 loses rollup rows (one stderr line names `migrations_pending` and `gbrain apply-migrations --yes --no-autopilot-install`) and never throws. `extract_health` doctor check reads last 7 days, warns at halt-rate > 10% AND when rollup_write_failures > 0, lists `halt_reasons` and `top_halt_reason` per kind and names the top reason in the warn line (`atoms=42.9%, last halt 1d ago (top reason: item_error ×3)`); pre-v104 brains report `ok`. Pinned by `test/extract-rollup-halt-reasons-5495.test.ts` (both engines). CLI: `gbrain extract status [--source-id ID] [--kind X] [--verbose] [--json]` (7-day rollup, sorted halt_rate desc + cost desc, top-5 + "more rows" hint, stable `schema_version: 1`); `gbrain extract --explain <kind>` (resolution chain pack-declared vs built-in cycle phase, prompt_template + fixture_corpus paths with `✓`/`(missing)`, last 7d rollup); `gbrain extract benchmark --pack X --kind Y` (loads pack fixture corpus through strict path validation — rejects absolute paths, `..` traversal, null bytes, AND symlinks resolving outside pack root; ships as a stub-reporter). `src/core/schema-pack/manifest-v1.ts` widens `extractable` from `z.boolean()` to `z.union([z.boolean(), ExtractableSpecSchema])` (carries `prompt_template`, `fixture_corpus`, `eval_dimensions`, `benchmark_min_recall`, plus reserved `verifier_path` — parses but refuses at runtime); `extractableSpecsFromPack` + `getExtractableSpec` + `refuseVerifierPathInV042` in `src/core/schema-pack/extractable.ts`; `gbrain schema scaffold-extractable <type> --pack <pack>` declares the type extractable, generates 5 placeholder fixtures + a prompt template stub under `packs/<pack>/{fixtures,prompts}/extract/`, refuses to overwrite without `--force`. Pinned by `test/extractable-spec-widening.test.ts` (22), `test/extract/receipt-writer.test.ts` (12, canonical PGLite block R3+R4), `test/extract/benchmark.test.ts` (17), `test/extract/status.test.ts` (15), `test/schema-pack/scaffold-extractable.test.ts` (15, privacy guards), `test/doctor-extract-health.test.ts` (8).- `src/core/extraction-review.ts` — Extraction quarantine lane markers, sibling of `src/core/quarantine.ts` / `embed-skip.ts` (frontmatter-key pattern, no schema migration). Auto-extracted stubs from untrusted input carry the PAIR `provenance: 'auto-extracted'` + `status: 'unverified'` (both required — user pages with their own `status`/`provenance` never match). Exports `quarantineMarkers()`, `isUnverifiedExtraction()` (JS predicate) and `unverifiedExtractionFragment(alias)` — the single SQL source of truth consumed by `buildSourceFactorCase` (namespace source-boost guard), both engines' `getUnverifiedExtractionPageIds`, the `extraction_pending` op, and the `unverified_extractions` doctor check, so filter and marker keys can never drift. Consequences: unverified stubs are excluded from the compiled-truth fusion boost + the `people/`/`companies/` source-boost (rank as ordinary content), stamped `unverified: true` in search results (`stampUnverifiedExtractions`, hybrid.ts), listed by `extraction_pending`, promoted (status → `verified`, provenance kept for audit) or rejected (soft-delete) by the owner-only `extraction_review` op. Pinned by `test/extraction-review.test.ts` (PGLite) + `test/e2e/extraction-review-postgres.test.ts` (live Postgres parity).diff --git a/src/core/extract/receipt-writer.ts b/src/core/extract/receipt-writer.tsindex 2ed7105295..379f8af348 100644--- a/src/core/extract/receipt-writer.ts+++ b/src/core/extract/receipt-writer.ts@@ -8,8 +8,8 @@** Two structural protections against extraction loops (D-EXTRACT-19,* belt + suspenders):- * 1. `type: extract_receipt` — eligibility predicate's type filter- * rejects this type because it's not in ELIGIBLE_TYPES.+ * 1. the page `type` column `extract_receipt` — eligibility predicate's+ * type filter rejects this type because it's not in ELIGIBLE_TYPES.* 2. `dream_generated: true` — the anti-loop guard at* `src/core/facts/eligibility.ts:62` rejects this flag.*@@ -160,13 +160,13 @@ function buildReceiptBody(input: ExtractReceiptInput): string {}/**- * Build the receipt frontmatter. Two anti-loop flags- * (type:extract_receipt + dream_generated:true) are stamped by every- * writeReceipt call regardless of caller. Per D-EXTRACT-19.+ * Build the receipt frontmatter. `dream_generated: true` is stamped by every+ * writeReceipt call regardless of caller; the other anti-loop flag is the+ * page-level `type` writeReceipt passes to putPage, never a frontmatter key+ * (`type` is parser-reserved, #7058). Per D-EXTRACT-19.*/function buildReceiptFrontmatter(input: ExtractReceiptInput): Record<string, unknown> {const fm: Record<string, unknown> = {- type: 'extract_receipt',dream_generated: true,// #1978: receipts record an operation, not a source document — the// run_id/round fields ARE the provenance. Explicit exemption keeps thediff --git a/test/extract/receipt-writer.test.ts b/test/extract/receipt-writer.test.tsindex 32a6e23a8c..245104f29e 100644--- a/test/extract/receipt-writer.test.ts+++ b/test/extract/receipt-writer.test.ts@@ -2,8 +2,9 @@//// Pins:// - D-EXTRACT-17 slug shape: extracts/{date}/{kind}/{source_id}/{run_id_short}/round-{N}.md-// - D-EXTRACT-19 belt+suspenders: type:extract_receipt + dream_generated:true-// are BOTH stamped in frontmatter regardless of caller input+// - D-EXTRACT-19 belt+suspenders: page type extract_receipt + frontmatter+// dream_generated:true are BOTH stamped regardless of caller input; the+// parser-reserved `type` never lands in frontmatter (#7058)// - Stable run_id_short (8 chars) so resumed runs land under same dir// - Optional eval_pass / eval_score / model_id frontmatter only on// LLM-backed extractors that supplied them@@ -138,8 +139,8 @@ describe('writeReceipt — frontmatter D-EXTRACT-19 belt+suspenders', () => {const { slug, page } = await writeReceipt(engine, BASE_INPUT);expect(slug).toBe('extracts/2026-05-27/facts.conversation/default/a1b2c3d4/round-full');expect(page.type).toBe('extract_receipt');- // belt + suspenders: both anti-loop flags are present- expect(page.frontmatter?.type).toBe('extract_receipt');+ // belt + suspenders: both anti-loop flags are present; type is the page column, not a reserved frontmatter key (#7058)+ expect(page.frontmatter?.type).toBeUndefined();expect(page.frontmatter?.dream_generated).toBe(true);// #1978: receipts are operation records, not derived documents —// explicit raw-trace exemption so the doctor raw_provenance check@@ -172,7 +173,8 @@ describe('writeReceipt — frontmatter D-EXTRACT-19 belt+suspenders', () => {expect(page.frontmatter?.eval_pass).toBeUndefined();expect(page.frontmatter?.eval_score).toBeUndefined();// Anti-loop flags STILL present even on deterministic extractors- expect(page.frontmatter?.type).toBe('extract_receipt');+ expect(page.type).toBe('extract_receipt');+ expect(page.frontmatter?.type).toBeUndefined();expect(page.frontmatter?.dream_generated).toBe(true);});diff --git a/test/receipt-frontmatter-reserved-keys-7058.test.ts b/test/receipt-frontmatter-reserved-keys-7058.test.tsnew file mode 100644index 0000000000..cc83415adb--- /dev/null+++ b/test/receipt-frontmatter-reserved-keys-7058.test.ts@@ -0,0 +1,39 @@+/**+ * #7058: an extract receipt must not store the parser-reserved `type` key+ * inside its frontmatter. Every extraction run writes a receipt, so a reserved+ * key there makes doctor's `stale_frontmatter_keys` grow each run, and the+ * `gbrain repair frontmatter-keys` sweep can never keep it at zero. The page's+ * `type` column (protection 1 of the anti-loop pair) still reads+ * `extract_receipt`, and `dream_generated: true` (protection 2) stays.+ */+import { afterAll, beforeAll, beforeEach, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { writeReceipt } from '../src/core/extract/receipt-writer.ts';+import { staleFrontmatterKeysCheck } from '../src/commands/doctor/checks/frontmatter-keys.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+});++test('#7058: a fresh receipt keeps stale_frontmatter_keys ok and its page type is extract_receipt', async () => {+ const { slug } = await writeReceipt(engine, { kind: 'atoms', source_id: 'default', run_id: 'run-abcdef1234', round: 'single',+ extracted_at: '2026-10-15T00:00:00.000Z', total_rows: 2, cost_usd: 0 });+ const check = await staleFrontmatterKeysCheck(engine);+ expect(check.status).toBe('ok');+ const [row] = await engine.executeRaw<{ type: string; dream_generated: string | null; fm_type: string | null }>(+ `SELECT type, frontmatter->>'dream_generated' AS dream_generated, frontmatter->>'type' AS fm_type FROM pages WHERE slug = $1 AND source_id = 'default'`, [slug]);+ expect(row).toEqual({ type: 'extract_receipt', dream_generated: 'true', fm_type: null });+});