Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.56.1.0 fix(ingestion): repair transcript, timeline, and email parsing (#5441)
Garry Tan04f7df5c3a62
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 99465a577a..3cfc8258f9 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.54.1.1",+ "version": "0.56.1.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex d7d372f1eb..365d0dd37a 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.54.1.1",+ "version": "0.56.1.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.mdindex ae17a8e6ff..5d6aaf1184 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.54.1.1 -->+<!-- gbrain-runbook-stamp: 0.56.1.0 --><!-- This stamp must equal the VERSION file at every release; CI enforces it(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it tothe installed binary and warns on skew. -->diff --git a/CHANGELOG.md b/CHANGELOG.mdindex cc1b945635..f48b1c7df4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,48 @@All notable changes to GBrain will be documented in this file.+## [0.56.1.0] - 2026-09-24++**Meeting imports tell you what they could read, and crowded timelines no longer stall extraction.**++Some meeting exports put each speaker's name inside a small structured label instead of a plain heading. GBrain can now read the supported single-quoted form without guessing who spoke. Labels that are malformed, nested, or quoted as examples stay unparsed. When a page cannot be read, the extraction summary says so instead of implying that its facts were already extracted.++You can also preview extraction without asking a model to interpret the transcript. The preview explains whether a page has the wrong type, too few turns, unsupported formatting, or no eligible turns after your chosen cutoff time. Pages with a fresh completion record are counted separately. Existing skip totals remain available to scripts.++Timeline extraction handles long runs of spaces without the previous slowdown. Text hidden inside code stays hidden without joining the real lines around it. The email text-conversion helper also cleans supported escaped markup while preserving ordinary addresses, comparisons, and valid Unicode. This helper change does not add a new email-import path.++### What changes in practice++| Input | What you see |+|---|---|+| A supported speaker-object transcript | Utterances retain the explicitly named speaker. |+| An unsupported transcript | A parse-skip explanation, not a false already-processed message. |+| A timeline line with excessive leading spaces | Bounded parsing instead of a long stall. |+| Escaped email formatting | Cleaned text, with unsupported or invalid entities left literal. |++## To take advantage of v0.56.1.0++Run `gbrain upgrade`. For a read-only preview of one meeting source:++```bash+gbrain extract-conversation-facts --source-id meetings --dry-run+```++**Say to your agent:** *"Run `extract-conversation-facts --dry-run` on my meeting source and explain why any pages were skipped."*++This release adds no schema migration and does not automatically reprocess historical pages. Correcting a previously unparsed transcript leaves it eligible for a later extraction; fresh completion outcomes keep their existing meaning. The email helper uses a fixed decoding limit and is a text converter, not a browser sanitizer.++### Itemized changes++- Add the narrow `python-dict-utterance` conversation pattern with explicit attribution, conservative wrapper rejection, and normal section boundaries. Contributed by @furuchanchan in #5365; fixes #5364.+- Preserve `pages_skipped` and add `pages_skipped_unparsed`, `pages_skipped_type_mismatch`, `pages_skipped_insufficient_turns`, and `pages_skipped_since` through CLI and worker aggregation. Keep dry-run parsing model-free.+- Make both timeline date-prefix matchers non-ambiguous and preserve every CR/LF position and UTF-16 offset when masking code. Contributed by @Masashi-Ono0611 in #5369.+- Keep `stripEmailHtml` capped before processing, remove recognized markup with quote-aware matching around at most two entity-decoding passes, and validate numeric Unicode scalars. Contributed by @furuchanchan in #5388; fixes #5327.++### For contributors++- Add parser corpus, real-core retry/source/provenance, model-free preview, oversized-page, timeline-consumer, and bounded email-conversion regressions without weakening existing assertions.+## [0.54.1.1] - 2026-09-24**Your agent can now open administration and guide another agent through a working connection.**diff --git a/VERSION b/VERSIONindex 18dd0d2a64..01a30a8318 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.54.1.1+0.56.1.0diff --git a/docs/architecture/conversation-parser-patterns.md b/docs/architecture/conversation-parser-patterns.mdindex 42365d4bc4..22dca7e57c 100644--- a/docs/architecture/conversation-parser-patterns.md+++ b/docs/architecture/conversation-parser-patterns.md@@ -16,8 +16,9 @@ adding or changing a format.pattern explicitly requires full-body scoring.4. Reject the winner when its acceptance score is below the false-positivefloor.-5. Apply the winning pattern to every line and attach continuation lines to the- preceding message.+5. Apply the winning pattern to every line and attach supported continuation+ lines to the preceding message. Speaker-object transcripts instead reject+ unsupported candidate regions rather than attributing their text to a speaker.6. Optionally run LLM polish or fallback when those features are enabled.Pattern order is only a tie-breaker. A new regex must be structurally distinct@@ -142,6 +143,36 @@ formats:Keeping these examples in both `test_negative` and parser regression tests makesthe non-shadowing contract executable.+## Single-quoted speaker objects++The `python-dict-utterance` pattern recognizes this narrow export shape without+evaluating Python or guessing a person's identity:++```text+{'source': 'microphone', 'attribution': 'me'}: hello+{'source': 'speaker', 'name': 'alice-example', 'attribution': 'them'}: hi+```++`source` and `attribution` must be `microphone`/`me` or `speaker`/`them`.+An optional explicit `name` wins regardless of field order. Names are 1–80+letters, digits, spaces, periods, underscores, or hyphens, starting with a+letter or digit. Unknown or duplicate keys, conflicting pairs, nested values,+escaped names, JSON-style quoting, and multiline utterances are not supported.++A bare transcript must start with a complete supported speaker header, apart+from date headings and blank or fenced-code lines. A dedicated `Transcript`+heading may follow summary sections. Quoted/nested wrappers cannot open that+section, and unsupported lines inside a candidate invalidate the candidate+rather than exposing interior examples as speakers. Fenced and indented code+cannot open speakers; excluded lines still count toward the density threshold.+A following non-date heading ends the section without erasing its genuine+turns. Dates use the existing page-date fallback and recognized date headings.++**Say to your agent:** *"Preview this conversation and tell me whether its+speakers can be read without guessing."* The agent can use+`gbrain extract-conversation-facts --source-id default --slug conversations/example --dry-run`;+the preview does not call a model or mark the page complete.+## Adding a built-in format1. Collect multiple anonymized examples, including separator and timestampdiff --git a/docs/architecture/key-files/commands-3.md b/docs/architecture/key-files/commands-3.mdindex 255cd33c53..f72a4de978 100644--- a/docs/architecture/key-files/commands-3.md+++ b/docs/architecture/key-files/commands-3.md@@ -25,7 +25,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/eval.ts` — `gbrain eval` command: single-run table + A/B config comparison. Sub-subcommand dispatch on `args[0]` routes `gbrain eval export` + `gbrain eval prune` + `gbrain eval replay` into session-capture handlers; bare `gbrain eval --qrels …` fall-through preserves the legacy IR-metrics flow. `gbrain eval cross-modal` is in the dispatch (the user-facing path is the cli.ts no-DB branch — `src/commands/eval.ts:cross-modal` only fires when callers re-enter with an existing engine).-- `src/commands/extract-conversation-facts.ts` + `src/core/cycle/conversation-facts-backfill.ts` — bulk fact extraction for long-form conversation pages. Walks conversation/meeting/slack/email/imessage/imessage-daily pages, splits them into time-windowed segments (30-min gap or 30-msg cap), prepends a topical/temporal header, and uses the strict `extractFactsFromTurnWithOutcome()` path so provider and output failures remain retryable instead of becoming successful empty pages. Invariants: **strict per-source core** (`runExtractConversationFactsCore({sourceId, ...})` always takes one sourceId; CLI + cycle phase each do their own multi-source iteration because `PHASE_SCOPE='source'` is taxonomy-only); **bounded two-phase enumeration** (paginated `listPages({type, sourceId, limit:10})`; per-page body cap `MAX_PAGE_BODY_BYTES=25MB`); **page-global `row_num` accumulator** (the facts unique index is `(source_id, source_markdown_slug, row_num)`); **versioned snapshot-bound outcomes** (`cli:extract-conversation-facts:terminal:v2` for complete pages and a separate `non-extractable:v2` source for recognized pages with no eligible segment); **operation checkpoints are scheduling hints only** and never suppress a replay without a matching v2 outcome; **optional `opts.budgetTracker?`** is used as-is, while an absent tracker is created with `maxCostUsd`; **body reads cover compiled truth, timeline, and configured raw-transcript sidecars**; **`facts.extraction_enabled` kill-switch** with `--override-disabled`; **`--types LIST` allowlist** (`conversation,meeting,slack,email,imessage,imessage-daily`); **`--background` via `maybeBackground`**; and **speaker-shaped-fold decline** — when the parse reports `unrecognized_headings` containing a speaker-shaped label (1-2 title-cased words, not in the doc-heading stoplist — the stoplist gates the DECLINE only, so a miss is warn-noise, never data loss) AND the parse produced fewer than two distinct speakers, the page is declined instead of extracted under wrong attribution: counted in `pages_skipped_unrecognized_speaker` (Result/CLI/cycle surfaces), warned to stderr with the folding pattern id, and deliberately NON-terminal (no durable audit row and no orphan cleanup, so a future parser/pattern fix retries the page); multi-speaker pages with folds proceed warn-only. The companion `conversation_facts_backfill` cycle phase is default-off, iterates every source, and enforces per-source plus brain-wide cost and wall-time caps. Migration v94 provides the partial facts index used by outcome lookups. `computeConversationFactsBacklogCheck` reports fresh completed, scanned-not-extractable, and unfinished counts separately, warning when more than 10 eligible pages lack a fresh v2 outcome. `sources audit` exposes `facts_backfill_estimate: {pages, est_segments, est_cost_usd, types}`. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. `--workers N` for LLM-bound fact extraction over conversation pages, with a per-page advisory lock via `src/core/db-lock.ts:withRefreshingLock` (lock id `extract-conversation-facts:<source>:<slug>`, TTL `PER_PAGE_LOCK_TTL_MINUTES=2` with 20s refresh via `Math.max(15s, 120s/6)`; `LockUnavailableError` triggers skip-and-continue with rate-limited log per (source, minute) + `pages_lock_skipped` counter + CLI exits 3 when non-zero AND no hard failures). `deleteOrphanFactsForPage(engine, sourceId, slug)` provides delete-orphans-first replay safety — wipes facts from a prior crashed run for this (sourceId, slug) before re-extracting, so a terminal audit row can never certify a partial insertFacts failure. `assertFactsEmbeddingDimMatchesConfig(engine)` is the startup preflight (throws `FactsEmbeddingDimMismatchError` with paste-ready ALTER hint BEFORE the first insert; cached per engine via WeakMap). Result type carries `pages_lock_skipped` + `orphan_facts_cleaned`. Checkpoint state is a shared `cpMap: Map<slug, endIso>` (NOT a per-page-mutated `cpEntries: string[]`) so atomic `Map.set` survives parallel workers. Minion handler `extract-conversation-facts` in `src/commands/jobs.ts` round-trips `workers` via `job.data.workers` for `--background --workers 20`. Cycle config key `cycle.conversation_facts_backfill.workers` (default 1; opt-in concurrency under brain-wide cost + walltime caps). Pinned by `test/extract-conversation-facts-workers.test.ts` + the existing extract-conversation-facts behavioral tests. with `src/commands/doctor.ts` durable outcome authority: page completion survives operation-checkpoint GC through versioned terminal audit rows (`cli:extract-conversation-facts:terminal:v2`), while recognized pages with no eligible segment use the separate `cli:extract-conversation-facts:non-extractable:v2` source. Each outcome is bound to the exact parsed snapshot: regular pages use `content_hash` plus the UTC effective date; raw-conversation sidecars and legacy null-hash pages use a canonical SHA-256 over every parser-relevant input. Selection checks the token before locking, refetches under the lock, and verifies it again before writing the outcome, so an edit cannot be certified by stale work. The strict extraction path treats provider, refusal, truncation, malformed/schema-invalid output, segment-write, cleanup, and terminal-write failures as unfinished work; bulk failures increment `pages_failed`, affect CLI/cycle receipts and exit status, and never advance the legacy checkpoint. Checkpoints are only a scheduling hint: a slug without a matching v2 outcome is replayed delete-first. `no_match`, errors, cancellation, and dry runs never become durable negatives. Result, CLI, cycle, and doctor surfaces keep completed, scanned-not-extractable, unfinished, failed, and lock-skipped counts separate. See [Conversation backfill durable outcomes](../../operations/conversation-backfill-outcomes.md) for the operator and maintainer contract. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. Managed bulk calls, including previews that can invoke extraction, refuse before queue or provider work; they are listed separately from the supported coordinated fact operation.+- `src/commands/extract-conversation-facts.ts` + `src/core/cycle/conversation-facts-backfill.ts` — bulk fact extraction for long-form conversation pages. Walks conversation/meeting/slack/email/imessage/imessage-daily pages, splits them into time-windowed segments (30-min gap or 30-msg cap), prepends a topical/temporal header, and uses the strict `extractFactsFromTurnWithOutcome()` path so provider and output failures remain retryable instead of becoming successful empty pages. Invariants: **strict per-source core** (`runExtractConversationFactsCore({sourceId, ...})` always takes one sourceId; CLI + cycle phase each do their own multi-source iteration because `PHASE_SCOPE='source'` is taxonomy-only); **bounded two-phase enumeration** (paginated `listPages({type, sourceId, limit:10})`; per-page body cap `MAX_PAGE_BODY_BYTES=25MB`); **page-global `row_num` accumulator** (the facts unique index is `(source_id, source_markdown_slug, row_num)`); **versioned snapshot-bound outcomes** (`cli:extract-conversation-facts:terminal:v2` for complete pages and a separate `non-extractable:v2` source for recognized pages with no eligible segment); **operation checkpoints are scheduling hints only** and never suppress a replay without a matching v2 outcome; **optional `opts.budgetTracker?`** is used as-is, while an absent tracker is created with `maxCostUsd`; **body reads cover compiled truth, timeline, and configured raw-transcript sidecars**; **`facts.extraction_enabled` kill-switch** with `--override-disabled`; **`--types LIST` allowlist** (`conversation,meeting,slack,email,imessage,imessage-daily`); **`--background` via `maybeBackground`**; and **speaker-shaped-fold decline** — when the parse reports `unrecognized_headings` containing a speaker-shaped label (1-2 title-cased words, not in the doc-heading stoplist — the stoplist gates the DECLINE only, so a miss is warn-noise, never data loss) AND the parse produced fewer than two distinct speakers, the page is declined instead of extracted under wrong attribution: counted in `pages_skipped_unrecognized_speaker` (Result/CLI/cycle surfaces), warned to stderr with the folding pattern id, and deliberately NON-terminal (no durable audit row and no orphan cleanup, so a future parser/pattern fix retries the page); multi-speaker pages with folds proceed warn-only. The companion `conversation_facts_backfill` cycle phase is default-off, iterates every source, and enforces per-source plus brain-wide cost and wall-time caps. Migration v94 provides the partial facts index used by outcome lookups. `computeConversationFactsBacklogCheck` reports fresh completed, scanned-not-extractable, and unfinished counts separately, warning when more than 10 eligible pages lack a fresh v2 outcome. `sources audit` exposes `facts_backfill_estimate: {pages, est_segments, est_cost_usd, types}`. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. `--workers N` for LLM-bound fact extraction over conversation pages, with a per-page advisory lock via `src/core/db-lock.ts:withRefreshingLock` (lock id `extract-conversation-facts:<source>:<slug>`, TTL `PER_PAGE_LOCK_TTL_MINUTES=2` with 20s refresh via `Math.max(15s, 120s/6)`; `LockUnavailableError` triggers skip-and-continue with rate-limited log per (source, minute) + `pages_lock_skipped` counter + CLI exits 3 when non-zero AND no hard failures). `deleteOrphanFactsForPage(engine, sourceId, slug)` provides delete-orphans-first replay safety — wipes facts from a prior crashed run for this (sourceId, slug) before re-extracting, so a terminal audit row can never certify a partial insertFacts failure. `assertFactsEmbeddingDimMatchesConfig(engine)` is the startup preflight (throws `FactsEmbeddingDimMismatchError` with paste-ready ALTER hint BEFORE the first insert; cached per engine via WeakMap). Result type carries `pages_lock_skipped` + `orphan_facts_cleaned`. Additive `pages_skipped_unparsed`, `pages_skipped_type_mismatch`, `pages_skipped_insufficient_turns`, and `pages_skipped_since` explain the unchanged `pages_skipped` aggregate across core, CLI, workers, and cycle sources; durable completion remains separate. `--dry-run` stops after segmentation, with no parser-fallback, extractor, or embedding calls and no durable knowledge/checkpoint/receipt/rollup writes. The narrow `python-dict-utterance` registry format and its quoted/nested-example rejection are documented in [conversation parser patterns](../conversation-parser-patterns.md). Checkpoint state is a shared `cpMap: Map<slug, endIso>` (NOT a per-page-mutated `cpEntries: string[]`) so atomic `Map.set` survives parallel workers. Minion handler `extract-conversation-facts` in `src/commands/jobs.ts` round-trips `workers` via `job.data.workers` for `--background --workers 20`. Cycle config key `cycle.conversation_facts_backfill.workers` (default 1; opt-in concurrency under brain-wide cost + walltime caps). Pinned by `test/extract-conversation-facts-workers.test.ts` + the existing extract-conversation-facts behavioral tests. with `src/commands/doctor.ts` durable outcome authority: page completion survives operation-checkpoint GC through versioned terminal audit rows (`cli:extract-conversation-facts:terminal:v2`), while recognized pages with no eligible segment use the separate `cli:extract-conversation-facts:non-extractable:v2` source. Each outcome is bound to the exact parsed snapshot: regular pages use `content_hash` plus the UTC effective date; raw-conversation sidecars and legacy null-hash pages use a canonical SHA-256 over every parser-relevant input. Selection checks the token before locking, refetches under the lock, and verifies it again before writing the outcome, so an edit cannot be certified by stale work. The strict extraction path treats provider, refusal, truncation, malformed/schema-invalid output, segment-write, cleanup, and terminal-write failures as unfinished work; bulk failures increment `pages_failed`, affect CLI/cycle receipts and exit status, and never advance the legacy checkpoint. Checkpoints are only a scheduling hint: a slug without a matching v2 outcome is replayed delete-first. `no_match`, errors, cancellation, and dry runs never become durable negatives. Result, CLI, cycle, and doctor surfaces keep completed, scanned-not-extractable, unfinished, failed, and lock-skipped counts separate. See [Conversation backfill durable outcomes](../../operations/conversation-backfill-outcomes.md) for the operator and maintainer contract. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. Managed bulk calls, including segmentation-only previews, refuse before queue or provider work; they are listed separately from the supported coordinated fact operation.- `src/commands/extract.ts` — `gbrain extract links|timeline|all [--source fs|db] [--source-id <id>]`: batch link/timeline extraction. fs walks markdown files, db walks pages from the engine (mutation-immune snapshot iteration; use for live brains with no local checkout). No in-memory dedup pre-load — candidates buffered 100 at a time and flushed via `addLinksBatch` / `addTimelineEntriesBatch`; `ON CONFLICT DO NOTHING` enforces uniqueness at the DB layer, `created` counter returns real rows inserted. `ExtractOpts.slugs?: string[]` enables incremental extract via `extractForSlugs()` (single combined links+timeline pass); the cycle path threads sync's `pagesAffected` through. Every per-slug extractor — `extractForSlugs` (the cycle's incremental pass) and the two sync hooks `extractLinksForSlugs` / `extractTimelineForSlugs` — resolves each requested slug through `resolveSlugRelPath`: the `buildSlugPathIndex(walkMarkdownFiles(dir))` index first, then — only on an index miss — the legacy `join(dir, slug + '.md')` existence check. The index is the primary because `pathToSlug` lowercases and slugifies, so a reconstructed path only finds files whose names are already slugs, and every other file looked deleted and was skipped in silence; the legacy fallback stays because sync ADMITS files the walker never emits (`_`-prefixed names, dot-dirs waived via `sync.include_hidden`) and those slugs still round-trip to their real path — without it such a page imports with no edges. On a slug collision the index prefers the file whose name IS the slug (else the first walked entry), so resolution never depends on directory-read order. Both return `ExtractForSlugsResult { created, processed }`; `processed` is the subset actually read, and the shared `slugsSafeToStamp(links, timeline)` intersection is what every caller may stamp. Stamping the full requested set marks a silently-skipped page fresh and hides it from `extract --stale` permanently. All three call sites (`src/commands/sync.ts`, `src/core/github-source.ts`, `src/core/google/google-source.ts`) stamp the intersection. `walkMarkdownFiles(brainDir)` still runs to build `allSlugs` for link resolution. `--source-id <id>` scopes extraction to one source on federated brains (resolved via `resolveSourceWithTier()` before any SQL; failures hint `gbrain sources list`). `gbrain extract --stale [--source-id <id>] [--catch-up] [--dry-run] [--json]` branch (`extractStaleFromDB`) — incremental DB-source link+timeline sweep over pages whose `pages.links_extracted_at` watermark is stale. Embedded callers (the cycle) pass `quiet: true` so the helper writes nothing to stdout, including its JSON result; standalone CLI output is unchanged. In `jsonMode` every fs path, `extractForSlugs` included, reports a dropped flush as a `{event:'batch_error'}` stderr line rather than going silent. Stale predicate (shared by both engines + the doctor check): `links_extracted_at IS NULL OR links_extracted_at < LINK_EXTRACTOR_VERSION_TS::timestamptz OR updated_at > links_extracted_at` (the `updated_at` arm catches MCP `put_page` / `sync --no-extract` edited-since-extract). Three `BrainEngine` methods (parity in postgres-engine.ts + pglite-engine.ts + bootstrap probes): `countStalePagesForExtraction(opts?)`, `listStalePagesForExtraction({batchSize, afterPageId?, sourceId?, versionTs?})` (returns page CONTENT to avoid N+1 `getPage`; `rowToStalePage` in utils.ts maps the row, `StalePageRow` in types.ts), `markPagesExtractedBatch(refs, defaultExtractedAt)` (3-array unnest `slug[],source_id[],ts[]`; each ref may carry its own `extractedAt`). `STALE_BATCH_SIZE` default 25 (`GBRAIN_EXTRACT_STALE_BATCH`; small because page bodies are unbounded — the LIMIT is the only fetch-time memory bound); `STALE_TIME_BUDGET_MS` 30min wall-clock (`--catch-up` removes the cap). Non-swallowing flush: link/timeline flush throws propagate and abort the batch; stamp LAST so a crash leaves pages unstamped and they re-extract idempotently (`addLinksBatch` ON CONFLICT DO NOTHING + timeline dedup). `extractStaleFromDB` stamps with each row's READ `updated_at` (not `now()`), so a concurrent edit during the sweep keeps the page stale and it re-extracts next run rather than marked fresh-with-old-content. Source-correct stamping at DB-extract sites via `stampExtracted` (best-effort, never throws); `extractLinksFromDB` only stamps the combined watermark when `subcommand === 'all'` (a links-only run must not hide timeline staleness). `LINK_EXTRACTOR_VERSION_TS` lives in `src/core/link-extraction.ts` (bump like `CHUNKER_VERSION` to invalidate all prior stamps). Migration v112 (`pages_links_extracted_at`) adds nullable `TIMESTAMPTZ` + composite `(source_id, links_extracted_at)` index (CONCURRENTLY + invalid-remnant pre-drop on Postgres, plain on PGLite), NO backfill so the real backlog surfaces on first `gbrain doctor`. Schema parity in schema.sql + pglite-schema.ts + schema-embedded.generated.ts + `REQUIRED_BOOTSTRAP_COVERAGE`. `src/commands/doctor.ts:checkLinksExtractionLag` (the `links_extraction_lag` check, also in `doctorReportRemote`) warn-only by default (>`GBRAIN_EXTRACTION_LAG_WARN_PCT`, default 20%; shared `EXTRACTION_LAG_WARN_PCT_DEFAULT` + `EXTRACTION_LAG_MIN_PAGES=100` + exported `_resolveEnvNumber`), hard-fails only when `GBRAIN_EXTRACTION_LAG_FAIL_PCT` is set; vacuous-skips <100 pages (no `--source`); pre-v112 brains graceful-skip via `isUndefinedColumnError`; strictly a SQL COUNT (safe on remote/thin-client). `src/commands/sync.ts` carries `--no-extract` (threaded through single-source + `--all` + `syncOneSource`), stamps `links_extracted_at` at the inline-extract call site for the slugs the extractors actually read, and `maybeExtractionNudge` prints a one-line stderr nudge after a `synced | first_sync | up_to_date` sync that leaves a backlog (`shouldNudgeAfterSync` pure predicate; `GBRAIN_SYNC_NO_EXTRACT_NUDGE` suppresses). `src/core/retry.ts` lists `'extract.stale'` in `BATCH_AUDIT_SITES`; `src/core/doctor-categories.ts` lists `links_extraction_lag` in `BRAIN_CHECK_NAMES`. Pinned by `test/extract-stale.test.ts` (incl. edited-after-stamp + crash-contract), `test/sync-inline-extract-stamps.serial.test.ts`, `test/sync-nudge-status-gate.test.ts`, `test/doctor-links-extraction-lag.test.ts`, engine-parity (Postgres↔PGLite) for the 3 methods + v112 round-trip. The stale SELECT in both engines projects a deterministic full-µs UTC string `to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso` (carried on `StalePageRow.updated_at_iso`, populated by `rowToStalePage` in utils.ts with an ISO-only fallback — never `String(Date)`, which `::timestamptz` misparses); `extractStaleFromDB` stamps that exact-precision value, not a JS `Date` (which truncates to milliseconds), so on Postgres `links_extracted_at` equals the row's `updated_at` to the microsecond and `links_extraction_lag` clears — a ms-truncated stamp stays strictly below the µs `updated_at` and leaves every page perpetually stale, which `extract --stale` could never satisfy. `to_char` (not raw `::text`, which is `DateStyle`-fragile) keeps the projection deterministic. The `markPagesExtractedBatch` SQL is unchanged, so callers passing an explicit (e.g. backdated) `extractedAt` still control the stamp and the edited-since arm is exact. A deterministic PGLite case in `test/extract-stale.test.ts` injects a µs `updated_at`, runs `--stale`, and asserts the lag is 0 and stays 0.- Extract CLI help — `EXTRACT_HELP` in `src/commands/extract.ts` is the canonical detailed usage shared by `--help` and invalid-subcommand errors. `src/cli.ts` routes `extract --help` before engine connection so help works on unconfigured installs; the top-level TOOLS block advertises every mode-specific flag. Pinned by `test/cli-help-discoverability.test.ts`.diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.mdindex 04ab6f7403..2302a149b6 100644--- a/docs/architecture/key-files/core-utilities-1.md+++ b/docs/architecture/key-files/core-utilities-1.md@@ -21,7 +21,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/cycle.ts` — brain maintenance cycle primitive (23 phases; `ALL_PHASES` is the ordered source of truth). `runCycle(engine: BrainEngine | null, opts: CycleOpts): Promise<CycleReport>` composes phases in semantic order along the core spine lint → backlinks → sync → synthesize → extract → patterns → recompute_emotional_weight → embed → orphans, with the extraction/graph/consolidation phases (extract_facts, extract_atoms, resolve_symbol_edges, …) slotted between per the ordering comments on `ALL_PHASES`. `synthesize` runs after sync (cross-references see a fresh brain) and before extract (auto-link materializes its writes); `patterns` runs after extract so it reads a fresh graph (subagent put_page sets `ctx.remote=true` and skips auto-link/timeline by default, so extract is the canonical materialization); `recompute_emotional_weight` sees the union of `syncPagesAffected` + `synthesizeWrittenSlugs` incrementally, or all pages when neither anchor is set (full backfill via `gbrain dream --phase recompute_emotional_weight`). `CycleReport.schema_version: "1"` is stable; `totals` is additive (`pages_emotional_weight_recomputed`, `transcripts_processed`, `synth_pages_written`, `patterns_written`). Three callers: `gbrain dream` CLI, `gbrain autopilot` daemon inline path, the Minions `autopilot-cycle` handler. Coordination via `gbrain_cycle_locks` DB table + `~/.gbrain/cycle.lock` file lock with PID-liveness for PGLite; the two handles compose into ONE lock whose `refresh()` treats the fenced DB row as the authoritative multi-writer identity and the file half as best-effort freshness — the file lock is refreshed ONLY while the fenced DB refresh reports ownership, so a losing holder can never clobber the successor's file lock on the very tick it detects the steal. A dedicated serialized refresher — `startCycleLockRefresher(lock, controller, lockId)` (exported; unref'd `setInterval` at `max(15s, TTL/6)`, env-only override `GBRAIN_CYCLE_LOCK_REFRESH_MS`, in-flight guard so a slow refresh never overlaps the next tick) — heartbeats the lock through long phases (synthesis/patterns/consolidation waits routinely outlive the TTL with no other heartbeat). A fenced miss aborts the controller with `LockStolenError`; that steal signal combines with the worker's external signal via the exported `anyAbortSignal(signals)` (duck-type-tolerant — stubs without `addEventListener` are observed by poll; returns `{signal, dispose}` and dispose detaches the caller-signal listener + clears the poll timer so daemons don't leak), and the run stops at the next phase boundary with a structured partial report carrying `reason: 'lock_stolen'` (for the 5 long phases — synthesize / extract_atoms / patterns / synthesize_concepts / consolidate — the steal races the phase promise and stops the WAIT immediately; their in-flight work runs to its own bounded timeout because their opts can't carry a signal yet). Transient refresh errors log and retry next tick (the TTL stays the backstop). `yieldBetweenPhases` runs between phases; `yieldDuringPhase` is in-phase keepalive. Engine nullable; lock-skip on read-only phase selections. `CycleOpts.signal?: AbortSignal` propagates the worker's abort signal with `checkAborted()` between every phase. `CycleOpts.deadlineAtMs` (the enclosing minion job's ABSOLUTE wall-clock deadline, threaded from `MinionJobContext.deadlineAtMs` by the autopilot-cycle handler; null for direct `gbrain dream` callers) flows into patterns, propose_takes, AND synthesize so time-spending phases derive their deadlines from the REAL remaining job budget instead of duplicated literals that collide with the job's own kill timer. Pinned by `test/cycle-lock-steal.serial.test.ts` (mid-run steal → partial report, no further phases, successor row intact) + `test/cycle-any-abort-signal.test.ts` + `test/db-lock-fencing.test.ts`. `runPhaseSync` returns `pagesAffected` via `SyncPhaseResult` (threaded to `runPhaseExtract` as the 4th arg) and takes `willRunExtractPhase: boolean` setting `noExtract: phases.includes('extract')` so `gbrain dream --phase sync` doesn't silently lose extraction. The extract phase calls `runExtractCore` and `extractStaleFromDB` with `quiet: true` (and `jsonMode: false`), so the helpers' human summaries never land on stdout ahead of the `dream --json` CycleReport while batch-loss diagnostics stay human-readable on stderr (`quiet` is its own knob on `ExtractOpts` — using `jsonMode: true` as a stand-in flipped the stderr channel to JSON events in a plain `gbrain dream`); `totals.pages_extracted` counts pages (`pages_processed` from the targeted pass + `stale_pages_drained`), not links created. `resolveSourceForDir(engine, brainDir)` threads `sourceId` to `performSync()` so sync reads the per-source `sources.last_commit` anchor (not the drift-prone global `config.sync.last_commit`). `CycleOpts.brainDir` is `string | null`; when null (checkout-less postgres/Supabase brain) the 6 filesystem phases (lint/backlinks/sync/synthesize/extract/patterns) skip with `details.reason: 'no_brain_dir'` and the DB-only phases run; `resolveSourceForDir` is null-tolerant. `cycleSourceId = opts.sourceId ?? resolveSourceForDir(engine, brainDir)` is the canonical per-source scope for `extract_facts`/`extract_atoms`/calibration — and for `synthesize` (threaded as `SynthesizePhaseOpts.sourceId` so synthesized pages land in the cycle's resolved source, not `'default'`) — so `gbrain dream --source repo-a` reconciles repo-a's facts even with no checkout (instead of scoping to `'default'` while stamping repo-a fresh). `deriveStatus` counts `edges_resolved`/`edges_ambiguous` as work so an edges-only cycle reports `ok` not `clean`, and scores ONLY attempted phases — the implicit source-cycle exclusion skip-records are bookkeeping and never dilute failure aggregation; the `jobs.ts` `autopilot-cycle` + phase-wrapper handlers pass `null` (not `'.'`) when no repo is configured. The cycle is SPLIT for autopilot fan-out along the `PHASE_SCOPE` taxonomy in `src/core/cycle/phase-scope.ts` (see its entry): cycle.ts derives `SOURCE_PHASES` / `MIXED_PHASES` / `GLOBAL_PHASES` / `MAINTENANCE_PHASES` (mixed ∪ global, original cycle order) plus `SOURCE_FRESHNESS_PHASES` (deterministic, non-LLM: lint/backlinks/sync/extract/extract_facts/recompute_emotional_weight — defined in phase-scope.ts) and `SOURCE_BACKGROUND_PHASES` (LLM-backed/unbounded source work = SOURCE minus FRESHNESS). `resolveCyclePhases(requested, sourceId)` at the shared runCycle boundary: default/no-source → `requested ?? ALL_PHASES` (the canonical `default` cycle remains full); a named non-default source with NO explicit phases → `SOURCE_FRESHNESS_PHASES` only (the freshness keeper's implicit `dream --source X` path must stamp freshness without first draining LLM-backed maintenance); explicit phase lists are honored VERBATIM — `dream --source X --phase synthesize` (and `--input <file>`, which implies synthesize) is deliberate operator intent, and `--phase orphans --source X` still narrows orphans via `forceGlobalOrphans`. The N-way duplication guard lives at the QUEUE boundary instead: the `autopilot-cycle` handler intersects queued per-source payloads with `SOURCE_FRESHNESS_PHASES` (queued payloads may carry mixed+background phases; an all-rejected or empty list is an explicit no-op skip with reason `all_phases_rejected_by_normalization`, never an implicit run, and rejected phases surface on the job result as `phases_rejected_by_normalization`). On the implicit path, excluded phases surface as `skipped` with `details.reason: 'excluded_from_implicit_source_cycle'` + `phase_scope`. Per-source `autopilot-cycle` jobs enqueue `phases: SOURCE_FRESHNESS_PHASES` and stamp `last_source_cycle_at`; the single `autopilot-global-maintenance` job runs `MAINTENANCE_PHASES` (no `sourceId`) and stamps the brain-level `autopilot.last_global_at` config key (`LAST_GLOBAL_AT_KEY`). SOURCE_BACKGROUND phases have NO automatic lane on multi-source brains (the legacy full-cycle job fires only when the brain has no sources rows) — run them explicitly (`gbrain dream --source X --phase extract_atoms`) until the background lane lands (see TODOS). The freshness stamp gate is `opts.sourceId && phases.length > 0 && engine && !dryRun && !aborted && status ∈ {ok, clean, partial}`; `last_full_cycle_at` is still written alongside `last_source_cycle_at` on a per-source success for doctor/legacy readers (not a gate for the brain-wide phases). Pinned by `test/dream-postgres.serial.test.ts` + `test/jobs-autopilot-cycle-braindir.serial.test.ts` + `test/autopilot-global-maintenance.test.ts` + `test/cycle-enabled-phase-completeness.test.ts`. `runPhaseLint` + `runPhaseBacklinks` carry the `export` keyword so behavioral tests can drive them directly (internal helpers exposed for test-only consumption; downstream code should NOT depend on them). Pinned by `test/cycle-legacy-phases.test.ts` (11 cases across both phases: clean run → status='ok', partial fix → status='warn' with `dryRun` in details, dry-run path doesn't write, throw-from-lib → status='fail' with the wrapper's try/catch envelope populated). with `src/core/cycle/extract-atoms.ts` + `src/core/cycle/synthesize-concepts.ts` + `src/commands/extract.ts` + `src/commands/doctor.ts` + `src/core/op-checkpoint.ts`: six daily-driver ops behaviors. (1) Batch idempotency: `atomsExistingForHashes(engine, sourceId, hashes[])` (exported from `src/core/cycle/extract-atoms.ts`) answers in one batched SQL roundtrip (never a per-hash loop) returning already-extracted `content_hash16` values; fail-open (SQL error → empty set, extraction proceeds); powered by migration v104 `pages_atom_source_hash_idx` (partial expression index on `frontmatter->>'source_hash'` for atom rows where `deleted_at IS NULL`; Postgres `CREATE INDEX CONCURRENTLY` with invalid-remnant pre-drop, PGLite plain). (2) Cycle lock TTL + heartbeat: `LOCK_TTL_MINUTES = 5`; `buildYieldDuringPhase(lock, outer)` (exported, with `LockHandle`) calls `lock.refresh()` + any external hook on every fire, throttled to 30s via `maybeYield`, firing both in the main loop AND immediately after every `await chat(...)`; `synthesize_concepts` uses the same throttled hook. A crashed cycle releases its lock within one short TTL, while the dedicated `startCycleLockRefresher` interval (see the coordination sentence above) keeps a healthy long-running cycle alive even across a single multi-minute `await chat(...)` — the timer fires during awaits, so no single slow call can silently expire the lock. (3) Progress wiring: `progress?: ProgressReporter` opt on `ExtractAtomsOpts` and `SynthesizeConceptsOpts`; cycle.ts passes its phase-level reporter down (NOT a child reporter, which would collide on `cycle.extract_atoms.extract_atoms.work`); phases only call `tick()`/`heartbeat()`, cycle.ts owns `start()`/`finish()`. (4) `by-mention` resume: `mentionsFingerprint({source, type, since, gazetteerHash})` in `src/core/op-checkpoint.ts` — the gazetteer hash (`hashGazetteer` in `src/core/by-mention.ts` — every entry's source_id/slug/title/tokens, not just the first-token bucket keys, so a new "Acme Labs" beside an existing "Acme Corp" moves it) is load-bearing (adding entity pages mid-pause shifts the hash → new fingerprint → fresh scan against the new gazetteer, never silent skip); `findMentionedEntities` keys its self-link guard and first-mention dedup on `(source_id, slug)`, so under `link_resolution.cross_source` a foreign namesake of the scanning page is a real target and same-slug pages in two sources both link; the gazetteer itself is entity-page titles PLUS live-verified `page_aliases` entries joined to entity-typed pages (ambiguous aliases and alias-vs-title collisions within a source are skipped), so body mentions of a documented alias link too; `gbrain extract links --by-mention` resumes via `op_checkpoints` with `flushAndCheckpoint` ordering (links flush to DB FIRST, page keys commit to checkpoint SECOND, persist THIRD, so a crash mid-batch leaves the page un-checkpointed and resume re-scans it); persist every 1000 items OR 30s; clean exit clears the checkpoint; `--dry-run` skips both load and write. (5) `sync_consolidation` doctor check (multi-source brains see a paste-ready `gbrain sync --all --parallel 4 --workers 4 --skip-failed`; single-source "not applicable"; SQL errors return `warn` via the check's own try/catch). (6) Test-isolation: `test/cycle-last-full-cycle-at.test.ts` + `test/schema-cli.test.ts` use per-test `GBRAIN_HOME=tempdir`. Pinned by `test/cycle/extract-atoms-batch.test.ts`, `test/cycle/cycle-lock-ttl.test.ts` (pins `LOCK_TTL_MINUTES === 5`), `test/op-checkpoint-mentions-fingerprint.test.ts`, `test/cycle/extract-atoms-progress.test.ts`, `test/cycle/synthesize-concepts-progress.test.ts`, `test/cycle/yield-during-phase-refresh.test.ts`, `test/cycle/yield-during-phase-throttle.test.ts`, `test/extract-by-mention-resume.test.ts`, `test/doctor-sync-consolidation.test.ts`. Companion `sync --all` recipe block in `skills/cron-scheduler/SKILL.md`. `synthesize_concepts` writes concept pages through `importFromContent` (the same parse→chunk→embed pipeline put_page uses, with put_page's `isAvailable('embedding')` → `noEmbed` gate) so `concepts/` pages carry `content_chunks` + embeddings and are reachable by retrieval (where `source-boost.ts` weights them 1.3×). `purge` phase (soft-delete TTLs) also GCs stale `op_checkpoints` rows older than 7 days. Non-fatal on pre-v67 brains (DROP-target-table check before DELETE). The cycle threads its abort signal into the embed phase (`runPhaseEmbed(engine, dryRun, signal)`) so a timed-out cycle's long embed phase honors cancellation and releases `gbrain_cycle_locks` right away instead of after a full backlog run.-- `src/core/data-research.ts` — Recipe validation, field extraction (MRR/ARR regex), dedup, tracker parsing, HTML stripping.+- `src/core/data-research.ts` — Recipe validation, field extraction (MRR/ARR regex), dedup, tracker parsing, HTML-to-text conversion. `stripEmailHtml` caps input before at most two non-recursive passes decoding supported named/decimal entities. Quote-aware removal of comments, style/script blocks, and recognized HTML tags runs before each decode and once afterward, discarding recognized tags before decoding their attribute contents. Unknown tag names and invalid tag forms remain literal, preserving angle-bracket addresses and non-HTML comparisons; actual HTML-shaped text is still interpreted as markup. Decimal entities must be valid Unicode scalars; invalid values and unsupported entities stay literal. Preserves paragraph breaks. This is a conversion helper, not a browser sanitizer or a live Gmail ingestion hook. Pinned by `test/data-research.test.ts`.- `src/core/doctor-cause-rank.ts` — pure cause-ranking for `gbrain doctor`. `rankIssues(checks)` returns non-ok checks ordered fail-before-warn then root-before-symptom then name (deterministic). `ROOT_CAUSE_CHECKS` / `SYMPTOM_CHECKS` are ORDERING ONLY — tier membership asserts no causality. `downstream_of` is set ONLY from a small map of KNOWN grounded edges (`queue_health` / `supervisor` → `worker_oom_loop`, since they read the same `aborted: watchdog` / `rss_watchdog` source) AND only when the named root is itself failing — never a root×symptom cartesian (co-occurrence never implies causality). `fix` prefers `details.fix_hint` else the message. `CAUSE_GRAPH_NAMES` + `allKnownCheckNames()` back a drift guard asserting every graphed name is a real check. Consumed by `computeDoctorReport` (`top_issues` field, additive, schema_version stays 2) + the "Top issues (ranked by cause)" header in `outputResults`. Pinned by `test/doctor-cause-rank.test.ts`.diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.mdindex f0863bf1d8..a2cd176259 100644--- a/docs/architecture/key-files/graph-and-facts.md+++ b/docs/architecture/key-files/graph-and-facts.md@@ -3,6 +3,8 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.+- `src/core/markdown-code.ts` — `stripCodeBlocks` masks fenced and inline code while preserving every CR/LF and UTF-16 code-unit offset. Citation paragraphs and later link references retain their original boundaries, including after an unclosed fence. `parseTimelineEntries` in `src/core/link-extraction.ts` groups the optional dash with its trailing whitespace so leading whitespace does not trigger overlapping repetition. Existing date, delimiter, and code-fence recognition rules remain unchanged. Pinned through real FS/DB link and timeline consumers by `test/timeline-parser-regression.test.ts`; its adversarial whitespace workload runs in a timeout-bounded child process.+- `src/core/check-resolvable.ts` — Resolver validation: reachability, MECE overlap, DRY checks, structured fix objects. `CROSS_CUTTING_PATTERNS.conventions` is an array (notability gate accepts `conventions/quality.md` and `_brain-filing-rules.md`). `extractTriggers()` delegates to the shared SKILL.md parser, so MECE gap detection and the trigger index agree on block lists, single-line flow sequences, wrapped flow sequences, and CRLF input. `extractDelegationTargets()` parses `> **Convention:**`, `> **Filing rule:**`, and inline backtick references. DRY suppression is proximity-based via `DRY_PROXIMITY_LINES = 40`. `parseResolverEntries` accepts BOTH the markdown table AND a compact list format (`- **skill-name**: trigger1 | trigger2 | trigger3` or `- skill-name: trigger1 | trigger2`); shapes can mix in one file, folded by the multi-resolver merge. Skill name MUST be kebab-lowercase (regex `[a-z][a-z0-9-]+`) so prose bullets like `- **Note**:`/`- **Convention**:`/`- **TODO**:` don't false-match as skill rows. `skillPath` is ALWAYS derived as `skills/<name>/SKILL.md`: an optional `→ \`skills/path\`` (or ASCII `->`) suffix is stripped from the trigger but NOT honored as the path — two consumers (`routing-eval.ts:skillSlugFromPath`, the manifest lookup) assume the convention; use the table format for non-conventional paths. Multi-trigger rows fan out to one entry per trigger sharing the same `skillPath`; `checkResolvable` dedupes so the reachability count counts each skill once. Pinned by `test/check-resolvable.test.ts` (resolver shapes plus trigger array syntax cases) + `test/check-resolvable-openclaw-compact.test.ts` (8 cases over `test/fixtures/openclaw-compact-resolver/` and `test/fixtures/openclaw-mixed-merge/`). Tutorial: `docs/guides/scaling-skills.md` (three-tier scaling: ~300-skill agent to ~4K tokens/turn from ~25K). `checkResolvable(skillsDir, opts?)` takes an optional `skillsDirSource` (the detection tier from `autoDetectSkillsDir`, threaded by both callers: doctor.ts and the check-resolvable command; an explicit `--skills-dir` passes `null`). An `unreachable` issue downgrades from `error` to `warning` only when ALL hold: the directory was found via the ungated `cwd_walk_up` tier, no resolver file contributes rows (no `RESOLVER.md`; a generic `AGENTS.md` with zero table rows counts as absent), unreachable skills outnumber reachable ones, and no `manifest.json` exists on disk. This keeps a foreign tool's `skills/` dir walked up to from cwd from being scored as a broken gbrain skillpack, while a real skillpack (RESOLVER.md present, higher-confidence tier, dense trigger coverage, or any manifest.json, even a corrupted one) stays strict. A foreign dir with zero `triggers:` and no resolver file still hard-fails via the `missing_file` branch (separate follow-up).- `src/core/entities/resolve.ts` — Free-form entity name → canonical slug resolution. `resolveEntitySlug(engine, source_id, raw)`: exact slug → alias-exact (an unambiguous `page_aliases` hit via `resolveAliases`, verified against LIVE pages since `page_aliases` has no FK — a stale alias row can never point at a deleted page; fail-open on pre-v110 brains missing the table; `ResolutionSource` reports `alias_exact`) → unique source-scoped full-basename match for multi-token names across people/companies/hosts/projects/concepts → unambiguous bare-name prefix expansion across `people/<token>-%` + `companies/<token>-%` → high-specificity fuzzy match for multi-token input (pg_trgm @ 0.7 threshold) → deterministic `slugify` holding fallback. Bare-name collisions never use popularity as confidence; shared-token company names below the threshold remain unresolved. Two helpers for the phantom-redirect pass: `resolvePhantomCanonical(engine, sourceId, phantomSlug)` SKIPS the exact-slug step (a phantom slug `'alice'` would exact-match itself and no-op the redirect); returns the canonical only when non-null AND contains `/`. `findPrefixCandidates(engine, sourceId, token)` is a standalone SQL query returning ALL candidates across `PREFIX_EXPANSION_DIRS` (hardcoded `['people', 'companies']`) via `slug LIKE ANY($N::text[])` over patterns `dir/token` + `dir/token-%`, cap of 10 ordered by `connection_count DESC, slug ASC`. Pinned by `test/entity-resolve.test.ts` (explicit, unique, ambiguous-person, and shared-token-company cases) plus `test/phantom-redirect.test.ts` (resolvePhantomCanonical 3 cases + findPrefixCandidates 6 cases incl. multi-dir ambiguity and the `people/aliceberg`-doesn't-match-`alice` false-positive guard).diff --git a/docs/operations/conversation-backfill-outcomes.md b/docs/operations/conversation-backfill-outcomes.mdindex 666b0ab187..cf65c57c06 100644--- a/docs/operations/conversation-backfill-outcomes.md+++ b/docs/operations/conversation-backfill-outcomes.md@@ -172,7 +172,14 @@ and snapshot verification. Force means "recompute" rather than "relax safety."## Operator signals-The result exposes separate counters:+`pages_skipped` retains its existing aggregate meaning. Its reason-specific+subsets distinguish `pages_skipped_unparsed`, `pages_skipped_type_mismatch`,+`pages_skipped_insufficient_turns`, and `pages_skipped_since`; speaker-attribution+declines retain `pages_skipped_unrecognized_speaker`. These subsets explain a+skip without adding a second page to the aggregate. `--since` filtering is not+a checkpoint skip, and a parse miss remains retryable.++The result also exposes separate durable-outcome and failure counters:- `pages_skipped_completed`- `pages_skipped_non_extractable`@@ -183,6 +190,23 @@ The CLI aggregates these across sources. The autopilot backfill phase includesthem in phase details. `gbrain doctor` reports `completed`,`scanned_not_extractable`, and `backlog` independently.+### Preview without model calls++**Say to your agent:** *"Preview which conversations can be read, and explain+why any are skipped."*++```bash+gbrain extract-conversation-facts --source-id default --dry-run --limit 10 --workers 1+```++Dry-run reports segmentation and skip reasons without calling the parser+fallback, fact extractor, or embedding provider. It does not write facts,+durable outcomes, checkpoints, receipt pages, or extraction rollups. Normal+source checks and transient advisory-lock handling still apply. The preview+does not estimate how many facts a later model call would return.++### Verify durable outcomes+Run a small canary twice:```bashdiff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 941e29d47b..15b35aa2c0 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.54.1.1",+ "version": "0.56.1.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","kind": "context-engine",diff --git a/package.json b/package.jsonindex addede90c7..583f87a1f6 100644--- a/package.json+++ b/package.json@@ -179,7 +179,7 @@"bun": ">=1.3.11"},"license": "MIT",- "version": "0.54.1.1",+ "version": "0.56.1.0","overrides": {"@ai-sdk/provider-utils": "4.0.33","@hono/node-server": "^2.0.5",diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.jsonindex d22dfca4b3..caa326fb0b 100644--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.54.1.1",+ "version": "0.56.1.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.jsonindex d01f01cf00..cbb9ec1190 100644--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.54.1.1",+ "version": "0.56.1.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.mdindex 7249f0cabc..8712eb314c 100644--- a/plugin-variants/gbrain-coding/README.md+++ b/plugin-variants/gbrain-coding/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.54.1.1 -->+<!-- gbrain-plugin-tree-stamp: 0.56.1.0 --># gbrain-coding (generated persona variant — do not hand-edit)Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.jsonindex d56e81b397..0d943db2a5 100644--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.54.1.1",+ "version": "0.56.1.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.jsonindex 040bfd199e..0de87d2865 100644--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.54.1.1",+ "version": "0.56.1.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.mdindex 6b00a49f60..e723e865df 100644--- a/plugin-variants/gbrain-daily/README.md+++ b/plugin-variants/gbrain-daily/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.54.1.1 -->+<!-- gbrain-plugin-tree-stamp: 0.56.1.0 --># gbrain-daily (generated persona variant — do not hand-edit)Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.diff --git a/plugin/README.md b/plugin/README.mdindex bff381382e..d76995c890 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.54.1.1 -->+<!-- gbrain-plugin-tree-stamp: 0.56.1.0 --># gbrain plugin skill tree (generated — do not hand-edit)This tree is the curated skill set for the gbrain Codex and Claude Codediff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 1131c7d81b..db28507c14 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -7,7 +7,7 @@ src/cli.ts 4126 ratchet +48 fix wave: get_versions --json + honest ellipsis (#46src/commands/autopilot.ts 2671 ratchet grown v0.46.26.0 megawave (#4300 #4285 #3696) + master v0.46.27.0 env-file lane + boot warning + reload-safe install (#2608 #4443) + 1 nosemgrep dataflow annotation (path-traversal audit); +chat-connectors wiring; +20 #4728 wrapper exec guard (baked CLI path gone -> PATH fallback / --install hint); +5 #4952 (refs #4399): syncEnabled=false skip in the freshness dispatch loopsrc/commands/doctor.ts 4593 ratchet grown v0.46.26.0 megawave: silent-death checks, self-upgrade honesty, noise pruning (#3944 #3925 #3958); +21 lines (#4518: don't assert "supervisor not running" when the --fast mode DB-lock fallback was never attempted); +12 lines (#2036/#4484: schema_version warns on forward DB skew); +12 lines (#4476: oversized_pages excludes embed_skip pages via canonical EMBED_SKIP_FILTER_FRAGMENT); merged wave-g-prs (#4421 #4425 #4517 #4519): one in-branch live-column diff on detectMissingColumns + engine-aware superseded upgrade-error suppression (explicit ok); grown db-availability loop: classified connection check + synthesized total-outage entry + hoisted pgbouncer helper + engine-fit check wiring + report engine/db_url_source fields; +chat-connectors wiring (master merge); +12 lines (#2036/#4484: schema_version warns on forward DB skew via schemaVersionHealth); merged wave-g-prs (#4421 #4425 #4517 #4519): in-branch live-column diff + engine-aware superseded upgrade-error suppression; wave-k: schema_columns emitted as its own check inside the ledger-current branch (gbrain#4421), schema_version via schemaVersionHealth module, conversation_format_coverage peeled to doctor/checks/conversation-coverage.ts (#4193); +7 backup_coverage check registration (monthly backup check); +master-merge true-up; wave-k: schema_columns emitted as its own check inside the ledger-current branch (gbrain#4421), schema_version via schemaVersionHealth module, conversation_format_coverage peeled to doctor/checks/conversation-coverage.ts (#4193); +9 v0.47 gmail-loops: google_oauth vault-health check dispatch; +17 (#4712: git-root-pinned source skip note wiring + all-skipped warn-not-ok status for multi_source_drift); +8 memorable_relay_health wiring (check itself is a peel: doctor/checks/integrations-memorable.ts); +9 ambient-writeback WP6: memory_writeback check registration (logic lives in doctor/checks/memory-writeback.ts); +14 default_source_local_path registration (#4739 — check body peeled to doctor/checks/default-source-path.ts); +9 atom_provenance_drift registration (#4566 — check body lives in doctor/checks/extraction-sync.ts); master: | merged v0.48.1.0 true-up; #5252 wave: scoped projection readiness registration; shared content: register the separately scoped canonical publication/recovery check; merged reliability/shared-skills source integrationsrc/commands/embed.ts 2144 ratchet lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring-src/commands/extract-conversation-facts.ts 2106 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration+src/commands/extract-conversation-facts.ts 2125 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364)src/commands/extract.ts 2659 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisionssrc/commands/jobs.ts 3210 ratchet grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled); security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; queued import failures remain failures; master integration: grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled); #5105: two-line delegate validates revision and durable authority before fact backstop execution; upstream integration: preserve independently reviewed master additions with branch facade extraction; +13 v0.50.5.0 security merge (upstream delta; coordinated facade retained); merged reliability/shared-skills source integrationsrc/commands/serve-http.ts 3098 ratchet registration and grant routes extracted; owner authentication and configured discovery remain in the HTTP facade; one shared bootstrap-token-shape import from serve-service; merged scoped shared-skill resources and named capability checksdiff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.tsindex cda93eb886..78a8a719db 100644--- a/src/commands/extract-conversation-facts.ts+++ b/src/commands/extract-conversation-facts.ts@@ -335,6 +335,10 @@ export interface ExtractConversationFactsResult {pages_considered: number;pages_processed: number;pages_skipped: number;+ pages_skipped_unparsed: number;+ pages_skipped_type_mismatch: number;+ pages_skipped_insufficient_turns: number;+ pages_skipped_since: number;pages_skipped_too_large: number;pages_skipped_disappeared: number;/** Fresh terminal outcomes skipped before parsing or model work. */@@ -1000,6 +1004,11 @@ async function processPage(const segments = splitIntoSegments(messages, { sinceIso });if (segments.length === 0) {state.result.pages_skipped++;+ if (!declinedUnrecognizedSpeaker) {+ if (messages.length === 0) state.result.pages_skipped_unparsed++;+ else if (allSegments.length === 0) state.result.pages_skipped_insufficient_turns++;+ else state.result.pages_skipped_since++;+ }if (!state.dryRun &&parseResult.phase !== 'no_match' &&@@ -1039,27 +1048,30 @@ async function processPage(return { newEndIso: null };}+ if (state.dryRun) {+ state.result.segments_processed += state.segmentLimit > 0+ ? Math.min(segments.length, state.segmentLimit)+ : segments.length;+ state.result.pages_processed++;+ return { newEndIso: null };+ }+// D11: delete-orphans-first replay safety. Wipes any facts written by// a prior crashed / killed / partial run for this (sourceId, slug)// pair before we re-extract. The lock we hold (D2 + D12 refreshing// lock above the caller) guarantees no other worker is writing to// this page right now, so the DELETE+INSERT pair is safe.- if (!state.dryRun) {- const cleaned = await deleteOrphanFactsForPage(state.engine, state.sourceId, page.slug);- if (cleaned > 0) {- state.result.orphan_facts_cleaned += cleaned;- process.stderr.write(- `[extract-conversation-facts] cleaned ${cleaned} orphan fact(s) for ${page.slug} from prior partial run\n`,- );- }+ const cleaned = await deleteOrphanFactsForPage(state.engine, state.sourceId, page.slug);+ if (cleaned > 0) {+ state.result.orphan_facts_cleaned += cleaned;+ process.stderr.write(+ `[extract-conversation-facts] cleaned ${cleaned} orphan fact(s) for ${page.slug} from prior partial run\n`,+ );}// Page-global row_num: after delete-orphans-first the table has no- // rows for this (sourceId, slug), so we always start from 0. Peek- // is kept as a defensive fallback for dry-run + non-deleting paths.- let rowNum = state.dryRun- ? await peekRowNumStart(state.engine, state.sourceId, page.slug)- : 0;+ // rows for this (sourceId, slug), so we always start from 0.+ let rowNum = 0;let newestEnd: string | null = null;let segmentsThisPage = 0;let pageInsertedTotal = 0;@@ -1129,13 +1141,7 @@ async function processPage();},);- const commitSegmentResolutionTelemetry = () => {- mergeSaveTimeResolutionCounts(pageResolution, segmentResolution);- state.result.fallback_slugify_count += segmentResolution.fallback_slugify_count;- state.result.resolution_errors += segmentResolution.resolution_errors;- };-- if (!state.dryRun && extracted.length > 0) {+ if (extracted.length > 0) {// Eng-v2 C1 / E11: page-global row_num stays unique across segments.// entity_slug is already canonical here — resolveExtractedEntitiesForSave// (above) ran every fact through the shipped resolver cascade (#3729/#4052),@@ -1159,25 +1165,22 @@ async function processPage(const ins = await state.engine.insertFacts(rows, { source_id: state.sourceId }); // gbrain-allow-direct-insert: canonical bulk extraction path for conversation pages — fences-as-system-of-record doesn't apply because conversations don't carry `## Facts` fences (the chat-log shape is the source-of-truth)pageInsertedTotal += ins.inserted;state.result.facts_inserted += ins.inserted;- rowNum += extracted.length;- commitSegmentResolutionTelemetry();- } else {- // dry-run: count for reporting, no DB write.- rowNum += extracted.length;- commitSegmentResolutionTelemetry();}+ rowNum += extracted.length;+ mergeSaveTimeResolutionCounts(pageResolution, segmentResolution);+ state.result.fallback_slugify_count += segmentResolution.fallback_slugify_count;+ state.result.resolution_errors += segmentResolution.resolution_errors;newestEnd = seg.endIso;if (state.sleepMs > 0) await sleep(state.sleepMs);}// Eng-v2 C7 / E16: write terminal audit row after all segments commit- // successfully. Only run when not dry-run AND we got through every+ // successfully. Only run when we got through every// segment (no break on segmentLimit; that's an explicit partial run).const fullyProcessed =state.segmentLimit === 0 || segmentsThisPage < state.segmentLimit;if (- !state.dryRun &&fullyProcessed &&newestEnd !== null &&await snapshotIsCurrent(state.engine, state.sourceId, snapshot)@@ -1193,7 +1196,7 @@ async function processPage(snapshot.versionToken,);rowNum++;- } else if (!state.dryRun && fullyProcessed && newestEnd !== null) {+ } else if (fullyProcessed && newestEnd !== null) {process.stderr.write(`[extract-conversation-facts] ${page.slug} changed during extraction; leaving it unfinished for replay\n`,);@@ -1203,7 +1206,7 @@ async function processPage(return { newEndIso: null };}- if (!state.dryRun && newestEnd !== null) {+ if (newestEnd !== null) {// v0.41.15.0 (codex #5/#6): per-page atomic checkpoint write. Mutate// the shared Map in place — JS single-threaded event loop makes// Map.set atomic across parallel workers; we don't need a load-mutate-@@ -1294,6 +1297,10 @@ export async function runExtractConversationFactsCore(pages_considered: 0,pages_processed: 0,pages_skipped: 0,+ pages_skipped_unparsed: 0,+ pages_skipped_type_mismatch: 0,+ pages_skipped_insufficient_turns: 0,+ pages_skipped_since: 0,pages_skipped_too_large: 0,pages_skipped_disappeared: 0,pages_skipped_completed: 0,@@ -1465,6 +1472,7 @@ export async function runExtractConversationFactsCore(}if (!concreteTypes.includes(page.type)) {result.pages_skipped++;+ result.pages_skipped_type_mismatch++;continue;}await processPageWithLock(page);@@ -1477,6 +1485,7 @@ export async function runExtractConversationFactsCore(}if (!concreteTypes.includes(page.type)) {result.pages_skipped++;+ result.pages_skipped_type_mismatch++;return;}@@ -1844,7 +1853,7 @@ Options:Default: reads cycle.conversation_facts_backfill.types config(falls back to the full allowlist).--slug <slug> Process a single page (overrides multi-page enumeration).- --dry-run Show segmentation + counts; no DB writes, no checkpoint advance.+ --dry-run Show segmentation + counts; no model calls, DB writes, or checkpoint advance.--limit <N> Cap pages processed (default: all).--since <iso> Only consider messages newer than this ISO timestamp.--force Re-process the target page (clears its resume entry).@@ -1943,6 +1952,10 @@ export async function runExtractConversationFacts(pages_considered: 0,pages_processed: 0,pages_skipped: 0,+ pages_skipped_unparsed: 0,+ pages_skipped_type_mismatch: 0,+ pages_skipped_insufficient_turns: 0,+ pages_skipped_since: 0,pages_skipped_too_large: 0,pages_skipped_disappeared: 0,pages_skipped_completed: 0,@@ -1991,6 +2004,10 @@ export async function runExtractConversationFacts(aggregate.pages_considered += perSource.pages_considered;aggregate.pages_processed += perSource.pages_processed;aggregate.pages_skipped += perSource.pages_skipped;+ aggregate.pages_skipped_unparsed += perSource.pages_skipped_unparsed;+ aggregate.pages_skipped_type_mismatch += perSource.pages_skipped_type_mismatch;+ aggregate.pages_skipped_insufficient_turns += perSource.pages_skipped_insufficient_turns;+ aggregate.pages_skipped_since += perSource.pages_skipped_since;aggregate.pages_skipped_too_large += perSource.pages_skipped_too_large;aggregate.pages_skipped_disappeared += perSource.pages_skipped_disappeared;aggregate.pages_skipped_completed += perSource.pages_skipped_completed;@@ -2015,16 +2032,18 @@ export async function runExtractConversationFacts(progress.finish();}- const verb = parsed.dryRun ? '(dry run) would extract' : 'extracted';+ const outcome = parsed.dryRun+ ? '(dry run) segmentation only; no facts extracted'+ : `extracted ${aggregate.facts_extracted} facts (${aggregate.facts_inserted} inserted)`;console.log(- `\nDone: ${verb} ${aggregate.facts_extracted} facts ` +- `(${aggregate.facts_inserted} inserted) across ${aggregate.segments_processed} segments ` ++ `\nDone: ${outcome} across ${aggregate.segments_processed} segments ` +`from ${aggregate.pages_processed}/${aggregate.pages_considered} pages ` +`in ${sourceIds.length} source(s). ` +`Spent ~$${totalSpent.toFixed(4)}.`,);if (aggregate.pages_skipped > 0) {- console.log(` Skipped ${aggregate.pages_skipped} page(s) with no new segments since last checkpoint.`);+ console.log(` Skipped ${aggregate.pages_skipped} page(s) without eligible segments or outside the selected types:`);+ console.log(` ${aggregate.pages_skipped_unparsed} with no parseable speaker turns (retryable); ${aggregate.pages_skipped_type_mismatch} with a type mismatch; ${aggregate.pages_skipped_insufficient_turns} with insufficient turns; ${aggregate.pages_skipped_since} with no eligible segments after --since; ${aggregate.pages_skipped_unrecognized_speaker} declined for speaker attribution.`);}if (aggregate.pages_skipped_too_large > 0) {console.log(` Skipped ${aggregate.pages_skipped_too_large} page(s) exceeding ${MAX_PAGE_BODY_BYTES / 1024 / 1024}MB body cap.`);diff --git a/src/core/conversation-parser/builtins.ts b/src/core/conversation-parser/builtins.tsindex 1a7de30a88..3d05b1ca92 100644--- a/src/core/conversation-parser/builtins.ts+++ b/src/core/conversation-parser/builtins.ts@@ -1,7 +1,7 @@/*** v0.41.16.0 — Built-in conversation parser pattern registry.*- * Eighteen hand-vetted patterns covering the chat-export formats this+ * Hand-vetted patterns covering the chat-export formats this* codebase is most likely to encounter. Each pattern's regex was* derived from a public format reference (source_doc field) so future* maintainers can verify against the wild shape.@@ -50,7 +50,25 @@ export function cleanSpeaker(raw: string, override?: RegExp): string {return stripped || raw.trim();}-/** The 18 hand-vetted built-in patterns. */+const speakerObjectFields = [+ ['microphone', 'me'],+ ['speaker', 'them'],+].flatMap(([source, attribution]) => {+ const fields = [+ `'source'[ \\t]*:[ \\t]*'${source}'`,+ `'attribution'[ \\t]*:[ \\t]*'${attribution}'`,+ "'name'[ \\t]*:[ \\t]*'[\\p{L}\\p{N}][\\p{L}\\p{N} ._-]{0,79}'",+ ];+ return [[0, 1], [1, 0], [0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]]+ .map(order => order.map(i => fields[i]).join('[ \\t]*,[ \\t]*'));+});++const speakerObjectRegex = new RegExp(+ `^\\{(?=[ \\t]*(?:${speakerObjectFields.join('|')})[ \\t]*\\}:[ \\t]+\\S)` ++ "(?:[^}]*'name'[ \\t]*:[ \\t]*|[^}]*'attribution'[ \\t]*:[ \\t]*)'([^']+)'[^}]*\\}:[ \\t]+(.+)$",+ 'u',+);+export const BUILTIN_PATTERNS: readonly PatternEntry[] = [// -------------------------------------------------------------------// INLINE-DATE patterns (date in every line; less ambiguous; tried first).@@ -833,6 +851,30 @@ export const BUILTIN_PATTERNS: readonly PatternEntry[] = [source_doc:'gbrain nightly transcript ingest: compiled_truth bodies use markdown headings per turn',},+ {+ id: 'python-dict-utterance',+ origin: 'builtin',+ regex: speakerObjectRegex,+ captures: { speaker_group: 1, text_group: 2 },+ date_source: 'frontmatter',+ time_format: '24h',+ timezone_policy: 'utc_assumed_with_warn',+ multi_line: false,+ quick_reject: /^\{/,+ score_full_body: true,+ test_positive: [+ "{'source': 'microphone', 'attribution': 'me'}: hello",+ "{'source': 'speaker', 'name': 'alice-example', 'attribution': 'them'}: hi",+ "{'attribution': 'them', 'source': 'speaker', 'name': 'alice-example'}: hi",+ ],+ test_negative: [+ "{'source': 'speaker', 'attribution': 'me'}: conflicting attribution",+ "{'source': 'speaker', 'attribution': 'them', 'name': 'alice-example', 'name': 'bob-example'}: duplicate",+ "{'source': 'speaker', 'attribution': 'them', 'extra': {}}: nested",+ '{"source": "speaker", "attribution": "them"}: unsupported JSON',+ ],+ source_doc: 'https://github.com/garrytan/gbrain/issues/5364',+ },];/**diff --git a/src/core/conversation-parser/parse.ts b/src/core/conversation-parser/parse.tsindex 714287e612..6a323b55dc 100644--- a/src/core/conversation-parser/parse.ts+++ b/src/core/conversation-parser/parse.ts@@ -330,6 +330,9 @@ export function applyPattern(if (!body) return [];const out: MatchedMessage[] = [];const lines = body.split(/\r?\n/);+ const allowedAnchors = entry.id === 'python-dict-utterance'+ ? speakerObjectAnchorsAllowed(body, entry)+ : undefined;// Some multi-day conversation exports use markdown date headings instead// of repeating a date on every message. Keep the caller's context immutable// while advancing a local date anchor as those headings are encountered.@@ -380,12 +383,15 @@ export function applyPattern(}}+ if (allowedAnchors?.[i] === false) continue;const dateHeader = dateHeaderRe.exec(line);if (dateHeader) {runningCtx.fallbackDate = dateHeader[1];continue;}+ if (allowedAnchors && !entry.regex.test(line)) continue;+// Quick-reject fast path.if (entry.quick_reject && !entry.quick_reject.test(line)) {collectFoldedHeading(line); // #4136 — folded below or dropped pre-anchor@@ -450,13 +456,93 @@ function getNonBlankLines(body: string, headCap?: number): string[] {return headCap !== undefined ? all.slice(0, headCap) : all;}+function speakerObjectAnchorsAllowed(body: string, entry: PatternEntry): boolean[] {+ let fence: string | undefined;+ let inTranscript: boolean | undefined;+ let invalidRegion = false;+ let malformedPreamble = false;+ let preambleQuote: string | undefined;+ const preambleClosers: string[] = [];+ const scanPreamble = (line: string): void => {+ for (let i = 0; i < line.length; i++) {+ const char = line[i];+ if (preambleQuote) {+ if (char === '\\') i++;+ else if (line.startsWith(preambleQuote, i)) {+ i += preambleQuote.length - 1;+ preambleQuote = undefined;+ }+ continue;+ }+ if (char === "'" || char === '"' || char === '`') {+ let wordStart = i;+ while (wordStart > 0 && /[\p{L}\p{N}_]/u.test(line[wordStart - 1])) wordStart--;+ const word = line.slice(wordStart, i);+ if (char === "'" && word && !/^(?:r|u|b|f|fr|rf|br|rb)$/i.test(word)) continue;+ preambleQuote = line.startsWith(char.repeat(3), i) ? char.repeat(3) : char;+ i += preambleQuote.length - 1;+ } else if (char === '{') preambleClosers.push('}');+ else if (char === '[') preambleClosers.push(']');+ else if (char === '(') preambleClosers.push(')');+ else if ('}])'.includes(char) && preambleClosers.length > 0 && preambleClosers.pop() !== char) malformedPreamble = true;+ }+ };+ const allowed = body.split(/\r?\n/).map(raw => {+ const line = raw.trim();+ if (malformedPreamble || preambleQuote || preambleClosers.length > 0) {+ if (entry.regex.test(line) || /^#{1,6}\s+Transcript\s*$/i.test(line)) invalidRegion = true;+ if (!malformedPreamble) scanPreamble(line);+ return false;+ }+ const marker = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(raw);+ if (fence) {+ if (marker && marker[1][0] === fence[0] && marker[1].length >= fence.length && !marker[2].trim()) fence = undefined;+ return false;+ }+ if (marker) {+ fence = marker[1];+ return false;+ }+ if (!line || /^(?: {4}| *\t)/.test(raw)) return false;+ if (/^#{1,6}\s+Transcript\s*$/i.test(line)) {+ inTranscript = true;+ return false;+ }+ if (/^#{1,4}\s+\d{4}-\d{2}-\d{2}\s*$/.test(line)) return inTranscript !== false;+ if (/^#{1,6}\s/.test(line)) {+ inTranscript = false;+ scanPreamble(line);+ return false;+ }+ const matches = entry.regex.test(line);+ if (inTranscript === undefined) {+ inTranscript = matches;+ if (!matches) invalidRegion = true;+ } else if (inTranscript && !matches) {+ invalidRegion = true;+ } else if (!inTranscript) {+ scanPreamble(line);+ }+ return inTranscript && matches;+ });+ return invalidRegion ? allowed.fill(false) : allowed;+}++function speakerObjectScoringLines(body: string, entry: PatternEntry, headCap?: number): string[] {+ const allowed = speakerObjectAnchorsAllowed(body, entry);+ const lines = body.split(/\r?\n/)+ .map((line, index) => ({ line: line.trim(), allowed: allowed[index] }))+ .filter(({ line }) => line.length > 0)+ .map(({ line, allowed }) => allowed ? line : '');+ return headCap === undefined ? lines : lines.slice(0, headCap);+}+/*** Core scorer over a pre-split line array. Both `scorePattern` (head* window) and `scorePatternFull` (whole body) delegate here so the* quick_reject + regex loop lives in one place. Reused by- * `parseConversation`'s fallback path which pre-splits ONCE and- * passes the array to all 18 candidates (saves 17 redundant body- * splits per fallback pass).+ * `parseConversation`'s fallback path shares a pre-split array across+ * candidates that use ordinary line scoring.*/function scoreFromLines(lines: readonly string[],@@ -540,6 +626,7 @@ function scoreFromLines(* Exported for tests.*/export function scorePattern(body: string, entry: PatternEntry): number {+ if (entry.id === 'python-dict-utterance') return scoreFromLines(speakerObjectScoringLines(body, entry, SCORING_HEAD_LINES), entry);return scoreFromLines(getNonBlankLines(body, SCORING_HEAD_LINES), entry);}@@ -555,6 +642,7 @@ export function scorePattern(body: string, entry: PatternEntry): number {* needs full-body scoring of a single pattern.*/export function scorePatternFull(body: string, entry: PatternEntry): number {+ if (entry.id === 'python-dict-utterance') return scoreFromLines(speakerObjectScoringLines(body, entry), entry);return scoreFromLines(getNonBlankLines(body), entry);}@@ -624,7 +712,7 @@ export function parseConversation(const allLines = getNonBlankLines(body);scored = candidates.map((entry) => ({entry,- score: scoreFromLines(allLines, entry),+ score: entry.id === 'python-dict-utterance' ? scorePatternFull(body, entry) : scoreFromLines(allLines, entry),priority: priorityOf(entry.id),}));sortScored(scored);@@ -650,7 +738,7 @@ export function parseConversation(// candidate; this only tightens its acceptance (a real transcript// stays ~1.0; a 3/200-label notes page drops to ~0.015 → no_match).if (top.entry.score_full_body && !fullBodyScored) {- top.score = scoreFromLines(getNonBlankLines(body), top.entry);+ top.score = scorePatternFull(body, top.entry);}// Minimum acceptance floor (closes Codex P1 #2): an essay withdiff --git a/src/core/cycle/conversation-facts-backfill.ts b/src/core/cycle/conversation-facts-backfill.tsindex f1e60607c9..c4d9d22ac2 100644--- a/src/core/cycle/conversation-facts-backfill.ts+++ b/src/core/cycle/conversation-facts-backfill.ts@@ -222,6 +222,10 @@ export async function runPhaseConversationFactsBackfill(pages_considered: 0,pages_processed: 0,pages_skipped: 0,+ pages_skipped_unparsed: 0,+ pages_skipped_type_mismatch: 0,+ pages_skipped_insufficient_turns: 0,+ pages_skipped_since: 0,pages_skipped_too_large: 0,pages_skipped_disappeared: 0,pages_skipped_completed: 0,@@ -372,6 +376,10 @@ export async function runPhaseConversationFactsBackfill(const totals = {pages_processed: 0,pages_skipped: 0,+ pages_skipped_unparsed: 0,+ pages_skipped_type_mismatch: 0,+ pages_skipped_insufficient_turns: 0,+ pages_skipped_since: 0,pages_skipped_completed: 0,pages_skipped_non_extractable: 0,pages_marked_non_extractable: 0,@@ -386,6 +394,10 @@ export async function runPhaseConversationFactsBackfill(if (!r.error) totals.sources_processed++;totals.pages_processed += r.pages_processed;totals.pages_skipped += r.pages_skipped;+ totals.pages_skipped_unparsed += r.pages_skipped_unparsed;+ totals.pages_skipped_type_mismatch += r.pages_skipped_type_mismatch;+ totals.pages_skipped_insufficient_turns += r.pages_skipped_insufficient_turns;+ totals.pages_skipped_since += r.pages_skipped_since;totals.pages_skipped_completed += r.pages_skipped_completed;totals.pages_skipped_non_extractable += r.pages_skipped_non_extractable;totals.pages_marked_non_extractable += r.pages_marked_non_extractable;@@ -412,6 +424,10 @@ export async function runPhaseConversationFactsBackfill(sources_processed: totals.sources_processed,pages_processed: totals.pages_processed,pages_skipped: totals.pages_skipped,+ pages_skipped_unparsed: totals.pages_skipped_unparsed,+ pages_skipped_type_mismatch: totals.pages_skipped_type_mismatch,+ pages_skipped_insufficient_turns: totals.pages_skipped_insufficient_turns,+ pages_skipped_since: totals.pages_skipped_since,pages_skipped_completed: totals.pages_skipped_completed,pages_skipped_non_extractable: totals.pages_skipped_non_extractable,pages_marked_non_extractable: totals.pages_marked_non_extractable,diff --git a/src/core/data-research.ts b/src/core/data-research.tsindex 91a619c451..b9ca3fb0ea 100644--- a/src/core/data-research.ts+++ b/src/core/data-research.ts@@ -368,46 +368,65 @@ export function buildDateWindows(}// ----------------------------------------------------------------------------// HTML email stripping (6-phase pipeline)+// HTML email stripping// ---------------------------------------------------------------------------const MAX_HTML_SIZE = 500 * 1024; // 500KB cap (ReDoS prevention)+const EMAIL_HTML_TAGS = new Set((+ 'a abbr acronym address area article aside audio b base basefont bdi bdo big blockquote body br button ' ++ 'canvas caption center cite code col colgroup data datalist dd del details dfn dialog dir div dl dt em embed ' ++ 'fieldset figcaption figure font footer form frame frameset h1 h2 h3 h4 h5 h6 head header hgroup hr html i iframe ' ++ 'img input ins kbd label legend li link main map mark marquee menu meta meter nav noframes noscript object ' ++ 'ol optgroup option output p param picture plaintext pre progress q rp rt ruby s samp script search section ' ++ 'select slot small source span strike strong style sub summary sup table tbody td template textarea tfoot ' ++ 'th thead time title tr track tt u ul var video wbr xmp'+).split(' '));++function stripEmailMarkup(text: string): string {+ return text+ .replace(/<!--[\s\S]*?-->/g, '')+ .replace(/<(style|script)(?=[\s>])(?:[^<>"']|"[^"]*"|'[^']*')*>[\s\S]*?<\/\1\s*>/gi, '')+ .replace(/<br\s*\/?>/gi, '\n')+ .replace(/<\/(p|div|tr|li|h[1-6])>/gi, '\n')+ .replace(/<\/?([a-z][a-z0-9:-]*)(?=[\s/>])(?:[^<>"']|"[^"]*"|'[^']*')*>|<![^>]*>|<\?[^>]*\?>/gi,+ (tag, name: string | undefined) => name && !EMAIL_HTML_TAGS.has(name.toLowerCase()) ? tag : '');+}-/** Strip HTML from email bodies. 6-phase pipeline with input size cap. */+/** Strip HTML from email bodies with bounded entity decoding and an input size cap. */export function stripEmailHtml(html: string): string {- // Phase 0: Size cap (ReDoS prevention)let text = html;if (text.length > MAX_HTML_SIZE) {text = text.slice(0, MAX_HTML_SIZE) + '\n...[truncated]';}- // Phase 1: Remove <style> and <script> blocks entirely- text = text.replace(/<style[\s\S]*?<\/style>/gi, '');- text = text.replace(/<script[\s\S]*?<\/script>/gi, '');-- // Phase 2: Convert block elements to newlines- text = text.replace(/<br\s*\/?>/gi, '\n');- text = text.replace(/<\/(p|div|tr|li|h[1-6])>/gi, '\n');+ for (let pass = 0; pass < 2; pass++) {+ text = stripEmailMarkup(text);+ text = text.replace(/&(nbsp|amp|lt|gt|quot|#\d+);/gi, (entity, code: string) => {+ switch (code.toLowerCase()) {+ case 'nbsp': return ' ';+ case 'amp': return '&';+ case 'lt': return '<';+ case 'gt': return '>';+ case 'quot': return '"';+ default: {+ const value = Number(code.slice(1));+ if (!Number.isInteger(value) || value > 0x10FFFF || (value >= 0xD800 && value <= 0xDFFF)) {+ return entity;+ }+ return String.fromCodePoint(value);+ }+ }+ });+ }- // Phase 3: Strip remaining HTML tags (non-greedy)- text = text.replace(/<[^>]*?>/g, '');+ text = stripEmailMarkup(text);- // Phase 4: Strip inline CSS artifacts (skip on large inputs for performance)if (text.length < 100000) {text = text.replace(/@media[^{]*\{[^}]*\}/g, '');text = text.replace(/\.[a-zA-Z][\w-]*\s*\{[^}]*\}/g, '');text = text.replace(/#[a-zA-Z][\w-]*\s*\{[^}]*\}/g, '');}- // Phase 5: Decode HTML entities- text = text.replace(/ /gi, ' ');- text = text.replace(/&/gi, '&');- text = text.replace(/</gi, '<');- text = text.replace(/>/gi, '>');- text = text.replace(/"/gi, '"');- text = text.replace(/&#(\d+);/g, (_, code) => String.fromCharCode(parseInt(code)));-- // Phase 6: Collapse whitespacetext = text.replace(/[ \t]+/g, ' ');text = text.replace(/\n{3,}/g, '\n\n');text = text.trim();diff --git a/src/core/link-extraction.ts b/src/core/link-extraction.tsindex 46f71cf3cd..fca894a565 100644--- a/src/core/link-extraction.ts+++ b/src/core/link-extraction.ts@@ -1623,11 +1623,11 @@ export function findTimelineSourceDelimiter(text: string): number {// `Source — Summary` split ONLY to pipe-separated bullets (the canonical// shape the FS extractor matches); a dash-separated bullet's rest is one// summary and must not be shattered on its first interior dash.-const TIMELINE_LINE_RE = /^\s*-?\s*\*\*(\d{4}-\d{2}-\d{2})\*\*\s*([|\-–—]+)\s*(.+?)\s*$/;+const TIMELINE_LINE_RE = /^\s*(?:-\s*)?\*\*(\d{4}-\d{2}-\d{2})\*\*\s*([|\-–—]+)\s*(.+?)\s*$/;// Chinese date lines: `- 2020年1月2日 | summary` (bold optional). Requires the// 年/月 markers so plain ASCII `- 2020-01-02 - text` does NOT match — non-bold// ASCII dates were never timeline entries and must stay that way.-const TIMELINE_LINE_RE_CN = /^\s*-?\s*(?:\*\*)?(\d{4})年(\d{1,2})月(\d{1,2})日?(?:\*\*)?\s*([|\-–—]+)\s*(.+?)\s*$/;+const TIMELINE_LINE_RE_CN = /^\s*(?:-\s*)?(?:\*\*)?(\d{4})年(\d{1,2})月(\d{1,2})日?(?:\*\*)?\s*([|\-–—]+)\s*(.+?)\s*$/;/*** Parse timeline entries from content. Looks at:diff --git a/src/core/markdown-code.ts b/src/core/markdown-code.tsindex 64667b462a..eb8c724b40 100644--- a/src/core/markdown-code.ts+++ b/src/core/markdown-code.ts@@ -1,7 +1,7 @@/*** Strip fenced code blocks (```...```) and inline code (`...`) from markdown,- * replacing them with whitespace of equivalent length. Preserves byte offsets- * for callers that care about positions.+ * replacing non-newline characters with spaces. Preserves CR/LF characters+ * and UTF-16 code-unit offsets for callers that care about positions.*/export function stripCodeBlocks(content: string): string {let out = '';@@ -9,9 +9,9 @@ export function stripCodeBlocks(content: string): string {while (i < content.length) {if (content.startsWith('```', i)) {const end = content.indexOf('```', i + 3);- if (end === -1) { out += ' '.repeat(content.length - i); break; }- out += ' '.repeat(end + 3 - i);- i = end + 3;+ const afterFence = end === -1 ? content.length : end + 3;+ out += content.slice(i, afterFence).replace(/[^\r\n]/g, ' ');+ i = afterFence;continue;}if (content[i] === '`') {@@ -21,7 +21,7 @@ export function stripCodeBlocks(content: string): string {i++;continue;}- out += ' '.repeat(end + 1 - i);+ out += content.slice(i, end + 1).replace(/[^\r\n]/g, ' ');i = end + 1;continue;}diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex 03c782ab94..ebc77ce549 100644--- a/templates/bootstrap/template-repo/README.md+++ b/templates/bootstrap/template-repo/README.md@@ -1,6 +1,6 @@# gbrain agent workspace — template-<!-- gbrain-template-stamp: 0.54.1.1 -->+<!-- gbrain-template-stamp: 0.56.1.0 -->This repository is the **"Use this template"** distribution artifact for a[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the samediff --git a/test/conversation-parser/speaker-object.test.ts b/test/conversation-parser/speaker-object.test.tsnew file mode 100644index 0000000000..0238d68065--- /dev/null+++ b/test/conversation-parser/speaker-object.test.ts@@ -0,0 +1,160 @@+import { describe, expect, test } from 'bun:test';+import { parseConversation } from '../../src/core/conversation-parser/parse.ts';++const first = "{'source': 'microphone', 'attribution': 'me'}: hello";+const second = "{'source': 'speaker', 'name': 'alice-example', 'attribution': 'them'}: hi";++describe('speaker objects (#5364)', () => {+ test('parses the reported shape using the page date', () => {+ const result = parseConversation(`${first}\n${second}`, { fallbackDate: '2026-06-02' });+ expect(result.phase).toBe('regex_match');+ expect(result.matched_pattern_id).toBe('python-dict-utterance');+ expect(result.messages).toEqual([+ { speaker: 'me', timestamp: '2026-06-02T00:00:00Z', text: 'hello' },+ { speaker: 'alice-example', timestamp: '2026-06-02T00:00:00Z', text: 'hi' },+ ]);+ });++ const fields = ["'source': 'speaker'", "'attribution': 'them'", "'name': 'alice-example'"];+ for (const order of [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]]) {+ test(`explicit name wins in key order ${order.join(',')}`, () => {+ const result = parseConversation(`{${order.map(i => fields[i]).join(', ')}}: hello`);+ expect(result.messages).toEqual([+ { speaker: 'alice-example', timestamp: '1970-01-01T00:00:00Z', text: 'hello' },+ ]);+ });+ }++ test('fallback attribution works in either key order with horizontal whitespace', () => {+ const result = parseConversation("{ 'attribution' : 'them', 'source' : 'speaker' }: hi");+ expect(result.messages.map(m => m.speaker)).toEqual(['them']);+ });++ test('finds a dedicated transcript section after summary prose', () => {+ const result = parseConversation(`# Meeting\n## Summary\nA short overview.\n## Transcript\n${first}\n${second}`);+ expect(result.messages.map(m => m.speaker)).toEqual(['me', 'alice-example']);+ });++ test('allows ordinary quoted summary prose before a dedicated transcript', () => {+ const result = parseConversation(`## Summary\nAlice's update was "ready" (after review).\n## Transcript\n${first}\n${second}`);+ expect(result.messages.map(m => m.speaker)).toEqual(['me', 'alice-example']);+ });++ test.each(["The founders' update is ready.", "Both participants' notes are ready.", "Alice's update is ready."])(+ 'does not treat a prose apostrophe as a literal wrapper: %s', (summary) => {+ const result = parseConversation(`## Summary\n${summary}\n## Transcript\n${first}\n${second}`);+ expect(result.messages.map(m => m.speaker)).toEqual(['me', 'alice-example']);+ },+ );++ test.each(['Follow up next week.', 'Good job :)', 'Quoted note: "unfinished', 'An unfinished list ['])(+ 'ends an explicit transcript without reclassifying its following notes: %s', (notes) => {+ const result = parseConversation(`## Transcript\n${first}\n${second}\n## Action Items\n${notes}`);+ expect(result.messages.map(m => [m.speaker, m.text])).toEqual([['me', 'hello'], ['alice-example', 'hi']]);+ },+ );++ test('ordinary summary punctuation does not hide a following transcript', () => {+ const result = parseConversation(`## Summary\nGood job :)\n## Transcript\n${first}\n${second}`);+ expect(result.messages.map(m => m.speaker)).toEqual(['me', 'alice-example']);+ });++ test('a wrapper in a following heading cannot open another transcript section', () => {+ const result = parseConversation(`## Transcript\n${first}\n${second}\n## Example {'quoted': '''\n## Transcript\n${first}\n${second}`);+ expect(result.phase).toBe('no_match');+ expect(result.messages).toEqual([]);+ });++ test('preserves running date headings without opening fenced speakers', () => {+ const result = parseConversation(`## 2026-06-02\n${first}\n\`\`\`python\n${second}\n\`\`\`\n## 2026-06-03\n${second}`);+ expect(result.messages).toEqual([+ { speaker: 'me', timestamp: '2026-06-02T00:00:00Z', text: 'hello' },+ { speaker: 'alice-example', timestamp: '2026-06-03T00:00:00Z', text: 'hi' },+ ]);+ });++ test('code-example date headings cannot change genuine turn timestamps', () => {+ const result = parseConversation(`${first}\n\`\`\`md\n## 2099-01-01\n${second}\n\`\`\`\n${second}`, { fallbackDate: '2026-06-02' });+ expect(result.messages).toHaveLength(2);+ expect(result.messages.map(m => m.timestamp)).toEqual(['2026-06-02T00:00:00Z', '2026-06-02T00:00:00Z']);+ });++ test('keeps higher-priority existing formats on score ties', () => {+ const result = parseConversation(`**Alice Example** (2024-03-15 9:00 AM): old format\n${first}`);+ expect(result.matched_pattern_id).toBe('imessage-slack');+ });++ test('can be disabled through the existing registry option', () => {+ expect(parseConversation(first, { disabledBuiltinIds: ['python-dict-utterance'] }).phase).toBe('no_match');+ });++ const wrappers = [+ `{'example': '''\n${first}\n${second}\n'''}`,+ `{'example': """\n${first}\n${second}\n"""}`,+ `{'example': {\n${first}\n${second}\n}}`,+ `[\n${first}\n${second}\n]`,+ `'''\n${first}\n${second}\n'''`,+ `payload = (\n${first}\n${second}\n)`,+ `{'example': '''\n## Transcript\n${first}\n${second}\n'''}`,+ ];+ for (const [index, wrapper] of wrappers.entries()) {+ for (const [position, prefix] of [['bare', ''], ['section', '## Transcript\n'], ['after-turn', `${first}\n`]] as const) {+ test(`rejects wrapper ${index + 1} at the ${position} candidate boundary`, () => {+ const result = parseConversation(prefix + wrapper);+ expect(result.phase).toBe('no_match');+ expect(result.messages).toEqual([]);+ });+ }+ }++ for (const [index, opener] of ["{'example': '''", '{"example": {', '[', 'payload(', "r'", 'r"""'].entries()) {+ test(`an unclosed preamble wrapper ${index + 1} cannot create a Transcript section`, () => {+ const result = parseConversation(`## Summary\n${opener}\n## Transcript\n${first}\n${second}`);+ expect(result.phase).toBe('no_match');+ expect(result.messages).toEqual([]);+ });+ }++ const rejected = [+ "{'speaker': 'alice-example'}: hi",+ "{'name': 'alice-example'}: hi",+ "{'attribution': 'unknown'}: hi",+ "{'source': 'speaker', 'attribution': 'unknown'}: hi",+ "{'source': 'microphone', 'attribution': 'them'}: hi",+ "{'source': 'speaker', 'attribution': 'me', 'name': 'alice-example'}: hi",+ "{'source': 'speaker', 'attribution': 'them', 'name': ''}: hi",+ "{'source': 'speaker', 'attribution': 'them', 'name': ' '}: hi",+ "{'source': 'speaker', 'attribution': 'them', 'name': 'alice-example', 'name': 'bob-example'}: hi",+ "{'source': 'speaker', 'source': 'speaker', 'attribution': 'them'}: hi",+ "{'source': 'speaker', 'attribution': 'them', 'attribution': 'them'}: hi",+ "{'source': 'speaker', 'attribution': 'them', 'metadata': {'name': 'alice-example'}}: hi",+ "{'source': 'speaker', 'attribution': 'them', 'extra': 'value'}: hi",+ "{'source': 'speaker', 'attribution': 'them', 'name': 'alice\\'example'}: hi",+ "{'source': 'speaker', 'attribution': 'them', 'name': 'alice\\nexample'}: hi",+ "{'source': 'speaker', 'attribution': 'them', 'name': 'alice\\u0020example'}: hi",+ "{'source': 'speaker', 'attribution': 'them', 'name': doSomething()}: hi",+ "{'source': 'speaker', 'attribution': 'them',}: hi",+ "{'source': 'speaker', 'attribution': 'them'} hi",+ "{'source': 'speaker', 'attribution': 'them'}:",+ '{"source": "speaker", "name": "alice-example", "attribution": "them"}: hi',+ `Example: ${first}`,+ `> ${first}\n> ${second}`,+ ` ${first}\n ${second}`,+ `\t${first}\n\t${second}`,+ ` \t${first}\n \t${second}`,+ `# Example\n${first}\n${second}`,+ `\`\`\`python\n${first}\n${second}\n\`\`\``,+ `~~~~python\n${first}\n~~~\n${second}\n~~~~`,+ `\`\`\`python\n${first}\n~~~\n${second}`,+ `Here is an example of a dictionary.\n${first}\n${second}\nThis is explanatory prose.`,+ `${first}\n${second}\n${Array.from({ length: 100 }, () => 'ordinary prose').join('\n')}`,+ `## 2026-06-02\n${first}\n{'name': 'bob-example'}: unsupported\n\`\`\`python\n${second}\n\`\`\`\n## 2026-06-03\n${second}`,+ ];+ for (const [index, body] of rejected.entries()) {+ test(`rejects malformed, ambiguous, or example input ${index + 1}`, () => {+ const result = parseConversation(body);+ expect(result.phase).toBe('no_match');+ expect(result.messages).toEqual([]);+ });+ }+});diff --git a/test/data-research.test.ts b/test/data-research.test.tsindex e23ec0f938..46c6b61455 100644--- a/test/data-research.test.ts+++ b/test/data-research.test.ts@@ -261,6 +261,68 @@ describe('data-research', () => {expect(result).toContain('>');});+ test.each([+ '<style>.hidden { color: red; }</style><script>hidden()</script><!-- hidden --><p>Hello</p><p>World<br>Again</p>',+ '<style>.hidden { color: red; }</style><script>hidden()</script><!-- hidden --><p>Hello</p><p>World<br>Again</p>',+ '<style>.hidden { color: red; }</style><script>hidden()</script><!-- hidden --><p>Hello</p><p>World<br>Again</p>',+ '&lt;style&gt;.hidden { color: red; }&lt;/style&gt;&lt;script&gt;hidden()&lt;/script&gt;&lt;!-- hidden --&gt;&lt;p&gt;Hello&lt;/p&gt;&lt;p&gt;World&lt;br&gt;Again&lt;/p&gt;',+ ])('strips raw or decoded email markup without joining paragraphs: %s', (html) => {+ expect(stripEmailHtml(html)).toBe('Hello\nWorld\nAgain');+ });++ test('removes mixed-case blocks with attributes and comment contents', () => {+ expect(stripEmailHtml('<STYLE type="text/css">hidden css</STYLE><SCRIPT defer>hidden script</SCRIPT><!-- <p>hidden comment</p> --><DIV>Visible</DIV>')).toBe('Visible');+ });++ test.each([+ ['1 < 2 and 3 > 1; R&D says "yes".', '1 < 2 and 3 > 1; R&D says "yes".'],+ ['1 < 2 and 3 > 1; R&D says "yes".', '1 < 2 and 3 > 1; R&D says "yes".'],+ ['中文 café 😀 & 😀 'fine'', "中文 café 😀 & 😀 'fine'"],+ ['© 😀 &#-1; � � � �', '© 😀 &#-1; � � � �'],+ ['퟿  ', '\uD7FF \uE000 \u{10FFFF}'],+ ['&amp;lt;p&amp;gt;Deep&amp;lt;/p&amp;gt;', '<p>Deep</p>'],+ ['Hello &amp; goodbye', 'Hello & goodbye'],+ ['', ''],+ ['<p>Visible</p><broken', 'Visible\n<broken'],+ ])('preserves text and bounded entity decoding: %s', (html, expected) => {+ expect(stripEmailHtml(html)).toBe(expected);+ });++ test('leaves overflowing decimal entities literal', () => {+ const entity = `&#${'9'.repeat(400)};`;+ expect(stripEmailHtml(entity)).toBe(entity);+ });++ test.each([+ ['<p>Contact <[email protected]> to confirm.</p>', 'Contact <[email protected]> to confirm.'],+ ['<p>Contact <[email protected]> to confirm.</p>', 'Contact <[email protected]> to confirm.'],+ ['Constraint: x<y and z>0.', 'Constraint: x<y and z>0.'],+ ['Constraint: x<y and z>0.', 'Constraint: x<y and z>0.'],+ ['<span class="note">R&D</span> <a href="https://example.com">Link</a>', 'R&D Link'],+ ['<font color="red">Legacy</font> <custom-placeholder>literal</custom-placeholder>', 'Legacy <custom-placeholder>literal</custom-placeholder>'],+ ])('distinguishes recognized HTML from visible angle-bracket text: %s', (html, expected) => {+ expect(stripEmailHtml(html)).toBe(expected);+ });++ test.each([+ '<span title="x<y">Visible</span>',+ '<a href="https://example.com" title="1 < 2">Visible</a>',+ '<span title="x>y">Visible</span>',+ '<span title="x>y and x<z">Visible</span>',+ '<span title="say "hi"">Visible</span>',+ '<span title="x&lt;y">Visible</span>',+ '<span title="say &quot;hi&quot;">Visible</span>',+ "<span title='x<y and x>z'>Visible</span>",+ ])('discards attributes without decoding their contents into markup: %s', (html) => {+ expect(stripEmailHtml(html)).toBe('Visible');+ });++ test('caps encoded input before decoding or removing hidden blocks', () => {+ const prefix = '<style>hidden</style><p>';+ const html = prefix + 'x'.repeat(500 * 1024 - prefix.length) + 'outside-the-cap';+ expect(stripEmailHtml(html)).toBe('x'.repeat(500 * 1024 - prefix.length) + '\n...[truncated]');+ });+test('truncates >500KB input (ReDoS prevention)', () => {// Use a string just over 500KB to trigger truncationconst huge = '<p>' + 'x'.repeat(510 * 1024) + '</p>';diff --git a/test/extract-conversation-facts-diagnostics.serial.test.ts b/test/extract-conversation-facts-diagnostics.serial.test.tsnew file mode 100644index 0000000000..980051e0c7--- /dev/null+++ b/test/extract-conversation-facts-diagnostics.serial.test.ts@@ -0,0 +1,133 @@+import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { __setChatTransportForTests, __setEmbedTransportForTests, configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import * as concurrency from '../src/core/sync-concurrency.ts';+import { runExtractConversationFacts, runExtractConversationFactsCore } from '../src/commands/extract-conversation-facts.ts';+import { runPhaseConversationFactsBackfill } from '../src/core/cycle/conversation-facts-backfill.ts';++let engine: PGLiteEngine;+let calls = 0;+let active = 0;+let maxActive = 0;+const body = "{'source': 'microphone', 'attribution': 'me'}: hello\n{'name': 'alice-example', 'attribution': 'them', 'source': 'speaker'}: hi";++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: { ANTHROPIC_API_KEY: 'sk-ant-test', OPENAI_API_KEY: 'sk-test' } });+ __setChatTransportForTests(async () => {+ calls++;+ active++;+ maxActive = Math.max(maxActive, active);+ await Bun.sleep(100);+ active--;+ return { text: '{"facts":[]}', blocks: [], stopReason: 'end', usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: 'stub', providerId: 'stub' };+ });+ __setEmbedTransportForTests((async () => { throw new Error('unexpected embedding call'); }) as never);+});++afterAll(async () => {+ __setChatTransportForTests(null);+ __setEmbedTransportForTests(null);+ resetGateway();+ await engine.disconnect();+});++beforeEach(async () => {+ calls = 0;+ active = 0;+ maxActive = 0;+ await engine.executeRaw('TRUNCATE facts, pages, op_checkpoints, extract_rollup_7d CASCADE');+ await engine.setConfig('facts.extraction_enabled', 'true');+ await engine.setConfig('conversation_parser.llm_fallback_enabled', 'false');+ await engine.setConfig('cycle.conversation_facts_backfill.enabled', 'true');+ await engine.setConfig('cycle.conversation_facts_backfill.workers', '3');+ for (const sourceId of ['speaker-a', 'speaker-b']) {+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT DO NOTHING', [sourceId]);+ for (const [slug, compiled_truth, type] of [+ ['conversations/object-1', body, 'conversation'],+ ['conversations/object-2', body, 'conversation'],+ ['conversations/object-3', body, 'conversation'],+ ['conversations/single', body.split('\n')[0], 'conversation'],+ ['conversations/unparsed', 'Opaque prose without speaker turns.', 'conversation'],+ ['people/profile-example', 'An ordinary profile.', 'person'],+ ] as const) {+ await engine.putPage(slug, { title: slug, type, compiled_truth, timeline: '', frontmatter: { date: '2026-06-02' } }, { sourceId });+ }+ }+});++describe('#5364 diagnostics across workers, sources, CLI, and cycle', () => {+ test('dry-run help promises segmentation without model calls', async () => {+ const log = spyOn(console, 'log').mockImplementation(() => {});+ try {+ await runExtractConversationFacts(engine, ['--help']);+ expect(log.mock.calls.map(call => call.join(' ')).join('\n')).toContain('--dry-run Show segmentation + counts; no model calls, DB writes, or checkpoint advance.');+ expect(calls).toBe(0);+ } finally {+ log.mockRestore();+ }+ });++ test('three actual pool workers share exact counters and keep source outcomes isolated', async () => {+ const workerCount = spyOn(concurrency, 'resolveWorkersWithClamp').mockReturnValue({ workers: 3, reason: 'override', wasClamped: false, requested: 3 });+ try {+ const result = await runExtractConversationFactsCore(engine, { sourceId: 'speaker-a', types: ['conversation'], workers: 3, sleepMs: 0 });+ expect(result).toMatchObject({ pages_considered: 5, pages_processed: 3, pages_skipped: 2, pages_skipped_unparsed: 1, pages_skipped_insufficient_turns: 1, pages_skipped_type_mismatch: 0, pages_skipped_since: 0, pages_failed: 0, pages_marked_non_extractable: 1, segments_processed: 3 });+ expect(calls).toBe(3);+ expect(maxActive).toBe(3);+ expect(await engine.executeRaw("SELECT id FROM facts WHERE source_id = 'speaker-b'")).toEqual([]);+ const replay = await runExtractConversationFactsCore(engine, { sourceId: 'speaker-a', types: ['conversation'], workers: 3, sleepMs: 0 });+ expect(replay).toMatchObject({ pages_considered: 5, pages_processed: 0, pages_skipped: 1, pages_skipped_unparsed: 1, pages_skipped_insufficient_turns: 0, pages_skipped_completed: 3, pages_skipped_non_extractable: 1 });+ expect(calls).toBe(3);+ } finally {+ workerCount.mockRestore();+ }+ });++ test('CLI combines dry-run skip subsets without claiming checkpoint skips', async () => {+ const log = spyOn(console, 'log').mockImplementation(() => {});+ try {+ await runExtractConversationFacts(engine, ['--dry-run', '--sleep', '0', '--types', 'conversation']);+ const summary = log.mock.calls.map(call => call.join(' ')).join('\n');+ expect(summary).toContain('across 6 segments');+ expect(summary).toContain('segmentation only; no facts extracted');+ expect(summary).toContain('from 6/10 pages');+ expect(summary).toContain('Skipped 4 page(s)');+ expect(summary).toContain('2 with no parseable speaker turns');+ expect(summary).toContain('2 with insufficient turns');+ expect(summary).not.toContain('since last checkpoint');+ expect(calls).toBe(0);+ log.mockClear();+ await runExtractConversationFacts(engine, ['--dry-run', '--slug', 'people/profile-example']);+ expect(log.mock.calls.map(call => call.join(' ')).join('\n')).toContain('2 with a type mismatch');+ log.mockClear();+ await runExtractConversationFacts(engine, ['--dry-run', '--types', 'conversation', '--since', '2099-01-01']);+ expect(log.mock.calls.map(call => call.join(' ')).join('\n')).toContain('6 with no eligible segments after --since');+ expect(calls).toBe(0);+ expect(await engine.executeRaw('SELECT id FROM facts')).toEqual([]);+ expect(await engine.executeRaw('SELECT * FROM op_checkpoints')).toEqual([]);+ expect(await engine.executeRaw('SELECT * FROM extract_rollup_7d')).toEqual([]);+ } finally {+ log.mockRestore();+ }+ });++ test('cycle totals equal exact per-source subsets in dry-run and durable replay', async () => {+ const dry = await runPhaseConversationFactsBackfill(engine, { dryRun: true });+ expect(dry.status).toBe('ok');+ expect(dry.details).toMatchObject({ pages_processed: 6, pages_skipped: 4, pages_skipped_unparsed: 2, pages_skipped_type_mismatch: 0, pages_skipped_insufficient_turns: 2, pages_skipped_since: 0 });+ const sources = dry.details?.per_source as Record<string, unknown>;+ for (const id of ['speaker-a', 'speaker-b']) expect(sources[id]).toMatchObject({ pages_considered: 5, pages_processed: 3, pages_skipped: 2, pages_skipped_unparsed: 1, pages_skipped_insufficient_turns: 1, pages_skipped_since: 0, pages_skipped_type_mismatch: 0 });+ expect(calls).toBe(0);+ expect(await engine.executeRaw('SELECT id FROM facts')).toEqual([]);+ expect(await engine.executeRaw('SELECT * FROM op_checkpoints')).toEqual([]);+ const first = await runPhaseConversationFactsBackfill(engine, {});+ expect(first.details).toMatchObject({ pages_processed: 6, pages_skipped: 4, pages_skipped_unparsed: 2, pages_skipped_insufficient_turns: 2, pages_marked_non_extractable: 2 });+ expect(calls).toBe(6);+ const second = await runPhaseConversationFactsBackfill(engine, {});+ expect(second.details).toMatchObject({ pages_processed: 0, pages_skipped: 2, pages_skipped_unparsed: 2, pages_skipped_insufficient_turns: 0, pages_skipped_completed: 6, pages_skipped_non_extractable: 2, pages_marked_non_extractable: 0 });+ expect(calls).toBe(6);+ });+});diff --git a/test/extract-conversation-facts.test.ts b/test/extract-conversation-facts.test.tsindex 5b6cd91ae7..b4915684b2 100644--- a/test/extract-conversation-facts.test.ts+++ b/test/extract-conversation-facts.test.ts@@ -45,6 +45,7 @@ import {} from '../src/commands/extract-conversation-facts.ts';import { _resetLlmCacheForTests } from '../src/core/conversation-parser/llm-base.ts';import { BudgetExhausted } from '../src/core/budget/budget-tracker.ts';+import { loadOpCheckpoint } from '../src/core/op-checkpoint.ts';// ---------------------------------------------------------------------------// pageTypesForAllowed — logical→concrete page-type expansion.@@ -534,6 +535,232 @@ describe('runExtractConversationFactsCore', () => {expect(result.segments_processed).toBeGreaterThanOrEqual(1);});+ test('#5364 speaker objects preserve provenance and isolate same-slug sources', async () => {+ const slug = 'conversations/speaker-object-example';+ const body = "{'source': 'microphone', 'attribution': 'me'}: hello\n{'source': 'speaker', 'name': 'alice-example', 'attribution': 'them'}: hi";+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('speaker-other', 'speaker-other') ON CONFLICT DO NOTHING`);+ for (const sourceId of ['default', 'speaker-other']) {+ await engine.putPage(slug, { type: 'meeting', title: 'Speaker object example', compiled_truth: body, timeline: '', frontmatter: { date: '2026-06-02' } }, { sourceId });+ }+ const turns: string[] = [];+ const result = await runExtractConversationFactsCore(engine, {+ sourceId: 'default', slug, sleepMs: 0,+ extractor: async input => {+ turns.push(input.turnText);+ return [{ fact: 'alice-example said hi', kind: 'event', confidence: 1, entity_slug: null, source: 'test', context: input.turnText }];+ },+ });+ expect(result.pages_processed).toBe(1);+ expect(result.facts_inserted).toBe(1);+ expect(turns).toHaveLength(1);+ expect(turns[0]).toContain('me (2026-06-02T00:00:00Z): hello');+ expect(turns[0]).toContain('alice-example (2026-06-02T00:00:00Z): hi');+ expect(turns[0]).not.toContain('them (');+ const rows = await engine.executeRaw<{ source_id: string; source_markdown_slug: string; source_session: string; context: string }>(+ `SELECT source_id, source_markdown_slug, source_session, context FROM facts WHERE source_markdown_slug = $1 AND source = $2`, [slug, PER_SEGMENT_SOURCE_PREFIX],+ );+ expect(rows).toHaveLength(1);+ expect(rows[0]).toMatchObject({ source_id: 'default', source_markdown_slug: slug, source_session: `${PER_SEGMENT_SOURCE_PREFIX}:${slug}`, context: turns[0] });+ expect(mainChatCalls).toBe(0);+ expect(fallbackCalls).toBe(0);+ const replay = await runExtractConversationFactsCore(engine, { sourceId: 'default', slug, sleepMs: 0 });+ expect(replay.pages_skipped_completed).toBe(1);+ expect(replay.pages_skipped).toBe(0);+ const other = await runExtractConversationFactsCore(engine, { sourceId: 'speaker-other', slug, dryRun: true, sleepMs: 0 });+ expect(other.pages_processed).toBe(1);+ expect(other.pages_skipped_completed).toBe(0);+ });++ test('#5364 dry-run on recognized turns never invokes extraction or changes durable state', async () => {+ await engine.setConfig('conversation_parser.llm_fallback_enabled', 'true');+ const before = await engine.executeRaw(`SELECT (SELECT count(*) FROM facts) AS facts, (SELECT count(*) FROM op_checkpoints) AS checkpoints, (SELECT count(*) FROM pages) AS pages, (SELECT count(*) FROM extract_rollup_7d) AS rollups`);+ let calls = 0;+ const result = await runExtractConversationFactsCore(engine, {+ sourceId: 'default', slug: 'conversations/imessage/alice-example', dryRun: true, sleepMs: 0,+ extractor: async () => { calls++; return []; },+ });+ expect(result.pages_processed).toBe(1);+ expect(result.segments_processed).toBeGreaterThan(0);+ expect(calls).toBe(0);+ expect(mainChatCalls).toBe(0);+ expect(fallbackCalls).toBe(0);+ expect(embeddedTexts).toEqual([]);+ expect(await engine.executeRaw(`SELECT (SELECT count(*) FROM facts) AS facts, (SELECT count(*) FROM op_checkpoints) AS checkpoints, (SELECT count(*) FROM pages) AS pages, (SELECT count(*) FROM extract_rollup_7d) AS rollups`)).toEqual(before);+ });++ test('#5364 skip reasons are additive subsets and no-match remains retryable', async () => {+ const singleton = 'conversations/single-speaker-object-example';+ await engine.putPage(singleton, { type: 'conversation', title: 'Single turn', compiled_truth: fmt('Alice Example', '2024-03-15', '9:00 AM', 'hello'), timeline: '', frontmatter: {} });+ const slugs = ['conversations/novel-format-example', singleton, 'people/alice-example'];+ for (const dryRun of [true, false]) {+ const result = await runExtractConversationFactsCore(engine, { sourceId: 'default', slugs, dryRun, sleepMs: 0 });+ expect(result).toMatchObject({ pages_skipped: 3, pages_skipped_unparsed: 1, pages_skipped_type_mismatch: 1, pages_skipped_insufficient_turns: 1, pages_skipped_since: 0, pages_marked_non_extractable: dryRun ? 0 : 1 });+ }+ const retry = await runExtractConversationFactsCore(engine, { sourceId: 'default', slugs, sleepMs: 0 });+ expect(retry).toMatchObject({ pages_skipped: 2, pages_skipped_unparsed: 1, pages_skipped_type_mismatch: 1, pages_skipped_insufficient_turns: 0, pages_skipped_non_extractable: 1 });+ expect(await engine.executeRaw(`SELECT id FROM facts WHERE source_markdown_slug = 'conversations/novel-format-example'`)).toEqual([]);+ expect(mainChatCalls).toBe(0);+ expect(fallbackCalls).toBe(0);+ });++ test('#5364 explicit since filtering is distinct from insufficient turns and checkpoints', async () => {+ const result = await runExtractConversationFactsCore(engine, { sourceId: 'default', slug: 'conversations/imessage/alice-example', sinceIso: '2099-01-01T00:00:00Z', sleepMs: 0 });+ expect(result).toMatchObject({ pages_skipped: 1, pages_skipped_since: 1, pages_skipped_insufficient_turns: 0, pages_skipped_unparsed: 0, pages_skipped_completed: 0, pages_marked_non_extractable: 0 });+ expect(mainChatCalls).toBe(0);+ });++ test('#5364 repairing the same no-match page extracts once without touching another source', async () => {+ const slug = 'conversations/repairable-speaker-object-example';+ const sourceId = 'default';+ const otherSourceId = 'speaker-other';+ const title = 'Repairable speaker object example';+ const unsupported = 'An unsupported transcript without speaker anchors.';+ const supported = "{'source': 'microphone', 'attribution': 'me'}: hello\n{'attribution': 'them', 'name': 'alice-example', 'source': 'speaker'}: hi";+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT DO NOTHING', [otherSourceId]);+ for (const id of [sourceId, otherSourceId]) {+ await engine.putPage(slug, { type: 'meeting', title, compiled_truth: unsupported, timeline: '', frontmatter: { date: '2026-06-02' } }, { sourceId: id });+ }+ const otherPage = await engine.getPage(slug, { sourceId: otherSourceId });+ const checkpoint = (id: string) => ({ op: 'extract-conversation-facts', fingerprint: extractConversationFactsFingerprint({ sourceId: id }) });+ const assertOtherUntouched = async () => {+ expect(await engine.getPage(slug, { sourceId: otherSourceId })).toEqual(otherPage);+ expect(await engine.executeRaw('SELECT id FROM facts WHERE source_id = $1', [otherSourceId])).toEqual([]);+ expect(await loadOpCheckpoint(engine, checkpoint(otherSourceId))).toEqual([]);+ };+ const turns: string[] = [];+ const extractor = async (input: { turnText: string }) => {+ turns.push(input.turnText);+ return [{ fact: 'alice-example said hi', kind: 'event' as const, confidence: 1, entity_slug: null, source: 'test', context: input.turnText }];+ };+ for (let attempt = 0; attempt < 2; attempt++) {+ const result = await runExtractConversationFactsCore(engine, { sourceId, slug, extractor, sleepMs: 0 });+ expect(result).toMatchObject({ pages_considered: 1, pages_processed: 0, pages_skipped: 1, pages_skipped_unparsed: 1, pages_skipped_completed: 0, pages_skipped_non_extractable: 0, pages_marked_non_extractable: 0, facts_inserted: 0 });+ expect(await engine.executeRaw('SELECT id FROM facts WHERE source_markdown_slug = $1', [slug])).toEqual([]);+ expect(await loadOpCheckpoint(engine, checkpoint(sourceId))).toEqual([]);+ expect(turns).toEqual([]);+ expect(mainChatCalls).toBe(0);+ expect(fallbackCalls).toBe(0);+ expect(embeddedTexts).toEqual([]);+ await assertOtherUntouched();+ }++ await engine.putPage(slug, { type: 'meeting', title, compiled_truth: supported, timeline: '', frontmatter: { date: '2026-06-02' } }, { sourceId });+ const repaired = await runExtractConversationFactsCore(engine, { sourceId, slug, extractor, sleepMs: 0 });+ expect(repaired).toMatchObject({ pages_processed: 1, pages_skipped: 0, pages_skipped_unparsed: 0, segments_processed: 1, facts_inserted: 1 });+ const expectedTurn = `Page: ${title}\nConversation between me and alice-example from 2026-06-02T00:00:00Z to 2026-06-02T00:00:00Z\n---\nme (2026-06-02T00:00:00Z): hello\nalice-example (2026-06-02T00:00:00Z): hi`;+ expect(turns).toEqual([expectedTurn]);+ const facts = await engine.executeRaw<{ source_id: string; source: string; source_session: string; source_markdown_slug: string; context: string; row_num: number }>(+ 'SELECT source_id, source, source_session, source_markdown_slug, context, row_num FROM facts WHERE source_markdown_slug = $1 ORDER BY row_num', [slug],+ );+ expect(facts).toHaveLength(2);+ expect(facts[0]).toEqual({ source_id: sourceId, source: PER_SEGMENT_SOURCE_PREFIX, source_session: `${PER_SEGMENT_SOURCE_PREFIX}:${slug}`, source_markdown_slug: slug, context: expectedTurn, row_num: 0 });+ expect(facts[1]).toMatchObject({ source_id: sourceId, source: TERMINAL_AUDIT_SOURCE, source_markdown_slug: slug, row_num: 1 });+ expect(await loadOpCheckpoint(engine, checkpoint(sourceId))).toEqual([encodeCheckpointEntry(sourceId, slug, '2026-06-02T00:00:00Z')]);+ await assertOtherUntouched();++ const replay = await runExtractConversationFactsCore(engine, { sourceId, slug, extractor, sleepMs: 0 });+ expect(replay).toMatchObject({ pages_considered: 1, pages_processed: 0, pages_skipped: 0, pages_skipped_completed: 1, facts_inserted: 0 });+ expect(turns).toEqual([expectedTurn]);+ expect(await engine.executeRaw('SELECT source_id, source, source_session, source_markdown_slug, context, row_num FROM facts WHERE source_markdown_slug = $1 ORDER BY row_num', [slug])).toEqual(facts);+ expect(mainChatCalls).toBe(0);+ expect(fallbackCalls).toBe(0);+ expect(embeddedTexts).toEqual([]);+ await assertOtherUntouched();+ });++ test('#5364 wrapper-contained speakers never reach extraction or certify an outcome', async () => {+ const first = "{'source': 'microphone', 'attribution': 'me'}: hello";+ const second = "{'source': 'speaker', 'name': 'alice-example', 'attribution': 'them'}: hi";+ const wrappers = [+ `{'example': '''\n${first}\n${second}\n'''}`,+ `{'example': {\n${first}\n${second}\n}}`,+ `[\n${first}\n${second}\n]`,+ `payload = (\n${first}\n${second}\n)`,+ `{'example': '''\n## Transcript\n${first}\n${second}\n'''}`,+ `## Summary\npayload(\n## Transcript\n${first}\n${second}`,+ `## Summary\nr'\n## Transcript\n${first}\n${second}`,+ ];+ let extractorCalls = 0;+ for (const [index, wrapper] of wrappers.entries()) {+ for (const [position, prefix] of [['bare', ''], ['section', '## Transcript\n'], ['after-turn', `${first}\n`]] as const) {+ const slug = `conversations/wrapper-${index}-${position}`;+ await engine.putPage(slug, { type: 'meeting', title: 'Wrapped speaker examples', compiled_truth: prefix + wrapper, timeline: '', frontmatter: { date: '2026-06-02' } });+ const result = await runExtractConversationFactsCore(engine, {+ sourceId: 'default', slug, sleepMs: 0,+ extractor: async () => {+ extractorCalls++;+ return [{ fact: 'invented speaker context', kind: 'event', confidence: 1, entity_slug: null, source: 'test' }];+ },+ });+ expect(result).toMatchObject({ pages_considered: 1, pages_processed: 0, pages_skipped: 1, pages_skipped_unparsed: 1, pages_marked_non_extractable: 0, pages_skipped_completed: 0, segments_processed: 0, facts_inserted: 0 });+ expect(await engine.executeRaw('SELECT id FROM facts WHERE source_markdown_slug = $1', [slug])).toEqual([]);+ expect(await loadOpCheckpoint(engine, { op: 'extract-conversation-facts', fingerprint: extractConversationFactsFingerprint({ sourceId: 'default' }) })).toEqual([]);+ expect(extractorCalls).toBe(0);+ expect(mainChatCalls).toBe(0);+ expect(fallbackCalls).toBe(0);+ expect(embeddedTexts).toEqual([]);+ }+ }+ });++ test('#5364 summary punctuation and following notes preserve genuine transcript extraction', async () => {+ const turns = "{'source': 'microphone', 'attribution': 'me'}: hello\n{'source': 'speaker', 'name': 'alice-example', 'attribution': 'them'}: hi";+ const bodies = [+ `## Summary\nThe founders' update is ready. Good job :)\n## Transcript\n${turns}`,+ `## Transcript\n${turns}\n## Action Items\nFollow up next week.`,+ ];+ const extracted: string[] = [];+ for (const [index, body] of bodies.entries()) {+ const slug = `conversations/section-boundary-${index}`;+ await engine.putPage(slug, { type: 'meeting', title: 'Sectioned transcript', compiled_truth: body, timeline: '', frontmatter: { date: '2026-06-02' } });+ const result = await runExtractConversationFactsCore(engine, {+ sourceId: 'default', slug, sleepMs: 0,+ extractor: async ({ turnText }) => {+ extracted.push(turnText);+ return [{ fact: 'alice-example said hi', kind: 'event', confidence: 1, entity_slug: null, source: 'test' }];+ },+ });+ expect(result).toMatchObject({ pages_processed: 1, pages_skipped_unparsed: 0, segments_processed: 1, facts_inserted: 1 });+ expect(await engine.executeRaw('SELECT id FROM facts WHERE source_markdown_slug = $1 AND source = $2', [slug, TERMINAL_AUDIT_SOURCE])).toHaveLength(1);+ }+ expect(extracted).toHaveLength(2);+ for (const text of extracted) {+ expect(text).toContain('me (2026-06-02T00:00:00Z): hello');+ expect(text).toContain('alice-example (2026-06-02T00:00:00Z): hi');+ expect(text).not.toContain('founders');+ expect(text).not.toContain('Follow up');+ }+ expect(mainChatCalls).toBe(0);+ expect(fallbackCalls).toBe(0);+ });++ test('#5364 oversized pages stop before extraction without touching another source', async () => {+ const slug = 'conversations/oversized-speaker-example';+ const otherSourceId = 'oversized-other';+ const turns = `${fmt('Alice Example', '2026-06-02', '9:00 AM', 'hello')}\n${fmt('Bob Example', '2026-06-02', '9:01 AM', 'hi')}\n`;+ const body = turns + 'x'.repeat(MAX_PAGE_BODY_BYTES + 1 - Buffer.byteLength(turns));+ expect(Buffer.byteLength(body)).toBe(MAX_PAGE_BODY_BYTES + 1);+ await engine.putPage(slug, { type: 'meeting', title: 'Oversized transcript', compiled_truth: body, timeline: '', frontmatter: { date: '2026-06-02' } });+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT DO NOTHING', [otherSourceId]);+ await engine.putPage(slug, { type: 'meeting', title: 'Other source transcript', compiled_truth: turns, timeline: '', frontmatter: { date: '2026-06-02' } }, { sourceId: otherSourceId });+ const otherPage = await engine.getPage(slug, { sourceId: otherSourceId });+ let extractorCalls = 0;+ const result = await runExtractConversationFactsCore(engine, {+ sourceId: 'default', slug, sleepMs: 0,+ extractor: async () => { extractorCalls++; return []; },+ });+ expect(result).toMatchObject({ pages_considered: 1, pages_processed: 0, pages_skipped: 0, pages_skipped_too_large: 1, pages_skipped_unparsed: 0, pages_skipped_insufficient_turns: 0, pages_marked_non_extractable: 0, pages_skipped_completed: 0, segments_processed: 0, facts_inserted: 0 });+ expect(extractorCalls).toBe(0);+ expect(mainChatCalls).toBe(0);+ expect(fallbackCalls).toBe(0);+ expect(embeddedTexts).toEqual([]);+ expect(await engine.executeRaw('SELECT id FROM facts WHERE source_markdown_slug = $1', [slug])).toEqual([]);+ for (const sourceId of ['default', otherSourceId]) {+ expect(await loadOpCheckpoint(engine, { op: 'extract-conversation-facts', fingerprint: extractConversationFactsFingerprint({ sourceId }) })).toEqual([]);+ }+ expect(await engine.getPage(slug, { sourceId: otherSourceId })).toEqual(otherPage);+ });+test('historical backfill embeds and retains high, medium, low, and absent-tier facts', async () => {// Regression target: passing high-only admission into the historical// extractor call would suppress low (and absent-tier) facts before embed.diff --git a/test/fixtures/conversation-formats/all.jsonl b/test/fixtures/conversation-formats/all.jsonlindex 9b2f9e4b8b..f721e98a45 100644--- a/test/fixtures/conversation-formats/all.jsonl+++ b/test/fixtures/conversation-formats/all.jsonl@@ -1,3 +1,11 @@+{"fixture_id":"speaker-object-quoted-wrapper","pattern":null,"frontmatter":{},"body":"{'example': '''\n{'source': 'microphone', 'attribution': 'me'}: hello\n{'source': 'speaker', 'name': 'alice-example', 'attribution': 'them'}: hi\n'''}","expected_messages":0,"expected_participants":[]}+{"fixture_id":"speaker-object-nested-wrapper","pattern":null,"frontmatter":{},"body":"## Transcript\n{'example': {\n{'source': 'microphone', 'attribution': 'me'}: hello\n{'source': 'speaker', 'name': 'alice-example', 'attribution': 'them'}: hi\n}}","expected_messages":0,"expected_participants":[]}+{"fixture_id":"speaker-object-wrapper-after-turn","pattern":null,"frontmatter":{},"body":"{'source': 'microphone', 'attribution': 'me'}: real turn\n[\n{'source': 'microphone', 'attribution': 'me'}: example\n{'source': 'speaker', 'name': 'alice-example', 'attribution': 'them'}: example\n]","expected_messages":0,"expected_participants":[]}+{"fixture_id":"speaker-object-wrapped-section","pattern":null,"frontmatter":{},"body":"## Summary\npayload(\n## Transcript\n{'source': 'microphone', 'attribution': 'me'}: hello\n{'source': 'speaker', 'name': 'alice-example', 'attribution': 'them'}: hi","expected_messages":0,"expected_participants":[]}+{"fixture_id":"speaker-object-001","pattern":"python-dict-utterance","frontmatter":{"date":"2026-06-02"},"body":"{'source': 'microphone', 'attribution': 'me'}: hello\n{'source': 'speaker', 'name': 'alice-example', 'attribution': 'them'}: hi","expected_messages":2,"expected_participants":["me","alice-example"]}+{"fixture_id":"speaker-object-002","pattern":"python-dict-utterance","frontmatter":{"date":"2026-06-02"},"body":"## Summary\nA meeting summary.\n## Transcript\n{'attribution': 'me', 'source': 'microphone', 'name': 'bob-example'}: hello\n{'name': 'alice-example', 'attribution': 'them', 'source': 'speaker'}: hi","expected_messages":2,"expected_participants":["bob-example","alice-example"]}+{"fixture_id":"speaker-object-duplicate","pattern":null,"frontmatter":{},"body":"{'source': 'speaker', 'attribution': 'them', 'name': 'alice-example', 'name': 'bob-example'}: ambiguous","expected_messages":0,"expected_participants":[]}+{"fixture_id":"speaker-object-code","pattern":null,"frontmatter":{},"body":"```python\n{'source': 'microphone', 'attribution': 'me'}: hello\n{'source': 'speaker', 'attribution': 'them'}: hi\n```","expected_messages":0,"expected_participants":[]}{"fixture_id":"imessage-001","pattern":"imessage-slack","frontmatter":{"date":"2024-03-15"},"body":"**Alice Example** (2024-03-15 9:00 AM): morning\n**Bob Example** (2024-03-15 9:01 AM): hey there\n**Alice Example** (2024-03-15 9:02 AM): how are you\n**Bob Example** (2024-03-15 9:03 AM): good thanks\n**Alice Example** (2024-03-15 9:04 AM): you?","expected_messages":5,"expected_participants":["Alice Example","Bob Example"]}{"fixture_id":"imessage-002","pattern":"imessage-slack","frontmatter":{"date":"2024-03-15"},"body":"**Charlie Example** (2024-03-15 2:00 PM): afternoon\n**Charlie Example** (2024-03-15 2:01 PM): are you there?\n**Diana Example** (2024-03-15 2:05 PM): yes\n**Charlie Example** (2024-03-15 2:06 PM): great","expected_messages":4,"expected_participants":["Charlie Example","Diana Example"]}{"fixture_id":"imessage-time-only-12h-001","pattern":"bold-paren-time-12h","frontmatter":{"date":"2024-03-15"},"body":"## 2024-03-15\n**Alice Example** (9:04 AM): morning\n**Bob Example** (9:05 AM): hey there\n## 2024-03-16\n**Alice Example** (10:06 PM): second day\n**Bob Example** (10:07 PM): good night","expected_messages":4,"expected_participants":["Alice Example","Bob Example"]}diff --git a/test/timeline-parser-regression.test.ts b/test/timeline-parser-regression.test.tsnew file mode 100644index 0000000000..e7260edfa1--- /dev/null+++ b/test/timeline-parser-regression.test.ts@@ -0,0 +1,162 @@+import { describe, expect, test } from 'bun:test';+import { spawnSync } from 'node:child_process';+import { extractLinksFromFile, extractTimelineFromContent } from '../src/commands/extract.ts';+import { extractEntityRefs, extractPageLinks, parseTimelineEntries } from '../src/core/link-extraction.ts';+import { stripCodeBlocks } from '../src/core/markdown-code.ts';+import { parseInlineCitationTimelineEntries } from '../src/core/timeline-citations.ts';++describe('timeline prefix compatibility', () => {+ test('keeps optional bullets, whitespace, date spellings, and separator runs', () => {+ for (const prefix of ['', ' \t', '-', ' \t-\t ', '\u00a0-\u3000']) {+ for (const date of ['**2024-02-29**', '2024年2月29日', '**2024年02月29日**', '2024年2月29', '**2024年2月29**']) {+ for (const separator of ['|', '-', '--', '–', '—', '|–—']) {+ for (const ending of ['', '\r']) {+ const input = `${prefix}${date} ${separator} Notes — Event${ending}`;+ expect(parseTimelineEntries(input)).toEqual([{+ date: '2024-02-29',+ summary: separator.includes('|') ? 'Event' : 'Notes — Event',+ detail: '',+ source: separator.includes('|') ? 'Notes' : 'markdown',+ }]);+ }+ }+ }+ }+ });++ test('keeps invalid calendar dates and unsupported ASCII shapes rejected', () => {+ for (const date of ['**2026-02-29**', '**1900-02-29**', '**2026-13-01**', '**2026-01-00**', '2026年2月30日', '**2026年0月1日**', '2026年1月32日', '2024-02-29', '**2024-2-29**']) {+ expect(parseTimelineEntries(` \t- ${date} | Event`)).toEqual([]);+ }+ expect(parseTimelineEntries(' \t- **2024-02-29** | ')).toEqual([]);+ });++ test('bounds adversarial whitespace in a child process and reports 1x/2x/4x scaling', () => {+ const parserUrl = new URL('../src/core/link-extraction.ts', import.meta.url).href;+ const child = spawnSync(process.execPath, ['--eval', `+ import { deepStrictEqual } from 'node:assert';+ import { parseTimelineEntries } from ${JSON.stringify(parserUrl)};+ parseTimelineEntries('not-a-date');+ const diagnostics = [];+ for (const spaces of [4_000, 8_000, 16_000]) {+ const input = ' '.repeat(spaces) + 'not-a-date';+ const started = performance.now();+ deepStrictEqual(parseTimelineEntries(input), []);+ diagnostics.push({ spaces, ms: performance.now() - started });+ }+ console.log(JSON.stringify({ diagnostics }));+ const whitespace = ' '.repeat(1_000_000);+ for (const suffix of ['', 'not-a-date', '- not-a-date']) {+ deepStrictEqual(parseTimelineEntries(whitespace + suffix), []);+ }+ for (const date of ['**2024-02-29**', '2024年2月29日']) {+ for (const bullet of ['', '- ']) {+ deepStrictEqual(parseTimelineEntries(whitespace + bullet + date + ' | Event'), [+ { date: '2024-02-29', summary: 'Event', detail: '', source: 'markdown' },+ ]);+ }+ }+ console.log('bounded timeline cases passed');+ `], { encoding: 'utf8', timeout: 20_000, killSignal: 'SIGKILL' });+ console.log(child.stdout);+ expect(child.error, child.stderr).toBeUndefined();+ expect(child.signal, child.stderr).toBeNull();+ expect(child.status, child.stderr).toBe(0);+ expect(child.stdout).toContain('bounded timeline cases passed');+ }, 30_000);+});++for (const [label, eol] of [['LF', '\n'], ['CRLF', '\r\n']] as const) {+ describe(`code masking with ${label}`, () => {+ for (const closed of [true, false]) {+ test(`preserves every newline and UTF-16 offset in ${closed ? 'closed' : 'unclosed'} fences`, () => {+ const before = `Before 🧪 [Visible](people/visible)${eol}`;+ const code = ['```md', '示例 🧪 [Hidden](people/hidden)', 'Fake. [Source: fixture, 2024-02-29]', ...(closed ? ['```'] : [])].join(eol);+ const after = closed ? `${eol}After [[people/after]]` : '';+ const input = before + code + after;+ const masked = stripCodeBlocks(input);+ expect(masked.length).toBe(input.length);+ expect([...masked.matchAll(/[\r\n]/g)].map(m => [m.index, m[0]]))+ .toEqual([...input.matchAll(/[\r\n]/g)].map(m => [m.index, m[0]]));+ for (let i = 0; i < input.length; i++) {+ const hidden = i >= before.length && i < before.length + code.length;+ expect(masked[i]).toBe(hidden && input[i] !== '\r' && input[i] !== '\n' ? ' ' : input[i]);+ }+ });+ }++ test('keeps adjacent real citations separate across a closed fence', () => {+ const separateLines = [+ 'Before. [Source: before memo, 2024-02-27]',+ '```md',+ 'Fake. [Source: hidden memo, 2024-02-28]',+ '```',+ 'After. [Source: after memo, 2024-02-29]',+ ].join(eol);+ const expected = [+ { date: '2024-02-27', source: 'before memo', summary: 'Before.' },+ { date: '2024-02-29', source: 'after memo', summary: 'After.' },+ ];+ const adjoiningProse = [+ 'Before. [Source: before memo, 2024-02-27]```md',+ 'Fake. [Source: hidden memo, 2024-02-28]',+ '```After. [Source: after memo, 2024-02-29]',+ ].join(eol);+ for (const content of [separateLines, adjoiningProse]) {+ expect(parseInlineCitationTimelineEntries(content)).toEqual(expected);+ expect(parseTimelineEntries(content)).toEqual(expected.map(entry => ({ ...entry, detail: `Source: ${entry.source}` })));+ expect(extractTimelineFromContent(content, 'notes/example')).toEqual(expected.map(entry => ({ ...entry, slug: 'notes/example' })));+ }+ });++ test('hides unclosed fences and inline citations without losing real citations', () => {+ const content = [+ 'Real. `Fake. [Source: inline memo, 2024-02-28]` [Source: real memo, 2024-02-27]',+ '```md',+ 'Hidden. [Source: hidden memo, 2024-02-29]',+ ].join(eol);+ const expected = [{ date: '2024-02-27', source: 'real memo', summary: 'Real.' }];+ expect(parseInlineCitationTimelineEntries(content)).toEqual(expected);+ expect(parseTimelineEntries(content)).toEqual(expected.map(entry => ({ ...entry, detail: 'Source: real memo' })));+ expect(extractTimelineFromContent(content, 'notes/example')).toEqual(expected.map(entry => ({ ...entry, slug: 'notes/example' })));+ });++ test('hides code references and keeps real link offsets in both extract paths', async () => {+ const content = [+ '🧪 [Before](../people/before.md)',+ '`[Inline](../people/inline.md)`',+ '```md',+ '[Hidden](../people/hidden.md) [[people/hidden-wiki]]',+ '```',+ '[[people/after]]',+ '```',+ '[Unclosed](../people/unclosed.md)',+ ].join(eol);+ const slugs = new Set(['people/before', 'people/inline', 'people/hidden', 'people/hidden-wiki', 'people/after', 'people/unclosed']);+ expect(extractEntityRefs(content).map(({ slug, index }) => ({ slug, index }))).toEqual([+ { slug: 'people/before', index: content.indexOf('[Before]') },+ { slug: 'people/after', index: content.indexOf('[[people/after]]') },+ ]);+ const fsLinks = await extractLinksFromFile(content, 'notes/example.md', slugs);+ expect(fsLinks.map(link => link.to_slug).sort()).toEqual(['people/after', 'people/before']);+ const dbLinks = await extractPageLinks('notes/example', content, {}, 'note', {+ resolve: async name => slugs.has(name) ? name : null,+ });+ expect(dbLinks.candidates.map(link => link.targetSlug).sort()).toEqual(['people/after', 'people/before']);+ });+ });+}++test('inline masking preserves bare CR and the existing unmatched/multiline backtick behavior', () => {+ const inline = '`示例 🧪`';+ expect(stripCodeBlocks(`Before ${inline} after`)).toBe(`Before ${' '.repeat(inline.length)} after`);+ expect(stripCodeBlocks('before `a\rb` after')).toBe('before \r after');+ for (const input of ['before `unclosed', '`first\nsecond`', '`first\r\nsecond`']) {+ expect(stripCodeBlocks(input)).toBe(input);+ }+});++test('fence masking preserves mixed LF, CRLF, and bare CR at exact offsets', () => {+ expect(stripCodeBlocks('before```md\r\n🧪\ra\n```after')).toBe('before \r\n \r \n after');+ expect(stripCodeBlocks('before```md\r\n🧪\ra\n')).toBe('before \r\n \r \n');+});