Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.59.11.0 fix(import): recorded page identity, slug collisions, replace-on-sync links and timeline, strict entity resolution, calendar-stable dates (#5668)

Garry Tan2ede415d74d5
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 0b8db854d3..d952fb4918 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.59.10.0",
+ "version": "0.59.11.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.json
index ebe1ae00e9..6b698ec59e 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.59.10.0",
+ "version": "0.59.11.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.md
index 068b930a9f..cc4b5969d4 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -1,4 +1,4 @@
-<!-- gbrain-runbook-stamp: 0.59.10.0 -->
+<!-- gbrain-runbook-stamp: 0.59.11.0 -->
<!-- This stamp must equal the VERSION file at every release; CI enforces it
(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it to
the installed binary and warns on skew. -->
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 819b58672b..54ed07c4fd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,45 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [0.59.11.0] - 2026-09-28
+
+**Your brain stops losing notes, stops linking people to the wrong person, and forgets links and dates you deleted.**
+
+Several everyday edits used to corrupt memory quietly. Moving a note that carries an `id:` to another folder and running a full sync could leave that note with no page at all. Two different notes sharing an `id:` (templates do this) meant the second one was never indexed. Two files whose names differ only in spaces or case overwrote each other on every edit. When the embedding provider was down, a new note was not saved at all.
+
+The graph drifted too. Removing a `[[link]]` or fixing a dated bullet left the old edge and the old timeline entry behind, because sync only ever added. A link to "Carol Exampl" attached to the page of a different person called "Carol Example", and facts about someone with no page could land on a meeting page. Renaming a page broke every link written against its old name. Dates depended on the syncing computer's time zone, "2024-02-30" became March 1, and undated notes took the import time as their date.
+
+All of that is fixed. Sync now treats the note's text as the truth for its links and timeline, the same way the MCP `put_page` path already did.
+
+| On a synthetic brain (64 near-name people, 4 companies) | Before | After |
+| --- | --- | --- |
+| Link resolver precision (265 probes, recall stays 1.0) | 0.745 (67 wrong entities) | 0.995 (1 wrong) |
+| Fact entity resolver precision | 0.838 (38 wrong) | 1.0 (0 wrong) |
+| Edge precision after 20 sync edits (true edges 34) | 0.374 (91 edges) | 1.0 (34 edges) |
+| Timeline precision after 20 sync edits | 0.104 | 1.0 |
+
+BrainBench (all harnesses, all suites) and the retrieval canary are byte-identical before and after. LONGMEMEVAL_ROW
+
+### To take advantage of v0.59.11.0
+
+Run `gbrain upgrade`. There is no migration. New behavior applies as pages are written; to repair an existing graph, run `gbrain sync --full` (moved and colliding files reconcile, image pages pick up missing visual vectors) and `gbrain extract --stale` for pages edited since their last extraction. Watch the sync output for `slug collision` warnings: rename one of the two files to index both. `gbrain embed --stale` embeds any page saved during a provider outage.
+
+### Itemized changes
+
+- **Moved files keep their page.** When a file's `frontmatter.id` matches a page whose recorded file is gone, import renames that page in place (links, facts and timeline survive) instead of skipping, so a full sync no longer soft-deletes the only live copy. A shared `id:` with different content imports as its own page; only same id plus same content while the old file still exists is skipped as a duplicate. `findDuplicatePage` excludes the caller's own slug and ranks an id match ahead of a text match.
+- **Slug collisions are loud.** Two live files that map to one slug no longer overwrite each other. The file named exactly like the slug owns it; otherwise the current owner keeps it, and the other file reports `skip_reason: slug_collision` with a warning naming both paths.
+- **An embedding outage never blocks a write.** The text and chunks commit with empty vectors and `embedding_deferred: true`; the stale sweep embeds them later. A code file whose embedding failed is no longer stamped as embedded.
+- **Images retry their index.** An unchanged image is skipped only when it has its visual vector (when embedding is on) and OCR (when OCR is on), so images imported under `--no-embed` or an OCR skip are rebuilt. Image pages record their source path, so a deleted image is reconciled by full sync.
+- **Sync reconciles derived data.** The sync and cycle extractors replace a page's own markdown links (other producers' edges stay) and remove timeline rows its previous text produced that the current text no longer does.
+- **Near-names stay unresolved.** Fuzzy matches to a person, company, fund or organization need the same name tokens (case, punctuation, order, accents and suffixes like "Inc" aside). Otherwise the link resolver leaves the reference unresolved and the fact resolver keeps the reference's own slug. The live keyword fallback is source-scoped.
+- **Renames leave an alias.** `updateSlug` records `old -> new` in `slug_aliases` in the same transaction; the link resolver and file-sync extraction resolve old slugs to the renamed page, so inbound edges survive.
+- **Dates are calendar facts.** Date-only values are UTC calendar dates and naive datetimes are read as UTC on every host. Invalid dates such as `2024-02-30` are rejected, including unquoted YAML values. `created`, `created_at`, `date_created` and `date created` are content dates. An undated page falls back to its file's timestamp and keeps that date across edits.
+
+### For contributors
+
+- New tests: `test/import-identity-move.test.ts`, `test/import-slug-collision.test.ts`, `test/import-embed-outage.test.ts`, `test/import-image-retry.test.ts`, `test/sync-derived-reconcile.test.ts`, `test/entity-resolution-near-names.test.ts`, `test/rename-slug-alias.test.ts`, `test/effective-date-calendar.test.ts`.
+- Contract updates in existing tests: an id echo with different content no longer redirects (`test/put-page-dedup-fence.test.ts`, `test/minions/delegated-execution.serial.test.ts`), a rename records its own alias (`test/helpers/deep-research-contract.ts`), the incremental extract test restores the engine methods it wraps (`test/extract-incremental.test.ts`), the cycle diagnostics test drops a page's link replacement instead of a batch (`test/cycle-stale-drain.test.ts`), identity matches against a moved file land at the destination (`test/sync-rename-reconcile.serial.test.ts`), the per-slug sync lanes replace ordinary meeting links while the full-walk lane stays additive (`test/attendance-retrieval.test.ts`), a one-edit person typo falls back to its own slug (`test/entity-resolve.test.ts`), and the effective-date fallback prefers the creation anchor over the last write (`test/effective-date.test.ts`).
+
## [0.59.10.0] - 2026-09-28
**Memory maintenance preserves what it cannot safely rebuild and tells you what remains unfinished.**
diff --git a/VERSION b/VERSION
index dd4b94f925..373cda93c1 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.59.10.0
+0.59.11.0
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsv
index 709f23c972..b041b32f5a 100644
--- a/docs/architecture/canonical-writers.tsv
+++ b/docs/architecture/canonical-writers.tsv
@@ -60,7 +60,7 @@ src/core/git-remote.ts 0 filesystem_guard Clone, pull and rebase entry points ch
src/core/github-source.ts 3 coordinator Managed connector imports, deletion and checkpoints use prepared journal publication; unbound API sources explicitly persist in the database and bound sources retain canonical filesystem publication.
src/core/google/google-source.ts 3 coordinator Managed connector imports, deletion and checkpoints use prepared journal publication; legacy materialization is confined to unmanaged sources.
src/core/google/loops-extract.ts 1 early_refusal Unsupported managed loop extraction refuses before model calls; unchanged unmanaged fact/fence writes remain guarded.
-src/core/import-file.ts 15 coordinator Prepared import applies under journal publication and revision CAS; direct managed imports refuse early, and legacy source-path repair follows revision validation inside a savepoint.
+src/core/import-file.ts 16 coordinator Prepared import applies under journal publication and revision CAS; direct managed imports refuse early, legacy source-path repair follows revision validation inside a savepoint, and a moved file's page is renamed only on the direct (unmanaged) path.
src/core/last-retrieved.ts 1 projection Derived indexing, retrieval telemetry, or source settings; canonical fields remain guarded by SQL triggers.
src/core/migrate.ts 13 schema Schema installation and forward-reference DDL; coordinated activation quiesces canonical writers.
src/core/minions/handlers/ingest-capture.ts 1 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.
@@ -158,4 +158,6 @@ src/core/shared-skills/setup.ts 1 engine_guard Trusted preactivation empty-sourc
src/core/shared-skills/optimizer.ts 0 coordinator Shared optimization preserves the exact approved closure and original grants in private staging; only accepted body changes reach put_skill with the original revision and stable request UUID.
src/core/persistence/import-prepare.ts 1 coordinator The prepared local import updates source_path only inside canonical publication; owner, input and target hashes, source confinement and knowledge-versus-skill boundary revalidate before apply.
src/core/persistence/grandfather.ts 2 coordinator Private migration intents preserve exact page/source/incarnation/revision identity and rollback snapshots; frontmatter/hash and existing text seals change only inside canonical file publication, without new embedding or fact-backstop effects.
+src/core/page-state/rename-alias.ts 3 engine_guard Rename aliases write slug_aliases inside the updateSlug transaction; the canonical table SQL trigger requires coordinator capability, so legacy calls fail before publication.
+src/core/timeline-extract.ts 1 engine_guard Retracting removed markdown timeline rows is canonical table SQL; the trigger requires coordinator capability, so legacy calls fail before canonical DB publication.
src/core/persistence/connector-google-receipts.ts 1 coordinator Account and message-owned Gmail receipt metadata changes only under canonical source/page locks, identity/revision and file guards; guarded projection installation preserves withdrawal overlays without replaying bodies or extracting facts.
diff --git a/docs/architecture/key-files/commands-3.md b/docs/architecture/key-files/commands-3.md
index b95b88f278..2a0fe705c5 100644
--- a/docs/architecture/key-files/commands-3.md
+++ b/docs/architecture/key-files/commands-3.md
@@ -29,7 +29,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `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.
+- `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). The full fs/db walks buffer candidates 100 at a time and flush via `addLinksBatch` / `addTimelineEntriesBatch` (additive); `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. The per-slug extractors reconcile like `put_page`: each page's own markdown-derived links are replaced through `replacePageFileLinks` (`src/core/link-reconciliation.ts`, `replaceDerivedLinks` with `preserveExisting`; other producers survive, a page with no row counts as processed with no links, and a failed replacement is reported on stderr and leaves the page stale), and `retractRemovedTimelineEntries` (`src/core/timeline-extract.ts`) deletes the exact (date, source, summary) rows the page's previous version produced that its current text no longer does. `loadSlugAliasTargets` adds renamed pages' old slugs (`slug_aliases`) to `allSlugs` so links written before a rename resolve to the current slug. 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`.
- `src/commands/features.ts` — `gbrain features --json --auto-fix`: usage scan + feature adoption salesman.
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index 91d1ac65f7..bfb189e266 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -43,7 +43,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/ops/sources.ts` — `sources_remove` is confined to the caller's WRITE authority via `assertSourceInCallerWriteScope(ctx, id)` (context.ts): an untrusted caller may hard-remove only its own write source; a federated read grant naming a source does not make it removable; any other id answers `OperationError('not_found', 'Unknown source: <id>')`, byte-identical to a nonexistent source so the error is not an existence oracle. `sources_status` keeps the read-scope helper (`assertSourceInCallerScope`), so a federated grant can still diagnose a source it cannot remove. Trusted local CLI keeps the full operator view. Over HTTP every client carries a write source (registration default `default`) and its own `oauth_clients.source_id` row FK-RESTRICTs removing that source, so hard removal is effectively an operator action (`gbrain sources remove`); a source a remote `sources_admin` caller just created via `sources_add` stays outside its authority until the operator rescopes the client. There is no `sources_archive` op — archive lives in the CLI (`gbrain sources archive`). Pinned by `test/sources-mcp.test.ts` (federated-read-only id → not_found while status still answers; write-source id → removed; unbound → any; local → any; `remote: undefined` fail-closed) and `test/e2e/sources-remote-mcp.test.ts` (real server: not_found before AND after a read-grant widen; operator CLI completes; rescoping `--source` moves the authority).
-- `src/core/page-state/` — Canonical page concurrency foundation shared by both engines. `schema.ts` (migration 150) adds source incarnation UUIDs, logical page revisions, text-projection revisions, and persistent guards for absent pages. `guards.ts` locks sorted sources then page identities in an existing transaction; callers lock sources before authority/request/fact rows. `snapshot.ts` reads page/tags/withdrawals in one MVCC statement and applies withdrawals using database-normalized text. `transactions.ts` makes helper transaction APIs compose through savepoints. `versions.ts` records the complete canonical snapshot; `materialize.ts` persists only verified canonical overlay bytes without another logical revision. `types.ts` defines revision preconditions: missing revision is create-only, explicit force overwrites. Plain legacy `putPage` calls keep compatibility until their owning operation adopts the managed write protocol. `projection-schema.ts` (migration 153) invalidates unverified prior projections once and queues durable work; `projections.ts` rebuilds Markdown without a worktree/provider and installs only matching canonical revisions. Embedding installs also compare exact chunk identities/text. Source importers seal code/image projections; all read arms hide unsealed projections.
+- `src/core/page-state/` — Canonical page concurrency foundation shared by both engines. `schema.ts` (migration 150) adds source incarnation UUIDs, logical page revisions, text-projection revisions, and persistent guards for absent pages. `guards.ts` locks sorted sources then page identities in an existing transaction; callers lock sources before authority/request/fact rows. `snapshot.ts` reads page/tags/withdrawals in one MVCC statement and applies withdrawals using database-normalized text. `transactions.ts` makes helper transaction APIs compose through savepoints. `versions.ts` records the complete canonical snapshot; `rename-alias.ts` records `slug_aliases(old -> new)` inside both engines' `updateSlug` transaction, repoints aliases that named the old slug and drops one spelled like the new slug (`test/rename-slug-alias.test.ts`); `materialize.ts` persists only verified canonical overlay bytes without another logical revision. `types.ts` defines revision preconditions: missing revision is create-only, explicit force overwrites. Plain legacy `putPage` calls keep compatibility until their owning operation adopts the managed write protocol. `projection-schema.ts` (migration 153) invalidates unverified prior projections once and queues durable work; `projections.ts` rebuilds Markdown without a worktree/provider and installs only matching canonical revisions. Embedding installs also compare exact chunk identities/text. Source importers seal code/image projections; all read arms hide unsealed projections.
- `src/core/page-state/projections.ts` — captures canonical revision, source incarnation, page identity, the complete raw chunk inventory and resolved indexing inputs before preparing derived work. Embedding reads require a current text seal; healing/rebuild capture can explicitly include unsealed pages. Projection installation compares its originating seal, chunk identities/text/source/completion state, chunker version and indexing context (including stored corpus generation) under the page guard before replacing any row. A same-revision re-chunk may replace the snapshot it actually captured; a delayed older installation cannot discard newer chunks or vectors. Rebuild also rechecks its queued job before capture so a completed job from an old listing stays completed. Chunkless healing sanitizes complete body/timeline fences before splitting, preserving withdrawn history in direct page reads while excluding it from retrieval. Tests: `page-projection-origin.test.ts`, `page-projection-vector-preservation.test.ts` (PGLite and isolated Postgres), `embed-stale-chunkless-pages.serial.test.ts` (public healing entry). Shared `markdown-chunks.ts` and `code-chunks.ts` preserve fenced code and source-language metadata. Recovery preserves compatible legacy NULL-hash vectors without stamping provenance; non-NULL hash, model, context or chunk-identity drift still invalidates them. It replaces outgoing code edges without deleting incoming edges to retained chunks and clears backfill watermarks. Failed jobs rotate with a retained diagnostic; successful drain refreshes planner statistics.
diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.md
index e2b9b919e1..4dac3a4dcd 100644
--- a/docs/architecture/key-files/files-and-sync-1.md
+++ b/docs/architecture/key-files/files-and-sync-1.md
@@ -11,7 +11,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/content-sanity.ts` — pure assessor for the content-sanity defense. `assessContent(content, opts): SanityVerdict` returns one of `ok | warn_oversize | hard_block_junk_pattern | soft_block_oversize` with `{reason, bytes, matched_pattern_name?}`. Six built-in junk patterns (Cloudflare challenge dumps, CAPTCHAs, 403 dumps, bare error-page titles) compiled at module load; operator literal substrings via `loadOperatorLiterals()` from `src/core/content-sanity-literals.ts`. `ContentSanityBlockError` tagged class is the typed throw shape every wrapper site (`gbrain import`, `put_page` MCP op, `gbrain sync`, `/ingest` webhook) catches via the existing exception flow. The bytes-parity contract pins `Buffer.byteLength(content, 'utf8')` against the embedder's actual byte count so a 499K-byte page can't be soft-blocked on assessment then overflow on embed. Knob resolution chain env > file (`~/.gbrain/config.json`) > DB > defaults. Four knobs: `content_sanity.bytes_warn` (50_000), `content_sanity.bytes_block` (500_000), `content_sanity.junk_patterns_enabled` (true), `content_sanity.disabled` (false; `GBRAIN_NO_SANITY=1` is the loud-stderr kill-switch). `assessContentSanity(opts): SanityAssessment` returns the three-tier disposition (`shouldQuarantine` / `shouldFlag` + reason/detail) consumed by `importFromContent` and `gbrain quarantine scan`; adds the fuzzy prose-vs-markup ratio pass (markup chars / total above `max_markup_ratio`; code pages exempt; gated by `prose_check_enabled`) on top of the byte + junk-pattern passes. Three more knobs: `content_sanity.junk_disposition` (`quarantine` default | `reject`; no env override — a destructive flip belongs in explicit config), `content_sanity.max_markup_ratio` (0.85, env `GBRAIN_MAX_MARKUP_RATIO`, clamped `(0,1]`), `content_sanity.prose_check_enabled` (true). Pinned by `test/content-sanity.test.ts`. Per-pattern opt-out without the kill-switch: `content_sanity.disabled_patterns` names built-in junk patterns to skip (a JSON array `["access_denied"]` or a comma list `access_denied,error_title`; malformed JSON falls back to the comma parse so a hand-typed value still lands) — the file plane takes the array, the DB plane the string.
-- `src/core/data-frontmatter.ts` — shared data-only YAML/JSON parsing and serialization. Rejects unsupported language selectors before parsing, uses js-yaml safe schema with existing scalar types, sanitizes parser errors, and keeps body text opaque. Used by markdown, capture, recipes, plugins, and greenfield ingestion. Independent fixtures: `test/data-frontmatter.test.ts`, `test/frontmatter-security.test.ts`.
+- `src/core/data-frontmatter.ts` — shared data-only YAML/JSON parsing and serialization. Rejects unsupported language selectors before parsing, uses js-yaml safe schema with existing scalar types (a calendar-invalid timestamp such as `2024-02-30` stays a string instead of rolling over to March 1), sanitizes parser errors, and keeps body text opaque. Used by markdown, capture, recipes, plugins, and greenfield ingestion. Independent fixtures: `test/data-frontmatter.test.ts`, `test/frontmatter-security.test.ts`.
- `src/core/default-source-path-check.ts` — pure `assessDefaultSourcePath(input)` verdict for the `default_source_local_path` doctor check (no DB/FS access — caller supplies gathered inputs, the npm-squat-check.ts shape). INVARIANT: `default.local_path: null` is the DESIGNED fallback topology (write-through nests under `sync.repo_path`), NOT an error — the check warns ONLY when the null pointer provably breaks something: the fallback repo is another source's own working tree (the leak-guard collision: every unscoped default write-through silently skipped), or default has file-backed pages and no resolvable root. Everything else (no pages, resolvable fallback, deliberate DB-only brain) is ok. The repair it names is the non-destructive `gbrain sources set-path default <path>`.
@@ -25,7 +25,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/import-checkpoint.ts` — `loadCheckpoint(brainDir)`, `saveCheckpoint(brainDir, completed)`, `resumeFilter(files, completed, brainDir)`, `clearCheckpoint()`, plus the `ImportCheckpoint` type. Path-set format `{schema_version, brainDir, completed: string[]}`. Atomic write via `.tmp` + `rename()` so a mid-write crash never leaves a partial JSON. `loadCheckpoint` returns `null` on: missing file, malformed JSON, brainDir mismatch (ran against a different brain), and the old positional format (logged to stderr before discard). `resumeFilter` returns `{toProcess, skippedCount}` — pure, no I/O, deterministic. `clearCheckpoint` is no-op-on-missing for clean-exit cleanup. Honors `GBRAIN_HOME` via `gbrainPath()` so `withEnv({GBRAIN_HOME: tmpdir})` test isolation works without monkey-patching fs. Best-effort persistence — `saveCheckpoint` logs warnings on write errors but never throws.
-- `src/core/import-file.ts` — importFromFile + importFromContent (chunk + embed + tags). The `beforeCommit` hook runs inside the guarded canonical transaction so a rejected file write rolls back its projections; optional legacy source-path repair uses a savepoint. Deferred importer embedding callbacks capture the committed text projection and indexing context, then install with an UPDATE-only revision/chunk/hash check. Tests: `test/import-publication-guards.test.ts`. Coordinated `prepare` imports resolve and atomically stamp the page/source/global contextual wrapping mode even with `noEmbed:true`; the durable outbox later embeds that revision. The existing paid-synopsis title fallback and mount trust gate remain in force, while embedding signatures only certify completed vectors. `test/persistence-contextual-embedding.test.ts` covers both engines, policy precedence, deferred provider execution, and a competing title replacement. `importFromContent` and `importCodeFile` stamp `pages.embedding_signature` via `setPageEmbeddingSignature(slug, {sourceId, signature: currentEmbeddingSignature()})` when the import actually embedded (not `--no-embed`) so a model/dims swap is detectable as stale; `importCodeFile` only stamps when every chunk was freshly embedded this call (`needsEmbedIndexes.length === chunks.length`), mixed reuse-by-hash pages stay unstamped (`reindex --code --force` / `embed --stale` handle those). `importFromContent`'s tag reconciliation is ADD-ONLY: it only `addTag` (idempotent, ON CONFLICT DO NOTHING). The `tags` table has no provenance column and frontmatter tags are stripped from stored `pages.frontmatter` (markdown.ts:118), so a frontmatter-origin tag can't be distinguished from a DB-enrichment tag (auto-tag / dream synthesize / signal-detector) at re-import — deletion is unsafe (would wipe enrichment under `gbrain reindex --markdown`). Accepted trade-off: removing a tag from frontmatter does not remove it from the DB on next sync (needs a `tag_source` provenance column). Pinned by `test/reindex-preserve-tags.test.ts` + `test/import-file.test.ts`. identity-based dedup pre-check at `:427-490`. Calls `engine.findDuplicatePage?.(sourceId, {hash, frontmatterId})` (optional `?` so test doubles compile). Posture: SKIP when `frontmatter.id` matches (true external duplicate from overlapping ingest roots), WARN-ALWAYS on content_hash collision with different/missing `frontmatter.id` (templates and daily logs may legitimately share text), FAIL CLOSED on lookup error, bypass via `--force-rechunk`. Soft-deleted pages excluded at the engine layer so tombstones don't block legitimate re-imports under new slugs. Pinned by `test/import-dedup-frontmatter-id.test.ts` (11 cases). `importFromContent` is the narrow waist every ingest path passes through (`gbrain import`, `gbrain sync`, `put_page` MCP, `/ingest` webhook). It runs a three-tier content-quality disposition via `assessContentSanity` from `src/core/content-sanity.ts` BEFORE chunking: (1) high-confidence junk (built-in Cloudflare/CAPTCHA interstitial patterns + operator literals) → QUARANTINE (stamps the `quarantine` frontmatter marker, writes ZERO chunks, hides the page from search) OR REJECT (throw → sync-failure) when `content_sanity.junk_disposition` is `reject`; (2) fuzzy markup-heavy (prose-vs-markup ratio above `content_sanity.max_markup_ratio`, warn-tier byte window, code pages exempt) → `content_flag:markup_heavy` marker (page stays fully searchable, marker rides search results + get_page to warn the agent); (3) oversize → `embed_skip` soft-block via `buildEmbedSkipMarker()` PLUS a `content_flag:oversized` marker, AND deletes any pre-existing chunks in the same transaction so search can't surface stale chunks. Gate-owned markers (`quarantine`, `content_flag`) are STRIPPED from untrusted (remote MCP, `ctx.remote !== false`) frontmatter so a write-scoped client can't hide pages or forge the warning channel; markers are excluded from `content_hash` so a flagged page doesn't re-embed every sync. `gbrain import` honors `errors > 0` for non-zero exit. `classifyErrorCode` in `src/core/sync.ts` recognizes the `PAGE_JUNK_PATTERN` code so sync-failures.jsonl grouping bins these. `extractEntityRefs` (canonical; matches both `[Name](../people/slug)` markdown links and Obsidian `[[people/slug|Name]]` wikilinks), `extractPageLinks`, `inferLinkType` heuristics (attended/works_at/invested_in/founded/advises/source/mentions), `parseTimelineEntries`, `isAutoLinkEnabled` config helper. Link candidates match any dir-shaped path (existence-checked at persist). Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts. Pinned by `test/import-file-content-sanity.test.ts`. `importCodeFile` writes `source_path: relativePath` on every code page (the same repo-relative path markdown imports record) so the full-sync reconcile — which only considers `source_path IS NOT NULL` rows — can retire a deleted code file's page; `putPage` COALESCEs the column, so rows imported before this keep NULL until the file changes, `sync --force`, or `gbrain reindex-code --force`.
+- `src/core/import-file.ts` — importFromFile + importFromContent (chunk + embed + tags). The `beforeCommit` hook runs inside the guarded canonical transaction so a rejected file write rolls back its projections; optional legacy source-path repair uses a savepoint. Deferred importer embedding callbacks capture the committed text projection and indexing context, then install with an UPDATE-only revision/chunk/hash check. Tests: `test/import-publication-guards.test.ts`. Coordinated `prepare` imports resolve and atomically stamp the page/source/global contextual wrapping mode even with `noEmbed:true`; the durable outbox later embeds that revision. The existing paid-synopsis title fallback and mount trust gate remain in force, while embedding signatures only certify completed vectors. `test/persistence-contextual-embedding.test.ts` covers both engines, policy precedence, deferred provider execution, and a competing title replacement. `importFromContent` and `importCodeFile` stamp `pages.embedding_signature` via `setPageEmbeddingSignature(slug, {sourceId, signature: currentEmbeddingSignature()})` when the import actually embedded (not `--no-embed`) so a model/dims swap is detectable as stale; `importCodeFile` only stamps when every chunk was freshly embedded this call (`needsEmbedIndexes.length === chunks.length`), mixed reuse-by-hash pages stay unstamped (`reindex --code --force` / `embed --stale` handle those). `importFromContent`'s tag reconciliation is ADD-ONLY: it only `addTag` (idempotent, ON CONFLICT DO NOTHING). The `tags` table has no provenance column and frontmatter tags are stripped from stored `pages.frontmatter` (markdown.ts:118), so a frontmatter-origin tag can't be distinguished from a DB-enrichment tag (auto-tag / dream synthesize / signal-detector) at re-import — deletion is unsafe (would wipe enrichment under `gbrain reindex --markdown`). Accepted trade-off: removing a tag from frontmatter does not remove it from the DB on next sync (needs a `tag_source` provenance column). Pinned by `test/reindex-preserve-tags.test.ts` + `test/import-file.test.ts`. identity decisions live in `src/core/import-identity.ts` (`decideImportIdentity`, `collidingSlugOwner`; pure reads, the importer applies them). The dedup pre-check calls `engine.findDuplicatePage?.(sourceId, {hash, frontmatterId, excludeSlug})` (optional `?` so test doubles compile; the caller's own slug never matches, and a `frontmatter.id` match ranks ahead of a bare hash match). Posture: MOVE when the `frontmatter.id` matches and the other page's recorded `source_path` is gone under this import's root (`sourceRoot`, set by `importFromFile`): `updateSlug` carries the row (page id, links, facts, timeline, plus a rename alias) and the new content imports onto it, so a full sync's delete-reconcile has nothing live to remove; SKIP only when the id AND the content (`content_hash`, or title and body for a row written outside the importer) both match while the recorded file still exists (overlapping ingest roots); IMPORT with a warning when the id matches but content differs (templates, copy-paste; an edit is never frozen by the other page); WARN-ALWAYS on a bare content_hash collision; FAIL CLOSED on lookup error; bypass via `--force-rechunk`. Content-only callers (`put_page`, transcripts) never move a page. Soft-deleted pages excluded at the engine layer so tombstones don't block legitimate re-imports under new slugs. Slug collisions: when another live file (`existing.source_path`, realpath-distinct) already owns the slug, the incoming file is skipped with `skip_reason: 'slug_collision'` and a stderr warning, unless the incoming file is named exactly `<slug>.md` (the file the link extractor reads for that slug), so two spellings never overwrite each other. An embedding failure never blocks the text write: chunks commit with NULL vectors, no embedding signature is stamped, the result carries `embedding_deferred: true`, and the stale sweep embeds them later (a code file whose embed failed is not stamped either). `effective_date` for an undated page falls back to `fallbackCreatedAt` (stored fallback date, else the file's own timestamp via `fileTimes`, else now), never the latest write. Pinned by `test/import-dedup-frontmatter-id.test.ts`, `test/import-identity-move.test.ts`, `test/import-slug-collision.test.ts`, `test/import-embed-outage.test.ts` and `test/effective-date-calendar.test.ts`. `importFromContent` is the narrow waist every ingest path passes through (`gbrain import`, `gbrain sync`, `put_page` MCP, `/ingest` webhook). It runs a three-tier content-quality disposition via `assessContentSanity` from `src/core/content-sanity.ts` BEFORE chunking: (1) high-confidence junk (built-in Cloudflare/CAPTCHA interstitial patterns + operator literals) → QUARANTINE (stamps the `quarantine` frontmatter marker, writes ZERO chunks, hides the page from search) OR REJECT (throw → sync-failure) when `content_sanity.junk_disposition` is `reject`; (2) fuzzy markup-heavy (prose-vs-markup ratio above `content_sanity.max_markup_ratio`, warn-tier byte window, code pages exempt) → `content_flag:markup_heavy` marker (page stays fully searchable, marker rides search results + get_page to warn the agent); (3) oversize → `embed_skip` soft-block via `buildEmbedSkipMarker()` PLUS a `content_flag:oversized` marker, AND deletes any pre-existing chunks in the same transaction so search can't surface stale chunks. Gate-owned markers (`quarantine`, `content_flag`) are STRIPPED from untrusted (remote MCP, `ctx.remote !== false`) frontmatter so a write-scoped client can't hide pages or forge the warning channel; markers are excluded from `content_hash` so a flagged page doesn't re-embed every sync. `gbrain import` honors `errors > 0` for non-zero exit. `classifyErrorCode` in `src/core/sync.ts` recognizes the `PAGE_JUNK_PATTERN` code so sync-failures.jsonl grouping bins these. `extractEntityRefs` (canonical; matches both `[Name](../people/slug)` markdown links and Obsidian `[[people/slug|Name]]` wikilinks), `extractPageLinks`, `inferLinkType` heuristics (attended/works_at/invested_in/founded/advises/source/mentions), `parseTimelineEntries`, `isAutoLinkEnabled` config helper. Link candidates match any dir-shaped path (existence-checked at persist). Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts. Pinned by `test/import-file-content-sanity.test.ts`. `importImageFile` records `source_path` on every image page and skips an unchanged image only when its index is complete for the run: a visual vector when embedding is on, and OCR (`ocr_status: 'done'` in frontmatter, or legacy stored OCR text) when OCR is enabled, so an image first imported under `--no-embed` or an OCR skip is rebuilt on its next import (`test/import-image-retry.test.ts`). `importCodeFile` writes `source_path: relativePath` on every code page (the same repo-relative path markdown imports record) so the full-sync reconcile — which only considers `source_path IS NOT NULL` rows — can retire a deleted code file's page; `putPage` COALESCEs the column, so rows imported before this keep NULL until the file changes, `sync --force`, or `gbrain reindex-code --force`.
- `src/core/link-source-check-repair.ts` — schema-drift self-heal for the `links_link_source_check` CHECK constraint (third instance of the `timeline-dedup-repair.ts` / `pages-upsert-arbiter.ts` class). Migration v114 opened `link_source` from a closed allowlist to the kebab-case gate; the migrator trusts the version ledger, so a brain stamped >= 114 whose live constraint reverted to the pre-v114 allowlist (drifted restore, manual DDL) rejects every kebab provenance write (`atom-provenance`, `concept-provenance`) while the ledger reads current. `LINK_SOURCE_KEBAB_RE` is the ONE exported copy of the regex (a drift-guard test pins it to the literal in migrate.ts v114, `schema.sql`, `pglite-schema.ts`). `checkLinkSourceCheck(engine)` probes `pg_constraint` (`pg_get_constraintdef` + `convalidated`) and classifies the drift as `absent` / `wrong_def` / `not_validated` (read-only; powers the `links_link_source_check` doctor check in `doctor/checks/core-health.ts`, whose severity follows what writes do: only `wrong_def` rejects kebab writes → fail; `absent` / `not_validated` still accept them → warn). `repairLinkSourceCheck(engine)` first COUNTs rows that fail the gate and returns `reason: 'violations'` WITHOUT any DDL when there are any (the prior constraint survives; rows are never touched; a brain with a bad row never pays for a failing ALTER at every engine open), then restores v114's definition mirroring the migration's engine split: Postgres runs DROP + `ADD ... NOT VALID` in one `engine.transaction` (atomic, no scan) and `VALIDATE CONSTRAINT` as a separate `engine.runMigration` outside it (SHARE UPDATE EXCLUSIVE, never a plain ADD's ACCESS EXCLUSIVE + full-table scan), with a `not_validated` drift getting the VALIDATE only; PGLite keeps the one-shot DROP+ADD transaction. A DDL failure re-counts violators (a row written between probe and ALTER) and rethrows when there are none. `LINK_SOURCE_GATE_MIGRATION_VERSION` (114) is the ledger gate `runMigrations` applies before calling it. Pinned by `test/link-source-check-repair.test.ts` (PGLite, incl. a recording-engine assertion that violators trigger no DDL and that a sub-114 ledger never probes) and the DATABASE_URL-gated `test/e2e/link-source-check-repair-postgres.test.ts` (two-phase DDL sequence on real Postgres).
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.md
index 19c2b34977..9d3a871220 100644
--- a/docs/architecture/key-files/graph-and-facts.md
+++ b/docs/architecture/key-files/graph-and-facts.md
@@ -74,7 +74,7 @@ rejection of serve-only flags before a brain opens.
- `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).
+- `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>-%` → fuzzy candidates for multi-token input taken only when `sameEntityName` holds (same name tokens ignoring case, punctuation, order, accents and corporate suffixes), so a near-name such as "Alicia Example" never lands on Alice and a person without a page never lands on a meeting page → deterministic `slugify` holding fallback. Bare-name collisions never use popularity as confidence. `isIdentityEntity(slug, type)` (person/company/fund/organization types or their directories) and `sameEntityName` are shared with `makeResolver`. The phantom-redirect helper keeps the legacy 0.7 trigram rule. 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).
- `src/core/entity-identity.ts` + `src/core/ops/entity-identity.ts` — cross-source entity identity (cross-source federation). THE IDENTITY KEY IS `(source_id, slug)`: the same real-world entity routinely exists as a different page per mounted source, and nothing else in gbrain asserts "these pages are the same entity". The `entity_identities` table (migration v137) records that assertion explicitly — member pages grouped under an opaque `entity_id` handle (`validateEntityId`: slug-flavored, lowercase, max 128 chars), one optional canonical member per group, a page belongs to at most one identity (`UNIQUE (source_id, page_id)`; re-linking MOVES it). Posture is MANUAL-ONLY by design: rows come exclusively from the `entity_identity_link` op — no auto-matching or name-similarity heuristics, because a wrong identity merge silently corrupts retrieval. Three ops: `entity_identity_link` / `entity_identity_unlink` (write, localOnly — merges change what retrieval unions across sources, too sharp for a remote surface) + `entity_identity_list` (read; restricts MEMBER visibility to a federated grant or remote scalar scope, while a trusted local caller sees the full cross-source group — cross-source IS the feature). Retrieval union is OFF by default behind the `entity_identity.union` config key; when on, get_links/get_backlinks merge edges from identity co-members (dedup'd), never widening past the caller's source grant. Same SQL text on both engines (parity by construction); pinned by the entity-identity test + the DATABASE_URL-gated engine-parity suite. Topology context: `docs/architecture/brains-and-sources.md`.
@@ -88,7 +88,7 @@ rejection of serve-only flags before a brain opens.
- `src/core/fence-shared.ts` — shared pipe-table primitives for the `## Takes` (`takes-fence.ts`) and `## Facts` (`facts-fence.ts`) fences: `parseRowCells`, `isSeparatorRow`, `stripStrikethrough`, `parseStringCell`, `escapeFenceCell`. `parseRowCells` is escape-aware: `\|` stays inside its cell and decodes back to a literal `|` (exact inverse of `escapeFenceCell`), while any other backslash passes through verbatim so existing fence text (e.g. Windows paths) is byte-stable across a render → parse cycle. This matters because the fence is canonical and reconcile is wipe-and-reinsert — a pipe inside a cell shifting the column layout would corrupt every row behind it on the next reconcile. Pinned by the escape cases in `test/facts-fence.test.ts` + the full render → parse → reconcile round-trip in `test/e2e/facts-fence-reconcile-postgres.test.ts`.
-- `src/core/link-extraction.ts` — shared library for the graph layer. `extractEntityRefs` (canonical) matches `[Name](../people/slug)` markdown links and Obsidian `[[people/slug|Name]]` wikilinks; `extractPageLinks`, `inferLinkType` heuristics (attended/works_at/invested_in/founded/advises/source/mentions), `parseTimelineEntries`, `isAutoLinkEnabled`. Markdown links, bare-slug prose refs, and slash-shaped wikilinks match ANY dir-shaped path (`ANY_DIR_SEGMENT`), not a directory whitelist — nonexistent targets are dropped by the persist paths' page-existence checks (`resolveCandidateSources`, put_page's allSlugs filter, `addLinksBatch` INNER JOINs) and counted as `skippedMissingTarget` in the extract summaries; the `DIR_PATTERN` whitelist is only the typed fast-path for pass-2b wikilinks (non-whitelisted `[[dir/...]]` get an equivalent direct typed candidate in pass 2c, plus the flag-gated suffix rescue for non-exact matches). Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts. **Opt-in global-basename wikilink resolution** (default off): `WIKILINK_GENERIC_RE` catches bare `[[name]]` wikilinks outside `DIR_PATTERN` (third pass `2c` in `extractEntityRefs`); `EntityRef.needsResolution: true` tags refs from this pass (the ref's `slug` is the wikilink TARGET, `name` the optional display alias). `SlugResolver` gains optional `resolveBasenameMatches(name): Promise<string[]>` (multi-match by design — emits one edge per matching page). The single shared basename matcher is `buildBasenameIndex(slugs)` + `queryBasenameIndex(index, name)` + `normalizeBasename` (keys raw/lower/slugified tail, stable-sorted shorter-first then lexical), used by `makeResolver`, the FS `resolveBasenameMatchesFromSlugs`, AND the doctor check so they cannot drift. `makeResolver(engine, {mode, sourceId})` builds the index lazily via `engine.getAllSlugs({sourceId})` — source-scoped so a bare `[[name]]` never resolves to a same-tail page in a different source. `extractPageLinks` gains `opts.globalBasename` (routes `needsResolution` refs through `resolveBasenameMatches` keyed on `ref.slug`, emits candidates tagged `linkType: 'wikilink_basename'` + `linkSource: 'wikilink-resolved'`, skips self-loops) and `opts.skipFrontmatter`. All three surfaces (FS extract, DB extract, `put_page` auto-link) tag provenance with `link_source='wikilink-resolved'`; `put_page` includes it in its reconcilable-edge set so stale basename edges are removed when the wikilink or the flag goes away. Exports `WIKILINK_BASENAME_LINK_TYPE` + `isGlobalBasenameEnabled(engine)` (resolution order: env `GBRAIN_LINK_RESOLUTION_GLOBAL_BASENAME` → DB config `link_resolution.global_basename` → default false). `gbrain doctor`'s `link_resolution_opportunity` check surfaces a paste-ready enable hint when ≥5 bare wikilinks would resolve AND ≥20% match. Migration v113 widens `links_link_source_check` to admit `'wikilink-resolved'`; v114 then opens it to any kebab-case provenance (`^[a-z][a-z0-9]*(-[a-z0-9]+)*$`, ≤64 chars) so external derivers register their own tag (e.g. `citation-graph`) without a migration. `LINK_EXTRACTOR_VERSION_TS` also lives here (bump like `CHUNKER_VERSION` to invalidate prior extract-stale stamps). Pinned by `test/link-extraction.test.ts`, `test/extract-fs.test.ts`, `test/doctor.test.ts`, `test/e2e/global-basename-pglite.test.ts`.
+- `src/core/link-extraction.ts` — shared library for the graph layer. `extractEntityRefs` (canonical) matches `[Name](../people/slug)` markdown links and Obsidian `[[people/slug|Name]]` wikilinks; `extractPageLinks`, `inferLinkType` heuristics (attended/works_at/invested_in/founded/advises/source/mentions), `parseTimelineEntries`, `isAutoLinkEnabled`. Markdown links, bare-slug prose refs, and slash-shaped wikilinks match ANY dir-shaped path (`ANY_DIR_SEGMENT`), not a directory whitelist — nonexistent targets are dropped by the persist paths' page-existence checks (`resolveCandidateSources`, put_page's allSlugs filter, `addLinksBatch` INNER JOINs) and counted as `skippedMissingTarget` in the extract summaries; the `DIR_PATTERN` whitelist is only the typed fast-path for pass-2b wikilinks (non-whitelisted `[[dir/...]]` get an equivalent direct typed candidate in pass 2c, plus the flag-gated suffix rescue for non-exact matches). Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts. **Opt-in global-basename wikilink resolution** (default off): `WIKILINK_GENERIC_RE` catches bare `[[name]]` wikilinks outside `DIR_PATTERN` (third pass `2c` in `extractEntityRefs`); `EntityRef.needsResolution: true` tags refs from this pass (the ref's `slug` is the wikilink TARGET, `name` the optional display alias). `SlugResolver` gains optional `resolveBasenameMatches(name): Promise<string[]>` (multi-match by design — emits one edge per matching page). The single shared basename matcher is `buildBasenameIndex(slugs)` + `queryBasenameIndex(index, name)` + `normalizeBasename` (keys raw/lower/slugified tail, stable-sorted shorter-first then lexical), used by `makeResolver`, the FS `resolveBasenameMatchesFromSlugs`, AND the doctor check so they cannot drift. `makeResolver` step 1 falls back to `resolveSlugWithAlias` (rename aliases) for a slug-shaped value with no live page; its fuzzy title step and live keyword step (source-scoped) accept a person/company/fund/organization candidate only under `sameEntityName`, so a near-name stays unresolved instead of linking to a different entity (`test/entity-resolution-near-names.test.ts`). `makeResolver(engine, {mode, sourceId})` builds the index lazily via `engine.getAllSlugs({sourceId})` — source-scoped so a bare `[[name]]` never resolves to a same-tail page in a different source. `extractPageLinks` gains `opts.globalBasename` (routes `needsResolution` refs through `resolveBasenameMatches` keyed on `ref.slug`, emits candidates tagged `linkType: 'wikilink_basename'` + `linkSource: 'wikilink-resolved'`, skips self-loops) and `opts.skipFrontmatter`. All three surfaces (FS extract, DB extract, `put_page` auto-link) tag provenance with `link_source='wikilink-resolved'`; `put_page` includes it in its reconcilable-edge set so stale basename edges are removed when the wikilink or the flag goes away. Exports `WIKILINK_BASENAME_LINK_TYPE` + `isGlobalBasenameEnabled(engine)` (resolution order: env `GBRAIN_LINK_RESOLUTION_GLOBAL_BASENAME` → DB config `link_resolution.global_basename` → default false). `gbrain doctor`'s `link_resolution_opportunity` check surfaces a paste-ready enable hint when ≥5 bare wikilinks would resolve AND ≥20% match. Migration v113 widens `links_link_source_check` to admit `'wikilink-resolved'`; v114 then opens it to any kebab-case provenance (`^[a-z][a-z0-9]*(-[a-z0-9]+)*$`, ≤64 chars) so external derivers register their own tag (e.g. `citation-graph`) without a migration. `LINK_EXTRACTOR_VERSION_TS` also lives here (bump like `CHUNKER_VERSION` to invalidate prior extract-stale stamps). Pinned by `test/link-extraction.test.ts`, `test/extract-fs.test.ts`, `test/doctor.test.ts`, `test/e2e/global-basename-pglite.test.ts`.
- `src/core/timeline-dedup-repair.ts` — schema-drift self-heal for `idx_timeline_dedup`. A master-merge migration renumbering can leave a brain's version counter stamped past the index change while the index keeps an old shape — and every `addTimelineEntry` batch then fails its `ON CONFLICT` inference, silently breaking timeline writes brain-wide. The version counter can't detect this, so the repair is keyed off the actual index SHAPE. Canonical shape is `(page_id, date, md5(summary), source)` — md5-keyed (migration v138) because a raw long/incompressible summary would overflow the btree v4 row cap (~2704 bytes) and abort every timeline insert for that page; both engines' insert sites infer `ON CONFLICT` on the md5 tuple, so `EXPECTED_COLUMNS` MUST carry the md5 form (a raw-shape expectation would make the repair revert v138 on every migrate pass). `checkTimelineDedupIndex(engine)` returns `{tablePresent, indexPresent, columns, needsRepair}` (read-only; powers the `timeline_dedup_index` doctor check; the indexdef column parser is paren-depth-aware so `md5(summary)` — or any future expression column — parses as ONE column instead of flagging a correct index as drifted forever) and `repairTimelineDedupIndex(engine)` dedupes-then-rebuilds to the canonical shape (raw-summary grouping ⟺ md5 grouping modulo negligible collisions). `runMigrations` invokes the repair on every pass (including the no-pending early-return path); idempotent no-op when the index already matches. `gbrain apply-migrations --force-schema` triggers it on demand. Pinned by `test/timeline-dedup-repair.test.ts`.
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 834d2c44c6..0c3645c2bd 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -1,7 +1,7 @@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.59.10.0",
+ "version": "0.59.11.0",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"kind": "context-engine",
diff --git a/package.json b/package.json
index d0b5c23938..5d153ab2ed 100644
--- a/package.json
+++ b/package.json
@@ -190,7 +190,7 @@
"bun": ">=1.3.11"
},
"license": "MIT",
- "version": "0.59.10.0",
+ "version": "0.59.11.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.json
index 5241cddb34..2d14389cf6 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.59.10.0",
+ "version": "0.59.11.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.json
index 904ec6d231..9f0a053a4d 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.59.10.0",
+ "version": "0.59.11.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.md
index 67021813fe..5662f026c4 100644
--- a/plugin-variants/gbrain-coding/README.md
+++ b/plugin-variants/gbrain-coding/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.59.10.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.59.11.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.json
index d62a794632..4f144e1d06 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.59.10.0",
+ "version": "0.59.11.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.json
index eb0436b1c7..78a5f87df8 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.59.10.0",
+ "version": "0.59.11.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.md
index 27f05f8c4a..ebd759de46 100644
--- a/plugin-variants/gbrain-daily/README.md
+++ b/plugin-variants/gbrain-daily/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.59.10.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.59.11.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.md
index 59bf10424b..14ca9883c3 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.59.10.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.59.11.0 -->
# gbrain plugin skill tree (generated — do not hand-edit)
This tree is the curated skill set for the gbrain Codex and Claude Code
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 0058c9daa3..d29eef1380 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -8,7 +8,7 @@ src/commands/autopilot.ts 2725 ratchet grown v0.46.26.0 megawave (#4300 #4285 #3
src/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 integration
src/commands/embed.ts 2169 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; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures
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 2571 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 revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain
+src/commands/extract.ts 2578 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 revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution
src/commands/jobs.ts 3260 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 integration; +1 #5584: skillopt job reflect_max_tokens (validated + clamped via skillopt/output-cap.ts); lowered #5585: skillopt handler body peeled to skillopt/job.ts (execution-time model re-resolution + strict re-check); typed readiness, configuration-blocked lifecycle and bounded release (issue #5560 merge)
src/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 checks
src/core/ai/gateway.ts 4441 ratchet +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings
@@ -16,14 +16,14 @@ src/commands/sync.ts 5995 ratchet +1 #4786/#3068 pre-landing: pullFailed early r
src/core/cycle.ts 3207 ratchet grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false
src/core/cycle/synthesize.ts 3218 ratchet merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates
src/core/cycle/extract-atoms.ts 1752 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration
-src/core/engine.ts 2660 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract
-src/core/import-file.ts 2207 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication
+src/core/engine.ts 2665 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract
+src/core/import-file.ts 2236 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor
src/core/migrate.ts 722 region-exempt append-only MIGRATIONS array grows freely; runner logic is ratcheted — grown v0.46.26.0: repair-handler hooks (#3957 pages-upsert-arbiter); wave-k v142 takes-embedding resize is in-region (renumbered from v141; master consumed v141 for #4482); master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: projection migration helper; #5105: lease schema helper; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +1 import for focused topology migration module; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: static projection statistics import; DDL remains region-exempt; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion
src/core/operations.ts 329 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base
-src/core/pglite-engine.ts 6127 ratchet +6 #4881: ontology provenance-page visibility gate (getOntology/findOntologyConflicts); grown v0.46.26.0 megawave parity twins + master v0.46.26.0 private-queue columns; +#3754 traverseGraph soft-delete filters; grown wave-g (#4524 #4527): canonical islanded orphans + timestamp-preserving migrate; wave-k: +1 semantic takes retrieval delegate (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +7 getAllConfig bulk read (#3980); +22: pre-close WAL CHECKPOINT in disconnect (#3893); +10: #4109 atomic link/timeline mutation + typed per-endpoint miss (parity); +1: getBacklinkCounts page-id keying comment (#4380); +14: dream-verdict TTL expiry predicate + sweep (#4069); +7 test-gap-wave merge true-up; +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +51: #4592 source-scoped getStats/getHealth (bound $1 scope, both-endpoint link rule); +5 file-bytes snapshot hash (coverage-immune — CI shards were silently cold-initting); +7 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); cold-initting); +11: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +2: #4681 listPages projects updated_at_iso (microsecond keyset cursor); master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: grant and authority schema bootstrap parity; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; upstream integration: preserve independently reviewed master additions with branch facade extraction; +1 v0.50.5.0 security merge (upstream delta; coordinated facade retained); +7 ceiling: bounded in-memory create retry with attached-database exclusion and second-failure diagnostics; #5252 bounded candidate recovery and statistics snapshot dependency; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared-skills integration on company-ingestion base; shared skills: include explicit access DDL in snapshot invalidation; archived eligibility: source-locked drift and raw signature mutations
+src/core/pglite-engine.ts 6133 ratchet +6 #4881: ontology provenance-page visibility gate (getOntology/findOntologyConflicts); grown v0.46.26.0 megawave parity twins + master v0.46.26.0 private-queue columns; +#3754 traverseGraph soft-delete filters; grown wave-g (#4524 #4527): canonical islanded orphans + timestamp-preserving migrate; wave-k: +1 semantic takes retrieval delegate (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +7 getAllConfig bulk read (#3980); +22: pre-close WAL CHECKPOINT in disconnect (#3893); +10: #4109 atomic link/timeline mutation + typed per-endpoint miss (parity); +1: getBacklinkCounts page-id keying comment (#4380); +14: dream-verdict TTL expiry predicate + sweep (#4069); +7 test-gap-wave merge true-up; +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +51: #4592 source-scoped getStats/getHealth (bound $1 scope, both-endpoint link rule); +5 file-bytes snapshot hash (coverage-immune — CI shards were silently cold-initting); +7 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); cold-initting); +11: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +2: #4681 listPages projects updated_at_iso (microsecond keyset cursor); master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: grant and authority schema bootstrap parity; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; upstream integration: preserve independently reviewed master additions with branch facade extraction; +1 v0.50.5.0 security merge (upstream delta; coordinated facade retained); +7 ceiling: bounded in-memory create retry with attached-database exclusion and second-failure diagnostics; #5252 bounded candidate recovery and statistics snapshot dependency; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared-skills integration on company-ingestion base; shared skills: include explicit access DDL in snapshot invalidation; archived eligibility: source-locked drift and raw signature mutations; +6 write-path wave: updateSlug records its rename alias in one transaction
src/core/postgres-engine.ts 5577 ratchet +6 #4881: ontology provenance-page visibility gate (parity twin); lowered wave-g: #4477 bootstrap peel to src/core/postgres-engine/ modules (ratchet holds the win); +2 on wave-g-prs merge true-up; wave-k: +2 semantic takes retrieval (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +11 getAllConfig bulk read (#3980); +13: #4109 atomic FOR KEY SHARE link/timeline mutation + typed per-endpoint miss; +2: getBacklinkCounts page-id keying comment (#4380); +12: dream-verdict TTL expiry predicate + sweep (#4069); +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +61: #4592 source-scoped getStats/getHealth (scope predicate, both-endpoint link rule); +11 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); rule); +12: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata, parity twin); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +3: #4681 listPages projects updated_at_iso (microsecond keyset cursor, parity twin); #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop barrier and direct transaction route; upstream integration: preserve independently reviewed master additions with branch facade extraction; +1 v0.50.5.0 security merge (upstream delta; coordinated facade retained)
src/core/search/hybrid.ts 3215 ratchet +2: preserve local query-deadline classification through gateway error wrapping; grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; grown db-availability loop: all-lexical-arms-dead access-error rethrow (a dead DB must never return an empty success) — refined to both-arms-FAILED (a succeeded-but-empty arm proves the DB is alive); grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; +2: backlink-boost counts page-id keying doc (#4380); +59 2026-09 adversarial batch 2: both-mode text-only demotion gate (textVectorArmNonEmpty) + relaxed_dropped meta + keyword_relaxed_carried degraded stamp + intent-skew caveat docs; +35 #3617 follow-up: relaxed-row fusion demotion (vectorArmNonEmpty gate + keywordFusionList/titleFusionList) with the LongMemEval 51.3%-vs-93.8% receipt comment; +24 2026-08 eval fix wave (E5b/D8): adaptive-return knobs-hash v27 fold (resolved gate + intent class threaded to the cache key), adaptive-on skipCache removal, dedupOpts cache-skip honesty, explicit-maxPerPage min() precedence under walk widening; (#4380); +20 wave #4256: compiledTruthBoost helper — synthetic chunkless title rows (chunk_id 0 + empty chunk_text) never gain the 2x compiled-truth boost (#3695); composition true-up (fix-wave multi-train) | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: read-policy propagation and semantic result-cache containment; ranker wave v0.48.4.0: role-tagged fusion arms, relational rerank pin, metadata boost gate, per-call knob seams, onRerankPool hook (+150) merged over master's read-policy plumbing (+31); +11 #4359 (#4972): thread the loaded search-mode config snapshot from hybridSearchCached into the inner hybridSearch call (INTERNAL _searchModeInput opt) so both resolve from the same one DB-plane config read instead of two independent ones — closes the cache-key/result desync window and removes the second config-table round trip on every hybridSearchCached call; #5252 wave: inclusive date bounds and public vector incompleteness; shared date-bounds peel retains exports; merged company ingestion/schema routing changes; retired provider integration removed
-src/core/types.ts 2072 ratchet +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed
+src/core/types.ts 2073 ratchet +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source
src/core/minions/queue.ts 2513 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release
src/commands/init.ts 1932 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init
src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)
@@ -31,7 +31,7 @@ src/core/minions/handlers/subagent.ts 1918 ratchet merged: master v131 settle re
src/commands/bootstrap.ts 2115 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics
src/core/minions/worker.ts 1764 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry
src/commands/sources.ts 1993 ratchet grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts
-src/core/link-extraction.ts 2082 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges
+src/core/link-extraction.ts 2099 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver
src/core/embedding-migration.ts 1513 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation
src/core/github-source.ts 1576 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper
src/commands/hook.ts 1881 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking
diff --git a/src/commands/extract.ts b/src/commands/extract.ts
index 4c5e469741..b07932216f 100644
--- a/src/commands/extract.ts
+++ b/src/commands/extract.ts
@@ -43,9 +43,10 @@ import { setCliExitVerdict } from '../core/cli-force-exit.ts';
import { ATTENDANCE_REPAIR_HELP, isAttendanceRepairRequest } from './extract-attendance-repair.ts';
import { join, relative, dirname } from 'path';
import type { BrainEngine, LinkBatchInput, TimelineBatchInput } from '../core/engine.ts';
+import { isUndefinedTableError } from '../core/utils.ts';
import type { PageType } from '../core/types.ts';
import { parseMarkdown } from '../core/markdown.ts';
-import { resolveCandidateSources, resolveLinkFallbackDefault, loadLinkPageMetadata, capturedLinkEndpoints, fileLinkOwnership, replaceFileLinks, type LinkPageMetadata } from '../core/link-reconciliation.ts';
+import { resolveCandidateSources, resolveLinkFallbackDefault, loadLinkPageMetadata, capturedLinkEndpoints, fileLinkOwnership, replaceFileLinks, replacePageFileLinks, type LinkPageMetadata } from '../core/link-reconciliation.ts';
export { reconcileSourceLinks, type SourceLinkReconciliationResult } from '../core/link-reconciliation.ts';
export { extractMarkdownLinks } from '../core/link-extraction.ts';
import {
@@ -63,7 +64,7 @@ import { resolveIncludeFrontmatter } from '../core/extract-frontmatter.ts';
import { inferLinkTypeFromPack } from '../core/schema-pack/link-inference.ts';
import { PageRegexBudget } from '../core/schema-pack/redos-guard.ts';
export { extractTimelineFromContent, type ExtractedTimelineEntry } from '../core/timeline-extract.ts';
-import { extractTimelineFromContent, type ExtractedTimelineEntry } from '../core/timeline-extract.ts';
+import { extractTimelineFromContent, retractRemovedTimelineEntries, type ExtractedTimelineEntry } from '../core/timeline-extract.ts';
import { createProgress } from '../core/progress.ts';
import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';
import { pathToSlug, slugifyPath, slugifySegment, pruneDir, isSyncable } from '../core/sync.ts';
@@ -467,12 +468,34 @@ function loadFsPageTypes(files: ReadonlyArray<{ path: string; relPath: string }>
return types;
}
+/**
+ * Old slugs of renamed pages (slug_aliases), mapped to their current slug when
+ * that slug has a file in this walk. The old slugs join `allSlugs` so a link
+ * written before the rename still resolves; a slug that is itself a live file
+ * never becomes an alias.
+ */
+async function loadSlugAliasTargets(engine: BrainEngine, sourceId: string, allSlugs: Set<string>): Promise<Map<string, string>> {
+ let rows: Array<{ alias_slug: string; canonical_slug: string }> = [];
+ try {
+ rows = await engine.executeRaw('SELECT alias_slug, canonical_slug FROM slug_aliases WHERE source_id = $1', [sourceId]);
+ } catch (error) {
+ if (!isUndefinedTableError(error)) throw error;
+ }
+ const aliases = new Map(rows.filter(row => !allSlugs.has(row.alias_slug) && allSlugs.has(row.canonical_slug))
+ .map(row => [row.alias_slug, row.canonical_slug]));
+ for (const alias of aliases.keys()) allSlugs.add(alias);
+ return aliases;
+}
+
export async function extractLinksFromFile(
content: string, relPath: string, allSlugs: Set<string>,
opts?: { includeFrontmatter?: boolean; globalBasename?: boolean; pack?: LinkExtractionPack | null;
- pageTypes?: ReadonlyMap<string, string> },
+ pageTypes?: ReadonlyMap<string, string>; aliases?: ReadonlyMap<string, string> },
): Promise<ExtractedLink[]> {
const links: ExtractedLink[] = [];
+ // Renamed pages: `allSlugs` also holds their old slugs (see
+ // loadSlugAliasTargets), which resolve here to the page's current slug.
+ const canonical = (target: string) => opts?.aliases?.get(target) ?? target;
const slug = pathToSlug(relPath);
const fileDir = dirname(relPath);
// Issue #972: globalBasename routes bare `[[name]]` wikilinks through
@@ -503,7 +526,8 @@ export async function extractLinksFromFile(
const isBasename = resolvedSlugs.length > 1
|| (globalBasename && resolvedSlugs.length === 1
&& resolveSlug(fileDir, relTarget, allSlugs) === null);
- for (const target of resolvedSlugs) {
+ for (const resolved of resolvedSlugs) {
+ const target = canonical(resolved);
// Issue #972 (codex [P2]): drop a basename self-loop ([[own-tail]] on
// its own page resolving back to itself).
if (isBasename && target === slug) continue;
@@ -565,7 +589,7 @@ export async function extractLinksFromFile(
// digit-leading folders (`90-people/nicolai`) and nested paths.
// Exact Set membership guards it — no false positives.
if (/\//.test(trimmed) && /^[a-z0-9][a-z0-9/_-]*$/.test(trimmed) && allSlugs.has(trimmed)) {
- return trimmed;
+ return canonical(trimmed);
}
const hints = Array.isArray(dirHint) ? dirHint : (dirHint ? [dirHint] : []);
// Both slug grammars, as in makeResolver step 2 (#4855): the folded
@@ -575,7 +599,7 @@ export async function extractLinksFromFile(
if (!hint) continue;
for (const form of forms) {
const candidate = `${hint}/${form}`;
- if (allSlugs.has(candidate)) return candidate;
+ if (allSlugs.has(candidate)) return canonical(candidate);
}
}
return null;
@@ -1259,32 +1283,24 @@ async function extractForSlugs(
if (doLinks && !pack) throw new Error('Cannot extract links: active schema pack is unavailable.');
const pageTypes = loadFsPageTypes(allFiles, pack);
const ownership = !dryRun && doLinks ? await fileLinkOwnership(engine, sourceId ?? 'default') : undefined;
+ const aliases = doLinks ? await loadSlugAliasTargets(engine, sourceId ?? 'default', allSlugs) : undefined;
- const linkBatch: LinkBatchInput[] = [];
const timelineBatch: TimelineBatchInput[] = [];
- async function flushLinks() {
- if (linkBatch.length === 0) return;
- // Snapshot BEFORE clear so a producer pushing during the 500ms retry
- // delay can't lose items on the second attempt. Error messages read
- // snapshot.length (batch.length is 0 by the time the catch fires).
- const snapshot = linkBatch.slice();
- linkBatch.length = 0;
+ // A page's links are replaced in one transaction. A failed replacement keeps
+ // the batch-loss contract of the timeline flush below (stderr, never stdout)
+ // and leaves the page unprocessed, so it stays stale for the next sweep.
+ async function replaceLinksReportingLoss(slug: string, links: LinkBatchInput[], owner: NonNullable<typeof ownership>): Promise<number> {
try {
- // v0.41.18.0: engine self-retries on Supavisor blip. auditSite routes
- // the audit JSONL emission. Per-snapshot try/catch preserves the
- // log-and-continue contract for exhausted retries.
- linksCreated += await engine.addLinksBatch(snapshot, { auditSite: 'extract.links_inc' }); // gbrain-allow-direct-insert: gbrain extract command — canonical link reconciliation from markdown body
+ return await replacePageFileLinks(engine, slug, sourceId ?? 'default', links, includeFrontmatter, owner) ?? 0;
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
- // Same two-channel contract as the fs-walk siblings: the cycle runs this
- // path with jsonMode (stdout belongs to the dream --json report), and a
- // flush that drops rows must still surface on stderr.
if (jsonMode) {
- process.stderr.write(JSON.stringify({ event: 'batch_error', size: snapshot.length, error: msg }) + '\n');
+ process.stderr.write(JSON.stringify({ event: 'batch_error', size: links.length, error: msg }) + '\n');
} else {
- console.error(` link batch error (${snapshot.length} rows lost): ${msg}`);
+ console.error(` link replacement error for ${slug} (${links.length} rows not written): ${msg}`);
}
+ throw e;
}
}
@@ -1304,21 +1320,20 @@ async function extractForSlugs(
}
}
- // v0.41.15.0 (T7): sliding-pool fan-out. The shared linkBatch /
- // timelineBatch arrays + flush functions still serve correctly because
- // every push + length check + length=0 reset is synchronous JS — no
- // await between the check and the reset means workers never see a
- // half-cleared batch. flushLinks/flushTimeline snapshot before await,
- // so the second worker's pushes during the await land cleanly in the
- // (now-empty) batch for the next flush.
+ // v0.41.15.0 (T7): sliding-pool fan-out. Links are replaced per page; the
+ // shared timelineBatch array + flush still serve correctly because every
+ // push + length check + length=0 reset is synchronous JS — no await between
+ // the check and the reset means workers never see a half-cleared batch.
+ // flushTimeline snapshots before await, so the second worker's pushes
+ // during the await land cleanly in the (now-empty) batch for the next flush.
await runSlidingPool({
items: slugs,
workers,
signal,
failureLabel: (slug) => slug,
onItem: async (slug) => {
- // #1972: bail before doing any work for this slug on abort. Trailing
- // flushLinks/flushTimeline still commit accumulated rows — no torn write.
+ // #1972: bail before doing any work for this slug on abort. The trailing
+ // flushTimeline still commits accumulated rows — no torn write.
if (isAborted(signal)) return;
const relPath = resolveSlugRelPath(slugToPath, brainDir, slug);
if (relPath === undefined) return; // deleted file — sync already handled removal
@@ -1329,30 +1344,26 @@ async function extractForSlugs(
const content = readFileSync(fullPath, 'utf-8');
if (doLinks) {
- const links = await extractLinksFromFile(content, relPath, allSlugs, { globalBasename, includeFrontmatter, pack, pageTypes });
- let reconciled = false;
- if (ownership && (snapshot?.page.type === 'meeting' || ownership.origins.has(slug) || links.some(link => link.link_type === 'attended' && link.origin_slug === slug && link.to_slug === slug))) {
- if (!snapshot) throw new Error('Link extraction origin is missing');
- const written = await replaceFileLinks(engine, slug, sourceId ?? 'default', links, includeFrontmatter, snapshot, ownership, content, { pack, globalBasename });
- if (written === null) return;
- reconciled = written !== undefined;
- linksCreated += written ?? 0;
- }
- if (!reconciled) for (const link of links) {
- if (dryRun) {
+ const links = await extractLinksFromFile(content, relPath, allSlugs, { globalBasename, includeFrontmatter, pack, pageTypes, aliases });
+ if (dryRun) {
+ for (const link of links) {
if (!stdoutQuiet) console.log(` ${link.from_slug} → ${link.to_slug} (${link.link_type})`);
linksCreated++;
- } else {
- linkBatch.push(sourceId
- ? { ...link, from_source_id: sourceId, to_source_id: sourceId, origin_source_id: sourceId }
- : link);
- if (linkBatch.length >= BATCH_SIZE) await flushLinks();
}
+ } else if (ownership) {
+ let written: number | null | undefined;
+ if (snapshot?.page.type === 'meeting' || ownership.origins.has(slug) || links.some(link => link.link_type === 'attended' && link.origin_slug === slug && link.to_slug === slug)) {
+ if (!snapshot) throw new Error('Link extraction origin is missing');
+ written = await replaceFileLinks(engine, slug, sourceId ?? 'default', links, includeFrontmatter, snapshot, ownership, content, { pack, globalBasename });
+ if (written === null) return;
+ }
+ linksCreated += written ?? await replaceLinksReportingLoss(slug, links, ownership);
}
}
if (doTimeline) {
const entries = extractTimelineFromContent(content, slug);
+ if (!dryRun) await retractRemovedTimelineEntries(engine, slug, sourceId ?? 'default', entries);
for (const entry of entries) {
if (dryRun) {
if (!stdoutQuiet) console.log(` ${entry.slug}: ${entry.date} — ${entry.summary}`);
@@ -1371,7 +1382,6 @@ async function extractForSlugs(
},
});
- await flushLinks();
await flushTimeline();
// #2636: the Dream cycle disables sync's inline extraction and routes
// changed slugs through this incremental path — without a stamp here,
@@ -1616,13 +1626,9 @@ export async function extractLinksForSlugs(
// back for it and the edges were lost for good.
const slugToPath = buildSlugPathIndex(allFiles);
const allSlugs = new Set(slugToPath.keys());
- // v0.18.0+ multi-source: post-sync extract reconciles same-source edges.
- // Markdown→markdown links within one repo always live in the caller's
- // sourceId. Cross-source extraction (rare) would need a per-repo source
- // manifest; not in this PR's scope.
- const linkOpts = opts?.sourceId
- ? { fromSourceId: opts.sourceId, toSourceId: opts.sourceId, originSourceId: opts.sourceId }
- : undefined;
+ // Post-sync extract replaces each page's own markdown-derived edges in the
+ // caller's source (the put_page contract); cross-source extraction would
+ // need a per-repo source manifest.
// Issue #972: same flag as the standalone extract path.
const globalBasename = await isGlobalBasenameEnabled(engine);
// #3190: pack-aware typing on the sync inline hook too.
@@ -1631,6 +1637,7 @@ export async function extractLinksForSlugs(
if (!pack) throw new Error('Cannot extract links: active schema pack is unavailable.');
const pageTypes = loadFsPageTypes(allFiles, pack);
const ownership = await fileLinkOwnership(engine, sourceId);
+ const aliases = await loadSlugAliasTargets(engine, sourceId, allSlugs);
// #4999: resolved HERE, like isGlobalBasenameEnabled above, so every caller
// (sync, GitHub/Google source inline extracts) honours the configured
// frontmatter knob without per-caller threading — an unattended sync used to
@@ -1650,18 +1657,14 @@ export async function extractLinksForSlugs(
const snapshot = ownership.metadata.get(`${sourceId}\0${slug}`)?.type === 'meeting' || ownership.origins.has(slug)
? await engine.readPageSnapshot(slug, { sourceId }) : null;
const content = readFileSync(filePath, 'utf-8');
- const links = await extractLinksFromFile(content, relPath, allSlugs, { globalBasename, includeFrontmatter, pack, pageTypes });
- let reconciled = false;
+ const links = await extractLinksFromFile(content, relPath, allSlugs, { globalBasename, includeFrontmatter, pack, pageTypes, aliases });
+ let written: number | null | undefined;
if (snapshot?.page.type === 'meeting' || ownership.origins.has(slug) || links.some(link => link.link_type === 'attended' && link.origin_slug === slug && link.to_slug === slug)) {
if (!snapshot) throw new Error('Link extraction origin is missing');
- const written = await replaceFileLinks(engine, slug, sourceId, links, includeFrontmatter, snapshot, ownership, content, { pack, globalBasename });
+ written = await replaceFileLinks(engine, slug, sourceId, links, includeFrontmatter, snapshot, ownership, content, { pack, globalBasename });
if (written === null) continue;
- reconciled = written !== undefined;
- created += written ?? 0;
- }
- if (!reconciled) for (const link of links) {
- try { await engine.addLink(link.from_slug, link.to_slug, link.context, link.link_type, link.link_source, link.origin_slug, link.origin_field, linkOpts); created++; } catch {} // gbrain-allow-direct-insert: gbrain extract single-row fallback when batch path declines a row
}
+ created += written ?? await replacePageFileLinks(engine, slug, sourceId, links, includeFrontmatter, ownership) ?? 0;
processed.push(slug);
} catch { /* skip: unreadable — not processed, stays stale */ }
}
@@ -1690,8 +1693,10 @@ export async function extractTimelineForSlugs(
const filePath = join(repoPath, relPath);
try {
const content = readFileSync(filePath, 'utf-8');
+ const entries = extractTimelineFromContent(content, slug);
+ await retractRemovedTimelineEntries(engine, slug, opts?.sourceId ?? 'default', entries);
processed.push(slug);
- for (const entry of extractTimelineFromContent(content, slug)) {
+ for (const entry of entries) {
try { await engine.addTimelineEntry(entry.slug, { date: entry.date, source: entry.source, summary: entry.summary, detail: entry.detail }, entryOpts); created++; } catch { /* skip */ } // gbrain-allow-direct-insert: gbrain extract single-row fallback for timeline entries
}
} catch { /* skip: unreadable — not processed, stays stale */ }
diff --git a/src/core/backfill-effective-date.ts b/src/core/backfill-effective-date.ts
index e27fa6495f..b25676cf22 100644
--- a/src/core/backfill-effective-date.ts
+++ b/src/core/backfill-effective-date.ts
@@ -26,7 +26,7 @@
*/
import type { BrainEngine } from './engine.ts';
-import { computeEffectiveDate } from './effective-date.ts';
+import { computeEffectiveDate, fallbackCreatedAt } from './effective-date.ts';
import type { EffectiveDateSource } from './types.ts';
const BATCH_SIZE = 1000;
@@ -198,7 +198,7 @@ export async function backfillEffectiveDate(
frontmatter: fm,
filename,
updatedAt: new Date(r.updated_at),
- createdAt: new Date(r.created_at),
+ createdAt: fallbackCreatedAt({ existing: r, now: new Date(r.created_at) }),
});
// No-op-on-equal: skip the UPDATE if existing matches (saves write
@@ -229,7 +229,7 @@ export async function backfillEffectiveDate(
frontmatter: fm,
filename,
updatedAt: new Date(r.updated_at),
- createdAt: new Date(r.created_at),
+ createdAt: fallbackCreatedAt({ existing: r, now: new Date(r.created_at) }),
});
const existingMs = r.effective_date ? new Date(r.effective_date).getTime() : null;
const computedMs = computed.date ? computed.date.getTime() : null;
diff --git a/src/core/data-frontmatter.ts b/src/core/data-frontmatter.ts
index f4d9001091..db3717890f 100644
--- a/src/core/data-frontmatter.ts
+++ b/src/core/data-frontmatter.ts
@@ -1,4 +1,25 @@
-import { safeLoad, safeDump } from 'js-yaml';
+import { safeLoad, safeDump, Schema, Type, DEFAULT_SAFE_SCHEMA } from 'js-yaml';
+
+// js-yaml's timestamp type builds `2024-02-30` as March 1 (Date.UTC rolls the
+// day over). A calendar-invalid timestamp stays the string the author wrote,
+// so date consumers reject it instead of storing the wrong day.
+type TimestampBehavior = { resolve(data: string): boolean; construct(data: string): Date; represent(data: object): string };
+const baseTimestamp = (DEFAULT_SAFE_SCHEMA as unknown as { compiledTypeMap: { scalar: Record<string, TimestampBehavior> } })
+ .compiledTypeMap.scalar['tag:yaml.org,2002:timestamp']!;
+const calendarTimestamp = new Type('tag:yaml.org,2002:timestamp', {
+ kind: 'scalar',
+ resolve: (data: string) => {
+ if (!baseTimestamp.resolve(data)) return false;
+ const m = /^(\d{4})-(\d{1,2})-(\d{1,2})/.exec(data);
+ if (!m) return true;
+ const d = new Date(Date.UTC(+m[1], +m[2] - 1, +m[3]));
+ return d.getUTCFullYear() === +m[1] && d.getUTCMonth() === +m[2] - 1 && d.getUTCDate() === +m[3];
+ },
+ construct: baseTimestamp.construct,
+ instanceOf: Date,
+ represent: baseTimestamp.represent,
+});
+const FRONTMATTER_SCHEMA = new Schema({ include: [DEFAULT_SAFE_SCHEMA], implicit: [calendarTimestamp] });
export interface DataFrontmatter {
data: Record<string, unknown>;
@@ -33,7 +54,7 @@ export function parseDataFrontmatter(input: string): DataFrontmatter {
const block = closing ? rest.slice(0, closing.index) : rest;
let value: unknown;
try {
- value = block.trim() === '' ? {} : language === 'json' ? JSON.parse(block) : safeLoad(block);
+ value = block.trim() === '' ? {} : language === 'json' ? JSON.parse(block) : safeLoad(block, { schema: FRONTMATTER_SCHEMA });
} catch (error) {
// Parser messages can contain the document itself. Report only location,
// so request/job diagnostics never copy private frontmatter into logs.
diff --git a/src/core/effective-date.ts b/src/core/effective-date.ts
index 825413928e..0da945471d 100644
--- a/src/core/effective-date.ts
+++ b/src/core/effective-date.ts
@@ -10,8 +10,9 @@
* 2. frontmatter.date — dated essays
* 3. frontmatter.published — writing/
* 4. filename-date — leading YYYY-MM-DD in basename
- * 5. updated_at — fallback
- * 6. created_at — last resort (only if updated_at NULL)
+ * 5. frontmatter created keys — created / created_at / date_created
+ * 6. created_at — fallback: the stable creation anchor
+ * 7. updated_at — last resort
*
* Per-prefix override: for `daily/` and `meetings/` slug prefixes, the
* filename-date jumps to position 1 — the filename is the user's primary
@@ -57,6 +58,29 @@ export interface ComputeEffectiveDateOpts {
*/
const FILENAME_FIRST_PREFIXES = ['daily/', 'meetings/'];
+/** Creation-date keys Obsidian and Notion exports carry; a content date after the others. */
+const CREATED_KEYS = ['created', 'created_at', 'date_created', 'date created'];
+
+/**
+ * The fallback anchor for an undated page: a page that already fell back
+ * keeps its stored date, a new file-backed page takes its file's timestamp
+ * (the earlier of birth and modification time), and anything else takes the
+ * row's creation time. Never the time of the latest write.
+ */
+export function fallbackCreatedAt(opts: {
+ existing?: { effective_date?: Date | string | null; effective_date_source?: string | null; created_at?: Date | string | null } | null;
+ fileTimes?: { birthtime?: Date; mtime?: Date } | null;
+ now: Date;
+}): Date {
+ const { existing, fileTimes, now } = opts;
+ if (existing?.effective_date_source === 'fallback' && existing.effective_date) return new Date(existing.effective_date);
+ if (existing?.created_at) return new Date(existing.created_at);
+ const times = [fileTimes?.birthtime, fileTimes?.mtime]
+ .filter((d): d is Date => d instanceof Date && d.getTime() > 0)
+ .map(d => d.getTime());
+ return times.length ? new Date(Math.min(...times)) : now;
+}
+
const MIN_DATE_MS = Date.UTC(1990, 0, 1);
const FILENAME_DATE_RE = /^(\d{4}-\d{2}-\d{2})/;
@@ -67,7 +91,31 @@ function maxDateMs(): number {
return Date.now() + 365 * 24 * 60 * 60 * 1000;
}
-/** Parse a frontmatter value as a Date. Accepts Date instances, ISO strings, YYYY-MM-DD. Returns null on any failure. */
+const MONTHS: Record<string, number> = {
+ jan: 1, january: 1, feb: 2, february: 2, mar: 3, march: 3, apr: 4, april: 4, may: 5, jun: 6, june: 6,
+ jul: 7, july: 7, aug: 8, august: 8, sep: 9, sept: 9, september: 9, oct: 10, october: 10,
+ nov: 11, november: 11, dec: 12, december: 12,
+};
+const NUMERIC_DATE_RE = /^(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})$/;
+const DATETIME_RE = /^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2})(?::(\d{2})(\.\d+)?)?\s*(Z|[+-]\d{2}:?\d{2})?$/i;
+const MONTH_DAY_YEAR_RE = /^(?:[a-z]+,?\s+)?([a-z]{3,9})\.?\s+(\d{1,2})(?:st|nd|rd|th)?,?\s+(\d{4})$/i;
+const DAY_MONTH_YEAR_RE = /^(\d{1,2})(?:st|nd|rd|th)?\s+([a-z]{3,9})\.?,?\s+(\d{4})$/i;
+
+/** A UTC calendar date, or null when Y/M/D does not name a real day (2024-02-30). */
+function utcCalendarDate(year: number, month: number, day: number, h = 0, m = 0, sec = 0, ms = 0): Date | null {
+ const d = new Date(Date.UTC(year, month - 1, day, h, m, sec, ms));
+ return d.getUTCFullYear() === year && d.getUTCMonth() === month - 1 && d.getUTCDate() === day ? d : null;
+}
+
+/**
+ * Parse a frontmatter value as a Date. Returns null on any failure.
+ *
+ * Calendar shapes never depend on the syncing host's timezone: date-only
+ * values (`2024-03-15`, `2024/03/15`, `March 5, 2024`, `5 March 2024`) are UTC
+ * calendar dates, and a datetime without an offset is read as UTC. A
+ * calendar-invalid date (`2024-02-30`) is rejected rather than rolled over.
+ * Other strings fall back to Date.parse.
+ */
export function parseDateLoose(value: unknown): Date | null {
if (value == null) return null;
if (value instanceof Date) {
@@ -76,6 +124,22 @@ export function parseDateLoose(value: unknown): Date | null {
if (typeof value === 'string') {
const trimmed = value.trim();
if (trimmed === '') return null;
+ const numeric = NUMERIC_DATE_RE.exec(trimmed);
+ if (numeric) return utcCalendarDate(+numeric[1], +numeric[2], +numeric[3]);
+ const datetime = DATETIME_RE.exec(trimmed);
+ if (datetime) {
+ const [, y, mo, d, h, mi, sec, frac, zone] = datetime;
+ const wall = utcCalendarDate(+y, +mo, +d, +h, +mi, +(sec ?? 0), frac ? Math.round(+frac * 1000) : 0);
+ if (!wall || +h > 23 || +mi > 59 || +(sec ?? 0) > 59) return null;
+ if (!zone || zone.toUpperCase() === 'Z') return wall;
+ const sign = zone.startsWith('-') ? -1 : 1;
+ const [zh, zm] = [+zone.slice(1, 3), +zone.slice(-2)];
+ return new Date(wall.getTime() - sign * (zh * 60 + zm) * 60_000);
+ }
+ const mdy = MONTH_DAY_YEAR_RE.exec(trimmed);
+ if (mdy && MONTHS[mdy[1].toLowerCase()]) return utcCalendarDate(+mdy[3], MONTHS[mdy[1].toLowerCase()], +mdy[2]);
+ const dmy = DAY_MONTH_YEAR_RE.exec(trimmed);
+ if (dmy && MONTHS[dmy[2].toLowerCase()]) return utcCalendarDate(+dmy[3], MONTHS[dmy[2].toLowerCase()], +dmy[1]);
const ms = Date.parse(trimmed);
if (!Number.isFinite(ms)) return null;
return new Date(ms);
@@ -125,6 +189,7 @@ export function computeEffectiveDate(opts: ComputeEffectiveDateOpts): EffectiveD
const fmDate = validateInRange(parseDateLoose(frontmatter.date));
const fmPublished = validateInRange(parseDateLoose(frontmatter.published));
const filenameDate = extractFilenameDate(filename);
+ const fmCreated = CREATED_KEYS.map(key => validateInRange(parseDateLoose(frontmatter[key]))).find(d => d !== null) ?? null;
// Build the ordered candidate list. For filename-first prefixes
// (daily/, meetings/) the filename moves to the head of the chain.
@@ -134,25 +199,28 @@ export function computeEffectiveDate(opts: ComputeEffectiveDateOpts): EffectiveD
{ date: fmEvent, source: 'event_date' },
{ date: fmDate, source: 'date' },
{ date: fmPublished, source: 'published' },
+ { date: fmCreated, source: 'created' },
]
: [
{ date: fmEvent, source: 'event_date' },
{ date: fmDate, source: 'date' },
{ date: fmPublished, source: 'published' },
{ date: filenameDate, source: 'filename' },
+ { date: fmCreated, source: 'created' },
];
for (const c of candidates) {
if (c.date !== null) return { date: c.date, source: c.source };
}
- // Fallback chain: updated_at, then created_at. Both are guaranteed
- // non-null by the schema; the validation here is defensive against bad
- // test fixtures.
- const upd = validateInRange(updatedAt);
- if (upd !== null) return { date: upd, source: 'fallback' };
+ // Fallback chain: the creation anchor, then updated_at. The anchor is
+ // stable across edits (see fallbackCreatedAt), so an undated page keeps its
+ // date instead of taking every write's time. Both are guaranteed non-null
+ // by the schema; the validation here is defensive against bad fixtures.
const cre = validateInRange(createdAt);
if (cre !== null) return { date: cre, source: 'fallback' };
+ const upd = validateInRange(updatedAt);
+ if (upd !== null) return { date: upd, source: 'fallback' };
return { date: null, source: null };
}
diff --git a/src/core/engine.ts b/src/core/engine.ts
index 17e4b6f9c9..aad719c94c 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -819,10 +819,15 @@ export interface BrainEngine {
* `engine.findDuplicatePage?.(...)` and fall through on undefined.
* `deleted_at IS NULL` is deliberate — a soft-deleted page should NOT
* block a legitimate re-import under a new slug.
+ *
+ * `excludeSlug` removes the caller's own row, so a page never matches
+ * itself. A `frontmatter.id` match ranks ahead of a bare `content_hash`
+ * match, so a page that shares the external id is never hidden behind an
+ * unrelated page that happens to share text.
*/
findDuplicatePage?(
sourceId: string,
- opts: { hash: string; frontmatterId?: string | null },
+ opts: { hash: string; frontmatterId?: string | null; excludeSlug?: string },
): Promise<{ slug: string; id: number } | null>;
/**
* Hard-delete a page row. Cascades to content_chunks, page_links,
diff --git a/src/core/entities/resolve.ts b/src/core/entities/resolve.ts
index 0e8e91bd5b..bcd0173998 100644
--- a/src/core/entities/resolve.ts
+++ b/src/core/entities/resolve.ts
@@ -33,8 +33,8 @@ import { isUndefinedTableError } from '../utils.ts';
* 1. If `raw` is already a page slug shape (contains a "/" or matches an
* exact pages.slug row in this source), return it untouched.
* 2. Resolve a bare name only when prefix expansion finds one candidate.
- * 3. For multi-token input, require a high-specificity fuzzy match against
- * pages.slug + pages.title within the source (case-insensitive).
+ * 3. For multi-token input, take a fuzzy candidate within the source only
+ * when it carries the same name tokens (sameEntityName).
* 4. Fall back to a deterministic slugify: lowercase-no-spaces with
* hyphen-collapse. NOT prefixed with a directory — caller decides
* whether to prefix `people/`, `companies/`, etc.
@@ -106,6 +106,33 @@ function fallbackSlugify(trimmed: string): string {
return slugify(trimmed);
}
+const IDENTITY_TYPES = new Set(['person', 'company', 'fund', 'organization']);
+const IDENTITY_DIRS = ['people/', 'companies/', 'funds/', 'orgs/', 'organizations/'];
+const NAME_NOISE_TOKENS = new Set(['the', 'inc', 'llc', 'ltd', 'co', 'corp', 'corporation', 'plc', 'gmbh']);
+
+/** True for pages that name one real-world person, company, fund or organization. */
+export function isIdentityEntity(slug: string, type?: string | null): boolean {
+ return (type != null && IDENTITY_TYPES.has(type)) || IDENTITY_DIRS.some(dir => slug.startsWith(dir));
+}
+
+function nameTokens(value: string): string {
+ const folded = foldNonDecomposingLatin(value).normalize('NFKD').replace(/\p{M}/gu, '').toLowerCase();
+ const tokens = folded.split(/[^\p{L}\p{N}]+/u).filter(token => token && !NAME_NOISE_TOKENS.has(token));
+ return [...new Set(tokens)].sort().join(' ');
+}
+
+/**
+ * A fuzzy candidate names the same entity as a reference only when both carry
+ * the same name tokens, ignoring case, punctuation, order, accents and
+ * corporate suffixes. "Example, Alice" matches "Alice Example"; "Alicia
+ * Example" and "Alice Examples" do not, so a near-name never resolves to a
+ * different entity.
+ */
+export function sameEntityName(reference: string, candidateTitle: string | null | undefined, candidateSlug: string): boolean {
+ const wanted = nameTokens(reference);
+ return wanted !== '' && (wanted === nameTokens(candidateTitle ?? '') || wanted === nameTokens(candidateSlug.split('/').pop() ?? ''));
+}
+
/**
* Alias-exact arm (v0.46.15, #3730): unambiguous single-slug page_aliases hit,
* verified against LIVE pages — page_aliases has no FK to pages, so stale
@@ -266,7 +293,7 @@ export async function resolvePhantomCanonical(
// The phantom slug is the input; we treat it as the search term too,
// because phantom slugs ARE the lowercased bare name a fuzzy / prefix
// lookup would naturally target.
- const fuzzy = await tryFuzzyMatch(engine, source_id, trimmed);
+ const fuzzy = await tryFuzzyMatch(engine, source_id, trimmed, false);
if (fuzzy && fuzzy !== phantomSlug && fuzzy.includes('/')) return fuzzy;
const expanded = await tryPrefixExpansion(engine, source_id, slugify(trimmed));
@@ -439,6 +466,7 @@ async function tryFuzzyMatch(
engine: BrainEngine,
source_id: string,
raw: string,
+ sameNameOnly = true,
): Promise<string | null> {
const lc = raw.toLowerCase();
const fragment = slugify(raw);
@@ -460,13 +488,14 @@ async function tryFuzzyMatch(
OR slug ILIKE '%' || $3 || '%'
)
ORDER BY score DESC, slug ASC
- LIMIT 3`,
+ LIMIT 5`,
[source_id, lc, fragment],
);
- // 0.4 confidently misattributes names that share only a generic company
- // token (for example "Beacon Capital" → "Benton Capital"). Keep fuzzy
- // typo tolerance, but require high-specificity overlap before writing a
- // fact to an existing entity.
+ // A trigram score alone attributes facts about "Alicia Example" to Alice,
+ // and facts about a person with no page to a meeting page that carries
+ // their name. Entity resolution takes a candidate only when it names the
+ // same entity; anything else falls back to the reference's own slug.
+ if (sameNameOnly) return rows.find(row => sameEntityName(raw, row.title, row.slug))?.slug ?? null;
if (rows.length > 0 && rows[0].score >= 0.7) return rows[0].slug;
} catch {
// pg_trgm functions might not be available on every engine config;
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index 1361c60b54..c7ededb64c 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -1,9 +1,10 @@
import { assertUnmanagedCanonicalWriter } from './persistence/maintenance.ts';
import { assertImportBase, sameCanonicalImport } from './page-state/import-guard.ts';
import { stabilizeSafetyAssessments } from './persistence/reconcile-safety.ts';
+import { decideImportIdentity, collidingSlugOwner } from './import-identity.ts';
import { readSourceFileSync } from './minions/source-filesystem.ts';
import { readFileSync, statSync, lstatSync } from 'fs';
-import { basename, extname } from 'path';
+import { basename, extname, resolve } from 'path';
import { createHash } from 'crypto';
import type { BrainEngine, FileSpec } from './engine.ts';
import { parseMarkdown } from './markdown.ts';
@@ -26,7 +27,7 @@ import { embedMultimodal, currentEmbeddingSignature } from './embedding.ts';
import { embedBatchWithBackoff } from './embed-retry.ts';
import { slugifyPath, slugifyCodePath, isCodeFilePath, hasMalformedPathSegment } from './sync.ts';
import type { ChunkInput, PageInput, PageType } from './types.ts';
-import { computeEffectiveDate } from './effective-date.ts';
+import { computeEffectiveDate, fallbackCreatedAt } from './effective-date.ts';
import { MARKDOWN_CHUNKER_VERSION } from './chunkers/recursive.ts';
import { logSlugFallback } from './audit-slug-fallback.ts';
import { resolveContextualRetrievalMode } from './contextual-retrieval-resolver.ts';
@@ -143,9 +144,11 @@ export interface ImportResult {
* treated as failures. 'malformed_path' = the FILENAME contains bracket or
* control characters (never importable; rename the file) — sync counts these
* in its malformed summary and keeps them OUT of failedFiles / the failure
- * ledger so they can never gate bookmark advancement.
+ * ledger so they can never gate bookmark advancement. 'slug_collision' =
+ * another live file already owns this slug (see importFromContent); the
+ * skip repeats until one file is renamed.
*/
- skip_reason?: 'malformed_path';
+ skip_reason?: 'malformed_path' | 'slug_collision';
/**
* Advisory (schema.type_warnings): the page's explicit frontmatter `type:`
* is an alias of a canonical pack type or undeclared in the pack. The type
@@ -153,6 +156,9 @@ export interface ImportResult {
* distinct type per run.
*/
type_warning?: { kind: 'alias_of' | 'undeclared'; type: string; canonical?: string; directory?: string };
+ /** True when the text committed but the embedding provider failed; the
+ * chunks carry NULL vectors until the stale sweep embeds them. */
+ embedding_deferred?: boolean;
}
export const MAX_FILE_SIZE = 5_000_000; // 5MB
@@ -229,6 +235,14 @@ export async function importFromContent(
* fallback). MCP `put_page` callers leave undefined (no file).
*/
sourcePath?: string;
+ /**
+ * Absolute directory `sourcePath` is relative to. importFromFile sets it
+ * so the identity dedup can tell a moved file (its recorded path is gone)
+ * from a second file that shares a frontmatter.id.
+ */
+ sourceRoot?: string;
+ /** The source file's timestamps: the date of a new page that carries no date of its own. */
+ fileTimes?: { birthtime?: Date; mtime?: Date };
/**
* v0.32.7 CJK wave (codex post-merge F1): bypass the
* `existing.content_hash === hash` short-circuit and ALWAYS re-chunk +
@@ -572,6 +586,15 @@ export async function importFromContent(
const existing = opts.prepare ? existingSnapshot?.page ?? null : await engine.getPage(slug, { sourceId: sourceId ?? 'default', includeDeleted: true });
if (existing) stabilizeSafetyAssessments(parsed.frontmatter, existing.frontmatter);
+ const collisionOwner = collidingSlugOwner(existing, slug, opts.sourceRoot, opts.sourcePath);
+ if (collisionOwner) {
+ process.stderr.write(
+ `[import] slug collision: ${opts.sourcePath} and ${collisionOwner} both map to ${slug} ` +
+ `in source ${sourceId ?? 'default'}; keeping ${collisionOwner}. Rename one file to import both.\n`
+ );
+ return { slug, status: 'skipped', chunks: 0, skip_reason: 'slug_collision' };
+ }
+
// #2044 / #4548: remote get_page/fetch intentionally strip non-'world'
// facts rows before an untrusted caller ever sees them. A documented
// get_page -> edit -> put_page round-trip therefore arrives MISSING rows
@@ -691,71 +714,45 @@ export async function importFromContent(
}
}
- // v0.41.13 (#1309) — identity-based cross-slug dedup pre-check.
- //
- // Catches the overlapping-ingest-roots bug class: when a user runs
- // `gbrain import /vault/Subdir/` then later `gbrain import /vault/`,
- // the same file is ingested under two different slugs (e.g.
- // `vault/subdir/note` and `vault/note`). The slug-only check above
- // misses it because the slugs differ; this check identifies the true
- // duplicate by content_hash OR external frontmatter.id (granola UUID,
- // ULID, etc.).
- //
- // Posture (codex review):
- // - SKIP only when frontmatter.id matches (true external duplicate).
- // - WARN-ALWAYS when content_hash matches but identity differs (two
- // intentional pages that happen to share text — templates, daily
- // logs). User decides whether to investigate.
- // - FAIL CLOSED on lookup error: a DB throw means we cannot verify
- // uniqueness, so throw rather than silently allow a duplicate.
- //
- // Soft-deleted rows are excluded at the engine layer (`deleted_at IS NULL`)
- // so a tombstoned page doesn't block a legitimate re-import.
- // Test doubles that don't implement `findDuplicatePage` fall through
- // via the `?.` shape — no failure mode for fake engines.
+ // Identity dedup (#1309): move, skip a true duplicate, or index both.
+ // See decideImportIdentity for the posture.
const fmId = (parsed.frontmatter as Record<string, unknown> | undefined)?.id;
const fmIdStr = typeof fmId === 'string' && fmId.length > 0 ? fmId : null;
- if (!opts.forceRechunk && engine.findDuplicatePage) {
- let dup: { slug: string; id: number } | null = null;
- try {
- dup = await engine.findDuplicatePage(sourceId ?? 'default', {
- hash,
- frontmatterId: fmIdStr,
- });
- } catch (err) {
- throw new Error(
- `[import] dedup pre-check failed for ${opts.sourcePath ?? slug}: ` +
- `${(err as Error).message}. Re-run import after DB recovery.`
- );
- }
- if (dup && dup.slug !== slug) {
- // Look up the duplicate page so we can compare frontmatter.id.
- const dupPage = await engine.getPage(dup.slug, { sourceId: sourceId ?? 'default' });
- const dupFmId = (dupPage?.frontmatter as Record<string, unknown> | undefined)?.id;
- const dupFmIdStr = typeof dupFmId === 'string' && dupFmId.length > 0 ? dupFmId : null;
- const sameExternalId = fmIdStr !== null && dupFmIdStr === fmIdStr;
- if (sameExternalId) {
- if (opts.prepare) {
- const result: ImportResult = { slug: dup.slug, status: 'skipped', chunks: 0, parsedPage };
- return opts.prepare({ slug: dup.slug, parsedPage, observedRevision: (existing as (typeof existing & { knowledge_revision?: string }) | null)?.knowledge_revision ?? null,
- noop: true, result, validate: async () => {}, apply: async () => {} });
- }
- // True duplicate (same external ID). Skip + log to stderr.
- process.stderr.write(
- `[import] skipping ${opts.sourcePath ?? slug}: identical to ${dup.slug} ` +
- `(frontmatter.id=${fmIdStr}) in source ${sourceId ?? 'default'}. ` +
- `Pass --force-rechunk to override.\n`
- );
- return { slug: dup.slug, status: 'skipped', chunks: 0, parsedPage };
- }
- // Same content_hash, different (or missing) frontmatter.id.
- // Surface a warning but proceed with the insert — they may be
- // legitimate independent pages that happen to share text.
- process.stderr.write(
- `[import] WARNING: ${opts.sourcePath ?? slug} shares content_hash with ${dup.slug} ` +
- `(${hash.slice(0, 8)}) but has different frontmatter.id. Indexing both.\n`
- );
+ const identity = opts.forceRechunk ? { kind: 'none' as const } : await decideImportIdentity(engine, {
+ sourceId: sourceId ?? 'default', slug, hash, frontmatterId: fmIdStr, sourcePath: opts.sourcePath, sourceRoot: opts.sourceRoot,
+ body: { title: parsed.title, compiled_truth: parsed.compiled_truth, timeline: parsed.timeline || '' },
+ });
+ if (identity.kind === 'move' && !existing && !opts.prepare
+ && await engine.updateSlug(identity.dupSlug, slug, { sourceId: sourceId ?? 'default' }) > 0) {
+ process.stderr.write(
+ `[import] ${opts.sourcePath} carries frontmatter.id=${fmIdStr} from moved file ${identity.dupSourcePath}; ` +
+ `renamed ${identity.dupSlug} -> ${slug} in source ${sourceId ?? 'default'}.\n`
+ );
+ return importFromContent(engine, slug, content, opts);
+ }
+ if (identity.kind === 'duplicate') {
+ if (opts.prepare) {
+ const result: ImportResult = { slug: identity.dupSlug, status: 'skipped', chunks: 0, parsedPage };
+ return opts.prepare({ slug: identity.dupSlug, parsedPage, observedRevision: (existing as (typeof existing & { knowledge_revision?: string }) | null)?.knowledge_revision ?? null,
+ noop: true, result, validate: async () => {}, apply: async () => {} });
}
+ process.stderr.write(
+ `[import] skipping ${opts.sourcePath ?? slug}: identical to ${identity.dupSlug} ` +
+ `(frontmatter.id=${fmIdStr}) in source ${sourceId ?? 'default'}. ` +
+ `Pass --force-rechunk to override.\n`
+ );
+ return { slug: identity.dupSlug, status: 'skipped', chunks: 0, parsedPage };
+ }
+ if (identity.kind === 'shared_id') {
+ process.stderr.write(
+ `[import] WARNING: ${opts.sourcePath ?? slug} shares frontmatter.id=${fmIdStr} with ${identity.dupSlug} ` +
+ `but its content differs. Indexing both.\n`
+ );
+ } else if (identity.kind === 'shared_hash') {
+ process.stderr.write(
+ `[import] WARNING: ${opts.sourcePath ?? slug} shares content_hash with ${identity.dupSlug} ` +
+ `(${hash.slice(0, 8)}) but not its frontmatter.id. Indexing both.\n`
+ );
}
// Preserve the importer projection (including fenced code and zero-chunk
@@ -844,7 +841,23 @@ export async function importFromContent(
chunks[i].token_count = Math.ceil(wrappedTexts[i].length / 4);
}
};
- if (!opts.onPostCommitEmbedding) await embedChunks();
+ // An embedding outage never blocks the text write: the page and its chunks
+ // commit with NULL vectors and no embedding signature, and the stale sweep
+ // (`gbrain embed --stale`, sync's embed pass, the cycle) embeds them once
+ // the provider recovers.
+ let embeddingDeferred = false;
+ if (!opts.onPostCommitEmbedding) {
+ try {
+ await embedChunks();
+ } catch (err) {
+ embeddingDeferred = true;
+ for (const c of chunks) { c.embedding = undefined; c.token_count = undefined; }
+ process.stderr.write(
+ `[import] ${slug}: embedding failed (${err instanceof Error ? err.message : String(err)}); ` +
+ `text saved, chunks queued for \`gbrain embed --stale\`.\n`
+ );
+ }
+ }
// v0.40.3.0: corpus_generation hash for D27 P1-5 cache invalidation.
// Record the selected wrapper generation for inline or deferred embedding;
@@ -875,9 +888,9 @@ export async function importFromContent(
// v0.29.1 — compute effective_date from frontmatter precedence chain.
// Filename comes from importFromFile path (basename) or the slug tail
- // (put_page MCP op fallback). updatedAt/createdAt use the existing
- // page's timestamps when present; otherwise NOW() (the row about to
- // be created). The result drives the recency boost and since/until
+ // (put_page MCP op fallback). An undated page falls back to a stable
+ // anchor (fallbackCreatedAt): its stored fallback date, else its file's
+ // timestamp, else now — never the latest write. The result drives the recency boost and since/until
// filters when callers opt in; nothing in the default search path
// consults it.
const filenameForChain = opts.filename ?? slug.split('/').pop() ?? slug;
@@ -887,7 +900,7 @@ export async function importFromContent(
frontmatter: parsed.frontmatter,
filename: filenameForChain,
updatedAt: existing?.updated_at ?? nowDate,
- createdAt: existing?.created_at ?? nowDate,
+ createdAt: fallbackCreatedAt({ existing, fileTimes: opts.fileTimes, now: nowDate }),
});
await tx.putPage(slug, {
@@ -962,7 +975,7 @@ export async function importFromContent(
// embedded (not --no-embed), so a later model/dims swap is detectable
// as stale via embed --stale. The deferred/backfill + per-slug embed
// paths stamp too; this covers the inline import/sync path.
- if (!opts.noEmbed && !opts.onPostCommitEmbedding) {
+ if (!opts.noEmbed && !opts.onPostCommitEmbedding && !embeddingDeferred) {
// D9: signature is null when the gateway is unconfigured — skip the
// stamp (a wrong signature is worse than none).
const importSig = currentEmbeddingSignature();
@@ -1074,6 +1087,7 @@ export async function importFromContent(
...(pageQuarantined ? { quarantined: true } : {}),
...(pageFlagged ? { flagged: true, flag_reason: pageFlagReason } : {}),
...(typeWarning ? { type_warning: typeWarning } : {}),
+ ...(embeddingDeferred ? { embedding_deferred: true } : {}),
};
}
@@ -1326,6 +1340,9 @@ export async function importFromFile(
...opts,
filename: fileBasename,
sourcePath: relativePath,
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- walks up from the caller's own file path by the depth of its own relative path to recover the import root; import-identity confines every probe under that root
+ sourceRoot: resolve(filePath, ...relativePath.split(/[\\/]/).map(() => '..')),
+ fileTimes: { birthtime: stat.birthtime, mtime: stat.mtime },
// The disk file IS the source of truth: a file the user emptied is a
// deliberate clear, so it passes putPage's empty-overwrite guard.
allowEmptyOverwrite: true,
@@ -1461,6 +1478,7 @@ export async function importCodeFile(
}
// Embed only the new/changed chunks.
+ let codeEmbeddingFailed = false;
if (!opts.noEmbed && needsEmbedIndexes.length > 0) {
try {
const textsToEmbed = needsEmbedIndexes.map((i) => chunks[i]!.chunk_text);
@@ -1471,6 +1489,7 @@ export async function importCodeFile(
chunks[i]!.token_count = Math.ceil(chunks[i]!.chunk_text.length / 4);
}
} catch (e: unknown) {
+ codeEmbeddingFailed = true;
console.warn(`[gbrain] embedding failed for code file ${slug}: ${e instanceof Error ? e.message : String(e)}`);
}
}
@@ -1513,7 +1532,7 @@ export async function importCodeFile(
// carrying old-model vectors). Mixed pages stay unstamped rather than
// falsely marked current; `reindex --code --force` / `embed --stale`
// handle the swap for those.
- if (!opts.noEmbed && needsEmbedIndexes.length === chunks.length) {
+ if (!opts.noEmbed && !codeEmbeddingFailed && needsEmbedIndexes.length === chunks.length) {
// D9: no stamp without a gateway (wrong signature is worse than none).
const codeSig = currentEmbeddingSignature();
if (codeSig) {
@@ -2060,10 +2079,19 @@ export async function importImageFile(
return { slug: imageSlug, status: 'skipped', chunks: 0,
error: 'Image OCR contains protected sections. Remove that content from the source image and reimport the changed image.' };
}
- // An unchanged legacy image still needs its full OCR/visual index rebuilt.
- const sealed = await engine.executeRaw(`SELECT id FROM pages p WHERE p.source_id = $1 AND p.slug = $2 AND ${safeChunksFilter('p')}`,
+ // An unchanged legacy image still needs its full OCR/visual index rebuilt,
+ // and so does an image whose earlier import lacked the visual vector or
+ // OCR text this run would build (--no-embed, OCR budget skip, provider
+ // error). Legacy rows without `ocr_status` count as OCR'd when they hold
+ // OCR text.
+ const sealed = await engine.executeRaw<{ has_visual: boolean }>(
+ `SELECT EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id = p.id AND c.embedding_image IS NOT NULL) AS has_visual
+ FROM pages p WHERE p.source_id = $1 AND p.slug = $2 AND ${safeChunksFilter('p')}`,
[sourceOpts.sourceId, imageSlug]);
- if (sealed.length && !existing.deleted_at && existing.text_projection_revision === existing.knowledge_revision) {
+ const ocrWanted = !opts.noEmbed && process.env.GBRAIN_EMBEDDING_IMAGE_OCR === 'true';
+ const ocrDone = (existing.frontmatter as Record<string, unknown>)?.ocr_status === 'done' || existing.compiled_truth.trim() !== '';
+ const indexComplete = !!sealed[0] && (opts.noEmbed || sealed[0].has_visual) && (!ocrWanted || ocrDone);
+ if (indexComplete && !existing.deleted_at && existing.text_projection_revision === existing.knowledge_revision) {
if (opts.prepare) return opts.prepare({ slug: imageSlug, observedRevision: existing.knowledge_revision ?? null, noop: true,
result: { slug: imageSlug, status: 'skipped', chunks: 0 }, validate: async () => {}, apply: async () => {} });
await engine.transaction(tx => assertImportBase(tx, imageSlug, sourceOpts.sourceId, existing));
@@ -2125,6 +2153,7 @@ export async function importImageFile(
mime_type: decoded.mime,
bytes: buf.byteLength,
...exif,
+ ...(ocr.successful ? { ocr_status: 'done' } : {}),
};
// Single chunk per image. chunk_text holds OCR text or filename so
@@ -2159,7 +2188,7 @@ export async function importImageFile(
timeline: '',
frontmatter,
content_hash: hash,
- ...(opts.prepare ? { source_path: relativePath } : {}),
+ source_path: relativePath,
},
// The image bytes are the source of truth and the body is OCR-derived:
// a changed image whose OCR yields nothing legitimately blanks the body.
diff --git a/src/core/import-identity.ts b/src/core/import-identity.ts
new file mode 100644
index 0000000000..2cec593d54
--- /dev/null
+++ b/src/core/import-identity.ts
@@ -0,0 +1,107 @@
+/**
+ * File identity decisions for importFromContent: frontmatter.id dedup and
+ * slug collisions. Pure reads; the importer applies the decision.
+ */
+
+import { existsSync, realpathSync } from 'fs';
+import { resolve, sep } from 'path';
+import type { BrainEngine } from './engine.ts';
+import type { Page } from './types.ts';
+import { slugifyPath } from './sync.ts';
+
+export interface ImportIdentityInput {
+ sourceId: string;
+ slug: string;
+ hash: string;
+ /** The page text; a row written outside the importer carries a different hash for the same text. */
+ body: { title: string; compiled_truth: string; timeline: string };
+ frontmatterId: string | null;
+ /** Repo-relative path and the directory it is relative to, when importing a file. */
+ sourcePath?: string;
+ sourceRoot?: string;
+}
+
+export type ImportIdentityDecision =
+ | { kind: 'none' }
+ | { kind: 'move'; dupSlug: string; dupSourcePath: string }
+ | { kind: 'duplicate'; dupSlug: string }
+ | { kind: 'shared_id'; dupSlug: string }
+ | { kind: 'shared_hash'; dupSlug: string };
+
+/**
+ * Identity-based cross-slug dedup (#1309, overlapping ingest roots): find
+ * another page with this content_hash or external frontmatter.id.
+ *
+ * - move: the id matches and that page's recorded source file is gone under
+ * this import's root. The importer renames the row in place (page id,
+ * links, facts and timeline survive) and imports the new content onto it,
+ * so a full sync's delete-reconcile has nothing live to remove.
+ * - duplicate: the id matches and so does the content (hash, or title and
+ * body for a row written outside the importer) while the recorded file
+ * still exists (or no file is known). The importer skips.
+ * - shared_id: the id matches but the content differs. Templates and
+ * copy-paste reuse ids, so both pages index; an edit is never frozen.
+ * - shared_hash: same text, different identity. Both pages index.
+ *
+ * Content-only callers (put_page, transcripts) pass no sourceRoot, so they
+ * never move a page. A lookup error fails closed.
+ */
+export async function decideImportIdentity(engine: BrainEngine, input: ImportIdentityInput): Promise<ImportIdentityDecision> {
+ if (!engine.findDuplicatePage) return { kind: 'none' };
+ let dup: { slug: string; id: number } | null;
+ try {
+ dup = await engine.findDuplicatePage(input.sourceId, { hash: input.hash, frontmatterId: input.frontmatterId, excludeSlug: input.slug });
+ } catch (err) {
+ throw new Error(
+ `[import] dedup pre-check failed for ${input.sourcePath ?? input.slug}: ` +
+ `${(err as Error).message}. Re-run import after DB recovery.`
+ );
+ }
+ if (!dup) return { kind: 'none' };
+ const dupPage = await engine.getPage(dup.slug, { sourceId: input.sourceId });
+ const dupFmId = (dupPage?.frontmatter as Record<string, unknown> | undefined)?.id;
+ const sameExternalId = input.frontmatterId !== null && dupFmId === input.frontmatterId;
+ if (!sameExternalId) return { kind: 'shared_hash', dupSlug: dup.slug };
+ const dupSourcePath = dupPage?.source_path ?? null;
+ const dupFile = input.sourceRoot !== undefined && dupSourcePath !== null ? pathUnderRoot(input.sourceRoot, dupSourcePath) : null;
+ if (dupFile !== null && dupSourcePath !== null && input.sourcePath !== undefined && dupSourcePath !== input.sourcePath && !existsSync(dupFile)) {
+ return { kind: 'move', dupSlug: dup.slug, dupSourcePath };
+ }
+ const sameContent = dupPage?.content_hash === input.hash || (!!dupPage && dupPage.title === input.body.title
+ && dupPage.compiled_truth === input.body.compiled_truth && (dupPage.timeline ?? '') === input.body.timeline);
+ return sameContent ? { kind: 'duplicate', dupSlug: dup.slug } : { kind: 'shared_id', dupSlug: dup.slug };
+}
+
+/**
+ * The live file that already owns `slug`, when it is not the file being
+ * imported. Two files that slugify to one slug (`notes/Foo Bar.md`,
+ * `notes/foo-bar.md`) would otherwise overwrite each other on every edit. The
+ * file named exactly like the slug owns it (the file the link extractor reads
+ * for that slug); otherwise the current owner keeps it. An owner path that is
+ * gone, or resolves to the same file (a case-only rename on a case-insensitive
+ * filesystem), is no collision.
+ */
+export function collidingSlugOwner(existing: Pick<Page, 'source_path' | 'deleted_at'> | null, slug: string,
+ sourceRoot: string | undefined, sourcePath: string | undefined): string | null {
+ const owner = existing?.source_path;
+ if (!owner || existing?.deleted_at || sourceRoot === undefined || sourcePath === undefined) return null;
+ if (owner === sourcePath || sourcePath === `${slug}.md` || slugifyPath(owner) !== slug) return null;
+ const ownerFile = pathUnderRoot(sourceRoot, owner);
+ const candidateFile = pathUnderRoot(sourceRoot, sourcePath);
+ if (ownerFile === null || candidateFile === null) return null;
+ try {
+ return realpathSync.native(ownerFile) !== realpathSync.native(candidateFile) ? owner : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * A repo-relative path joined to its (absolute, normalized) import root, or
+ * null when it would escape the root.
+ */
+function pathUnderRoot(root: string, relativePath: string): string | null {
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- the joined path is checked to stay inside `root` on the next line before any filesystem probe, and it is only ever used for existsSync/realpath, never read or written
+ const full = resolve(root, relativePath);
+ return full.startsWith(root.endsWith(sep) ? root : root + sep) ? full : null;
+}
diff --git a/src/core/link-extraction.ts b/src/core/link-extraction.ts
index 5123938eb7..ff8a1ea90c 100644
--- a/src/core/link-extraction.ts
+++ b/src/core/link-extraction.ts
@@ -20,6 +20,7 @@ import { parseInlineCitationTimelineEntries } from './timeline-citations.ts';
import { slugifyPath, slugifySegment } from './sync.ts';
import { SLUG_WORD_CHARS, SLUG_VARIATION_SELECTORS_RE } from './cjk.ts';
import { foldNonDecomposingLatin } from './latin-fold.ts';
+import { isIdentityEntity, sameEntityName } from './entities/resolve.ts';
// #3190: pack-aware link typing. link-inference imports only manifest-v1
// (zod) + redos-guard (node:vm) — no cycle back into this module.
import type { SchemaPackManifest } from './schema-pack/manifest-v1.ts';
@@ -1539,6 +1540,15 @@ export function makeResolver(
cache.set(cacheKey, trimmed);
return trimmed;
}
+ // A renamed page leaves `old -> new` in slug_aliases; links written
+ // against the old slug keep resolving to the page that moved.
+ if (typeof engine.resolveSlugWithAlias === 'function') {
+ const canonical = await engine.resolveSlugWithAlias(trimmed, opts.sourceId ?? 'default');
+ if (canonical !== trimmed && await engine.getPage(canonical, { sourceId: opts.sourceId ?? 'default' })) {
+ cache.set(cacheKey, canonical);
+ return canonical;
+ }
+ }
}
// Step 2: dir-hint + slugify → exact getPage. Two grammars (#4855):
@@ -1566,10 +1576,17 @@ export function makeResolver(
// so cross-source slug suggestions don't get silently dropped at the
// FK filter downstream. Mirrors the same scope fix `tryFuzzyMatch` got
// via #1436.
+ // A person, company, fund or organization candidate must carry the
+ // same name tokens (sameEntityName): a near-name like "Carol Exampl" never
+ // links to a different person's page and stays unresolved instead.
const searchHints = hints.length > 0 ? hints : [undefined];
+ const confident = async (slug: string): Promise<boolean> => {
+ const page = await engine.getPage(slug, opts.sourceId ? { sourceId: opts.sourceId } : undefined); // gbrain-allow-unscoped-getpage: read-only confidence check on a candidate the fuzzy lookup just returned
+ return !!page && (!isIdentityEntity(slug, page.type) || sameEntityName(trimmed, page.title, slug));
+ };
for (const hint of searchHints) {
const match = await engine.findByTitleFuzzy(trimmed, hint, 0.55, opts.sourceId);
- if (match) {
+ if (match && await confident(match.slug)) {
cache.set(cacheKey, match.slug);
return match.slug;
}
@@ -1580,13 +1597,13 @@ export function makeResolver(
// mode skips this step entirely to keep migration deterministic.
if (opts.mode === 'live') {
try {
- const results = await engine.searchKeyword(trimmed, { limit: 3 });
+ const results = await engine.searchKeyword(trimmed, { limit: 3, ...(opts.sourceId ? { sourceId: opts.sourceId } : {}) });
if (results.length > 0 && results[0].score >= 0.8) {
// Filter by dir hint if provided.
const top = hints.length > 0
? results.find(r => hints.some(h => r.slug.startsWith(`${h}/`)))
: results[0];
- if (top) {
+ if (top && (!isIdentityEntity(top.slug, top.type) || sameEntityName(trimmed, top.title, top.slug))) {
cache.set(cacheKey, top.slug);
return top.slug;
}
diff --git a/src/core/link-reconciliation.ts b/src/core/link-reconciliation.ts
index 0cb4de03a3..9990431d04 100644
--- a/src/core/link-reconciliation.ts
+++ b/src/core/link-reconciliation.ts
@@ -163,6 +163,27 @@ export async function replaceFileLinks(engine: BrainEngine, slug: string, source
return result.created;
}
+/**
+ * Replace one file page's own markdown-derived links with what its current
+ * text produces, the put_page contract: an edge the text no longer supports
+ * is removed, other producers' edges stay. Returns the number of new edges,
+ * or null when the page row is missing. Links whose endpoints are not live
+ * pages in the source are dropped, as the add-only path's failed inserts were.
+ */
+export async function replacePageFileLinks(engine: BrainEngine, slug: string, sourceId: string,
+ links: LinkBatchInput[], includeFrontmatter: boolean,
+ ownership: Awaited<ReturnType<typeof fileLinkOwnership>>): Promise<number | null> {
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId });
+ if (!snapshot) return null;
+ const rows = links.filter(link => ownership.metadata.has(`${sourceId}\0${link.from_slug}`)
+ && ownership.metadata.has(`${sourceId}\0${link.to_slug}`)).map(link => ({ ...link,
+ from_source_id: sourceId, to_source_id: sourceId, origin_source_id: sourceId }));
+ const result = await engine.replaceDerivedLinks({ slug, sourceId, expectedRevision: snapshot.revision,
+ sourceIncarnation: snapshot.sourceIncarnation }, rows, { includeFrontmatter, preserveExisting: true,
+ includeLegacyNullProducer: false });
+ return result.created;
+}
+
export async function fileLinkOwnership(engine: BrainEngine, sourceId: string) {
const pages = await loadLinkPageMetadata(engine);
const metadata = new Map(pages.map(row => [`${row.source_id}\0${row.slug}`, row]));
diff --git a/src/core/page-state/rename-alias.ts b/src/core/page-state/rename-alias.ts
new file mode 100644
index 0000000000..425ad1e60e
--- /dev/null
+++ b/src/core/page-state/rename-alias.ts
@@ -0,0 +1,32 @@
+import type { BrainEngine } from '../engine.ts';
+import { isUndefinedTableError } from '../utils.ts';
+
+/**
+ * Record `old -> new` in slug_aliases when a page is renamed, inside the
+ * caller's transaction, so `[[old]]` links and `get_page old` keep resolving.
+ * Aliases that named the old slug are repointed at the new one, and an alias
+ * spelled like the new slug is dropped: a live page now owns that slug. A
+ * brain whose schema predates slug_aliases (an early migration renaming
+ * slugs) skips the alias inside a savepoint.
+ */
+export async function recordRenameAlias(
+ tx: Pick<BrainEngine, 'transaction'>,
+ sourceId: string,
+ oldSlug: string,
+ newSlug: string,
+): Promise<void> {
+ if (oldSlug === newSlug) return;
+ try {
+ await tx.transaction(async savepoint => {
+ await savepoint.executeRaw('DELETE FROM slug_aliases WHERE source_id = $1 AND alias_slug = $2', [sourceId, newSlug]);
+ await savepoint.executeRaw('UPDATE slug_aliases SET canonical_slug = $3 WHERE source_id = $1 AND canonical_slug = $2',
+ [sourceId, oldSlug, newSlug]);
+ await savepoint.executeRaw(`INSERT INTO slug_aliases (source_id, alias_slug, canonical_slug, notes)
+ VALUES ($1, $2, $3, 'rename')
+ ON CONFLICT (source_id, alias_slug) DO UPDATE SET canonical_slug = EXCLUDED.canonical_slug`,
+ [sourceId, oldSlug, newSlug]);
+ });
+ } catch (error) {
+ if (!isUndefinedTableError(error)) throw error;
+ }
+}
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index a22ccc384e..b4190a9b0e 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -7,6 +7,7 @@ import { assertPageRevision } from './page-state/types.ts';
import { lockPageKeys as acquirePageKeys } from './page-state/guards.ts';
import { readPageSnapshot as readCanonicalPageSnapshot } from './page-state/snapshot.ts';
import { createPageVersion } from './page-state/versions.ts';
+import { recordRenameAlias } from './page-state/rename-alias.ts';
import { composablePgliteTransaction } from './page-state/transactions.ts';
import { GRANT_COLUMNS_SQL } from './grants/schema.ts';
import type { PageReadScope } from './types.ts';
@@ -1739,16 +1740,17 @@ export class PGLiteEngine implements BrainEngine {
*/
async findDuplicatePage(
sourceId: string,
- opts: { hash: string; frontmatterId?: string | null },
+ opts: { hash: string; frontmatterId?: string | null; excludeSlug?: string },
): Promise<{ slug: string; id: number } | null> {
const fmId = opts.frontmatterId ?? null;
const sql = `SELECT id, slug FROM pages
WHERE source_id = $1
AND deleted_at IS NULL
AND (content_hash = $2 OR (frontmatter->>'id' = $3 AND $3 IS NOT NULL))
- ORDER BY id
+ AND ($4::text IS NULL OR slug <> $4)
+ ORDER BY (frontmatter->>'id' IS NOT DISTINCT FROM $3) DESC, id
LIMIT 1`;
- const { rows } = await this.db.query(sql, [sourceId, opts.hash, fmId]);
+ const { rows } = await this.db.query(sql, [sourceId, opts.hash, fmId, opts.excludeSlug ?? null]);
if (rows.length === 0) return null;
const r = rows[0] as { id: number | string; slug: string };
return { slug: r.slug, id: Number(r.id) };
@@ -5785,14 +5787,18 @@ export class PGLiteEngine implements BrainEngine {
newSlug = validateSlug(newSlug);
const sourceId = opts?.sourceId ?? 'default';
// Source-qualify so a rename in source A doesn't sweep up same-slug rows
- // in sources B/C/D (mirrors postgres-engine.ts).
- const result = await this.db.query(
- `UPDATE pages SET slug = $1, updated_at = now() WHERE slug = $2 AND source_id = $3`,
- [newSlug, oldSlug, sourceId]
- );
- // #3056: rows moved — a zero-row UPDATE does not throw, so the count is
- // the only way callers can see the no-op.
- return result.affectedRows ?? 0;
+ // in sources B/C/D (mirrors postgres-engine.ts). The rename and its
+ // slug alias commit together.
+ return this.transaction(async tx => {
+ const moved = await tx.executeRaw(
+ `UPDATE pages SET slug = $1, updated_at = now() WHERE slug = $2 AND source_id = $3 RETURNING id`,
+ [newSlug, oldSlug, sourceId]
+ );
+ if (moved.length > 0) await recordRenameAlias(tx, sourceId, oldSlug, newSlug);
+ // #3056: rows moved — a zero-row UPDATE does not throw, so the count is
+ // the only way callers can see the no-op.
+ return moved.length;
+ });
}
async rewriteLinks(_oldSlug: string, _newSlug: string): Promise<void> {
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 7c6fec995f..0bc1bdcb6a 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -6,6 +6,7 @@ import { assertPageRevision } from './page-state/types.ts';
import { lockPageKeys as acquirePageKeys } from './page-state/guards.ts';
import { readPageSnapshot as readCanonicalPageSnapshot } from './page-state/snapshot.ts';
import { createPageVersion } from './page-state/versions.ts';
+import { recordRenameAlias } from './page-state/rename-alias.ts';
import { composablePostgresTransaction } from './page-state/transactions.ts';
import type { PageReadScope } from './types.ts';
import type { PageReadPolicy } from './types.ts';
@@ -691,9 +692,10 @@ export class PostgresEngine implements BrainEngine {
*/
async findDuplicatePage(
sourceId: string,
- opts: { hash: string; frontmatterId?: string | null },
+ opts: { hash: string; frontmatterId?: string | null; excludeSlug?: string },
): Promise<{ slug: string; id: number } | null> {
const fmId = opts.frontmatterId ?? null;
+ const excludeSlug = opts.excludeSlug ?? null;
// RLS scope binding: sourceId is positional here.
return await this.withScopedReadTransaction(undefined, sourceId, async (tx) => {
const rows = await tx`
@@ -701,7 +703,8 @@ export class PostgresEngine implements BrainEngine {
WHERE source_id = ${sourceId}
AND deleted_at IS NULL
AND (content_hash = ${opts.hash} OR (frontmatter->>'id' = ${fmId} AND ${fmId}::text IS NOT NULL))
- ORDER BY id
+ AND (${excludeSlug}::text IS NULL OR slug <> ${excludeSlug})
+ ORDER BY (frontmatter->>'id' IS NOT DISTINCT FROM ${fmId}::text) DESC, id
LIMIT 1
`;
if (rows.length === 0) return null;
@@ -5016,15 +5019,21 @@ export class PostgresEngine implements BrainEngine {
// Sync
async updateSlug(oldSlug: string, newSlug: string, opts?: { sourceId?: string }): Promise<number> {
newSlug = validateSlug(newSlug);
- const sql = this.sql;
const sourceId = opts?.sourceId ?? 'default';
// Source-qualify so a rename in source A doesn't sweep up same-slug rows
// in sources B/C/D (which would either rename them all OR fail the
// (source_id, slug) UNIQUE if the new slug already exists in another source).
- const result = await sql`UPDATE pages SET slug = ${newSlug}, updated_at = now() WHERE slug = ${oldSlug} AND source_id = ${sourceId}`;
- // #3056: rows moved — a zero-row UPDATE does not throw, so the count is
- // the only way callers can see the no-op.
- return result.count ?? 0;
+ // The rename and its slug alias commit together.
+ return this.transaction(async tx => {
+ const moved = await tx.executeRaw(
+ `UPDATE pages SET slug = $1, updated_at = now() WHERE slug = $2 AND source_id = $3 RETURNING id`,
+ [newSlug, oldSlug, sourceId],
+ );
+ if (moved.length > 0) await recordRenameAlias(tx, sourceId, oldSlug, newSlug);
+ // #3056: rows moved — a zero-row UPDATE does not throw, so the count is
+ // the only way callers can see the no-op.
+ return moved.length;
+ });
}
async rewriteLinks(_oldSlug: string, _newSlug: string): Promise<void> {
diff --git a/src/core/timeline-extract.ts b/src/core/timeline-extract.ts
index a8b2b149da..30b49a44cc 100644
--- a/src/core/timeline-extract.ts
+++ b/src/core/timeline-extract.ts
@@ -12,6 +12,7 @@
*/
import { parseInlineCitationTimelineEntries, findTimelineSourceDelimiter } from './link-extraction.ts';
+import type { BrainEngine } from './engine.ts';
export interface ExtractedTimelineEntry {
slug: string;
@@ -91,3 +92,36 @@ export function extractTimelineFromContent(content: string, slug: string): Extra
return entries;
}
+
+/**
+ * Retract the timeline rows a page's previous text produced that its current
+ * text no longer does (a corrected or deleted dated bullet). The previous text
+ * is the page's latest version snapshot, taken before the import that changed
+ * it. Only exact (date, source, summary) tuples that text produced are
+ * removed, so rows from other producers (enrichment, meeting fan-out, event
+ * projections) are never touched. Returns the number of rows removed.
+ */
+export async function retractRemovedTimelineEntries(
+ engine: Pick<BrainEngine, 'executeRaw'>,
+ slug: string,
+ sourceId: string,
+ current: ReadonlyArray<ExtractedTimelineEntry>,
+): Promise<number> {
+ const [previous] = await engine.executeRaw<{ compiled_truth: string; timeline: string | null }>(
+ `SELECT v.compiled_truth, v.timeline FROM page_versions v JOIN pages p ON p.id = v.page_id
+ WHERE p.source_id = $1 AND p.slug = $2 ORDER BY v.id DESC LIMIT 1`, [sourceId, slug]);
+ if (!previous) return 0;
+ const key = (e: Pick<ExtractedTimelineEntry, 'date' | 'source' | 'summary'>) => JSON.stringify([e.date, e.source, e.summary]);
+ const kept = new Set(current.map(key));
+ const removed = extractTimelineFromContent(`${previous.compiled_truth}\n${previous.timeline ?? ''}`, slug)
+ .filter(entry => !kept.has(key(entry)))
+ .map(({ date, source, summary }) => ({ date, source, summary }));
+ if (!removed.length) return 0;
+ const rows = await engine.executeRaw(
+ `DELETE FROM timeline_entries t USING pages p
+ WHERE p.id = t.page_id AND p.source_id = $1 AND p.slug = $2 AND t.event_page_id IS NULL
+ AND EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS r(date date, source text, summary text)
+ WHERE r.date = t.date AND r.source = t.source AND r.summary = t.summary)
+ RETURNING t.id`, [sourceId, slug, JSON.stringify(removed)]);
+ return rows.length;
+}
diff --git a/src/core/types.ts b/src/core/types.ts
index e1f91ffecc..6ba21247cc 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -196,6 +196,7 @@ export type EffectiveDateSource =
| 'date'
| 'published'
| 'filename'
+ | 'created'
| 'fallback';
// `image` (v0.27.1): multimodal ingestion path, parallel to markdown + code.
diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.md
index 8a1c315f67..b8c4b36fb7 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.59.10.0 -->
+<!-- gbrain-template-stamp: 0.59.11.0 -->
This repository is the **"Use this template"** distribution artifact for a
[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the same
diff --git a/test/attendance-retrieval.test.ts b/test/attendance-retrieval.test.ts
index a4a99a41e3..75043bb502 100644
--- a/test/attendance-retrieval.test.ts
+++ b/test/attendance-retrieval.test.ts
@@ -95,13 +95,16 @@ for (const kind of ['pglite', ...(process.env.DATABASE_URL ? ['postgres'] : [])]
capabilities: { embeddings: { available: false }, extraction: { available: false }, search: 'keyword-only', mode: 'keyless' } });
}
for (const lane of ['fs-sync', 'fs-incremental', 'fs-batch']) {
- test(`${lane}: ordinary meeting links keep additive filesystem handling`, async () => {
+ // The per-slug sync lanes replace a page's own markdown-derived links
+ // (the put_page contract); the full-walk batch lane stays additive.
+ const replaces = lane !== 'fs-batch';
+ test(`${lane}: ordinary meeting links ${replaces ? 'are replaced like put_page' : 'keep additive filesystem handling'}`, async () => {
await seed(meeting, 'meeting', '[Alice](../people/alice-example.md)');
await extract(lane);
expect((await engine.getLinks(meeting, { sourceId })).map(row => row.to_slug)).toEqual([person]);
await seed(meeting, 'meeting', 'An ordinary reference was removed, with no attendance claim.');
await extract(lane);
- expect((await engine.getLinks(meeting, { sourceId })).map(row => row.to_slug)).toEqual([person]);
+ expect((await engine.getLinks(meeting, { sourceId })).map(row => row.to_slug)).toEqual(replaces ? [] : [person]);
});
test(`${lane}: unchanged DB-only attendance survives and real evidence removal retracts it`, async () => {
await seed(meeting, 'meeting', positive);
diff --git a/test/cycle-stale-drain.test.ts b/test/cycle-stale-drain.test.ts
index 46119d3d5c..133559fe52 100644
--- a/test/cycle-stale-drain.test.ts
+++ b/test/cycle-stale-drain.test.ts
@@ -222,9 +222,16 @@ describe('cycle extract phase stale drain (#4062)', () => {
// The cycle calls runExtractCore with jsonMode: true so the helper's human
// summary never lands ahead of the dream --json report. Quiet must not mean
// silent: a flush that drops rows still has to surface on stderr.
+ // Links are replaced per page (the put_page contract), so the dropped write
+ // is that page's replacement; both endpoints are live pages.
writeFileSync(join(brainDir, 'alice.md'), '# Alice\nMet [[bob]] today.\n');
writeFileSync(join(brainDir, 'bob.md'), '# Bob\nQuiet page.\n');
- const addLinks = spyOn(engine, 'addLinksBatch').mockRejectedValueOnce(new Error('pool exhausted'));
+ await engine.executeRaw(
+ `INSERT INTO pages (slug, source_id, type, title, compiled_truth, timeline)
+ VALUES ('alice', 'wiki', 'person', 'Alice', 'Met [[bob]] today.', ''),
+ ('bob', 'wiki', 'person', 'Bob', 'Quiet page.', '')`,
+ );
+ const addLinks = spyOn(engine, 'replaceDerivedLinks').mockRejectedValueOnce(new Error('pool exhausted'));
const log = spyOn(console, 'log').mockImplementation(() => {});
const stdout = spyOn(process.stdout, 'write').mockReturnValue(true);
const err = spyOn(console, 'error').mockImplementation(() => {});
diff --git a/test/effective-date-calendar.test.ts b/test/effective-date-calendar.test.ts
new file mode 100644
index 0000000000..1d343af536
--- /dev/null
+++ b/test/effective-date-calendar.test.ts
@@ -0,0 +1,115 @@
+/**
+ * effective_date is a calendar fact, not a property of the syncing machine.
+ *
+ * - Date-only values ("2024-03-15", "2024/03/15", "March 5, 2024") are UTC
+ * calendar dates, and a naive datetime ("2024-03-15 10:00") is read as UTC,
+ * so every host stores the same instant whatever its TZ.
+ * - Calendar-invalid dates ("2024-02-30", including an unquoted YAML value)
+ * are rejected instead of rolling over to March 1.
+ * - An undated page no longer takes the import time: `created` frontmatter
+ * keys are content dates, a new file falls back to its own timestamp, and
+ * a later edit keeps the page's fallback date instead of moving it.
+ *
+ * Pure functions plus one PGLite import ($0).
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { mkdtempSync, writeFileSync, utimesSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { computeEffectiveDate, parseDateLoose } from '../src/core/effective-date.ts';
+import { parseMarkdown } from '../src/core/markdown.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromFile } from '../src/core/import-file.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const iso = (value: unknown) => parseDateLoose(value)?.toISOString() ?? null;
+
+describe('parseDateLoose is host-timezone independent', () => {
+ const cases: Array<[string, string]> = [
+ ['March 5, 2024', '2024-03-05T00:00:00.000Z'],
+ ['5 March 2024', '2024-03-05T00:00:00.000Z'],
+ ['2024/03/15', '2024-03-15T00:00:00.000Z'],
+ ['2024-03-15', '2024-03-15T00:00:00.000Z'],
+ ['2024-03-15 10:00', '2024-03-15T10:00:00.000Z'],
+ ['2024-03-15T10:00:00', '2024-03-15T10:00:00.000Z'],
+ ['2024-03-15T10:00:00+09:00', '2024-03-15T01:00:00.000Z'],
+ ];
+ for (const tz of ['Asia/Tokyo', 'America/Los_Angeles', 'UTC']) {
+ test(`TZ=${tz}`, async () => {
+ await withEnv({ TZ: tz }, async () => {
+ for (const [input, expected] of cases) expect([input, iso(input)]).toEqual([input, expected]);
+ });
+ });
+ }
+
+ test('calendar-invalid dates are rejected, not rolled over', () => {
+ for (const input of ['2024-02-30', '2023-02-29', '2024/13/01', 'February 30, 2024', '2024-04-31 09:00']) {
+ expect([input, iso(input)]).toEqual([input, null]);
+ }
+ expect(iso('2024-02-29')).toBe('2024-02-29T00:00:00.000Z');
+ });
+
+ test('an unquoted invalid YAML date is not rolled over by the frontmatter parser', () => {
+ const parsed = parseMarkdown('---\ntitle: x\ndate: 2024-02-30\n---\nbody\n', 'notes/x.md');
+ expect(iso(parsed.frontmatter.date)).toBeNull();
+ const valid = parseMarkdown('---\ntitle: x\ndate: 2024-02-29\n---\nbody\n', 'notes/x.md');
+ expect(iso(valid.frontmatter.date)).toBe('2024-02-29T00:00:00.000Z');
+ });
+
+ test('an invalid filename date falls through the chain', () => {
+ const r = computeEffectiveDate({
+ slug: 'daily/2024-02-30', frontmatter: {}, filename: '2024-02-30',
+ updatedAt: new Date('2025-01-02T00:00:00Z'), createdAt: new Date('2025-01-01T00:00:00Z'),
+ });
+ expect(r.source).toBe('fallback');
+ });
+});
+
+describe('undated pages', () => {
+ test('created frontmatter keys are content dates', () => {
+ for (const key of ['created', 'created_at', 'date_created', 'date created']) {
+ const r = computeEffectiveDate({
+ slug: 'notes/x', frontmatter: { [key]: '2019-06-01' }, filename: 'x',
+ updatedAt: new Date('2025-01-02T00:00:00Z'), createdAt: new Date('2025-01-01T00:00:00Z'),
+ });
+ expect([key, r.source, r.date?.toISOString()]).toEqual([key, 'created', '2019-06-01T00:00:00.000Z']);
+ }
+ });
+
+ test('the fallback prefers the stable creation anchor over the last write', () => {
+ const r = computeEffectiveDate({
+ slug: 'notes/x', frontmatter: {}, filename: 'x',
+ updatedAt: new Date('2025-01-02T00:00:00Z'), createdAt: new Date('2019-01-01T00:00:00Z'),
+ });
+ expect(r).toEqual({ date: new Date('2019-01-01T00:00:00Z'), source: 'fallback' });
+ });
+
+ describe('import', () => {
+ let engine: PGLiteEngine;
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ }, 60_000);
+ afterAll(async () => { if (engine) await engine.disconnect(); }, 60_000);
+
+ test('a new undated file takes its own timestamp and keeps it across edits', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'undated-'));
+ const file = join(root, 'old-note.md');
+ writeFileSync(file, '---\ntitle: Old note\n---\n\nWritten long ago.\n');
+ const written = new Date('2016-05-04T12:00:00Z');
+ utimesSync(file, written, written);
+ await importFromFile(engine, file, 'old-note.md', { noEmbed: true });
+ const read = async () => (await engine.executeRaw<{ effective_date: string; effective_date_source: string }>(
+ `SELECT effective_date, effective_date_source FROM pages WHERE slug = 'old-note'`))[0];
+ const first = await read();
+ expect(new Date(first.effective_date).toISOString()).toBe(written.toISOString());
+ expect(first.effective_date_source).toBe('fallback');
+
+ writeFileSync(file, '---\ntitle: Old note\n---\n\nWritten long ago, edited today.\n');
+ await importFromFile(engine, file, 'old-note.md', { noEmbed: true });
+ expect(new Date((await read()).effective_date).toISOString()).toBe(written.toISOString());
+ });
+ });
+});
diff --git a/test/effective-date.test.ts b/test/effective-date.test.ts
index 7c8c261f9a..844d7b186c 100644
--- a/test/effective-date.test.ts
+++ b/test/effective-date.test.ts
@@ -79,10 +79,10 @@ describe('computeEffectiveDate precedence chain (default order)', () => {
expect(r.date?.toISOString().startsWith('2024-06-15')).toBe(true);
});
- test('fallback to updated_at when chain exhausted', () => {
+ test('fallback to the stable creation anchor, not the last write, when chain exhausted', () => {
const r = run({});
expect(r.source).toBe('fallback');
- expect(r.date?.toISOString()).toBe(baseUpdated.toISOString());
+ expect(r.date?.toISOString()).toBe(baseCreated.toISOString());
});
});
@@ -147,7 +147,7 @@ describe('computeEffectiveDate parse failure fall-through', () => {
test('filename without date prefix → fallback', () => {
const r = run({ filename: 'no-date-here' });
expect(r.source).toBe('fallback');
- expect(r.date?.toISOString()).toBe(baseUpdated.toISOString());
+ expect(r.date?.toISOString()).toBe(baseCreated.toISOString());
});
});
diff --git a/test/entity-resolution-near-names.test.ts b/test/entity-resolution-near-names.test.ts
new file mode 100644
index 0000000000..6a2d2cc579
--- /dev/null
+++ b/test/entity-resolution-near-names.test.ts
@@ -0,0 +1,87 @@
+/**
+ * Near-name references must not resolve to a different entity.
+ *
+ * The link resolver (wikilinks, frontmatter entity fields) and the fact entity
+ * resolver used trigram similarity alone, so "Carol Exampl" linked to the page of
+ * a different person, "Carol Example", and facts about "Bob Jones Example" (no
+ * page) landed on a meeting page. A fuzzy candidate that is a person, company,
+ * fund or organization now resolves only when its name carries the same tokens
+ * as the reference (case, punctuation, order and accents aside). Otherwise the
+ * reference stays unresolved: the link resolver returns null and the fact
+ * resolver falls back to the reference's own slug.
+ *
+ * PGLite in-memory, no embeddings ($0).
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { makeResolver } from '../src/core/link-extraction.ts';
+import { resolveEntitySlugWithSource } from '../src/core/entities/resolve.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ const pages: Array<[string, string, string]> = [
+ ['people/carol-example', 'person', 'Carol Example'],
+ ['people/alice-exampleson', 'person', 'Alice Exampleson'],
+ ['people/alice-smith-example', 'person', 'Alice Smith Example'],
+ ['companies/widgetco-robotics', 'company', 'Widgetco Robotics'],
+ ['meetings/2026-03-01-bob-jones-example-sync', 'meeting', 'Bob Jones Example sync'],
+ ['concepts/retrieval-augmented-generation', 'concept', 'Retrieval Augmented Generation'],
+ ];
+ for (const [slug, type, title] of pages) {
+ await importFromContent(engine, slug, `---\ntype: ${type}\ntitle: ${title}\n---\n\n${title} notes.\n`, { noEmbed: true });
+ }
+}, 60_000);
+
+afterAll(async () => {
+ if (engine) await engine.disconnect();
+}, 60_000);
+
+describe('link resolver', () => {
+ for (const mode of ['live', 'batch'] as const) {
+ test(`${mode}: a near-name of a different person or company stays unresolved`, async () => {
+ const r = makeResolver(engine, { mode, sourceId: 'default' });
+ expect(await r.resolve('Carol Exampl', 'people')).toBeNull();
+ expect(await r.resolve('Carol Exampl')).toBeNull();
+ expect(await r.resolve('Alice Examplston', 'people')).toBeNull();
+ expect(await r.resolve('Alicia Exampleson', 'people')).toBeNull();
+ expect(await r.resolve('Widgetco Robotic Arms', 'companies')).toBeNull();
+ expect(await r.resolve('Widgetco Robotic Arms')).toBeNull();
+ });
+
+ test(`${mode}: the same name in another spelling still resolves`, async () => {
+ const r = makeResolver(engine, { mode, sourceId: 'default' });
+ expect(await r.resolve('Exampleson, Alice', 'people')).toBe('people/alice-exampleson');
+ expect(await r.resolve('carol example')).toBe('people/carol-example');
+ });
+
+ test(`${mode}: typo tolerance survives for non-entity pages`, async () => {
+ const r = makeResolver(engine, { mode, sourceId: 'default' });
+ expect(await r.resolve('Retrieval Augmented Generaton')).toBe('concepts/retrieval-augmented-generation');
+ });
+ }
+});
+
+describe('fact entity resolver', () => {
+ test('a different person with a near name falls back to the reference slug', async () => {
+ expect(await resolveEntitySlugWithSource(engine, 'default', 'Alicia Smith Example'))
+ .toEqual({ slug: 'alicia-smith-example', source: 'fallback_slugify' });
+ });
+
+ test('a person without a page never lands on a meeting page', async () => {
+ expect(await resolveEntitySlugWithSource(engine, 'default', 'Bob Jones Example'))
+ .toEqual({ slug: 'bob-jones-example', source: 'fallback_slugify' });
+ });
+
+ test('the same person in another spelling still resolves', async () => {
+ expect(await resolveEntitySlugWithSource(engine, 'default', 'Example, Alice Smith'))
+ .toEqual({ slug: 'people/alice-smith-example', source: 'fuzzy_match' });
+ expect(await resolveEntitySlugWithSource(engine, 'default', 'Widgetco Robotics Inc'))
+ .toEqual({ slug: 'companies/widgetco-robotics', source: 'fuzzy_match' });
+ });
+});
diff --git a/test/entity-resolve.test.ts b/test/entity-resolve.test.ts
index 43edad54c6..f89dbacea3 100644
--- a/test/entity-resolve.test.ts
+++ b/test/entity-resolve.test.ts
@@ -146,8 +146,16 @@ describe('resolveEntitySlug — prefix expansion', () => {
expect(result).toContain('alice-example');
});
- it('preserves a high-specificity multi-token typo match', async () => {
+ it('does not attach a near-name to an existing person (a typo and a different person look alike)', async () => {
+ // "Alice Exampl" is one edit from "Alice Example", exactly as "Carol Exampl" is
+ // one edit from "Carol Example": trigram similarity cannot tell a typo from a
+ // different person, so the reference keeps its own slug.
const result = await resolveEntitySlug(engine as unknown as BrainEngine, 'default', 'Alice Exampl');
+ expect(result).toBe('alice-exampl');
+ });
+
+ it('resolves the same person written in another order or case', async () => {
+ const result = await resolveEntitySlug(engine as unknown as BrainEngine, 'default', 'example, ALICE');
expect(result).toBe('people/alice-example');
});
diff --git a/test/extract-incremental.test.ts b/test/extract-incremental.test.ts
index 3258c78b43..eff48f14a1 100644
--- a/test/extract-incremental.test.ts
+++ b/test/extract-incremental.test.ts
@@ -182,12 +182,20 @@ describe('runExtractCore — incremental cycle path (#417)', () => {
return originalAddTimeline(...args);
};
- await runExtractCore(engine as unknown as BrainEngine, {
- mode: 'all',
- dir: tempDir,
- slugs: ['people/alice-example'],
- dryRun: true,
- });
+ try {
+ await runExtractCore(engine as unknown as BrainEngine, {
+ mode: 'all',
+ dir: tempDir,
+ slugs: ['people/alice-example'],
+ dryRun: true,
+ });
+ } finally {
+ // Restore the shared engine's prototype methods: a wrapper bound to
+ // `engine` would run a later test's in-transaction batch insert outside
+ // its transaction.
+ delete (engine as unknown as { addLinksBatch?: unknown }).addLinksBatch;
+ delete (engine as unknown as { addTimelineEntriesBatch?: unknown }).addTimelineEntriesBatch;
+ }
expect(linksBatchCalled).toBe(false);
expect(timelineBatchCalled).toBe(false);
diff --git a/test/helpers/deep-research-contract.ts b/test/helpers/deep-research-contract.ts
index 26f049d1a8..093b6528aa 100644
--- a/test/helpers/deep-research-contract.ts
+++ b/test/helpers/deep-research-contract.ts
@@ -165,7 +165,9 @@ export function deepResearchContract(getEngine: () => BrainEngine): void {
test('source-bound aliases retain identity and canonical citations after rename', async () => {
const id = encodeDeepResearchId('beta', slug);
await getEngine().updateSlug(slug, 'notes/renamed-example', { sourceId: 'beta' });
- await getEngine().executeRaw(`INSERT INTO slug_aliases (source_id, alias_slug, canonical_slug) VALUES ('beta', $1, 'notes/renamed-example')`, [slug]);
+ // The rename records its own alias; no hand-written row is needed.
+ expect(await getEngine().executeRaw(`SELECT canonical_slug FROM slug_aliases WHERE source_id = 'beta' AND alias_slug = $1`, [slug]))
+ .toEqual([{ canonical_slug: 'notes/renamed-example' }]);
const page = await fetch(id);
expect(page.id).toBe(id);
expect(page.metadata.source_id).toBe('beta');
diff --git a/test/import-embed-outage.test.ts b/test/import-embed-outage.test.ts
new file mode 100644
index 0000000000..0b8cc00c5a
--- /dev/null
+++ b/test/import-embed-outage.test.ts
@@ -0,0 +1,65 @@
+/**
+ * An embedding outage must not block the text write.
+ *
+ * importFromContent embeds inline before its canonical transaction. A provider
+ * failure (outage, rate limit, missing key) used to throw before the page was
+ * stored. Now the page text and chunks commit with NULL vectors, no embedding
+ * signature is stamped, the result reports `embedding_deferred`, and the stale
+ * sweep embeds the chunks once the provider recovers.
+ *
+ * PGLite in-memory; the "provider" is a gateway stub that throws ($0).
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent, importCodeFile } from '../src/core/import-file.ts';
+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+
+afterAll(async () => {
+ resetGateway();
+ if (engine) await engine.disconnect();
+}, 60_000);
+
+describe('embedding outage', () => {
+ test('text and chunks persist with NULL vectors and the result says the embedding is deferred', async () => {
+ const r = await withEnv({ OPENAI_API_KEY: undefined }, async () => {
+ resetGateway();
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });
+ return importFromContent(engine, 'notes/decision', `---\ntitle: Decision\n---\n\nWe chose vendor B for the widget.\n`, {});
+ });
+ expect(r.status).toBe('imported');
+ expect(r.embedding_deferred).toBe(true);
+ const pages = await engine.executeRaw<{ compiled_truth: string; embedding_signature: string | null }>(
+ `SELECT compiled_truth, embedding_signature FROM pages WHERE slug = 'notes/decision'`);
+ expect(pages).toHaveLength(1);
+ expect(pages[0].compiled_truth).toContain('vendor B');
+ expect(pages[0].embedding_signature).toBeNull();
+ const chunks = await engine.executeRaw<{ n: number; embedded: number }>(
+ `SELECT count(*)::int AS n, count(c.embedding)::int AS embedded
+ FROM content_chunks c JOIN pages p ON p.id = c.page_id WHERE p.slug = 'notes/decision'`);
+ expect(chunks[0].n).toBeGreaterThan(0);
+ expect(chunks[0].embedded).toBe(0);
+ expect(await engine.countStaleChunks({ sourceId: 'default' })).toBeGreaterThan(0);
+ });
+
+ test('a code file whose embedding failed is not stamped as embedded with the current model', async () => {
+ const r = await withEnv({ OPENAI_API_KEY: undefined }, async () => {
+ resetGateway();
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });
+ return importCodeFile(engine, 'src/widget.ts', 'export function widget(): number {\n return 42;\n}\n', {});
+ });
+ expect(r.status).toBe('imported');
+ const [page] = await engine.executeRaw<{ embedding_signature: string | null }>(
+ `SELECT embedding_signature FROM pages WHERE source_path = 'src/widget.ts'`);
+ expect(page.embedding_signature).toBeNull();
+ });
+});
diff --git a/test/import-identity-move.test.ts b/test/import-identity-move.test.ts
new file mode 100644
index 0000000000..982994e04f
--- /dev/null
+++ b/test/import-identity-move.test.ts
@@ -0,0 +1,152 @@
+/**
+ * frontmatter.id identity dedup must never drop content or delete a live file's page.
+ *
+ * - A shared `id:` with DIFFERENT content is a distinct note, not a duplicate:
+ * it imports (template reuse, copy-paste), and editing one of two pages that
+ * already share an id is never frozen by the other page.
+ * - A file that MOVED (its recorded source_path is gone from disk) carries its
+ * page: the row is renamed in place so page id, links and facts survive, and
+ * a full sync's delete-reconcile no longer soft-deletes the only live page.
+ * - Same id + same content while the recorded file still exists stays the
+ * #1309 overlapping-roots skip.
+ *
+ * PGLite in-memory, no embeddings ($0).
+ */
+
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { mkdtempSync, writeFileSync, mkdirSync, renameSync } from 'fs';
+import { execSync } from 'child_process';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent, importFromFile } from '../src/core/import-file.ts';
+import { runSources } from '../src/commands/sources.ts';
+import { performSync } from '../src/commands/sync.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+
+afterAll(async () => {
+ if (engine) await engine.disconnect();
+}, 60_000);
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+});
+
+const page = (id: string, body: string) => `---\ntype: concept\ntitle: T\nid: ${id}\n---\n\n${body}\n`;
+
+const liveSlugs = async (sourceId = 'default') =>
+ (await engine.executeRaw<{ slug: string }>(
+ `SELECT slug FROM pages WHERE source_id = $1 AND deleted_at IS NULL ORDER BY slug`, [sourceId],
+ )).map(r => r.slug);
+
+function gitRepo(prefix: string): string {
+ const repo = mkdtempSync(join(tmpdir(), prefix));
+ execSync('git init -q && git config user.email t@t && git config user.name t', { cwd: repo });
+ return repo;
+}
+
+describe('frontmatter.id dedup compares content', () => {
+ test('different content sharing an id imports as its own page', async () => {
+ const a = await importFromContent(engine, 'notes/a', page('tmpl-1', 'Alpha content about widgets.'), { noEmbed: true });
+ const b = await importFromContent(engine, 'notes/b', page('tmpl-1', 'Totally different beta content about gadgets.'), { noEmbed: true });
+ expect(a.status).toBe('imported');
+ expect(b.status).toBe('imported');
+ expect(b.slug).toBe('notes/b');
+ expect(await liveSlugs()).toEqual(['notes/a', 'notes/b']);
+ const [row] = await engine.executeRaw<{ compiled_truth: string }>(`SELECT compiled_truth FROM pages WHERE slug = 'notes/b'`);
+ expect(row.compiled_truth).toContain('beta content about gadgets');
+ });
+
+ test('editing the later of two pages that already share an id lands the edit', async () => {
+ await importFromContent(engine, 'notes/a', page('shared', 'First page body.'), { noEmbed: true });
+ await importFromContent(engine, 'notes/b', page('shared', 'Second page body.'), { noEmbed: true });
+ const edit = await importFromContent(engine, 'notes/b', page('shared', 'Second page body, edited.'), { noEmbed: true });
+ expect(edit.status).toBe('imported');
+ expect(edit.slug).toBe('notes/b');
+ const [row] = await engine.executeRaw<{ compiled_truth: string }>(`SELECT compiled_truth FROM pages WHERE slug = 'notes/b'`);
+ expect(row.compiled_truth).toContain('edited');
+ });
+
+ test('same id and same content while the recorded file still exists skips', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'idmove-dup-'));
+ mkdirSync(join(root, 'subdir'), { recursive: true });
+ writeFileSync(join(root, 'subdir/note.md'), page('granola-1', 'Meeting notes.'));
+ writeFileSync(join(root, 'note.md'), page('granola-1', 'Meeting notes.'));
+ const first = await importFromFile(engine, join(root, 'subdir/note.md'), 'subdir/note.md', { noEmbed: true });
+ expect(first.status).toBe('imported');
+ const second = await importFromFile(engine, join(root, 'note.md'), 'note.md', { noEmbed: true });
+ expect(second.status).toBe('skipped');
+ expect(second.slug).toBe('subdir/note');
+ expect(await liveSlugs()).toEqual(['subdir/note']);
+ });
+
+ test('overlapping import roots converge on one page', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'idmove-roots-'));
+ mkdirSync(join(root, 'subdir'), { recursive: true });
+ writeFileSync(join(root, 'subdir/note.md'), page('granola-2', 'Meeting notes.'));
+ await importFromFile(engine, join(root, 'subdir/note.md'), 'note.md', { noEmbed: true });
+ await importFromFile(engine, join(root, 'subdir/note.md'), 'subdir/note.md', { noEmbed: true });
+ expect(await liveSlugs()).toEqual(['subdir/note']);
+ });
+
+ test('engine prefers the frontmatter.id match over a content_hash match and excludes the caller slug', async () => {
+ await engine.putPage('x/hash-twin', {
+ type: 'concept', title: 'X', compiled_truth: 'x', frontmatter: { type: 'concept' }, content_hash: 'h1',
+ });
+ await engine.putPage('y/id-twin', {
+ type: 'concept', title: 'Y', compiled_truth: 'y', frontmatter: { type: 'concept', id: 'ext-1' }, content_hash: 'h2',
+ });
+ const dup = await engine.findDuplicatePage!('default', { hash: 'h1', frontmatterId: 'ext-1' });
+ expect(dup?.slug).toBe('y/id-twin');
+ const self = await engine.findDuplicatePage!('default', { hash: 'h2', frontmatterId: 'ext-1', excludeSlug: 'y/id-twin' });
+ expect(self).toBeNull();
+ });
+});
+
+describe('a moved file carries its page', () => {
+ test('full sync after moving a file with frontmatter.id keeps exactly one live page at the new path', async () => {
+ await runSources(engine, ['add', 'mv-src', '--no-federated']);
+ const repo = gitRepo('idmove-sync-');
+ mkdirSync(join(repo, 'inbox'), { recursive: true });
+ mkdirSync(join(repo, 'meetings'), { recursive: true });
+ writeFileSync(join(repo, 'inbox/standup.md'), page('uuid-123', 'Standup notes: ship the widget on Friday.'));
+ writeFileSync(join(repo, 'meetings/other.md'), page('uuid-999', 'Unrelated.'));
+ execSync('git add -A && git commit -qm init', { cwd: repo });
+ await performSync(engine, { repoPath: repo, full: true, sourceId: 'mv-src', noPull: true, noEmbed: true });
+ const [before] = await engine.executeRaw<{ id: number }>(`SELECT id FROM pages WHERE source_id = 'mv-src' AND slug = 'inbox/standup'`);
+
+ renameSync(join(repo, 'inbox/standup.md'), join(repo, 'meetings/standup.md'));
+ execSync('git add -A && git commit -qm move', { cwd: repo });
+ await performSync(engine, { repoPath: repo, full: true, sourceId: 'mv-src', noPull: true, noEmbed: true });
+
+ expect(await liveSlugs('mv-src')).toEqual(['meetings/other', 'meetings/standup']);
+ const [after] = await engine.executeRaw<{ id: number; source_path: string }>(
+ `SELECT id, source_path FROM pages WHERE source_id = 'mv-src' AND slug = 'meetings/standup'`);
+ expect(Number(after.id)).toBe(Number(before.id));
+ expect(after.source_path).toBe('meetings/standup.md');
+ }, 60_000);
+
+ test('a moved and edited file lands its new content on the carried page', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'idmove-edit-'));
+ mkdirSync(join(root, 'inbox'), { recursive: true });
+ mkdirSync(join(root, 'archive'), { recursive: true });
+ writeFileSync(join(root, 'inbox/plan.md'), page('uuid-plan', 'Draft plan.'));
+ await importFromFile(engine, join(root, 'inbox/plan.md'), 'inbox/plan.md', { noEmbed: true });
+ renameSync(join(root, 'inbox/plan.md'), join(root, 'archive/plan.md'));
+ writeFileSync(join(root, 'archive/plan.md'), page('uuid-plan', 'Final plan, approved.'));
+ const moved = await importFromFile(engine, join(root, 'archive/plan.md'), 'archive/plan.md', { noEmbed: true });
+ expect(moved.status).toBe('imported');
+ expect(moved.slug).toBe('archive/plan');
+ expect(await liveSlugs()).toEqual(['archive/plan']);
+ const [row] = await engine.executeRaw<{ compiled_truth: string }>(`SELECT compiled_truth FROM pages WHERE slug = 'archive/plan'`);
+ expect(row.compiled_truth).toContain('approved');
+ });
+});
diff --git a/test/import-image-retry.test.ts b/test/import-image-retry.test.ts
new file mode 100644
index 0000000000..09755933ad
--- /dev/null
+++ b/test/import-image-retry.test.ts
@@ -0,0 +1,92 @@
+/**
+ * An image imported without its visual vector or OCR text is retried.
+ *
+ * The image hash-skip used to key on the byte hash alone, so an image first
+ * imported under --no-embed, an OCR budget skip, or an OCR provider error kept
+ * filename-only text and no visual vector until its bytes changed. The skip
+ * now also requires the index to be complete for what this run would build,
+ * and the page records its repo-relative source_path on every path.
+ *
+ * PGLite in-memory; the Voyage provider is a fetch stub ($0).
+ */
+
+import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';
+import { mkdtempSync, writeFileSync, mkdirSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importImageFile } from '../src/core/import-file.ts';
+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+
+const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', 'base64');
+
+let engine: PGLiteEngine;
+let embedCalls = 0;
+const origFetch = globalThis.fetch;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+
+beforeEach(() => {
+ globalThis.fetch = (async () => {
+ embedCalls++;
+ return new Response(JSON.stringify({
+ data: [{ embedding: Array.from({ length: 1024 }, () => 0.1), index: 0 }], model: 'voyage-multimodal-3',
+ }), { status: 200, headers: { 'Content-Type': 'application/json' } });
+ }) as unknown as typeof fetch;
+});
+
+afterEach(() => {
+ globalThis.fetch = origFetch;
+ resetGateway();
+});
+
+afterAll(async () => {
+ if (engine) await engine.disconnect();
+}, 60_000);
+
+const configureVoyage = () => configureGateway({
+ embedding_model: 'voyage:voyage-multimodal-3',
+ embedding_multimodal_model: 'voyage:voyage-multimodal-3',
+ embedding_dimensions: 1024,
+ env: { VOYAGE_API_KEY: 'test-key' },
+});
+
+const imageRow = (slug: string) => engine.executeRaw<{ source_path: string | null; has_vec: boolean }>(
+ `SELECT p.source_path, c.embedding_image IS NOT NULL AS has_vec
+ FROM pages p JOIN content_chunks c ON c.page_id = p.id WHERE p.slug = $1`, [slug]);
+
+describe('image index retry', () => {
+ test('an image first imported without a visual vector gets one on the next import, then skips', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'img-retry-'));
+ mkdirSync(join(dir, 'photos'));
+ writeFileSync(join(dir, 'photos/whiteboard.png'), PNG);
+ const file = join(dir, 'photos/whiteboard.png');
+
+ const first = await importImageFile(engine, file, 'photos/whiteboard.png', { noEmbed: true });
+ expect(first.status).toBe('imported');
+ expect((await imageRow('photos/whiteboard.png'))[0]).toEqual({ source_path: 'photos/whiteboard.png', has_vec: false });
+
+ configureVoyage();
+ embedCalls = 0;
+ const second = await importImageFile(engine, file, 'photos/whiteboard.png', {});
+ expect(second.status).toBe('imported');
+ expect(embedCalls).toBe(1);
+ expect((await imageRow('photos/whiteboard.png'))[0].has_vec).toBe(true);
+
+ const third = await importImageFile(engine, file, 'photos/whiteboard.png', {});
+ expect(third.status).toBe('skipped');
+ expect(embedCalls).toBe(1);
+ });
+
+ test('a --no-embed re-import of an unchanged image still skips', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'img-noembed-'));
+ writeFileSync(join(dir, 'chart.png'), PNG);
+ await importImageFile(engine, join(dir, 'chart.png'), 'chart.png', { noEmbed: true });
+ const again = await importImageFile(engine, join(dir, 'chart.png'), 'chart.png', { noEmbed: true });
+ expect(again.status).toBe('skipped');
+ });
+});
diff --git a/test/import-slug-collision.test.ts b/test/import-slug-collision.test.ts
new file mode 100644
index 0000000000..3312bb10cb
--- /dev/null
+++ b/test/import-slug-collision.test.ts
@@ -0,0 +1,107 @@
+/**
+ * Two files that slugify to the same slug must not overwrite each other.
+ *
+ * `notes/Foo Bar.md` and `notes/foo-bar.md` both map to `notes/foo-bar`. The
+ * file named exactly like the slug owns it (the file the link extractor reads
+ * for that slug); between two other files the one that already owns the row
+ * keeps it. The other file is skipped with skip_reason 'slug_collision' and a
+ * warning naming both paths, on every sync, so an edit to either file never
+ * flips the page to the other body.
+ *
+ * PGLite in-memory, no embeddings ($0).
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { mkdtempSync, writeFileSync, mkdirSync, appendFileSync, renameSync } from 'fs';
+import { execSync } from 'child_process';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromFile } from '../src/core/import-file.ts';
+import { runSources } from '../src/commands/sources.ts';
+import { performSync } from '../src/commands/sync.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await runSources(engine, ['add', 'co', '--no-federated']);
+}, 60_000);
+
+afterAll(async () => {
+ if (engine) await engine.disconnect();
+}, 60_000);
+
+const rows = () => engine.executeRaw<{ slug: string; title: string; source_path: string; compiled_truth: string }>(
+ `SELECT slug, title, source_path, compiled_truth FROM pages WHERE source_id = 'co' AND deleted_at IS NULL ORDER BY slug`,
+);
+
+describe('slug collisions', () => {
+ test('the owning file keeps the page across syncs and edits to either file', async () => {
+ const repo = mkdtempSync(join(tmpdir(), 'collide-'));
+ execSync('git init -q && git config user.email t@t && git config user.name t', { cwd: repo });
+ mkdirSync(join(repo, 'notes'));
+ writeFileSync(join(repo, 'notes/Foo Bar.md'), `---\ntitle: One\n---\nFirst note about apples.\n`);
+ writeFileSync(join(repo, 'notes/foo-bar.md'), `---\ntitle: Two\n---\nSecond note about oranges.\n`);
+ execSync('git add -A && git commit -qm init', { cwd: repo });
+ const sync = () => performSync(engine, { repoPath: repo, sourceId: 'co', noPull: true, noEmbed: true });
+
+ await sync();
+ const first = await rows();
+ expect(first).toHaveLength(1);
+ const owner = first[0].source_path;
+ const ownerTitle = first[0].title;
+
+ const other = owner === 'notes/Foo Bar.md' ? 'notes/foo-bar.md' : 'notes/Foo Bar.md';
+ appendFileSync(join(repo, other), 'an edit to the file that does not own the page\n');
+ execSync('git commit -qam edit', { cwd: repo });
+ await sync();
+ const second = await rows();
+ expect(second).toHaveLength(1);
+ expect(second[0].source_path).toBe(owner);
+ expect(second[0].title).toBe(ownerTitle);
+ }, 60_000);
+
+ test('the losing file reports a slug_collision skip and the slug-named file keeps the page', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'collide-direct-'));
+ mkdirSync(join(root, 'notes'));
+ writeFileSync(join(root, 'notes/baz-qux.md'), `---\ntitle: Owner\n---\nOwner body.\n`);
+ writeFileSync(join(root, 'notes/Baz Qux.md'), `---\ntitle: Loser\n---\nLoser body.\n`);
+ const a = await importFromFile(engine, join(root, 'notes/baz-qux.md'), 'notes/baz-qux.md', { noEmbed: true });
+ expect(a.status).toBe('imported');
+ const b = await importFromFile(engine, join(root, 'notes/Baz Qux.md'), 'notes/Baz Qux.md', { noEmbed: true });
+ expect(b.status).toBe('skipped');
+ expect(b.skip_reason).toBe('slug_collision');
+ const [page] = await engine.executeRaw<{ title: string }>(`SELECT title FROM pages WHERE slug = 'notes/baz-qux' AND source_id = 'default'`);
+ expect(page.title).toBe('Owner');
+ });
+
+ test('between two other spellings the file that owns the row keeps it', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'collide-owner-'));
+ mkdirSync(join(root, 'notes'));
+ writeFileSync(join(root, 'notes/Quux Note.md'), `---\ntitle: Owner\n---\nOwner body.\n`);
+ writeFileSync(join(root, 'notes/QUUX NOTE.md'), `---\ntitle: Loser\n---\nLoser body.\n`);
+ await importFromFile(engine, join(root, 'notes/Quux Note.md'), 'notes/Quux Note.md', { noEmbed: true });
+ const b = await importFromFile(engine, join(root, 'notes/QUUX NOTE.md'), 'notes/QUUX NOTE.md', { noEmbed: true });
+ expect(b.skip_reason).toBe('slug_collision');
+ const [page] = await engine.executeRaw<{ title: string }>(`SELECT title FROM pages WHERE slug = 'notes/quux-note' AND source_id = 'default'`);
+ expect(page.title).toBe('Owner');
+ });
+
+ test('a file whose recorded owner path is gone takes the page over', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'collide-gone-'));
+ mkdirSync(join(root, 'notes'));
+ writeFileSync(join(root, 'notes/Zed Note.md'), `---\ntitle: Old\n---\nOld body.\n`);
+ await importFromFile(engine, join(root, 'notes/Zed Note.md'), 'notes/Zed Note.md', { noEmbed: true });
+ renameSync(join(root, 'notes/Zed Note.md'), join(root, 'notes/zed-note.md'));
+ writeFileSync(join(root, 'notes/zed-note.md'), `---\ntitle: New\n---\nNew body.\n`);
+ const r = await importFromFile(engine, join(root, 'notes/zed-note.md'), 'notes/zed-note.md', { noEmbed: true });
+ expect(r.status).toBe('imported');
+ const [page] = await engine.executeRaw<{ title: string; source_path: string }>(
+ `SELECT title, source_path FROM pages WHERE slug = 'notes/zed-note' AND source_id = 'default'`);
+ expect(page.title).toBe('New');
+ expect(page.source_path).toBe('notes/zed-note.md');
+ });
+});
diff --git a/test/minions/delegated-execution.serial.test.ts b/test/minions/delegated-execution.serial.test.ts
index 7dbad2a30f..b7be8eff39 100644
--- a/test/minions/delegated-execution.serial.test.ts
+++ b/test/minions/delegated-execution.serial.test.ts
@@ -174,7 +174,10 @@ describe('remote-owned production tool visibility', () => {
}
await expect(invoke('put_page', { slug: 'wiki/agents/HIDDEN', content: 'Replacement' })).rejects.toThrow();
await expect(invoke('add_timeline_entry', { slug: 'wiki/agents/hidden', date: '2026-08-01', summary: 'Unwanted entry' })).rejects.toThrow('outside your write visibility');
- await expect(invoke('put_page', { slug: 'wiki/agents/alias', content: '---\nid: private-fixture-id\n---\nReplacement' })).rejects.toMatchObject({ code: 'permission_denied' });
+ // Echoing the private page's frontmatter.id with different content is not a
+ // duplicate: it writes only the requested visible slug and never the private page.
+ const echoed = await invoke('put_page', { slug: 'wiki/agents/alias', content: '---\nid: private-fixture-id\n---\nReplacement' }) as { slug: string; status: string };
+ expect(echoed).toMatchObject({ slug: 'wiki/agents/alias', status: 'created_or_updated' });
expect((await engine.getPage('wiki/agents/hidden', { sourceId: 'default' }))?.compiled_truth).toContain('private-body-marker');
expect(await engine.getTimeline('wiki/agents/hidden', { sourceId: 'default' })).toHaveLength(0);
await engine.softDeletePage('wiki/agents/hidden', { sourceId: 'default' });
diff --git a/test/put-page-dedup-fence.test.ts b/test/put-page-dedup-fence.test.ts
index de6297389c..869780e702 100644
--- a/test/put-page-dedup-fence.test.ts
+++ b/test/put-page-dedup-fence.test.ts
@@ -38,6 +38,7 @@ let victimRevision: string;
const VICTIM_SLUG = 'people/alice-example';
const VICTIM_ID = 'external-uuid-victim';
+const VICTIM_BODY = 'Confidential.';
function put(): Operation {
const found = operations.find(o => o.name === 'put_page');
@@ -72,9 +73,14 @@ function boundAuth(prefixes: string[]): AuthInfo {
};
}
-/** The attacker's move: echo the victim's frontmatter id under an in-fence slug. */
-async function putEchoingVictimId(ctx: OperationContext, slug: string, id = VICTIM_ID) {
- return withEnv({ GBRAIN_HOME: home }, () => put().handler(ctx, { slug, content: page(id, 'Attacker body, different text.') }));
+/**
+ * The attacker's move: echo the victim's frontmatter id under an in-fence slug.
+ * The dedup redirect only fires for a true duplicate (same id AND same content),
+ * so the echo carries the duplicated body; a different body imports at the
+ * requested slug instead (pinned at the end of this file).
+ */
+async function putEchoingVictimId(ctx: OperationContext, slug: string, id = VICTIM_ID, body = VICTIM_BODY) {
+ return withEnv({ GBRAIN_HOME: home }, () => put().handler(ctx, { slug, content: page(id, body) }));
}
async function expectFenced(p: Promise<unknown>): Promise<void> {
@@ -108,7 +114,7 @@ beforeEach(async () => {
await engine.executeRaw(`INSERT INTO oauth_clients(client_id,client_name,scope,source_id,federated_read,bound_slug_prefixes,bound_tools,delegated_slug_prefixes,bound_source_id,bound_max_concurrent)
VALUES('gbrain_cl_dedup_fence','Example dedup client','read write agent','default',$1,$2,$3,$4,'default',1)`,
[['default'], ['emp-bob/'], ['put_page'], ['emp-bob/*']]);
- const victim = await importFromContent(engine, VICTIM_SLUG, page(VICTIM_ID, 'Confidential.'), {
+ const victim = await importFromContent(engine, VICTIM_SLUG, page(VICTIM_ID, VICTIM_BODY), {
noEmbed: true,
sourceId: 'default',
});
@@ -160,7 +166,7 @@ describe('put_page: dedup-resolved slug is fenced by the caller\'s own confineme
subagentId: 7,
allowedSlugPrefixes: ['wiki/agents/7/*'],
});
- const r = await putEchoingVictimId(ctx, 'wiki/agents/7/second', 'in-fence-id') as {
+ const r = await putEchoingVictimId(ctx, 'wiki/agents/7/second', 'in-fence-id', 'Body.') as {
slug: string; status: string;
};
expect(r.status).toBe('duplicate');
@@ -177,7 +183,7 @@ describe('put_page: dedup-resolved slug is fenced by the caller\'s own confineme
expect(inFence.status).toBe('imported');
const ctx = makeCtx({ auth: boundAuth(['emp-bob/']) });
- const r = await putEchoingVictimId(ctx, 'emp-bob/second', 'bob-id') as {
+ const r = await putEchoingVictimId(ctx, 'emp-bob/second', 'bob-id', 'Body.') as {
slug: string; status: string;
};
expect(r.status).toBe('duplicate');
@@ -200,4 +206,14 @@ describe('put_page: dedup-resolved slug is fenced by the caller\'s own confineme
expect(r.slug).toBe(VICTIM_SLUG);
expect((await engine.readPageSnapshot(VICTIM_SLUG, { sourceId: 'default' }))!.revision).toBe(victimRevision);
});
+
+ test('an id echo with different content writes only the requested slug', async () => {
+ const ctx = makeCtx({ auth: boundAuth(['emp-bob/']) });
+ const r = await putEchoingVictimId(ctx, 'emp-bob/notes', VICTIM_ID, 'Attacker body, different text.') as {
+ slug: string; status: string;
+ };
+ expect(r.slug).toBe('emp-bob/notes');
+ expect(r.status).not.toBe('duplicate');
+ expect((await engine.readPageSnapshot(VICTIM_SLUG, { sourceId: 'default' }))!.revision).toBe(victimRevision);
+ });
});
diff --git a/test/rename-slug-alias.test.ts b/test/rename-slug-alias.test.ts
new file mode 100644
index 0000000000..fe73a1441e
--- /dev/null
+++ b/test/rename-slug-alias.test.ts
@@ -0,0 +1,94 @@
+/**
+ * Renames leave a slug alias, and links written against the old slug keep
+ * resolving.
+ *
+ * updateSlug only rewrote pages.slug, so nothing recorded where a page went:
+ * `[[people/alice-example]]` in a referrer stopped resolving after the page was
+ * renamed, and any replace-semantics link pass (put_page, sync) then deleted
+ * the inbound edge. updateSlug now records `slug_aliases(old -> new)` in the
+ * same transaction (repointing aliases that named the old slug), and both the
+ * DB resolver and file-sync extraction resolve through it.
+ *
+ * PGLite in-memory, no embeddings ($0).
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { mkdtempSync, writeFileSync, mkdirSync, appendFileSync } from 'fs';
+import { execSync } from 'child_process';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { makeResolver } from '../src/core/link-extraction.ts';
+import { runSources } from '../src/commands/sources.ts';
+import { performSync } from '../src/commands/sync.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await runSources(engine, ['add', 'rl', '--no-federated']);
+}, 60_000);
+
+afterAll(async () => {
+ if (engine) await engine.disconnect();
+}, 60_000);
+
+const aliases = (sourceId: string) => engine.executeRaw<{ alias_slug: string; canonical_slug: string }>(
+ `SELECT alias_slug, canonical_slug FROM slug_aliases WHERE source_id = $1 ORDER BY alias_slug`, [sourceId]);
+
+describe('updateSlug records an alias', () => {
+ test('a rename writes old -> new and repoints earlier aliases', async () => {
+ await importFromContent(engine, 'people/bob-example', `---\ntype: person\ntitle: Bob Example\n---\n\nBob.\n`, { noEmbed: true });
+ expect(await engine.updateSlug('people/bob-example', 'people/bob-example-2')).toBe(1);
+ expect(await engine.updateSlug('people/bob-example-2', 'people/bob-example-3')).toBe(1);
+ expect(await aliases('default')).toEqual([
+ { alias_slug: 'people/bob-example', canonical_slug: 'people/bob-example-3' },
+ { alias_slug: 'people/bob-example-2', canonical_slug: 'people/bob-example-3' },
+ ]);
+ const r = makeResolver(engine, { mode: 'batch', sourceId: 'default' });
+ expect(await r.resolve('people/bob-example')).toBe('people/bob-example-3');
+ expect(await engine.resolveSlugWithAlias('people/bob-example', 'default')).toBe('people/bob-example-3');
+ });
+
+ test('renaming back onto an aliased slug drops the self-referencing alias', async () => {
+ await importFromContent(engine, 'people/carol-example', `---\ntype: person\ntitle: Carol Example\n---\n\nCarol.\n`, { noEmbed: true });
+ await engine.updateSlug('people/carol-example', 'people/carol-example-2');
+ await engine.updateSlug('people/carol-example-2', 'people/carol-example');
+ expect((await aliases('default')).filter(a => a.alias_slug.startsWith('people/carol'))).toEqual([
+ { alias_slug: 'people/carol-example-2', canonical_slug: 'people/carol-example' },
+ ]);
+ });
+});
+
+describe('sync keeps inbound edges across a rename', () => {
+ test('editing the referrer after a rename keeps its edge to the renamed page', async () => {
+ const repo = mkdtempSync(join(tmpdir(), 'rename-alias-'));
+ execSync('git init -q && git config user.email t@t && git config user.name t', { cwd: repo });
+ mkdirSync(join(repo, 'notes'));
+ mkdirSync(join(repo, 'people'));
+ writeFileSync(join(repo, 'notes/seed.md'), `---\ntype: note\ntitle: Seed\n---\n\nseed\n`);
+ execSync('git add -A && git commit -qm seed', { cwd: repo });
+ const sync = () => performSync(engine, { repoPath: repo, sourceId: 'rl', noPull: true, noEmbed: true });
+ await sync();
+ writeFileSync(join(repo, 'notes/a.md'), `---\ntype: note\ntitle: A\n---\n\nMet with [[people/alice-example]] about the widget.\n`);
+ writeFileSync(join(repo, 'people/alice-example.md'), `---\ntype: person\ntitle: Alice Example\n---\n\nAlice is an engineer.\n`);
+ execSync('git add -A && git commit -qm add', { cwd: repo });
+ await sync();
+ const edges = async () => (await engine.executeRaw<{ t: string }>(
+ `SELECT t.slug t FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id
+ WHERE f.source_id = 'rl' AND f.slug = 'notes/a' ORDER BY 1`)).map(r => r.t);
+ expect(await edges()).toEqual(['people/alice-example']);
+
+ execSync('git mv people/alice-example.md people/alice-example-2.md && git commit -qm mv', { cwd: repo });
+ await sync();
+ expect(await aliases('rl')).toEqual([{ alias_slug: 'people/alice-example', canonical_slug: 'people/alice-example-2' }]);
+
+ appendFileSync(join(repo, 'notes/a.md'), `\nFollow-up: shipped.\n`);
+ execSync('git commit -qam edit', { cwd: repo });
+ await sync();
+ expect(await edges()).toEqual(['people/alice-example-2']);
+ }, 60_000);
+});
diff --git a/test/sync-derived-reconcile.test.ts b/test/sync-derived-reconcile.test.ts
new file mode 100644
index 0000000000..6a703b1e01
--- /dev/null
+++ b/test/sync-derived-reconcile.test.ts
@@ -0,0 +1,109 @@
+/**
+ * File-sync extraction reconciles derived links and timeline rows.
+ *
+ * Link extraction on the sync paths (sync's inline hook and the cycle's
+ * incremental extract) used to be add-only, so a removed wikilink kept its
+ * edge, and a corrected dated bullet kept the old timeline row next to the new
+ * one. Both paths now replace a page's own markdown-derived links (as MCP
+ * put_page does) and retract the timeline rows its previous text produced but
+ * its current text no longer does. Rows from other producers survive.
+ *
+ * PGLite in-memory, no embeddings ($0).
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { mkdtempSync, writeFileSync, mkdirSync } from 'fs';
+import { execSync } from 'child_process';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runSources } from '../src/commands/sources.ts';
+import { performSync } from '../src/commands/sync.ts';
+import { runExtractCore } from '../src/commands/extract.ts';
+import { importFromFile } from '../src/core/import-file.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await runSources(engine, ['add', 'dr', '--no-federated']);
+ await runSources(engine, ['add', 'cy', '--no-federated']);
+}, 60_000);
+
+afterAll(async () => {
+ if (engine) await engine.disconnect();
+}, 60_000);
+
+const links = async (sourceId: string) => (await engine.executeRaw<{ f: string; t: string }>(
+ `SELECT f.slug f, t.slug t FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id
+ WHERE f.source_id = $1 ORDER BY 1, 2`, [sourceId])).map(r => `${r.f}->${r.t}`);
+
+const timeline = async (sourceId: string, slug: string) => (await engine.executeRaw<{ d: string; summary: string }>(
+ `SELECT t.date::text d, t.summary FROM timeline_entries t JOIN pages p ON p.id = t.page_id
+ WHERE p.source_id = $1 AND p.slug = $2 ORDER BY 1, 2`, [sourceId, slug])).map(r => `${r.d} ${r.summary}`);
+
+const note = (body: string) => `---\ntype: note\ntitle: A\n---\n\n${body}\n`;
+const person = (bullet: string) =>
+ `---\ntype: person\ntitle: Alice Example\n---\n\nAlice is an engineer.\n\n<!-- timeline -->\n\n## Timeline\n\n${bullet}\n`;
+
+function gitRepo(): string {
+ const repo = mkdtempSync(join(tmpdir(), 'derived-reconcile-'));
+ execSync('git init -q && git config user.email t@t && git config user.name t', { cwd: repo });
+ mkdirSync(join(repo, 'notes'));
+ mkdirSync(join(repo, 'people'));
+ writeFileSync(join(repo, 'people/bob-example.md'), `---\ntype: person\ntitle: Bob Example\n---\n\nBob is a designer.\n`);
+ return repo;
+}
+
+describe('sync inline extraction', () => {
+ test('removing a wikilink removes its edge and correcting a bullet replaces its timeline row', async () => {
+ const repo = gitRepo();
+ const sync = () => performSync(engine, { repoPath: repo, sourceId: 'dr', noPull: true, noEmbed: true });
+ execSync('git add -A && git commit -qm seed', { cwd: repo });
+ await sync();
+ writeFileSync(join(repo, 'notes/a.md'), note('Met with [[people/alice-example]] and [[people/bob-example]] about the widget.'));
+ writeFileSync(join(repo, 'people/alice-example.md'), person('- **2024-03-01** | Joined acme-example as CTO'));
+ execSync('git add -A && git commit -qm add', { cwd: repo });
+ await sync();
+ expect(await links('dr')).toEqual(['notes/a->people/alice-example', 'notes/a->people/bob-example']);
+ expect(await timeline('dr', 'people/alice-example')).toEqual(['2024-03-01 Joined acme-example as CTO']);
+
+ await engine.addTimelineEntry('people/alice-example', { date: '2023-01-01', source: 'enrichment', summary: 'Mentioned in a board memo' }, { sourceId: 'dr' });
+
+ writeFileSync(join(repo, 'notes/a.md'), note('Met with [[people/alice-example]] about the widget.'));
+ writeFileSync(join(repo, 'people/alice-example.md'), person('- **2024-04-01** | Joined acme-example as VP Eng'));
+ execSync('git commit -qam edit', { cwd: repo });
+ await sync();
+ expect(await links('dr')).toEqual(['notes/a->people/alice-example']);
+ expect(await timeline('dr', 'people/alice-example')).toEqual([
+ '2023-01-01 Mentioned in a board memo',
+ '2024-04-01 Joined acme-example as VP Eng',
+ ]);
+ }, 60_000);
+});
+
+describe('cycle incremental extraction', () => {
+ test('the slug-scoped extract replaces links and retracts removed timeline rows', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'derived-cycle-'));
+ mkdirSync(join(dir, 'notes'));
+ mkdirSync(join(dir, 'people'));
+ const write = async (rel: string, body: string) => {
+ writeFileSync(join(dir, rel), body);
+ await importFromFile(engine, join(dir, rel), rel, { noEmbed: true, sourceId: 'cy' });
+ };
+ const extract = (slugs: string[]) => runExtractCore(engine, { mode: 'all', dir, slugs, sourceId: 'cy', quiet: true });
+ await write('people/bob-example.md', `---\ntype: person\ntitle: Bob Example\n---\n\nBob.\n`);
+ await write('people/carol-example.md', person('- **2024-03-01** | Joined widget-co'));
+ await write('notes/b.md', note('Talked to [[people/bob-example]] and [[people/carol-example]].'));
+ await extract(['notes/b', 'people/carol-example', 'people/bob-example']);
+ expect(await links('cy')).toEqual(['notes/b->people/bob-example', 'notes/b->people/carol-example']);
+
+ await write('notes/b.md', note('Talked to [[people/carol-example]].'));
+ await write('people/carol-example.md', person('- **2024-05-01** | Joined widget-co'));
+ await extract(['notes/b', 'people/carol-example']);
+ expect(await links('cy')).toEqual(['notes/b->people/carol-example']);
+ expect(await timeline('cy', 'people/carol-example')).toEqual(['2024-05-01 Joined widget-co']);
+ }, 60_000);
+});
diff --git a/test/sync-rename-reconcile.serial.test.ts b/test/sync-rename-reconcile.serial.test.ts
index aa79691250..3d0375676b 100644
--- a/test/sync-rename-reconcile.serial.test.ts
+++ b/test/sync-rename-reconcile.serial.test.ts
@@ -152,12 +152,12 @@ describe('#3056: rename fallback reconciles the stale old row', () => {
expect(staleRows[0].deleted_at).not.toBeNull();
});
- test('dedup-skip against the old row must NOT reconcile: the only copy survives', async () => {
+ test('identity match against the old row never loses the only copy', async () => {
const { performSync } = await import('../src/commands/sync.ts');
- // frontmatter.id gives identity dedup a handle: the import at the new
- // path can skip as "identical to <old row>" — in which case NOTHING
- // landed at the destination and deleting the old row would destroy the
- // only copy of the content.
+ // frontmatter.id gives identity dedup a handle on the old row. The old
+ // file is gone, so the import at the new path is a move, never a
+ // "duplicate" skip: the renamed content lands at the destination and the
+ // old row may then be reconciled. Exactly one live copy must remain.
const md = ['---', 'type: person', 'title: Carol', 'id: ext-3056', '---', '', 'Carol is a person.'].join('\n');
const repo = mkRepo({ 'people/carol.md': md });
await performSync(engine, { repoPath: repo, ...SYNC_OPTS });
@@ -173,14 +173,13 @@ describe('#3056: rename fallback reconciles the stale old row', () => {
await performSync(engine, { repoPath: repo, ...SYNC_OPTS });
- // The import skipped against the OLD row (identity dedup), so the
- // destination never materialized with the renamed content — the
- // reconcile must not have deleted the old row, which still holds the
- // only copy.
- const carol = await engine.getPage('people/carol');
- expect(carol).not.toBeNull();
- expect(carol!.compiled_truth).toContain('Carol is a person.');
- expect((await engine.getPage('people/dana'))!.compiled_truth).toBe('occupies the destination slug');
+ const copies = await engine.executeRaw<{ slug: string; compiled_truth: string }>(
+ `SELECT slug, compiled_truth FROM pages
+ WHERE source_id = 'default' AND deleted_at IS NULL AND frontmatter->>'id' = 'ext-3056'`,
+ );
+ expect(copies).toHaveLength(1);
+ expect(copies[0].slug).toBe('people/dana');
+ expect(copies[0].compiled_truth).toContain('Carol is a person.');
});
test('reconcile never deletes by slug guess: unrelated manual row survives', async () => {