Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.58.0.0 feat: evidence-bound attendance, opt-in recall packing, gated repair (#5458)

Garry Tana610db7b7243
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 8baffc5fa7..4ba72c8633 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.57.1.0",
+ "version": "0.58.0.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 1ad43161e7..621738d0bb 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.57.1.0",
+ "version": "0.58.0.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 cfca2e7c5b..9a3a4ff820 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -1,4 +1,4 @@
-<!-- gbrain-runbook-stamp: 0.57.1.0 -->
+<!-- gbrain-runbook-stamp: 0.58.0.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 64702ea1a6..704464f583 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,89 @@ 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.58.0.0] - 2026-09-24
+
+**Separate confirmed attendance from mentions, and give question evidence room in recall.**
+
+Meeting notes often name people who were invited, absent, or simply discussed.
+When your active schema does not define its own attendance rules, GBrain now
+requires an explicit attendee list with confirmed person references before
+recording attendance. Mentioning someone elsewhere in a note is not enough.
+Examples in code blocks and hidden comments do not count either.
+
+For a question about your notes, you can now give matching pages first use of
+recall's limited reading budget. Stored facts fill the remaining space. The
+existing facts-first default stays unchanged because questions about those
+facts can get worse when pages take their place.
+
+Historical attendance cleanup is a separate, local-only operation. Preview a
+small source-scoped window, review its proposed changes, then approve that
+exact preview only after verifying a full database backup. Upgrading alone
+does not authorize or run this repair.
+
+### Try question-first recall
+
+```bash
+gbrain recall --query 'What did the planning meeting decide?' \
+ --budget-tokens 512 --budget-policy query_first --json
+```
+
+The same `budget_policy` option is available on the `recall` memory verb.
+Omit it to retain existing behavior, or explicitly select `facts_first`.
+
+| Controlled comparison | Complete evidence with the default | With the selected policy |
+| --- | --- | --- |
+| Eleven synthetic page-evidence questions | 1 of 11 | 9 of 11 with query-first |
+| Three fact-focused controls | 3 of 3 | 3 of 3 with facts-first |
+| One deliberately misrouted fact question | 1 of 1 | 0 of 1 with query-first |
+
+These are measurements of retained evidence, not generated-answer accuracy or
+a broad semantic-search benchmark. See the [evaluation record](docs/eval/ATTENDANCE_RECALL_EVALUATION.md)
+for the matched baseline, fixture identity and excluded expansion experiment.
+
+### Things to watch
+
+Schema-pack-owned attendance directions remain unchanged, including the shipped
+base and company packs; they do not gain incoming attendance lookup. Missing
+packs or unresolved attendees preserve the prior graph for retry instead of
+guessing. Historical repair requires separate operator approval, briefly locks
+link writes database-wide, and cannot be undone by reverting the binary.
+
+## To take advantage of v0.58.0.0
+
+Follow [the upgrade and verification guide](skills/migrations/v0.58.0.0.md).
+No new schema migration, automatic backfill, provider change or capture opt-in
+is required. Preserve existing service and re-embedding opt-outs. If an earlier
+migration failed, inspect that failure before running
+`gbrain apply-migrations --yes --no-autopilot-install`; that command is not an
+attendance repair. Follow the [attendance operator guide](docs/guides/attendance-evidence.md)
+before previewing or applying historical changes.
+
+### Itemized changes
+
+- **Attendance evidence:** Canonical attendee lists resolve live person pages
+ in the allowed source scope. Origin-owned reconciliation preserves unrelated
+ and manual links, honors each source's schema pack, and keeps incomplete
+ extraction retryable across publication, filesystem, DB, stale and sweep
+ paths. Timeline extraction consumes supported attendance evidence.
+- **Recall packing:** One-shot CLI and memory-verb callers can select
+ `budget_policy: "query_first"` or `"facts_first"`, with explicit packing
+ accounting and matching validation across local and remote transports.
+ Conditional query expansion is not included.
+- **Historical repair:** Trusted-local `extract links --repair-attendance`
+ supports bounded previews, exact-digest approval, private receipts and
+ checkpoints, transactional source/endpoint revalidation, and crash replay.
+ MCP and thin clients cannot run it; `--yes` alone cannot authorize an apply.
+- **Concurrent write admission:** When several tools write at once, PostgreSQL
+ admissions get more time to progress behind short counter transactions.
+ Individual lock waits allow up to 100ms while preserving the five-second
+ retry budget, retained request IDs, and pool access for reads between attempts.
+
+### For contributors
+
+Attendance and repair regressions run against PGLite and PostgreSQL. Each E2E
+file now receives its own temporary HOME and GBRAIN_HOME, preventing one file's
+initialization from changing the schema configuration used by the next file.
## [0.57.1.0] - 2026-09-24
**More capacity for Linux CI, with the same acceptance checks.**
diff --git a/VERSION b/VERSION
index f8e188a18b..440798bf1f 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.57.1.0
+0.58.0.0
diff --git a/docs/TESTING.md b/docs/TESTING.md
index ca46e327f5..1de12c4fb2 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -143,6 +143,12 @@ abort/lock loss, and successful warning-only controls.
### Test command tiers
+The sequential E2E runner gives each test file a fresh `HOME` and `GBRAIN_HOME`.
+Configuration written by a CLI initialization or schema migration remains
+available within that file, but cannot change a later file's selected schema or
+harness state. Each file's home is removed after it exits, including failures;
+the runner's exit trap also cleans up interrupted runs.
+
Test command tiers, each with a clear scope:
| Command | What it runs | Wallclock | When to use |
diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.md
index 181f454ea3..a20980e84d 100644
--- a/docs/architecture/key-files/commands-4.md
+++ b/docs/architecture/key-files/commands-4.md
@@ -47,7 +47,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/quarantine.ts` — `gbrain quarantine <list|clear|scan>` operator surface for the content-quality gate. `list [--json] [--include-flagged]` paginates `listPages` and reports quarantined (HIDDEN) pages, optionally also `content_flag` (FLAGGED, searchable) pages. `clear <slug> [--force] [--no-embed] [--json]` drops both markers and re-imports through the normal pipeline so the page re-chunks + re-embeds and becomes searchable; the gate re-runs on import so genuinely-junk pages re-quarantine (exit 1) unless `--force` sets `GBRAIN_NO_SANITY=1` for that one import. `scan [--limit N] [--apply] [--no-embed] [--json]` re-assesses already-ingested pages so junk predating the gate gets marked (unchanged content short-circuits normal sync, so it never re-assesses otherwise); dry-run uses the SAME effective `content_sanity` config thresholds `--apply` will use, idempotent (skips already-marked pages), `--apply` re-imports with `forceRechunk` to set markers + (for quarantine) drop chunks. Dispatched in `cli.ts`. Pinned by `test/quarantine-cli.test.ts`.
-- `src/commands/recall.ts` — the `gbrain recall` CLI (facts-first read; local engine or thin-client). Entity→text fallback: a bare positional is entity-first, but when the entity arm matches ZERO facts (and no `--grep`/`--supersessions`/`--session-id` narrows the read) the query retries as the SQL-level fact-text grep with a one-line stderr note — so keyless/casual usage (`gbrain recall coffee`) finds the fact either way. One gating predicate + one note formatter (`entityTextFallbackApplies`/`noteEntityTextFallback`) shared by the local path and the thin-client mirror so the two can't drift; explicit `--grep` callers keep exact semantics (their filter already ran, no fallback surprise). `--since` composes with the positional entity and with `--session-id` through `engine.listFactsSince({entitySlug, sessionId})` (one query, cutoff before LIMIT, event time unless `--since-last-run`), mirroring the `recall` op's composition in `src/core/ops/facts.ts`; pinned by `test/facts-recall-since-composition.test.ts`.
+- `src/commands/recall.ts` — the `gbrain recall` CLI (facts-first by default; local engine or thin-client). Optional `--budget-policy facts_first|query_first` routes a one-shot read through the shared operation, forwarding fact filters and using remote recall on thin clients. Enum validation uses the shared operation definition; option order does not affect budget parsing. Only query-first with a nonblank query preserves numeric fractions until server packing; omitted/explicit facts-first keeps legacy integer parsing. The new option rejects watch/cursor/rollup/as-context combinations rather than silently ignoring them. Opt-in selector failures use stamped v1 errors; JSON mode emits structured local and remote errors on stdout with a nonzero exit, preserving remote read-error details without requiring a mutation receipt. Omitted-policy validation and fallback remain unchanged. Entity→text fallback: a bare positional without verb options is entity-first, but when the entity arm matches ZERO facts (and no `--grep`/`--supersessions`/`--session-id` narrows the read), the query retries as SQL-level fact-text grep with a stderr note. One predicate and note formatter are shared by the local path and thin-client mirror; explicit grep callers keep exact semantics. `--since` composes with entity and session in one query before LIMIT, on event time unless `--since-last-run`. Pinned by `test/facts-recall-since-composition.test.ts`, `test/recall-budget-policy-transports.test.ts`, `test/recall-budget-policy-thin-cli.test.ts`, and `test/recall-budget-policy-thin.serial.test.ts`.
- `src/commands/reindex-aliases.ts` — `gbrain reindex --aliases [--limit N] [--dry-run] [--json] [--source <id>]`: backfills the free-text alias layer for EXISTING pages whose frontmatter `aliases:` predate the alias table (the import-time projection covers new + changed pages). Reads each page's frontmatter `aliases:`, writes via `engine.setPageAliases`. Idempotent + convergent (setPageAliases replaces a page's alias set) so no op-checkpoint needed; walks `listAllPageRefs` (cheap cross-source enumeration), `--source` narrows. Pinned by `test/search/reindex-aliases.test.ts`.
diff --git a/docs/architecture/key-files/company-brain.md b/docs/architecture/key-files/company-brain.md
index ec4427660a..ca8da34d1f 100644
--- a/docs/architecture/key-files/company-brain.md
+++ b/docs/architecture/key-files/company-brain.md
@@ -10,5 +10,6 @@ For the operator workflow, see the [company-brain ingestion guide](../../guides/
- `src/commands/company-brain-{inspect,connect,demo}.ts` — dedicated source subcommand parsing and versioned JSON/error output. Inspection is engine-free; connect requires explicit brain/source selection and previews through the existing resident-owner route before a probe-only local connection. Human progress is stderr-scoped for JSON output. `core/company-brain/{demo,sample,evidence,status}.ts` supplies the real-pipeline offline sample, actual source-scoped evidence, and private receipt status without fabricated answers or host-path fields.
- `src/core/{derived-links,link-reconciliation}.ts` — source-qualified, revision-fenced atomic replacement of derived edges; manual rows survive. The source reconciliation API supports bounded cursors, refuses changed endpoints, and resolves no foreign-source fallback. Standard DB extraction passes the same captured endpoint revision fences. `test/derived-link-reconciliation.test.ts` and `test/extract-endpoint-revision.serial.test.ts` cover both engines and rollback/freshness behavior.
+- `src/core/attendance-repair.ts` and `src/commands/extract-attendance-repair.ts` — trusted-local historical attendance preview and exact-receipt apply. Indexed source-page slug windows precede eligibility filtering; explicit Markdown evidence uses capped endpoint and adjacency lookups, while all frontmatter remains report-only and unmaterialized. A narrow `derived-links.ts` delta preserves unrelated row IDs and evidence; brain/source incarnation, page revisions, ontology/parser and affected-edge hashes fence each origin transaction. Existing `op_checkpoints` banks commit proof before the private cursor advances across committed origins and revalidated skipped pages, making interruption replay idempotent. No broad derived replacement, normal-extraction watermark updates, MCP administration or provider calls. Covered by the dual-engine `test/attendance-repair.test.ts` and real CLI `test/attendance-repair-cli.serial.test.ts`; operator contract and limits are in `docs/guides/attendance-evidence.md`.
- `src/core/schema-pack/base/company-brain.yaml` — optional company vocabulary extending `gbrain-base-v2` without normalization rules or maintenance phases. Overrides company aliases and prefixes so product stays a distinct query and path type. Bundled through `schema-pack/bundled.ts` and `bundled-assets.ts`; attribution is in `third-party/company-brain/`. The generic fictional sample in `src/core/company-brain/sample/` preserves the upstream layout and relationship metadata. `test/company-brain-schema.test.ts` pins inherited lint, type closure, folder inference, read-only bundling, and sample references.
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index 24be7e559b..9496a31429 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -53,7 +53,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/persistence/{atom-maintenance,atom-retry,facts-maintenance,facts-prepare,prepared-maintenance}.ts` — resident dispatch for durable atom publication/completion, explicit atom retry, authorized multi-entity fact-fence/backstop append and local synthesize/patterns/consolidation. Accepted output replays provider-free after restart; page/take preparers recheck original/current grants, source incarnation and revisions. Unresolved facts remain DB-only without phantom pages. Retired takes skip; semantic fact snapshots exclude derived vector/cache fields and journal quotas reject overlarge retained intent. Managed consolidation retains the explicit chronological `valid_until` writeback from the legacy consolidation phase, scoped to the accepted source/fact IDs and revalidated semantic snapshots; contradiction probes never gain supersession authority. Remote maintenance and unapproved bulk lanes remain refused. Tests: `test/managed-extract-atoms.test.ts`, `test/managed-facts-backstop.test.ts`, `test/managed-maintenance.test.ts`.
-- `src/core/persistence/admission-retry.ts` — bounded retries for database-confirmed admission transaction aborts. Each retry reuses the UUID and normalized intent, rechecks guarded authority and reserves quota only on commitment. Standalone journal admission uses 10ms lock waits within the five-second retry budget; backoff occurs after rollback releases the connection so counter contention leaves pool capacity for reads. Ambiguous connection/commit errors are never classified as confirmed rollback. Real counter-lock, read-capacity and after-insert rollback tests live in `test/persistence-journal.test.ts`. Withdrawal retries wrap its whole source-exclusive transaction with its existing lock policy; `admitWriteInTransaction` never backs off inside an existing unit of work. `test/persistence-withdrawal-retry.test.ts` verifies guard release, complete rollback and bounded contention.
+- `src/core/persistence/admission-retry.ts` — bounded retries for database-confirmed admission transaction aborts. Each retry reuses the UUID and normalized intent, rechecks guarded authority and reserves quota only on commitment. Standalone journal admission uses 100ms lock waits within the five-second retry budget to retain queue position behind short counter transactions; backoff occurs after rollback releases the connection so counter contention leaves pool capacity for reads. Ambiguous connection/commit errors are never classified as confirmed rollback. Real counter-lock, sustained-queue progress, read-capacity and after-insert rollback tests live in `test/persistence-journal.test.ts`. Withdrawal retries wrap its whole source-exclusive transaction with its existing lock policy; `admitWriteInTransaction` never backs off inside an existing unit of work. `test/persistence-withdrawal-retry.test.ts` verifies guard release, complete rollback and bounded contention.
- `src/core/persistence/connector-sync.ts` — managed Google/GitHub API ingestion uses source-scoped journaled import/deletion and `managed-connector` checkpoint CAS, not Git cursors. Unbound connectors use reviewed `connector_database` SQL-only authority; bound connectors retain canonical file publication with guarded root/hash/revision/epoch. Standalone entry, page reads and submissions authenticate the current source, local grant and canonical owner, then start the existing consumer and wait up to five seconds for retained worktree publications to settle before checking file bytes or deriving new request identity. Blocked recovery returns its retained receipt and `blocked_reason`; startup recovery precedes connector fetching, and operator edits still fail the strict file-drift check. Explicit `--retry-failed` atomically admits a new linked attempt and stores a per-base-request `managed-connector-retry` pointer, without changing the API cursor or reopening terminal receipts. Approval revalidates current and accepted authority, source/configuration/owner and idle state; concurrent approvals and pending/restarted calls reuse the already approved attempt. Receipt compaction retains the digest and authority needed for exact replay and retry. Checkpoint page-receipt lists are server-derived validation dependencies, excluded from caller identity but frozen in the first admitted intent; changed dependency lists on an unchanged sweep cannot bypass a terminal checkpoint. Durable connector cursors and retry pointers survive generic seven-day checkpoint GC, including completed sweeps needed for incremental resume. Source incarnation/configuration changes select separate cursors; obsolete state remains retained rather than automatically retiring by age. Failed pagination/identity reads cannot advance freshness or delete unconfirmed pages. Tests: `test/persistence-connectors.test.ts`, `test/persistence-connector-retry.test.ts` and `test/helpers/connector-restart.ts` cover synthetic public sync entry in fresh processes, actual SIGKILL between file publication and DB commit, blocked recovery, zero-fetch authorization refusal, aged cursor purge/resume, real storage failures, compacted retries, checkpoint dependencies, atomic approval/lost acknowledgement and concurrent paused-owner replay on PGLite and disposable Postgres.
diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.md
index 97103095f6..9164e5d328 100644
--- a/docs/architecture/key-files/core-utilities-2.md
+++ b/docs/architecture/key-files/core-utilities-2.md
@@ -28,4 +28,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/utils.ts` — Shared SQL utilities used by both engines. Exports `parseEmbedding(value)` (throws on unknown input, used by migration + ingest paths where data integrity matters) and `tryParseEmbedding(value)` (returns `null` + warns once per process, used by search/rescore paths where availability matters more than strictness). `isUndefinedColumnError(err)` predicate — pattern-matches Postgres SQLSTATE 42703 / "column ... does not exist" with engine-driver shape variation tolerated; used by `oauth-provider.ts` so genuine errors (lock timeout, network blip, permission denied) propagate while column-missing falls through to the legacy fallback. `validateSourceId(id)` throws on anything outside `^[a-z0-9_-]+$`, used by the per-source disk-layout fix in patterns.ts/synthesize.ts before any `join(brainDir, '.sources', source_id, slug+'.md')` so source_id can't traverse out of brainDir. `rowToSearchResult` projects email `message_id` / `thread_id` metadata and exposes `source_subject` only when a non-empty Message-ID proves the page is an email, so generated page titles never become authoritative email subjects. `rowToPage` populates the required `Page.source_id` from the SELECT projection (`scripts/check-source-id-projection.sh` enforces every projection feeding `rowToPage` includes the column). `bigintToStringReplacer(key, value)` — the JSON replacer turning `bigint` into strings (the postgres.js int8 wire shape), shared by cli.ts's local-result normalizer (which re-exports it) and the commands that stringify results themselves (`gbrain call`, `extract --explain`); commands import it from here, never from the dispatcher. Its doc comment deliberately carries no double-dash flag literals — the flag-registry generator harvests them from every module a command transitively imports, and utils.ts is imported by nearly all.
-- `src/core/verbs.ts` — MEMORY_VERBS v1: the four frozen protocol verbs (`remember`, `entity`, `synthesize`, `forget`) as first-class Operations, plus `MEMORY_VERBS_VERSION` (single source of truth, =1), `VERB_NAMES`, the hand-authored `RESPONSE_SCHEMAS` registry (Operation carries input params only; response shapes live here and conformance validates LIVE responses against them), and `ERROR_SCHEMA`. The fifth verb is the extended `recall` op in operations.ts. RUNTIME LEAF invariant: operations.ts spreads `verbOperations` into its array at module-eval time, so this file must never statically import operations.ts VALUES (type-only imports fine; handlers use dynamic import) — violating it causes a TDZ crash on whichever module evaluates second. Every verb error carries a populated `suggestion` + `protocol_version` (via `verbError` in operations.ts). The `forget` verb deliberately has NO cliHints (CLI_ONLY `forget` dispatches first and would shadow it). Frozen contract: docs/protocol/MEMORY_VERBS_v1.md; pinned by test/memory-verbs-conformance.test.ts.
+- `src/core/verbs.ts` — MEMORY_VERBS v1: the four frozen protocol verbs (`remember`, `entity`, `synthesize`, `forget`) as first-class Operations, plus `MEMORY_VERBS_VERSION` (single source of truth, =1), `VERB_NAMES`, the hand-authored `RESPONSE_SCHEMAS` registry (Operation carries input params only; response shapes live here and conformance validates LIVE responses against them), and `ERROR_SCHEMA`. The extended `recall` op is defined in ops/facts.ts and registered through operations.ts. Its response registry advertises optional `budget_packing` policy/applied/reason and per-arm integer accounting without changing required default fields or protocol version; `test/protocol-document.test.ts` pins discovery and malformed metadata rejection. RUNTIME LEAF invariant: operations.ts spreads `verbOperations` into its array at module-eval time, so this file must never statically import operations.ts VALUES (type-only imports fine; handlers use dynamic import) — violating it causes a TDZ crash on whichever module evaluates second. Every verb error carries a populated `suggestion` + `protocol_version` (via `verbError` in operations.ts). The `forget` verb deliberately has NO cliHints (CLI_ONLY `forget` dispatches first and would shadow it). Frozen contract: docs/protocol/MEMORY_VERBS_v1.md; pinned by test/memory-verbs-conformance.test.ts.
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.md
index a2cd176259..19c2b34977 100644
--- a/docs/architecture/key-files/graph-and-facts.md
+++ b/docs/architecture/key-files/graph-and-facts.md
@@ -3,7 +3,74 @@
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-- `src/core/markdown-code.ts` — `stripCodeBlocks` masks fenced and inline code while preserving every CR/LF and UTF-16 code-unit offset. Citation paragraphs and later link references retain their original boundaries, including after an unclosed fence. `parseTimelineEntries` in `src/core/link-extraction.ts` groups the optional dash with its trailing whitespace so leading whitespace does not trigger overlapping repetition. Existing date, delimiter, and code-fence recognition rules remain unchanged. Pinned through real FS/DB link and timeline consumers by `test/timeline-parser-regression.test.ts`; its adversarial whitespace workload runs in a timeout-bounded child process.
+## Attendance evidence and ownership
+
+The shared and filesystem extractors recognize canonical attendance only from
+supported explicit lists and uniquely resolved person targets when no pack owns
+the relationship. Callers resolve source identities before
+`resolvedLinkCandidate` orients a Markdown or uniquely resolved bare-wikilink claim as person-to-meeting with the
+meeting as its origin.
+Only parsed link targets can make canonical body claims; display-label slugs stay
+ordinary mentions. `hasAttendanceEvidence` indexes the ordered, nonoverlapping
+evidence ranges rather than rescanning them for every reference. Strict
+frontmatter resolution has a separate, source-keyed cache capped at 256 entries
+within one resolver lifetime.
+Accepted ranges exclude HTML-comment spans, including comments inside an
+otherwise valid list line; a reference scanner seeing those spans cannot
+promote their hidden targets. Engine-backed link extraction requires a loaded
+ontology before graph writes. Failed local preparation instead returns an
+automatic-link error so the note can commit without rewriting pack-owned edges.
+`DerivedLinkEndpointChangedError` identifies only missing or revision-changed
+endpoints detected before graph mutation. Automatic publication catches that
+specific failure, preserving its note and prior graph with retryable auto-link
+metadata; direct reconciliation still refuses. Other errors propagate and roll
+back publication rather than being mislabeled as a harmless link conflict.
+`replaceDerivedLinks` validates that origin and the locked person/meeting types
+and revisions; its `preserveExisting` path keeps matching row identities while
+refreshing their evidence context and origin field. Ambiguous bare-name spellings
+remain mentions rather than asserted attendees, and nonmatching constrained pack
+rules suppress canonical fallback in both extractors.
+Automatic preparation discovers resolved frontmatter targets before applying
+pack target-type constraints, so an unchanged pack-owned attendance row is not
+deleted merely because its endpoint appears only in frontmatter. Missing
+endpoint metadata remains incomplete; known non-person targets are not admitted.
+Filesystem attendance reconciliation excludes legacy rows whose producer is
+unknown; existing canonical-write and sweep handling of those rows is unchanged.
+`prepareAutomaticLinks`, DB/stale extraction, filesystem extraction, and sweep
+share that ownership, so attendee re-extraction cannot delete a meeting claim,
+and removing the meeting's evidence can remove it. `link-reconciliation.ts` owns
+the shared source/default/federation resolution policy, re-exported by the extract
+command. Filesystem attendance uses file evidence with database endpoint metadata;
+missing, ambiguous, or denied attendance resolution preserves the prior graph and
+does not advance extraction watermarks. Incomplete local preparation still allows
+`put_page` to commit the note, with auto-link error metadata and retryable extraction.
+The shared Markdown mask preserves positions while respecting backtick and tilde
+fence closing rules. Attendance opts into comment masking in that same scanner,
+so comment openers inside code do not conceal later evidence. Other callers keep
+their existing code-only masking. Pack-owned outgoing mappings,
+including the shipped base and company packs, stay unchanged. See
+[explicit attendance evidence](../../guides/attendance-evidence.md) for grammar,
+coverage limits, and the distinction from a historical repair.
+
+## Recall source selection
+
+`recall.source_id` narrows both fact and page arms using the existing authorized
+scope resolver, then checks source liveness. Explicit `default` is not omission.
+With no selector, fact scope and page federation retain their previous behavior.
+The opted-in thin CLI uses engine-free scope resolution and refuses `--brain`;
+its source tests execute the real remote dispatcher, not only a canned response.
+Degraded serving has its own explicit `serve` dispatch guard, so the generated
+registry cannot assign its flags to the preceding thin-recall branch.
+`test/cli-recall-flag-ownership.test.ts` pins fresh generation and real CLI
+rejection of serve-only flags before a brain opens.
+
+## Files
+
+- `src/core/extract-timeline-from-meetings.ts` — normalizes canonical incoming and pack-owned outgoing `attended` edges into meeting/person roles before timeline fan-out. SQL requires a live person and live meeting (including legacy meeting notes); existing private-meeting filtering, source opt-in and source-qualified deduplication still apply. Dual-engine tests in `test/extract-timeline-attendance.test.ts` use an empty gazetteer so a body-mention fallback cannot conceal a broken attendance consumer.
+
+- `src/core/ops/facts.ts` — shared fact/memory operations, including `recall`. Recall keeps source/visibility and fact filters before per-arm candidate limits. Its default/explicit `facts_first` packing preserves the frozen memory-verb contract, including the positive sub-one budget quirk. Optional `query_first` packs the ranked page prefix first only with a nonblank query and positive finite budget; floor-zero and exhausted remainders explicitly return empty arms rather than call the unbounded zero-budget packer. Neither arm skips oversized prefix items or truncates. No-query and inactive-budget paths keep legacy behavior. Only policy-supplied calls add `budget_packing` effective-policy/reason and candidate/kept/dropped/estimated-used accounting. Counter sums match the frozen fields. Do not change the global packer or fact relevance to implement this policy. `test/recall-budget-policy.test.ts` pins numeric boundaries, compatibility, candidate ordering, filters, source/private/safe-projection behavior and shared transport validation.
+
+- `src/core/markdown-code.ts` — `stripCodeBlocks` masks fenced and inline code while preserving every CR/LF and UTF-16 code-unit offset. Citation paragraphs and later link references retain their original boundaries, including after an unclosed fence. `parseTimelineEntries` in `src/core/link-extraction.ts` groups the optional dash with its trailing whitespace so leading whitespace does not trigger overlapping repetition. Existing date and delimiter rules remain unchanged. Standalone backtick and tilde fences require valid closing markers; historical inline triple-backtick spans remain masked. Pinned through real FS/DB link and timeline consumers by `test/timeline-parser-regression.test.ts`; its adversarial whitespace workload runs in a timeout-bounded child process.
- `src/core/check-resolvable.ts` — Resolver validation: reachability, MECE overlap, DRY checks, structured fix objects. `CROSS_CUTTING_PATTERNS.conventions` is an array (notability gate accepts `conventions/quality.md` and `_brain-filing-rules.md`). `extractTriggers()` delegates to the shared SKILL.md parser, so MECE gap detection and the trigger index agree on block lists, single-line flow sequences, wrapped flow sequences, and CRLF input. `extractDelegationTargets()` parses `> **Convention:**`, `> **Filing rule:**`, and inline backtick references. DRY suppression is proximity-based via `DRY_PROXIMITY_LINES = 40`. `parseResolverEntries` accepts BOTH the markdown table AND a compact list format (`- **skill-name**: trigger1 | trigger2 | trigger3` or `- skill-name: trigger1 | trigger2`); shapes can mix in one file, folded by the multi-resolver merge. Skill name MUST be kebab-lowercase (regex `[a-z][a-z0-9-]+`) so prose bullets like `- **Note**:`/`- **Convention**:`/`- **TODO**:` don't false-match as skill rows. `skillPath` is ALWAYS derived as `skills/<name>/SKILL.md`: an optional `→ \`skills/path\`` (or ASCII `->`) suffix is stripped from the trigger but NOT honored as the path — two consumers (`routing-eval.ts:skillSlugFromPath`, the manifest lookup) assume the convention; use the table format for non-conventional paths. Multi-trigger rows fan out to one entry per trigger sharing the same `skillPath`; `checkResolvable` dedupes so the reachability count counts each skill once. Pinned by `test/check-resolvable.test.ts` (resolver shapes plus trigger array syntax cases) + `test/check-resolvable-openclaw-compact.test.ts` (8 cases over `test/fixtures/openclaw-compact-resolver/` and `test/fixtures/openclaw-mixed-merge/`). Tutorial: `docs/guides/scaling-skills.md` (three-tier scaling: ~300-skill agent to ~4K tokens/turn from ~25K). `checkResolvable(skillsDir, opts?)` takes an optional `skillsDirSource` (the detection tier from `autoDetectSkillsDir`, threaded by both callers: doctor.ts and the check-resolvable command; an explicit `--skills-dir` passes `null`). An `unreachable` issue downgrades from `error` to `warning` only when ALL hold: the directory was found via the ungated `cwd_walk_up` tier, no resolver file contributes rows (no `RESOLVER.md`; a generic `AGENTS.md` with zero table rows counts as absent), unreachable skills outnumber reachable ones, and no `manifest.json` exists on disk. This keeps a foreign tool's `skills/` dir walked up to from cwd from being scored as a broken gbrain skillpack, while a real skillpack (RESOLVER.md present, higher-confidence tier, dense trigger coverage, or any manifest.json, even a corrupted one) stays strict. A foreign dir with zero `triggers:` and no resolver file still hard-fails via the `missing_file` branch (separate follow-up).
diff --git a/docs/architecture/thin-client.md b/docs/architecture/thin-client.md
index bf30097d8c..c9d7e71266 100644
--- a/docs/architecture/thin-client.md
+++ b/docs/architecture/thin-client.md
@@ -58,6 +58,14 @@ carries the routing-seam picture):
`RemoteMcpErrorReason` union the dispatcher's `never` switch keys off.
Full symbol-level detail: the `src/core/mcp-client.ts` entry in
[`KEY_FILES.md`](./KEY_FILES.md).
+- `src/commands/recall.ts` — explicit `--budget-policy` calls bypass the local
+ engine in the CLI dispatcher and use the remote recall operation. The dispatcher
+ reuses the command's parser, so a query value that resembles a policy flag does
+ not activate this route. An explicit `--brain` is rejected as on the shared
+ thin route. `--source`/`--source-id`, environment and dotfile scope use the
+ engine-free resolver; an explicit `default` is forwarded, not dropped.
+ The host's declared `recall.source_id` narrows both arms through the existing
+ authorization resolver. Omitted-policy CLI behavior is unchanged.
- `src/core/cli-options.ts` — `parseGlobalFlags` supports `--timeout=Ns`
(accepts `30s`, `2m`, `500ms`, plain ms). Default `null` = per-command
default (30s for most ops, 180s for `think`). `parseTimeout(s)` exported
diff --git a/docs/eval/ATTENDANCE_RECALL_EVALUATION.md b/docs/eval/ATTENDANCE_RECALL_EVALUATION.md
new file mode 100644
index 0000000000..a0ac8a1aff
--- /dev/null
+++ b/docs/eval/ATTENDANCE_RECALL_EVALUATION.md
@@ -0,0 +1,95 @@
+# Attendance and recall packing evaluation
+
+## Decision
+
+Explicit attendance makes the graph reflect supported meeting evidence instead
+of ordinary mentions. Query-first packing helps question-focused recall when
+unrelated facts would otherwise use its entire context budget. It remains an
+explicit opt-in because fact-focused questions can lose necessary facts.
+Conditional query expansion is excluded: it lost substantially more complete
+evidence than it gained against the original-query baseline.
+
+These are separate claims. Attendance tests establish extraction, ownership and
+consumer behavior. The packing comparison measures retained evidence, not answer
+accuracy. Neither establishes a broad semantic-retrieval improvement.
+
+## Matched packing comparison
+
+The synthetic cohort contains 16 cases: eleven page-evidence questions, three
+fact-focused controls, one deliberately misrouted fact-focused question, and one
+source/privacy control. Each case runs the same actual `recall` handler with
+omitted policy, explicit `facts_first`, and the case's selected policy. The
+fixture manifest SHA-256 is
+`16f14c6738518c4eff6276ed29f173e313b1303b7a046e0da1931509e839621f`.
+Complete evidence means that every required page slug and exact required fact
+is present, not that a generated answer was judged correct.
+
+The recorded first-wave replay on tree
+`50a7ee3081d443b92db79bd785421c3742fc8e03` produced 48 actual receipts using
+in-memory PGLite and keyless keyword fallback, with no provider calls:
+
+| Cohort | Cases | Baseline complete | Selected policy complete | Wins / losses |
+|---|---:|---:|---:|---:|
+| Page-evidence questions | 11 | 1 | 9 | 8 / 0 |
+| Fact-focused controls | 3 | 3 | 3 | 0 / 0 |
+| Forced query-first fact-risk probe | 1 | 1 | 0 | 0 / 1 |
+| Source/privacy control | 1 | 1 | 1 | 0 / 0 |
+
+The eleven question cases used an estimated 944 tokens in the baseline and 874
+with query-first packing. These are estimates from the existing packer, not
+model-billed tokens. All sixteen omitted-policy receipts matched the baseline
+apart from fixture timestamps. Explicit `facts_first` matched omission apart
+from its documented additive accounting. No forbidden source/private page was
+returned in the source/privacy control.
+
+A fresh paired replay after the correctness pass compared upstream
+`db56c778e8b287482e21df654e6df6dbcc9745fd` with candidate
+`2f33f01486f51a4d42fba5f41c9df82148f6b7de` (tree
+`702c804ec8440143e92dda0754af582e4f681167`). It produced 48 receipts per
+revision with zero provider calls and reproduced every table count and the
+944-to-874 token estimate above. All sixteen omitted-policy results matched
+the new upstream baseline after normalizing only fixture `created_at` values;
+explicit fact-first results additionally differed only by `budget_packing`.
+
+The questions are synthetic development fixtures, not a held-out semantic
+retrieval benchmark. Repeated budgets and related fixtures are not independent
+user questions. The forced fact-risk loss is retained rather than averaged into
+the positive cohort. Keep fact-first routing for fact-focused consumers; do not
+turn the question-cohort result into a default-policy change.
+
+## Conditional expansion result
+
+The separate held-out evaluation recorded 672 cells over 56 unique questions.
+At result limit five, the 48 answerable questions retained complete evidence in
+46 original-query cases, 29 always-expand cases and 31 conditional-expand cases.
+Conditional expansion gained one case and lost sixteen against the original
+query. Its four wins and two losses against always-expand do not justify
+shipping it: always-expand was already the weaker comparator.
+
+This result excludes conditional expansion from the attendance/packing change.
+It does not establish that every query-expansion method is ineffective, or that
+an unrelated research paper has been faithfully replicated.
+
+## Correctness evidence and limits
+
+The executable attendance cases live in `test/attendance-retrieval.test.ts`,
+`test/attendance-extraction-bounds.test.ts`,
+`test/derived-link-reconciliation.test.ts` and
+`test/extract-timeline-attendance.test.ts`. They cover real publication and
+query paths, DB/stale/sweep/filesystem ingestion, pack-owned directions,
+source/type/privacy constraints, ambiguous references, deletion ownership,
+comment/code masking and timeline consumption without a gazetteer fallback.
+The database-backed cases run on PGLite and disposable PostgreSQL.
+
+Historical repair has separate preview/apply and crash-replay cases in
+`test/attendance-repair.test.ts`, connection identity cases in
+`test/attendance-repair-identity.test.ts`, and real local-CLI cases in
+`test/attendance-repair-cli.serial.test.ts`. Passing those tests does not
+authorize a repair on a real brain. Repair requires an exact reviewed preview,
+separate operator approval, and a verified full database backup, as described
+in [the operator guide](../guides/attendance-evidence.md).
+
+The ordinary filesystem extractor reads source-wide endpoint metadata for
+canonical resolution. That cost is not represented as a measured latency
+regression here. There is no production-brain repair, native-harness activation,
+or broad answer-quality claim in these results.
diff --git a/docs/guides/attendance-evidence.md b/docs/guides/attendance-evidence.md
new file mode 100644
index 0000000000..7f7c2b21ca
--- /dev/null
+++ b/docs/guides/attendance-evidence.md
@@ -0,0 +1,232 @@
+# Explicit attendance evidence
+
+Only a link's target can become its attendee. Names or slugs inside the link's
+display label are not additional attendees.
+
+When a schema pack does not override attendance, GBrain records a confirmed
+person's attendance as `person --attended--> meeting`. It requires an explicit
+attendance list, not a person mentioned somewhere in the meeting note.
+
+**Say to your agent:** *"Who attended this meeting? Show the source, and don't
+count people who were only invited or mentioned."*
+
+## Supported evidence
+
+On a `meeting` page, use canonical structured `attendees` frontmatter, a bare
+`Attendees:` link list, or a dedicated `## Attendees` section containing only
+bare link-list entries. Each reference must resolve unambiguously to a live
+`person` page in the allowed source scope. For example:
+
+```markdown
+---
+type: meeting
+title: Planning
+---
+
+Attendees: [Alice Example](../people/alice-example.md)
+```
+
+An alternative body is:
+
+```markdown
+## Attendees
+- [Alice Example](../people/alice-example.md)
+```
+
+Free prose, qualified lists, code examples, and ordinary mentions are not
+canonical attendance evidence. Keep absent or invited-only people outside the
+attendee list: a bare list asserts that each linked person attended, and link
+labels are not a natural-language qualification parser. Unsupported or
+ambiguous references remain mentions or unresolved references.
+
+HTML comments and backtick and tilde code fences are excluded even when they contain headings
+inside an attendee section. A closing fence must use the opening character,
+have at least its length, and contain only trailing whitespace.
+An inline comment beside a visible attendee does not make its hidden references
+part of the attendee list, even when those references resolve to live people.
+An example comment opener inside code does not hide real attendance below it.
+When global basename resolution is enabled, a unique bare attendee wikilink
+can resolve to a person; missing or ambiguous names remain incomplete.
+
+The existing query surface can read the resulting relationship:
+
+```bash
+gbrain call query '{"query":"Who attended meetings/planning?","expand":false,"relational":true}'
+```
+
+The meeting owns the derived claim. Re-extracting the person does not delete
+it; removing the attendance evidence and re-extracting the meeting does.
+Manual claims and claims from other origins remain separate. Remote writes
+still follow the existing deferred-maintenance rules in
+[memory boundaries](memory-boundaries.md).
+
+Filesystem extraction uses the file as evidence and the database for canonical
+attendance endpoint types and source identities. A person does not need a local
+Markdown file. Source-qualified references follow the same explicit opt-in,
+federation, and configured-default rules as database extraction.
+
+An unresolved or denied attendance reference is not a retraction. The origin's
+derived graph stays unchanged, and extraction does not mark it processed or
+advance its watermark. Local page publication still accepts the content,
+reports an auto-link error, and leaves extraction retryable. Removing the
+supported evidence entirely still retracts its owned attendance edge. Ordinary
+filesystem links and schema-pack-owned mappings retain their existing behavior.
+A linked page changing or disappearing between preparation and the locked
+graph check has the same automatic-link error outcome: the note is saved, no
+new graph delta is written, and later extraction can retry. This does not
+suppress source/authority conflicts or unexpected storage failures.
+DB and stale extraction report skipped incomplete-attendance pages; their JSON
+summaries add `skipped_attendance_incomplete` only when it is nonzero. Sweep
+reports `attendance_resolution_incomplete`, not a budget timeout, for that case.
+Filesystem extraction omits incomplete pages from its processed set, but does
+not currently provide a per-reason skip counter.
+
+## Schema-pack boundary
+
+An unavailable schema pack is not a pack with no attendance override. Link
+extraction refuses before changing the graph when the active pack cannot load;
+sweep reports a link/timeline pass error. Local publication still accepts the
+note but reports an automatic-link error and preserves the prior graph. Repair
+or restore the pack configuration, then retry extraction.
+
+Pack-owned relationship directions and inference rules are unchanged. This
+includes the shipped `gbrain-base` and `company-brain` outgoing attendance
+mappings: they do **not** gain incoming `Who attended` lookup from this change.
+Inspect the active schema and its declared direction rather than reversing
+those rows or disabling the pack as a workaround.
+
+This change does not automatically repair historical links or run a full-brain
+backfill. A repair on a real brain requires a separately approved, verified full
+database backup; a Markdown export is not a rollback image. No native agent
+harness activation or broad answer-accuracy improvement is implied.
+
+## Preview-bound historical repair
+
+**Say to your agent:** *"Preview historical attendance links in source `notes`.
+Show the proposed additions, removals and skipped origins. Don't apply anything
+until I've reviewed that exact preview and verified a full database backup."*
+
+Use the existing **trusted-local** DB extraction surface. It is unavailable to
+MCP and thin clients. An explicit live source is required, even when a default
+source is configured. DB-only meeting pages work without filesystem sync.
+The literal source ID `default` must also exist and remain live: its incarnation
+pins the brain identity even when repairing another source. Either archive
+indicator on the selected source or `default` refuses preview and apply.
+
+```bash
+umask 077
+mkdir -m 700 attendance-review
+gbrain extract links --source db --repair-attendance --source-id notes --json \
+ > attendance-review/preview.json
+```
+
+Preview writes no logical database rows, extraction watermarks, source files,
+receipts or checkpoints. It opens an existing database without migrations or
+automatic repair; a storage engine may still maintain its locks and WAL files.
+The operator's shell creates the private receipt above. Keep it private: it
+contains source-qualified page identities and hashes, but no copied source
+text or evidence snippets. Review its `counts`, bounded `diagnostics`, `pack`,
+`direction`, and `origins` before authorizing it.
+Each preview invocation creates a new approval ID and exact digest, even when
+it proposes no changes. Save and approve that exact receipt rather than
+regenerating it between review and apply.
+The connection pin hashes only the selected brain and its stable target:
+the resolved PGLite path, or PostgreSQL scheme, ordered hosts/ports and database.
+Credentials, userinfo, unrelated configuration and query option values do not
+participate. PostgreSQL targets require explicit hosts and a database; ordered
+multihost and bracketed IPv6 addresses are supported. Socket/service URLs,
+query-based target overrides and malformed targets refuse rather than sharing
+a fallback identity. Changing the target or brain requires a fresh preview;
+rotating credentials alone does not. Previews from the older connection-pin
+format also require a fresh preview.
+
+The default window is **250 source pages**; `--limit` accepts 1–1000. The
+indexed `(source_id, slug)` window is selected before filtering deleted or
+nonmeeting pages. `counts.scanned` counts that window, while
+`counts.eligibleOrigins` counts live meetings inside it. A window may have no
+eligible origins. After applying a reviewed window, use `--after-slug` with
+its `nextAfterSlug` to preview the next one. Each window requires a new preview,
+confirmation and checkpoint file path. Do not reuse `cursor.json` with a new
+preview: the checkpoint belongs to the exact approved receipt, so use names
+such as `preview-002.json` and `cursor-002.json` for the next window.
+Database ordering determines the cursor, including Unicode
+and punctuation; a full-sized final window requires one more empty preview.
+The cursor is a bounded traversal, not a snapshot across separate previews:
+new or renamed pages behind it require another pass from the beginning.
+
+Historical repair accepts only explicit Markdown attendance links. **All
+frontmatter attendance is report-only**, including apparently canonical paths,
+and existing frontmatter claims keep their IDs and evidence. Repair neither
+loads frontmatter nor approximates the ordinary extractor's source-wide
+title/alias uniqueness checks. Body targets use bounded, source-scoped exact
+slug lookups; missing or ambiguous targets skip the origin without deletion.
+Mixed person/non-person attendance lists are also report-only: repair does not
+partially reinterpret them or delete earlier claims to make the list fit.
+
+Each eligible origin is capped at 256 KiB of body text, 256 lookup slugs and
+512 adjacent link rows of any type. Three capped adjacency probes each inspect
+at most 513 logical IDs before selecting attendance edges. An over-limit
+origin, proposed post-repair adjacency or oversized attendance evidence is
+report-only. Oversized body and edge evidence are not transferred from the
+database into the repair process. These are logical row and transfer bounds,
+not physical MVCC page-scan or total-process-memory guarantees. At most 20
+diagnostic details are retained, alongside aggregate counts. Retained origin
+receipts above 16 MiB are refused; retry with a smaller window.
+
+Repair preserves pack-owned outgoing attendance, including shipped base and
+company-brain mappings. Missing packs are also report-only. It never guesses
+ownership for NULL, unknown or manual producers. Legacy outgoing Markdown is
+eligible only when authoritative source text proves the same resolved person's
+attendance. Other derived/manual links keep their row IDs and evidence.
+
+Before applying on a real brain, quiesce old extraction writers, verify a full
+database backup and its recovery procedure, and obtain separate operator
+approval. Copy the exact receipt's `digest` into the following command:
+
+```bash
+gbrain extract links --source db --repair-attendance --source-id notes \
+ --apply-preview attendance-review/preview.json --confirm APPROVED_DIGEST \
+ --yes --backup-verified --checkpoint attendance-review/cursor.json
+```
+
+`--backup-verified` acknowledges the operator's backup verification; it does
+not perform or verify a backup. The receipt and checkpoint must be owned,
+private regular files in an owned private directory. Symlinks are refused.
+Filesystem, stale, global, parallel, mention/NER and timeline extraction flags
+cannot be combined with repair. `--yes` alone never applies a new scan.
+
+Each origin runs in its own transaction. Brain connection and source
+incarnation, origin/endpoint IDs and revisions, parser/ontology identity,
+reference resolution and exact affected edge rows are checked again. Changed
+state refuses the preview instead of silently recalculating approval. The
+transaction applies only the attendance delta and banks a private database
+commit receipt; the private file cursor advances only after that commit.
+Re-run the exact apply command after interruption. A commit before a cursor
+write is recognized without deleting/reinserting identical rows. A failed
+origin is not passed; changed state requires a fresh preview. The cursor also
+covers revalidated deleted/nonmeeting prefixes and tails, including windows
+with no eligible origins, but never passes an uncommitted origin. A successful
+prefix remains committed if a later origin fails.
+
+Version-2 approvals expire **seven days after their database-clock issuance
+time**. The commit proof must independently remain within the existing global
+**seven-day checkpoint pruning horizon**, measured from the proof row's update
+time. A late apply or replay extends neither deadline. Version-1 receipts,
+expired approvals and retained expired proofs require a fresh preview, new
+confirmation digest and new checkpoint path. Repair has no pruning exemption.
+If proof is pruned or otherwise lost, obtain and approve a fresh preview;
+retaining the private cursor does not establish a database commit or extend
+either lifetime. A still-young no-op approval with missing proof can be
+indistinguishable from first apply when its approved pre-state is unchanged;
+repair does not reconstruct missing commit history. Row-identity
+preservation is an A2 repair/replay property, not a promise about other writers:
+later ordinary DB re-extraction can preserve attendance semantics while changing
+repaired row IDs, invalidating replay of the old preview. Preview again then too.
+
+Each origin transaction takes a table-wide link lock, pausing link writers
+across the database while ordinary PostgreSQL reads remain available. PGLite
+retains its existing single-owner connection model. Lock waits are capped at
+five seconds and individual statements at ten seconds; contention refuses the
+current origin for retry. Existing normal extraction paths and their watermarks
+are unchanged. Reverting the code does not undo a repair; recovery requires the
+full database backup or a separately verified reverse repair.
diff --git a/docs/guides/concurrent-writes.md b/docs/guides/concurrent-writes.md
index ff71910ced..bc6ac323df 100644
--- a/docs/guides/concurrent-writes.md
+++ b/docs/guides/concurrent-writes.md
@@ -263,7 +263,9 @@ serializes startup and remains held until the listener has actually closed.
Admission retries confirmed database lock/serialization aborts for up to five
seconds using the same UUID. Standalone journal admission limits each database
-lock wait to 10ms and backs off after rollback releases the connection. Confirmed
+lock wait to 100ms and backs off after rollback releases the connection. This
+allows admission to retain its place behind short counter transactions rather
+than repeatedly abandoning the lock queue. Confirmed
lock-contention aborts use 5–25ms retry jitter; other retryable aborts retain
25–100ms jitter. Waiting page writers release pool capacity between attempts
instead of holding connections through long counter-lock waits.
diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.md
index 06d6c0b63a..c2145544fa 100644
--- a/docs/protocol/MEMORY_VERBS_v1.md
+++ b/docs/protocol/MEMORY_VERBS_v1.md
@@ -106,7 +106,7 @@ have no per-client row: they serve the server-resolved surface directly.
## The verbs
-### recall(query?, entity?, budget_tokens?, since?, session_id?, limit?, …) — read
+### recall(query?, entity?, budget_tokens?, budget_policy?, source_id?, since?, session_id?, limit?, …) — read
Retrieve saved facts and (with `query`) budget-packed page snippets.
@@ -119,10 +119,33 @@ Retrieve saved facts and (with `query`) budget-packed page snippets.
composes with `entity` and `session_id` in the same query, before the
per-arm limit. An unparseable value is rejected with `invalid_params`.
- `limit` is a PER-ARM cap (facts and search results each).
-- `budget_tokens`: SERVER-side packing — facts pack first (limit-capped
- one-liners, so search-arm starvation is bounded), search results take the
- remainder. The estimator is char/4 (±10–15%); `budget_used` reports packed
- tokens, `dropped_count` what didn't fit. Never advisory, never client-side.
+- `budget_tokens`: SERVER-side packing — by default facts pack first and search
+ results take the remainder. A positive finite numeric budget is floored;
+ other values leave the arrays unbudgeted. Costs are `ceil(fact.length/4)` or
+ `ceil(title.length/4) + ceil(chunk.length/4)`, not exact tokenizer counts or
+ JSON-envelope size. `budget_used` reports estimated packed tokens and
+ `dropped_count` counts candidates that did not fit. Legacy compatibility:
+ a positive numeric budget below one reports budget zero but keeps all facts
+ and no pages; this old path is not a strict fractional cap.
+- `budget_policy`: optional `facts_first | query_first`, default `facts_first`.
+ Explicit facts-first preserves the default behavior, including its fractional
+ quirk. Query-first applies only with a nonblank `query` and positive finite
+ numeric budget: pack the ranked page prefix first, then the fact prefix in the
+ remaining budget. If the floored budget is zero, keep neither arm. An exhausted
+ remainder keeps zero second-arm items. Each arm stops at its first oversized
+ item without skipping to smaller later items or truncating. No page hits or
+ an oversized first page leaves the full budget for facts. Without a nonblank
+ query, use exact legacy facts-first behavior; without a positive finite budget,
+ keep the unbudgeted arrays. Candidate selection, source grants, visibility,
+ fact filters and per-arm limits are unchanged.
+- `source_id`: optional concrete source for both evidence arms. An explicit
+ `default` is distinct from omission. The existing authorization resolver
+ checks the selector before source existence; denied, nonexistent and archived
+ sources fail rather than falling back to a broader grant. Omission preserves
+ the existing context/grant scope and local federation behavior.
+ Selector failures use stamped v1 errors: `scope_denied` for a denied source,
+ `not_found` for a missing or archived source, and `invalid_params` for an
+ invalid selector. `detail` preserves the underlying source-error classification.
- No embedding provider configured? The search arm degrades to keyword-only
and the response notes `search_degraded` — never an error.
@@ -136,7 +159,66 @@ Response — an additive SUPERSET of the plain facts envelope on EVERY call
| `total` | int | count of facts returned |
| `results[]` | array | search arm only: `slug`, `title`, `chunk`, `evidence`, `create_safety`, `provenance` (origin page slug) |
| `search_degraded` | string? | present when keyword-only fallback fired |
-| `budget_tokens` / `budget_used` / `dropped_count` | int? | present when `budget_tokens` was passed |
+| `budget_tokens` / `budget_used` / `dropped_count` | int? | present for a positive finite numeric budget, including when its floor is zero |
+| `budget_packing` | object? | present only when a valid `budget_policy` is supplied; effective policy and per-arm accounting |
+
+`budget_packing` contains `policy` (effective `facts_first | query_first`),
+`applied` (whether the requested budget policy applied), `reason`, and `facts` /
+`results` objects with `candidates`, `kept`, `dropped`, and `used`. Candidates are
+the already authorized, filtered, limit-capped arms, not all rows in the brain.
+`candidates = kept + dropped` per arm; the sums of `used` and `dropped` equal
+`budget_used` and `dropped_count` when those frozen fields exist. On unbudgeted
+calls, `used` counts the unchanged returned evidence and frozen budget fields
+remain absent. Omitting the policy adds no new response field. Optional null or
+empty-string policy values normalize to absence through the ordinary transport
+validator; invalid types and enum values are `invalid_params`.
+
+Reasons, in precedence order: `no_query` (query-first requested without a nonblank
+query), `no_positive_finite_budget`, `budget_below_one` (a positive budget floors to zero),
+`no_candidates`, `first_items_exceed_budget` (candidates exist but neither prefix
+head fits), and `packed`. Ineligible query-first requests report effective
+`facts_first` and `applied: false`. `packed` does not guarantee all required
+evidence fit, or that a returned page answers the question.
+
+For `budget_below_one`, eligible query-first applies an empty budget to both
+arms and reports `applied: true`. Facts-first preserves the legacy sub-one
+overrun, but reports `applied: false` rather than claiming its evidence fit.
+With an explicit CLI policy, local and thin callers preserve an explicit
+`--source default` over ambient selectors and reject missing or archived
+sources. The policy accepts concrete source IDs, not `__all__`; omit the source
+selector to retain the existing context/grant scope. Legacy calls without the
+policy retain their existing CLI source-resolution and fractional-budget rules.
+
+**Opt-in caller:** for a question about saved page evidence with a tight budget:
+
+```bash
+gbrain recall --query 'zebra telescope' --budget-tokens 75 --budget-policy query_first --json
+```
+
+```json
+{"name":"recall","arguments":{"query":"zebra telescope","budget_tokens":75,"budget_policy":"query_first"}}
+```
+
+Keep entity-first, event/session-filtered and fact-focused callers on facts-first;
+an irrelevant matching page can otherwise displace their useful fact. The policy
+does not change `context_pack` or existing third-party calls. Maintained caller
+guidance lives in `skills/query/SKILL.md` and `skills/brain-ops/SKILL.md`; schema
+advertisement and documentation are not evidence of native-harness adoption.
+Require an observed opted-in call in a fresh conversation before claiming it.
+
+The named CLI accepts the policy before or after the other options, including
+`--budget-policy=query_first`, and rejects missing/invalid values. Its omitted
+and explicit facts-first paths preserve legacy integer parsing of budget text
+(`0.5` becomes an absent budget). Only explicit query-first with a nonblank query
+preserves numeric fractions until the operation floors them. MCP and
+`gbrain call recall` use the numeric operation contract above. Opt-in named calls
+forward fact filters and use the remote operation on thin clients; `--watch`,
+`--since-last-run`, `--rollup`, and `--as-context` cannot be combined with the new
+policy option. Their existing calls without the option are unchanged.
+For opted-in local and thin `--json` calls, selector rejections and remote
+operation failures emit structured errors on stdout and exit nonzero. Remote
+error messages, suggestions, details and documentation references are retained,
+including ordinary read errors without mutation receipts.
**evidence** (enum, zero-LLM heuristic): `alias_hit` \| `exact_title_match` \|
`high_vector_match` \| `keyword_exact` \| `weak_semantic` — why each result
diff --git a/llms-full.txt b/llms-full.txt
index 2d97f0f4fb..3a6a644aae 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -6898,7 +6898,7 @@ have no per-client row: they serve the server-resolved surface directly.
## The verbs
-### recall(query?, entity?, budget_tokens?, since?, session_id?, limit?, …) — read
+### recall(query?, entity?, budget_tokens?, budget_policy?, source_id?, since?, session_id?, limit?, …) — read
Retrieve saved facts and (with `query`) budget-packed page snippets.
@@ -6911,10 +6911,33 @@ Retrieve saved facts and (with `query`) budget-packed page snippets.
composes with `entity` and `session_id` in the same query, before the
per-arm limit. An unparseable value is rejected with `invalid_params`.
- `limit` is a PER-ARM cap (facts and search results each).
-- `budget_tokens`: SERVER-side packing — facts pack first (limit-capped
- one-liners, so search-arm starvation is bounded), search results take the
- remainder. The estimator is char/4 (±10–15%); `budget_used` reports packed
- tokens, `dropped_count` what didn't fit. Never advisory, never client-side.
+- `budget_tokens`: SERVER-side packing — by default facts pack first and search
+ results take the remainder. A positive finite numeric budget is floored;
+ other values leave the arrays unbudgeted. Costs are `ceil(fact.length/4)` or
+ `ceil(title.length/4) + ceil(chunk.length/4)`, not exact tokenizer counts or
+ JSON-envelope size. `budget_used` reports estimated packed tokens and
+ `dropped_count` counts candidates that did not fit. Legacy compatibility:
+ a positive numeric budget below one reports budget zero but keeps all facts
+ and no pages; this old path is not a strict fractional cap.
+- `budget_policy`: optional `facts_first | query_first`, default `facts_first`.
+ Explicit facts-first preserves the default behavior, including its fractional
+ quirk. Query-first applies only with a nonblank `query` and positive finite
+ numeric budget: pack the ranked page prefix first, then the fact prefix in the
+ remaining budget. If the floored budget is zero, keep neither arm. An exhausted
+ remainder keeps zero second-arm items. Each arm stops at its first oversized
+ item without skipping to smaller later items or truncating. No page hits or
+ an oversized first page leaves the full budget for facts. Without a nonblank
+ query, use exact legacy facts-first behavior; without a positive finite budget,
+ keep the unbudgeted arrays. Candidate selection, source grants, visibility,
+ fact filters and per-arm limits are unchanged.
+- `source_id`: optional concrete source for both evidence arms. An explicit
+ `default` is distinct from omission. The existing authorization resolver
+ checks the selector before source existence; denied, nonexistent and archived
+ sources fail rather than falling back to a broader grant. Omission preserves
+ the existing context/grant scope and local federation behavior.
+ Selector failures use stamped v1 errors: `scope_denied` for a denied source,
+ `not_found` for a missing or archived source, and `invalid_params` for an
+ invalid selector. `detail` preserves the underlying source-error classification.
- No embedding provider configured? The search arm degrades to keyword-only
and the response notes `search_degraded` — never an error.
@@ -6928,7 +6951,66 @@ Response — an additive SUPERSET of the plain facts envelope on EVERY call
| `total` | int | count of facts returned |
| `results[]` | array | search arm only: `slug`, `title`, `chunk`, `evidence`, `create_safety`, `provenance` (origin page slug) |
| `search_degraded` | string? | present when keyword-only fallback fired |
-| `budget_tokens` / `budget_used` / `dropped_count` | int? | present when `budget_tokens` was passed |
+| `budget_tokens` / `budget_used` / `dropped_count` | int? | present for a positive finite numeric budget, including when its floor is zero |
+| `budget_packing` | object? | present only when a valid `budget_policy` is supplied; effective policy and per-arm accounting |
+
+`budget_packing` contains `policy` (effective `facts_first | query_first`),
+`applied` (whether the requested budget policy applied), `reason`, and `facts` /
+`results` objects with `candidates`, `kept`, `dropped`, and `used`. Candidates are
+the already authorized, filtered, limit-capped arms, not all rows in the brain.
+`candidates = kept + dropped` per arm; the sums of `used` and `dropped` equal
+`budget_used` and `dropped_count` when those frozen fields exist. On unbudgeted
+calls, `used` counts the unchanged returned evidence and frozen budget fields
+remain absent. Omitting the policy adds no new response field. Optional null or
+empty-string policy values normalize to absence through the ordinary transport
+validator; invalid types and enum values are `invalid_params`.
+
+Reasons, in precedence order: `no_query` (query-first requested without a nonblank
+query), `no_positive_finite_budget`, `budget_below_one` (a positive budget floors to zero),
+`no_candidates`, `first_items_exceed_budget` (candidates exist but neither prefix
+head fits), and `packed`. Ineligible query-first requests report effective
+`facts_first` and `applied: false`. `packed` does not guarantee all required
+evidence fit, or that a returned page answers the question.
+
+For `budget_below_one`, eligible query-first applies an empty budget to both
+arms and reports `applied: true`. Facts-first preserves the legacy sub-one
+overrun, but reports `applied: false` rather than claiming its evidence fit.
+With an explicit CLI policy, local and thin callers preserve an explicit
+`--source default` over ambient selectors and reject missing or archived
+sources. The policy accepts concrete source IDs, not `__all__`; omit the source
+selector to retain the existing context/grant scope. Legacy calls without the
+policy retain their existing CLI source-resolution and fractional-budget rules.
+
+**Opt-in caller:** for a question about saved page evidence with a tight budget:
+
+```bash
+gbrain recall --query 'zebra telescope' --budget-tokens 75 --budget-policy query_first --json
+```
+
+```json
+{"name":"recall","arguments":{"query":"zebra telescope","budget_tokens":75,"budget_policy":"query_first"}}
+```
+
+Keep entity-first, event/session-filtered and fact-focused callers on facts-first;
+an irrelevant matching page can otherwise displace their useful fact. The policy
+does not change `context_pack` or existing third-party calls. Maintained caller
+guidance lives in `skills/query/SKILL.md` and `skills/brain-ops/SKILL.md`; schema
+advertisement and documentation are not evidence of native-harness adoption.
+Require an observed opted-in call in a fresh conversation before claiming it.
+
+The named CLI accepts the policy before or after the other options, including
+`--budget-policy=query_first`, and rejects missing/invalid values. Its omitted
+and explicit facts-first paths preserve legacy integer parsing of budget text
+(`0.5` becomes an absent budget). Only explicit query-first with a nonblank query
+preserves numeric fractions until the operation floors them. MCP and
+`gbrain call recall` use the numeric operation contract above. Opt-in named calls
+forward fact filters and use the remote operation on thin clients; `--watch`,
+`--since-last-run`, `--rollup`, and `--as-context` cannot be combined with the new
+policy option. Their existing calls without the option are unchanged.
+For opted-in local and thin `--json` calls, selector rejections and remote
+operation failures emit structured errors on stdout and exit nonzero. Remote
+error messages, suggestions, details and documentation references are retained,
+including ordinary read errors without mutation receipts.
**evidence** (enum, zero-LLM heuristic): `alias_hit` \| `exact_title_match` \|
`high_vector_match` \| `keyword_exact` \| `weak_semantic` — why each result
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index d7cdcd3102..c9857f4f57 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -1,7 +1,7 @@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.57.1.0",
+ "version": "0.58.0.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 8697ea84e3..f651907544 100644
--- a/package.json
+++ b/package.json
@@ -179,7 +179,7 @@
"bun": ">=1.3.11"
},
"license": "MIT",
- "version": "0.57.1.0",
+ "version": "0.58.0.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 fe3b8770d1..251a1967de 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.57.1.0",
+ "version": "0.58.0.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 2596833a85..f8b51d1ced 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.57.1.0",
+ "version": "0.58.0.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 9fdda95621..fc7ed62f09 100644
--- a/plugin-variants/gbrain-coding/README.md
+++ b/plugin-variants/gbrain-coding/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.57.1.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.58.0.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-coding/skills/brain-ops/SKILL.md b/plugin-variants/gbrain-coding/skills/brain-ops/SKILL.md
index 4f4e1c484b..153ce158bd 100644
--- a/plugin-variants/gbrain-coding/skills/brain-ops/SKILL.md
+++ b/plugin-variants/gbrain-coding/skills/brain-ops/SKILL.md
@@ -9,6 +9,7 @@ description: |
triggers:
- any brain read/write/lookup/citation
tools:
+ - recall
- search
- query
- get_page
@@ -50,6 +51,18 @@ suppresses writes for that turn, including when standing capture is enabled.
> Fall back to the classic ops when the verbs aren't on the surface. Contract:
> `docs/protocol/MEMORY_VERBS_v1.md`.
>
+> **Tight-budget page questions:** explicitly use
+> `recall({query: "zebra telescope", budget_tokens: 75, budget_policy: "query_first"})`
+> so ranked page evidence packs before recent facts. CLI:
+> `gbrain recall --query 'zebra telescope' --budget-tokens 75 --budget-policy query_first --json`.
+> Keep entity-first, event/session-filtered and fact-focused questions on their
+> existing facts-first route; do not change `context_pack`. Costs are character-based
+> estimates, and an oversized first item is dropped without skipping or truncation.
+> Read `budget_packing` before interpreting an empty result as missing memory.
+> See `skills/query/SKILL.md` for the MCP request and caller example. Guidance is
+> not native-harness activation: adoption remains unverified until a fresh
+> conversation is observed making the opted-in call.
+>
> **Choose a readback path that can see the intended visibility.** Trusted local
> CLI callers can recall and withdraw private facts. Every MCP caller, including
> stdio, and a thin CLI connected to MCP currently have world-only fact recall
diff --git a/plugin-variants/gbrain-coding/skills/query/SKILL.md b/plugin-variants/gbrain-coding/skills/query/SKILL.md
index 819f7b9e07..5815c66bc8 100644
--- a/plugin-variants/gbrain-coding/skills/query/SKILL.md
+++ b/plugin-variants/gbrain-coding/skills/query/SKILL.md
@@ -19,6 +19,7 @@ triggers:
- "connections"
- "graph query"
tools:
+ - recall
- search
- query
- get_page
@@ -101,6 +102,41 @@ Answers should include:
Search returns **chunks**, not full pages. Read the excerpts first before deciding
whether to load a full page.
+For a question about saved **page evidence** with a tight budget, explicitly choose
+`recall` with `budget_policy: "query_first"`. It gives the existing ranked page
+results first use of the budget, then packs recent/filtered facts into what remains.
+This is an opt-in packing choice, not a new relevance model: an irrelevant page can
+displace a useful fact. Keep entity-first, session/event-filtered and fact-focused
+questions on their existing facts-first route. Do not change `context_pack` or
+existing third-party calls.
+
+```bash
+gbrain recall --query 'zebra telescope' --budget-tokens 75 --budget-policy query_first --json
+```
+
+Equivalent MCP request:
+
+```json
+{"name":"recall","arguments":{"query":"zebra telescope","budget_tokens":75,"budget_policy":"query_first"}}
+```
+
+**Say to your agent:** “Recall the saved notes about the zebra telescope using a
+75-token estimated budget and query-first packing. Cite the returned evidence;
+if the first page cannot fit, tell me rather than treating that as missing memory.”
+
+Use the resolved brain and source as usual; the option does not widen permissions.
+`budget_packing` reports the effective policy and per-arm candidate/kept/dropped/used
+counts. Costs estimate `ceil(fact.length/4)` or
+`ceil(title.length/4) + ceil(chunk.length/4)`, not exact tokenizer or JSON-envelope
+size. Packing never skips an oversized prefix item or truncates it; multiple
+required pages may still not fit. With no nonblank query or no positive finite
+budget, the operation keeps legacy behavior. An eligible positive budget below one
+token returns empty arms. See the protocol for fractional-budget compatibility.
+
+This guidance and advertised tool schemas do not prove native-harness adoption.
+Confirm an observed query-first call in a fresh harness conversation before
+claiming activation; otherwise report adoption as unverified.
+
- `gbrain search` / `gbrain query` return ranked chunks with context snippets.
These are often enough to answer the question directly.
- Only use `gbrain get <slug>` to load the full page when a chunk confirms the
diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
index ba08cf7c7c..3ab1bb9b6a 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.57.1.0",
+ "version": "0.58.0.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 5eed9648dc..0774d23bc2 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.57.1.0",
+ "version": "0.58.0.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 d008ef493e..023b9a2cd3 100644
--- a/plugin-variants/gbrain-daily/README.md
+++ b/plugin-variants/gbrain-daily/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.57.1.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.58.0.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-variants/gbrain-daily/skills/query/SKILL.md b/plugin-variants/gbrain-daily/skills/query/SKILL.md
index 819f7b9e07..5815c66bc8 100644
--- a/plugin-variants/gbrain-daily/skills/query/SKILL.md
+++ b/plugin-variants/gbrain-daily/skills/query/SKILL.md
@@ -19,6 +19,7 @@ triggers:
- "connections"
- "graph query"
tools:
+ - recall
- search
- query
- get_page
@@ -101,6 +102,41 @@ Answers should include:
Search returns **chunks**, not full pages. Read the excerpts first before deciding
whether to load a full page.
+For a question about saved **page evidence** with a tight budget, explicitly choose
+`recall` with `budget_policy: "query_first"`. It gives the existing ranked page
+results first use of the budget, then packs recent/filtered facts into what remains.
+This is an opt-in packing choice, not a new relevance model: an irrelevant page can
+displace a useful fact. Keep entity-first, session/event-filtered and fact-focused
+questions on their existing facts-first route. Do not change `context_pack` or
+existing third-party calls.
+
+```bash
+gbrain recall --query 'zebra telescope' --budget-tokens 75 --budget-policy query_first --json
+```
+
+Equivalent MCP request:
+
+```json
+{"name":"recall","arguments":{"query":"zebra telescope","budget_tokens":75,"budget_policy":"query_first"}}
+```
+
+**Say to your agent:** “Recall the saved notes about the zebra telescope using a
+75-token estimated budget and query-first packing. Cite the returned evidence;
+if the first page cannot fit, tell me rather than treating that as missing memory.”
+
+Use the resolved brain and source as usual; the option does not widen permissions.
+`budget_packing` reports the effective policy and per-arm candidate/kept/dropped/used
+counts. Costs estimate `ceil(fact.length/4)` or
+`ceil(title.length/4) + ceil(chunk.length/4)`, not exact tokenizer or JSON-envelope
+size. Packing never skips an oversized prefix item or truncates it; multiple
+required pages may still not fit. With no nonblank query or no positive finite
+budget, the operation keeps legacy behavior. An eligible positive budget below one
+token returns empty arms. See the protocol for fractional-budget compatibility.
+
+This guidance and advertised tool schemas do not prove native-harness adoption.
+Confirm an observed query-first call in a fresh harness conversation before
+claiming activation; otherwise report adoption as unverified.
+
- `gbrain search` / `gbrain query` return ranked chunks with context snippets.
These are often enough to answer the question directly.
- Only use `gbrain get <slug>` to load the full page when a chunk confirms the
diff --git a/plugin/README.md b/plugin/README.md
index c911154ffd..24f0017f81 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.57.1.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.58.0.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/plugin/skills/brain-ops/SKILL.md b/plugin/skills/brain-ops/SKILL.md
index 4f4e1c484b..153ce158bd 100644
--- a/plugin/skills/brain-ops/SKILL.md
+++ b/plugin/skills/brain-ops/SKILL.md
@@ -9,6 +9,7 @@ description: |
triggers:
- any brain read/write/lookup/citation
tools:
+ - recall
- search
- query
- get_page
@@ -50,6 +51,18 @@ suppresses writes for that turn, including when standing capture is enabled.
> Fall back to the classic ops when the verbs aren't on the surface. Contract:
> `docs/protocol/MEMORY_VERBS_v1.md`.
>
+> **Tight-budget page questions:** explicitly use
+> `recall({query: "zebra telescope", budget_tokens: 75, budget_policy: "query_first"})`
+> so ranked page evidence packs before recent facts. CLI:
+> `gbrain recall --query 'zebra telescope' --budget-tokens 75 --budget-policy query_first --json`.
+> Keep entity-first, event/session-filtered and fact-focused questions on their
+> existing facts-first route; do not change `context_pack`. Costs are character-based
+> estimates, and an oversized first item is dropped without skipping or truncation.
+> Read `budget_packing` before interpreting an empty result as missing memory.
+> See `skills/query/SKILL.md` for the MCP request and caller example. Guidance is
+> not native-harness activation: adoption remains unverified until a fresh
+> conversation is observed making the opted-in call.
+>
> **Choose a readback path that can see the intended visibility.** Trusted local
> CLI callers can recall and withdraw private facts. Every MCP caller, including
> stdio, and a thin CLI connected to MCP currently have world-only fact recall
diff --git a/plugin/skills/query/SKILL.md b/plugin/skills/query/SKILL.md
index 819f7b9e07..5815c66bc8 100644
--- a/plugin/skills/query/SKILL.md
+++ b/plugin/skills/query/SKILL.md
@@ -19,6 +19,7 @@ triggers:
- "connections"
- "graph query"
tools:
+ - recall
- search
- query
- get_page
@@ -101,6 +102,41 @@ Answers should include:
Search returns **chunks**, not full pages. Read the excerpts first before deciding
whether to load a full page.
+For a question about saved **page evidence** with a tight budget, explicitly choose
+`recall` with `budget_policy: "query_first"`. It gives the existing ranked page
+results first use of the budget, then packs recent/filtered facts into what remains.
+This is an opt-in packing choice, not a new relevance model: an irrelevant page can
+displace a useful fact. Keep entity-first, session/event-filtered and fact-focused
+questions on their existing facts-first route. Do not change `context_pack` or
+existing third-party calls.
+
+```bash
+gbrain recall --query 'zebra telescope' --budget-tokens 75 --budget-policy query_first --json
+```
+
+Equivalent MCP request:
+
+```json
+{"name":"recall","arguments":{"query":"zebra telescope","budget_tokens":75,"budget_policy":"query_first"}}
+```
+
+**Say to your agent:** “Recall the saved notes about the zebra telescope using a
+75-token estimated budget and query-first packing. Cite the returned evidence;
+if the first page cannot fit, tell me rather than treating that as missing memory.”
+
+Use the resolved brain and source as usual; the option does not widen permissions.
+`budget_packing` reports the effective policy and per-arm candidate/kept/dropped/used
+counts. Costs estimate `ceil(fact.length/4)` or
+`ceil(title.length/4) + ceil(chunk.length/4)`, not exact tokenizer or JSON-envelope
+size. Packing never skips an oversized prefix item or truncates it; multiple
+required pages may still not fit. With no nonblank query or no positive finite
+budget, the operation keeps legacy behavior. An eligible positive budget below one
+token returns empty arms. See the protocol for fractional-budget compatibility.
+
+This guidance and advertised tool schemas do not prove native-harness adoption.
+Confirm an observed query-first call in a fresh harness conversation before
+claiming activation; otherwise report adoption as unverified.
+
- `gbrain search` / `gbrain query` return ranked chunks with context snippets.
These are often enough to answer the question directly.
- Only use `gbrain get <slug>` to load the full page when a chunk confirms the
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.ts
index 3a2fa69152..2bdf113842 100644
--- a/scripts/e2e-test-map.ts
+++ b/scripts/e2e-test-map.ts
@@ -135,7 +135,8 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
// differently on real pgvector than on PGLite.
"src/core/embedding-migration.ts": ["test/e2e/migrate-embeddings-postgres.test.ts"],
"src/core/stored-embedding-identity.ts": ["test/e2e/unsupported-embedding-identity-postgres.test.ts"],
- "src/commands/extract.ts": ["test/e2e/multi-source-bug-class.test.ts"],
+ "src/commands/extract.ts": ["test/e2e/multi-source-bug-class.test.ts", "test/e2e/attendance-retrieval-postgres.test.ts", "test/e2e/extract-timeline-attendance-postgres.test.ts"],
+ "src/commands/extract-attendance-repair.ts": ["test/e2e/attendance-repair-postgres.test.ts"],
"src/commands/migrate-engine.ts": [
"test/e2e/multi-source-bug-class.test.ts",
"test/e2e/migrate-engine-pglite-to-postgres.test.ts",
@@ -346,7 +347,13 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
// Doctor check modules peeled from doctor.ts feed the same e2e surface.
"src/commands/doctor/**": ["test/e2e/doctor-progress.test.ts"],
// Knowledge graph layer feeds graph-quality.
- "src/core/link-extraction.ts": ["test/e2e/graph-quality.test.ts"],
+ "src/core/link-extraction.ts": ["test/e2e/graph-quality.test.ts", "test/e2e/attendance-retrieval-postgres.test.ts"],
+ "src/core/attendance-repair.ts": ["test/e2e/attendance-repair-postgres.test.ts"],
+ "src/core/extract-timeline-from-meetings.ts": ["test/e2e/extract-timeline-attendance-postgres.test.ts"],
+ "src/core/derived-links.ts": ["test/e2e/attendance-retrieval-postgres.test.ts", "test/e2e/attendance-repair-postgres.test.ts"],
+ "src/core/link-reconciliation.ts": ["test/e2e/attendance-retrieval-postgres.test.ts"],
+ "src/core/persistence/links-preparation.ts": ["test/e2e/attendance-retrieval-postgres.test.ts"],
+ "src/core/sweep.ts": ["test/e2e/attendance-retrieval-postgres.test.ts"],
// v0.38 ingestion substrate. POST /ingest lives inside serve-http.ts
// (per the plan-eng-review E1 decision); the daemon + built-in sources
// + ingest_capture Minion handler all feed the in-process roundtrip
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index fe11b01f1b..76390f260a 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -3,12 +3,12 @@
# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in
# the same commit as any peel (the guard fails on >50 lines of stale slack).
# Columns: path max_lines policy note
-src/cli.ts 4073 ratchet +48 fix wave: get_versions --json + honest ellipsis (#4692), boolean-flag literal true/false consume (#4602); grown v0.46.26.0 megawave: SIGCHLD reaper install, silent-failure surfacing, confirm-race gate (#2443 #2898 #2297); grown wave-g (#4488 #4508): in-band error exit codes + think --source validation; grown db-availability loop: engine/db-repair dispatch, degraded-serve catch, marker choke points (bottom handler + no-config exit + doctor fallback), engine-free config-set dispatch; fix cycle: static classifier imports, resolved-brain degraded gate, guarded reconnect, help rows; +chat-connectors wiring (master merge); wave-k +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +master-merge true-up; +20 gbrain backup pre-engine dispatch + startup backup nag rail (monthly backup check); wave-k: +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +3: doctor --no-migrate probeOnly seam (#4364); +37 v0.47 gmail-loops: google/creds dispatch + waiting/loops cases + self-help entries + OPEN LOOPS help section; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: CLI combines hosted access and explicit legacy queue review; lowered to 4077: GHSA wave v0.50.5.0 moved the #3688 guardrails block into core/cli-preflight.ts (-10); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; #5252 wave: partial-retrieval notices and resident code reindex delegation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared skills: parse typed object/array operation flags before resident-owner delegation; merged reliability/shared-skills source integration; retired provider integration removed
+src/cli.ts 4096 ratchet +48 fix wave: get_versions --json + honest ellipsis (#4692), boolean-flag literal true/false consume (#4602); grown v0.46.26.0 megawave: SIGCHLD reaper install, silent-failure surfacing, confirm-race gate (#2443 #2898 #2297); grown wave-g (#4488 #4508): in-band error exit codes + think --source validation; grown db-availability loop: engine/db-repair dispatch, degraded-serve catch, marker choke points (bottom handler + no-config exit + doctor fallback), engine-free config-set dispatch; fix cycle: static classifier imports, resolved-brain degraded gate, guarded reconnect, help rows; +chat-connectors wiring (master merge); wave-k +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +master-merge true-up; +20 gbrain backup pre-engine dispatch + startup backup nag rail (monthly backup check); wave-k: +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +3: doctor --no-migrate probeOnly seam (#4364); +37 v0.47 gmail-loops: google/creds dispatch + waiting/loops cases + self-help entries + OPEN LOOPS help section; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: CLI combines hosted access and explicit legacy queue review; lowered to 4077: GHSA wave v0.50.5.0 moved the #3688 guardrails block into core/cli-preflight.ts (-10); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; #5252 wave: partial-retrieval notices and resident code reindex delegation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared skills: parse typed object/array operation flags before resident-owner delegation; merged reliability/shared-skills source integration Explicit-policy thin recall routing before local engine connection; actual CLI subprocess regression coverage. Reject explicit thin recall brain selection before dispatch.; +10 A2 preview-bound attendance repair dispatch and help; integrated upstream provider retirement with thin recall and gated repair dispatch
src/commands/autopilot.ts 2671 ratchet grown v0.46.26.0 megawave (#4300 #4285 #3696) + master v0.46.27.0 env-file lane + boot warning + reload-safe install (#2608 #4443) + 1 nosemgrep dataflow annotation (path-traversal audit); +chat-connectors wiring; +20 #4728 wrapper exec guard (baked CLI path gone -> PATH fallback / --install hint); +5 #4952 (refs #4399): syncEnabled=false skip in the freshness dispatch loop
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 2144 ratchet lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring
src/commands/extract-conversation-facts.ts 2125 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364)
-src/commands/extract.ts 2659 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions
+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/jobs.ts 3210 ratchet grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled); security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; queued import failures remain failures; master integration: grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled); #5105: two-line delegate validates revision and durable authority before fact backstop execution; upstream integration: preserve independently reviewed master additions with branch facade extraction; +13 v0.50.5.0 security merge (upstream delta; coordinated facade retained); merged reliability/shared-skills source integration
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 4500 ratchet +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
@@ -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 1546 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
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 1878 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
+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/embedding-migration.ts 1435 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed
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/scripts/run-e2e.sh b/scripts/run-e2e.sh
index 2f25c406f8..c0a6b300c4 100755
--- a/scripts/run-e2e.sh
+++ b/scripts/run-e2e.sh
@@ -287,12 +287,15 @@ for f in "${files[@]}"; do
else
TIMEOUT_CMD=""
fi
+ FILE_HOME="$E2E_TMP_HOME/file-$file_idx"
+ mkdir -p "$FILE_HOME/.gbrain"
rc=0
- $TIMEOUT_CMD bun test --timeout=60000 ${COVERAGE_ARGS[@]+"${COVERAGE_ARGS[@]}"} "$f" > "$E2E_TMP_HOME/current.log" 2>&1 &
+ HOME="$FILE_HOME" GBRAIN_HOME="$FILE_HOME" $TIMEOUT_CMD bun test --timeout=60000 ${COVERAGE_ARGS[@]+"${COVERAGE_ARGS[@]}"} "$f" > "$E2E_TMP_HOME/current.log" 2>&1 &
ACTIVE_E2E_PID=$!
wait "$ACTIVE_E2E_PID" || rc=$?
ACTIVE_E2E_PID=""
output=$(cat "$E2E_TMP_HOME/current.log")
+ rm -rf "$FILE_HOME"
if [ "$rc" -eq 0 ]; then
if [ "$f" = "test/e2e/pgbouncer-teardown.test.ts" ] && \
[ "${GBRAIN_CI_REQUIRE_PGBOUNCER:-0}" = "1" ] && \
diff --git a/skills/brain-ops/SKILL.md b/skills/brain-ops/SKILL.md
index 4f4e1c484b..153ce158bd 100644
--- a/skills/brain-ops/SKILL.md
+++ b/skills/brain-ops/SKILL.md
@@ -9,6 +9,7 @@ description: |
triggers:
- any brain read/write/lookup/citation
tools:
+ - recall
- search
- query
- get_page
@@ -50,6 +51,18 @@ suppresses writes for that turn, including when standing capture is enabled.
> Fall back to the classic ops when the verbs aren't on the surface. Contract:
> `docs/protocol/MEMORY_VERBS_v1.md`.
>
+> **Tight-budget page questions:** explicitly use
+> `recall({query: "zebra telescope", budget_tokens: 75, budget_policy: "query_first"})`
+> so ranked page evidence packs before recent facts. CLI:
+> `gbrain recall --query 'zebra telescope' --budget-tokens 75 --budget-policy query_first --json`.
+> Keep entity-first, event/session-filtered and fact-focused questions on their
+> existing facts-first route; do not change `context_pack`. Costs are character-based
+> estimates, and an oversized first item is dropped without skipping or truncation.
+> Read `budget_packing` before interpreting an empty result as missing memory.
+> See `skills/query/SKILL.md` for the MCP request and caller example. Guidance is
+> not native-harness activation: adoption remains unverified until a fresh
+> conversation is observed making the opted-in call.
+>
> **Choose a readback path that can see the intended visibility.** Trusted local
> CLI callers can recall and withdraw private facts. Every MCP caller, including
> stdio, and a thin CLI connected to MCP currently have world-only fact recall
diff --git a/skills/migrations/v0.58.0.0.md b/skills/migrations/v0.58.0.0.md
new file mode 100644
index 0000000000..903f1905fe
--- /dev/null
+++ b/skills/migrations/v0.58.0.0.md
@@ -0,0 +1,85 @@
+# Upgrade to v0.58.0.0: explicit attendance and optional question-first recall
+
+Preserve the agent's identity, source grants, capture preferences, provider
+choices and existing service opt-outs. This release adds no schema migration
+and authorizes no live repair, automatic backfill or paid enrichment.
+
+## Upgrade and verify without changing defaults
+
+1. On a managed deployment, stop and drain older owners and workers before
+ replacing them. Retain the original installation and a verified full
+ database backup. A Markdown export is not a full backup.
+2. Use the supported upgrade path while retaining independent opt-outs:
+
+ ```bash
+ GBRAIN_NO_AUTOPILOT_INSTALL=1 GBRAIN_NO_REEMBED=1 gbrain upgrade --no-autopilot-install
+ ```
+
+ If an earlier migration failed, inspect that failure before using
+ `gbrain apply-migrations --yes --no-autopilot-install`. Do not delete its
+ ledger, rerun initialization or enable capture to bypass a refusal.
+3. Restart compatible owners/workers and verify the installed version and
+ a permitted page read through the existing connection:
+
+ ```bash
+ gbrain --version
+ gbrain sources writer status --json
+ ```
+
+ The version should be `0.58.0.0` or a later approved release. Retain the
+ existing brain and source selection; do not switch them just to make a
+ check pass. A writer claim is not permission to activate it.
+
+## Keep question-first recall opt-in
+
+Omitted `budget_policy` retains the existing facts-first behavior. Only use
+`query_first` for a question where matching page evidence should take priority
+over stored facts:
+
+```bash
+gbrain recall --query 'What did the planning meeting decide?' \
+ --budget-tokens 512 --budget-policy query_first --json
+```
+
+The memory verb accepts the same choice as `budget_policy: "query_first"`.
+Use `facts_first` for fact-focused consumers. Review returned evidence rather
+than treating a small synthetic packing win as a general answer-quality claim.
+No query-expansion change or native-harness activation is part of this upgrade.
+
+## Inspect attendance rules before extracting
+
+Read [the evidence and operator guide](../../docs/guides/attendance-evidence.md).
+Where the active schema does not override attendance, explicit attendee lists
+must resolve to live person pages; ordinary mentions, code examples and hidden
+comments are not attendance evidence. Removing supported evidence retracts only
+the origin's owned claims. Unresolved references preserve the graph for retry.
+
+Pack-owned directions remain unchanged. In particular, the shipped base and
+company packs retain their outgoing attendance mappings and do not gain
+incoming attendance lookup. Do not disable or rewrite a pack to force a match.
+Restore a missing pack before retrying refused extraction. Normal remote page
+writes keep their existing deferred-maintenance behavior.
+
+## Historical repair requires a separate decision
+
+Do not run repair automatically from this migration guide. The trusted-local
+`gbrain extract links --source db --repair-attendance --source-id notes --json`
+surface can preview a bounded window only after the operator chooses a live
+source. Keep the preview private and inspect proposed additions, removals and
+skips. MCP and thin clients cannot perform this operation.
+
+Before applying, quiesce older extraction writers, verify a full database backup
+and its recovery procedure, and obtain approval for the exact saved preview's
+digest. Follow the operator guide's private-directory, confirmation and
+checkpoint requirements. `--backup-verified` acknowledges the operator's
+verification; it does not create or verify a backup.
+
+Each origin commits separately and briefly locks link writers database-wide.
+Changed inputs refuse the preview, and approvals and commit proofs have bounded
+lifetimes. Resume only with the exact approved command and private checkpoint;
+when the guide requires a fresh preview, obtain fresh approval too. Reverting
+the binary does not undo a completed repair.
+
+If verification fails, preserve the refusal and inspect it before retrying.
+Report a sanitized description at https://github.com/garrytan/gbrain/issues;
+never attach credentials, private previews, checkpoint contents or backups.
diff --git a/skills/query/SKILL.md b/skills/query/SKILL.md
index 819f7b9e07..5815c66bc8 100644
--- a/skills/query/SKILL.md
+++ b/skills/query/SKILL.md
@@ -19,6 +19,7 @@ triggers:
- "connections"
- "graph query"
tools:
+ - recall
- search
- query
- get_page
@@ -101,6 +102,41 @@ Answers should include:
Search returns **chunks**, not full pages. Read the excerpts first before deciding
whether to load a full page.
+For a question about saved **page evidence** with a tight budget, explicitly choose
+`recall` with `budget_policy: "query_first"`. It gives the existing ranked page
+results first use of the budget, then packs recent/filtered facts into what remains.
+This is an opt-in packing choice, not a new relevance model: an irrelevant page can
+displace a useful fact. Keep entity-first, session/event-filtered and fact-focused
+questions on their existing facts-first route. Do not change `context_pack` or
+existing third-party calls.
+
+```bash
+gbrain recall --query 'zebra telescope' --budget-tokens 75 --budget-policy query_first --json
+```
+
+Equivalent MCP request:
+
+```json
+{"name":"recall","arguments":{"query":"zebra telescope","budget_tokens":75,"budget_policy":"query_first"}}
+```
+
+**Say to your agent:** “Recall the saved notes about the zebra telescope using a
+75-token estimated budget and query-first packing. Cite the returned evidence;
+if the first page cannot fit, tell me rather than treating that as missing memory.”
+
+Use the resolved brain and source as usual; the option does not widen permissions.
+`budget_packing` reports the effective policy and per-arm candidate/kept/dropped/used
+counts. Costs estimate `ceil(fact.length/4)` or
+`ceil(title.length/4) + ceil(chunk.length/4)`, not exact tokenizer or JSON-envelope
+size. Packing never skips an oversized prefix item or truncates it; multiple
+required pages may still not fit. With no nonblank query or no positive finite
+budget, the operation keeps legacy behavior. An eligible positive budget below one
+token returns empty arms. See the protocol for fractional-budget compatibility.
+
+This guidance and advertised tool schemas do not prove native-harness adoption.
+Confirm an observed query-first call in a fresh harness conversation before
+claiming activation; otherwise report adoption as unverified.
+
- `gbrain search` / `gbrain query` return ranked chunks with context snippets.
These are often enough to answer the question directly.
- Only use `gbrain get <slug>` to load the full page when a chunk confirms the
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index 20350ed45b..6ef6883f9e 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -20,7 +20,7 @@
"brain-ingest-gate/routing-eval.jsonl": "281e94affbb8631ef7ff44203884cce1c03c468b27f893829da1e6e439401a33",
"brain-link-discipline/SKILL.md": "489268f71a01abb6213df8a8bb5f4d16d587b09dd670ac3c47876a8ed808b5ae",
"brain-link-discipline/routing-eval.jsonl": "0adea4c6d72fdb849c12fe2cad718568b9ab704299b00b093c40c2284faf684c",
- "brain-ops/SKILL.md": "a76ee75dba71c4aa534f252e35e355ae0a7530f961d43ffe7243a285f142adfc",
+ "brain-ops/SKILL.md": "566dcf7f12f18fab09967c5ab4f77ce949f1a2151dc707f678c0a9e3b835b3df",
"brain-pdf/SKILL.md": "13c3e3162763a4503685db0a10663475d3687c4874b5f04d539af83a990f643e",
"brain-pdf/routing-eval.jsonl": "119e4fa113ea45783cee4499e63a729fdeecb4d9a45d47497754b4f5b21d0734",
"brain-taxonomist/SKILL.md": "dea4557b540868ec2c56bf43ee7f63c5d03a22d4047cd0dfbeaf19adef334f60",
@@ -147,6 +147,7 @@
"migrations/v0.53.0.0.md": "117461f687ea33e0ba2a952aecd00b9d2085a2a0562d2b1b50145dad0a5a4728",
"migrations/v0.54.1.0.md": "ceee87cfc7bb28036e9cadb5b70b7ec9eabcce6d445e259f3ee410a95fe69603",
"migrations/v0.56.2.0.md": "e88f04a5deaef82ebb8bd194aec931f26e69e87687098eb64b94666931b5e319",
+ "migrations/v0.58.0.0.md": "a6ee3d3125ff1be612df776c7b8d6dfcaeb57ca073255793a67dff78a23c51cc",
"migrations/v0.7.0.md": "97c2740445a10b1c5c7123c17dbd625fa27a94095b85d27c2b278da756c4c59a",
"migrations/v0.8.0.md": "1919ff8b8f3680612ff888e7cfcc0d86ece5d5304ae19af4497bdf40b050561a",
"migrations/v0.8.1.md": "fad7341cfb5e02545fb8a23221d12ab395fc3d8db15d1d8ee8a18844aea6563a",
@@ -161,7 +162,7 @@
"postgres-adopt/SKILL.md": "4c402527bd0d98aa4e7f1a341a25ac0d1bba5e98b3dd55bcc5e30ed2858fa0e0",
"postgres-adopt/routing-eval.jsonl": "db91c1fae408a45082979c402c11eff413277ace6cf746297cc86009dcaefe06",
"publish/SKILL.md": "e06b609db780a3cc93a1755a87b30ff08ffdc0fdbc834c1422b2ad2489b57497",
- "query/SKILL.md": "b12aae4e86b893038b1d9e97a977bd6a7939db9f5c57dde12c11d8d7451e0762",
+ "query/SKILL.md": "7a5857b4898f2e20cfa2d69c4d24e071978ab38a7471a12d9652da4093f202c1",
"query/routing-eval.jsonl": "74f5a91e52fabc54e0e9403fa17db87ee26bb7ebb8ae8005148c51142abc62fe",
"remote-mcp/SKILL.md": "3021054e2b21fa589310181d5140bc6caae5a4d75e3f3aa2cdbddac272cd4873",
"remote-mcp/routing-eval.jsonl": "7287693135c9fe2d6495d81d22746ddf41b116254db4b6e683dbdee251e08f8e",
diff --git a/src/cli.ts b/src/cli.ts
index 52f91d98cc..d47b81bada 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -470,6 +470,13 @@ async function main() {
return;
}
+ if (command === 'extract' && !args.some(arg => arg === '--help' || arg === '-h')
+ && args.some(arg => ['--repair-attendance', '--apply-preview', '--backup-verified', '--confirm', '--checkpoint'].includes(arg.split('=')[0]))) {
+ const { runAttendanceRepairCli } = await import('./commands/extract-attendance-repair.ts');
+ await runAttendanceRepairCli(args.slice(1), cliOpts.brain);
+ return;
+ }
+
// v0.42 self-upgrade: ride this invocation as an update heartbeat. Cache-read-
// only, fail-open, never blocks. Skips the update path's own commands + sets
// GBRAIN_SKIP_STARTUP_HOOKS for their children. Runs for every real command.
@@ -2960,6 +2967,19 @@ async function handleCliOnly(command: string, args: string[]) {
}
}
+ if (command === 'recall' && isThinClient(loadConfig())) {
+ const { hasRecallBudgetPolicy, runRecall } = await import('./commands/recall.ts');
+ if (hasRecallBudgetPolicy(args)) {
+ if (getCliOptions().brain) {
+ console.error('--brain is not supported on a thin-client install: the remote server is a single brain. ' +
+ 'Remove the flag, or run from a machine with local mounts (gbrain mounts list).');
+ process.exit(1);
+ }
+ await runRecall(null as never, args);
+ return;
+ }
+ }
+
// All remaining CLI-only commands need a DB connection.
// db-availability loop (4c): `serve` alone survives a dead POSTGRES here —
// degraded mode keeps the MCP server present in the harness (the classified
@@ -2990,35 +3010,35 @@ async function handleCliOnly(command: string, args: string[]) {
return null;
}
})();
- const degradable =
- command === 'serve' &&
+ if (command === 'serve' &&
process.env.GBRAIN_SERVE_DEGRADED !== '0' &&
process.env.GBRAIN_SERVE_DEGRADED !== 'false' &&
- resolvedEngineKind === 'postgres';
- if (!degradable) throw serveConnectError;
- try {
- const d = classifyDbAccessError(serveConnectError, { url: loadConfig()?.database_url ?? null, brainId: dbMarkerBrainId() });
- console.error(`${formatDbMarker(d)}\n${d.message}\n${d.remediation} Run: gbrain db-repair`);
- } catch { /* marker is best-effort; degraded serve still starts */ }
- const { createDegradedEngine } = await import('./core/degraded-engine.ts');
- const degraded = createDegradedEngine({
- initialError: serveConnectError,
- // Guarded reconnect: connectEngine's no-config path calls
- // process.exit(1) directly — if config.json disappears while serve is
- // degraded, the reconnect must THROW into the classified envelope, not
- // kill the live MCP server mid-RPC. HOST brains only: a mount routes
- // through connectMountEngine before loadConfig() and needs no host
- // config, so the guard must not brick a mount serve's recovery.
- reconnect: async () => {
- if ((dbMarkerBrainId() ?? 'host') === 'host' && !loadConfig()) {
- throw new Error('No brain configured (config.json missing or unreadable). Run: gbrain init');
- }
- return connectEngine();
- },
- });
- const { runServe } = await import('./commands/serve.ts');
- await runServe(degraded, args);
- return; // serve doesn't disconnect
+ resolvedEngineKind === 'postgres') {
+ try {
+ const d = classifyDbAccessError(serveConnectError, { url: loadConfig()?.database_url ?? null, brainId: dbMarkerBrainId() });
+ console.error(`${formatDbMarker(d)}\n${d.message}\n${d.remediation} Run: gbrain db-repair`);
+ } catch { /* marker is best-effort; degraded serve still starts */ }
+ const { createDegradedEngine } = await import('./core/degraded-engine.ts');
+ const degraded = createDegradedEngine({
+ initialError: serveConnectError,
+ // Guarded reconnect: connectEngine's no-config path calls
+ // process.exit(1) directly — if config.json disappears while serve is
+ // degraded, the reconnect must THROW into the classified envelope, not
+ // kill the live MCP server mid-RPC. HOST brains only: a mount routes
+ // through connectMountEngine before loadConfig() and needs no host
+ // config, so the guard must not brick a mount serve's recovery.
+ reconnect: async () => {
+ if ((dbMarkerBrainId() ?? 'host') === 'host' && !loadConfig()) {
+ throw new Error('No brain configured (config.json missing or unreadable). Run: gbrain init');
+ }
+ return connectEngine();
+ },
+ });
+ const { runServe } = await import('./commands/serve.ts');
+ await runServe(degraded, args);
+ return; // serve doesn't disconnect
+ }
+ throw serveConnectError;
}
try {
switch (command) {
@@ -3884,6 +3904,9 @@ TOOLS
extract links --by-mention [--ner] --source db
extract timeline --from-meetings [--infer-dates] --source db
extract --stale [--source-id ID] [--catch-up] [--dry-run] [--json]
+ extract links --source db --repair-attendance --source-id ID
+ [--limit 250] [--after-slug SLUG] [--json]
+ Apply: --apply-preview FILE --confirm DIGEST --yes --backup-verified --checkpoint FILE
extract --explain <kind> [--json] Full details: gbrain extract --help
publish <page.md> [--password] Shareable HTML (strips private data, optional AES-256)
check-backlinks <check|fix> [dir] Find/fix missing back-links across brain
diff --git a/src/commands/extract-attendance-repair.ts b/src/commands/extract-attendance-repair.ts
new file mode 100644
index 0000000000..a3576572e3
--- /dev/null
+++ b/src/commands/extract-attendance-repair.ts
@@ -0,0 +1,188 @@
+import { closeSync, constants, existsSync, fstatSync, fsyncSync, lstatSync, openSync, readFileSync,
+ renameSync, unlinkSync, writeFileSync } from 'node:fs';
+import { dirname, join, resolve } from 'node:path';
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../core/engine.ts';
+import type { EngineConfig } from '../core/types.ts';
+import { loadConfig, isThinClient, toEngineConfig } from '../core/config.ts';
+import { createEngine } from '../core/engine-factory.ts';
+import { resolveBrainId } from '../core/brain-resolver.ts';
+import { loadMounts } from '../core/brain-registry.ts';
+import { readRepairSidecar } from '../core/pglite-repair.ts';
+import { applyAttendanceRepair, previewAttendanceRepair, attendanceRepairHash, assertAttendanceRepairAuthority,
+ validateAttendanceRepairScope, ATTENDANCE_REPAIR_LIMIT, type AttendanceRepairPreview,
+ type AttendanceRepairAuthority } from '../core/attendance-repair.ts';
+
+export const ATTENDANCE_REPAIR_HELP = ` gbrain extract links --source db --repair-attendance --source-id ID
+ [--limit 250] [--after-slug SLUG] [--json]
+ Read-only attendance preview (maximum 1000 source pages), JSON receipt on stdout.
+ Only trusted local callers; no filesystem/stale/global extraction modes.
+ Apply the exact private preview with --apply-preview FILE --confirm DIGEST
+ --yes --backup-verified --checkpoint FILE. Requires a verified full DB backup.
+ See docs/guides/attendance-evidence.md for bounds and pack exclusions.
+`;
+
+export function isAttendanceRepairRequest(args: string[]) {
+ return args.some(arg => ['--repair-attendance', '--apply-preview', '--backup-verified', '--confirm', '--checkpoint'].includes(arg.split('=')[0]));
+}
+
+export function attendanceRepairConnectionIdentity(brainId: string, connection: EngineConfig) {
+ if (connection.engine === 'pglite') {
+ if (!connection.database_path || connection.database_path.includes('\0')) throw new Error('Attendance repair requires an explicit PGLite path');
+ return attendanceRepairHash([brainId, { engine: 'pglite', path: resolve(connection.database_path) }]);
+ }
+ try {
+ if (connection.engine && connection.engine !== 'postgres') throw new Error();
+ const value = connection.database_url;
+ if (!value || /[\x00-\x20\x7f]/.test(value)) throw new Error();
+ const match = value.match(/^(postgres(?:ql)?:)\/\/([^/?#]+)(\/[^?#]*)(?:\?([^#]*))?$/i);
+ if (!match || match[2].indexOf('@') !== match[2].lastIndexOf('@')) throw new Error();
+ const scheme = match[1].toLowerCase();
+ const authority = match[2].slice(match[2].lastIndexOf('@') + 1);
+ const hosts = authority.split(',').map(host => {
+ if (!host || host.includes('%')) throw new Error();
+ const parsed = new URL(`${scheme}//${host}/`);
+ if (!parsed.hostname || parsed.username || parsed.password || parsed.pathname !== '/') throw new Error();
+ return parsed;
+ });
+ const query = new URLSearchParams(match[4]);
+ if ([...query.keys()].some(key => ['host', 'hostaddr', 'hostname', 'port', 'database', 'dbname', 'db', 'path', 'service', 'servicefile']
+ .includes(key.toLowerCase()))) throw new Error();
+ const database = new URL(`${scheme}//${authority.split(',')[0]}${match[3]}`).pathname.slice(1);
+ if (!database) throw new Error();
+ const fallbackPort = hosts[0].port || process.env.PGPORT || '5432';
+ const endpoints = hosts.map(host => {
+ const port = host.port || fallbackPort;
+ if (!/^\d+$/.test(port) || Number(port) < 1 || Number(port) > 65535) throw new Error();
+ return [host.hostname.toLowerCase(), Number(port)];
+ });
+ return attendanceRepairHash([brainId, { engine: 'postgres', scheme, hosts: endpoints, database }]);
+ } catch {
+ throw new Error('Attendance repair requires a supported explicit PostgreSQL endpoint and database');
+ }
+}
+
+export function parseAttendanceRepairArgs(args: string[], authority: AttendanceRepairAuthority) {
+ assertAttendanceRepairAuthority(authority);
+ if (args[0] !== 'links') throw new Error('Attendance repair requires extract links');
+ const values = new Map<string, string | boolean>();
+ const booleans = new Set(['--repair-attendance', '--yes', '--backup-verified', '--json', '--dry-run']);
+ const valued = new Set(['--source', '--source-id', '--limit', '--after-slug', '--apply-preview', '--confirm', '--checkpoint']);
+ for (let index = 1; index < args.length; index++) {
+ const flag = args[index];
+ if (values.has(flag)) throw new Error('Repeated attendance repair flag');
+ if (booleans.has(flag)) values.set(flag, true);
+ else if (valued.has(flag) && args[index + 1] && !args[index + 1].startsWith('--')) values.set(flag, args[++index]);
+ else throw new Error('Unsupported attendance repair flag or combination');
+ }
+ if (!values.has('--repair-attendance') || values.get('--source') !== 'db' || !values.get('--source-id')) {
+ throw new Error('Attendance repair requires --source db --repair-attendance --source-id ID');
+ }
+ const sourceId = values.get('--source-id') as string;
+ const limit = values.has('--limit') ? Number(values.get('--limit')) : ATTENDANCE_REPAIR_LIMIT;
+ const afterSlug = values.get('--after-slug') as string | undefined;
+ validateAttendanceRepairScope(sourceId, limit, afterSlug);
+ const apply = values.get('--apply-preview') as string | undefined;
+ const confirm = values.get('--confirm') as string | undefined;
+ const checkpoint = values.get('--checkpoint') as string | undefined;
+ if (apply) {
+ if (!values.has('--yes') || !values.has('--backup-verified') || !confirm || !/^[a-f0-9]{64}$/.test(confirm) || !checkpoint
+ || ['--dry-run', '--limit', '--after-slug'].some(flag => values.has(flag))) {
+ throw new Error('Apply requires --apply-preview FILE --confirm DIGEST --yes --backup-verified --checkpoint FILE; no scan or dry-run flags');
+ }
+ if (resolve(apply) === resolve(checkpoint)) throw new Error('Preview and checkpoint paths must differ');
+ } else if (['--yes', '--backup-verified', '--confirm', '--checkpoint'].some(flag => values.has(flag))) {
+ throw new Error('Apply confirmation requires --apply-preview FILE');
+ }
+ return { sourceId, limit, afterSlug, apply, confirm, checkpoint, json: values.has('--json') };
+}
+
+function privateStat(path: string, directory = false) {
+ const stat = lstatSync(path);
+ if (stat.isSymbolicLink() || (directory ? !stat.isDirectory() : !stat.isFile())
+ || (stat.mode & 0o077) !== 0 || (process.getuid && stat.uid !== process.getuid())) {
+ throw new Error('Repair receipt and checkpoint must be private, owned, non-symlink files in a private directory');
+ }
+ return stat;
+}
+
+function readPrivateJson(path: string) {
+ privateStat(dirname(resolve(path)), true);
+ privateStat(path);
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
+ try {
+ const stat = fstatSync(fd);
+ if (!stat.isFile() || stat.size > 32 * 1024 ** 2 || (stat.mode & 0o077) !== 0
+ || (process.getuid && stat.uid !== process.getuid())) throw new Error('Invalid or oversized private repair receipt');
+ return JSON.parse(readFileSync(fd, 'utf8'));
+ } finally { closeSync(fd); }
+}
+
+export async function runAttendanceRepair(engine: BrainEngine, args: string[], authority: AttendanceRepairAuthority,
+ brainIdentity?: string) {
+ const options = parseAttendanceRepairArgs(args, authority);
+ if (!options.apply) {
+ const preview = await previewAttendanceRepair(engine, { ...options, remote: false, brainIdentity });
+ if (!options.json) console.error(`Attendance preview: ${preview.counts.scanned} source pages scanned, ${preview.counts.eligibleOrigins} eligible origins, ${preview.counts.changed} changed; ${preview.counts.add} add, ${preview.counts.remove} remove, ${preview.counts.skipped} skipped. Frontmatter is report-only. No changes applied.`);
+ process.stdout.write(JSON.stringify(preview) + '\n');
+ return preview;
+ }
+ const preview = readPrivateJson(options.apply) as AttendanceRepairPreview;
+ const checkpoint = resolve(options.checkpoint!);
+ privateStat(dirname(checkpoint), true);
+ if (existsSync(checkpoint)) {
+ const previous = readPrivateJson(checkpoint);
+ if (previous.digest !== preview.digest || previous.sourceIncarnation !== preview.sourceIncarnation
+ || previous.ontology !== preview.ontology) throw new Error('Checkpoint belongs to another preview, source or ontology');
+ }
+ const result = await applyAttendanceRepair(engine, preview, { remote: false, sourceId: options.sourceId,
+ brainIdentity, confirm: options.confirm!, yes: true, backupVerified: true,
+ checkpoint: async state => {
+ privateStat(dirname(checkpoint), true);
+ if (existsSync(checkpoint)) privateStat(checkpoint);
+ const temporary = `${checkpoint}.${randomUUID()}.tmp`;
+ const fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
+ try { writeFileSync(fd, JSON.stringify(state) + '\n'); fsyncSync(fd); }
+ finally { closeSync(fd); }
+ try { renameSync(temporary, checkpoint); }
+ catch (error) { unlinkSync(temporary); throw error; }
+ const directory = openSync(dirname(checkpoint), constants.O_RDONLY);
+ try { fsyncSync(directory); } finally { closeSync(directory); }
+ } });
+ process.stdout.write(JSON.stringify({ digest: preview.digest, ...result }) + '\n');
+ return result;
+}
+
+export async function runAttendanceRepairCli(args: string[], brainFlag: string | null) {
+ parseAttendanceRepairArgs(args, { remote: false });
+ const config = loadConfig();
+ if (isThinClient(config)) throw new Error('Attendance repair is unavailable to remote or thin clients');
+ const brainId = resolveBrainId(brainFlag);
+ let connection: EngineConfig;
+ if (brainId === 'host') {
+ if (!config) throw new Error('Attendance repair requires an existing configured brain');
+ connection = toEngineConfig(config);
+ } else {
+ const mount = loadMounts().find(entry => entry.id === brainId && entry.enabled !== false);
+ if (!mount) throw new Error('Attendance repair requires an existing direct local mount');
+ connection = { engine: mount.engine, database_url: mount.database_url, database_path: mount.database_path };
+ }
+ if (connection.engine === 'pglite') {
+ if (!connection.database_path || !existsSync(join(connection.database_path, 'PG_VERSION')))
+ throw new Error('Attendance repair cannot create a PGLite database');
+ if (readRepairSidecar(connection.database_path).episodeStartedAt !== null)
+ throw new Error('Resolve the existing PGLite repair episode before attendance preview');
+ } else if (!connection.database_url) throw new Error('Attendance repair requires an existing database URL');
+ const brainIdentity = attendanceRepairConnectionIdentity(brainId, connection);
+ const engine = await createEngine(connection);
+ const previousRepair = process.env.GBRAIN_PGLITE_WAL_REPAIR;
+ process.env.GBRAIN_PGLITE_WAL_REPAIR = 'off';
+ try {
+ await engine.connect({ ...connection, poolSize: 1 } as EngineConfig & { poolSize: number });
+ await runAttendanceRepair(engine, args, { remote: false }, brainIdentity);
+ } finally {
+ await engine.disconnect();
+ if (previousRepair === undefined) delete process.env.GBRAIN_PGLITE_WAL_REPAIR;
+ else process.env.GBRAIN_PGLITE_WAL_REPAIR = previousRepair;
+ }
+}
diff --git a/src/commands/extract.ts b/src/commands/extract.ts
index af0dd53b65..4c5e469741 100644
--- a/src/commands/extract.ts
+++ b/src/commands/extract.ts
@@ -40,14 +40,17 @@
import { readFileSync, readdirSync, lstatSync, existsSync } from 'fs';
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 type { PageType } from '../core/types.ts';
import { parseMarkdown } from '../core/markdown.ts';
-import { loadLinkPageMetadata, type LinkPageMetadata } from '../core/link-reconciliation.ts';
+import { resolveCandidateSources, resolveLinkFallbackDefault, loadLinkPageMetadata, capturedLinkEndpoints, fileLinkOwnership, replaceFileLinks, type LinkPageMetadata } from '../core/link-reconciliation.ts';
export { reconcileSourceLinks, type SourceLinkReconciliationResult } from '../core/link-reconciliation.ts';
+export { extractMarkdownLinks } from '../core/link-extraction.ts';
import {
extractPageLinks, parseTimelineEntries, deriveTimelineAnchor, inferLinkType, makeResolver,
+ attendanceEvidenceRanges, hasAttendanceEvidence, resolvedLinkCandidate, orientCanonicalAttendance, extractMarkdownLinks,
extractFrontmatterLinks, isGlobalBasenameEnabled, isCrossSourceLinksEnabled, LINK_EXTRACTOR_VERSION_TS,
WIKILINK_BASENAME_LINK_TYPE,
buildBasenameIndex, queryBasenameIndex, stripCodeBlocks, normalizeBasename,
@@ -76,7 +79,6 @@ export type { WithRetryOpts } from '../core/retry.ts';
import { buildGazetteer, findMentionedEntities, hashGazetteer } from '../core/by-mention.ts';
// #4611: the cross-source link fallback follows the configured
// `sources.default` (validated shape) instead of the literal 'default'.
-import { isValidSourceId } from '../core/source-id.ts';
import {
loadOpCheckpoint, recordCompleted, clearOpCheckpoint, mentionsFingerprint,
} from '../core/op-checkpoint.ts';
@@ -199,122 +201,7 @@ function refsWithSnapshotStamps(
return out;
}
-/**
- * v0.42.7 (#1696): pure cross-source resolution for one extracted link
- * candidate. Validates both endpoints exist (else the batch JOIN drops the row),
- * then picks from_source_id / to_source_id: prefer the origin page's source,
- * fall back to 'default', else skip (never push a wrong-source edge). Shared
- * by extractLinksFromDB and extractStaleFromDB so the F10 multi-source
- * resolution and the source-isolation policy can't drift.
- *
- * v0.46.28.0 (#2589): the failure case now carries a `reason` instead of a
- * bare `null`. A target that resolves via `global_basename` to a page that
- * exists ONLY in a source other than the origin's or 'default' was
- * indistinguishable from a genuinely-missing target — both silently dropped
- * the candidate and both counted (misleadingly) as "target page doesn't
- * exist". This stays default-deny by design: cross-source edges remain
- * unwritten (source isolation — see CLAUDE.md), but callers can now
- * attribute the drop correctly instead of reporting a wrong reason.
- *
- * #3478: only a federated origin source may fall back to 'default'; when
- * `allowCrossSource` is false both endpoints must live in the page's own
- * source, else skip with reason 'cross_source' (never push a wrong-source
- * edge).
- *
- * #3908: `opts.crossSource` (the `link_resolution.cross_source` config flag)
- * is the explicit operator opt-in — it supersedes the ambient federation
- * gate, which only exists to stop DEFAULT-ON silent cross-source regrowth.
- * With it on, a cross-source-only candidate resolves with the
- * lexicographically smallest matching source (deterministic, so repeated
- * extracts and both engines converge on the same edge under the
- * (source_id, slug) composite key) instead of dropping with 'cross_source'.
- *
- * #4611: the fallback lane compares against `opts.defaultSourceId` (the
- * configured `sources.default`, resolved once per run by the callers via
- * resolveLinkFallbackDefault) instead of the LITERAL string 'default'.
- * Renaming the brain's default source no longer silently kills the
- * cross-source fallback. Omitted → 'default' (back-compat).
- */
-export type CandidateSourceResolution =
- | { ok: true; fromSlug: string; fromSourceId: string; toSourceId: string }
- | { ok: false; reason: 'missing_target' | 'missing_from' | 'cross_source' };
-
-/**
- * #4611: resolve the source id the cross-source link fallback compares
- * against. Reads the operator-configured `sources.default` (same key the
- * write-routing ladder in source-resolver.ts tier 5 reads), silently
- * falling back to the seeded literal 'default' on unset/invalid/config
- * errors — extraction must never fail on a bad config row.
- */
-export async function resolveLinkFallbackDefault(
- engine: Pick<BrainEngine, 'getConfig'>,
-): Promise<string> {
- try {
- const v = await engine.getConfig('sources.default');
- if (v && isValidSourceId(v)) return v;
- } catch {
- // Best-effort read; the seeded literal below is the safe terminal.
- }
- return 'default';
-}
-
-export function resolveCandidateSources(
- c: LinkCandidate,
- pageSlug: string,
- pageSourceId: string,
- allSlugs: Set<string>,
- slugToSources: Map<string, string[]>,
- allowCrossSource: boolean,
- opts: { crossSource?: boolean; defaultSourceId?: string } = {},
-): CandidateSourceResolution {
- const fromSlug = c.fromSlug ?? pageSlug;
- if (!allSlugs.has(c.targetSlug)) return { ok: false, reason: 'missing_target' };
- if (!allSlugs.has(fromSlug)) return { ok: false, reason: 'missing_from' };
- const fromSources = slugToSources.get(fromSlug) ?? [];
- const targetSources = slugToSources.get(c.targetSlug) ?? [];
- if (c.targetSourceId) {
- if (!targetSources.includes(c.targetSourceId)) return { ok: false, reason: 'missing_target' };
- if (!fromSources.includes(pageSourceId)) return { ok: false, reason: 'missing_from' };
- if (c.targetSourceId !== pageSourceId && !allowCrossSource && !opts.crossSource) return { ok: false, reason: 'cross_source' };
- return { ok: true, fromSlug, fromSourceId: pageSourceId, toSourceId: c.targetSourceId };
- }
- if (!allowCrossSource && !opts.crossSource) {
- if (!fromSources.includes(pageSourceId) || !targetSources.includes(pageSourceId)) {
- // #3478 isolation × #2589 counting: both endpoints exist but not in
- // the origin's own source — a counted cross-source drop, never an edge.
- return { ok: false, reason: 'cross_source' };
- }
- return { ok: true, fromSlug, fromSourceId: pageSourceId, toSourceId: pageSourceId };
- }
- // #4611: follow the CONFIGURED default source, not the literal 'default'.
- const defaultSourceId = opts.defaultSourceId ?? 'default';
- const fromSourceId = fromSources.includes(pageSourceId) ? pageSourceId
- : (fromSources.includes(defaultSourceId) ? defaultSourceId : fromSources[0]);
- let toSourceId: string;
- if (targetSources.includes(fromSourceId)) {
- toSourceId = fromSourceId;
- } else if (targetSources.includes(defaultSourceId)) {
- toSourceId = defaultSourceId;
- } else if (targetSources.length > 0) {
- // #2589: the target exists ONLY in other sources. Historically this was
- // a silent null (indistinguishable from a missing endpoint — multi-source
- // graphs went sparse with dead_links stuck at 0). Behind the opt-in
- // `link_resolution.cross_source` flag the edge is allowed with a
- // DETERMINISTIC pick (lexicographically smallest source, so repeated
- // extracts and both engines converge on the same edge under the
- // (source_id, slug) composite key); off, callers get the distinguishable
- // 'cross_source' reason to COUNT the drop instead of burying it.
- if (!opts.crossSource) return { ok: false, reason: 'cross_source' };
- // Allocation-free deterministic min (bulk loops call this per candidate;
- // in the motivating federated topology most candidates hit this branch).
- let min = targetSources[0];
- for (const s of targetSources) if (s < min) min = s;
- toSourceId = min;
- } else {
- return { ok: false, reason: 'cross_source' };
- }
- return { ok: true, fromSlug, fromSourceId, toSourceId };
-}
+export { resolveCandidateSources, resolveLinkFallbackDefault, type CandidateSourceResolution } from '../core/link-reconciliation.ts';
// isRetryableConnError reference retained for any inline classification at
// call sites. Engine-level retry uses the same predicate via core/retry.ts.
@@ -356,6 +243,7 @@ interface ExtractResult {
pages_processed: number;
/** #2589: drop counters, present on the DB links path only (additive). */
skipped_missing_target?: number;
+ skipped_attendance_incomplete?: number;
skipped_cross_source?: number;
}
@@ -442,50 +330,6 @@ export function resolveSlugRelPath(
// --- Link extraction ---
-/**
- * Extract markdown links to .md files (relative paths only).
- *
- * Handles two syntaxes:
- * 1. Standard markdown: [text](relative/path.md)
- * 2. Wikilinks: [[relative/path]] or [[relative/path|Display Text]]
- *
- * Both are resolved relative to the file that contains them. External URLs
- * (containing ://) are always skipped. Section anchors (#heading) are stripped
- * from both (#4995); for wikilinks, the .md suffix is added if absent.
- */
-export function extractMarkdownLinks(content: string): { name: string; relTarget: string }[] {
- const results: { name: string; relTarget: string }[] = [];
-
- const mdPattern = /\[([^\]]+)\]\(([^)#]+\.md)(?:#[^)]*)?\)/g;
- let match;
- while ((match = mdPattern.exec(content)) !== null) {
- let target = match[2];
- if (target.includes('://')) continue;
- // Obsidian's useMarkdownLinks mode percent-encodes link targets
- // (`[Alice](People/Alice%20Chen.md)`). Decode before resolution; a
- // malformed escape keeps the raw text rather than throwing.
- if (target.includes('%')) {
- try { target = decodeURIComponent(target); } catch { /* keep raw */ }
- }
- results.push({ name: match[1], relTarget: target });
- }
-
- const wikiPattern = /\[\[([^|\]]+?)(?:\|[^\]]*?)?\]\]/g;
- while ((match = wikiPattern.exec(content)) !== null) {
- const rawPath = match[1].trim();
- if (rawPath.includes('://')) continue;
- const hashIdx = rawPath.indexOf('#');
- const pagePath = hashIdx >= 0 ? rawPath.slice(0, hashIdx) : rawPath;
- if (!pagePath) continue;
- const relTarget = pagePath.endsWith('.md') ? pagePath : pagePath + '.md';
- const pipeIdx = match[0].indexOf('|');
- const displayName = pipeIdx >= 0 ? match[0].slice(pipeIdx + 1, -2).trim() : rawPath;
- results.push({ name: displayName, relTarget });
- }
-
- return results;
-}
-
/**
* Resolve a wikilink target to a canonical slug, given the directory of the
* containing page and the set of all known slugs in the brain.
@@ -511,6 +355,8 @@ export function resolveSlug(fileDir: string, relTarget: string, allSlugs: Set<st
return null;
};
+ if (targetNoExt.startsWith('/')) return hit(targetNoExt.slice(1));
+
const s1 = hit(join(fileDir, targetNoExt));
if (s1) return s1;
@@ -601,10 +447,16 @@ function inferTypeByDir(fromDir: string, toDir: string, frontmatter?: Record<str
}
if (from === 'people' && to === 'deals') return 'involved_in';
if (from === 'deals' && to === 'companies') return 'deal_for';
- if (from === 'meetings' && to === 'people') return 'attended';
return 'mentions';
}
+async function loadSourceLinkPacks(engine: BrainEngine, sourceIds: string[], packs: Map<string, LinkExtractionPack | null>) {
+ for (const sourceId of new Set(sourceIds)) {
+ if (packs.has(sourceId)) continue;
+ packs.set(sourceId, (await loadActivePackForLocalEngine(engine, { sourceId }))?.manifest ?? null);
+ }
+}
+
function loadFsPageTypes(files: ReadonlyArray<{ path: string; relPath: string }>, pack: LinkExtractionPack | null): Map<string, string> {
const types = new Map<string, string>();
const activePack = pack?.page_types ? { page_types: pack.page_types } : undefined;
@@ -638,8 +490,9 @@ export async function extractLinksFromFile(
// `[[name]]` inside a code block doesn't create an FS edge. Mirrors the
// DB path, which goes through extractEntityRefs (which strips internally).
const scanContent = stripCodeBlocks(content);
+ const attendanceRanges = attendanceEvidenceRanges(content);
- for (const { name, relTarget } of extractMarkdownLinks(scanContent)) {
+ for (const { name, relTarget, index } of extractMarkdownLinks(scanContent, true)) {
const resolvedSlugs = resolveSlugAll(fileDir, relTarget, allSlugs, { globalBasename });
if (resolvedSlugs.length === 0) continue;
// Single hit on the ancestor path → emit one edge with the inferred
@@ -658,26 +511,37 @@ export async function extractLinksFromFile(
? `wikilink (basename match): [${name}]`
: `markdown link: [${name}]`;
const targetType = opts?.pageTypes?.get(target) ?? parseMarkdown('', `${target}.md`, { activePack }).type;
- const position = scanContent.indexOf(name);
+ const position = index ?? scanContent.indexOf(name);
const evidence = scanContent.slice(Math.max(0, position - 120), position + 240);
let inferred = pack ? inferLinkTypeFromPack(pack, guessedPageType, evidence, packBudget, targetType) : null;
+ const bareTarget = relTarget.endsWith('.md') ? relTarget.slice(0, -3) : relTarget;
+ const ambiguousAttendance = !inferred && guessedPageType === 'meeting' && targetType === 'person'
+ && !bareTarget.includes('/') && new Set([slugifyPath(bareTarget), normalizeBasename(bareTarget)]
+ .map(form => join(dirname(target), form)).filter(candidate => allSlugs.has(candidate)
+ && (opts?.pageTypes?.get(candidate) ?? parseMarkdown('', `${candidate}.md`, { activePack }).type) === 'person')).size > 1;
+ const canonicalAttendance = !inferred && guessedPageType === 'meeting' && targetType === 'person'
+ && resolvedSlugs.length === 1 && !ambiguousAttendance
+ && !pack?.link_types.some(lt => lt.name === 'attended' && (lt.inference?.page_type || lt.inference?.target_type))
+ && hasAttendanceEvidence(attendanceRanges, position);
if (!inferred) {
- inferred = inferLinkType(guessedPageType, evidence, scanContent, target, targetType);
+ inferred = guessedPageType === 'meeting' ? (canonicalAttendance ? 'attended' : 'mentions')
+ : inferLinkType(guessedPageType, evidence, scanContent, target, targetType);
if (inferred === 'mentions' && !pack && !parsed.typeExplicit) inferred = inferTypeByDir(fileDir, dirname(target), fm);
if (pack?.link_types.some(lt => lt.name === inferred && (lt.inference?.page_type || lt.inference?.target_type))) inferred = 'mentions';
}
if (inferred === 'attended' && guessedPageType === 'meeting' && targetType !== 'person') inferred = 'mentions';
- links.push({
+ const link: ExtractedLink = {
from_slug: slug,
to_slug: target,
- link_type: isBasename
+ link_type: isBasename && !canonicalAttendance
? WIKILINK_BASENAME_LINK_TYPE
: inferred,
- context,
+ context: canonicalAttendance ? evidence : context,
// Issue #972: tag basename edges so the FS path matches DB/put_page
// provenance and migration v112's widened CHECK is exercised here too.
- link_source: isBasename ? 'wikilink-resolved' : undefined,
- });
+ link_source: isBasename ? 'wikilink-resolved' : canonicalAttendance ? 'markdown' : undefined,
+ };
+ links.push(canonicalAttendance ? orientCanonicalAttendance(link) : link);
}
}
@@ -686,6 +550,14 @@ export async function extractLinksFromFile(
// step 2 (dir-hint + slugify via normalizeBasename — #2367: was an inline
// ASCII-only clone that emptied CJK names and mis-folded accents).
const fsResolver = {
+ async resolveAttendance(name: string, dirHint?: string | string[]): Promise<string | null> {
+ const value = name.trim();
+ const hints = Array.isArray(dirHint) ? dirHint : dirHint ? [dirHint] : [];
+ const candidates = value.includes('/') ? [value] : hints.flatMap(hint =>
+ [...new Set([normalizeBasename(value), slugifySegment(value)])].map(form => `${hint}/${form}`));
+ const matches = [...new Set(candidates.filter(candidate => allSlugs.has(candidate)))];
+ return matches.length === 1 ? matches[0] : null;
+ },
async resolve(name: string, dirHint?: string | string[]): Promise<string | null> {
if (!name) return null;
const trimmed = name.trim();
@@ -867,6 +739,8 @@ export async function runExtractCore(engine: BrainEngine, opts: ExtractOpts): Pr
const r = await extractLinksFromDir(engine, opts.dir, dryRun, jsonMode, workers, opts.signal, opts.sourceId, quiet);
result.links_created = r.created;
result.pages_processed = r.pages;
+ const processed = new Set(r.processed);
+ stampRefs = stampRefs.filter(ref => processed.has(ref.slug));
}
if (opts.mode === 'timeline' || opts.mode === 'all') {
const r = await extractTimelineFromDir(engine, opts.dir, dryRun, jsonMode, workers, opts.signal, opts.sourceId, quiet);
@@ -923,6 +797,7 @@ Extraction:
it. It is NOT the content's authored/effective date.
Incremental sweep:
+${ATTENDANCE_REPAIR_HELP}
gbrain extract --stale [--source-id <id>] [--include-frontmatter]
[--catch-up] [--dry-run] [--json]
Re-extract links + timeline only for stale pages. DB-source; safe to
@@ -935,12 +810,17 @@ Inspection:
Status:
gbrain extract status [--source-id ID] [--kind X] [--verbose] [--json]`;
-export async function runExtract(engine: BrainEngine, args: string[]) {
+export async function runExtract(engine: BrainEngine, args: string[], authority?: { remote: boolean }) {
if (args.includes('--help') || args.includes('-h')) {
console.log(EXTRACT_HELP);
return;
}
+ if (isAttendanceRepairRequest(args)) {
+ const { runAttendanceRepair } = await import('./extract-attendance-repair.ts');
+ return runAttendanceRepair(engine, args, { remote: authority?.remote !== false });
+ }
+
const subcommand = args[0];
// v0.42 Wave C+D dispatch — new operator surfaces. These intercept
@@ -1266,6 +1146,7 @@ export async function runExtract(engine: BrainEngine, args: string[]) {
// additive fields, only present on the DB links path.
result.skipped_missing_target = r.skippedMissingTarget;
result.skipped_cross_source = r.skippedCrossSource;
+ if (r.skippedAttendanceIncomplete) result.skipped_attendance_incomplete = r.skippedAttendanceIncomplete;
}
if (subcommand === 'timeline' || subcommand === 'all') {
const r = await extractTimelineFromDB(engine, dryRun, jsonMode, typeFilter, since, { sourceIdFilter, inferDates });
@@ -1373,9 +1254,11 @@ async function extractForSlugs(
// Issue #972: read the basename flag once per extract run.
const globalBasename = await isGlobalBasenameEnabled(engine);
// #3190: active pack loaded once per run for pack-aware link typing +
- // pack frontmatter_links. Null keeps legacy inference.
- const pack = (await loadActivePackForLocalEngine(engine))?.manifest ?? null;
+ // pack frontmatter_links.
+ const pack = (await loadActivePackForLocalEngine(engine, { sourceId: sourceId ?? 'default' }))?.manifest ?? null;
+ 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 linkBatch: LinkBatchInput[] = [];
const timelineBatch: TimelineBatchInput[] = [];
@@ -1441,11 +1324,21 @@ async function extractForSlugs(
if (relPath === undefined) return; // deleted file — sync already handled removal
const fullPath = join(brainDir, relPath);
try {
+ const snapshot = ownership && (ownership.metadata.get(`${sourceId ?? 'default'}\0${slug}`)?.type === 'meeting' || ownership.origins.has(slug))
+ ? await engine.readPageSnapshot(slug, { sourceId: sourceId ?? 'default' }) : null;
const content = readFileSync(fullPath, 'utf-8');
if (doLinks) {
const links = await extractLinksFromFile(content, relPath, allSlugs, { globalBasename, includeFrontmatter, pack, pageTypes });
- for (const link of links) {
+ 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) {
if (!stdoutQuiet) console.log(` ${link.from_slug} → ${link.to_slug} (${link.link_type})`);
linksCreated++;
@@ -1509,7 +1402,7 @@ async function extractLinksFromDir(
sourceId?: string,
// Embedded callers own the report: nothing on stdout (see ExtractOpts.quiet).
quiet: boolean = false,
-): Promise<{ created: number; pages: number }> {
+): Promise<{ created: number; pages: number; processed: string[] }> {
const stdoutQuiet = jsonMode || quiet;
const files = walkMarkdownFiles(brainDir);
const allSlugs = new Set(files.map(f => pathToSlug(f.relPath)));
@@ -1519,8 +1412,11 @@ async function extractLinksFromDir(
// match for bare wikilinks like `[[struktura]]`.
const globalBasename = await isGlobalBasenameEnabled(engine);
// #3190: pack-aware typing + pack frontmatter_links (loaded once per walk).
- const pack = (await loadActivePackForLocalEngine(engine))?.manifest ?? null;
+ const pack = (await loadActivePackForLocalEngine(engine, { sourceId: sourceId ?? 'default' }))?.manifest ?? null;
+ if (!pack) throw new Error('Cannot extract links: active schema pack is unavailable.');
const pageTypes = loadFsPageTypes(files, pack);
+ const ownership = dryRun ? undefined : await fileLinkOwnership(engine, sourceId ?? 'default');
+ const processed: string[] = [];
// Progress stream on stderr (separate from the action-events --json writes
// to stdout, which tests grep for). Rate-gated; respects global --quiet /
@@ -1559,9 +1455,20 @@ async function extractLinksFromDir(
// #1972: bail before this file on abort; trailing flush() commits the batch.
if (isAborted(signal)) return;
try {
+ const slug = pathToSlug(file.relPath);
+ const snapshot = ownership && (ownership.metadata.get(`${sourceId ?? 'default'}\0${slug}`)?.type === 'meeting' || ownership.origins.has(slug))
+ ? await engine.readPageSnapshot(slug, { sourceId: sourceId ?? 'default' }) : null;
const content = readFileSync(file.path, 'utf-8');
const links = await extractLinksFromFile(content, file.relPath, allSlugs, { globalBasename, pack, pageTypes });
- for (const link of links) {
+ 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, false, snapshot, ownership, content, { pack, globalBasename });
+ if (written === null) return;
+ reconciled = written !== undefined;
+ created += written ?? 0;
+ }
+ if (!reconciled) for (const link of links) {
if (dryRunSeen) {
const key = `${link.from_slug}::${link.to_slug}::${link.link_type}`;
if (dryRunSeen.has(key)) continue;
@@ -1575,6 +1482,7 @@ async function extractLinksFromDir(
if (batch.length >= BATCH_SIZE) await flush();
}
}
+ processed.push(slug);
} catch { /* skip unreadable */ }
progress.tick(1);
},
@@ -1586,7 +1494,7 @@ async function extractLinksFromDir(
const label = dryRun ? '(dry run) would create' : 'created';
console.log(`Links: ${label} ${created} from ${files.length} pages`);
}
- return { created, pages: files.length };
+ return { created, pages: files.length, processed };
}
async function extractTimelineFromDir(
@@ -1718,8 +1626,11 @@ export async function extractLinksForSlugs(
// Issue #972: same flag as the standalone extract path.
const globalBasename = await isGlobalBasenameEnabled(engine);
// #3190: pack-aware typing on the sync inline hook too.
- const pack = (await loadActivePackForLocalEngine(engine))?.manifest ?? null;
+ const sourceId = opts?.sourceId ?? 'default';
+ const pack = (await loadActivePackForLocalEngine(engine, { sourceId }))?.manifest ?? null;
+ if (!pack) throw new Error('Cannot extract links: active schema pack is unavailable.');
const pageTypes = loadFsPageTypes(allFiles, pack);
+ const ownership = await fileLinkOwnership(engine, sourceId);
// #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
@@ -1736,11 +1647,22 @@ export async function extractLinksForSlugs(
// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- relPath comes from the slug→path index built by walkMarkdownFiles(repoPath) (repo-relative entries of that walk) or the validated-slug legacy fallback, never from a caller
const filePath = join(repoPath, relPath);
try {
+ 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');
- processed.push(slug);
- for (const link of await extractLinksFromFile(content, relPath, allSlugs, { globalBasename, includeFrontmatter, pack, pageTypes })) {
- 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 { /* skip */ } // gbrain-allow-direct-insert: gbrain extract single-row fallback when batch path declines a row
+ const links = await extractLinksFromFile(content, relPath, allSlugs, { globalBasename, includeFrontmatter, pack, pageTypes });
+ let reconciled = false;
+ 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 });
+ 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
}
+ processed.push(slug);
} catch { /* skip: unreadable — not processed, stays stale */ }
}
return { created, processed };
@@ -1802,17 +1724,6 @@ function filterRefsSince<T extends { updated_at: Date }>(
return refs.filter(r => r.updated_at.getTime() > sinceMs);
}
-function capturedLinkEndpoints(links: LinkBatchInput[], metadata: ReadonlyMap<string, LinkPageMetadata>) {
- const keys = new Set(links.flatMap(link => [
- `${link.from_source_id ?? 'default'}\0${link.from_slug}`, `${link.to_source_id ?? 'default'}\0${link.to_slug}`,
- ]));
- return [...keys].map(key => {
- const endpoint = metadata.get(key);
- if (!endpoint) throw new Error('A derived link endpoint was not captured during type resolution');
- return { slug: endpoint.slug, sourceId: endpoint.source_id, revision: endpoint.knowledge_revision };
- });
-}
-
async function extractLinksFromDB(
engine: BrainEngine,
dryRun: boolean,
@@ -1820,7 +1731,7 @@ async function extractLinksFromDB(
typeFilter: PageType | undefined,
since: string | undefined,
opts?: { includeFrontmatter?: boolean; sourceIdFilter?: string; stampWatermark?: boolean },
-): Promise<{ created: number; pages: number; unresolved: UnresolvedFrontmatterRef[]; skippedMissingTarget: number; skippedCrossSource: number }> {
+): Promise<{ created: number; pages: number; unresolved: UnresolvedFrontmatterRef[]; skippedMissingTarget: number; skippedCrossSource: number; skippedAttendanceIncomplete: number }> {
const includeFrontmatter = opts?.includeFrontmatter ?? false;
const sourceIdFilter = opts?.sourceIdFilter;
// C3 (D6): the links_extracted_at watermark covers links AND timeline, so a
@@ -1833,10 +1744,6 @@ async function extractLinksFromDB(
// Issue #972: opt-in global-basename wikilink resolution. Read once
// per extract run; threaded into each extractPageLinks call.
const globalBasename = await isGlobalBasenameEnabled(engine);
- // #3190: active schema pack, loaded ONCE per run — pack-declared link
- // verbs (link_types[].inference) + frontmatter_links apply during
- // extraction instead of being silently ignored. Null = legacy inference.
- const pack = (await loadActivePackForLocalEngine(engine))?.manifest ?? null;
// Issue #2589: opt-in cross-source edges (deterministic to_source_id pick);
// off, cross-source-only candidates are counted, never silently dropped.
const crossSource = await isCrossSourceLinksEnabled(engine);
@@ -1880,6 +1787,7 @@ async function extractLinksFromDB(
// The resolver maps above are built from the UNFILTERED refs — link
// targets outside the window must still resolve.
const walkRefs = filterRefsSince(allRefs, since);
+ const packs = new Map<string, LinkExtractionPack | null>();
// #3478: the 'default' fallback in resolveCandidateSources is a federation
// feature — an isolated source must not regrow cross-source edges on every
// sweep. Sources absent from the table (or archived) fail closed to isolated.
@@ -1887,7 +1795,11 @@ async function extractLinksFromDB(
(await loadAllSources(engine, { federatedOnly: true })).map(source => source.id),
);
const targetMetadata = new Map((await loadLinkPageMetadata(engine)).map(p => [`${p.source_id}\0${p.slug}`, p]));
+ await loadSourceLinkPacks(engine, walkRefs.filter(ref => !typeFilter
+ || targetMetadata.get(`${ref.source_id}\0${ref.slug}`)?.type === typeFilter).map(ref => ref.source_id), packs);
+ if ([...packs.values()].some(pack => !pack)) throw new Error('Cannot extract links: active schema pack is unavailable.');
let processed = 0, created = 0;
+ let skippedAttendanceIncomplete = 0;
// #2576: skipped-candidate counter — see extractStaleFromDB's twin.
let skippedMissingTarget = 0;
// #2589: target resolved (via global_basename) to a page that exists only
@@ -1911,6 +1823,9 @@ async function extractLinksFromDB(
if (!snapshot) continue;
const page = snapshot.page;
if (typeFilter && page.type !== typeFilter) continue;
+ await loadSourceLinkPacks(engine, [source_id], packs);
+ const pack = packs.get(source_id);
+ if (!pack) throw new Error('Cannot extract links: active schema pack is unavailable.');
const batch: LinkBatchInput[] = [];
if (!resolvers.has(source_id)) resolvers.set(source_id, makeResolver(engine, { mode: 'batch', sourceId: source_id }));
const resolver = resolvers.get(source_id)!;
@@ -1930,6 +1845,7 @@ async function extractLinksFromDB(
} },
);
unresolved.push(...extracted.unresolved);
+ if (!extracted.attendanceComplete) { skippedAttendanceIncomplete++; continue; }
for (const c of extracted.candidates) {
// v0.32.8 F10 cross-source link resolution, extracted to the shared pure
@@ -1947,38 +1863,25 @@ async function extractLinksFromDB(
else skippedMissingTarget++;
continue;
}
- const { fromSlug, fromSourceId, toSourceId } = resolved;
+ const row = resolvedLinkCandidate(c, slug, source_id, resolved);
+ const { from_slug: fromSlug, to_slug: toSlug, from_source_id: fromSourceId, to_source_id: toSourceId } = row;
if (dryRunSeen) {
- const key = `${fromSourceId}::${fromSlug}::${toSourceId}::${c.targetSlug}::${c.linkType}::${c.linkSource ?? 'markdown'}`;
+ const key = `${fromSourceId}::${fromSlug}::${toSourceId}::${toSlug}::${c.linkType}::${c.linkSource ?? 'markdown'}`;
if (dryRunSeen.has(key)) continue;
dryRunSeen.add(key);
if (jsonMode) {
process.stdout.write(JSON.stringify({
action: 'add_link', from: fromSlug, from_source_id: fromSourceId,
- to: c.targetSlug, to_source_id: toSourceId,
+ to: toSlug, to_source_id: toSourceId,
type: c.linkType, context: c.context, link_source: c.linkSource,
}) + '\n');
} else {
- console.log(` ${fromSlug} → ${c.targetSlug} (${c.linkType})${c.linkSource === 'frontmatter' ? ' [fm]' : ''}`);
+ console.log(` ${fromSlug} → ${toSlug} (${c.linkType})${c.linkSource === 'frontmatter' ? ' [fm]' : ''}`);
}
created++;
} else {
- batch.push({
- from_slug: fromSlug,
- to_slug: c.targetSlug,
- link_type: c.linkType,
- context: c.context,
- link_source: c.linkSource,
- origin_slug: c.originSlug,
- origin_field: c.originField,
- // v0.32.8 F4: thread source ids so the batch JOIN doesn't fan out
- // across sources. Default source_id='default' for back-compat with
- // pre-v0.32.8 callers (the engine still accepts undefined).
- from_source_id: fromSourceId,
- to_source_id: toSourceId,
- origin_source_id: source_id,
- });
+ batch.push(row);
}
}
if (!dryRun) {
@@ -2012,6 +1915,7 @@ async function extractLinksFromDB(
if (!jsonMode) {
const label = dryRun ? '(dry run) would create' : 'created';
console.log(`Links: ${label} ${created} from ${processed} pages (db source)`);
+ if (skippedAttendanceIncomplete) console.log(`Skipped ${skippedAttendanceIncomplete} page(s) with unresolved attendance; prior links and extraction watermarks were preserved.`);
if (skippedMissingTarget > 0) {
console.log(`Skipped ${skippedMissingTarget} candidate(s) whose target page doesn't exist (references to non-pages are never persisted).`);
}
@@ -2036,7 +1940,7 @@ async function extractLinksFromDB(
// #2589: the counters ride the return value so machine consumers (and the
// --json path, which has no summary event on this path) can see the drops —
// "counted, never silent" must hold beyond human-mode console lines.
- return { created, pages: processed, unresolved, skippedMissingTarget, skippedCrossSource };
+ return { created, pages: processed, unresolved, skippedMissingTarget, skippedCrossSource, skippedAttendanceIncomplete };
}
async function extractTimelineFromDB(
@@ -2176,7 +2080,7 @@ export async function extractStaleFromDB(
*/
timeBudgetMs?: number;
},
-): Promise<{ linksCreated: number; timelineCreated: number; pagesProcessed: number; staleRemaining: number; skippedMissingTarget?: number; skippedCrossSource?: number }> {
+): Promise<{ linksCreated: number; timelineCreated: number; pagesProcessed: number; staleRemaining: number; skippedMissingTarget?: number; skippedCrossSource?: number; skippedAttendanceIncomplete?: number }> {
const { dryRun, jsonMode, sourceIdFilter, catchUp } = opts;
const includeFrontmatter = opts.includeFrontmatter ?? await resolveIncludeFrontmatter(engine);
const log = opts.quiet ? (..._args: unknown[]) => {} : console.log;
@@ -2214,8 +2118,7 @@ export async function extractStaleFromDB(
// extractLinksFromDB (including the codex-[P1] `sourceId` scoping).
const resolvers = new Map<string, ReturnType<typeof makeResolver>>();
const globalBasename = await isGlobalBasenameEnabled(engine);
- // #3190: pack-aware verbs + frontmatter_links (see extractLinksFromDB).
- const pack = (await loadActivePackForLocalEngine(engine))?.manifest ?? null;
+ const packs = new Map<string, LinkExtractionPack | null>();
// Issue #2589: mirrors extractLinksFromDB (see resolveCandidateSources).
const crossSource = await isCrossSourceLinksEnabled(engine);
// #4611: mirrors extractLinksFromDB — configured default, resolved once.
@@ -2242,7 +2145,9 @@ export async function extractStaleFromDB(
const startMs = Date.now();
let afterPageId = 0;
let linksCreated = 0, timelineCreated = 0, pagesProcessed = 0;
+ let skippedAttendanceIncomplete = 0;
let budgetHit = false;
+ let packUnavailable = false;
// #2576: candidates whose endpoint pages don't exist are skipped, not
// persisted. Counted so a dropped reference is observable in the summary
// instead of vanishing silently (the failure mode that hid bug 2).
@@ -2258,11 +2163,18 @@ export async function extractStaleFromDB(
batchSize: STALE_BATCH_SIZE, afterPageId, sourceId: sourceIdFilter, versionTs,
});
if (rows.length === 0) break;
+ await loadSourceLinkPacks(engine, rows.map(page => page.source_id), packs);
const timelineRows: TimelineBatchInput[] = [];
const processedRefs: Array<{ slug: string; source_id: string; extractedAt: string }> = [];
for (const page of rows) {
+ const pack = packs.get(page.source_id);
+ if (!pack) {
+ if (sourceIdFilter) throw new Error('Cannot extract links: active schema pack is unavailable.');
+ packUnavailable = true;
+ continue;
+ }
const snapshot = await engine.readPageSnapshot(page.slug, { sourceId: page.source_id });
if (!snapshot) throw new Error('Link extraction origin changed during the stale scan');
const fullContent = snapshot.page.compiled_truth + '\n' + snapshot.page.timeline;
@@ -2277,6 +2189,7 @@ export async function extractStaleFromDB(
return resolved.ok ? targetMetadata.get(`${resolved.toSourceId}\0${targetSlug}`)?.type : undefined;
} },
);
+ if (!extracted.attendanceComplete) { skippedAttendanceIncomplete++; continue; }
for (const c of extracted.candidates) {
const r = resolveCandidateSources(
c, page.slug, page.source_id, allSlugs, slugToSources,
@@ -2288,12 +2201,7 @@ export async function extractStaleFromDB(
else skippedMissingTarget++;
continue;
}
- linkRows.push({
- from_slug: r.fromSlug, to_slug: c.targetSlug, link_type: c.linkType,
- context: c.context, link_source: c.linkSource, origin_slug: c.originSlug,
- origin_field: c.originField, from_source_id: r.fromSourceId,
- to_source_id: r.toSourceId, origin_source_id: page.source_id,
- });
+ linkRows.push(resolvedLinkCandidate(c, page.slug, page.source_id, r));
}
const written = await engine.replaceDerivedLinks({ slug: page.slug, sourceId: page.source_id,
expectedRevision: snapshot.revision, sourceIncarnation: snapshot.sourceIncarnation }, linkRows, { includeFrontmatter,
@@ -2337,18 +2245,20 @@ export async function extractStaleFromDB(
// failure surfaces instead of looping forever.
await engine.markPagesExtractedBatch(processedRefs, new Date().toISOString());
- pagesProcessed += rows.length;
- progress.tick(rows.length);
+ pagesProcessed += processedRefs.length;
+ progress.tick(processedRefs.length);
afterPageId = rows[rows.length - 1]!.id;
if (!catchUp && Date.now() - startMs > timeBudgetMs) { budgetHit = true; break; }
}
progress.finish();
+ if (packUnavailable) throw new Error('Cannot extract links: active schema pack is unavailable.');
const staleRemaining = await engine.countStalePagesForExtraction({ sourceId: sourceIdFilter, versionTs });
if (!jsonMode) {
log(`Extract --stale: ${linksCreated} link(s) + ${timelineCreated} timeline entr(ies) from ${pagesProcessed} page(s).`);
+ if (skippedAttendanceIncomplete) log(`Skipped ${skippedAttendanceIncomplete} page(s) with unresolved attendance; prior links and extraction watermarks were preserved.`);
if (skippedMissingTarget > 0) {
log(`Skipped ${skippedMissingTarget} candidate(s) whose target page doesn't exist (references to non-pages are never persisted).`);
}
@@ -2363,9 +2273,11 @@ export async function extractStaleFromDB(
action: 'extract_stale_done', links_created: linksCreated, timeline_created: timelineCreated,
pages_processed: pagesProcessed, stale_remaining: staleRemaining, budget_hit: budgetHit,
skipped_missing_target: skippedMissingTarget, skipped_cross_source: skippedCrossSource,
+ ...(skippedAttendanceIncomplete ? { skipped_attendance_incomplete: skippedAttendanceIncomplete } : {}),
}) + '\n');
}
- return { linksCreated, timelineCreated, pagesProcessed, staleRemaining, skippedMissingTarget, skippedCrossSource };
+ return { linksCreated, timelineCreated, pagesProcessed, staleRemaining, skippedMissingTarget, skippedCrossSource,
+ ...(skippedAttendanceIncomplete ? { skippedAttendanceIncomplete } : {}) };
}
/**
diff --git a/src/commands/recall.ts b/src/commands/recall.ts
index 01ea397c8a..9aa65a5164 100644
--- a/src/commands/recall.ts
+++ b/src/commands/recall.ts
@@ -34,9 +34,9 @@ import type { BrainEngine, FactRow, FactKind } from '../core/engine.ts';
import { effectiveConfidence } from '../core/facts/decay.ts';
import { resolveEntitySlug } from '../core/entities/resolve.ts';
import { loadConfig, isThinClient } from '../core/config.ts';
-import { callRemoteTool, unpackToolResult } from '../core/mcp-client.ts';
+import { callRemoteTool, RemoteMcpError, unpackToolResult } from '../core/mcp-client.ts';
import { readCursor, writeCursor } from '../core/recall-cursor-state.ts';
-import { resolveSourceId } from '../core/source-resolver.ts';
+import { resolveSourceId, resolveSourceIdEngineFree, SourceTargetError } from '../core/source-resolver.ts';
// Same kebab-case shape gate the source-resolver applies. v0.32: applied
// locally on thin-client where the canonical resolver's assertSourceExists
@@ -71,6 +71,8 @@ interface ParsedFlags {
// (this hand-rolled CLI otherwise ignores unknown flags silently).
query: string | null;
budgetTokens: number | null;
+ budgetPolicy: string | null;
+ sourceExplicit: boolean;
// v0.32
sinceLastRun: boolean;
pending: boolean;
@@ -101,12 +103,15 @@ function parseFlags(args: string[]): ParsedFlags {
limit: 50,
query: null,
budgetTokens: null,
+ budgetPolicy: null,
+ sourceExplicit: false,
sinceLastRun: false,
pending: false,
rollup: false,
watchSeconds: null,
};
let positional = '';
+ let rawBudget: string | undefined;
for (let i = 0; i < args.length; i++) {
const a = args[i];
if (a === '--since') { out.since = parseSinceParam(args[++i] ?? ''); continue; }
@@ -117,10 +122,19 @@ function parseFlags(args: string[]): ParsedFlags {
if (a === '--include-expired') { out.includeExpired = true; continue; }
if (a === '--as-context') { out.asContext = true; continue; }
if (a === '--json') { out.json = true; continue; }
- if (a === '--source') { out.source = args[++i] ?? 'default'; continue; }
+ if (a === '--source') { out.source = args[++i] ?? 'default'; out.sourceExplicit = true; continue; }
+ if (a === '--source-id') { out.source = args[++i] ?? ''; out.sourceExplicit = true; continue; }
+ if (a.startsWith('--source-id=')) { out.source = a.slice('--source-id='.length); out.sourceExplicit = true; continue; }
if (a === '--limit') { out.limit = parseInt(args[++i] ?? '50', 10) || 50; continue; }
if (a === '--query') { out.query = args[++i] ?? null; continue; }
- if (a === '--budget-tokens') { out.budgetTokens = parseInt(args[++i] ?? '', 10) || null; continue; }
+ if (a === '--budget-tokens') { rawBudget = args[++i]; continue; }
+ if (a === '--budget-policy') {
+ const next = args[i + 1];
+ out.budgetPolicy = next === undefined || next.startsWith('--') ? '' : next;
+ if (next !== undefined && !next.startsWith('--')) i++;
+ continue;
+ }
+ if (a.startsWith('--budget-policy=')) { out.budgetPolicy = a.slice('--budget-policy='.length); continue; }
if (a === '--since-last-run') { out.sinceLastRun = true; continue; }
if (a === '--pending') { out.pending = true; continue; }
if (a === '--rollup') { out.rollup = true; continue; }
@@ -138,6 +152,9 @@ function parseFlags(args: string[]): ParsedFlags {
if (!positional) positional = a;
}
if (positional) out.entity = positional;
+ out.budgetTokens = (out.budgetPolicy === 'query_first' && out.query?.trim()
+ ? Number(rawBudget)
+ : parseInt(rawBudget ?? '', 10)) || null;
if (out.today && !out.since) {
const start = new Date();
start.setHours(0, 0, 0, 0);
@@ -146,6 +163,10 @@ function parseFlags(args: string[]): ParsedFlags {
return out;
}
+export function hasRecallBudgetPolicy(args: string[]): boolean {
+ return parseFlags(args).budgetPolicy !== null;
+}
+
function parseSinceParam(raw: string): Date | null {
if (!raw) return null;
const iso = Date.parse(raw);
@@ -218,8 +239,45 @@ async function resolveSourceForRecall(
export async function runRecall(engine: BrainEngine, args: string[]): Promise<void> {
const flags = parseFlags(args);
- validateAndNormalizeFlags(flags);
+ if (flags.budgetPolicy !== null) {
+ const { MEMORY_VERBS_VERSION, operationsByName, verbError } = await import('../core/operations.ts');
+ const { validateParams } = await import('../mcp/validate-params.ts');
+ const { reportPersistenceCliError } = await import('./persistence-delegate.ts');
+ try {
+ const error = validateParams(operationsByName.recall, { budget_policy: flags.budgetPolicy })
+ ?? (flags.watchSeconds !== null || flags.sinceLastRun || flags.rollup || flags.asContext
+ ? '--budget-policy cannot be combined with --watch, --since-last-run, --rollup, or --as-context.' : null);
+ if (error) throw verbError('invalid_params', error,
+ 'Use --budget-policy facts_first or query_first on a one-shot recall, or omit the policy for CLI-only behavior.');
+ const selector = flags.sourceExplicit ? flags.source : process.env.GBRAIN_SOURCE || undefined;
+ if (selector !== undefined && !SOURCE_ID_RE.test(selector)) {
+ throw verbError('invalid_params', 'recall requires a concrete source id matching [a-z0-9-]{1,32}.',
+ 'Choose a registered source id, or omit the source selector to use your existing scope.', 'source_id');
+ }
+ const thinClient = isThinClient(loadConfig());
+ const sourceId = resolveSourceIdEngineFree(flags.sourceExplicit ? flags.source : null)
+ ?? (thinClient ? undefined : await resolveSourceId(engine, null));
+ await runRecallVerb(engine, flags, sourceId);
+ } catch (error) {
+ if (error instanceof RemoteMcpError) {
+ const { setCliExitVerdict, writeStdoutFinal } = await import('../core/cli-force-exit.ts');
+ const detail = { protocol_version: MEMORY_VERBS_VERSION, ...error.toJSON() };
+ if (flags.json) await writeStdoutFinal(JSON.stringify(detail, null, 2) + '\n');
+ console.error(`Error [${detail.error}]: ${detail.message}`);
+ if (detail.suggestion) console.error(`Fix: ${detail.suggestion}`);
+ setCliExitVerdict(1);
+ return;
+ }
+ if (error instanceof SourceTargetError) {
+ error = verbError('not_found', error.message,
+ 'Choose an active source with the source selector, or repair your local source configuration.', 'unknown_source');
+ }
+ if (!await reportPersistenceCliError(error, flags.json)) throw error;
+ }
+ return;
+ }
+ validateAndNormalizeFlags(flags);
const cfg = loadConfig();
const thinClient = isThinClient(cfg);
@@ -251,7 +309,7 @@ export async function runRecall(engine: BrainEngine, args: string[]): Promise<vo
* through the recall OP (same code path MCP exercises) and renders facts +
* search results with the budget footer. `--json` prints the raw envelope.
*/
-async function runRecallVerb(engine: BrainEngine, flags: ParsedFlags, sourceId: string): Promise<void> {
+async function runRecallVerb(engine: BrainEngine, flags: ParsedFlags, sourceId?: string): Promise<void> {
const { operationsByName } = await import('../core/operations.ts');
const op = operationsByName['recall'];
const ctx = {
@@ -264,9 +322,9 @@ async function runRecallVerb(engine: BrainEngine, flags: ParsedFlags, sourceId:
},
dryRun: false,
remote: false as const,
- sourceId,
+ sourceId: sourceId ?? 'default',
};
- const result = (await op.handler(ctx, {
+ const params = {
...(flags.entity ? { entity: flags.entity } : {}),
...(flags.query ? { query: flags.query } : {}),
...(flags.budgetTokens ? { budget_tokens: flags.budgetTokens } : {}),
@@ -274,7 +332,17 @@ async function runRecallVerb(engine: BrainEngine, flags: ParsedFlags, sourceId:
...(flags.grep ? { grep: flags.grep } : {}),
include_expired: flags.includeExpired,
limit: flags.limit,
- })) as {
+ ...(flags.budgetPolicy !== null ? {
+ budget_policy: flags.budgetPolicy,
+ ...(sourceId !== undefined ? { source_id: sourceId } : {}),
+ ...(flags.sessionId ? { session_id: flags.sessionId } : {}),
+ ...(flags.supersessions ? { supersessions: true } : {}),
+ ...(flags.pending ? { include_pending: true } : {}),
+ } : {}),
+ };
+ const result = (flags.budgetPolicy !== null && isThinClient(ctx.config)
+ ? unpackToolResult(await callRemoteTool(ctx.config, 'recall', params, { timeoutMs: 30_000 }))
+ : await op.handler(ctx, params)) as {
facts: Array<{ fact_id: string; fact: string; kind: string; entity_slug: string | null; provenance: string }>;
results?: Array<{ slug: string; title: string | null; evidence: string; chunk: string | null }>;
search_degraded?: string;
diff --git a/src/core/attendance-repair.ts b/src/core/attendance-repair.ts
new file mode 100644
index 0000000000..d56eb8b798
--- /dev/null
+++ b/src/core/attendance-repair.ts
@@ -0,0 +1,381 @@
+import { createHash, randomUUID } from 'node:crypto';
+import type { BrainEngine, LinkBatchInput } from './engine.ts';
+import { extractPageLinks, extractEntityRefs, attendanceEvidenceRanges, hasAttendanceEvidence,
+ resolvedLinkCandidate, normalizeBasename, LINK_EXTRACTOR_VERSION_TS,
+ type LinkExtractionPack, type SlugResolver } from './link-extraction.ts';
+import { slugifyPath } from './sync.ts';
+import { isValidSourceId } from './source-id.ts';
+import { loadActivePackForEngine, approvedSchemaIdentity } from './schema-pack/engine-resolution.ts';
+import { invalidatePackCache } from './schema-pack/registry.ts';
+import { executeRawJsonb } from './sql-query.ts';
+import { applyAttendanceDelta } from './derived-links.ts';
+
+export const ATTENDANCE_REPAIR_PARSER = `attendance-repair-v2:${LINK_EXTRACTOR_VERSION_TS}`;
+export const ATTENDANCE_REPAIR_LIMIT = 250;
+export const ATTENDANCE_REPAIR_MAX = 1000;
+const MAX_REFS = 256;
+const MAX_EDGES = 512;
+const MAX_BYTES = 256 * 1024;
+const CHECKPOINT_OP = 'attendance-repair';
+const APPROVAL_LIFETIME_MS = 7 * 86400_000;
+
+export function attendanceRepairHash(value: unknown): string {
+ const canonical = (item: unknown): unknown => Array.isArray(item) ? item.map(canonical)
+ : item && typeof item === 'object' ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)
+ .map(([key, entry]) => [key, canonical(entry)])) : item;
+ return createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');
+}
+
+interface PagePin { id: string; slug: string; source_id: string; type: string; revision: string }
+interface ScanPage extends PagePin { deleted: boolean }
+interface OriginPage extends PagePin {
+ compiled_truth: string | null;
+ timeline: string | null;
+ bytes: number;
+}
+export interface AttendanceEdge {
+ id: string;
+ from_page_id: string;
+ to_page_id: string;
+ origin_page_id: string | null;
+ link_source: string | null;
+ origin_field: string | null;
+ link_kind: string | null;
+ row_hash: string | null;
+}
+export interface AttendanceOriginPreview {
+ page: PagePin;
+ contentHash: string;
+ lookupSlugs: string[];
+ endpoints: PagePin[];
+ adjacentRows: number;
+ before: AttendanceEdge[];
+ remove: string[];
+ add: Array<{ from: string; producer: string; field: string | null; evidenceHash: string }>;
+ unchanged: number;
+ skipped: number;
+ ambiguous: number;
+ reason?: string;
+}
+export interface AttendanceRepairPreview {
+ version: 2;
+ approvalId: string;
+ issuedAt: number;
+ parser: string;
+ brain: string;
+ sourceId: string;
+ sourceIncarnation: string;
+ ontology: string;
+ pack: string;
+ direction: 'person_to_meeting' | 'pack_semantics_preserved' | 'pack_unavailable';
+ frontmatter: 'report_only';
+ afterSlug: string;
+ limit: number;
+ nextAfterSlug: string;
+ complete: boolean;
+ window: ScanPage[];
+ origins: AttendanceOriginPreview[];
+ counts: { scanned: number; eligibleOrigins: number; changed: number; add: number; remove: number; unchanged: number;
+ skipped: number; ambiguous: number; conflicts: number; pack_semantics_preserved: number };
+ diagnostics: Array<{ originId: string; reason: string }>;
+ digest: string;
+}
+export interface AttendanceRepairAuthority { remote: boolean }
+
+export function assertAttendanceRepairAuthority(authority: AttendanceRepairAuthority) {
+ if (authority.remote !== false) throw new Error('Attendance repair requires trusted local authority');
+}
+
+export function validateAttendanceRepairScope(sourceId: string, limit = ATTENDANCE_REPAIR_LIMIT, afterSlug = '') {
+ if (!isValidSourceId(sourceId)) throw new Error('Attendance repair requires an explicit source ID');
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > ATTENDANCE_REPAIR_MAX) throw new Error('Attendance repair limit must be 1–1000');
+ if (typeof afterSlug !== 'string' || Buffer.byteLength(afterSlug) > 2048 || /[\x00-\x1f\x7f]/.test(afterSlug)) {
+ throw new Error('Attendance repair after-slug must be a bounded slug cursor');
+ }
+}
+
+async function identity(engine: BrainEngine, sourceId: string) {
+ const sources = await engine.executeRaw<{ id: string; incarnation: string }>(
+ 'SELECT id, incarnation FROM sources WHERE id=ANY($1::text[]) AND archived IS NOT TRUE AND archived_at IS NULL', [[sourceId, 'default']]);
+ const source = sources.find(row => row.id === sourceId);
+ const brain = sources.find(row => row.id === 'default');
+ if (!source || !brain) throw new Error(`Attendance repair requires an existing live source and brain identity: ${!source
+ ? `selected source '${sourceId}'` : "literal 'default' identity source"} is missing or archived`);
+ return { sourceIncarnation: source.incarnation, brain: attendanceRepairHash(brain.incarnation) };
+}
+
+async function ontology(engine: BrainEngine, sourceId: string) {
+ const bindings = [await engine.getConfig('schema_pack'), await engine.getConfig(`schema_pack.source.${sourceId}`),
+ process.env.GBRAIN_SCHEMA_PACK ?? null];
+ try {
+ let resolved = await loadActivePackForEngine(engine, { remote: false, sourceId });
+ invalidatePackCache(resolved.manifest.name);
+ resolved = await loadActivePackForEngine(engine, { remote: false, sourceId });
+ const pack = resolved.manifest;
+ const overridden = pack.link_types.some(link => link.name === 'attended' && link.inference)
+ || pack.frontmatter_links.some(mapping => mapping.page_type === 'meeting'
+ && (mapping.link_type === 'attended' || mapping.fields.includes('attendees')));
+ return { hash: attendanceRepairHash([bindings, approvedSchemaIdentity(resolved)]), name: pack.name,
+ direction: overridden ? 'pack_semantics_preserved' as const : 'person_to_meeting' as const, pack };
+ } catch {
+ return { hash: attendanceRepairHash(bindings), name: 'unavailable', direction: 'pack_unavailable' as const, pack: null };
+ }
+}
+
+const PAGE_PIN_SQL = 'id::text, slug, source_id, type, knowledge_revision::text AS revision';
+
+async function readOrigin(engine: BrainEngine, sourceId: string, id: string): Promise<OriginPage> {
+ const rows = await engine.executeRaw<OriginPage>(`SELECT ${PAGE_PIN_SQL},
+ octet_length(compiled_truth)+octet_length(COALESCE(timeline,'')) AS bytes,
+ CASE WHEN octet_length(compiled_truth)+octet_length(COALESCE(timeline,''))<=$3 THEN compiled_truth END AS compiled_truth,
+ CASE WHEN octet_length(compiled_truth)+octet_length(COALESCE(timeline,''))<=$3 THEN timeline END AS timeline
+ FROM pages WHERE source_id=$1 AND id=$2::bigint AND deleted_at IS NULL`, [sourceId, id, MAX_BYTES]);
+ if (!rows.length) throw new Error('Attendance repair origin changed or was deleted');
+ return rows[0];
+}
+
+async function readEdges(engine: BrainEngine, id: string) {
+ const candidates = await engine.executeRaw<{ id: string }>(`WITH candidates AS MATERIALIZED (
+ (SELECT id FROM links WHERE from_page_id=$1::bigint LIMIT $2)
+ UNION (SELECT id FROM links WHERE to_page_id=$1::bigint LIMIT $2)
+ UNION (SELECT id FROM links WHERE origin_page_id=$1::bigint LIMIT $2)
+ ) SELECT id::text FROM candidates LIMIT $2`, [id, MAX_EDGES + 1]);
+ if (candidates.length > MAX_EDGES || !candidates.length) return { edges: [] as AttendanceEdge[], count: candidates.length };
+ const edges = await engine.executeRaw<AttendanceEdge>(`SELECT id::text, from_page_id::text, to_page_id::text,
+ origin_page_id::text, link_source, link_kind,
+ CASE WHEN octet_length(context)+octet_length(COALESCE(origin_field,''))<=$2 THEN origin_field END AS origin_field,
+ CASE WHEN octet_length(context)+octet_length(COALESCE(origin_field,''))<=$2 THEN encode(sha256(convert_to(to_jsonb(l)::text,'UTF8')),'hex') END AS row_hash
+ FROM links l WHERE id=ANY($1::bigint[]) AND link_type='attended' ORDER BY l.id`, [candidates.map(row => row.id), MAX_BYTES]);
+ return { edges, count: candidates.length };
+}
+
+function pagePin(page: PagePin): PagePin {
+ return { id: page.id, slug: page.slug, source_id: page.source_id, type: page.type, revision: page.revision };
+}
+
+async function prepareOrigin(engine: BrainEngine, page: OriginPage, pack: LinkExtractionPack | null, direction: string, pinnedSlugs: string[] = []) {
+ const result: AttendanceOriginPreview = { page: pagePin(page), contentHash: attendanceRepairHash([
+ page.compiled_truth, page.timeline, page.bytes]), lookupSlugs: [], endpoints: [], adjacentRows: 0, before: [],
+ remove: [], add: [], unchanged: 0, skipped: 0, ambiguous: 0 };
+ const additions: LinkBatchInput[] = [];
+ const stop = (reason: string) => { result.reason = reason; result.skipped++; return { result, additions: [] as LinkBatchInput[] }; };
+ const adjacent = await readEdges(engine, page.id);
+ result.before = adjacent.edges;
+ result.adjacentRows = adjacent.count;
+ if (direction !== 'person_to_meeting') return stop(direction);
+ if (page.type !== 'meeting') return stop('origin_type_unsupported');
+ if (page.bytes > MAX_BYTES || page.compiled_truth === null) return stop('origin_size_limit');
+ if (adjacent.count > MAX_EDGES) return stop('edge_limit');
+ if (result.before.some(edge => edge.row_hash === null)) return stop('edge_size_limit');
+ const needed = new Set<string>(pinnedSlugs);
+ const resolver: SlugResolver = { async resolve() { return null; } };
+ const content = `${page.compiled_truth}\n${page.timeline ?? ''}`;
+ const first = await extractPageLinks(page.slug, content, {}, page.type, resolver,
+ { pack, skipFrontmatter: true, targetType: () => 'person' });
+ for (const candidate of first.candidates) {
+ if (!candidate.targetSourceId || candidate.targetSourceId === page.source_id) needed.add(candidate.targetSlug);
+ }
+ if (needed.size > MAX_REFS) return stop('reference_limit');
+ const edgeIds = [...new Set(result.before.flatMap(edge => [edge.from_page_id, edge.to_page_id]))].filter(id => id !== page.id);
+ const edgeEndpoints = edgeIds.length ? await engine.executeRaw<PagePin>(`SELECT ${PAGE_PIN_SQL} FROM pages
+ WHERE source_id=$1 AND id=ANY($2::bigint[]) AND deleted_at IS NULL ORDER BY slug`, [page.source_id, edgeIds]) : [];
+ for (const endpoint of edgeEndpoints) needed.add(endpoint.slug);
+ if (needed.size > MAX_REFS) return stop('reference_limit');
+ result.lookupSlugs = [...needed].sort();
+ const endpoints = needed.size ? await engine.executeRaw<PagePin>(`SELECT ${PAGE_PIN_SQL} FROM pages
+ WHERE source_id=$1 AND slug=ANY($2::text[]) AND deleted_at IS NULL ORDER BY slug`, [page.source_id, result.lookupSlugs]) : [];
+ result.endpoints = endpoints;
+ const index = new Map(endpoints.map(endpoint => [endpoint.slug, endpoint]));
+ const ranges = attendanceEvidenceRanges(content);
+ const ambiguousBare = extractEntityRefs(content).filter(ref => ref.needsResolution && !ref.slug.includes('/')
+ && ref.index !== undefined && hasAttendanceEvidence(ranges, ref.index)
+ && [...new Set([slugifyPath(ref.slug), normalizeBasename(ref.slug)])]
+ .filter(slug => index.get(slug)?.type === 'person').length !== 1);
+ const unresolvedBody = first.candidates.filter(candidate => candidate.canonicalAttendance
+ && ((candidate.targetSourceId && candidate.targetSourceId !== page.source_id) || index.get(candidate.targetSlug)?.type !== 'person'));
+ if (unresolvedBody.length || ambiguousBare.length) {
+ result.ambiguous = unresolvedBody.length + ambiguousBare.length;
+ return stop('unresolved_attendees');
+ }
+ const extracted = await extractPageLinks(page.slug, content, {}, page.type, resolver,
+ { pack, skipFrontmatter: true, targetType: (slug, source) => !source || source === page.source_id ? index.get(slug)?.type : undefined });
+ const desired = new Map<string, LinkBatchInput>();
+ for (const candidate of extracted.candidates) {
+ if (candidate.linkType !== 'attended' || (candidate.targetSourceId && candidate.targetSourceId !== page.source_id)) continue;
+ const row = resolvedLinkCandidate(candidate, page.slug, page.source_id,
+ { fromSlug: candidate.fromSlug ?? page.slug, fromSourceId: page.source_id, toSourceId: page.source_id });
+ if (row.to_slug !== page.slug || row.origin_slug !== page.slug || index.get(row.from_slug)?.type !== 'person'
+ || row.link_source !== 'markdown') continue;
+ desired.set(`${index.get(row.from_slug)!.id}:${row.link_source}`, row);
+ }
+ const retained = new Set<string>();
+ for (const edge of result.before) {
+ const canonicalKey = `${edge.from_page_id}:${edge.link_source}`;
+ const owned = edge.origin_page_id === page.id && edge.to_page_id === page.id
+ && edge.link_source === 'markdown';
+ const legacy = edge.from_page_id === page.id && edge.origin_page_id === null && edge.link_source === 'markdown';
+ if ((owned || legacy) && !endpoints.some(endpoint => endpoint.id === (owned ? edge.from_page_id : edge.to_page_id)
+ && endpoint.type === 'person')) return stop('endpoint_unavailable');
+ if (owned) {
+ if (desired.has(canonicalKey)) { retained.add(canonicalKey); result.unchanged++; }
+ else result.remove.push(edge.id);
+ } else if (legacy) {
+ if (!desired.has(`${edge.to_page_id}:markdown`)) return stop('legacy_evidence_unproven');
+ result.remove.push(edge.id);
+ } else result.skipped++;
+ }
+ for (const [key, row] of desired) {
+ if (retained.has(key)) continue;
+ additions.push(row);
+ result.add.push({ from: index.get(row.from_slug)!.id, producer: row.link_source!, field: row.origin_field ?? null,
+ evidenceHash: attendanceRepairHash(row.context ?? '') });
+ }
+ if (adjacent.count - result.remove.length + result.add.length > MAX_EDGES) return stop('edge_limit');
+ return { result, additions };
+}
+
+export async function previewAttendanceRepair(engine: BrainEngine, options: AttendanceRepairAuthority & {
+ sourceId: string; limit?: number; afterSlug?: string; brainIdentity?: string;
+}): Promise<AttendanceRepairPreview> {
+ assertAttendanceRepairAuthority(options);
+ const limit = options.limit ?? ATTENDANCE_REPAIR_LIMIT;
+ const afterSlug = options.afterSlug ?? '';
+ validateAttendanceRepairScope(options.sourceId, limit, afterSlug);
+ const [{ issued_at }] = await engine.executeRaw<{ issued_at: string }>(
+ 'SELECT floor(extract(epoch FROM clock_timestamp())*1000)::text AS issued_at');
+ const selected = await identity(engine, options.sourceId);
+ selected.brain = attendanceRepairHash([selected.brain, options.brainIdentity ?? null]);
+ const schema = await ontology(engine, options.sourceId);
+ const window = await engine.executeRaw<ScanPage>(`SELECT ${PAGE_PIN_SQL}, deleted_at IS NOT NULL AS deleted
+ FROM pages WHERE source_id=$1 AND slug>$2 ORDER BY slug LIMIT $3`, [options.sourceId, afterSlug, limit]);
+ const origins: AttendanceOriginPreview[] = [];
+ let retainedBytes = 0;
+ for (const page of window.filter(page => page.type === 'meeting' && !page.deleted)) {
+ const { result } = await prepareOrigin(engine, await readOrigin(engine, options.sourceId, page.id), schema.pack, schema.direction);
+ if (attendanceRepairHash(result.page) !== attendanceRepairHash(pagePin(page))) throw new Error('Attendance origin changed during preview');
+ if (result.reason) { result.remove = []; result.add = []; }
+ retainedBytes += Buffer.byteLength(JSON.stringify(result));
+ if (retainedBytes > 16 * 1024 ** 2) throw new Error('Attendance preview exceeds 16 MiB; use a smaller --limit');
+ origins.push(result);
+ }
+ const counts = { scanned: window.length, eligibleOrigins: origins.length, changed: 0, add: 0, remove: 0, unchanged: 0,
+ skipped: window.length - origins.length, ambiguous: 0,
+ conflicts: 0, pack_semantics_preserved: 0 };
+ for (const origin of origins) {
+ counts.changed += Number(origin.add.length + origin.remove.length > 0);
+ counts.add += origin.add.length; counts.remove += origin.remove.length; counts.unchanged += origin.unchanged;
+ counts.skipped += origin.skipped; counts.ambiguous += origin.ambiguous;
+ counts.pack_semantics_preserved += Number(origin.reason === 'pack_semantics_preserved');
+ }
+ const preview: AttendanceRepairPreview = { version: 2, approvalId: randomUUID(), issuedAt: Number(issued_at), parser: ATTENDANCE_REPAIR_PARSER, ...selected,
+ sourceId: options.sourceId, ontology: schema.hash, pack: schema.name, direction: schema.direction, afterSlug, limit,
+ frontmatter: 'report_only', nextAfterSlug: window.at(-1)?.slug ?? afterSlug, complete: window.length < limit,
+ window, origins, counts, diagnostics: origins.filter(origin => origin.reason).slice(0, 20)
+ .map(origin => ({ originId: origin.page.id, reason: origin.reason! })), digest: '' };
+ preview.digest = attendanceRepairHash({ ...preview, digest: '' });
+ return preview;
+}
+
+export async function applyAttendanceRepair(engine: BrainEngine, preview: AttendanceRepairPreview,
+ options: AttendanceRepairAuthority & { sourceId: string; confirm: string; yes: boolean; backupVerified: boolean; brainIdentity?: string;
+ checkpoint: (state: { digest: string; sourceIncarnation: string; ontology: string; committed: number; originId: string | null;
+ afterSlug: string; pagesProcessed: number;
+ approvedAdded: number; approvedRemoved: number; createdThisRun: number; removedThisRun: number; replayed: number }) => Promise<void>;
+ }) {
+ assertAttendanceRepairAuthority(options);
+ validateAttendanceRepairScope(options.sourceId, preview.limit, preview.afterSlug);
+ if (options.yes !== true || options.backupVerified !== true || typeof options.checkpoint !== 'function') {
+ throw new Error('Attendance apply requires --yes, --backup-verified and a private checkpoint');
+ }
+ if (preview.version !== 2 || typeof preview.approvalId !== 'string'
+ || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(preview.approvalId)
+ || !Number.isSafeInteger(preview.issuedAt) || preview.issuedAt <= 0 || preview.issuedAt > 8640000000000000
+ || preview.parser !== ATTENDANCE_REPAIR_PARSER || preview.sourceId !== options.sourceId
+ || preview.digest !== options.confirm || preview.digest !== attendanceRepairHash({ ...preview, digest: '' })
+ || preview.origins.length > preview.limit || preview.window.length > preview.limit
+ || preview.frontmatter !== 'report_only' || preview.nextAfterSlug !== (preview.window.at(-1)?.slug ?? preview.afterSlug)) {
+ throw new Error('Attendance preview identity mismatch');
+ }
+ if (attendanceRepairHash(preview.origins.map(origin => origin.page)) !== attendanceRepairHash(preview.window
+ .filter(page => page.type === 'meeting' && !page.deleted).map(pagePin))) throw new Error('Attendance preview window mismatch');
+ if (preview.origins.some(origin => origin.lookupSlugs.length > MAX_REFS || origin.endpoints.length > MAX_REFS
+ || origin.before.length > MAX_EDGES + 1 || origin.add.length > MAX_REFS || origin.remove.length > MAX_EDGES
+ || !/^\d+$/.test(origin.page.id)) || new Set(preview.origins.map(origin => origin.page.id)).size !== preview.origins.length) {
+ throw new Error('Attendance preview exceeds repair bounds');
+ }
+ const initialIdentity = await identity(engine, preview.sourceId);
+ const initialSchema = await ontology(engine, preview.sourceId);
+ if (attendanceRepairHash([initialIdentity.brain, options.brainIdentity ?? null]) !== preview.brain
+ || initialIdentity.sourceIncarnation !== preview.sourceIncarnation || initialSchema.hash !== preview.ontology) {
+ throw new Error('Attendance source, brain or ontology changed; preview again');
+ }
+ let committed = 0;
+ let created = 0;
+ let removed = 0;
+ let replayed = 0;
+ let approvedAdded = 0;
+ let approvedRemoved = 0;
+ let pagesProcessed = 0;
+ let originId: string | null = null;
+ const pending = [...preview.origins, ...(preview.window.at(-1)?.id !== preview.origins.at(-1)?.page.id || !preview.window.length ? [null] : [])];
+ for (const approved of pending) {
+ const end = approved ? preview.window.findIndex(page => page.id === approved.page.id) + 1 : preview.window.length;
+ const segment = preview.window.slice(pagesProcessed, end);
+ const result = await engine.transaction(async tx => {
+ await tx.executeRaw("SET LOCAL lock_timeout='5s'");
+ await tx.executeRaw("SET LOCAL statement_timeout='10s'");
+ await tx.executeRaw('LOCK TABLE config IN SHARE MODE');
+ await tx.executeRaw('SELECT id FROM sources WHERE id=ANY($1::text[]) ORDER BY id FOR SHARE', [[preview.sourceId, 'default']]);
+ await tx.lockPageKeys([...segment.map(page => ({ sourceId: preview.sourceId, slug: page.slug })),
+ ...(approved?.lookupSlugs ?? []).map(slug => ({ sourceId: preview.sourceId, slug }))]);
+ if (approved) await tx.executeRaw('LOCK TABLE links IN SHARE ROW EXCLUSIVE MODE');
+ const actualIdentity = await identity(tx, preview.sourceId);
+ const actualSchema = await ontology(tx, preview.sourceId);
+ if (attendanceRepairHash([actualIdentity.brain, options.brainIdentity ?? null]) !== preview.brain || actualIdentity.sourceIncarnation !== preview.sourceIncarnation
+ || actualSchema.hash !== preview.ontology) throw new Error('Attendance source, brain or ontology changed; preview again');
+ const actualSegment = segment.length ? await tx.executeRaw<ScanPage>(`SELECT ${PAGE_PIN_SQL}, deleted_at IS NOT NULL AS deleted
+ FROM pages WHERE source_id=$1 AND slug=ANY($2::text[]) ORDER BY slug`, [preview.sourceId, segment.map(page => page.slug)]) : [];
+ if (attendanceRepairHash(actualSegment) !== attendanceRepairHash(segment)) throw new Error('Attendance scan window changed; preview again');
+ const [{ checked_at }] = await tx.executeRaw<{ checked_at: string }>(
+ 'SELECT floor(extract(epoch FROM clock_timestamp())*1000)::text AS checked_at');
+ if (preview.issuedAt > Number(checked_at) || Number(checked_at) - preview.issuedAt >= APPROVAL_LIFETIME_MS) {
+ throw new Error('Attendance approval expired or is not yet valid; preview again');
+ }
+ if (!approved) return { created: 0, removed: 0, replayed: 0 };
+ const page = await readOrigin(tx, preview.sourceId, approved.page.id);
+ const prepared = await prepareOrigin(tx, page, actualSchema.pack, actualSchema.direction, approved.lookupSlugs);
+ if (prepared.result.reason) { prepared.result.remove = []; prepared.result.add = []; }
+ if (attendanceRepairHash([prepared.result.page, prepared.result.contentHash, prepared.result.endpoints, prepared.result.lookupSlugs])
+ !== attendanceRepairHash([approved.page, approved.contentHash, approved.endpoints, approved.lookupSlugs])) {
+ throw new Error('Attendance origin or endpoint changed; preview again');
+ }
+ const key = attendanceRepairHash([preview.digest, approved.page.id]);
+ const receipts = await tx.executeRaw<{ completed_keys: string[]; live: boolean }>(
+ `SELECT completed_keys, updated_at > clock_timestamp()-interval '7 days' AND updated_at <= clock_timestamp() AS live
+ FROM op_checkpoints WHERE op=$1 AND fingerprint=$2 FOR SHARE`, [CHECKPOINT_OP, key]);
+ if (receipts.length) {
+ if (!receipts[0].live) throw new Error('Attendance commit proof expired; preview again');
+ if (receipts[0].completed_keys[0] !== attendanceRepairHash([prepared.result.before, prepared.result.adjacentRows])) {
+ throw new Error('Committed attendance edges changed; preview again');
+ }
+ return { created: 0, removed: 0, replayed: 1 };
+ }
+ if (attendanceRepairHash(prepared.result) !== attendanceRepairHash(approved)) throw new Error('Attendance edges or resolution changed; preview again');
+ const delta = await applyAttendanceDelta(tx, approved.page, approved.remove, prepared.additions);
+ if ((await ontology(tx, preview.sourceId)).hash !== preview.ontology) throw new Error('Attendance ontology changed during repair');
+ const after = await readEdges(tx, approved.page.id);
+ if (!approved.reason && after.count > MAX_EDGES) throw new Error('Attendance delta exceeded its edge bound');
+ await executeRawJsonb(tx, `INSERT INTO op_checkpoints(op,fingerprint,completed_keys)
+ VALUES ($1,$2,($3::jsonb)->'keys')`, [CHECKPOINT_OP, key], [{ keys: [attendanceRepairHash([after.edges, after.count])] }]);
+ return { ...delta, replayed: 0 };
+ });
+ pagesProcessed = end;
+ if (approved) { committed++; originId = approved.page.id; }
+ created += result.created; removed += result.removed; replayed += result.replayed;
+ approvedAdded += approved?.add.length ?? 0; approvedRemoved += approved?.remove.length ?? 0;
+ await options.checkpoint({ digest: preview.digest, sourceIncarnation: preview.sourceIncarnation,
+ ontology: preview.ontology, committed, originId, afterSlug: segment.at(-1)?.slug ?? preview.afterSlug, pagesProcessed, approvedAdded, approvedRemoved,
+ createdThisRun: created, removedThisRun: removed, replayed });
+ }
+ return { committed, pagesProcessed, created, removed, replayed, afterSlug: preview.nextAfterSlug, complete: true };
+}
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 8a8c48a795..ccdf98c5cb 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -53,7 +53,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'enrich': ['--access', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--concurrency', '--confirm-destructive', '--date', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--explain', '--file', '--follow', '--force', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--mode', '--model', '--multimodal', '--once', '--order', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--reenrich-after', '--resume', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--stats', '--status', '--surface', '--thin', '--thin-threshold', '--timeout', '--trusted-extraction', '--types', '--url', '--workers', '--yes'],
'eval': ['--ab-relational', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--capture-pool', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-cache', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--pglite', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--receipt-dir', '--record', '--refresh-cache', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--status', '--strategy', '--suite', '--suites', '--supabase', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--timeout', '--tool', '--top-k', '--top-regressions', '--until', '--update-baseline', '--usefulness-min', '--verbose', '--verify', '--with-code-intel', '--yes'],
'export': ['--background', '--brain', '--dir', '--explain', '--fix', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--slug-prefix', '--source', '--timeout', '--type'],
- 'extract': ['--background', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--dry-run', '--explain', '--follow', '--from-meetings', '--help', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--ner', '--pack', '--path', '--progress-interval', '--progress-json', '--quiet', '--rebuild', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--workers', '--yes'],
+ 'extract': ['--after-slug', '--apply-preview', '--background', '--backup-verified', '--brain', '--by-mention', '--catch-up', '--checkpoint', '--concurrency', '--confirm', '--dir', '--dry-run', '--explain', '--follow', '--from-meetings', '--help', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--limit', '--ner', '--pack', '--path', '--progress-interval', '--progress-json', '--quiet', '--rebuild', '--repair-attendance', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--workers', '--yes'],
'extract-conversation-facts': ['--background', '--brain', '--concurrency', '--confirm-destructive', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-embedding', '--override-disabled', '--path', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--segment-limit', '--since', '--sleep', '--slug', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--workers', '--yes'],
'features': ['--all', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--explain', '--facts', '--from-meetings', '--help', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--ner', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--path', '--priority', '--rebuild', '--refresh', '--repo', '--since', '--slugs', '--source', '--source-id', '--stale', '--target', '--type', '--verbose', '--workers'],
'files': ['--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-pointer', '--page', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--source', '--timeout', '--type', '--yes'],
@@ -87,7 +87,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'providers': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--model', '--source', '--status', '--touchpoint'],
'publish': ['--accent', '--bg', '--border', '--brain', '--card-bg', '--code-bg', '--error', '--fg', '--help', '--json', '--link', '--muted', '--out', '--password', '--source', '--title'],
'quarantine': ['--apply', '--brain', '--force', '--force-rechunk', '--help', '--include-flagged', '--json', '--limit', '--no-embed', '--source', '--source-id', '--stale'],
- 'recall': ['--access', '--as-context', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--budget-tokens', '--date', '--days', '--entities', '--explain', '--file', '--follow', '--full', '--grep', '--help', '--http', '--image', '--include-expired', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--pending', '--progress-interval', '--progress-json', '--query', '--quiet', '--reason', '--request-id', '--rollup', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--stats', '--supersessions', '--surface', '--timeout', '--today', '--trusted-extraction', '--types', '--url', '--watch', '--yes'],
+ 'recall': ['--access', '--as-context', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--date', '--days', '--entities', '--explain', '--file', '--follow', '--full', '--grep', '--help', '--http', '--image', '--include-expired', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--pending', '--progress-interval', '--progress-json', '--query', '--quiet', '--reason', '--request-id', '--rollup', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--source-id', '--stats', '--supersessions', '--surface', '--timeout', '--today', '--trusted-extraction', '--types', '--url', '--watch', '--yes'],
'reconcile-links': ['--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout'],
'reindex': ['--aliases', '--background', '--brain', '--concurrency', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--force-rechunk', '--help', '--json', '--limit', '--markdown', '--multimodal', '--no-embed', '--no-embedding', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--repo', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--type', '--workers', '--yes'],
'reindex-code': ['--background', '--brain', '--break-lock', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-embed', '--path', '--progress-interval', '--progress-json', '--quiet', '--source', '--status', '--timeout', '--workers', '--yes'],
@@ -116,7 +116,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'sweep': ['--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-delegate', '--once', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout'],
'sync': ['--abbrev-ref', '--abort', '--account', '--all', '--allow-empty', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--ids', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--repo', '--reset', '--restore-only', '--resume', '--retry-failed', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--watch', '--window', '--workers', '--working-tree', '--yes'],
'takes': ['--accept', '--batch-size', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--pglite', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],
- 'think': ['--anchor', '--bind', '--brain', '--calibration-holder', '--enable-dcr', '--enable-dcr-insecure', '--help', '--http', '--json', '--log-full-params', '--mcp-only', '--model', '--oauth-request', '--port', '--print-admin-token', '--public-url', '--rounds', '--save', '--since', '--source', '--source-guard', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--take', '--token-ttl', '--until', '--url', '--with-calibration', '--yes'],
+ 'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],
'transcripts': ['--all', '--all-discovery', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--progress-interval', '--progress-json', '--quiet', '--since', '--source', '--source-id', '--timeout'],
'upgrade': ['--acknowledge-no-backup', '--all', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--quiet', '--repo', '--require-db', '--skills-dir', '--skip-verify', '--source', '--status', '--swap-only', '--target', '--uninstall', '--user', '--verify', '--version', '--workers', '--yes'],
'waiting': ['--all', '--brain', '--help', '--json', '--source', '--stale-ok', '--status', '--top', '--type'],
diff --git a/src/core/derived-links.ts b/src/core/derived-links.ts
index 0b42ce3827..8bdcc2be32 100644
--- a/src/core/derived-links.ts
+++ b/src/core/derived-links.ts
@@ -1,6 +1,7 @@
import type { BrainEngine, LinkBatchInput } from './engine.ts';
import { assertPageRevision } from './page-state/types.ts';
import { executeRawJsonb } from './sql-query.ts';
+import { sanitizeForJsonb } from './batch-rows.ts';
export interface DerivedLinkOrigin {
slug: string;
@@ -11,6 +12,8 @@ export interface DerivedLinkOrigin {
export interface DerivedLinkReplacementOptions {
includeFrontmatter?: boolean;
+ preserveExisting?: boolean;
+ includeLegacyNullProducer?: boolean;
expectedEndpoints?: Array<{ slug: string; sourceId: string; revision: string }>;
}
@@ -22,6 +25,27 @@ export class DerivedLinkRepairRequiredError extends Error {
}
}
+export class DerivedLinkEndpointChangedError extends Error {
+ readonly code = 'revision_conflict';
+}
+
+export async function applyAttendanceDelta(tx: Pick<BrainEngine, 'executeRaw' | 'addLinksBatch'>,
+ origin: { id: string; slug: string; source_id: string; type: string }, remove: string[], additions: LinkBatchInput[]) {
+ if (origin.type !== 'meeting' || remove.length > 512 || additions.length > 256
+ || additions.some(row => row.link_type !== 'attended' || row.to_slug !== origin.slug
+ || row.to_source_id !== origin.source_id || row.from_source_id !== origin.source_id
+ || row.origin_slug !== origin.slug || row.origin_source_id !== origin.source_id
+ || row.link_source !== 'markdown')) throw new Error('Invalid attendance delta');
+ const removed = remove.length ? await tx.executeRaw(`DELETE FROM links WHERE id=ANY($1::bigint[])
+ AND link_type='attended' AND link_source='markdown'
+ AND (origin_page_id=$2::bigint OR (origin_page_id IS NULL AND from_page_id=$2::bigint AND link_source='markdown'))
+ RETURNING id`, [remove, origin.id]) : [];
+ if (removed.length !== remove.length) throw new Error('Attendance removal changed');
+ const created = additions.length ? await tx.addLinksBatch(additions, { auditSite: 'addLinksBatch' }) : 0;
+ if (created !== additions.length) throw new Error('Attendance insertion did not persist the approved delta');
+ return { created, removed: removed.length };
+}
+
export async function replaceDerivedLinks(
engine: Pick<BrainEngine, 'transaction'>,
origin: DerivedLinkOrigin,
@@ -37,9 +61,13 @@ export async function replaceDerivedLinks(
|| (link.origin_source_id && link.origin_source_id !== origin.sourceId)) {
throw new TypeError('Derived link origin does not match the replacement scope');
}
- const row = { ...link, link_source: producer, origin_slug: producer === 'frontmatter' ? origin.slug : undefined, origin_source_id: origin.sourceId,
+ const reversedAttendance = (producer === 'markdown' || producer === 'wikilink-resolved') && link.link_type === 'attended'
+ && link.origin_slug === origin.slug && link.origin_source_id === origin.sourceId
+ && (link.from_slug !== origin.slug || (link.from_source_id ?? origin.sourceId) !== origin.sourceId)
+ && link.to_slug === origin.slug && (link.to_source_id ?? origin.sourceId) === origin.sourceId;
+ const row = { ...link, link_source: producer, origin_slug: producer === 'frontmatter' || reversedAttendance ? origin.slug : undefined, origin_source_id: origin.sourceId,
from_source_id: link.from_source_id ?? origin.sourceId, to_source_id: link.to_source_id ?? origin.sourceId };
- if (producer !== 'frontmatter' && (row.from_slug !== origin.slug || row.from_source_id !== origin.sourceId)) {
+ if (producer !== 'frontmatter' && !reversedAttendance && (row.from_slug !== origin.slug || row.from_source_id !== origin.sourceId)) {
throw new TypeError('Markdown links must originate at the replaced page');
}
if (row.from_slug !== origin.slug || row.from_source_id !== origin.sourceId) {
@@ -59,7 +87,7 @@ export async function replaceDerivedLinks(
throw new Error('Derived link origin changed or was deleted');
}
const id = snapshot.page.id;
- if (opts.includeFrontmatter !== false) {
+ if (opts.includeFrontmatter !== false && !opts.preserveExisting) {
const ambiguous = await tx.executeRaw(`SELECT 1 FROM links WHERE link_source='frontmatter'
AND origin_page_id IS NULL AND (from_page_id=$1 OR to_page_id=$1) LIMIT 1`, [id]);
if (ambiguous.length) throw new DerivedLinkRepairRequiredError();
@@ -69,13 +97,61 @@ export async function replaceDerivedLinks(
LEFT JOIN pages f ON f.slug=v.from_slug AND f.source_id=v.from_source_id AND f.deleted_at IS NULL
LEFT JOIN pages t ON t.slug=v.to_slug AND t.source_id=v.to_source_id AND t.deleted_at IS NULL
WHERE f.id IS NULL OR t.id IS NULL LIMIT 1`, [], [{ rows }]);
- if (missing.length) throw new Error('A derived link endpoint changed or was deleted');
+ if (missing.length) throw new DerivedLinkEndpointChangedError('A derived link endpoint changed or was deleted');
if (opts.expectedEndpoints?.length) {
const changed = await executeRawJsonb(tx, `SELECT 1 FROM jsonb_to_recordset(($1::jsonb)->'rows')
AS v(slug text, "sourceId" text, revision text)
LEFT JOIN pages p ON p.slug=v.slug AND p.source_id=v."sourceId" AND p.deleted_at IS NULL
WHERE p.id IS NULL OR p.knowledge_revision::text <> v.revision LIMIT 1`, [], [{ rows: opts.expectedEndpoints }]);
- if (changed.length) throw new Error('A derived link endpoint changed after type resolution');
+ if (changed.length) throw new DerivedLinkEndpointChangedError('A derived link endpoint changed after type resolution');
+ }
+ const reversed = rows.filter(row => row.link_type === 'attended' && row.origin_slug
+ && row.to_slug === origin.slug && row.to_source_id === origin.sourceId
+ && (row.from_slug !== origin.slug || row.from_source_id !== origin.sourceId));
+ if (reversed.length) {
+ if (snapshot.page.type !== 'meeting' || reversed.some(row => row.link_source !== 'frontmatter' && !opts.expectedEndpoints?.some(endpoint =>
+ endpoint.slug === row.from_slug && endpoint.sourceId === row.from_source_id))) {
+ throw new TypeError('Canonical attendance requires a meeting origin and revision-bound person endpoints');
+ }
+ const invalid = await executeRawJsonb(tx, `SELECT 1 FROM jsonb_to_recordset(($1::jsonb)->'rows')
+ AS v(from_slug text, from_source_id text)
+ JOIN pages p ON p.slug=v.from_slug AND p.source_id=v.from_source_id
+ WHERE p.type <> 'person' LIMIT 1`, [], [{ rows: reversed }]);
+ if (invalid.length) throw new TypeError('Canonical attendance requires person endpoints');
+ }
+ if (opts.preserveExisting) {
+ const existing = await tx.executeRaw<{ id: number; from_slug: string; to_slug: string;
+ from_source_id: string; to_source_id: string; link_type: string; link_source: string | null;
+ origin_slug: string | null; origin_source_id: string | null; context: string; origin_field: string | null }>(`SELECT l.id, f.slug from_slug, t.slug to_slug,
+ f.source_id from_source_id, t.source_id to_source_id, l.link_type, l.link_source,
+ o.slug origin_slug, o.source_id origin_source_id, l.context, l.origin_field
+ FROM links l JOIN pages f ON f.id=l.from_page_id JOIN pages t ON t.id=l.to_page_id
+ LEFT JOIN pages o ON o.id=l.origin_page_id
+ WHERE (l.link_source=ANY($2::text[]) OR ($3::boolean AND l.link_source IS NULL))
+ AND (l.origin_page_id=$1 OR (l.origin_page_id IS NULL AND l.from_page_id=$1
+ AND (l.link_source IN ('markdown','wikilink-resolved') OR l.link_source IS NULL)))`, [id, producers, opts.includeLegacyNullProducer !== false]);
+ const identity = (row: Pick<LinkBatchInput, 'from_source_id' | 'from_slug' | 'to_source_id' | 'to_slug' | 'link_type'>
+ & { link_source?: string | null; origin_slug?: string | null }) => JSON.stringify([row.from_source_id, row.from_slug,
+ row.to_source_id, row.to_slug, row.link_type ?? '', row.link_source ?? 'markdown', row.origin_slug ?? null]);
+ const wanted = new Map(rows.map(row => [identity(row), row]));
+ const retained = new Set(existing.map(identity));
+ const obsolete = existing.filter(row => !wanted.has(identity(row))).map(row => row.id);
+ if (obsolete.length) await tx.executeRaw('DELETE FROM links WHERE id=ANY($1::bigint[])', [obsolete]);
+ const updates = existing.flatMap(previous => {
+ const desired = wanted.get(identity(previous));
+ if (!desired) return [];
+ const context = sanitizeForJsonb(desired.context || '');
+ const origin_field = desired.origin_field || null;
+ return previous.context !== context || previous.origin_field !== origin_field
+ ? [{ id: previous.id, context, origin_field }] : [];
+ });
+ if (updates.length) await executeRawJsonb(tx, `UPDATE links l SET context=v.context, origin_field=v.origin_field
+ FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(id bigint, context text, origin_field text)
+ WHERE l.id=v.id`, [], [{ rows: updates }]);
+ const additions = rows.filter(row => !retained.has(identity(row)));
+ const created = additions.length ? await tx.addLinksBatch(additions, { auditSite: 'addLinksBatch' }) : 0;
+ if (created !== additions.length) throw new Error('Derived link replacement did not persist every candidate');
+ return { created, removed: obsolete.length };
}
const removed = await tx.executeRaw(`DELETE FROM links WHERE link_source=ANY($2::text[])
AND (origin_page_id=$1 OR (origin_page_id IS NULL AND from_page_id=$1
diff --git a/src/core/extract-timeline-from-meetings.ts b/src/core/extract-timeline-from-meetings.ts
index c7a3d4cfcc..9f671374d2 100644
--- a/src/core/extract-timeline-from-meetings.ts
+++ b/src/core/extract-timeline-from-meetings.ts
@@ -57,10 +57,10 @@ interface MeetingRow {
}
interface AttendedEdgeRow {
- from_slug: string;
- from_source_id: string;
- to_slug: string;
- to_source_id: string;
+ meeting_slug: string;
+ meeting_source_id: string;
+ attendee_slug: string;
+ attendee_source_id: string;
}
const BATCH_SIZE = 200;
@@ -69,7 +69,7 @@ const BATCH_SIZE = 200;
const MEETING_PAGE_PREDICATE =
`(type = 'meeting' OR (type = 'note' AND frontmatter ->> 'legacy_type' = 'meeting'))`;
const MEETING_EDGE_PREDICATE =
- `(pf.type = 'meeting' OR (pf.type = 'note' AND pf.frontmatter ->> 'legacy_type' = 'meeting'))`;
+ `(meeting.type = 'meeting' OR (meeting.type = 'note' AND meeting.frontmatter ->> 'legacy_type' = 'meeting'))`;
export async function extractTimelineFromMeetings(
engine: BrainEngine,
@@ -101,19 +101,21 @@ export async function extractTimelineFromMeetings(
// Build a Map<meetingKey → attendees[]> for O(1) attendee lookup per meeting.
const meetingKeys = new Set(meetings.map((m) => `${m.source_id}::${m.slug}`));
const attendedEdges = await engine.executeRaw<AttendedEdgeRow>(
- `SELECT pf.slug AS from_slug, pf.source_id AS from_source_id,
- pt.slug AS to_slug, pt.source_id AS to_source_id
+ `SELECT meeting.slug AS meeting_slug, meeting.source_id AS meeting_source_id,
+ attendee.slug AS attendee_slug, attendee.source_id AS attendee_source_id
FROM links l
- JOIN pages pf ON pf.id = l.from_page_id
- JOIN pages pt ON pt.id = l.to_page_id
+ JOIN pages meeting ON meeting.id IN (l.from_page_id, l.to_page_id)
+ JOIN pages attendee ON attendee.id = CASE WHEN meeting.id = l.from_page_id
+ THEN l.to_page_id ELSE l.from_page_id END
WHERE l.link_type = 'attended'
AND ${MEETING_EDGE_PREDICATE}
- AND pf.deleted_at IS NULL
- AND pt.deleted_at IS NULL`,
+ AND attendee.type = 'person'
+ AND meeting.deleted_at IS NULL
+ AND attendee.deleted_at IS NULL`,
);
const attendeesByMeeting = new Map<string, AttendedEdgeRow[]>();
for (const e of attendedEdges) {
- const key = `${e.from_source_id}::${e.from_slug}`;
+ const key = `${e.meeting_source_id}::${e.meeting_slug}`;
if (!meetingKeys.has(key)) continue;
const list = attendeesByMeeting.get(key);
if (list) list.push(e);
@@ -201,10 +203,10 @@ export async function extractTimelineFromMeetings(
const attendees = attendeesByMeeting.get(meetingKey) ?? [];
const targets = new Map<string, { slug: string; source_id: string }>();
for (const e of attendees) {
- if (!allowCrossSource && e.to_source_id !== meeting.source_id) continue;
- targets.set(`${e.to_source_id}::${e.to_slug}`, {
- slug: e.to_slug,
- source_id: e.to_source_id,
+ if (!allowCrossSource && e.attendee_source_id !== meeting.source_id) continue;
+ targets.set(`${e.attendee_source_id}::${e.attendee_slug}`, {
+ slug: e.attendee_slug,
+ source_id: e.attendee_source_id,
});
}
diff --git a/src/core/link-extraction.ts b/src/core/link-extraction.ts
index fca894a565..5123938eb7 100644
--- a/src/core/link-extraction.ts
+++ b/src/core/link-extraction.ts
@@ -11,10 +11,11 @@
* methods. Auto-link config is the one impure helper (reads engine.getConfig).
*/
-import type { BrainEngine } from './engine.ts';
+import type { BrainEngine, LinkBatchInput } from './engine.ts';
import type { PageType, EffectiveDateSource } from './types.ts';
import { ensureWellFormed } from './text-safe.ts';
import { stripCodeBlocks } from './markdown-code.ts';
+import { isValidSourceId } from './source-id.ts';
import { parseInlineCitationTimelineEntries } from './timeline-citations.ts';
import { slugifyPath, slugifySegment } from './sync.ts';
import { SLUG_WORD_CHARS, SLUG_VARIATION_SELECTORS_RE } from './cjk.ts';
@@ -188,7 +189,7 @@ const ANY_DIR_SEGMENT = '[a-z0-9][a-z0-9_-]*';
* are dropped by the callers' existence checks, exactly as before.
*/
const ENTITY_REF_RE = new RegExp(
- `\\[([^\\]]+)\\]\\((?:\\.\\.\\/)*(${ANY_DIR_SEGMENT}\\/[^)\\s#]+?)(?:\\.md)?(?:#[^)]*)?\\)`,
+ `\\[([^\\]]+)\\]\\((?:/|(?:\\.\\.\\/)*)(${ANY_DIR_SEGMENT}\\/[^)\\s#]+?)(?:\\.md)?(?:#[^)]*)?\\)`,
'g',
);
@@ -557,6 +558,7 @@ function resolveRelativeSlug(pageSlug: string, ref: EntityRef): string {
// ─── Link candidates (richer than EntityRef) ────────────────────
export interface LinkCandidate {
+ canonicalAttendance?: boolean;
/**
* Source page slug for the edge. When omitted, callers default to
* "the page being written" (operations.ts runAutoLink) or "the page
@@ -599,6 +601,7 @@ export interface LinkCandidate {
export interface PageLinksResult {
candidates: LinkCandidate[];
unresolved: UnresolvedFrontmatterRef[];
+ attendanceComplete: boolean;
}
/**
@@ -625,7 +628,8 @@ export async function extractPageLinks(
pageType: PageType,
resolver: SlugResolver,
opts: { globalBasename?: boolean; skipFrontmatter?: boolean; pack?: LinkExtractionPack | null;
- targetType?: (slug: string, sourceId?: string) => string | undefined } = {},
+ targetType?: (slug: string, sourceId?: string) => string | undefined;
+ onResolvedFrontmatterTarget?: (slug: string) => void } = {},
): Promise<PageLinksResult> {
const candidates: LinkCandidate[] = [];
@@ -644,21 +648,38 @@ export async function extractPageLinks(
// `content` (stripCodeBlocks and the wikilink mask are length-preserving,
// so indices line up); idx < 0 / undefined keeps the old behavior.
const suppressedRanges = rolePriorSuppressedRanges(stripCodeBlocks(content));
- const typeFor = (ctx: string, targetSlug: string, idx?: number, sourceId?: string): string => {
+ const attendanceRanges = attendanceEvidenceRanges(content);
+ const attendancePending = new Set<number>();
+ const attendanceResolved = new Set<number>();
+ const attendanceAmbiguous = new Set<number>();
+ const typeFor = (ctx: string, targetSlug: string, idx?: number, sourceId?: string, bodyReference = true): Pick<LinkCandidate, 'linkType' | 'canonicalAttendance'> => {
const targetType = opts.targetType?.(targetSlug, sourceId);
if (pack) {
const packVerb = inferLinkTypeFromPack(pack, pageType as string, ctx, packBudget, targetType);
if (packVerb) {
if (packVerb === 'attended' && pageType === 'meeting'
- && (opts.targetType ? targetType !== 'person' : !targetSlug.startsWith('people/'))) return 'mentions';
- return packVerb;
+ && (opts.targetType ? targetType !== 'person' : !targetSlug.startsWith('people/'))) return { linkType: 'mentions' };
+ return { linkType: packVerb };
}
}
+ if (pageType === 'meeting') {
+ if (!bodyReference) return { linkType: 'mentions' };
+ if (pack?.link_types.some(lt => lt.name === 'attended' && (lt.inference?.page_type || lt.inference?.target_type))) return { linkType: 'mentions' };
+ if (idx !== undefined && hasAttendanceEvidence(attendanceRanges, idx)) {
+ attendancePending.add(idx);
+ if (!opts.targetType || targetType !== undefined) attendanceResolved.add(idx);
+ }
+ if ((opts.targetType ? targetType === 'person' : targetSlug.startsWith('people/'))
+ && idx !== undefined && hasAttendanceEvidence(attendanceRanges, idx)) {
+ return { linkType: 'attended', canonicalAttendance: true };
+ }
+ return { linkType: 'mentions' };
+ }
const suppressPrior = idx !== undefined && idx >= 0 && inSuppressedRange(suppressedRanges, idx);
const legacy = inferLinkType(pageType, ctx, suppressPrior ? undefined : content, targetSlug,
opts.targetType ? targetType ?? null : undefined);
- if (pack?.link_types.some(lt => lt.name === legacy && (lt.inference?.page_type || lt.inference?.target_type))) return 'mentions';
- return legacy;
+ if (pack?.link_types.some(lt => lt.name === legacy && (lt.inference?.page_type || lt.inference?.target_type))) return { linkType: 'mentions' };
+ return { linkType: legacy };
};
// 1. Markdown entity refs.
@@ -686,7 +707,7 @@ export async function extractPageLinks(
const context = idx >= 0 ? excerpt(content, idx, 240) : ref.name;
candidates.push({
targetSlug: target,
- linkType: typeFor(context, target, idx),
+ ...typeFor(context, target, idx),
context,
linkSource: 'markdown',
});
@@ -716,7 +737,7 @@ export async function extractPageLinks(
const litContext = litIdx >= 0 ? excerpt(content, litIdx, 240) : ref.name;
candidates.push({
targetSlug: ref.slug,
- linkType: typeFor(litContext, ref.slug, litIdx),
+ ...typeFor(litContext, ref.slug, litIdx),
context: litContext,
linkSource: 'markdown',
});
@@ -736,21 +757,10 @@ export async function extractPageLinks(
// flag off. Exact slugs only; downstream existence checks drop the miss.
const bareDirect = new Set<string>();
if (slashIdx === -1) {
- for (const form of new Set([slugifyPath(ref.slug), normalizeBasename(ref.slug)])) {
- // Self-loop guard: `[[own-basename]]` on the root page itself.
- if (!form || form === slug) continue;
- bareDirect.add(form);
- const litIdx = ref.index ?? content.indexOf(ref.slug);
- const litContext = litIdx >= 0 ? excerpt(content, litIdx, 240) : ref.name;
- candidates.push({
- targetSlug: form,
- linkType: typeFor(litContext, form, litIdx),
- context: litContext,
- linkSource: 'markdown',
- });
+ for (const form of [slugifyPath(ref.slug), normalizeBasename(ref.slug)]) {
+ if (form && form !== slug) bareDirect.add(form);
}
}
- if (typeof resolver.resolveBasenameMatches !== 'function') continue;
// Issue #972 (codex): resolve by the wikilink TARGET (ref.slug — the
// text inside `[[...]]` before any `|`), NOT the display alias
// (ref.name = match[2]). `[[struktura|the project]]` must resolve
@@ -768,27 +778,37 @@ export async function extractPageLinks(
// above already covers it (#2576), so keeping it would double-emit.
let matches: string[] = [];
const slugified = ref.slug.includes('/') ? slugifyPath(ref.slug) : '';
- if (slugified.includes('/')) {
+ if (resolver.resolveBasenameMatches && slugified.includes('/')) {
const tail = slugified.slice(slugified.lastIndexOf('/') + 1);
matches = (await resolver.resolveBasenameMatches(tail))
.filter(m => m !== ref.slug && (m === slugified || m.endsWith(`/${slugified}`)));
- } else if (opts.globalBasename) {
+ } else if (resolver.resolveBasenameMatches && opts.globalBasename) {
// #4062: exclude the root-exact slugified form — the direct typed
// candidate above already covers it (same rule the dir-qualified
// branch applies to its raw literal). Keeping it would double-emit.
matches = (await resolver.resolveBasenameMatches(ref.slug))
.filter(m => !bareDirect.has(m));
}
- if (matches.length === 0) continue;
- const idx = content.indexOf(ref.slug);
+ matches = matches.filter(matched => matched !== slug);
+ const idx = ref.index ?? content.indexOf(ref.slug);
const context = idx >= 0 ? excerpt(content, idx, 240) : ref.name;
+ const targets = [...new Set([...bareDirect, ...matches])];
+ const personTargets = targets.filter(target => opts.targetType
+ ? opts.targetType(target) === 'person' : target.startsWith('people/'));
+ const uniquePerson = personTargets.length === 1;
+ if (pageType === 'meeting' && opts.targetType && !uniquePerson
+ && targets.filter(target => opts.targetType!(target) !== undefined).length > 1) attendanceAmbiguous.add(idx);
+ for (const target of bareDirect) {
+ const inferred = typeFor(context, target, idx);
+ candidates.push({ targetSlug: target,
+ ...(inferred.canonicalAttendance && !uniquePerson ? { linkType: 'mentions' } : inferred),
+ context, linkSource: 'markdown' });
+ }
for (const matched of matches) {
- // Issue #972 (codex [P2]): a basename `[[own-tail]]` on its own page
- // resolves back to itself — drop the self-loop.
- if (matched === slug) continue;
+ const inferred = typeFor(context, matched, idx);
candidates.push({
targetSlug: matched,
- linkType: WIKILINK_BASENAME_LINK_TYPE,
+ ...(inferred.canonicalAttendance && uniquePerson ? inferred : { linkType: WIKILINK_BASENAME_LINK_TYPE }),
context,
linkSource: 'wikilink-resolved',
});
@@ -814,7 +834,7 @@ export async function extractPageLinks(
candidates.push({
targetSlug,
targetSourceId: ref.sourceId ?? undefined,
- linkType: typeFor(context, targetSlug, idx, ref.sourceId ?? undefined),
+ ...typeFor(context, targetSlug, idx, ref.sourceId ?? undefined),
context,
linkSource: 'markdown',
});
@@ -846,9 +866,10 @@ export async function extractPageLinks(
// #2576: never emit a self-loop for a page mentioning its own slug.
if (m[1] === slug) continue;
const context = excerpt(strippedContent, m.index, 240);
+ const inferred = typeFor(context, m[1], m.index, undefined, false);
candidates.push({
targetSlug: m[1],
- linkType: typeFor(context, m[1], m.index),
+ ...(inferred.canonicalAttendance ? { linkType: 'mentions' } : inferred),
context,
linkSource: 'markdown',
});
@@ -863,10 +884,13 @@ export async function extractPageLinks(
// synthetic `nullResolver`; that pattern broke once the bare-wikilink
// path needed `resolveBasenameMatches` on the real resolver.
let fmUnresolved: UnresolvedFrontmatterRef[] = [];
+ let frontmatterAttendanceComplete = true;
if (!opts.skipFrontmatter) {
- const fm = await extractFrontmatterLinks(slug, pageType, frontmatter, resolver, opts.globalBasename, pack, opts.targetType);
+ const fm = await extractFrontmatterLinks(slug, pageType, frontmatter, resolver, opts.globalBasename, pack, opts.targetType,
+ opts.onResolvedFrontmatterTarget);
candidates.push(...fm.candidates);
fmUnresolved = fm.unresolved;
+ frontmatterAttendanceComplete = fm.attendanceComplete;
}
// Within-page dedup: same (fromSlug, targetSlug, linkType, linkSource)
@@ -880,12 +904,156 @@ export async function extractPageLinks(
const seen = new Set<string>();
const result: LinkCandidate[] = [];
for (const c of candidates) {
- const key = `${c.fromSlug ?? ''}\u0000${c.targetSourceId ?? ''}\u0000${c.targetSlug}\u0000${c.linkType}\u0000${c.linkSource ?? ''}`;
+ const key = `${c.fromSlug ?? ''}\u0000${c.targetSourceId ?? ''}\u0000${c.targetSlug}\u0000${c.linkType}\u0000${c.linkSource ?? ''}\u0000${c.canonicalAttendance ?? false}`;
if (seen.has(key)) continue;
seen.add(key);
result.push(c);
}
- return { candidates: result, unresolved: fmUnresolved };
+ return { candidates: result, unresolved: fmUnresolved,
+ attendanceComplete: [...attendancePending].every(index => attendanceResolved.has(index) && !attendanceAmbiguous.has(index))
+ && frontmatterAttendanceComplete };
+}
+
+export function resolvedLinkCandidate(candidate: LinkCandidate, originSlug: string, originSourceId: string,
+ resolved: { fromSlug: string; fromSourceId: string; toSourceId: string }): LinkBatchInput {
+ const row = {
+ from_slug: resolved.fromSlug, to_slug: candidate.targetSlug,
+ from_source_id: resolved.fromSourceId, to_source_id: resolved.toSourceId,
+ link_type: candidate.linkType, context: candidate.context, link_source: candidate.linkSource,
+ origin_slug: candidate.canonicalAttendance ? originSlug : candidate.originSlug,
+ origin_source_id: originSourceId, origin_field: candidate.originField,
+ };
+ return candidate.canonicalAttendance ? orientCanonicalAttendance(row) : row;
+}
+
+export function orientCanonicalAttendance<T extends LinkBatchInput>(row: T): T {
+ return { ...row, from_slug: row.to_slug, to_slug: row.from_slug,
+ from_source_id: row.to_source_id, to_source_id: row.from_source_id,
+ origin_slug: row.from_slug, origin_source_id: row.from_source_id };
+}
+
+/**
+ * Extract markdown links to .md files (relative paths only).
+ *
+ * Handles two syntaxes:
+ * 1. Standard markdown: [text](relative/path.md)
+ * 2. Wikilinks: [[relative/path]] or [[relative/path|Display Text]]
+ *
+ * Both are resolved relative to the file that contains them. External URLs
+ * (containing ://) are always skipped. Section anchors (#heading) are stripped
+ * from both (#4995); for wikilinks, the .md suffix is added if absent.
+ */
+export function extractMarkdownLinks(content: string, positions = false): { name: string; relTarget: string; index?: number }[] {
+ const results: { name: string; relTarget: string; index?: number }[] = [];
+
+ const mdPattern = /\[([^\]]+)\]\(([^)#]+\.md)(?:#[^)]*)?\)/g;
+ let match;
+ while ((match = mdPattern.exec(content)) !== null) {
+ let target = match[2];
+ if (target.includes('://')) continue;
+ // Obsidian's useMarkdownLinks mode percent-encodes link targets
+ // (`[Alice](People/Alice%20Chen.md)`). Decode before resolution; a
+ // malformed escape keeps the raw text rather than throwing.
+ if (target.includes('%')) {
+ try { target = decodeURIComponent(target); } catch { /* keep raw */ }
+ }
+ results.push({ name: match[1], relTarget: target, ...(positions ? { index: match.index } : {}) });
+ }
+
+ const wikiPattern = /\[\[([^|\]]+?)(?:\|[^\]]*?)?\]\]/g;
+ while ((match = wikiPattern.exec(content)) !== null) {
+ const rawPath = match[1].trim();
+ if (rawPath.includes('://')) continue;
+ const hashIdx = rawPath.indexOf('#');
+ const pagePath = hashIdx >= 0 ? rawPath.slice(0, hashIdx) : rawPath;
+ if (!pagePath) continue;
+ const relTarget = pagePath.endsWith('.md') ? pagePath : pagePath + '.md';
+ const pipeIdx = match[0].indexOf('|');
+ const displayName = pipeIdx >= 0 ? match[0].slice(pipeIdx + 1, -2).trim() : rawPath;
+ results.push({ name: displayName, relTarget, ...(positions ? { index: match.index } : {}) });
+ }
+
+ return results;
+}
+
+export function attendanceEvidenceRanges(content: string): Array<[number, number]> {
+ const comments: Array<[number, number]> = [];
+ let visible = '', afterComment = 0;
+ const masked = stripCodeBlocks(content, { onHtmlComment(start, end) {
+ comments.push([start, end]);
+ visible += content.slice(afterComment, start) + content.slice(start, end).replace(/[^\r\n]/g, ' ');
+ afterComment = end;
+ } });
+ visible += content.slice(afterComment);
+ const lines: Array<{ text: string; start: number; end: number }> = [];
+ let start = 0;
+ for (const text of visible.split('\n')) {
+ lines.push({ text, start, end: start + text.length });
+ start += text.length + 1;
+ }
+ const list = (text: string) => {
+ let count = 0;
+ const rest = text.replace(/\[\[[^\[\]\n]+\]\]|\[[^\[\]\n]+\]\([^\s()\n]+\)/g, () => { count++; return ''; });
+ return count > 0 && /^[\s,;.&]*$/.test(rest);
+ };
+ const ranges: Array<[number, number]> = [];
+ let section: { valid: boolean; entries: Array<[number, number]> } | undefined;
+ const finishSection = () => {
+ if (section?.valid) ranges.push(...section.entries);
+ section = undefined;
+ };
+ let frontmatter = lines[0]?.text.trim() === '---';
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i];
+ if (frontmatter) {
+ if (i > 0 && /^(?:---|\.\.\.)\s*$/.test(line.text)) frontmatter = false;
+ continue;
+ }
+ if (!masked.slice(line.start, line.end).trim()) {
+ if (section && line.text.trim()) section.valid = false;
+ continue;
+ }
+ if (/^#{1,2}[ \t]/.test(line.text)) finishSection();
+ if (/^##[ \t]+Attendees[ \t]*\r?$/i.test(line.text)) {
+ section = { valid: true, entries: [] };
+ continue;
+ }
+ if (section) {
+ if (!line.text.trim()) continue;
+ if (/^(?: {4}|\t)/.test(line.text)
+ || !list(line.text.replace(/^[ \t]*[-*+][ \t]+/, ''))) section.valid = false;
+ section.entries.push([line.start, line.end]);
+ continue;
+ }
+ const inline = /^Attendees:[ \t]*(.*)$/i.exec(line.text);
+ if (inline && list(inline[1])) ranges.push([line.start, line.end]);
+ }
+ finishSection();
+ const admitted: Array<[number, number]> = [];
+ let commentIndex = 0;
+ for (const [start, end] of ranges) {
+ let cursor = start;
+ while (commentIndex < comments.length && comments[commentIndex][1] <= start) commentIndex++;
+ for (let i = commentIndex; i < comments.length && comments[i][0] < end; i++) {
+ if (comments[i][0] > cursor) admitted.push([cursor, comments[i][0]]);
+ cursor = Math.max(cursor, comments[i][1]);
+ }
+ if (cursor < end) admitted.push([cursor, end]);
+ }
+ return admitted;
+}
+
+export function hasAttendanceEvidence(ranges: ReadonlyArray<readonly [number, number]>, index: number): boolean {
+ let low = 0;
+ let high = ranges.length - 1;
+ while (low <= high) {
+ const middle = Math.floor((low + high) / 2);
+ const [start, end] = ranges[middle];
+ if (index < start) high = middle - 1;
+ else if (index >= end) low = middle + 1;
+ else return true;
+ }
+ return false;
}
/**
@@ -1174,6 +1342,7 @@ export const FRONTMATTER_LINK_MAP: FrontmatterFieldMapping[] = [
// ─── Slug resolver ──────────────────────────────────────────────
export interface SlugResolver {
+ resolveAttendance?(name: string, dirHint?: string | string[]): Promise<string | null>;
/**
* Resolve a display name to a canonical slug.
* Returns null when no match meets confidence threshold — callers should
@@ -1276,6 +1445,8 @@ export function makeResolver(
opts: { mode: 'batch' | 'live'; sourceId?: string } = { mode: 'live' },
): SlugResolver {
const cache = new Map<string, string | null>();
+ const attendanceCache = new Map<string, string | null>();
+ const attendanceCacheLimit = 256;
// Issue #972: lazy-built basename → slug[] index for global-basename
// resolution. Built on first call to `resolveBasenameMatches`; reused
@@ -1311,6 +1482,29 @@ export function makeResolver(
}
return {
+ async resolveAttendance(name: string, dirHint?: string | string[]): Promise<string | null> {
+ let value = name.trim();
+ const colon = value.indexOf(':');
+ if (colon !== -1 && isValidSourceId(value.slice(0, colon))) {
+ if (value.slice(0, colon) !== (opts.sourceId ?? 'default')) return null;
+ value = value.slice(colon + 1);
+ }
+ const hints = Array.isArray(dirHint) ? dirHint : dirHint ? [dirHint] : [];
+ const cacheKey = JSON.stringify([opts.sourceId ?? 'default', value, hints]);
+ if (attendanceCache.has(cacheKey)) return attendanceCache.get(cacheKey)!;
+ const slugs = value.includes('/') ? [value] : [...new Set(hints.flatMap(hint =>
+ [normalizeBasename(value), slugifySegment(value)].map(form => `${hint}/${form}`)))];
+ const matches = await engine.executeRaw<{ slug: string }>(`SELECT slug FROM pages
+ WHERE source_id=$1 AND deleted_at IS NULL AND type='person'
+ AND (slug=ANY($2::text[]) OR lower(title)=lower($3)
+ OR EXISTS (SELECT 1 FROM jsonb_array_elements_text(CASE WHEN jsonb_typeof(frontmatter->'aliases')='array'
+ THEN frontmatter->'aliases' ELSE '[]'::jsonb END) alias WHERE lower(alias)=lower($3))) LIMIT 2`,
+ [opts.sourceId ?? 'default', slugs, value]);
+ const resolved = matches.length === 1 ? matches[0].slug : null;
+ if (attendanceCache.size >= attendanceCacheLimit) attendanceCache.clear();
+ attendanceCache.set(cacheKey, resolved);
+ return resolved;
+ },
async resolveBasenameMatches(name: string): Promise<string[]> {
// Issue #972 (codex [P2] DRY): shared query so resolver + FS + doctor
// return the same matches in the same stable order.
@@ -1439,6 +1633,7 @@ export interface UnresolvedFrontmatterRef {
export interface FrontmatterExtractResult {
candidates: LinkCandidate[];
unresolved: UnresolvedFrontmatterRef[];
+ attendanceComplete: boolean;
}
/**
@@ -1457,9 +1652,11 @@ export async function extractFrontmatterLinks(
globalBasename = false,
pack?: LinkExtractionPack | null,
targetType?: (slug: string) => string | undefined,
+ onResolvedTarget?: (slug: string) => void,
): Promise<FrontmatterExtractResult> {
const candidates: LinkCandidate[] = [];
const unresolved: UnresolvedFrontmatterRef[] = [];
+ let attendanceComplete = true;
const packMappings: FrontmatterFieldMapping[] = [];
if (pack && pack.frontmatter_links.length > 0) {
@@ -1516,8 +1713,11 @@ export async function extractFrontmatterLinks(
// through unchanged; the original `name` is preserved for the
// unresolved report and edge context.
const linkTarget = unwrapWikilink(name);
- let resolved = await resolver.resolve(linkTarget, mapping.dirHint);
- if (!resolved && globalBasename && typeof resolver.resolveBasenameMatches === 'function') {
+ const canonicalAttendance = mapping.type === 'attended' && mapping.direction === 'incoming';
+ let resolved = await (canonicalAttendance && resolver.resolveAttendance
+ ? resolver.resolveAttendance(linkTarget, mapping.dirHint) : resolver.resolve(linkTarget, mapping.dirHint));
+ if (!resolved && globalBasename && !(canonicalAttendance && resolver.resolveAttendance)
+ && typeof resolver.resolveBasenameMatches === 'function') {
// Issue #972 follow-up: extend global_basename resolution to
// frontmatter link fields. resolve() can't reach a bare-title
// wikilink value (e.g. `sources: "[[2025-12-25_mentor-extraction]]"`)
@@ -1533,12 +1733,16 @@ export async function extractFrontmatterLinks(
if (matches.length === 1) resolved = matches[0];
}
if (!resolved) {
+ if (mapping.type === 'attended') attendanceComplete = false;
unresolved.push({ field, name });
continue;
}
+ onResolvedTarget?.(resolved);
const expectedType = packMappings.includes(mapping)
- ? pack?.link_types.find(lt => lt.name === mapping.type)?.inference?.target_type : undefined;
- if (expectedType && targetType?.(resolved) !== expectedType) {
+ ? pack?.link_types.find(lt => lt.name === mapping.type)?.inference?.target_type
+ : mapping.type === 'attended' && mapping.direction === 'incoming' ? 'person' : undefined;
+ if (expectedType && (targetType || packMappings.includes(mapping)) && targetType?.(resolved) !== expectedType) {
+ if (targetType?.(resolved) === undefined && mapping.type === 'attended') attendanceComplete = false;
unresolved.push({ field, name, reason: 'target_type_mismatch' });
continue;
}
@@ -1563,7 +1767,7 @@ export async function extractFrontmatterLinks(
}
}
- return { candidates, unresolved };
+ return { candidates, unresolved, attendanceComplete };
}
// ─── Timeline parsing ───────────────────────────────────────────
diff --git a/src/core/link-reconciliation.ts b/src/core/link-reconciliation.ts
index bafaa37ec7..0cb4de03a3 100644
--- a/src/core/link-reconciliation.ts
+++ b/src/core/link-reconciliation.ts
@@ -1,6 +1,8 @@
import type { BrainEngine, LinkBatchInput } from './engine.ts';
-import { extractPageLinks, unwrapWikilink,
- type LinkExtractionPack, type SlugResolver } from './link-extraction.ts';
+import { extractPageLinks, unwrapWikilink, resolvedLinkCandidate,
+ isCrossSourceLinksEnabled, type LinkCandidate, type LinkExtractionPack, type SlugResolver } from './link-extraction.ts';
+import { fetchSource, isSourceFederated } from './sources-load.ts';
+import { parseMarkdown } from './markdown.ts';
import { isValidSourceId } from './source-id.ts';
import { buildSourceLocalReferenceIndex } from './source-local-reference-index.ts';
@@ -21,6 +23,7 @@ export async function loadLinkPageMetadata(engine: Pick<BrainEngine, 'executeRaw
export function makeIndexedLinkResolver(pages: readonly LinkPageMetadata[], sourceId: string): SlugResolver {
const index = buildSourceLocalReferenceIndex(pages.filter(page => page.source_id === sourceId));
return {
+ async resolveAttendance(name, dirHint) { return this.resolve(name, dirHint); },
async resolve(name, dirHint) {
if (!name) return null;
let value = name.trim();
@@ -89,6 +92,10 @@ export async function reconcileSourceLinks(
result.unresolved.push({ originSlug: page.slug, field: ref.field, target: ref.name,
reason: ref.reason ?? (foreign ? 'cross_source' : 'missing_target') });
}
+ if (!extracted.attendanceComplete) {
+ result.failures.push({ originSlug, code: 'attendance_resolution_incomplete' });
+ return result;
+ }
const rows: LinkBatchInput[] = [];
for (const candidate of extracted.candidates) {
const from = candidate.fromSlug ?? page.slug;
@@ -100,9 +107,8 @@ export async function reconcileSourceLinks(
result.unresolved.push({ originSlug, target: candidate.targetSlug, reason: 'missing_target' });
continue;
}
- rows.push({ from_slug: from, to_slug: candidate.targetSlug, link_type: candidate.linkType,
- context: candidate.context, link_source: candidate.linkSource, origin_slug: page.slug,
- origin_field: candidate.originField, from_source_id: sourceId, to_source_id: sourceId, origin_source_id: sourceId });
+ rows.push(resolvedLinkCandidate(candidate, page.slug, sourceId,
+ { fromSlug: from, fromSourceId: sourceId, toSourceId: sourceId }));
}
const written = await engine.replaceDerivedLinks({ slug: page.slug, sourceId,
expectedRevision: snapshot.revision, sourceIncarnation }, rows, { expectedEndpoints:
@@ -123,3 +129,230 @@ export async function reconcileSourceLinks(
return result;
}
}
+
+export async function replaceFileLinks(engine: BrainEngine, slug: string, sourceId: string,
+ links: LinkBatchInput[], includeFrontmatter: boolean,
+ snapshot: NonNullable<Awaited<ReturnType<BrainEngine['readPageSnapshot']>>>,
+ ownership: Awaited<ReturnType<typeof fileLinkOwnership>>, content: string,
+ opts: { pack: LinkExtractionPack | null; globalBasename: boolean }): Promise<number | null | undefined> {
+ const { metadata, resolver, resolve } = ownership;
+ const parsed = parseMarkdown(content, `${slug}.md`, { activePack: opts.pack?.page_types ? { page_types: opts.pack.page_types } : undefined });
+ const extracted = await extractPageLinks(slug, content, parsed.frontmatter, snapshot.page.type, resolver,
+ { ...opts, skipFrontmatter: !includeFrontmatter, targetType: (targetSlug, targetSourceId) => {
+ const result = resolve(slug, { targetSlug, targetSourceId, linkType: '', context: '' });
+ return result.ok ? metadata.get(`${result.toSourceId}\0${targetSlug}`)?.type : undefined;
+ } });
+ if (!extracted.attendanceComplete) return null;
+ const attendance = extracted.candidates.filter(candidate => candidate.canonicalAttendance
+ || (candidate.linkType === 'attended' && candidate.fromSlug && candidate.targetSlug === slug));
+ if (!ownership.origins.has(slug) && !attendance.length
+ && !links.some(link => link.link_type === 'attended' && link.to_slug === slug && link.origin_slug === slug)) return undefined;
+ const rows: LinkBatchInput[] = links.filter(link => !(link.link_type === 'attended' && link.to_slug === slug && link.origin_slug === slug)
+ && metadata.has(`${sourceId}\0${link.from_slug}`)
+ && metadata.has(`${sourceId}\0${link.to_slug}`)).map(link => ({ ...link,
+ from_source_id: sourceId, to_source_id: sourceId, origin_source_id: sourceId }));
+ for (const candidate of attendance) {
+ const resolved = resolve(slug, candidate);
+ if (!resolved.ok) return null;
+ rows.push(resolvedLinkCandidate(candidate, slug, sourceId, resolved));
+ }
+ const result = await engine.replaceDerivedLinks({ slug, sourceId, expectedRevision: snapshot.revision,
+ sourceIncarnation: snapshot.sourceIncarnation }, rows, { includeFrontmatter, preserveExisting: true,
+ includeLegacyNullProducer: false,
+ expectedEndpoints: capturedLinkEndpoints(rows, metadata) });
+ 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]));
+ const resolver = makeIndexedLinkResolver(pages, sourceId);
+ const { allSlugs, slugToSources } = indexLinkSources(pages);
+ const policy = await loadLinkSourcePolicy(engine, sourceId);
+ const resolve = (slug: string, candidate: LinkCandidate) => resolveCandidateSources(candidate, slug, sourceId,
+ allSlugs, slugToSources, policy.allowCrossSource, policy);
+ const origins = await engine.executeRaw<{ slug: string }>(`SELECT DISTINCT o.slug FROM links l
+ JOIN pages o ON o.id=l.origin_page_id WHERE o.source_id=$1 AND l.link_source IN ('markdown','wikilink-resolved','frontmatter')
+ AND l.link_type='attended' AND l.to_page_id=l.origin_page_id`, [sourceId]);
+ return { metadata, resolver, resolve, origins: new Set(origins.map(row => row.slug)) };
+}
+
+export function indexLinkSources(pages: ReadonlyArray<{ slug: string; source_id: string }>) {
+ const allSlugs = new Set<string>();
+ const slugToSources = new Map<string, string[]>();
+ for (const page of pages) {
+ allSlugs.add(page.slug);
+ const sources = slugToSources.get(page.slug) ?? [];
+ sources.push(page.source_id);
+ slugToSources.set(page.slug, sources);
+ }
+ return { allSlugs, slugToSources };
+}
+
+export async function loadLinkSourcePolicy(engine: BrainEngine, sourceId: string) {
+ const [source, crossSource, defaultSourceId] = await Promise.all([
+ fetchSource(engine, sourceId), isCrossSourceLinksEnabled(engine), resolveLinkFallbackDefault(engine),
+ ]);
+ return { allowCrossSource: source !== null && !source.archived && isSourceFederated(source.config), crossSource, defaultSourceId };
+}
+
+export function capturedLinkEndpoints(links: LinkBatchInput[], metadata: ReadonlyMap<string, Pick<LinkPageMetadata, 'slug' | 'source_id' | 'knowledge_revision'>>) {
+ const keys = new Set(links.flatMap(link => [
+ `${link.from_source_id ?? 'default'}\0${link.from_slug}`, `${link.to_source_id ?? 'default'}\0${link.to_slug}`,
+ ]));
+ return [...keys].map(key => {
+ const endpoint = metadata.get(key);
+ if (!endpoint) throw new Error('A derived link endpoint was not captured during type resolution');
+ return { slug: endpoint.slug, sourceId: endpoint.source_id, revision: endpoint.knowledge_revision };
+ });
+}
+
+/**
+ * v0.42.7 (#1696): pure cross-source resolution for one extracted link
+ * candidate. Validates both endpoints exist (else the batch JOIN drops the row),
+ * then picks from_source_id / to_source_id: prefer the origin page's source,
+ * fall back to 'default', else skip (never push a wrong-source edge). Shared
+ * by extractLinksFromDB and extractStaleFromDB so the F10 multi-source
+ * resolution and the source-isolation policy can't drift.
+ *
+ * v0.46.28.0 (#2589): the failure case now carries a `reason` instead of a
+ * bare `null`. A target that resolves via `global_basename` to a page that
+ * exists ONLY in a source other than the origin's or 'default' was
+ * indistinguishable from a genuinely-missing target — both silently dropped
+ * the candidate and both counted (misleadingly) as "target page doesn't
+ * exist". This stays default-deny by design: cross-source edges remain
+ * unwritten (source isolation — see CLAUDE.md), but callers can now
+ * attribute the drop correctly instead of reporting a wrong reason.
+ *
+ * #3478: only a federated origin source may fall back to 'default'; when
+ * `allowCrossSource` is false both endpoints must live in the page's own
+ * source, else skip with reason 'cross_source' (never push a wrong-source
+ * edge).
+ *
+ * #3908: `opts.crossSource` (the `link_resolution.cross_source` config flag)
+ * is the explicit operator opt-in — it supersedes the ambient federation
+ * gate, which only exists to stop DEFAULT-ON silent cross-source regrowth.
+ * With it on, a cross-source-only candidate resolves with the
+ * lexicographically smallest matching source (deterministic, so repeated
+ * extracts and both engines converge on the same edge under the
+ * (source_id, slug) composite key) instead of dropping with 'cross_source'.
+ *
+ * #4611: the fallback lane compares against `opts.defaultSourceId` (the
+ * configured `sources.default`, resolved once per run by the callers via
+ * resolveLinkFallbackDefault) instead of the LITERAL string 'default'.
+ * Renaming the brain's default source no longer silently kills the
+ * cross-source fallback. Omitted → 'default' (back-compat).
+ */
+export type CandidateSourceResolution =
+ | { ok: true; fromSlug: string; fromSourceId: string; toSourceId: string }
+ | { ok: false; reason: 'missing_target' | 'missing_from' | 'cross_source' };
+
+/**
+ * #4611: resolve the source id the cross-source link fallback compares
+ * against. Reads the operator-configured `sources.default` (same key the
+ * write-routing ladder in source-resolver.ts tier 5 reads), silently
+ * falling back to the seeded literal 'default' on unset/invalid/config
+ * errors — extraction must never fail on a bad config row.
+ */
+export async function resolveLinkFallbackDefault(
+ engine: Pick<BrainEngine, 'getConfig'>,
+): Promise<string> {
+ try {
+ const v = await engine.getConfig('sources.default');
+ if (v && isValidSourceId(v)) return v;
+ } catch {
+ // Best-effort read; the seeded literal below is the safe terminal.
+ }
+ return 'default';
+}
+
+export function resolveCandidateSources(
+ c: LinkCandidate,
+ pageSlug: string,
+ pageSourceId: string,
+ allSlugs: Set<string>,
+ slugToSources: Map<string, string[]>,
+ allowCrossSource: boolean,
+ opts: { crossSource?: boolean; defaultSourceId?: string } = {},
+): CandidateSourceResolution {
+ const fromSlug = c.fromSlug ?? pageSlug;
+ if (!allSlugs.has(c.targetSlug)) return { ok: false, reason: 'missing_target' };
+ if (!allSlugs.has(fromSlug)) return { ok: false, reason: 'missing_from' };
+ const fromSources = slugToSources.get(fromSlug) ?? [];
+ const targetSources = slugToSources.get(c.targetSlug) ?? [];
+ if (c.targetSourceId) {
+ if (!targetSources.includes(c.targetSourceId)) return { ok: false, reason: 'missing_target' };
+ if (!fromSources.includes(pageSourceId)) return { ok: false, reason: 'missing_from' };
+ if (c.targetSourceId !== pageSourceId && !allowCrossSource && !opts.crossSource) return { ok: false, reason: 'cross_source' };
+ return { ok: true, fromSlug, fromSourceId: pageSourceId, toSourceId: c.targetSourceId };
+ }
+ if (!allowCrossSource && !opts.crossSource) {
+ if (!fromSources.includes(pageSourceId) || !targetSources.includes(pageSourceId)) {
+ // #3478 isolation × #2589 counting: both endpoints exist but not in
+ // the origin's own source — a counted cross-source drop, never an edge.
+ return { ok: false, reason: 'cross_source' };
+ }
+ return { ok: true, fromSlug, fromSourceId: pageSourceId, toSourceId: pageSourceId };
+ }
+ // #4611: follow the CONFIGURED default source, not the literal 'default'.
+ const defaultSourceId = opts.defaultSourceId ?? 'default';
+ const fromSourceId = fromSources.includes(pageSourceId) ? pageSourceId
+ : (fromSources.includes(defaultSourceId) ? defaultSourceId : fromSources[0]);
+ let toSourceId: string;
+ if (targetSources.includes(fromSourceId)) {
+ toSourceId = fromSourceId;
+ } else if (targetSources.includes(defaultSourceId)) {
+ toSourceId = defaultSourceId;
+ } else if (targetSources.length > 0) {
+ // #2589: the target exists ONLY in other sources. Historically this was
+ // a silent null (indistinguishable from a missing endpoint — multi-source
+ // graphs went sparse with dead_links stuck at 0). Behind the opt-in
+ // `link_resolution.cross_source` flag the edge is allowed with a
+ // DETERMINISTIC pick (lexicographically smallest source, so repeated
+ // extracts and both engines converge on the same edge under the
+ // (source_id, slug) composite key); off, callers get the distinguishable
+ // 'cross_source' reason to COUNT the drop instead of burying it.
+ if (!opts.crossSource) return { ok: false, reason: 'cross_source' };
+ // Allocation-free deterministic min (bulk loops call this per candidate;
+ // in the motivating federated topology most candidates hit this branch).
+ let min = targetSources[0];
+ for (const s of targetSources) if (s < min) min = s;
+ toSourceId = min;
+ } else {
+ return { ok: false, reason: 'cross_source' };
+ }
+ return { ok: true, fromSlug, fromSourceId, toSourceId };
+}
+
+/**
+ * (slug, source_id) refs for EXACTLY the given slugs, chunked IN-list —
+ * the bounded replacement for listAllPageRefs in the sweep's pass 2. Same
+ * visibility as listAllPageRefs (deleted_at IS NULL).
+ */
+export async function lookupRefsForSlugs(
+ engine: BrainEngine,
+ slugs: string[],
+): Promise<{ allSlugs: Set<string>; slugToSources: Map<string, string[]>;
+ metadata: Array<{ slug: string; source_id: string; type: string; knowledge_revision: string }> }> {
+ const allSlugs = new Set<string>();
+ const slugToSources = new Map<string, string[]>();
+ const metadata: Array<{ slug: string; source_id: string; type: string; knowledge_revision: string }> = [];
+ const CHUNK = 200;
+ for (let i = 0; i < slugs.length; i += CHUNK) {
+ const chunk = slugs.slice(i, i + CHUNK);
+ const placeholders = chunk.map((_, j) => `$${j + 1}`).join(', ');
+ const rows = await engine.executeRaw<{ slug: string; source_id: string; type: string; knowledge_revision: string }>(
+ `SELECT slug, source_id, type, knowledge_revision FROM pages
+ WHERE deleted_at IS NULL AND slug IN (${placeholders})`,
+ chunk,
+ );
+ metadata.push(...rows);
+ for (const ref of rows) {
+ allSlugs.add(ref.slug);
+ const list = slugToSources.get(ref.slug) ?? [];
+ list.push(ref.source_id);
+ slugToSources.set(ref.slug, list);
+ }
+ }
+ return { allSlugs, slugToSources, metadata };
+}
diff --git a/src/core/markdown-code.ts b/src/core/markdown-code.ts
index eb8c724b40..0561af62ad 100644
--- a/src/core/markdown-code.ts
+++ b/src/core/markdown-code.ts
@@ -3,10 +3,32 @@
* replacing non-newline characters with spaces. Preserves CR/LF characters
* and UTF-16 code-unit offsets for callers that care about positions.
*/
-export function stripCodeBlocks(content: string): string {
+export function stripCodeBlocks(content: string, opts: { onHtmlComment?: (start: number, end: number) => void } = {}): string {
+ let fence: string | undefined;
let out = '';
let i = 0;
while (i < content.length) {
+ if (i === 0 || content[i - 1] === '\n') {
+ const newline = content.indexOf('\n', i);
+ const end = newline === -1 ? content.length : newline + 1;
+ const line = content.slice(i, end);
+ const marker = /^ {0,3}(`{3,}|~{3,})([^\n]*)/.exec(line);
+ if (fence || (marker && (marker[1][0] === '~' || !marker[2].includes('`')))) {
+ if (!fence) fence = marker![1];
+ else if (marker && marker[1][0] === fence[0] && marker[1].length >= fence.length && !marker[2].trim()) fence = undefined;
+ out += line.replace(/[^\r\n]/g, ' ');
+ i = end;
+ continue;
+ }
+ }
+ if (opts.onHtmlComment && content.startsWith('<!--', i)) {
+ const close = content.indexOf('-->', i + 4);
+ const end = close === -1 ? content.length : close + 3;
+ opts.onHtmlComment(i, end);
+ out += content.slice(i, end).replace(/[^\r\n]/g, ' ');
+ i = end;
+ continue;
+ }
if (content.startsWith('```', i)) {
const end = content.indexOf('```', i + 3);
const afterFence = end === -1 ? content.length : end + 3;
diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.ts
index a46b9aef16..6b20bdcbd3 100644
--- a/src/core/ops/facts.ts
+++ b/src/core/ops/facts.ts
@@ -17,7 +17,7 @@ import { readHolders } from './context.ts';
import type { Operation } from './contract.ts';
import { OperationError, verbError } from './contract.ts';
-import { federatedSearchScope, sourceScopeOpts, stampEvidenceSafe } from './context.ts';
+import { assertExplicitSourceLive, federatedSearchScope, parseSourceIdParam, sourceScopeOpts, stampEvidenceSafe } from './context.ts';
import { markKeywordHits } from '../search/evidence.ts';
import { hybridSearchCached, stampContentFlags } from '../search/hybrid.ts';
import { dedupResults } from '../search/dedup.ts';
@@ -184,6 +184,8 @@ const recall: Operation = {
entity: { type: 'string', description: 'Entity slug (canonical). Returns facts about this entity newest first.' },
query: { type: 'string', description: 'MEMORY_VERBS v1: free-text retrieval over pages (hybrid search arm). Response adds results[] (slug, title, chunk, evidence, create_safety, provenance). Combinable with entity (both arms run). Degrades to keyword-only search when no embedding provider is configured (search_degraded notes it; never an error).' },
budget_tokens: { type: 'number', description: 'MEMORY_VERBS v1: server-side token budget (char/4 estimate). Facts pack first, then results. Response adds budget_tokens, budget_used, dropped_count.' },
+ budget_policy: { type: 'string', enum: ['facts_first', 'query_first'], description: 'Optional packing order. facts_first preserves legacy behavior (default). query_first packs the ranked page prefix before facts only with a nonblank query and positive finite budget; a positive budget below one token keeps neither arm. No query or inactive budget preserves legacy behavior. Neither policy skips oversized items or truncates. Supplying this option adds budget_packing accounting. Keep fact-focused/entity-filtered questions on facts_first.' },
+ source_id: { type: 'string', description: 'Optional concrete source id for both facts and page results. Narrows the caller’s authorized scope, including an explicit default; a denied, missing, or archived source fails rather than widening. Omit to preserve the existing context/grant scope.' },
since: { type: 'string', description: 'ISO 8601 datetime or duration shorthand (e.g. "8 hours ago"). Filters the FACTS arm only, on event time (valid_from, falling back to created_at); composes with `entity` and `session_id`. An unparseable value is rejected (invalid_params).' },
session_id: { type: 'string', description: 'Source session id (e.g. topic-A). Returns facts captured in that session.' },
include_expired: { type: 'boolean', description: 'When true, include expired_at IS NOT NULL rows. Default false.' },
@@ -208,7 +210,22 @@ const recall: Operation = {
// source and merges newest-first; a single-source caller takes exactly
// the pre-v1 single-query path. A trusted-local `__all__` ({}) has no
// enumerable grant and keeps the resolved-scalar behavior.
- const scope = sourceScopeOpts(ctx);
+ let sourceIdParam: string | undefined;
+ let scope: ReturnType<typeof sourceScopeOpts>;
+ try {
+ sourceIdParam = parseSourceIdParam(p.source_id, 'recall');
+ scope = sourceIdParam === undefined ? sourceScopeOpts(ctx) : federatedSearchScope(ctx, sourceIdParam);
+ await assertExplicitSourceLive(ctx, sourceIdParam);
+ } catch (error) {
+ if (!(error instanceof OperationError) || p.source_id === undefined || p.source_id === null) throw error;
+ const code = error.code === 'permission_denied' ? 'scope_denied'
+ : error.code === 'unknown_source' ? 'not_found'
+ : error.code === 'invalid_params' ? 'invalid_params' : null;
+ if (code === null) throw error;
+ throw verbError(code, error.message,
+ error.suggestion ?? 'Choose a permitted active source, or omit source_id to use your existing scope.',
+ error.detail ?? error.code);
+ }
// Set-dedupe: a grant carrying a repeated id (or the scalar source again)
// must not fan out the same source twice into the merge.
const factSources: string[] = [...new Set(
@@ -393,7 +410,7 @@ const recall: Operation = {
// like search/query/get_page/list_pages/resolve_slugs. sourceScopeOpts
// alone pinned this arm to the scalar source, so a `federated: true`
// source was invisible to recall while visible to every sibling read op.
- const searchScope = federatedSearchScope(ctx);
+ const searchScope = federatedSearchScope(ctx, sourceIdParam);
// #4352 — recall's page-search arm enforces `visibility: private` for
// untrusted callers (matches the facts arms' world-only filter above).
const { resolveExcludePrivatePages } = await import('../search/private-visibility.ts');
@@ -419,15 +436,24 @@ const recall: Operation = {
bumpLastRetrievedAt(ctx.engine, searchResults.map(r => r.page_id));
}
- // ── MEMORY_VERBS v1 — server-side budget packing. Facts pack first (cheap,
- // high-precision one-liners, per-arm limit-capped so starvation is bounded),
- // then search results take the remainder. packToBudget treats budget<=0 as
- // a no-op, so an exhausted remainder must drop explicitly.
let packedFacts = rows;
let packedResults = searchResults;
let budgetUsed: number | undefined;
let droppedCount: number | undefined;
- if (budgetTokens !== null) {
+ const queryFirst = p.budget_policy === 'query_first' && queryText !== null && budgetTokens !== null;
+ if (queryFirst) {
+ const resultsPack = budgetTokens > 0
+ ? packToBudget(searchResults, resultTokens, budgetTokens)
+ : { items: [] as SearchResult[], meta: { used: 0, dropped: searchResults.length } };
+ packedResults = resultsPack.items;
+ const remaining = budgetTokens - resultsPack.meta.used;
+ const factsPack = remaining > 0
+ ? packToBudget(rows, r => estimateTokens(r.fact), remaining)
+ : { items: [] as FactRows, meta: { used: 0, dropped: rows.length } };
+ packedFacts = factsPack.items;
+ budgetUsed = resultsPack.meta.used + factsPack.meta.used;
+ droppedCount = resultsPack.meta.dropped + factsPack.meta.dropped;
+ } else if (budgetTokens !== null) {
const factsPack = packToBudget(rows, r => estimateTokens(r.fact), budgetTokens);
packedFacts = factsPack.items;
const remaining = budgetTokens - factsPack.meta.used;
@@ -440,6 +466,31 @@ const recall: Operation = {
droppedCount = factsPack.meta.dropped + resultsPack.meta.dropped;
}
+ const budgetPacking = p.budget_policy === 'facts_first' || p.budget_policy === 'query_first'
+ ? {
+ policy: queryFirst ? 'query_first' : 'facts_first',
+ applied: budgetTokens !== null && (queryFirst || (p.budget_policy === 'facts_first' && budgetTokens > 0)),
+ reason: p.budget_policy === 'query_first' && !queryText ? 'no_query'
+ : budgetTokens === null ? 'no_positive_finite_budget'
+ : budgetTokens === 0 ? 'budget_below_one'
+ : rows.length + searchResults.length === 0 ? 'no_candidates'
+ : packedFacts.length + packedResults.length === 0 ? 'first_items_exceed_budget'
+ : 'packed',
+ facts: {
+ candidates: rows.length,
+ kept: packedFacts.length,
+ dropped: rows.length - packedFacts.length,
+ used: packedFacts.reduce((sum, r) => sum + estimateTokens(r.fact), 0),
+ },
+ results: {
+ candidates: searchResults.length,
+ kept: packedResults.length,
+ dropped: searchResults.length - packedResults.length,
+ used: packedResults.reduce((sum, r) => sum + resultTokens(r), 0),
+ },
+ }
+ : undefined;
+
return {
facts: packedFacts.map(r => ({
id: r.id,
@@ -491,6 +542,7 @@ const recall: Operation = {
...(budgetTokens !== null
? { budget_tokens: budgetTokens, budget_used: budgetUsed, dropped_count: droppedCount }
: {}),
+ ...(budgetPacking ? { budget_packing: budgetPacking } : {}),
};
},
};
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index 61c3736a04..983140a6e9 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -79,7 +79,7 @@ export async function admitWrite(engine: BrainEngine, input: WriteAdmission, ove
const { requestId, apply } = await prepareAdmission(engine, input, overrides);
return retryWriteAdmission(requestId, remaining => engine.transaction(async tx => {
await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout',$1,true),set_config('statement_timeout',$2,true)",
- [`${Math.min(10, remaining)}ms`, `${remaining}ms`]);
+ [`${Math.min(100, remaining)}ms`, `${remaining}ms`]);
return apply(tx);
}));
}
diff --git a/src/core/persistence/links-preparation.ts b/src/core/persistence/links-preparation.ts
index 749c572a7d..fe87ea6709 100644
--- a/src/core/persistence/links-preparation.ts
+++ b/src/core/persistence/links-preparation.ts
@@ -1,46 +1,59 @@
import type { BrainEngine } from '../engine.ts';
import type { ParsedPage } from '../import-file.ts';
-import { extractPageLinks, isGlobalBasenameEnabled, makeResolver } from '../link-extraction.ts';
+import { extractPageLinks, isGlobalBasenameEnabled, makeResolver, resolvedLinkCandidate } from '../link-extraction.ts';
import { loadActivePackForLocalEngine } from '../schema-pack/best-effort.ts';
+import { DerivedLinkEndpointChangedError } from '../derived-links.ts';
+import { capturedLinkEndpoints, indexLinkSources, loadLinkSourcePolicy, resolveCandidateSources } from '../link-reconciliation.ts';
-/** Resolve outside transactions; install only under the originating page guard. */
export async function prepareAutomaticLinks(engine: BrainEngine, slug: string,
page: Pick<ParsedPage, 'type' | 'compiled_truth' | 'timeline' | 'frontmatter'>, sourceId: string) {
- const { candidates, unresolved } = await extractPageLinks(slug, `${page.compiled_truth}\n${page.timeline}`,
- page.frontmatter, page.type, makeResolver(engine, { mode: 'live', sourceId }), {
- globalBasename: await isGlobalBasenameEnabled(engine),
- pack: (await loadActivePackForLocalEngine(engine))?.manifest ?? null,
- });
- const previous = [...await engine.getLinks(slug, { sourceId }), ...await engine.getBacklinks(slug, { sourceId })];
- const keys = [...new Set([...candidates.flatMap(c => [c.targetSlug, c.fromSlug ?? slug]),
- ...previous.flatMap(l => [l.from_slug, l.to_slug])])].sort();
- return { pageKeys: keys.map(target => ({ sourceId, slug: target })), apply: async (tx: BrainEngine) => {
- const present = new Set((keys.length ? await tx.executeRaw<{ slug: string }>(
- 'SELECT slug FROM pages WHERE source_id=$1 AND slug=ANY($2::text[])', [sourceId, keys]) : []).map(row => row.slug));
- const valid = candidates.filter(c => present.has(c.targetSlug) && present.has(c.fromSlug ?? slug));
- const outgoing = await tx.getLinks(slug, { sourceId });
- const incoming = (await tx.getBacklinks(slug, { sourceId })).filter(l => l.link_source === 'frontmatter' && l.origin_slug === slug);
- const managed = outgoing.filter(l => l.link_source == null || ['markdown', 'wikilink-resolved'].includes(l.link_source)
- || l.link_source === 'frontmatter' && l.origin_slug === slug);
- const key = (from: string, to: string, type: string, origin: string | null | undefined) => JSON.stringify([from, to, type, origin ?? 'markdown']);
- const existing = new Map([...managed, ...incoming].map(l => [key(l.from_slug, l.to_slug, l.link_type, l.link_source), l]));
- const wanted = new Set<string>();
- let created = 0, removed = 0;
- for (const c of valid) {
- const from = c.fromSlug ?? slug;
- const linkSource = from === slug ? c.linkSource ?? 'markdown' : 'frontmatter';
- const identity = key(from, c.targetSlug, c.linkType, linkSource);
- if (wanted.has(identity)) continue;
- wanted.add(identity);
- await tx.addLink(from, c.targetSlug, c.context, c.linkType, linkSource, c.originSlug, c.originField,
- { fromSourceId: sourceId, toSourceId: sourceId, originSourceId: sourceId });
- if (!existing.has(identity)) created++;
+ const resolver = makeResolver(engine, { mode: 'live', sourceId });
+ const opts = { globalBasename: await isGlobalBasenameEnabled(engine),
+ pack: (await loadActivePackForLocalEngine(engine, { sourceId }))?.manifest ?? null };
+ if (!opts.pack) return { pageKeys: [{ sourceId, slug }],
+ apply: async () => ({ created: 0, removed: 0, errors: 1, unresolved_count: 1 }) };
+ const content = `${page.compiled_truth}\n${page.timeline}`;
+ const referenced = new Set([slug]);
+ const initial = await extractPageLinks(slug, content, page.frontmatter, page.type, resolver,
+ { ...opts, onResolvedFrontmatterTarget: target => referenced.add(target) });
+ const keys = [...new Set([...referenced, ...initial.candidates.flatMap(c => [c.targetSlug, c.fromSlug ?? slug])])].sort();
+ const endpointRows = await engine.executeRaw<{ slug: string; source_id: string; type: string; knowledge_revision: string }>(
+ 'SELECT slug, source_id, type, knowledge_revision FROM pages WHERE slug=ANY($1::text[]) AND deleted_at IS NULL', [keys]);
+ const endpoints = indexLinkSources(endpointRows);
+ const policy = await loadLinkSourcePolicy(engine, sourceId);
+ const metadata = new Map(endpointRows.map(row => [`${row.source_id}\0${row.slug}`, row]));
+ endpoints.allSlugs.add(slug);
+ endpoints.slugToSources.set(slug, [...new Set([sourceId, ...(endpoints.slugToSources.get(slug) ?? [])])]);
+ const resolve = (candidate: Parameters<typeof resolveCandidateSources>[0]) => resolveCandidateSources(candidate, slug,
+ sourceId, endpoints.allSlugs, endpoints.slugToSources, policy.allowCrossSource, policy);
+ const { candidates, unresolved, attendanceComplete } = await extractPageLinks(slug, content, page.frontmatter, page.type, resolver,
+ { ...opts, targetType: (targetSlug, targetSourceId) => {
+ const resolved = resolve({ targetSlug, targetSourceId, linkType: '', context: '' });
+ return resolved.ok ? (targetSlug === slug && resolved.toSourceId === sourceId ? page.type
+ : metadata.get(`${resolved.toSourceId}\0${targetSlug}`)?.type) : undefined;
+ } });
+ const rows = candidates.flatMap(candidate => {
+ const resolved = resolve(candidate);
+ if (!resolved.ok) return [];
+ if (!candidate.canonicalAttendance && (resolved.fromSourceId !== sourceId || resolved.toSourceId !== sourceId)) return [];
+ return [resolvedLinkCandidate(candidate, slug, sourceId, resolved)];
+ });
+ return { pageKeys: [{ sourceId, slug }, ...rows.flatMap(row => [
+ { sourceId: row.from_source_id!, slug: row.from_slug }, { sourceId: row.to_source_id!, slug: row.to_slug },
+ ])], apply: async (tx: BrainEngine) => {
+ if (!attendanceComplete) return { created: 0, removed: 0, errors: 1, unresolved_count: Math.max(1, unresolved.length) };
+ const snapshot = await tx.readPageSnapshot(slug, { sourceId });
+ if (!snapshot) throw new Error('Automatic link origin disappeared');
+ try {
+ const result = await tx.replaceDerivedLinks({ slug, sourceId, expectedRevision: snapshot.revision,
+ sourceIncarnation: snapshot.sourceIncarnation }, rows, { preserveExisting: true,
+ expectedEndpoints: capturedLinkEndpoints(rows, new Map([...metadata,
+ [`${sourceId}\0${slug}`, { slug, source_id: sourceId, type: page.type, knowledge_revision: snapshot.revision }]]))
+ .filter(endpoint => endpoint.slug !== slug || endpoint.sourceId !== sourceId) });
+ return { ...result, errors: 0, unresolved_count: unresolved.length };
+ } catch (error) {
+ if (!(error instanceof DerivedLinkEndpointChangedError)) throw error;
+ return { created: 0, removed: 0, errors: 1, unresolved_count: Math.max(1, unresolved.length) };
}
- for (const [identity, link] of existing) if (!wanted.has(identity)) {
- await tx.removeLink(link.from_slug, link.to_slug, link.link_type, link.link_source ?? undefined,
- { fromSourceId: sourceId, toSourceId: sourceId });
- removed++;
- }
- return { created, removed, errors: 0, unresolved_count: unresolved.length };
} };
}
diff --git a/src/core/sweep.ts b/src/core/sweep.ts
index c56e851e53..f1b7e2d8e5 100644
--- a/src/core/sweep.ts
+++ b/src/core/sweep.ts
@@ -1,3 +1,4 @@
+import { lookupRefsForSlugs } from './link-reconciliation.ts';
/**
* Serve-resident maintenance sweep [CX-P0.1, CX-P0.3, CX2-4].
*
@@ -278,6 +279,7 @@ async function runLinksTimelinePass(
const {
extractPageLinks,
+ resolvedLinkCandidate,
parseTimelineEntries,
makeResolver,
isGlobalBasenameEnabled,
@@ -326,13 +328,15 @@ async function runLinksTimelinePass(
// #3190: pack-aware verbs — the sweep must type edges the same way the
// extract command does or reconciliation flip-flops the link_type.
const { loadActivePackForLocalEngine } = await import('./schema-pack/best-effort.ts');
- const pack = (await loadActivePackForLocalEngine(engine))?.manifest ?? null;
+ const pack = (await loadActivePackForLocalEngine(engine, { sourceId }))?.manifest ?? null;
+ if (linksEnabled && !pack) throw new Error('Cannot extract links: active schema pack is unavailable.');
type Extracted = Awaited<ReturnType<typeof extractPageLinks>>;
const tlBatch: TimelineBatchInput[] = [];
const processedRefs: Array<{ slug: string; source_id: string; extractedAt: string }> = [];
const pageCandidates: Array<{ slug: string; candidates: Extracted['candidates'] }> = [];
+ const snapshots = new Map<string, NonNullable<Awaited<ReturnType<BrainEngine['readPageSnapshot']>>>>();
// Phase 1: per-page extraction. The per-slug getPage loop stays a loop —
// BrainEngine has no batch read-by-slug-list primitive (resolveSlugsByPaths
@@ -345,6 +349,10 @@ async function runLinksTimelinePass(
const slug = recent[i].slug;
const page = await engine.getPage(slug, { sourceId });
if (!page) continue;
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId });
+ if (!snapshot || snapshot.page.compiled_truth !== page.compiled_truth || snapshot.page.timeline !== page.timeline
+ || snapshot.page.type !== page.type || JSON.stringify(snapshot.page.frontmatter) !== JSON.stringify(page.frontmatter)) continue;
+ snapshots.set(slug, snapshot);
const fullContent = page.compiled_truth + '\n' + page.timeline;
@@ -387,6 +395,8 @@ async function runLinksTimelinePass(
// so resolveCandidateSources' F10 resolution is unchanged — it just sees
// only the rows it can possibly use. Zero candidates ⇒ zero queries.
const linkBatch: LinkBatchInput[] = [];
+ const endpointMetadata = new Map<string, { slug: string; source_id: string; type: string; knowledge_revision: string }>();
+ const incomplete = new Set<string>();
if (pageCandidates.length > 0) {
const needed = new Set<string>();
for (const { slug, candidates } of pageCandidates) {
@@ -396,7 +406,8 @@ async function runLinksTimelinePass(
if (c.fromSlug) needed.add(c.fromSlug);
}
}
- const { allSlugs, slugToSources } = await lookupRefsForSlugs(engine, [...needed]);
+ const { allSlugs, slugToSources, metadata } = await lookupRefsForSlugs(engine, [...needed]);
+ for (const row of metadata) endpointMetadata.set(`${row.source_id}\0${row.slug}`, row);
// #3478: the 'default' fallback is a federation feature — a sweep over an
// isolated source must not push cross-source edges. Single-row fetchSource
// (not loadAllSources) keeps the sweep's bounded-cost discipline; a missing
@@ -413,7 +424,19 @@ async function runLinksTimelinePass(
resolveLinkFallbackDefault(engine),
]);
let crossSourceDrops = 0;
- for (const { slug, candidates } of pageCandidates) {
+ for (const { slug } of pageCandidates) {
+ const page = snapshots.get(slug)!.page;
+ const { candidates, attendanceComplete } = await extractPageLinks(slug, `${page.compiled_truth}\n${page.timeline}`, page.frontmatter,
+ page.type, resolver, { skipFrontmatter: true, globalBasename, pack, targetType: (targetSlug, targetSourceId) => {
+ const resolved = resolveCandidateSources({ targetSlug, targetSourceId, linkType: '', context: '' }, slug,
+ sourceId, allSlugs, slugToSources, allowCrossSource, { crossSource, defaultSourceId: linkDefaultSourceId });
+ return resolved.ok ? endpointMetadata.get(`${resolved.toSourceId}\0${targetSlug}`)?.type : undefined;
+ } });
+ if (!attendanceComplete) {
+ incomplete.add(slug);
+ skip('attendance_resolution_incomplete');
+ continue;
+ }
for (const c of candidates) {
// #2589: a cross_source drop here means the target exists only in
// other sources and cross-source links are off — counted in the
@@ -426,18 +449,7 @@ async function runLinksTimelinePass(
if (resolved.reason === 'cross_source') crossSourceDrops++;
continue;
}
- linkBatch.push({
- from_slug: resolved.fromSlug,
- to_slug: c.targetSlug,
- link_type: c.linkType,
- context: c.context,
- link_source: c.linkSource,
- origin_slug: c.originSlug,
- origin_field: c.originField,
- from_source_id: resolved.fromSourceId,
- to_source_id: resolved.toSourceId,
- origin_source_id: sourceId,
- });
+ linkBatch.push(resolvedLinkCandidate(c, slug, sourceId, resolved));
}
}
if (crossSourceDrops > 0) skip('cross_source_link', crossSourceDrops);
@@ -445,9 +457,6 @@ async function runLinksTimelinePass(
// Engine batch primitives self-retry; default auditSite labels apply
// (BATCH_AUDIT_SITES is a closed enum owned by retry.ts).
- if (linkBatch.length > 0) {
- report.linksExtracted += await engine.addLinksBatch(linkBatch); // gbrain-allow-direct-insert: the sweep IS the extract path for workspace pages — remote put_page skips extraction by design [CX-P0.3]
- }
if (tlBatch.length > 0) {
report.timelineExtracted += await engine.addTimelineEntriesBatch(tlBatch); // gbrain-allow-direct-insert: same extract-path rationale as addLinksBatch above [CX-P0.3]
}
@@ -463,49 +472,30 @@ async function runLinksTimelinePass(
// fails (or is cut by budget) is left unstamped so the next sweep retries.
const stampable = new Set(processedRefs.map(r => r.slug));
if (linksEnabled) {
- const { autoLinkLockKey } = await import('./ops/pages.ts');
- const desiredBySlug = new Map<string, Set<string>>(
- processedRefs.map(r => [r.slug, new Set<string>()]),
+ const desiredBySlug = new Map<string, LinkBatchInput[]>(
+ processedRefs.map(r => [r.slug, []]),
);
for (const b of linkBatch) {
- // runAutoLink's exact key shape (ops/pages.ts outKeys).
- desiredBySlug.get(b.from_slug)?.add(
- `${b.to_slug}\u0000${b.link_type}\u0000${b.link_source ?? 'markdown'}`,
- );
+ desiredBySlug.get(b.origin_slug ?? b.from_slug)?.push(b);
}
for (const ref of processedRefs) {
- if (overBudget()) {
- skip('budget_exhausted:link_reconcile');
+ if (incomplete.has(ref.slug) || overBudget()) {
+ if (!incomplete.has(ref.slug)) skip('budget_exhausted:link_reconcile');
stampable.delete(ref.slug);
continue;
}
const desired = desiredBySlug.get(ref.slug)!;
try {
- report.linksRemoved += await engine.transaction(async (tx) => {
- try {
- // Same advisory lock runAutoLink takes, so sweep reconciliation
- // serializes against a concurrent local put_page on the slug.
- await tx.executeRaw(`SELECT pg_advisory_xact_lock(hashtext($1)::bigint)`, [
- autoLinkLockKey(sourceId, ref.slug),
- ]);
- } catch { /* engine without advisory locks — PGLite is single-process */ }
- const existing = await tx.getLinks(ref.slug, { sourceId });
- let removed = 0;
- for (const l of existing) {
- const reconcilable =
- l.link_source === 'markdown' || l.link_source == null ||
- l.link_source === 'wikilink-resolved';
- if (!reconcilable) continue;
- const key = `${l.to_slug}\u0000${l.link_type}\u0000${l.link_source ?? 'markdown'}`;
- if (desired.has(key)) continue;
- await tx.removeLink(ref.slug, l.to_slug, l.link_type, l.link_source ?? undefined, {
- fromSourceId: sourceId,
- toSourceId: l.to_source_id,
- });
- removed++;
- }
- return removed;
- });
+ const snapshot = snapshots.get(ref.slug)!;
+ const result = await engine.replaceDerivedLinks({ slug: ref.slug, sourceId,
+ expectedRevision: snapshot.revision, sourceIncarnation: snapshot.sourceIncarnation }, desired,
+ { includeFrontmatter: false, preserveExisting: true, expectedEndpoints: [...new Set(desired.flatMap(row =>
+ [`${row.from_source_id}\0${row.from_slug}`, `${row.to_source_id}\0${row.to_slug}`]))].map(key => {
+ const endpoint = endpointMetadata.get(key)!;
+ return { slug: endpoint.slug, sourceId: endpoint.source_id, revision: endpoint.knowledge_revision };
+ }) });
+ report.linksRemoved += result.removed;
+ report.linksExtracted += result.created;
} catch {
skip('link_reconcile_failed');
stampable.delete(ref.slug);
@@ -523,36 +513,6 @@ async function runLinksTimelinePass(
}
}
-/**
- * (slug, source_id) refs for EXACTLY the given slugs, chunked IN-list —
- * the bounded replacement for listAllPageRefs in the sweep's pass 2. Same
- * visibility as listAllPageRefs (deleted_at IS NULL).
- */
-async function lookupRefsForSlugs(
- engine: BrainEngine,
- slugs: string[],
-): Promise<{ allSlugs: Set<string>; slugToSources: Map<string, string[]> }> {
- const allSlugs = new Set<string>();
- const slugToSources = new Map<string, string[]>();
- const CHUNK = 200;
- for (let i = 0; i < slugs.length; i += CHUNK) {
- const chunk = slugs.slice(i, i + CHUNK);
- const placeholders = chunk.map((_, j) => `$${j + 1}`).join(', ');
- const rows = await engine.executeRaw<{ slug: string; source_id: string }>(
- `SELECT slug, source_id FROM pages
- WHERE deleted_at IS NULL AND slug IN (${placeholders})`,
- chunk,
- );
- for (const ref of rows) {
- allSlugs.add(ref.slug);
- const list = slugToSources.get(ref.slug) ?? [];
- list.push(ref.source_id);
- slugToSources.set(ref.slug, list);
- }
- }
- return { allSlugs, slugToSources };
-}
-
/**
* Pass 3 body. One `runFactsPipeline` call per unprocessed corpus file —
* the narrowest existing entry that takes raw transcript text through
diff --git a/src/core/verbs.ts b/src/core/verbs.ts
index 402f2395a8..171186d01d 100644
--- a/src/core/verbs.ts
+++ b/src/core/verbs.ts
@@ -404,6 +404,17 @@ const SYNTHESIS_STATUS_ENUM = [
'ok', 'empty_answer', 'not_json', 'output_truncated', 'no_llm', 'model_unusable', 'llm_error', 'extractive_fallback',
];
+const RECALL_BUDGET_ARM_SCHEMA = {
+ type: 'object',
+ required: ['candidates', 'kept', 'dropped', 'used'],
+ properties: {
+ candidates: { type: 'integer', minimum: 0, description: 'Authorized, filtered, limit-capped candidates before packing.' },
+ kept: { type: 'integer', minimum: 0 },
+ dropped: { type: 'integer', minimum: 0 },
+ used: { type: 'integer', minimum: 0, description: 'Estimated tokens in retained evidence, excluding the JSON envelope.' },
+ },
+};
+
export const RESPONSE_SCHEMAS: Record<VerbName, Record<string, unknown>> = {
recall: {
type: 'object',
@@ -445,9 +456,21 @@ export const RESPONSE_SCHEMAS: Record<VerbName, Record<string, unknown>> = {
},
},
search_degraded: { type: 'string', description: 'Present when the search arm fell back to keyword-only (no embedding provider).' },
- budget_tokens: { type: 'integer', description: 'Present when budget_tokens was passed.' },
+ budget_tokens: { type: 'integer', description: 'Present for a positive finite numeric budget, including when its floor is zero.' },
budget_used: { type: 'integer' },
dropped_count: { type: 'integer' },
+ budget_packing: {
+ type: 'object',
+ description: 'Present only when a valid budget_policy is supplied. Per-arm used and dropped sums match budget_used and dropped_count when those fields exist.',
+ required: ['policy', 'applied', 'reason', 'facts', 'results'],
+ properties: {
+ policy: { type: 'string', enum: ['facts_first', 'query_first'], description: 'Effective policy; ineligible query_first requests fall back to facts_first.' },
+ applied: { type: 'boolean', description: 'Whether the requested budget policy applied, not whether all required evidence fit.' },
+ reason: { type: 'string', enum: ['no_query', 'no_positive_finite_budget', 'budget_below_one', 'no_candidates', 'first_items_exceed_budget', 'packed'] },
+ facts: RECALL_BUDGET_ARM_SCHEMA,
+ results: RECALL_BUDGET_ARM_SCHEMA,
+ },
+ },
},
},
remember: {
diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.md
index dc7bcd8f86..0563f261da 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.57.1.0 -->
+<!-- gbrain-template-stamp: 0.58.0.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-extraction-bounds.test.ts b/test/attendance-extraction-bounds.test.ts
new file mode 100644
index 0000000000..fa7eb36990
--- /dev/null
+++ b/test/attendance-extraction-bounds.test.ts
@@ -0,0 +1,163 @@
+import { expect, test } from 'bun:test';
+import { attendanceEvidenceRanges, extractPageLinks, hasAttendanceEvidence, makeResolver } from '../src/core/link-extraction.ts';
+import { extractLinksFromFile } from '../src/commands/extract.ts';
+
+const person = 'people/alice-example';
+const meeting = 'meetings/planning';
+const resolver = { async resolve(value: string) { return value === person ? person : null; } };
+const types = new Map([[person, 'person'], [meeting, 'meeting']]);
+
+test('a unique basename is canonical evidence while missing and ambiguous names remain incomplete', async () => {
+ for (const targets of [[person], [], [person, 'archive/alice-example']]) {
+ const basenameResolver = { ...resolver, async resolveBasenameMatches() { return targets; } };
+ const result = await extractPageLinks(meeting, 'Attendees: [[Alice Example]]', {}, 'meeting', basenameResolver,
+ { globalBasename: true, targetType: slug => targets.includes(slug) ? 'person' : undefined });
+ expect(result.attendanceComplete).toBe(targets.length === 1);
+ expect(result.candidates.filter(row => row.canonicalAttendance).map(row => row.targetSlug)).toEqual(targets.length === 1 ? [person] : []);
+ }
+});
+
+test('commented attendance cannot borrow visible evidence and masking preserves CRLF and UTF-16 positions', async () => {
+ const body = `😀\r\n<!--\r\nAttendees: [[people/hidden-example]]\r\n-->\r\nAttendees: [[${person}]]`;
+ const ranges = attendanceEvidenceRanges(body);
+ expect(hasAttendanceEvidence(ranges, body.indexOf('[[people/hidden-example]]'))).toBe(false);
+ expect(hasAttendanceEvidence(ranges, body.indexOf(`[[${person}]]`))).toBe(true);
+ const result = await extractPageLinks(meeting, body, {}, 'meeting', resolver, { targetType: slug => types.get(slug) });
+ expect(result.attendanceComplete).toBe(true);
+ expect(result.candidates.filter(row => row.canonicalAttendance).map(row => row.targetSlug)).toEqual([person]);
+ expect(attendanceEvidenceRanges(`<!--\nAttendees: [[${person}]]`)).toEqual([]);
+});
+
+test('strict attendance names with a non-source colon remain eligible for exact title resolution', async () => {
+ const calls: unknown[][] = [];
+ const engine = { async executeRaw(_sql: string, args: unknown[]) { calls.push(args); return [{ slug: person }]; } };
+ const live = makeResolver(engine as never, { mode: 'batch', sourceId: 'example' });
+ expect(await live.resolveAttendance!('Example Person: host', 'people')).toBe(person);
+ expect(calls[0]?.[2]).toBe('Example Person: host');
+ expect(await live.resolveAttendance!(`other:${person}`, 'people')).toBeNull();
+ expect(calls).toHaveLength(1);
+});
+
+for (const body of [
+ `Attendees: [[${person}]] <!-- [[people/hidden-example]] -->`,
+ `## Attendees\r\n- [[${person}]] <!-- 😀 [[people/hidden-example]] -->\r\n## Notes`,
+ `Attendees: [[${person}]] <!-- [[people/hidden-example]]`,
+]) {
+ test(`inline commented targets are outside accepted attendance evidence: ${JSON.stringify(body)}`, async () => {
+ const pageTypes = new Map([...types, ['people/hidden-example', 'person']]);
+ const ranges = attendanceEvidenceRanges(body);
+ expect(hasAttendanceEvidence(ranges, body.indexOf('[[people/hidden-example]]'))).toBe(false);
+ expect(hasAttendanceEvidence(ranges, body.indexOf(`[[${person}]]`))).toBe(true);
+ const db = await extractPageLinks(meeting, body, {}, 'meeting', resolver, { targetType: slug => pageTypes.get(slug) });
+ const fs = await extractLinksFromFile(`---\ntype: meeting\n---\n${body}`, `${meeting}.md`, new Set(pageTypes.keys()), { pageTypes });
+ expect(db.candidates.filter(row => row.canonicalAttendance).map(row => row.targetSlug)).toEqual([person]);
+ expect(fs.filter(row => row.link_type === 'attended').map(row => row.from_slug)).toEqual([person]);
+ });
+}
+
+for (const example of ['```html\n<!--\n```', '~~~html\n<!--\n~~~', '`<!--`']) {
+ test(`a comment opener inside code does not hide later attendance: ${JSON.stringify(example)}`, async () => {
+ const body = `${example}\nAttendees: [[${person}]]`;
+ const db = await extractPageLinks(meeting, body, {}, 'meeting', resolver, { targetType: slug => types.get(slug) });
+ const fs = await extractLinksFromFile(`---\ntype: meeting\n---\n${body}`, `${meeting}.md`, new Set(types.keys()), { pageTypes: types });
+ expect(db.candidates.filter(row => row.canonicalAttendance).map(row => row.targetSlug)).toEqual([person]);
+ expect(fs.filter(row => row.link_type === 'attended').map(row => row.from_slug)).toEqual([person]);
+ });
+}
+
+for (const fence of ['~~~', '```', '~~~~', '````']) {
+ for (const falseClose of [...new Set([fence.slice(0, 2), fence.slice(0, -1), `${fence} not a closing fence`, fence[0] === '~' ? '```' : '~~~'])]) {
+ test(`attendee sections retain ${fence} state across headings and invalid closer ${falseClose}`, async () => {
+ const body = `## Attendees\n${fence}\n## Example\n${falseClose}\n# Still an example\nAttendees: [Alice](../people/alice-example.md)\n${fence}\n## Notes\nNo attendance evidence.`;
+ const db = await extractPageLinks(meeting, body, {}, 'meeting', resolver, { targetType: slug => types.get(slug) });
+ const fs = await extractLinksFromFile(`---\ntype: meeting\n---\n${body}`, `${meeting}.md`, new Set(types.keys()), { pageTypes: types });
+ expect(db.candidates.filter(row => row.linkType === 'attended')).toEqual([]);
+ expect(fs.filter(row => row.link_type === 'attended')).toEqual([]);
+ });
+ test(`attendance survives after ${fence} ignores invalid closer ${falseClose}`, async () => {
+ const body = `## Attendees\n${fence}\n## Example\n${falseClose}\nAttendees: [[people/hidden-example]]\n${fence}\n## Notes\nAttendees: [[${person}]]`;
+ const db = await extractPageLinks(meeting, body, {}, 'meeting', resolver, { targetType: slug => types.get(slug) });
+ const fs = await extractLinksFromFile(`---\ntype: meeting\n---\n${body}`, `${meeting}.md`, new Set(types.keys()), { pageTypes: types });
+ expect(db.candidates.filter(row => row.linkType === 'attended').map(row => row.targetSlug)).toEqual([person]);
+ expect(fs.filter(row => row.link_type === 'attended').map(row => row.from_slug)).toEqual([person]);
+ });
+ }
+ test(`attendance resumes at exact positions after a valid ${fence} closer`, async () => {
+ const body = `## Attendees\n${fence}\n## Example\nAttendees: [[people/missing-example]]\n${fence} \n## Notes\nAttendees: [[${person}]]`;
+ const db = await extractPageLinks(meeting, body, {}, 'meeting', resolver, { targetType: slug => types.get(slug) });
+ const fs = await extractLinksFromFile(`---\ntype: meeting\n---\n${body}`, `${meeting}.md`, new Set(types.keys()), { pageTypes: types });
+ expect(db.candidates.filter(row => row.linkType === 'attended').map(row => row.targetSlug)).toEqual([person]);
+ expect(fs.filter(row => row.link_type === 'attended').map(row => row.from_slug)).toEqual([person]);
+ });
+ test(`CRLF ${fence} fences hide examples through invalid closers and preserve later attendance`, async () => {
+ const body = ['## Attendees', fence, '## Example', `${fence} not a closer`,
+ 'Attendees: [[people/missing-example]]', `${fence} `, '## Notes', `Attendees: [[${person}]]`].join('\r\n');
+ const db = await extractPageLinks(meeting, body, {}, 'meeting', resolver, { targetType: slug => types.get(slug) });
+ const fs = await extractLinksFromFile(`---\r\ntype: meeting\r\n---\r\n${body}`, `${meeting}.md`, new Set(types.keys()), { pageTypes: types });
+ expect(db.candidates.filter(row => row.linkType === 'attended').map(row => row.targetSlug)).toEqual([person]);
+ expect(db.attendanceComplete).toBe(true);
+ expect(fs.filter(row => row.link_type === 'attended').map(row => row.from_slug)).toEqual([person]);
+ });
+}
+
+test('attendance membership reads logarithmically many ordered ranges with exact boundaries', () => {
+ const ranges: Array<[number, number]> = Array.from({ length: 25_000 }, (_, i) => [i * 4, i * 4 + 2]);
+ let reads = 0;
+ const tracked = new Proxy(ranges, { get(target, key, receiver) {
+ if (typeof key === 'string' && /^\d+$/.test(key)) reads++;
+ return Reflect.get(target, key, receiver);
+ } });
+ for (const [position, expected] of [[-1, false], [0, true], [1, true], [2, false], [99_996, true], [99_998, false], [100_000, false]] as const) {
+ reads = 0;
+ expect(hasAttendanceEvidence(tracked, position)).toBe(expected);
+ expect(reads).toBeLessThanOrEqual(16);
+ }
+ expect(hasAttendanceEvidence([], 0)).toBe(false);
+});
+
+test('many supported attendance entries do not multiply range scans per reference', async () => {
+ const body = Array(25_000).fill(`Attendees: [[${person}]]`).join('\n');
+ let start = performance.now();
+ await extractPageLinks(meeting, body, {}, 'note', resolver, { targetType: slug => types.get(slug) });
+ const noteMs = performance.now() - start;
+ start = performance.now();
+ const result = await extractPageLinks(meeting, body, {}, 'meeting', resolver, { targetType: slug => types.get(slug) });
+ const meetingMs = performance.now() - start;
+ expect(result.candidates).toHaveLength(1);
+ expect(result.candidates[0]).toMatchObject({ targetSlug: person, linkType: 'attended', canonicalAttendance: true });
+ expect(meetingMs).toBeLessThan(Math.max(2000, noteMs * 8));
+
+ start = performance.now();
+ await extractLinksFromFile(`---\ntype: note\n---\n${body}`, `${meeting}.md`, new Set(types.keys()), { pageTypes: types });
+ const fsNoteMs = performance.now() - start;
+ start = performance.now();
+ const fs = await extractLinksFromFile(`---\ntype: meeting\n---\n${body}`, `${meeting}.md`, new Set(types.keys()), { pageTypes: types });
+ const fsMeetingMs = performance.now() - start;
+ expect(fs).toHaveLength(25_000);
+ expect(fs.every(row => row.from_slug === person && row.to_slug === meeting && row.link_type === 'attended')).toBe(true);
+ expect(fsMeetingMs).toBeLessThan(Math.max(2000, fsNoteMs * 8));
+}, 120_000);
+
+test('strict attendance resolution caches repeated lookups separately within a bounded resolver lifetime', async () => {
+ const calls: unknown[][] = [];
+ const engine = {
+ async getPage() { return { slug: person }; },
+ async executeRaw(_sql: string, args: unknown[]) {
+ calls.push(args);
+ return args[2] === person ? [{ slug: person }] : [];
+ },
+ };
+ const live = makeResolver(engine as never, { mode: 'live', sourceId: 'example' });
+ expect(await live.resolve(person)).toBe(person);
+ for (let i = 0; i < 6; i++) expect(await live.resolveAttendance!(person)).toBe(person);
+ expect(calls).toHaveLength(1);
+ expect(calls[0][0]).toBe('example');
+ expect(await live.resolveAttendance!(`other:${person}`)).toBeNull();
+ expect(calls).toHaveLength(1);
+ for (let i = 0; i < 300; i++) expect(await live.resolveAttendance!(`missing-${i}`, 'people')).toBeNull();
+ const before = calls.length;
+ expect(await live.resolveAttendance!(person)).toBe(person);
+ expect(calls).toHaveLength(before + 1);
+ expect(await makeResolver(engine as never, { mode: 'live', sourceId: 'other' }).resolveAttendance!(person)).toBe(person);
+ expect(calls.at(-1)?.[0]).toBe('other');
+});
diff --git a/test/attendance-repair-cli.serial.test.ts b/test/attendance-repair-cli.serial.test.ts
new file mode 100644
index 0000000000..fb7075e49a
--- /dev/null
+++ b/test/attendance-repair-cli.serial.test.ts
@@ -0,0 +1,166 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { attendanceRepairConnectionIdentity, parseAttendanceRepairArgs } from '../src/commands/extract-attendance-repair.ts';
+import { runExtract } from '../src/commands/extract.ts';
+import { runCli } from './helpers/cli-spawn.ts';
+import { attendanceRepairHash, type AttendanceRepairPreview } from '../src/core/attendance-repair.ts';
+
+const flags = ['links', '--source', 'db', '--repair-attendance', '--source-id', 'repair-fixture'];
+const env = { GBRAIN_SOURCE: undefined, GBRAIN_BRAIN_ID: 'host', GBRAIN_SCHEMA_PACK: undefined,
+ GBRAIN_NO_BANNER: '1', GBRAIN_MODEL_DISCOVERY: 'off', GBRAIN_SKIP_STARTUP_HOOKS: '1',
+ ANTHROPIC_API_KEY: undefined, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined,
+ DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined };
+
+describe('attendance repair CLI authority and private receipts', () => {
+ let home: string;
+ beforeAll(() => { home = mkdtempSync(join(tmpdir(), 'gbrain-repair-cli-')); mkdirSync(join(home, '.bun')); });
+ afterAll(() => { rmSync(home, { recursive: true, force: true }); });
+
+ test('embedded command rejects missing or remote local authority before engine use', async () => {
+ for (const authority of [undefined, { remote: true }]) {
+ await expect(runExtract({} as PGLiteEngine, flags, authority)).rejects.toThrow('trusted local');
+ }
+ expect(() => parseAttendanceRepairArgs(flags, { remote: undefined as unknown as boolean })).toThrow('trusted local');
+ });
+
+ test('repair help is engine-free and discoverable', async () => {
+ for (const args of [['extract', '--help'], ['extract', '--repair-attendance', '--help'], ['--help']]) {
+ const result = await runCli(args, { home, cwd: home, env });
+ expect(result.exitCode).toBe(0);
+ expect(result.stdout).toContain('--repair-attendance'); expect(result.stdout).toContain('--backup-verified');
+ expect(result.stdout).toContain('--after-slug');
+ }
+ expect(existsSync(join(home, '.gbrain'))).toBe(false);
+ });
+
+ test('preview accepts a bounded source-page slug cursor', () => {
+ expect(parseAttendanceRepairArgs([...flags, '--after-slug', 'topics/é-example', '--limit', '1'], { remote: false }))
+ .toMatchObject({ afterSlug: 'topics/é-example', limit: 1 });
+ });
+
+ test.each([
+ ['links', '--repair-attendance'],
+ ['links', '--repair-attendance=true'], ['links', '--repair-attendance=false'],
+ ['links', '--source', 'fs', '--repair-attendance', '--source-id', 'repair-fixture'],
+ ['timeline', ...flags.slice(1)],
+ ['all', ...flags.slice(1)],
+ [...flags, '--stale'], [...flags, '--global'], [...flags, '--catch-up'], [...flags, '--dir', '.'],
+ [...flags, '--include-frontmatter'], [...flags, '--by-mention'], [...flags, '--ner'],
+ [...flags, '--limit', '1001'], [...flags, '--limit', '0'], [...flags, '--limit', '1.5'],
+ [...flags, '--after-id', '1'], [...flags, '--after-slug', '\n'],
+ [...flags, '--limit', '2', '--limit', '3'], [...flags, '--source-id', 'other'],
+ [...flags, '--yes'], [...flags, '--apply-preview', 'missing'],
+ [...flags, '--apply-preview', 'missing', '--confirm', '0'.repeat(64), '--yes', '--checkpoint', 'missing'],
+ [...flags, '--apply-preview', 'missing', '--confirm', '0'.repeat(64), '--yes', '--backup-verified',
+ '--checkpoint', 'missing', '--after-slug', 'meetings/example'],
+ ].map(args => [args]))('invalid command refuses before creating a brain: %j', async args => {
+ const before = readdirSync(home);
+ const result = await runCli(['extract', ...args], { home, cwd: home, env, timeoutMs: 20_000 });
+ expect(result.exitCode).toBe(1);
+ expect(result.stderr).not.toContain('Setting up brain schema');
+ expect(readdirSync(home)).toEqual(before);
+ }, 30_000);
+
+ test('thin-client command refuses without a remote request or local datastore', async () => {
+ const thinHome = join(home, 'thin'); const brain = join(thinHome, '.gbrain'); mkdirSync(brain, { recursive: true });
+ let requests = 0;
+ const server = Bun.serve({ hostname: '127.0.0.1', port: 0, fetch() { requests++; return new Response('unexpected', { status: 500 }); } });
+ writeFileSync(join(brain, 'config.json'), JSON.stringify({ engine: 'pglite', database_path: join(brain, 'absent-db'),
+ remote_mcp: { mcp_url: `http://127.0.0.1:${server.port}/mcp`, oauth_client_id: 'fixture', oauth_client_secret: 'fixture' } }));
+ try {
+ const result = await runCli(['extract', ...flags], { home: thinHome, cwd: thinHome, env, timeoutMs: 20_000 });
+ expect(result.exitCode).toBe(1); expect(result.stderr).toContain('thin clients');
+ expect(requests).toBe(0); expect(existsSync(join(brain, 'absent-db'))).toBe(false);
+ } finally { await server.stop(true); }
+ }, 30_000);
+
+ test('real CLI preview is logical-read-only and exact private apply resumes idempotently', async () => {
+ const local = join(home, 'local'); const brain = join(local, '.gbrain'); const privateDir = join(local, 'private');
+ mkdirSync(brain, { recursive: true }); mkdirSync(privateDir, { mode: 0o700 });
+ const databasePath = join(brain, 'brain.pglite');
+ writeFileSync(join(brain, 'config.json'), JSON.stringify({ engine: 'pglite', database_path: databasePath }));
+ const packDir = join(brain, 'schema-packs', 'repair-fixture'); mkdirSync(packDir, { recursive: true });
+ writeFileSync(join(packDir, 'pack.json'), JSON.stringify({ api_version: 'gbrain-schema-pack-v1', name: 'repair-fixture',
+ version: '1.0.0', extends: null, page_types: [], link_types: [], frontmatter_links: [] }));
+ const engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite', database_path: databasePath }); await engine.initSchema();
+ await engine.setConfig('schema_pack', 'repair-fixture');
+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES ('repair-fixture','repair-fixture')");
+ await engine.putPage('people/alice-example', { type: 'person', title: 'Example', compiled_truth: 'Person' }, { sourceId: 'repair-fixture' });
+ await engine.putPage('meetings/planning', { type: 'meeting', title: 'Planning', compiled_truth: 'Attendees: [Example](../people/alice-example.md)' }, { sourceId: 'repair-fixture' });
+ await engine.addLink('meetings/planning', 'people/alice-example', 'old evidence', 'attended', 'markdown', undefined, undefined,
+ { fromSourceId: 'repair-fixture', toSourceId: 'repair-fixture' });
+ const snapshot = async () => {
+ const tables: Record<string, unknown> = {};
+ for (const table of ['pages', 'links', 'config', 'op_checkpoints', 'page_write_guards']) {
+ tables[table] = await engine.executeRaw(`SELECT row_to_json(t) AS row FROM ${table} t ORDER BY row_to_json(t)::text`);
+ }
+ return tables;
+ };
+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation FROM sources WHERE id='default'");
+ const before = await snapshot(); await engine.disconnect();
+ const invoke = (args: string[]) => runCli(['extract', ...args], { home: local, cwd: local, env, timeoutMs: 30_000 });
+ const result = await invoke([...flags, '--json']);
+ expect({ code: result.exitCode, stderr: result.stderr }).toMatchObject({ code: 0 });
+ const preview = JSON.parse(result.stdout) as AttendanceRepairPreview;
+ expect(preview.brain).toBe(attendanceRepairHash([attendanceRepairHash(incarnation),
+ attendanceRepairConnectionIdentity('host', { engine: 'pglite', database_path: databasePath })]));
+ expect(preview.counts).toMatchObject({ add: 1, remove: 1 });
+ expect(readdirSync(privateDir)).toEqual([]);
+ expect(result.stdout + result.stderr).not.toContain('Setting up brain schema');
+ const next = await invoke([...flags, '--after-slug', preview.nextAfterSlug, '--limit', '1', '--json']);
+ expect(next.exitCode).toBe(0);
+ expect(JSON.parse(next.stdout)).toMatchObject({ afterSlug: preview.nextAfterSlug, complete: true,
+ counts: { scanned: 0, eligibleOrigins: 0 } });
+ await engine.connect({ engine: 'pglite', database_path: databasePath });
+ expect(await snapshot()).toEqual(before); await engine.disconnect();
+ const receipt = join(privateDir, 'preview.json'); const checkpoint = join(privateDir, 'cursor.json');
+ writeFileSync(receipt, result.stdout, { mode: 0o600 });
+ const apply = [...flags, '--apply-preview', receipt, '--confirm', preview.digest, '--yes', '--backup-verified', '--checkpoint', checkpoint];
+ chmodSync(receipt, 0o644);
+ expect((await invoke(apply)).exitCode).toBe(1); expect(existsSync(checkpoint)).toBe(false);
+ chmodSync(receipt, 0o600);
+ symlinkSync(receipt, checkpoint);
+ expect((await invoke(apply)).exitCode).toBe(1); expect(readFileSync(receipt, 'utf8')).toBe(result.stdout);
+ rmSync(checkpoint);
+ const applied = await invoke(apply);
+ expect({ code: applied.exitCode, stderr: applied.stderr }).toMatchObject({ code: 0 });
+ expect(JSON.parse(applied.stdout)).toMatchObject({ created: 1, removed: 1, committed: 1 });
+ expect(statSync(checkpoint).mode & 0o777).toBe(0o600);
+ expect(JSON.parse(readFileSync(checkpoint, 'utf8'))).toMatchObject({ digest: preview.digest,
+ afterSlug: preview.nextAfterSlug, pagesProcessed: preview.window.length });
+ const resumed = await invoke(apply);
+ expect({ code: resumed.exitCode, stderr: resumed.stderr }).toMatchObject({ code: 0 });
+ expect(JSON.parse(resumed.stdout)).toMatchObject({ created: 0, removed: 0, replayed: 1 });
+ await engine.connect({ engine: 'pglite', database_path: databasePath });
+ await engine.executeRaw("UPDATE op_checkpoints SET updated_at=now()-interval '8 days' WHERE op='attendance-repair'");
+ const after = await snapshot(); await engine.disconnect();
+ const expired = await invoke(apply);
+ expect(expired.exitCode).toBe(1); expect(expired.stderr).toContain('commit proof expired');
+ const freshResult = await invoke([...flags, '--json']);
+ expect(freshResult.exitCode).toBe(0);
+ const fresh = JSON.parse(freshResult.stdout) as AttendanceRepairPreview;
+ expect(fresh.digest).not.toBe(preview.digest); expect(fresh.approvalId).not.toBe(preview.approvalId);
+ expect(fresh.counts).toMatchObject({ add: 0, remove: 0 });
+ const freshReceipt = join(privateDir, 'fresh-preview.json');
+ const freshCheckpoint = join(privateDir, 'fresh-cursor.json');
+ writeFileSync(freshReceipt, freshResult.stdout, { mode: 0o600 });
+ const freshApply = [...flags, '--apply-preview', freshReceipt, '--confirm', fresh.digest, '--yes', '--backup-verified'];
+ const reused = await invoke([...freshApply, '--checkpoint', checkpoint]);
+ expect(reused.exitCode).toBe(1); expect(reused.stderr).toContain('Checkpoint belongs to another preview');
+ const approved = await invoke([...freshApply, '--checkpoint', freshCheckpoint]);
+ expect({ code: approved.exitCode, stderr: approved.stderr }).toMatchObject({ code: 0 });
+ expect(JSON.parse(approved.stdout)).toMatchObject({ created: 0, removed: 0, replayed: 0 });
+ const nextReceipt = join(privateDir, 'next-preview.json');
+ const nextPreview = JSON.parse(next.stdout) as AttendanceRepairPreview;
+ writeFileSync(nextReceipt, next.stdout, { mode: 0o600 });
+ const nextApply = [...flags, '--apply-preview', nextReceipt, '--confirm', nextPreview.digest, '--yes', '--backup-verified'];
+ expect((await invoke([...nextApply, '--checkpoint', freshCheckpoint])).exitCode).toBe(1);
+ expect((await invoke([...nextApply, '--checkpoint', join(privateDir, 'next-cursor.json')])).exitCode).toBe(0);
+ await engine.connect({ engine: 'pglite', database_path: databasePath });
+ const final = await snapshot(); await engine.disconnect();
+ for (const table of ['pages', 'links', 'config', 'page_write_guards']) expect(final[table]).toEqual(after[table]);
+ }, 120_000);
+});
diff --git a/test/attendance-repair-identity.test.ts b/test/attendance-repair-identity.test.ts
new file mode 100644
index 0000000000..8d925e5ed8
--- /dev/null
+++ b/test/attendance-repair-identity.test.ts
@@ -0,0 +1,86 @@
+import { describe, expect, test } from 'bun:test';
+import { resolve } from 'node:path';
+import type { EngineConfig } from '../src/core/types.ts';
+import { attendanceRepairConnectionIdentity } from '../src/commands/extract-attendance-repair.ts';
+import { attendanceRepairHash } from '../src/core/attendance-repair.ts';
+
+function connection(target = 'postgresql://db.example.invalid:5432/brain_example', rotation = false): EngineConfig {
+ const url = new URL(target);
+ url.username = rotation ? 'rotated_example' : 'operator_example';
+ url.password = rotation ? 'synthetic-rotation' : 'synthetic-original';
+ url.searchParams.set('sslpassword', rotation ? 'synthetic-query-rotation' : 'synthetic-query-original');
+ url.searchParams.set('application_name', rotation ? 'second_example' : 'first_example');
+ return { engine: 'postgres', database_url: url.toString() };
+}
+
+describe('attendance repair credential-free connection identity', () => {
+ test('credential rotation and irrelevant query/config fields do not change the PostgreSQL target', () => {
+ const original = attendanceRepairConnectionIdentity('host', connection());
+ expect(attendanceRepairConnectionIdentity('host', connection(undefined, true))).toBe(original);
+ expect(attendanceRepairConnectionIdentity('host', Object.assign(connection(), {
+ database_path: '/ignored/example', poolSize: 42, auth_token: 'synthetic-unused',
+ }))).toBe(original);
+ expect(original).toBe(attendanceRepairHash(['host', { engine: 'postgres', scheme: 'postgresql:',
+ hosts: [['db.example.invalid', 5432]], database: 'brain_example' }]));
+ });
+
+ test('host, port, database, scheme and brain selection remain pinned', () => {
+ const original = attendanceRepairConnectionIdentity('host', connection());
+ for (const target of ['postgresql://other.example.invalid:5432/brain_example',
+ 'postgresql://db.example.invalid:6543/brain_example', 'postgresql://db.example.invalid:5432/other_example',
+ 'postgres://db.example.invalid:5432/brain_example']) {
+ expect(attendanceRepairConnectionIdentity('host', connection(target))).not.toBe(original);
+ }
+ expect(attendanceRepairConnectionIdentity('other-brain', connection())).not.toBe(original);
+ });
+
+ test('PGLite pins only its resolved path and selected brain, not unused connection settings', () => {
+ const original = attendanceRepairConnectionIdentity('host', { engine: 'pglite', database_path: './example/../brain.pglite' });
+ expect(attendanceRepairConnectionIdentity('host', { ...connection(undefined, true), engine: 'pglite',
+ database_path: resolve('brain.pglite') })).toBe(original);
+ expect(original).toBe(attendanceRepairHash(['host', { engine: 'pglite', path: resolve('brain.pglite') }]));
+ expect(attendanceRepairConnectionIdentity('host', { engine: 'pglite', database_path: './other.pglite' })).not.toBe(original);
+ expect(attendanceRepairConnectionIdentity('other-brain', { engine: 'pglite', database_path: './brain.pglite' })).not.toBe(original);
+ });
+
+ test('multihost and IPv6 targets have distinct normalized identities without credential input', () => {
+ const url = 'postgresql://first.example.invalid:5433,[2001:db8::1]:5434/brain_example';
+ const original = attendanceRepairConnectionIdentity('host', { engine: 'postgres', database_url: url });
+ const withCredentials = url.replace('://', '://operator_example:synthetic-rotation@') + '?sslpassword=synthetic-query';
+ expect(attendanceRepairConnectionIdentity('host', { engine: 'postgres', database_url: withCredentials })).toBe(original);
+ expect(original).toBe(attendanceRepairHash(['host', { engine: 'postgres', scheme: 'postgresql:',
+ hosts: [['first.example.invalid', 5433], ['[2001:db8::1]', 5434]], database: 'brain_example' }]));
+ const targets = [url, url.replace('first.example', 'second.example'), url.replace('::1', '::2'),
+ url.replace(':5434', ':5435'), url.replace('brain_example', 'other_example'),
+ 'postgresql://[2001:db8::1]:5434/brain_example', 'postgresql://[2001:db8::2]:5434/brain_example'];
+ expect(new Set(targets.map(database_url => attendanceRepairConnectionIdentity('host', { engine: 'postgres', database_url }))).size)
+ .toBe(targets.length);
+ });
+
+ test('a missing multihost port follows the driver first-host default', () => {
+ expect(attendanceRepairConnectionIdentity('host', { engine: 'postgres',
+ database_url: 'postgresql://first.example.invalid:5433,second.example.invalid/brain_example' }))
+ .toBe(attendanceRepairConnectionIdentity('host', { engine: 'postgres',
+ database_url: 'postgresql://first.example.invalid:5433,second.example.invalid:5433/brain_example' }));
+ });
+
+ test.each(['not-a-url', 'https://db.example.invalid/brain_example', 'postgresql:///brain_example',
+ 'postgresql://db.example.invalid', 'postgresql://db.example.invalid/', 'postgresql://db.example.invalid:99999/brain_example',
+ 'postgresql://[invalid-ipv6]/brain_example', 'postgresql://first.example.invalid,,second.example.invalid/brain_example',
+ 'postgresql://%2Fvar%2Frun/brain_example', 'postgresql://db.example.invalid/brain_example?database=other_example',
+ 'postgresql://db.example.invalid/brain_example#fragment'])('malformed or unsupported targets refuse: %s', database_url => {
+ expect(() => attendanceRepairConnectionIdentity('host', { engine: 'postgres', database_url }))
+ .toThrow('Attendance repair requires a supported explicit PostgreSQL endpoint and database');
+ });
+
+ test('refusal messages never echo credential-bearing input', () => {
+ const database_url = 'postgresql://operator_example:[email protected]:99999/brain_example?sslpassword=synthetic-query';
+ try {
+ attendanceRepairConnectionIdentity('host', { engine: 'postgres', database_url });
+ throw new Error('expected refusal');
+ } catch (error) {
+ expect((error as Error).message).toBe('Attendance repair requires a supported explicit PostgreSQL endpoint and database');
+ }
+ expect(() => attendanceRepairConnectionIdentity('host', { engine: 'pglite' })).toThrow('explicit PGLite path');
+ });
+});
diff --git a/test/attendance-repair.test.ts b/test/attendance-repair.test.ts
new file mode 100644
index 0000000000..5517b852da
--- /dev/null
+++ b/test/attendance-repair.test.ts
@@ -0,0 +1,791 @@
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { previewAttendanceRepair, applyAttendanceRepair, attendanceRepairHash, type AttendanceRepairPreview } from '../src/core/attendance-repair.ts';
+import { __setPackLocatorForTests, _resetPackLocatorForTests, _resetPackCacheForTests } from '../src/core/schema-pack/index.ts';
+import { bundledPackPath } from '../src/core/schema-pack/bundled-assets.ts';
+import { makeResolver } from '../src/core/link-extraction.ts';
+import { softDeleteSource, restoreSource } from '../src/core/destructive-guard.ts';
+import { purgeStaleCheckpoints } from '../src/core/op-checkpoint.ts';
+import { attendanceRepairConnectionIdentity } from '../src/commands/extract-attendance-repair.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+const sourceId = 'repair-fixture';
+const person = 'people/alice-example';
+const meeting = 'meetings/planning';
+const positive = 'Attendees: [Alice Example](../people/alice-example.md)';
+const pack = { api_version: 'gbrain-schema-pack-v1', name: 'repair-fixture', version: '1.0.0', extends: null,
+ page_types: [], link_types: [], frontmatter_links: [] };
+
+for (const kind of ['pglite', ...(process.env.DATABASE_URL ? ['postgres'] : [])]) {
+ describe(`preview-bound attendance repair (${kind}; repair-fixture non-overridden person_to_meeting)`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ let root: string;
+ let checkpoints: unknown[];
+ beforeAll(async () => {
+ root = mkdtempSync(join(tmpdir(), 'gbrain-repair-'));
+ writeFileSync(join(root, 'pack.json'), JSON.stringify(pack));
+ __setPackLocatorForTests(name => name === pack.name ? join(root, 'pack.json') : bundledPackPath(name));
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else {
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+ close = () => engine.disconnect();
+ }
+ }, 120_000);
+ afterAll(async () => {
+ await close?.(); rmSync(root, { recursive: true, force: true });
+ _resetPackLocatorForTests(); _resetPackCacheForTests();
+ });
+ beforeEach(async () => {
+ checkpoints = [];
+ writeFileSync(join(root, 'pack.json'), JSON.stringify(pack));
+ _resetPackCacheForTests();
+ await engine.setConfig('schema_pack', pack.name);
+ await engine.executeRaw('DELETE FROM sources WHERE id=$1', [sourceId]);
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES ($1,$1)', [sourceId]);
+ await seed(person, 'person', 'Example person');
+ await seed(meeting, 'meeting', positive);
+ });
+ async function seed(slug: string, type: string, body: string, frontmatter: Record<string, unknown> = {}) {
+ await engine.putPage(slug, { type, title: slug, compiled_truth: body, frontmatter }, { sourceId, allowEmptyOverwrite: true });
+ }
+ async function legacy(producer: string | null = 'markdown') {
+ await engine.executeRaw(`INSERT INTO links(from_page_id,to_page_id,link_type,context,link_source)
+ SELECT f.id,t.id,'attended','old evidence',$3 FROM pages f,pages t
+ WHERE f.source_id=$1 AND t.source_id=$1 AND f.slug=$2 AND t.slug=$4`, [sourceId, meeting, producer, person]);
+ }
+ async function rows() {
+ return engine.executeRaw(`SELECT l.* FROM links l JOIN pages p ON p.id=l.from_page_id WHERE p.source_id=$1 ORDER BY l.id`, [sourceId]);
+ }
+ function preview(opts: { limit?: number; afterSlug?: string } = {}) {
+ return previewAttendanceRepair(engine, { sourceId, remote: false, ...opts });
+ }
+ function apply(receipt: AttendanceRepairPreview, extra: Record<string, unknown> = {}) {
+ return applyAttendanceRepair(engine, receipt, { remote: false, sourceId, yes: true, backupVerified: true,
+ confirm: receipt.digest, checkpoint: async state => { checkpoints.push(state); }, ...extra });
+ }
+
+ test('preview is read-only, omits source text, and exact delta preserves unrelated IDs and evidence', async () => {
+ await legacy();
+ await engine.addLink(meeting, person, 'unrelated evidence', 'mentions', 'markdown', undefined, undefined, { fromSourceId: sourceId, toSourceId: sourceId });
+ await engine.addLink(person, meeting, 'manual evidence', 'attended', 'manual', undefined, undefined, { fromSourceId: sourceId, toSourceId: sourceId });
+ const before = await rows();
+ const pages = await engine.executeRaw('SELECT * FROM pages WHERE source_id=$1 ORDER BY id', [sourceId]);
+ const guards = await engine.executeRaw('SELECT * FROM page_write_guards ORDER BY source_incarnation,slug');
+ const cp = await engine.executeRaw('SELECT * FROM op_checkpoints ORDER BY op,fingerprint');
+ const receipt = await preview();
+ expect(receipt.counts).toMatchObject({ scanned: 2, eligibleOrigins: 1, changed: 1, add: 1, remove: 1 });
+ expect(receipt.direction).toBe('person_to_meeting');
+ expect(JSON.stringify(receipt)).not.toContain('old evidence');
+ expect(JSON.stringify(receipt)).not.toContain(positive);
+ expect(await rows()).toEqual(before);
+ expect(await engine.executeRaw('SELECT * FROM pages WHERE source_id=$1 ORDER BY id', [sourceId])).toEqual(pages);
+ expect(await engine.executeRaw('SELECT * FROM page_write_guards ORDER BY source_incarnation,slug')).toEqual(guards);
+ expect(await engine.executeRaw('SELECT * FROM op_checkpoints ORDER BY op,fingerprint')).toEqual(cp);
+ expect(await apply(receipt)).toMatchObject({ created: 1, removed: 1, committed: 1 });
+ expect(checkpoints).toHaveLength(2);
+ expect(checkpoints.at(-1)).toMatchObject({ committed: 1, pagesProcessed: 2, afterSlug: person });
+ const after = await rows();
+ expect(after.filter(row => row.link_source === 'manual' || row.link_type === 'mentions'))
+ .toEqual(before.filter(row => row.link_source === 'manual' || row.link_type === 'mentions'));
+ expect(await engine.executeRaw('SELECT * FROM pages WHERE source_id=$1 ORDER BY id', [sourceId])).toEqual(pages);
+ });
+
+ for (const body of [
+ `${positive} <!-- [Hidden](../people/hidden-example.md) -->`,
+ '## Attendees\n- [Alice Example](../people/alice-example.md) <!-- [Hidden](../people/hidden-example.md) -->',
+ ]) test(`repair never approves or persists inline-commented attendance: ${JSON.stringify(body)}`, async () => {
+ await seed('people/hidden-example', 'person', 'Not an attendee.');
+ await seed(meeting, 'meeting', body);
+ const receipt = await preview();
+ expect(receipt.counts.add).toBe(1);
+ expect(await apply(receipt)).toMatchObject({ created: 1, removed: 0 });
+ expect((await engine.getBacklinks(meeting, { sourceId })).map(row => row.from_slug)).toEqual([person]);
+ });
+
+ test('second request and new preview are row-identity idempotent', async () => {
+ await legacy();
+ const receipt = await preview(); await apply(receipt);
+ const after = await rows();
+ expect(await apply(receipt)).toMatchObject({ created: 0, removed: 0, replayed: 1 });
+ const again = await preview();
+ expect(again.counts).toMatchObject({ add: 0, remove: 0, unchanged: 1 });
+ await apply(again);
+ expect(await rows()).toEqual(after);
+ });
+
+ test('receipts are credential-independent while cloned endpoint and brain pins remain distinct', async () => {
+ await legacy();
+ const url = new URL('postgresql://db.example.invalid:5432/brain_example');
+ url.username = 'operator_example'; url.password = 'synthetic-original';
+ url.searchParams.set('sslpassword', 'synthetic-query-original');
+ const firstIdentity = attendanceRepairConnectionIdentity('host', { engine: 'postgres', database_url: url.toString() });
+ const receipt = await previewAttendanceRepair(engine, { sourceId, remote: false, brainIdentity: firstIdentity });
+ url.username = 'rotated_example'; url.password = 'synthetic-rotation';
+ url.searchParams.set('sslpassword', 'synthetic-query-rotation');
+ const rotatedIdentity = attendanceRepairConnectionIdentity('host', { engine: 'postgres', database_url: url.toString() });
+ const rotated = await previewAttendanceRepair(engine, { sourceId, remote: false, brainIdentity: rotatedIdentity });
+ const { approvalId, issuedAt, digest, ...stable } = receipt;
+ const { approvalId: rotatedApprovalId, issuedAt: rotatedIssuedAt, digest: rotatedDigest, ...rotatedStable } = rotated;
+ expect(rotatedStable).toEqual(stable);
+ expect(rotatedApprovalId).not.toBe(approvalId); expect(rotatedDigest).not.toBe(digest);
+ expect(rotatedIssuedAt).toBeGreaterThanOrEqual(issuedAt);
+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation FROM sources WHERE id='default'");
+ const target = { engine: 'postgres', scheme: 'postgresql:', hosts: [['db.example.invalid', 5432]], database: 'brain_example' };
+ expect(receipt.brain).toBe(attendanceRepairHash([attendanceRepairHash(incarnation), attendanceRepairHash(['host', target])]));
+ for (const secret of ['operator_example', 'rotated_example', 'synthetic-original', 'synthetic-rotation',
+ 'synthetic-query-original', 'synthetic-query-rotation']) expect(JSON.stringify(receipt)).not.toContain(secret);
+ url.hostname = 'cloned.example.invalid';
+ const clonedIdentity = attendanceRepairConnectionIdentity('host', { engine: 'postgres', database_url: url.toString() });
+ await expect(apply(receipt, { brainIdentity: clonedIdentity })).rejects.toThrow('brain or ontology changed');
+ await expect(apply(receipt, { brainIdentity: attendanceRepairConnectionIdentity('other-brain', {
+ engine: 'postgres', database_url: url.toString() }) })).rejects.toThrow('brain or ontology changed');
+ expect(checkpoints).toHaveLength(0);
+ expect(await apply(receipt, { brainIdentity: rotatedIdentity })).toMatchObject({ created: 1, removed: 1 });
+ });
+
+ test('global seven-day pruning expires replay proof and requires a fresh preview without changing graph rows', async () => {
+ await legacy(); const receipt = await preview(); await apply(receipt); const before = await rows();
+ await engine.executeRaw("UPDATE op_checkpoints SET updated_at=now()-interval '8 days' WHERE op='attendance-repair' AND fingerprint=$1",
+ [attendanceRepairHash([receipt.digest, receipt.origins[0].page.id])]);
+ expect(await purgeStaleCheckpoints(engine)).toBeGreaterThanOrEqual(1);
+ checkpoints = [];
+ await expect(apply(receipt)).rejects.toThrow('Attendance edges or resolution changed');
+ expect(await rows()).toEqual(before); expect(checkpoints).toHaveLength(0);
+ const fresh = await preview(); expect(fresh.counts).toMatchObject({ add: 0, remove: 0, unchanged: 1 });
+ expect(await apply(fresh)).toMatchObject({ created: 0, removed: 0 });
+ expect(await rows()).toEqual(before);
+ });
+
+ for (const state of ['changed', 'no-op', 'report-only']) for (const proof of ['retained', 'pruned']) {
+ test(`${proof} expired proof refuses ${state} replay and fresh approval recovers without renewing old proof`, async () => {
+ if (state === 'changed') await legacy();
+ else if (state === 'no-op') await apply(await preview());
+ else { await engine.setConfig('schema_pack', 'company-brain'); await legacy(); }
+ const receipt = await preview();
+ await apply(receipt);
+ const before = await rows();
+ const originalKey = attendanceRepairHash([receipt.digest, receipt.origins[0].page.id]);
+ if (proof === 'pruned') {
+ receipt.issuedAt = Date.now() - 8 * 86400_000;
+ receipt.digest = attendanceRepairHash({ ...receipt, digest: '' });
+ }
+ const key = attendanceRepairHash([receipt.digest, receipt.origins[0].page.id]);
+ await engine.executeRaw("UPDATE op_checkpoints SET fingerprint=$2, updated_at=now()-interval '8 days' WHERE op='attendance-repair' AND fingerprint=$1",
+ [originalKey, key]);
+ if (proof === 'pruned') expect(await purgeStaleCheckpoints(engine)).toBeGreaterThanOrEqual(1);
+ const oldProof = await engine.executeRaw("SELECT * FROM op_checkpoints WHERE op='attendance-repair' AND fingerprint=$1", [key]);
+ checkpoints = [];
+ await expect(apply(receipt)).rejects.toThrow('expired');
+ expect(checkpoints).toHaveLength(0); expect(await rows()).toEqual(before);
+ const fresh = await preview();
+ expect(fresh.digest).not.toBe(receipt.digest);
+ expect(await apply(fresh)).toMatchObject({ created: 0, removed: 0, replayed: 0 });
+ expect(await apply(fresh)).toMatchObject({ created: 0, removed: 0, replayed: 1 });
+ expect(await rows()).toEqual(before);
+ expect(await engine.executeRaw("SELECT * FROM op_checkpoints WHERE op='attendance-repair' AND fingerprint=$1", [key])).toEqual(oldProof);
+ });
+ }
+
+ test('valid replay never refreshes durable proof age or row content', async () => {
+ const receipt = await preview(); await apply(receipt);
+ const key = attendanceRepairHash([receipt.digest, receipt.origins[0].page.id]);
+ await engine.executeRaw("UPDATE op_checkpoints SET updated_at=now()-interval '6 days' WHERE op='attendance-repair' AND fingerprint=$1", [key]);
+ const before = await engine.executeRaw("SELECT * FROM op_checkpoints WHERE op='attendance-repair' AND fingerprint=$1", [key]);
+ expect(await apply(receipt)).toMatchObject({ replayed: 1 });
+ expect(await engine.executeRaw("SELECT * FROM op_checkpoints WHERE op='attendance-repair' AND fingerprint=$1", [key])).toEqual(before);
+ });
+
+ for (const noOrigins of [false, true]) test(`expired first approval refuses before writes or cursor progress with zero origins=${noOrigins}`, async () => {
+ if (noOrigins) await seed('a-prefix/example', 'concept', 'Skipped page');
+ const receipt = await preview({ limit: 1 });
+ receipt.issuedAt = Date.now() - 8 * 86400_000;
+ receipt.digest = attendanceRepairHash({ ...receipt, digest: '' });
+ const before = await rows();
+ await expect(apply(receipt)).rejects.toThrow('expired');
+ expect(checkpoints).toHaveLength(0); expect(await rows()).toEqual(before);
+ expect((await apply(await preview({ limit: 1 }))).pagesProcessed).toBe(1);
+ });
+
+ test('fresh approvals recover a pruned no-op window and continue into the next window', async () => {
+ await seed('meetings/second', 'meeting', positive);
+ const first = await preview({ limit: 1 });
+ await apply(first);
+ const noOp = await preview({ limit: 1 }); await apply(noOp);
+ noOp.issuedAt = Date.now() - 8 * 86400_000;
+ const oldKey = attendanceRepairHash([noOp.digest, noOp.origins[0].page.id]);
+ noOp.digest = attendanceRepairHash({ ...noOp, digest: '' });
+ await engine.executeRaw("UPDATE op_checkpoints SET fingerprint=$2, updated_at=now()-interval '8 days' WHERE op='attendance-repair' AND fingerprint=$1",
+ [oldKey, attendanceRepairHash([noOp.digest, noOp.origins[0].page.id])]);
+ await purgeStaleCheckpoints(engine);
+ await expect(apply(noOp)).rejects.toThrow('expired');
+ const fresh = await preview({ limit: 1 });
+ expect(await apply(fresh)).toMatchObject({ created: 0, removed: 0, replayed: 0, afterSlug: meeting });
+ const next = await preview({ limit: 1, afterSlug: fresh.nextAfterSlug });
+ expect(next.approvalId).not.toBe(fresh.approvalId);
+ expect(await apply(next)).toMatchObject({ created: 1, removed: 0, afterSlug: 'meetings/second' });
+ expect(await apply(next)).toMatchObject({ created: 0, removed: 0, replayed: 1 });
+ });
+
+ test('approval lifetime is rechecked inside every origin transaction before advancing its cursor', async () => {
+ await seed('meetings/second', 'meeting', positive);
+ const receipt = await preview();
+ const transaction = engine.transaction;
+ let transactions = 0;
+ engine.transaction = (async function<T>(this: BrainEngine, fn: (tx: BrainEngine) => Promise<T>) {
+ return transaction.call(this, async tx => {
+ transactions++;
+ const executeRaw = tx.executeRaw;
+ tx.executeRaw = (async function(sql: string, params?: unknown[]) {
+ return executeRaw.call(tx, transactions > 1 && sql.includes('AS checked_at')
+ ? sql.replace('clock_timestamp()', "(clock_timestamp()+interval '8 days')") : sql, params);
+ }) as BrainEngine['executeRaw'];
+ try { return await fn(tx); } finally { tx.executeRaw = executeRaw; }
+ });
+ }) as BrainEngine['transaction'];
+ try { await expect(apply(receipt)).rejects.toThrow('approval expired'); }
+ finally { engine.transaction = transaction; }
+ expect(transactions).toBe(2);
+ expect(checkpoints).toHaveLength(1);
+ expect(checkpoints[0]).toMatchObject({ committed: 1, afterSlug: meeting });
+ expect(await rows()).toHaveLength(1);
+ });
+
+ test('approval identity and issuance validation rejects malformed, future and legacy receipts without writes', async () => {
+ const receipt = await preview();
+ const before = await rows();
+ for (const change of [
+ { approvalId: undefined }, { approvalId: 'x'.repeat(100_000) }, { approvalId: 42 }, { approvalId: 'not-a-uuid' },
+ { issuedAt: undefined }, { issuedAt: '1' }, { issuedAt: NaN }, { issuedAt: Infinity }, { issuedAt: 0 },
+ { issuedAt: -1 }, { issuedAt: 1.5 }, { issuedAt: Number.MAX_SAFE_INTEGER }, { version: 1 },
+ ]) {
+ const malformed = { ...receipt, ...change } as AttendanceRepairPreview;
+ malformed.digest = attendanceRepairHash({ ...malformed, digest: '' });
+ await expect(apply(malformed)).rejects.toThrow('identity mismatch');
+ }
+ const future = { ...receipt, issuedAt: receipt.issuedAt + 86400_000 };
+ future.digest = attendanceRepairHash({ ...future, digest: '' });
+ await expect(apply(future)).rejects.toThrow('not yet valid');
+ expect(checkpoints).toHaveLength(0); expect(await rows()).toEqual(before);
+ expect(await apply(receipt)).toMatchObject({ created: 1, removed: 0, replayed: 0 });
+ });
+
+ for (const producer of [null, 'manual', 'custom-producer']) {
+ test(`preserves ${producer ?? 'NULL'} producer`, async () => {
+ await legacy(producer);
+ const before = await rows();
+ const receipt = await preview();
+ expect(receipt.counts.remove).toBe(0);
+ await apply(receipt);
+ expect((await rows()).filter(row => row.link_source === producer)).toEqual(before);
+ });
+ }
+
+ for (const body of ['Mentioned [Alice](../people/alice-example.md).', 'Invited [Alice](../people/alice-example.md).',
+ 'Attendees: [Alice](../people/alice-example.md) did not attend', 'No evidence']) {
+ test(`unproven legacy evidence is report-only: ${body}`, async () => {
+ await seed(meeting, 'meeting', body); await legacy();
+ const before = await rows(); const receipt = await preview();
+ expect(receipt.counts).toMatchObject({ add: 0, remove: 0 });
+ expect(receipt.diagnostics[0].reason).toBe('legacy_evidence_unproven');
+ await apply(receipt); expect(await rows()).toEqual(before);
+ });
+ }
+
+ test('frontmatter paths are report-only and never remove an existing frontmatter claim', async () => {
+ await seed(meeting, 'meeting', '', { attendees: [person] });
+ await engine.addLink(person, meeting, 'frontmatter evidence', 'attended', 'frontmatter', meeting, 'attendees',
+ { fromSourceId: sourceId, toSourceId: sourceId, originSourceId: sourceId });
+ const before = await rows();
+ const receipt = await preview();
+ expect(receipt.frontmatter).toBe('report_only');
+ expect(receipt.counts).toMatchObject({ add: 0, remove: 0 });
+ await apply(receipt);
+ expect(await rows()).toEqual(before);
+ await seed(meeting, 'meeting', 'No frontmatter left');
+ await apply(await preview()); expect(await rows()).toEqual(before);
+ });
+
+ test('ambiguous hinted slug forms skip the origin without removing legacy rows', async () => {
+ await seed('people/duc-example', 'person', 'One person');
+ await seed('people/đuc-example', 'person', 'Another person');
+ await seed(meeting, 'meeting', '', { attendees: ['Đuc Example'] }); await legacy();
+ const before = await rows(); const receipt = await preview();
+ expect(receipt.frontmatter).toBe('report_only');
+ expect(receipt.counts.remove).toBe(0);
+ await apply(receipt); expect(await rows()).toEqual(before);
+ });
+
+ test('title-only references remain report-only without a full-source resolver', async () => {
+ await engine.executeRaw('UPDATE pages SET title=$1 WHERE source_id=$2 AND slug=$3', ['Different Label', sourceId, person]);
+ await seed(meeting, 'meeting', '', { attendees: ['Different Label'] });
+ const receipt = await preview();
+ expect(receipt.frontmatter).toBe('report_only');
+ expect(receipt.counts).toMatchObject({ add: 0, remove: 0 });
+ });
+
+ test('same-slug foreign endpoints and other-origin attendance remain unchanged', async () => {
+ const foreign = 'repair-other';
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES ($1,$1) ON CONFLICT DO NOTHING', [foreign]);
+ await engine.putPage(person, { type: 'person', title: 'Foreign Example', compiled_truth: 'Foreign person' }, { sourceId: foreign });
+ await seed('meetings/other-origin', 'meeting', 'Other evidence');
+ await engine.addLink(person, meeting, 'other origin evidence', 'attended', 'frontmatter', 'meetings/other-origin', 'attendees',
+ { fromSourceId: sourceId, toSourceId: sourceId, originSourceId: sourceId });
+ await engine.addLink(meeting, person, 'foreign evidence', 'attended', 'manual', undefined, undefined,
+ { fromSourceId: sourceId, toSourceId: foreign });
+ await legacy();
+ const before = (await rows()).filter(row => row.link_source !== 'markdown');
+ const receipt = await preview();
+ await apply(receipt);
+ expect((await rows()).filter(row => row.link_source !== 'markdown')).toEqual(before);
+ expect(receipt.origins[0].endpoints.every(endpoint => endpoint.source_id === sourceId)).toBe(true);
+ await engine.executeRaw('DELETE FROM sources WHERE id=$1', [foreign]);
+ });
+
+ test('missing and non-person body targets are counted and never guessed', async () => {
+ await seed(person, 'concept', 'Not a person');
+ expect((await preview()).counts).toMatchObject({ add: 0, ambiguous: 1 });
+ await engine.executeRaw('DELETE FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, person]);
+ expect((await preview()).counts).toMatchObject({ add: 0, ambiguous: 1 });
+ });
+
+ test('ambiguous bare body evidence never deletes an owned claim', async () => {
+ await seed('duc-example', 'person', 'One person'); await seed('đuc-example', 'person', 'Another person');
+ await seed(meeting, 'meeting', 'Attendees: [[Đuc Example]]');
+ await engine.addLink('duc-example', meeting, 'preserved body evidence', 'attended', 'markdown', meeting, undefined,
+ { fromSourceId: sourceId, toSourceId: sourceId, originSourceId: sourceId });
+ const before = await rows(); const receipt = await preview();
+ expect(receipt.counts).toMatchObject({ add: 0, remove: 0, ambiguous: 1 });
+ await apply(receipt); expect(await rows()).toEqual(before);
+ });
+
+ test('hinted frontmatter names do not authorize a claim before or after another candidate appears', async () => {
+ await seed('people/duc-example', 'person', 'One person');
+ await seed(meeting, 'meeting', '', { attendees: ['Đuc Example'] });
+ const receipt = await preview(); expect(receipt.counts.add).toBe(0);
+ await seed('people/đuc-example', 'person', 'Another person');
+ await apply(receipt);
+ expect((await preview()).counts.add).toBe(0);
+ expect(await rows()).toEqual([]);
+ });
+
+ for (const field of ['title', 'aliases']) test(`slash-containing frontmatter with a conflicting ${field} never bypasses A1 uniqueness`, async () => {
+ await seed('people/other-example', 'person', 'Conflicting person', field === 'aliases' ? { aliases: [person.toUpperCase()] } : {});
+ if (field === 'title') await engine.executeRaw('UPDATE pages SET title=$1 WHERE source_id=$2 AND slug=$3',
+ [person.toUpperCase(), sourceId, 'people/other-example']);
+ expect(await makeResolver(engine, { mode: 'batch', sourceId }).resolveAttendance!(person, 'people')).toBeNull();
+ await seed(meeting, 'meeting', '', { attendees: [person] });
+ await engine.addLink(person, meeting, 'preserved field evidence', 'attended', 'frontmatter', meeting, 'attendees',
+ { fromSourceId: sourceId, toSourceId: sourceId, originSourceId: sourceId });
+ const before = await rows(); const receipt = await preview();
+ expect(receipt.frontmatter).toBe('report_only'); expect(receipt.counts).toMatchObject({ add: 0, remove: 0 });
+ await apply(receipt); expect(await rows()).toEqual(before);
+ });
+
+ test('pack-owned outgoing semantics are excluded and pinned', async () => {
+ writeFileSync(join(root, 'pack.json'), JSON.stringify({ ...pack, link_types: [{ name: 'attended' }],
+ frontmatter_links: [{ page_type: 'meeting', fields: ['attendees'], link_type: 'attended' }] }));
+ await legacy(); const before = await rows(); const receipt = await preview();
+ expect(receipt.counts.pack_semantics_preserved).toBe(1);
+ expect(receipt.direction).toBe('pack_semantics_preserved');
+ await apply(receipt); expect(await rows()).toEqual(before);
+ });
+
+ test('unavailable pack is not treated as permission for legacy fallback', async () => {
+ await engine.setConfig('schema_pack', 'unavailable-fixture'); await legacy();
+ const before = await rows(); const receipt = await preview();
+ expect(receipt.direction).toBe('pack_unavailable');
+ await apply(receipt); expect(await rows()).toEqual(before);
+ });
+
+ for (const name of ['gbrain-base', 'company-brain']) test(`${name} shipped outgoing attendance is report-only`, async () => {
+ await engine.setConfig('schema_pack', name); await legacy();
+ const before = await rows(); const receipt = await preview();
+ expect(receipt.pack).toBe(name); expect(receipt.direction).toBe('pack_semantics_preserved');
+ expect(receipt.counts).toMatchObject({ add: 0, remove: 0, pack_semantics_preserved: 1 });
+ await apply(receipt); expect(await rows()).toEqual(before);
+ });
+
+ for (const mutation of ['origin-edit', 'endpoint-edit', 'origin-delete', 'endpoint-delete', 'origin-recreate', 'endpoint-recreate',
+ 'source-recreate', 'source-archive', 'source-archive-flag', 'ontology', 'ontology-file', 'edge-edit', 'edge-insert', 'edge-delete', 'edge-resolution', 'endpoint-type']) {
+ test(`${mutation} refuses stale preview without additional writes or checkpoint advance`, async () => {
+ await legacy(); const receipt = await preview();
+ const target = mutation.startsWith('origin') ? meeting : person;
+ if (mutation.endsWith('-edit') && mutation !== 'edge-edit') await seed(target, target === meeting ? 'meeting' : 'person', 'Changed');
+ else if (mutation.endsWith('-delete') && mutation !== 'edge-delete')
+ await engine.executeRaw('UPDATE pages SET deleted_at=now() WHERE source_id=$1 AND slug=$2', [sourceId, target]);
+ else if (mutation === 'origin-recreate' || mutation === 'endpoint-recreate') {
+ await engine.executeRaw('DELETE FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, target]);
+ await seed(target, target === meeting ? 'meeting' : 'person', target === meeting ? positive : 'Example person');
+ } else if (mutation === 'source-recreate') {
+ await engine.executeRaw('DELETE FROM sources WHERE id=$1', [sourceId]);
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES ($1,$1)', [sourceId]);
+ await seed(person, 'person', 'Example person'); await seed(meeting, 'meeting', positive);
+ } else if (mutation === 'source-archive') await engine.executeRaw('UPDATE sources SET archived_at=now() WHERE id=$1', [sourceId]);
+ else if (mutation === 'source-archive-flag') await engine.executeRaw('UPDATE sources SET archived=true, archived_at=NULL WHERE id=$1', [sourceId]);
+ else if (mutation === 'ontology') await engine.setConfig('schema_pack', 'unavailable-fixture');
+ else if (mutation === 'ontology-file') writeFileSync(join(root, 'pack.json'), JSON.stringify({ ...pack, version: '1.0.1' }));
+ else if (mutation === 'edge-edit') await engine.executeRaw('UPDATE links SET context=$1 WHERE id=$2', ['changed evidence', receipt.origins[0].before[0].id]);
+ else if (mutation === 'edge-delete') await engine.executeRaw('DELETE FROM links WHERE id=$1', [receipt.origins[0].before[0].id]);
+ else if (mutation === 'edge-insert') await legacy('manual');
+ else if (mutation === 'edge-resolution') await engine.executeRaw('UPDATE links SET resolution_type=$1 WHERE id=$2', ['qualified', receipt.origins[0].before[0].id]);
+ else if (mutation === 'endpoint-type') await seed(person, 'concept', 'Example concept');
+ const before = await rows();
+ await expect(apply(receipt)).rejects.toThrow();
+ expect(await rows()).toEqual(before); expect(checkpoints).toHaveLength(0);
+ });
+ }
+
+ for (const archivedId of [sourceId, 'default']) for (const phase of ['preview', 'apply']) {
+ test(`flag-only archived ${archivedId} refuses ${phase} without writes or checkpoint advance`, async () => {
+ await legacy(); const receipt = await preview(); const before = await rows();
+ const guards = await engine.executeRaw('SELECT * FROM page_write_guards ORDER BY source_incarnation,slug');
+ const cp = await engine.executeRaw('SELECT * FROM op_checkpoints ORDER BY op,fingerprint');
+ await engine.executeRaw('UPDATE sources SET archived=true, archived_at=NULL WHERE id=$1', [archivedId]);
+ try {
+ expect(await engine.executeRaw('SELECT archived, archived_at FROM sources WHERE id=$1', [archivedId]))
+ .toEqual([{ archived: true, archived_at: null }]);
+ await expect(phase === 'preview' ? preview() : apply(receipt)).rejects.toThrow(
+ `Attendance repair requires an existing live source and brain identity: ${archivedId === 'default'
+ ? "literal 'default' identity source" : `selected source '${archivedId}'`} is missing or archived`);
+ expect(await rows()).toEqual(before); expect(checkpoints).toHaveLength(0);
+ expect(await engine.executeRaw('SELECT * FROM page_write_guards ORDER BY source_incarnation,slug')).toEqual(guards);
+ expect(await engine.executeRaw('SELECT * FROM op_checkpoints ORDER BY op,fingerprint')).toEqual(cp);
+ } finally {
+ await engine.executeRaw('UPDATE sources SET archived=false WHERE id=$1', [archivedId]);
+ }
+ });
+ }
+
+ test('ordinary archive and restore lifecycle refuses repair while archived and permits a fresh preview after restore', async () => {
+ await legacy(); const receipt = await preview(); const before = await rows();
+ expect(await softDeleteSource(engine, sourceId)).toMatchObject({ id: sourceId, pageCount: 2 });
+ expect(await engine.executeRaw('SELECT archived, archived_at IS NOT NULL AS timestamped FROM sources WHERE id=$1', [sourceId]))
+ .toEqual([{ archived: true, timestamped: true }]);
+ await expect(preview()).rejects.toThrow('existing live source and brain identity');
+ await expect(apply(receipt)).rejects.toThrow('existing live source and brain identity');
+ expect(await rows()).toEqual(before); expect(checkpoints).toHaveLength(0);
+ expect(await restoreSource(engine, sourceId)).toBe(true);
+ expect(await engine.executeRaw('SELECT archived, archived_at FROM sources WHERE id=$1', [sourceId]))
+ .toEqual([{ archived: false, archived_at: null }]);
+ const restored = await preview();
+ expect(restored.counts).toMatchObject({ add: 1, remove: 1 });
+ expect(await apply(restored)).toMatchObject({ created: 1, removed: 1, committed: 1 });
+ });
+
+ test('parser and digest mismatch refuse before any transaction', async () => {
+ const receipt = await preview();
+ const staleParser = { ...receipt, parser: 'old-parser' };
+ staleParser.digest = attendanceRepairHash({ ...staleParser, digest: '' });
+ await expect(apply(staleParser)).rejects.toThrow('identity mismatch');
+ await expect(apply(receipt, { confirm: '0'.repeat(64) })).rejects.toThrow('identity mismatch');
+ await expect(apply(receipt, { brainIdentity: 'other-connection' })).rejects.toThrow();
+ expect(await rows()).toEqual([]);
+ });
+
+ test('failed insertion rolls back deletion and durable receipt', async () => {
+ await legacy(); const receipt = await preview(); const before = await rows();
+ await engine.executeRaw(`CREATE FUNCTION repair_fixture_reject() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN
+ RAISE EXCEPTION 'fixture insertion rejection'; END $$`);
+ await engine.executeRaw('CREATE TRIGGER repair_fixture_reject BEFORE INSERT ON links FOR EACH ROW EXECUTE FUNCTION repair_fixture_reject()');
+ try { await expect(apply(receipt)).rejects.toThrow(); }
+ finally {
+ await engine.executeRaw('DROP TRIGGER repair_fixture_reject ON links');
+ await engine.executeRaw('DROP FUNCTION repair_fixture_reject()');
+ }
+ expect(await rows()).toEqual(before); expect(checkpoints).toHaveLength(0);
+ expect(await apply(receipt)).toMatchObject({ created: 1, removed: 1, replayed: 0 });
+ });
+
+ test('database read-only permissions refuse apply without a checkpoint or row changes', async () => {
+ await legacy(); const receipt = await preview(); const before = await rows();
+ const transaction = engine.transaction;
+ engine.transaction = (async function<T>(this: BrainEngine, fn: (tx: BrainEngine) => Promise<T>) {
+ return transaction.call(this, async tx => {
+ await tx.executeRaw('SET TRANSACTION READ ONLY');
+ return fn(tx);
+ });
+ }) as BrainEngine['transaction'];
+ try { await expect(apply(receipt)).rejects.toThrow(); }
+ finally { engine.transaction = transaction; }
+ expect(await rows()).toEqual(before); expect(checkpoints).toHaveLength(0);
+ });
+
+ if (kind === 'postgres') test('a separate PostgreSQL reader sees a consistent graph while the repair holds write fences', async () => {
+ await legacy(); const receipt = await preview(); const before = await rows();
+ const transaction = engine.transaction;
+ let readDuringCommit = false;
+ engine.transaction = (async function<T>(this: BrainEngine, fn: (tx: BrainEngine) => Promise<T>) {
+ return transaction.call(this, async tx => {
+ const result = await fn(tx);
+ if (!readDuringCommit) { expect(await rows()).toEqual(before); readDuringCommit = true; }
+ return result;
+ });
+ }) as BrainEngine['transaction'];
+ try { await apply(receipt); }
+ finally { engine.transaction = transaction; }
+ expect(readDuringCommit).toBe(true); expect(await rows()).not.toEqual(before);
+ }, 20_000);
+
+ test('interruption after commit before cursor safely replays the committed origin', async () => {
+ await legacy(); const receipt = await preview();
+ await expect(apply(receipt, { checkpoint: async () => { throw new Error('interrupted before cursor'); } })).rejects.toThrow('interrupted');
+ const after = await rows();
+ expect(await apply(receipt)).toMatchObject({ created: 0, removed: 0, replayed: 1 });
+ expect(await rows()).toEqual(after);
+ });
+
+ for (const reason of ['pack_semantics_preserved', 'pack_unavailable', 'origin_size_limit', 'edge_limit', 'edge_size_limit', 'reference_limit']) {
+ test(`report-only ${reason} with existing edges replays a commit before private checkpoint progress`, async () => {
+ await legacy();
+ if (reason === 'pack_semantics_preserved') await engine.setConfig('schema_pack', 'company-brain');
+ if (reason === 'pack_unavailable') await engine.setConfig('schema_pack', 'unavailable-fixture');
+ if (reason === 'origin_size_limit') await seed(meeting, 'meeting', 'x'.repeat(256 * 1024 + 1));
+ if (reason === 'edge_limit') await engine.executeRaw(`INSERT INTO links(from_page_id,to_page_id,link_type,link_source)
+ SELECT f.id,t.id,'related-'||n,'markdown' FROM pages f,pages t,generate_series(1,600) n
+ WHERE f.source_id=$1 AND t.source_id=$1 AND f.slug=$2 AND t.slug=$3`, [sourceId, meeting, person]);
+ if (reason === 'edge_size_limit') await engine.executeRaw(`UPDATE links SET context=repeat('x',1048576)
+ WHERE from_page_id=(SELECT id FROM pages WHERE source_id=$1 AND slug=$2)`, [sourceId, meeting]);
+ if (reason === 'reference_limit') await seed(meeting, 'meeting', `Attendees: ${Array.from({ length: 257 }, (_, i) => `[Example](../people/example-${i}.md)`).join(', ')}`);
+ const before = await rows(); const receipt = await preview();
+ expect(receipt.origins[0].reason).toBe(reason);
+ expect(receipt.counts).toMatchObject({ add: 0, remove: 0 });
+ await expect(apply(receipt, { checkpoint: async () => { throw new Error('interrupted before private cursor'); } })).rejects.toThrow('interrupted');
+ expect(checkpoints).toHaveLength(0);
+ expect(await apply(receipt)).toMatchObject({ created: 0, removed: 0, replayed: 1 });
+ expect(await rows()).toEqual(before);
+ expect(receipt.origins[0].before.length).toBeLessThanOrEqual(512);
+ expect(receipt.origins[0].adjacentRows).toBeLessThanOrEqual(513);
+ expect(JSON.stringify(receipt).length).toBeLessThan(100_000);
+ });
+ }
+
+ test('mixed person and non-person explicit attendees leave the entire origin report-only', async () => {
+ await seed('concepts/example', 'concept', 'Not a person');
+ await seed(meeting, 'meeting', `${positive}, [Example concept](../concepts/example.md)`);
+ await legacy();
+ const before = await rows(); const receipt = await preview();
+ expect(receipt.origins[0].reason).toBe('unresolved_attendees');
+ expect(receipt.counts).toMatchObject({ add: 0, remove: 0 });
+ await apply(receipt);
+ expect(await apply(receipt)).toMatchObject({ replayed: 1 });
+ expect(await rows()).toEqual(before);
+ });
+
+ test('interruption after cursor and failure at next origin never advances past failure', async () => {
+ await seed('meetings/second', 'meeting', positive);
+ const receipt = await preview();
+ await expect(apply(receipt, { checkpoint: async (state: unknown) => { checkpoints.push(state); throw new Error('interrupted after cursor'); } })).rejects.toThrow();
+ expect(checkpoints).toHaveLength(1);
+ await seed('meetings/second', 'meeting', 'Changed');
+ await expect(apply(receipt)).rejects.toThrow();
+ expect(checkpoints).toHaveLength(2);
+ expect((checkpoints[1] as { committed: number }).committed).toBe(1);
+ });
+
+ test('source recreation invalidates an already committed cursor', async () => {
+ const receipt = await preview(); await apply(receipt);
+ expect(checkpoints).toHaveLength(2);
+ await engine.executeRaw('DELETE FROM sources WHERE id=$1', [sourceId]);
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES ($1,$1)', [sourceId]);
+ await seed(person, 'person', 'Example person'); await seed(meeting, 'meeting', positive);
+ await expect(apply(receipt)).rejects.toThrow('source, brain or ontology changed');
+ expect(checkpoints).toHaveLength(2); expect(await rows()).toEqual([]);
+ });
+
+ test('committed edge recreation is not accepted as idempotent replay', async () => {
+ const receipt = await preview(); await apply(receipt);
+ const [edge] = await rows();
+ await engine.executeRaw('DELETE FROM links WHERE id=$1', [edge.id]);
+ await engine.addLink(person, meeting, positive, 'attended', 'markdown', meeting, undefined,
+ { fromSourceId: sourceId, toSourceId: sourceId, originSourceId: sourceId });
+ await expect(apply(receipt)).rejects.toThrow('Committed attendance edges changed');
+ });
+
+ test('owned obsolete attendance alone is removed and its committed replay stays stable', async () => {
+ await apply(await preview());
+ await seed(meeting, 'meeting', 'No attendance evidence');
+ const receipt = await preview();
+ expect(receipt.counts).toMatchObject({ add: 0, remove: 1 });
+ await apply(receipt); expect(await rows()).toEqual([]);
+ expect(await apply(receipt)).toMatchObject({ replayed: 1 });
+ });
+
+ test('authority, source, confirmation and backup refusals happen without mutation', async () => {
+ const receipt = await preview();
+ for (const remote of [true, undefined, null]) {
+ await expect(previewAttendanceRepair(engine, { sourceId, remote: remote as boolean })).rejects.toThrow('trusted local');
+ await expect(apply(receipt, { remote })).rejects.toThrow('trusted local');
+ }
+ await expect(previewAttendanceRepair(engine, { sourceId: '', remote: false })).rejects.toThrow('explicit');
+ await expect(apply(receipt, { yes: false })).rejects.toThrow('--yes');
+ await expect(apply(receipt, { backupVerified: false })).rejects.toThrow('--backup-verified');
+ expect(await rows()).toEqual([]); expect(checkpoints).toHaveLength(0);
+ });
+
+ test('bounds reject invalid batches and cap retained diagnostics and source metadata', async () => {
+ for (const limit of [0, -1, 1001, 1.5, NaN, Infinity]) await expect(preview({ limit })).rejects.toThrow('1–1000');
+ for (let i = 0; i < 24; i++) await seed(`meetings/missing-${i}`, 'meeting', 'Attendees: [Missing](../people/missing-example.md)');
+ const original = engine.executeRaw;
+ const reads: string[] = [];
+ engine.executeRaw = (async (sql: string, params?: unknown[]) => {
+ reads.push(sql); return original.call(engine, sql, params);
+ }) as BrainEngine['executeRaw'];
+ let receipt: AttendanceRepairPreview;
+ try { receipt = await preview(); } finally { engine.executeRaw = original; }
+ expect(receipt.limit).toBe(250); expect(receipt.diagnostics).toHaveLength(20);
+ expect(receipt.origins.every(origin => origin.lookupSlugs.length <= 256)).toBe(true);
+ expect(reads.some(sql => /lower\(title\)|jsonb_array_elements_text|SELECT slug, source_id, type, title/.test(sql))).toBe(false);
+ const one = await preview({ limit: 1 });
+ expect(one.counts.scanned).toBe(1); expect(one.complete).toBe(false);
+ expect((await preview({ limit: 1000, afterSlug: one.nextAfterSlug })).counts.scanned).toBe(25);
+ });
+
+ test('oversized origins and reference sets are report-only', async () => {
+ await seed(meeting, 'meeting', 'x'.repeat(256 * 1024 + 1));
+ expect((await preview()).diagnostics[0].reason).toBe('origin_size_limit');
+ await seed(meeting, 'meeting', `Attendees: ${Array.from({ length: 257 }, (_, i) => `[Example](../people/example-${i}.md)`).join(', ')}`);
+ expect((await preview()).diagnostics[0].reason).toBe('reference_limit');
+ });
+
+ test('oversized bodies and edge evidence never cross the DB boundary, and frontmatter is not materialized', async () => {
+ await engine.executeRaw(`UPDATE pages SET compiled_truth=repeat('x',1048576),
+ frontmatter=jsonb_build_object('attendees',repeat('x',2097152)) WHERE source_id=$1 AND slug=$2`, [sourceId, meeting]);
+ const original = engine.executeRaw;
+ const originTransfers: Record<string, unknown>[] = [];
+ const statements: string[] = [];
+ engine.executeRaw = (async function(this: BrainEngine, sql: string, params?: unknown[]) {
+ statements.push(sql);
+ const result = await original.call(this, sql, params);
+ if (sql.includes('AS bytes')) originTransfers.push(...result as Record<string, unknown>[]);
+ return result;
+ }) as BrainEngine['executeRaw'];
+ try {
+ expect((await preview()).diagnostics[0].reason).toBe('origin_size_limit');
+ expect(originTransfers).toHaveLength(1);
+ expect(originTransfers[0]).toMatchObject({ compiled_truth: null, timeline: null, bytes: 1048576 });
+ expect(Object.hasOwn(originTransfers[0], 'frontmatter')).toBe(false);
+ expect(statements.some(sql => sql.includes('frontmatter'))).toBe(false);
+ } finally { engine.executeRaw = original; }
+ await seed(meeting, 'meeting', positive); await legacy();
+ await engine.executeRaw(`UPDATE links SET context=repeat('x',1048576), origin_field=repeat('y',1048576)
+ WHERE from_page_id=(SELECT id FROM pages WHERE source_id=$1 AND slug=$2)`, [sourceId, meeting]);
+ const receipt = await preview();
+ expect(receipt.diagnostics[0].reason).toBe('edge_size_limit');
+ expect(receipt.origins[0].before[0]).toMatchObject({ row_hash: null, origin_field: null });
+ expect(JSON.stringify(receipt).length).toBeLessThan(10_000);
+ await apply(receipt);
+ expect(receipt.counts).toMatchObject({ add: 0, remove: 0 });
+ });
+
+ test('large non-attendance adjacency cannot force an unbounded attendance scan', async () => {
+ await legacy();
+ await engine.executeRaw(`INSERT INTO links(from_page_id,to_page_id,link_type,link_source)
+ SELECT f.id,t.id,'related-'||n,'markdown' FROM pages f,pages t,generate_series(1,600) n
+ WHERE f.source_id=$1 AND t.source_id=$1 AND f.slug=$2 AND t.slug=$3`, [sourceId, meeting, person]);
+ const before = await rows(); const receipt = await preview();
+ expect(receipt.diagnostics[0].reason).toBe('edge_limit');
+ expect(receipt.origins[0].adjacentRows).toBe(513); expect(receipt.origins[0].before).toEqual([]);
+ expect(receipt.counts).toMatchObject({ add: 0, remove: 0 });
+ await apply(receipt); expect(await rows()).toEqual(before);
+ });
+
+ test('sparse windows include soft-deleted and nonmeeting pages before eligibility filtering', async () => {
+ await engine.executeRaw(`INSERT INTO pages(source_id,slug,type,title,compiled_truth,deleted_at)
+ SELECT $1,'a-sparse/'||lpad(n::text,4,'0'),CASE WHEN n%2=0 THEN 'meeting' ELSE 'concept' END,
+ 'Sparse Example','Fixture',CASE WHEN n%2=0 THEN now() ELSE NULL END
+ FROM generate_series(1,600) n`, [sourceId]);
+ const scans: number[] = []; const eligible: number[] = []; const seen: string[] = [];
+ let afterSlug = '';
+ for (let batch = 0; batch < 3; batch++) {
+ const receipt = await preview({ afterSlug });
+ scans.push(receipt.counts.scanned); eligible.push(receipt.counts.eligibleOrigins);
+ seen.push(...receipt.window.map(page => page.slug));
+ const applied = await apply(receipt);
+ expect(applied.pagesProcessed).toBe(receipt.window.length);
+ expect(checkpoints.at(-1)).toMatchObject({ afterSlug: receipt.nextAfterSlug, pagesProcessed: receipt.window.length });
+ expect((await apply(receipt)).created).toBe(0);
+ afterSlug = receipt.nextAfterSlug;
+ expect(receipt.complete).toBe(batch === 2);
+ }
+ expect(scans).toEqual([250, 250, 102]); expect(eligible).toEqual([0, 0, 1]);
+ expect(new Set(seen).size).toBe(602); expect(seen).toHaveLength(602);
+ const empty = await preview({ afterSlug });
+ expect(empty.counts).toMatchObject({ scanned: 0, eligibleOrigins: 0 }); expect(empty.complete).toBe(true);
+ expect((await apply(empty)).afterSlug).toBe(afterSlug);
+ }, 30_000);
+
+ test('cursor covers skipped prefixes but never crosses a failed origin or skipped tail', async () => {
+ await seed('a-prefix/example', 'concept', 'Skip prefix');
+ await seed('meetings/z-failure', 'meeting', positive);
+ await seed('zz-tail/example', 'concept', 'Skip tail');
+ const receipt = await preview();
+ await seed('meetings/z-failure', 'meeting', 'Changed after preview');
+ await expect(apply(receipt)).rejects.toThrow();
+ expect(checkpoints).toHaveLength(1);
+ expect(checkpoints[0]).toMatchObject({ committed: 1, pagesProcessed: 2, afterSlug: meeting });
+ await expect(apply(receipt)).rejects.toThrow();
+ expect(checkpoints).toHaveLength(2);
+ expect(checkpoints[1]).toMatchObject({ committed: 1, pagesProcessed: 2, afterSlug: meeting, replayed: 1 });
+ });
+
+ for (const change of ['source', 'ontology', 'skipped-page']) test(`zero-origin window refuses a stale ${change} before cursor advancement`, async () => {
+ await seed('a-prefix/example', 'concept', 'Skip prefix');
+ const receipt = await preview({ limit: 1 }); expect(receipt.counts.eligibleOrigins).toBe(0);
+ if (change === 'ontology') await engine.setConfig('schema_pack', 'unavailable-fixture');
+ else if (change === 'skipped-page') await seed('a-prefix/example', 'meeting', positive);
+ else {
+ await engine.executeRaw('DELETE FROM sources WHERE id=$1', [sourceId]);
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES ($1,$1)', [sourceId]);
+ }
+ await expect(apply(receipt)).rejects.toThrow(); expect(checkpoints).toHaveLength(0);
+ });
+
+ test('one-row slug windows traverse punctuation and Unicode in database order without duplicates', async () => {
+ for (const slug of ['topics/a-example', 'topics/a_example', 'topics/é-example', 'topics/z-example']) await seed(slug, 'concept', 'Fixture');
+ const expected = (await engine.executeRaw<{ slug: string }>('SELECT slug FROM pages WHERE source_id=$1 ORDER BY slug', [sourceId])).map(page => page.slug);
+ const seen: string[] = [];
+ let afterSlug = '';
+ for (let index = 0; index < expected.length; index++) {
+ const receipt = await preview({ limit: 1, afterSlug });
+ expect(receipt.window).toHaveLength(1); expect(receipt.complete).toBe(false);
+ seen.push(receipt.window[0].slug); afterSlug = receipt.nextAfterSlug;
+ expect((await apply(receipt)).afterSlug).toBe(afterSlug);
+ }
+ expect(seen).toEqual(expected);
+ const done = await preview({ limit: 1, afterSlug }); expect(done.complete).toBe(true); expect(done.window).toEqual([]);
+ });
+
+ test('default 250 and maximum 1000 page windows keep lookup work independent of a 10000-page source', async () => {
+ await engine.executeRaw(`INSERT INTO pages(source_id,slug,type,title,compiled_truth)
+ SELECT $1,'people/scale-'||n,'person','Scale Example '||n,'Example fixture' FROM generate_series(1,10000) n`, [sourceId]);
+ await engine.executeRaw(`INSERT INTO pages(source_id,slug,type,title,compiled_truth)
+ SELECT $1,'meetings/scale-'||n,'meeting','Scale Meeting '||n,$2 FROM generate_series(1,1000) n`, [sourceId, positive]);
+ const original = engine.executeRaw;
+ let endpointQueries = 0; let endpointRows = 0; let largestLookup = 0;
+ engine.executeRaw = (async function(this: BrainEngine, sql: string, params?: unknown[]) {
+ const result = await original.call(this, sql, params);
+ if (sql.includes('slug=ANY($2::text[])')) {
+ endpointQueries++; endpointRows += result.length; largestLookup = Math.max(largestLookup, (params?.[1] as string[]).length);
+ }
+ return result;
+ }) as BrainEngine['executeRaw'];
+ try {
+ const started = performance.now();
+ const small = await preview();
+ expect(small.counts.scanned).toBe(250); expect(small.complete).toBe(false);
+ expect(endpointQueries).toBe(250); expect(endpointRows).toBe(250); expect(largestLookup).toBe(1);
+ const large = await preview({ limit: 1000 });
+ expect(large.counts.scanned).toBe(1000); expect(large.complete).toBe(false);
+ expect(endpointQueries).toBe(1250); expect(endpointRows).toBe(1250); expect(largestLookup).toBe(1);
+ console.log(JSON.stringify({ fixture: 'attendance-repair-scale', engine: kind, sourcePages: 11002,
+ previewedOrigins: 1250, endpointQueries, endpointRows, largestLookup, elapsedMs: Math.round(performance.now() - started),
+ rssBytes: process.memoryUsage().rss }));
+ } finally { engine.executeRaw = original; }
+ }, 120_000);
+ });
+}
diff --git a/test/attendance-retrieval.test.ts b/test/attendance-retrieval.test.ts
new file mode 100644
index 0000000000..a4a99a41e3
--- /dev/null
+++ b/test/attendance-retrieval.test.ts
@@ -0,0 +1,942 @@
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { extractLinksForSlugs, runExtract, runExtractCore } from '../src/commands/extract.ts';
+import { prepareAutomaticLinks } from '../src/core/persistence/links-preparation.ts';
+import { disposePersistenceConsumer, persistenceConsumerStatus } from '../src/core/persistence/service.ts';
+import { runMaintenanceSweep } from '../src/core/sweep.ts';
+import { buildRelationalArm } from '../src/core/search/relational-recall.ts';
+import { extractPageLinks } from '../src/core/link-extraction.ts';
+import { extractLinksFromFile, extractStaleFromDB } from '../src/commands/extract.ts';
+import { operations } from '../src/core/operations.ts';
+import { parseSchemaPackManifest, __setPackLocatorForTests, _resetPackLocatorForTests, _resetPackCacheForTests } from '../src/core/schema-pack/index.ts';
+import { bundledPackPath } from '../src/core/schema-pack/bundled-assets.ts';
+import { loadActivePackForLocalEngine } from '../src/core/schema-pack/best-effort.ts';
+import { installFixtureChunks } from './helpers/page-projection.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+const sourceId = 'attendance-fixture';
+const person = 'people/alice-example';
+const meeting = 'meetings/planning';
+const positive = 'Attendees: [Alice](../people/alice-example.md)';
+
+for (const kind of ['pglite', ...(process.env.DATABASE_URL ? ['postgres'] : [])]) {
+ describe(`non-overridden canonical attendance lifecycle (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ let root: string;
+ let packRoot: string;
+ beforeAll(async () => {
+ if (kind === 'postgres') {
+ ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ } else {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ close = () => engine.disconnect();
+ }
+ root = mkdtempSync(join(tmpdir(), 'gbrain-attendance-'));
+ packRoot = mkdtempSync(join(tmpdir(), 'gbrain-attendance-pack-'));
+ await engine.setConfig('schema_pack', 'gbrain-base');
+ const base = (await loadActivePackForLocalEngine(engine))!.manifest;
+ writeFileSync(join(packRoot, 'pack.json'), JSON.stringify({ ...base, name: 'attendance-fixture', link_types: [], frontmatter_links: [] }));
+ __setPackLocatorForTests(name => name === 'attendance-fixture' ? join(packRoot, 'pack.json') : bundledPackPath(name));
+ await engine.setConfig('schema_pack', 'attendance-fixture');
+ await engine.setConfig('dream.synthesize.session_corpus_dir', root);
+ }, 120_000);
+ afterAll(async () => {
+ await close?.(); rmSync(root, { recursive: true, force: true }); rmSync(packRoot, { recursive: true, force: true });
+ _resetPackLocatorForTests(); _resetPackCacheForTests();
+ });
+ afterEach(async () => { await disposePersistenceConsumer(engine); });
+ beforeEach(async () => {
+ expect(persistenceConsumerStatus(engine).state).toBe('not_running');
+ rmSync(root, { recursive: true, force: true });
+ mkdirSync(root, { recursive: true });
+ await engine.setConfig('schema_pack', 'attendance-fixture');
+ await engine.setConfig(`schema_pack.source.${sourceId}`, '');
+ await engine.executeRaw('DELETE FROM sources WHERE id=$1', [sourceId]);
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES ($1,$1)', [sourceId]);
+ await seed(person, 'person', 'An example engineer.');
+ });
+ async function seed(slug: string, type: string, body: string, frontmatter: Record<string, unknown> = {}) {
+ await engine.putPage(slug, { type, title: slug, compiled_truth: body, frontmatter }, { sourceId });
+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: body || slug }], { sourceId });
+ const path = join(root, `${slug}.md`);
+ mkdirSync(dirname(path), { recursive: true });
+ const fields = Object.entries(frontmatter).map(([key, value]) => `${key}: ${JSON.stringify(value)}\n`).join('');
+ writeFileSync(path, `---\ntype: ${type}\ntitle: ${slug}\n${fields}---\n${body}`);
+ }
+ async function attendees() {
+ return (await buildRelationalArm(engine, 'Who attended meetings/planning?', { sourceId })).map(row => row.slug);
+ }
+ async function extract(lane: string, all = false) {
+ if (lane === 'db') {
+ const output = spyOn(console, 'log').mockImplementation(() => {});
+ try {
+ await runExtract(engine, [all ? 'all' : 'links', '--source', 'db', '--source-id', sourceId, '--json']);
+ return JSON.parse(output.mock.calls.at(-1)![0]);
+ } finally { output.mockRestore(); }
+ }
+ else if (lane === 'stale') return extractStaleFromDB(engine, { sourceIdFilter: sourceId, quiet: true, dryRun: false, jsonMode: false, catchUp: true });
+ else if (lane === 'fs-batch') return runExtractCore(engine, { mode: all ? 'all' : 'links', dir: root, sourceId, quiet: true });
+ else if (lane === 'fs-incremental') return runExtractCore(engine, { mode: all ? 'all' : 'links', dir: root, sourceId, slugs: [meeting, person], quiet: true });
+ else if (lane === 'fs-sync') return extractLinksForSlugs(engine, root, [meeting, person], { sourceId });
+ else if (lane === 'prepare') {
+ for (const slug of [meeting, person]) {
+ const page = (await engine.getPage(slug, { sourceId }))!;
+ const prepared = await prepareAutomaticLinks(engine, slug, page, sourceId);
+ await engine.transaction(async tx => { await tx.lockPageKeys(prepared.pageKeys); await prepared.apply(tx); });
+ }
+ } else return runMaintenanceSweep(engine, { sourceId, budgetMs: 60_000, batchLimit: 20,
+ 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 () => {
+ 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]);
+ });
+ test(`${lane}: unchanged DB-only attendance survives and real evidence removal retracts it`, async () => {
+ await seed(meeting, 'meeting', positive);
+ await extract('db');
+ rmSync(join(root, `${person}.md`));
+ await extract(lane);
+ expect(await attendees()).toEqual([person]);
+ await seed(meeting, 'meeting', 'The supported attendance evidence was removed.');
+ await extract(lane);
+ expect(await attendees()).toEqual([]);
+ });
+ }
+ for (const lane of ['fs-sync', 'fs-incremental', 'fs-batch', 'prepare', 'sweep', 'db', 'stale']) {
+ for (const [globalPack, sourcePack, incoming] of [
+ ['attendance-fixture', 'gbrain-base', false],
+ ['gbrain-base', 'attendance-fixture', true],
+ ['missing-example-pack', 'attendance-fixture', true],
+ ] as const) test(`${lane}: source-selected ${sourcePack} overrides global ${globalPack}`, async () => {
+ await engine.setConfig('schema_pack', globalPack);
+ await engine.setConfig(`schema_pack.source.${sourceId}`, sourcePack);
+ await seed(meeting, 'meeting', positive);
+ const exit = spyOn(process, 'exit').mockImplementation(code => { throw new Error(`Extraction exited with code ${code}`); });
+ try { await extract(lane, true); } finally { exit.mockRestore(); }
+ expect((await engine.getBacklinks(meeting, { sourceId })).filter(row => row.link_type === 'attended')).toHaveLength(incoming ? 1 : 0);
+ expect((await engine.getLinks(meeting, { sourceId })).filter(row => row.link_type === 'attended')).toHaveLength(incoming ? 0 : 1);
+ });
+ test(`${lane}: unavailable source-selected ontology preserves graph and watermark`, async () => {
+ await engine.setConfig('schema_pack', 'gbrain-base');
+ await seed(meeting, 'meeting', positive);
+ await extract('db');
+ const rows = () => engine.executeRaw('SELECT l.* FROM links l JOIN pages p ON p.id=l.from_page_id WHERE p.source_id=$1 ORDER BY l.id', [sourceId]);
+ const before = await rows();
+ expect(before).toHaveLength(1);
+ await engine.setConfig('schema_pack', 'attendance-fixture');
+ await engine.setConfig(`schema_pack.source.${sourceId}`, 'missing-example-pack');
+ await engine.executeRaw('UPDATE pages SET links_extracted_at=NULL WHERE source_id=$1 AND slug=$2', [sourceId, meeting]);
+ if (lane === 'db') {
+ const diagnostic = spyOn(console, 'error').mockImplementation(() => {});
+ const exit = spyOn(process, 'exit').mockImplementation(code => { throw new Error(`Extraction exited with code ${code}`); });
+ try { await expect(extract(lane, true)).rejects.toThrow('Extraction exited with code 1'); }
+ finally { exit.mockRestore(); diagnostic.mockRestore(); }
+ } else if (['stale', 'fs-sync', 'fs-incremental', 'fs-batch'].includes(lane)) {
+ await expect(extract(lane, true)).rejects.toThrow('schema pack');
+ } else await extract(lane, true);
+ expect(await rows()).toEqual(before);
+ expect((await engine.executeRaw<{ value: string | null }>('SELECT links_extracted_at AS value FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, meeting]))[0].value).toBeNull();
+ });
+ test(`${lane}: inline commented people do not become attendees`, async () => {
+ await seed('people/hidden-example', 'person', 'A hidden reference, not attendance.');
+ await seed(meeting, 'meeting', `${positive} <!-- [Hidden](../people/hidden-example.md) -->`);
+ await extract(lane, true);
+ expect(await attendees()).toEqual([person]);
+ });
+ test(`${lane}: unavailable ontology cannot reverse existing pack-owned attendance`, async () => {
+ await engine.setConfig('schema_pack', 'gbrain-base');
+ await seed(meeting, 'meeting', positive);
+ await extract('db');
+ const rows = () => engine.executeRaw('SELECT l.* FROM links l JOIN pages p ON p.id=l.from_page_id WHERE p.source_id=$1 ORDER BY l.id', [sourceId]);
+ const before = await rows();
+ expect(before).toHaveLength(1);
+ expect((await engine.getLinks(meeting, { sourceId }))[0].link_type).toBe('attended');
+ await engine.setConfig('schema_pack', 'missing-example-pack');
+ await engine.executeRaw('UPDATE pages SET links_extracted_at=NULL WHERE source_id=$1 AND slug=$2', [sourceId, meeting]);
+ if (lane === 'db') {
+ const diagnostic = spyOn(console, 'error').mockImplementation(() => {});
+ const exit = spyOn(process, 'exit').mockImplementation(code => { throw new Error(`Extraction exited with code ${code}`); });
+ try {
+ await expect(extract(lane, true)).rejects.toThrow('Extraction exited with code 1');
+ expect(diagnostic.mock.calls.flat()).toContain('Cannot extract links: active schema pack is unavailable.');
+ } finally { exit.mockRestore(); diagnostic.mockRestore(); }
+ } else if (['stale', 'fs-sync', 'fs-incremental', 'fs-batch'].includes(lane)) {
+ await expect(extract(lane, true)).rejects.toThrow('schema pack');
+ } else await extract(lane, true);
+ expect(await rows()).toEqual(before);
+ expect((await engine.executeRaw<{ value: string | null }>('SELECT links_extracted_at AS value FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, meeting]))[0].value).toBeNull();
+ await engine.setConfig('schema_pack', 'gbrain-base');
+ await extract(lane, true);
+ expect((await engine.getLinks(meeting, { sourceId })).filter(row => row.link_type === 'attended')).toHaveLength(1);
+ expect((await engine.getBacklinks(meeting, { sourceId })).filter(row => row.link_type === 'attended')).toEqual([]);
+ });
+ test(`${lane}: a unique bare attendee resolves, survives re-extraction, and retracts with its evidence`, async () => {
+ await engine.setConfig('link_resolution.global_basename', 'true');
+ try {
+ await seed(meeting, 'meeting', 'Attendees: [[Alice Example]]');
+ await extract(lane, true);
+ expect(await attendees()).toEqual([person]);
+ const rows = await engine.executeRaw<{ producer: string; origin: string }>(`SELECT l.link_source AS producer,o.slug AS origin
+ FROM links l JOIN pages o ON o.id=l.origin_page_id WHERE o.source_id=$1 AND o.slug=$2 AND l.link_type='attended'`, [sourceId, meeting]);
+ expect(rows).toEqual([{ producer: 'wikilink-resolved', origin: meeting }]);
+ await seed(person, 'person', 'An updated person with no attendance claim.');
+ await extract(lane, true);
+ expect(await attendees()).toEqual([person]);
+ await seed(meeting, 'meeting', 'The attendance list was removed.');
+ await extract(lane, true);
+ expect(await attendees()).toEqual([]);
+ } finally {
+ await engine.setConfig('link_resolution.global_basename', 'false');
+ }
+ });
+ test(`${lane}: HTML-commented attendance retracts the claim without asserting hidden evidence`, async () => {
+ await seed(meeting, 'meeting', positive);
+ await extract(lane);
+ expect(await attendees()).toEqual([person]);
+ await seed(meeting, 'meeting', `<!--\n${positive}\n-->`);
+ await extract(lane);
+ expect(await attendees()).toEqual([]);
+ });
+ test(`${lane}: missing display-label slugs do not make actual attendance incomplete`, async () => {
+ await seed(meeting, 'meeting', 'Attendees: [people/missing-example](../people/alice-example.md)');
+ await extract(lane);
+ expect(await attendees()).toEqual([person]);
+ });
+ for (const policy of ['explicit', 'federated-default']) test(`${lane}: ${policy} foreign attendance survives complete resolution`, async () => {
+ const peer = 'attendance-peer';
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES ($1,$1) ON CONFLICT DO NOTHING', [peer]);
+ const target = 'people/foreign-example';
+ await engine.putPage(target, { type: 'person', title: 'Foreign example', compiled_truth: 'DB-only person.' }, { sourceId: peer });
+ await engine.setConfig('link_resolution.cross_source', policy === 'explicit' ? 'true' : 'false');
+ await engine.setConfig('sources.default', peer);
+ if (policy === 'federated-default') await engine.executeRaw("UPDATE sources SET config=jsonb_set(config,'{federated}','true'::jsonb) WHERE id=$1", [sourceId]);
+ const body = `Attendees: [[${policy === 'explicit' ? `${peer}:` : ''}${target}]]`;
+ try {
+ await seed(meeting, 'meeting', body);
+ await extract('db');
+ await engine.executeRaw('UPDATE pages SET links_extracted_at=NULL WHERE source_id=$1 AND slug=$2', [sourceId, meeting]);
+ await extract(lane, true);
+ const rows = await engine.executeRaw<{ from_source: string; to_source: string }>(`SELECT f.source_id AS from_source,t.source_id AS to_source FROM links l JOIN pages f ON f.id=l.from_page_id JOIN pages t ON t.id=l.to_page_id JOIN pages o ON o.id=l.origin_page_id WHERE o.source_id=$1 AND o.slug=$2 AND l.link_type='attended'`, [sourceId, meeting]);
+ expect(rows).toEqual([{ from_source: peer, to_source: sourceId }]);
+ await engine.setConfig('link_resolution.cross_source', 'false');
+ await engine.executeRaw("UPDATE sources SET config=jsonb_set(config,'{federated}','false'::jsonb) WHERE id=$1", [sourceId]);
+ await engine.executeRaw('UPDATE pages SET links_extracted_at=NULL WHERE source_id=$1 AND slug=$2', [sourceId, meeting]);
+ const denied = await extract(lane, true);
+ if (lane === 'fs-sync') expect((denied as { processed: string[] }).processed).not.toContain(meeting);
+ expect((await engine.executeRaw('SELECT id FROM links WHERE origin_page_id=(SELECT id FROM pages WHERE source_id=$1 AND slug=$2)', [sourceId, meeting])).length).toBe(1);
+ expect((await engine.executeRaw<{ links_extracted_at: string | null }>('SELECT links_extracted_at FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, meeting]))[0].links_extracted_at).toBeNull();
+ } finally {
+ await engine.setConfig('link_resolution.cross_source', 'false');
+ await engine.setConfig('sources.default', 'default');
+ await engine.executeRaw('DELETE FROM sources WHERE id=$1', [peer]);
+ }
+ });
+ test(`${lane}: unresolved attendance cannot retract owned graph or mark success`, async () => {
+ await seed(meeting, 'meeting', positive);
+ await extract('db');
+ await seed(meeting, 'meeting', 'Attendees: [[people/missing-example]]');
+ await engine.executeRaw('UPDATE pages SET links_extracted_at=NULL WHERE source_id=$1 AND slug=$2', [sourceId, meeting]);
+ const unresolved = await extract(lane, true);
+ if (lane === 'fs-sync') expect((unresolved as { processed: string[] }).processed).not.toContain(meeting);
+ if (lane === 'db') expect((unresolved as { skipped_attendance_incomplete: number }).skipped_attendance_incomplete).toBe(1);
+ if (lane === 'stale') expect((unresolved as { skippedAttendanceIncomplete: number }).skippedAttendanceIncomplete).toBe(1);
+ if (lane === 'sweep') {
+ const skips = (unresolved as Awaited<ReturnType<typeof runMaintenanceSweep>>).skipped;
+ expect(skips).toContainEqual({ reason: 'attendance_resolution_incomplete', count: 1 });
+ expect(skips.some(row => row.reason === 'budget_exhausted:link_reconcile')).toBe(false);
+ }
+ expect(await attendees()).toEqual([person]);
+ expect((await engine.executeRaw<{ links_extracted_at: string | null }>('SELECT links_extracted_at FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, meeting]))[0].links_extracted_at).toBeNull();
+ });
+ for (const fence of ['~~~', '```']) test(`${lane}: section-nested ${fence} examples never persist attendance`, async () => {
+ await seed(meeting, 'meeting', `## Attendees\n${fence}\n## Example\n${positive}\n${fence}`);
+ await extract(lane);
+ expect(await attendees()).toEqual([]);
+ });
+ }
+ for (const lane of ['fs-incremental', 'fs-sync']) {
+ test(`${lane}: imported hidden meetings get guarded canonical attendance`, async () => {
+ const hidden = '.github/planning';
+ const extractHidden = () => lane === 'fs-sync'
+ ? extractLinksForSlugs(engine, root, [hidden], { sourceId })
+ : runExtractCore(engine, { mode: 'links', dir: root, sourceId, slugs: [hidden], quiet: true });
+ await seed(hidden, 'meeting', positive);
+ await extractHidden();
+ expect((await engine.getBacklinks(hidden, { sourceId })).filter(row => row.link_type === 'attended')
+ .map(row => row.from_slug)).toEqual([person]);
+ await seed(hidden, 'meeting', 'No attendance evidence.');
+ await extractHidden();
+ expect((await engine.getBacklinks(hidden, { sourceId })).filter(row => row.link_type === 'attended')).toEqual([]);
+ });
+ }
+
+ test('fs-sync: an ordinary missing target does not discard later links or processed status', async () => {
+ const note = 'notes/reference';
+ await seed(note, 'note', '[Missing](../people/missing-example.md)\n[Alice](../people/alice-example.md)');
+ writeFileSync(join(root, 'people/missing-example.md'), '---\ntype: person\n---\nNot imported.');
+ const result = await extractLinksForSlugs(engine, root, [note], { sourceId });
+ expect(result).toEqual({ created: 1, processed: [note] });
+ expect((await engine.getLinks(note, { sourceId })).map(row => row.to_slug)).toEqual([person]);
+ });
+
+ for (const lane of ['fs-incremental', 'fs-sync']) {
+ test(`${lane}: file-only meeting declarations cannot bypass the database origin type`, async () => {
+ const hidden = '.github/not-a-meeting';
+ await seed(hidden, 'note', positive);
+ writeFileSync(join(root, `${hidden}.md`), `---\ntype: meeting\n---\n${positive}`);
+ const result = lane === 'fs-sync'
+ ? await extractLinksForSlugs(engine, root, [hidden], { sourceId })
+ : await runExtractCore(engine, { mode: 'all', dir: root, sourceId, slugs: [hidden], quiet: true });
+ expect(lane === 'fs-sync' ? (result as { processed: string[] }).processed.length
+ : (result as { pages_processed: number }).pages_processed).toBe(0);
+ expect((await engine.getBacklinks(hidden, { sourceId })).filter(row => row.link_type === 'attended')).toEqual([]);
+ const stamp = await engine.executeRaw<{ links_extracted_at: string | null }>(
+ 'SELECT links_extracted_at FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, hidden]);
+ expect(stamp[0].links_extracted_at).toBeNull();
+ });
+ }
+
+ for (const lane of ['db', 'stale', 'fs-batch', 'fs-incremental', 'fs-sync', 'prepare', 'sweep']) {
+ test(`${lane}: display-label person slugs do not assert extra attendees`, async () => {
+ await seed('people/bob-example', 'person', 'A person named only in the display label.');
+ await seed(meeting, 'meeting', 'Attendees: [people/bob-example](../people/alice-example.md)');
+ await extract(lane);
+ expect(await attendees()).toEqual([person]);
+ });
+ test(`${lane}: ambiguous bare references do not assert either attendee`, async () => {
+ await seed('demo-example', 'person', 'One possible person.');
+ await seed('đemo-example', 'person', 'Another possible person.');
+ await seed(meeting, 'meeting', 'Attendees: [[Đemo Example]]');
+ await extract(lane);
+ expect(await attendees()).toEqual([]);
+ });
+ test(`${lane}: actual extraction persists, queries and removes meeting-owned Markdown`, async () => {
+ await seed(meeting, 'meeting', positive);
+ await extract(lane);
+ expect(await attendees()).toEqual([person]);
+ const edge = (await engine.getLinks(person, { sourceId })).find(row => row.link_type === 'attended')!;
+ expect(edge).toMatchObject({ from_slug: person, to_slug: meeting, link_source: 'markdown', origin_slug: meeting });
+ expect((await engine.relationalFanout([person], { sourceId, direction: 'out', linkTypes: ['attended'] })).map(row => row.slug)).toContain(meeting);
+ await seed(person, 'person', 'Updated person with no attendance claim.');
+ await extract(lane);
+ expect(await attendees()).toEqual([person]);
+ await seed(meeting, 'meeting', 'No attendance evidence remains.');
+ await extract(lane);
+ expect(await attendees()).toEqual([]);
+ });
+ }
+ for (const lane of ['db', 'stale']) {
+ test(`${lane}: mixed-source extraction resolves each origin's pack for identical slugs`, async () => {
+ const other = 'attendance-other-example';
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES ($1,$1)', [other]);
+ try {
+ await engine.setConfig(`schema_pack.source.${sourceId}`, 'gbrain-base');
+ await engine.setConfig(`schema_pack.source.${other}`, 'attendance-fixture');
+ await seed(meeting, 'meeting', positive);
+ await engine.putPage(person, { type: 'person', title: 'Alice Example', compiled_truth: 'Other source.' }, { sourceId: other });
+ await engine.putPage(meeting, { type: 'meeting', title: 'Planning', compiled_truth: positive }, { sourceId: other });
+ const output = spyOn(console, 'log').mockImplementation(() => {});
+ try {
+ if (lane === 'db') await runExtract(engine, ['all', '--source', 'db', '--json']);
+ else await extractStaleFromDB(engine, { quiet: true, dryRun: false, jsonMode: false, catchUp: true });
+ } finally { output.mockRestore(); }
+ expect((await engine.getLinks(meeting, { sourceId })).filter(row => row.link_type === 'attended')).toHaveLength(1);
+ expect((await engine.getBacklinks(meeting, { sourceId })).filter(row => row.link_type === 'attended')).toEqual([]);
+ expect((await engine.getLinks(meeting, { sourceId: other })).filter(row => row.link_type === 'attended')).toEqual([]);
+ expect((await engine.getBacklinks(meeting, { sourceId: other })).filter(row => row.link_type === 'attended')).toHaveLength(1);
+ await engine.setConfig(`schema_pack.source.${other}`, 'missing-example-pack');
+ await seed(meeting, 'meeting', `${positive}\nAn unrelated edit.`);
+ await extract(lane, true);
+ expect((await engine.getLinks(meeting, { sourceId })).filter(row => row.link_type === 'attended')).toHaveLength(1);
+ } finally {
+ await engine.executeRaw('DELETE FROM sources WHERE id=$1', [other]);
+ await engine.setConfig(`schema_pack.source.${other}`, '');
+ }
+ });
+ }
+ test('db: type-filtered extraction does not load an unrelated source pack', async () => {
+ const other = 'attendance-other-example';
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES ($1,$1)', [other]);
+ const output = spyOn(console, 'log').mockImplementation(() => {});
+ const diagnostic = spyOn(console, 'error').mockImplementation(() => {});
+ const exit = spyOn(process, 'exit').mockImplementation(code => { throw new Error(`Extraction exited with code ${code}`); });
+ try {
+ await seed(meeting, 'meeting', positive);
+ await engine.putPage(person, { type: 'person', title: 'Alice Example', compiled_truth: 'Other source.' }, { sourceId: other });
+ await engine.setConfig(`schema_pack.source.${other}`, 'missing-example-pack');
+ await runExtract(engine, ['links', '--source', 'db', '--type', 'meeting', '--json']);
+ expect(await attendees()).toEqual([person]);
+ } finally {
+ output.mockRestore(); diagnostic.mockRestore(); exit.mockRestore();
+ await engine.executeRaw('DELETE FROM sources WHERE id=$1', [other]);
+ await engine.setConfig(`schema_pack.source.${other}`, '');
+ }
+ });
+ test('db: unavailable selected source fails preflight before any healthy graph or combined watermark changes', async () => {
+ const other = 'attendance-other-example';
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES ($1,$1)', [other]);
+ const output = spyOn(console, 'log').mockImplementation(() => {});
+ const diagnostic = spyOn(console, 'error').mockImplementation(() => {});
+ const exit = spyOn(process, 'exit').mockImplementation(code => { throw new Error(`Extraction exited with code ${code}`); });
+ try {
+ await seed(meeting, 'meeting', positive);
+ await engine.putPage(meeting, { type: 'meeting', title: 'Planning', compiled_truth: 'Other source.' }, { sourceId: other });
+ await engine.setConfig(`schema_pack.source.${other}`, 'missing-example-pack');
+ await expect(runExtract(engine, ['all', '--source', 'db', '--json'])).rejects.toThrow('Extraction exited with code 1');
+ expect(await attendees()).toEqual([]);
+ expect((await engine.executeRaw<{ value: string | null }>('SELECT links_extracted_at AS value FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, meeting]))[0].value).toBeNull();
+ } finally {
+ output.mockRestore(); diagnostic.mockRestore(); exit.mockRestore();
+ await engine.executeRaw('DELETE FROM sources WHERE id=$1', [other]);
+ await engine.setConfig(`schema_pack.source.${other}`, '');
+ }
+ });
+ test('stale: an unavailable first source does not starve healthy later batches or become successful', async () => {
+ const other = 'attendance-other-example';
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES ($1,$1)', [other]);
+ const list = engine.listStalePagesForExtraction.bind(engine);
+ const batches = spyOn(engine, 'listStalePagesForExtraction').mockImplementation(opts => list({ ...opts, batchSize: 1 }));
+ try {
+ await seed(meeting, 'meeting', positive);
+ await engine.addLinksBatch([{ from_slug: meeting, to_slug: person, from_source_id: sourceId, to_source_id: sourceId,
+ link_type: 'attended', link_source: 'markdown', origin_slug: meeting, origin_source_id: sourceId }]);
+ const before = await engine.getLinks(meeting, { sourceId });
+ await engine.setConfig(`schema_pack.source.${sourceId}`, 'missing-example-pack');
+ await engine.putPage(person, { type: 'person', title: 'Alice Example', compiled_truth: 'Other source.' }, { sourceId: other });
+ await engine.putPage(meeting, { type: 'meeting', title: 'Planning', compiled_truth: positive }, { sourceId: other });
+ const drain = () => extractStaleFromDB(engine, { quiet: true, dryRun: false, jsonMode: false, catchUp: true });
+ await expect(drain()).rejects.toThrow('schema pack');
+ expect(await engine.getLinks(meeting, { sourceId })).toEqual(before);
+ expect((await engine.executeRaw<{ value: string | null }>('SELECT links_extracted_at AS value FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, meeting]))[0].value).toBeNull();
+ expect((await engine.getBacklinks(meeting, { sourceId: other })).filter(row => row.link_type === 'attended')).toHaveLength(1);
+ expect((await engine.executeRaw<{ value: string | null }>('SELECT links_extracted_at AS value FROM pages WHERE source_id=$1 AND slug=$2', [other, meeting]))[0].value).not.toBeNull();
+ await engine.putPage(meeting, { type: 'meeting', title: 'Planning', compiled_truth: 'The supported evidence was removed.' }, { sourceId: other });
+ await expect(drain()).rejects.toThrow('schema pack');
+ expect((await engine.getBacklinks(meeting, { sourceId: other })).filter(row => row.link_type === 'attended')).toEqual([]);
+ } finally {
+ batches.mockRestore();
+ await engine.executeRaw('DELETE FROM sources WHERE id=$1', [other]);
+ await engine.setConfig(`schema_pack.source.${other}`, '');
+ }
+ });
+ for (const origin of [sourceId, 'default']) {
+ for (const [globalPack, sourcePack, incoming] of [
+ ['attendance-fixture', 'gbrain-base', false],
+ ['gbrain-base', 'attendance-fixture', true],
+ ['missing-example-pack', 'attendance-fixture', true],
+ ] as const) test(`local publication: source-selected ${origin}/${sourcePack} overrides global ${globalPack}`, async () => {
+ await engine.setConfig('schema_pack', globalPack);
+ await engine.setConfig(`schema_pack.source.${origin}`, sourcePack);
+ try {
+ await engine.putPage(person, { type: 'person', title: 'Alice Example', compiled_truth: 'An example.' }, { sourceId: origin });
+ const op = operations.find(op => op.name === 'put_page')!;
+ const result = await op.handler({ engine, config: { engine: kind as 'pglite' | 'postgres' }, remote: false, sourceId: origin,
+ dryRun: false, logger: { info() {}, warn() {}, error() {} } }, { slug: meeting,
+ content: `---\ntype: meeting\ntitle: Planning\nattendees: ["${person}"]\n---\n${positive}` }) as { auto_links: { errors: number } };
+ expect(result.auto_links.errors).toBe(0);
+ expect((await engine.getBacklinks(meeting, { sourceId: origin })).filter(row => row.link_type === 'attended')).toHaveLength(incoming ? 2 : 0);
+ expect((await engine.getLinks(meeting, { sourceId: origin })).filter(row => row.link_type === 'attended')).toHaveLength(incoming ? 0 : 2);
+ } finally {
+ await engine.setConfig(`schema_pack.source.${origin}`, '');
+ if (origin === 'default') await engine.executeRaw('DELETE FROM pages WHERE source_id=$1', [origin]);
+ }
+ });
+ test(`local publication: unavailable source-selected ${origin} pack saves the note but preserves the graph`, async () => {
+ await engine.setConfig(`schema_pack.source.${origin}`, 'gbrain-base');
+ try {
+ await engine.putPage(person, { type: 'person', title: 'Alice Example', compiled_truth: 'An example.' }, { sourceId: origin });
+ const op = operations.find(op => op.name === 'put_page')!;
+ const ctx = { engine, config: { engine: kind as 'pglite' | 'postgres' }, remote: false, sourceId: origin,
+ dryRun: false, logger: { info() {}, warn() {}, error() {} } };
+ const content = `---\ntype: meeting\ntitle: Planning\nattendees: ["${person}"]\n---\n${positive}`;
+ await op.handler(ctx, { slug: meeting, content });
+ const before = await engine.getLinks(meeting, { sourceId: origin });
+ expect(before.filter(row => row.link_type === 'attended')).toHaveLength(2);
+ const snapshot = (await engine.readPageSnapshot(meeting, { sourceId: origin }))!;
+ await engine.setConfig(`schema_pack.source.${origin}`, 'missing-example-pack');
+ const result = await op.handler(ctx, { slug: meeting, expected_revision: snapshot.revision,
+ content: `${content}\nThe note must survive.` }) as { auto_links: { errors: number; created: number; removed: number } };
+ expect(result.auto_links).toMatchObject({ errors: 1, created: 0, removed: 0 });
+ expect(await engine.getLinks(meeting, { sourceId: origin })).toEqual(before);
+ expect((await engine.getPage(meeting, { sourceId: origin }))!.compiled_truth).toContain('The note must survive.');
+ } finally {
+ await engine.setConfig(`schema_pack.source.${origin}`, '');
+ if (origin === 'default') await engine.executeRaw('DELETE FROM pages WHERE source_id=$1', [origin]);
+ }
+ });
+ }
+ test('local publication discovers typed pack frontmatter before admitting edges and preserves unchanged row identity', async () => {
+ await engine.setConfig('schema_pack', 'company-brain');
+ const op = operations.find(op => op.name === 'put_page')!;
+ const ctx = { engine, config: { engine: kind as 'pglite' | 'postgres' }, remote: false, sourceId,
+ dryRun: false, logger: { info() {}, warn() {}, error() {} } };
+ const content = `---\ntype: meeting\ntitle: Planning\nattendees: ["${person}"]\n---\nNo body references.`;
+ const created = await op.handler(ctx, { slug: meeting, content }) as { auto_links: { errors: number } };
+ expect(created.auto_links.errors).toBe(0);
+ const rows = () => engine.executeRaw<{ id: string; from_slug: string; to_slug: string; producer: string }>(`SELECT l.id::text,f.slug AS from_slug,t.slug AS to_slug,l.link_source AS producer
+ 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 AND f.slug=$2 AND l.link_type='attended'`, [sourceId, meeting]);
+ const before = await rows();
+ expect(before).toHaveLength(1);
+ expect(before[0]).toMatchObject({ from_slug: meeting, to_slug: person, producer: 'frontmatter' });
+ const snapshot = (await engine.readPageSnapshot(meeting, { sourceId }))!;
+ const updated = await op.handler(ctx, { slug: meeting, expected_revision: snapshot.revision,
+ content: `${content}\nAn unrelated edit.` }) as { auto_links: { created: number; removed: number; errors: number } };
+ expect(updated.auto_links).toMatchObject({ created: 0, removed: 0, errors: 0 });
+ expect(await rows()).toEqual(before);
+ });
+ for (const change of ['edit', 'retype', 'delete']) {
+ test(`local publication keeps the note and prior graph when an endpoint changes after preparation: ${change}`, async () => {
+ await seed(meeting, 'meeting', positive);
+ await extract('db');
+ const snapshot = (await engine.readPageSnapshot(meeting, { sourceId }))!;
+ const rows = () => engine.executeRaw('SELECT l.* FROM links l JOIN pages p ON p.id=l.from_page_id WHERE p.source_id=$1 ORDER BY l.id', [sourceId]);
+ const before = await rows();
+ const executeRaw = engine.executeRaw;
+ let armed = true;
+ const race = spyOn(engine, 'executeRaw').mockImplementation(async function<T>(this: BrainEngine, sql: string, params?: unknown[], opts?: { signal?: AbortSignal }) {
+ const result = await executeRaw.bind(this)<T>(sql, params, opts);
+ if (armed && sql === 'SELECT slug, source_id, type, knowledge_revision FROM pages WHERE slug=ANY($1::text[]) AND deleted_at IS NULL') {
+ armed = false;
+ if (change === 'delete') await engine.softDeletePage(person, { sourceId });
+ else await engine.putPage(person, { type: change === 'retype' ? 'company' : 'person', title: 'Alice Example', compiled_truth: 'A concurrent edit.' }, { sourceId });
+ }
+ return result;
+ });
+ try {
+ const op = operations.find(op => op.name === 'put_page')!;
+ const result = await op.handler({ engine, config: { engine: kind as 'pglite' | 'postgres' }, remote: false, sourceId,
+ dryRun: false, logger: { info() {}, warn() {}, error() {} } }, { slug: meeting, expected_revision: snapshot.revision,
+ content: `---\ntype: meeting\ntitle: Planning\n---\n${positive}\nThe note must survive.` }) as { auto_links: { errors: number; created: number; removed: number } };
+ expect(armed).toBe(false);
+ expect(result.auto_links).toMatchObject({ errors: 1, created: 0, removed: 0 });
+ expect((await engine.getPage(meeting, { sourceId }))!.compiled_truth).toContain('The note must survive.');
+ expect(await rows()).toEqual(before);
+ expect((await engine.executeRaw<{ stale: boolean }>('SELECT links_extracted_at IS NULL OR updated_at>links_extracted_at AS stale FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, meeting]))[0].stale).toBe(true);
+ } finally { race.mockRestore(); }
+ });
+ }
+ test('local publication does not swallow unrelated graph storage failures', async () => {
+ await seed(meeting, 'meeting', positive);
+ await extract('db');
+ const snapshot = (await engine.readPageSnapshot(meeting, { sourceId }))!;
+ const before = await engine.getLinks(person, { sourceId });
+ const fault = spyOn(engine, 'replaceDerivedLinks').mockImplementation(async () => { throw new Error('Simulated graph storage failure.'); });
+ try {
+ const op = operations.find(op => op.name === 'put_page')!;
+ await expect(op.handler({ engine, config: { engine: kind as 'pglite' | 'postgres' }, remote: false, sourceId,
+ dryRun: false, logger: { info() {}, warn() {}, error() {} } }, { slug: meeting, expected_revision: snapshot.revision,
+ content: `---\ntype: meeting\ntitle: Planning\n---\n${positive}\nThis publication must roll back.` })).rejects.toMatchObject({ code: 'storage_error' });
+ expect((await engine.getPage(meeting, { sourceId }))!.compiled_truth).toBe(snapshot.page.compiled_truth);
+ expect(await engine.getLinks(person, { sourceId })).toEqual(before);
+ } finally { fault.mockRestore(); }
+ });
+ test('local publication admits the visible attendee but not a live person inside an inline comment', async () => {
+ await seed('people/hidden-example', 'person', 'Not an attendee.');
+ const op = operations.find(op => op.name === 'put_page')!;
+ await op.handler({ engine, config: { engine: kind as 'pglite' | 'postgres' }, remote: false, sourceId,
+ dryRun: false, logger: { info() {}, warn() {}, error() {} } }, { slug: meeting,
+ content: `---\ntype: meeting\ntitle: Planning\n---\n${positive} <!-- [Hidden](../people/hidden-example.md) -->` });
+ expect(await attendees()).toEqual([person]);
+ });
+ test('local publication preserves pack-owned attendance and reports unavailable ontology without losing the note', async () => {
+ await engine.setConfig('schema_pack', 'gbrain-base');
+ await seed(meeting, 'meeting', positive);
+ await extract('db');
+ const before = await engine.getLinks(meeting, { sourceId });
+ const snapshot = (await engine.readPageSnapshot(meeting, { sourceId }))!;
+ await engine.setConfig('schema_pack', 'missing-example-pack');
+ const op = operations.find(op => op.name === 'put_page')!;
+ const result = await op.handler({ engine, config: { engine: kind as 'pglite' | 'postgres' }, remote: false, sourceId,
+ dryRun: false, logger: { info() {}, warn() {}, error() {} } }, { slug: meeting, expected_revision: snapshot.revision,
+ content: `---\ntype: meeting\ntitle: Planning\n---\n${positive}\nAn unrelated note.` }) as { auto_links: { errors: number } };
+ expect(result.auto_links.errors).toBe(1);
+ expect((await engine.getPage(meeting, { sourceId }))!.compiled_truth).toContain('An unrelated note.');
+ expect(await engine.getLinks(meeting, { sourceId })).toEqual(before);
+ });
+ test('local publication does not admit a non-person into typed pack attendance', async () => {
+ await engine.setConfig('schema_pack', 'company-brain');
+ await seed('people/company-example', 'company', 'Not a person.');
+ const op = operations.find(op => op.name === 'put_page')!;
+ const result = await op.handler({ engine, config: { engine: kind as 'pglite' | 'postgres' }, remote: false, sourceId,
+ dryRun: false, logger: { info() {}, warn() {}, error() {} } }, { slug: meeting,
+ content: '---\ntype: meeting\ntitle: Planning\nattendees: ["people/company-example"]\n---\nNo body references.' }) as {
+ auto_links: { created: number; unresolved_count: number } };
+ expect(result.auto_links.created).toBe(0);
+ expect(result.auto_links.unresolved_count).toBe(1);
+ expect((await engine.getLinks(meeting, { sourceId })).filter(row => row.link_type === 'attended')).toEqual([]);
+ });
+ test('local publication retains typed pack attendance when resolved endpoint metadata is unavailable', async () => {
+ await engine.setConfig('schema_pack', 'company-brain');
+ await seed(meeting, 'meeting', 'No body references.', { attendees: [person] });
+ await engine.addLinksBatch([{ from_slug: meeting, to_slug: person, from_source_id: sourceId, to_source_id: sourceId,
+ link_type: 'attended', link_source: 'frontmatter', origin_slug: meeting, origin_source_id: sourceId, origin_field: 'attendees' }]);
+ const before = await engine.getLinks(meeting, { sourceId });
+ const snapshot = (await engine.readPageSnapshot(meeting, { sourceId }))!;
+ const executeRaw = engine.executeRaw;
+ const metadata = spyOn(engine, 'executeRaw').mockImplementation(function<T>(this: BrainEngine, sql: string, params?: unknown[], opts?: { signal?: AbortSignal }) {
+ return sql === 'SELECT slug, source_id, type, knowledge_revision FROM pages WHERE slug=ANY($1::text[]) AND deleted_at IS NULL'
+ ? Promise.resolve<T[]>([]) : executeRaw.bind(this)<T>(sql, params, opts);
+ });
+ try {
+ const op = operations.find(op => op.name === 'put_page')!;
+ const result = await op.handler({ engine, config: { engine: kind as 'pglite' | 'postgres' }, remote: false, sourceId,
+ dryRun: false, logger: { info() {}, warn() {}, error() {} } }, { slug: meeting, expected_revision: snapshot.revision,
+ content: `---\ntype: meeting\ntitle: Planning\nattendees: ["${person}"]\n---\nAn unrelated edit.` }) as { auto_links: { errors: number } };
+ expect(result.auto_links.errors).toBe(1);
+ expect((await engine.getPage(meeting, { sourceId }))!.compiled_truth).toBe('An unrelated edit.');
+ expect(await engine.getLinks(meeting, { sourceId })).toEqual(before);
+ } finally { metadata.mockRestore(); }
+ });
+ test('typed pack attendance preserves prior edges when the new target cannot be resolved', async () => {
+ await engine.setConfig('schema_pack', 'company-brain');
+ await seed(meeting, 'meeting', 'No body references.', { attendees: [person] });
+ await engine.addLinksBatch([{ from_slug: meeting, to_slug: person, from_source_id: sourceId, to_source_id: sourceId,
+ link_type: 'attended', link_source: 'frontmatter', origin_slug: meeting, origin_source_id: sourceId, origin_field: 'attendees' }]);
+ const before = await engine.getLinks(meeting, { sourceId });
+ const page = (await engine.getPage(meeting, { sourceId }))!;
+ const prepared = await prepareAutomaticLinks(engine, meeting, { ...page, frontmatter: { attendees: ['people/missing-example'] } }, sourceId);
+ const result = await engine.transaction(async tx => { await tx.lockPageKeys(prepared.pageKeys); return prepared.apply(tx); });
+ expect(result.errors).toBe(1);
+ expect(await engine.getLinks(meeting, { sourceId })).toEqual(before);
+ });
+ test('local put_page and remote deferred sweep preserve the actual Markdown producer', async () => {
+ const op = operations.find(op => op.name === 'put_page')!;
+ const ctx = { engine, config: { engine: kind as 'pglite' | 'postgres' }, remote: false, sourceId,
+ dryRun: false, logger: { info() {}, warn() {}, error() {} } };
+ await op.handler(ctx, { slug: meeting, content: `---\ntype: meeting\ntitle: Planning\n---\n${positive}` });
+ expect(await attendees()).toEqual([person]);
+ const snapshot = (await engine.readPageSnapshot(meeting, { sourceId }))!;
+ await op.handler({ ...ctx, remote: true }, { slug: meeting, expected_revision: snapshot.revision,
+ content: '---\ntype: meeting\ntitle: Planning\n---\nNo attendance evidence remains.' });
+ await extract('sweep');
+ expect(await attendees()).toEqual([]);
+ });
+ test('local put_page commits unresolved attendance content while preserving retryable graph', async () => {
+ await seed(meeting, 'meeting', positive);
+ await extract('db');
+ const snapshot = (await engine.readPageSnapshot(meeting, { sourceId }))!;
+ const body = 'Attendees: [[people/missing-example]]';
+ const op = operations.find(op => op.name === 'put_page')!;
+ const result = await op.handler({ engine, config: { engine: kind as 'pglite' | 'postgres' }, remote: false, sourceId,
+ dryRun: false, logger: { info() {}, warn() {}, error() {} } }, { slug: meeting, expected_revision: snapshot.revision,
+ content: `---\ntype: meeting\ntitle: Planning\n---\n${body}` }) as { auto_links: { errors: number; unresolved_count: number } };
+ expect((await engine.getPage(meeting, { sourceId }))?.compiled_truth).toBe(body);
+ expect(result.auto_links.errors).toBe(1);
+ expect(result.auto_links.unresolved_count).toBeGreaterThan(0);
+ expect(await attendees()).toEqual([person]);
+ const rows = await engine.executeRaw<{ stale: boolean }>('SELECT links_extracted_at IS NULL OR updated_at>links_extracted_at AS stale FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, meeting]);
+ expect(rows[0].stale).toBe(true);
+ });
+ test('actual put_page and query operations retain and remove the supported attendee', async () => {
+ const put = operations.find(op => op.name === 'put_page')!;
+ const query = operations.find(op => op.name === 'query')!;
+ const ctx = { engine, config: { engine: kind as 'pglite' | 'postgres' }, remote: false, sourceId,
+ dryRun: false, logger: { info() {}, warn() {}, error() {} } };
+ const params = { query: 'Who attended meetings/planning?', expand: false, relational: true, limit: 10 };
+ await put.handler(ctx, { slug: meeting, content: `---\ntype: meeting\ntitle: Planning\n---\n${positive}` });
+ const before = await query.handler(ctx, params) as Array<{ slug: string }>;
+ expect(before.map(row => row.slug)).toContain(person);
+ const snapshot = (await engine.readPageSnapshot(meeting, { sourceId }))!;
+ await put.handler(ctx, { slug: meeting, expected_revision: snapshot.revision,
+ content: '---\ntype: meeting\ntitle: Planning\n---\nNo attendance evidence remains.' });
+ const after = await query.handler(ctx, params) as Array<{ slug: string }>;
+ expect(after.map(row => row.slug)).not.toContain(person);
+ });
+ test('canonical frontmatter and body keep distinct provenance without duplicate people', async () => {
+ await seed(meeting, 'meeting', positive, { attendees: [person] });
+ await runExtract(engine, ['links', '--source', 'db', '--source-id', sourceId, '--include-frontmatter']);
+ expect(await attendees()).toEqual([person]);
+ expect((await engine.getLinks(person, { sourceId })).map(row => [row.link_source, row.origin_slug]).sort()).toEqual([
+ ['frontmatter', meeting], ['markdown', meeting],
+ ]);
+ await seed(meeting, 'meeting', 'No references remain.');
+ await runExtract(engine, ['links', '--source', 'db', '--source-id', sourceId, '--include-frontmatter']);
+ expect(await attendees()).toEqual([]);
+ });
+ test('ambiguous or non-person canonical frontmatter stays unresolved', async () => {
+ await engine.putPage('people/peer-example', { type: 'person', title: 'Shared name', compiled_truth: 'Another person.' }, { sourceId });
+ await engine.putPage(person, { type: 'person', title: 'Shared name', compiled_truth: 'A person.' }, { sourceId });
+ await seed('people/company-example', 'company', 'Not a person.');
+ await seed(meeting, 'meeting', 'No body links.', { attendees: ['Shared name', 'people/company-example'] });
+ await runExtract(engine, ['links', '--source', 'db', '--source-id', sourceId, '--include-frontmatter']);
+ expect(await engine.getBacklinks(meeting, { sourceId })).toEqual([]);
+ });
+ for (const lane of ['fs-sync', 'fs-incremental']) test(`${lane}: canonical frontmatter persists and removes under its meeting origin`, async () => {
+ const apply = async () => lane === 'fs-sync'
+ ? extractLinksForSlugs(engine, root, [meeting, person], { sourceId, includeFrontmatter: true })
+ : runExtractCore(engine, { mode: 'links', dir: root, slugs: [meeting, person], sourceId, includeFrontmatter: true, quiet: true });
+ await seed(meeting, 'meeting', 'No body links.', { attendees: [person] });
+ await apply();
+ expect(await attendees()).toEqual([person]);
+ expect((await engine.getLinks(person, { sourceId }))[0]).toMatchObject({ link_source: 'frontmatter', origin_slug: meeting, origin_source_id: sourceId });
+ await seed(person, 'person', 'Still no attendance claim on the person.');
+ await apply();
+ expect(await attendees()).toEqual([person]);
+ await seed(meeting, 'meeting', 'Attendees removed.');
+ await apply();
+ expect(await attendees()).toEqual([]);
+ });
+ test('private attendees and unsealed projections remain excluded from remote retrieval', async () => {
+ await seed(meeting, 'meeting', positive);
+ await extract('db');
+ expect(await attendees()).toEqual([person]);
+ expect((await buildRelationalArm(engine, 'Who attended meetings/planning?', { sourceId, excludePrivate: true, requireSafeChunks: true })).map(row => row.slug)).toEqual([person]);
+ await seed(person, 'person', 'A private attendee.', { visibility: 'private' });
+ expect(await buildRelationalArm(engine, 'Who attended meetings/planning?', { sourceId, excludePrivate: true, requireSafeChunks: true })).toEqual([]);
+ await engine.putPage(person, { type: 'person', title: 'Unsealed person', compiled_truth: 'An unprojected replacement.' }, { sourceId });
+ expect(await buildRelationalArm(engine, 'Who attended meetings/planning?', { sourceId, requireSafeChunks: true })).toEqual([]);
+ });
+ test('single and batch writers round-trip Markdown origin without exposing an ungranted origin', async () => {
+ await seed(meeting, 'meeting', positive);
+ await extract('db');
+ const original = (await engine.getLinks(person, { sourceId }))[0];
+ await engine.removeLink(person, meeting, 'attended', 'markdown', { fromSourceId: sourceId, toSourceId: sourceId });
+ await engine.addLink(person, meeting, original.context, 'attended', 'markdown', meeting, undefined,
+ { fromSourceId: sourceId, toSourceId: sourceId, originSourceId: sourceId });
+ expect((await engine.getLinks(person, { sourceId }))[0]).toEqual(original);
+ expect(await engine.addLinksBatch([{ from_slug: person, to_slug: meeting, link_type: 'attended', link_source: 'markdown',
+ from_source_id: sourceId, to_source_id: sourceId, origin_slug: meeting, origin_source_id: sourceId }])).toBe(0);
+ const hidden = 'attendance-origin';
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES ($1,$1) ON CONFLICT DO NOTHING', [hidden]);
+ await engine.putPage('notes/hidden', { type: 'note', title: 'Hidden origin', compiled_truth: 'Independent.' }, { sourceId: hidden });
+ await engine.addLink(person, meeting, 'Other origin', 'mentions', 'markdown', 'notes/hidden', undefined,
+ { fromSourceId: sourceId, toSourceId: sourceId, originSourceId: hidden });
+ expect((await engine.getLinks(person, { sourceIds: [sourceId] })).find(row => row.link_type === 'mentions')).toMatchObject({ origin_slug: null, origin_source_id: null });
+ });
+ test('failed filesystem attendance replacement stays retryable and preserves the last good graph', async () => {
+ await seed(meeting, 'meeting', positive);
+ await extract('fs-sync');
+ await seed(meeting, 'meeting', 'No references remain.');
+ const replace = engine.replaceDerivedLinks;
+ engine.replaceDerivedLinks = async () => { throw new Error('Injected replacement failure'); };
+ try {
+ const result = await extractLinksForSlugs(engine, root, [meeting], { sourceId });
+ expect(result.processed).toEqual([]);
+ expect(await attendees()).toEqual([person]);
+ } finally { engine.replaceDerivedLinks = replace; }
+ expect((await extractLinksForSlugs(engine, root, [meeting], { sourceId })).processed).toEqual([meeting]);
+ expect(await attendees()).toEqual([]);
+ });
+ for (const lane of ['fs-batch', 'fs-incremental']) test(`${lane}: failed attendance replacement does not advance its watermark`, async () => {
+ const apply = () => runExtractCore(engine, { mode: 'all', dir: root, sourceId, quiet: true,
+ ...(lane === 'fs-incremental' ? { slugs: [meeting, person] } : {}) });
+ await seed(meeting, 'meeting', positive);
+ await apply();
+ await seed(meeting, 'meeting', 'No references remain.');
+ const stamp = () => engine.executeRaw('SELECT links_extracted_at FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, meeting]);
+ const before = await stamp();
+ expect(before[0].links_extracted_at).not.toBeNull();
+ const replace = engine.replaceDerivedLinks;
+ engine.replaceDerivedLinks = async () => { throw new Error('Injected replacement failure'); };
+ try {
+ await apply();
+ expect(await stamp()).toEqual(before);
+ expect(await attendees()).toEqual([person]);
+ } finally { engine.replaceDerivedLinks = replace; }
+ await apply();
+ expect(await attendees()).toEqual([]);
+ expect(await stamp()).not.toEqual(before);
+ });
+ for (const packName of ['gbrain-base', 'company-brain']) test(`${packName}: pack_semantics_preserved`, async () => {
+ await engine.setConfig('schema_pack', packName);
+ await seed(meeting, 'meeting', positive, { attendees: [person] });
+ await runExtract(engine, ['links', '--source', 'db', '--source-id', sourceId, '--include-frontmatter']);
+ const rows = (await engine.getLinks(meeting, { sourceId })).filter(row => row.link_type === 'attended');
+ expect(rows.map(row => row.link_source).sort()).toEqual(['frontmatter', 'markdown']);
+ expect(rows.every(row => row.to_slug === person)).toBe(true);
+ expect(await attendees()).toEqual([]);
+ expect((await engine.relationalFanout([meeting], { sourceId, direction: 'out', linkTypes: ['attended'] })).map(row => row.slug)).toContain(person);
+ });
+ test('manual and other-origin rows survive exact meeting removal', async () => {
+ await seed(meeting, 'meeting', positive);
+ await seed('notes/evidence', 'note', 'Independent evidence.');
+ await extract('db');
+ await engine.addLink(person, meeting, 'Manual evidence', 'attended', 'manual', undefined, undefined,
+ { fromSourceId: sourceId, toSourceId: sourceId });
+ await engine.addLink(person, meeting, 'Other origin', 'attended', 'markdown', 'notes/evidence', undefined,
+ { fromSourceId: sourceId, toSourceId: sourceId, originSourceId: sourceId });
+ const preservedIds = () => engine.executeRaw(`SELECT id FROM links WHERE link_source='manual'
+ OR origin_page_id=(SELECT id FROM pages WHERE source_id=$1 AND slug='notes/evidence') ORDER BY id`, [sourceId]);
+ const before = await preservedIds();
+ await seed(meeting, 'meeting', 'No references remain.');
+ await extract('prepare');
+ expect(await preservedIds()).toEqual(before);
+ const rows = await engine.getLinks(person, { sourceId });
+ expect(rows.map(row => [row.link_source, row.origin_slug]).sort()).toEqual([
+ ['manual', null], ['markdown', 'notes/evidence'],
+ ]);
+ });
+ for (const [lane, packName] of [
+ ['prepare', 'attendance-fixture'], ['prepare', 'gbrain-base'],
+ ['sweep', 'attendance-fixture'], ['fs-batch', 'attendance-fixture'],
+ ['fs-incremental', 'attendance-fixture'], ['fs-sync', 'attendance-fixture'],
+ ]) test(`${lane}/${packName}: retained link identities refresh their evidence`, async () => {
+ await engine.setConfig('schema_pack', packName);
+ await seed(meeting, 'meeting', `${positive}\n\nRoom one.`);
+ await extract(lane);
+ const evidence = () => engine.executeRaw<{ id: number; context: string }>(`SELECT l.id,l.context FROM links l
+ JOIN pages f ON f.id=l.from_page_id JOIN pages t ON t.id=l.to_page_id
+ WHERE l.link_type='attended' AND f.source_id=$1 AND t.source_id=$1`, [sourceId]);
+ const before = await evidence();
+ expect(before).toHaveLength(1);
+ expect(before[0].context).toContain('Room one.');
+ await seed(meeting, 'meeting', `${positive}\n\nRoom two.`);
+ await extract(lane);
+ const after = await evidence();
+ expect(after).toHaveLength(1);
+ expect(after[0].id).toBe(before[0].id);
+ expect(after[0].context).toContain('Room two.');
+ expect(after[0].context).not.toContain('Room one.');
+ });
+ for (const lane of ['fs-batch', 'fs-incremental', 'fs-sync']) test(`${lane}: unknown legacy producers survive attendance reconciliation`, async () => {
+ await seed(meeting, 'meeting', positive);
+ await engine.addLink(meeting, person, 'Legacy unrelated claim', 'related', 'manual', undefined, undefined,
+ { fromSourceId: sourceId, toSourceId: sourceId });
+ await engine.executeRaw(`UPDATE links SET link_source=NULL WHERE link_type='related'
+ AND from_page_id=(SELECT id FROM pages WHERE source_id=$1 AND slug=$2)`, [sourceId, meeting]);
+ const legacyRows = () => engine.executeRaw(`SELECT id, context, link_type, link_source, origin_page_id FROM links
+ WHERE link_type='related' AND from_page_id=(SELECT id FROM pages WHERE source_id=$1 AND slug=$2)`, [sourceId, meeting]);
+ const before = await legacyRows();
+ expect(before).toHaveLength(1);
+ await extract(lane);
+ expect(await attendees()).toEqual([person]);
+ expect(await legacyRows()).toEqual(before);
+ await seed(meeting, 'meeting', 'No attendance evidence remains.');
+ await extract(lane);
+ expect(await attendees()).toEqual([]);
+ expect(await legacyRows()).toEqual(before);
+ });
+ test('reversed Markdown validation requires matching origin, types and captured endpoint revisions', async () => {
+ await seed(meeting, 'meeting', positive);
+ const snapshot = (await engine.readPageSnapshot(meeting, { sourceId }))!;
+ const endpoint = (await engine.readPageSnapshot(person, { sourceId }))!;
+ const origin = { slug: meeting, sourceId, expectedRevision: snapshot.revision, sourceIncarnation: snapshot.sourceIncarnation };
+ const row = { from_slug: person, to_slug: meeting, from_source_id: sourceId, to_source_id: sourceId,
+ link_type: 'attended', link_source: 'markdown', origin_slug: meeting, origin_source_id: sourceId };
+ await expect(engine.replaceDerivedLinks(origin, [{ ...row, link_type: 'mentions' }])).rejects.toThrow();
+ await expect(engine.replaceDerivedLinks(origin, [{ ...row, origin_source_id: 'default' }])).rejects.toThrow();
+ await expect(engine.replaceDerivedLinks(origin, [row])).rejects.toThrow();
+ await seed(person, 'company', 'A retyped endpoint.');
+ await expect(engine.replaceDerivedLinks(origin, [row], { expectedEndpoints: [{ slug: person, sourceId, revision: endpoint.revision }] })).rejects.toThrow();
+ const retyped = (await engine.readPageSnapshot(person, { sourceId }))!;
+ await expect(engine.replaceDerivedLinks(origin, [row], { expectedEndpoints: [{ slug: person, sourceId, revision: retyped.revision }] })).rejects.toThrow('person endpoints');
+ expect(await engine.getLinks(person, { sourceId })).toEqual([]);
+ });
+ test('source identities are resolved before reversing qualified Markdown', async () => {
+ const other = 'attendance-other';
+ await engine.executeRaw('DELETE FROM sources WHERE id=$1', [other]);
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES ($1,$1)', [other]);
+ await engine.putPage(person, { type: 'person', title: 'Foreign example', compiled_truth: 'Foreign attendee.' }, { sourceId: other });
+ await seed(meeting, 'meeting', `Attendees: [[${other}:${person}]]`);
+ await engine.setConfig('link_resolution.cross_source', 'true');
+ try {
+ await extract('db');
+ const rows = await engine.executeRaw(`SELECT f.source_id from_source, t.source_id to_source, o.source_id origin_source
+ FROM links l JOIN pages f ON f.id=l.from_page_id JOIN pages t ON t.id=l.to_page_id
+ JOIN pages o ON o.id=l.origin_page_id WHERE o.source_id=$1 AND o.slug=$2`, [sourceId, meeting]);
+ expect(rows).toEqual([{ from_source: other, to_source: sourceId, origin_source: sourceId }]);
+ expect(await engine.getLinks(person, { sourceId })).toEqual([]);
+ expect(await engine.getLinks(person, { sourceIds: [other], requireSafeChunks: true, excludePrivate: true })).toEqual([]);
+ await seed(meeting, 'meeting', 'Removed.');
+ await extract('db');
+ expect(await engine.executeRaw('SELECT 1 FROM links l JOIN pages o ON o.id=l.origin_page_id WHERE o.source_id=$1', [sourceId])).toEqual([]);
+ } finally { await engine.setConfig('link_resolution.cross_source', 'false'); }
+ });
+ for (const body of [
+ '[Alice](../people/alice-example.md) did not attend.',
+ 'Invited [Alice](../people/alice-example.md) for next month.',
+ 'Discussed a proposal from [Alice](../people/alice-example.md).',
+ 'Attendees: [Alice](../people/alice-example.md) (absent)',
+ '## Attendees\n- [Alice](../people/alice-example.md) was invited',
+ '```md\nAttendees: [Alice](../people/alice-example.md)\n```',
+ ]) test(`DB does not promote unsupported evidence: ${body}`, async () => {
+ await seed(meeting, 'meeting', body);
+ await extract('db');
+ expect((await engine.getLinks(meeting, { sourceId })).filter(row => row.link_type === 'attended')).toEqual([]);
+ expect(await attendees()).toEqual([]);
+ });
+ });
+}
+
+describe('shared and filesystem canonical attendance grammar', () => {
+ test('large malformed lists are bounded and never accept a valid prefix', async () => {
+ const { attendanceEvidenceRanges } = await import('../src/core/link-extraction.ts');
+ const started = performance.now();
+ expect(attendanceEvidenceRanges(`${positive} ${'['.repeat(65_536)}`)).toEqual([]);
+ expect(attendanceEvidenceRanges('Attendees: [nested[Alice](../people/alice-example.md)]')).toEqual([]);
+ expect(performance.now() - started).toBeLessThan(500);
+ });
+ const types = new Map([[person, 'person'], ['people/company-example', 'company'], [meeting, 'meeting']]);
+ const resolver = { async resolve(value: string) { return types.has(value) ? value : null; } };
+ test('nonmatching constrained attendance rules preserve pack ownership and outgoing mentions', async () => {
+ const pack = parseSchemaPackManifest({ api_version: 'gbrain-schema-pack-v1', name: 'constrained-attendance',
+ version: '1.0.0', extends: null, page_types: [], frontmatter_links: [],
+ link_types: [{ name: 'attended', inference: { page_type: 'meeting', target_type: 'person', regex: 'confirmed-attendance' } }] });
+ const shared = await extractPageLinks(meeting, positive, {}, 'meeting', resolver, { pack, targetType: slug => types.get(slug) });
+ expect(shared.candidates).toHaveLength(1);
+ expect(shared.candidates[0]).toMatchObject({ targetSlug: person, linkType: 'mentions' });
+ expect(shared.candidates[0].canonicalAttendance).not.toBe(true);
+ const fs = await extractLinksFromFile(`---\ntype: meeting\n---\n${positive}`, `${meeting}.md`, new Set(types.keys()), { pack, pageTypes: types });
+ expect(fs).toHaveLength(1);
+ expect(fs[0]).toMatchObject({ from_slug: meeting, to_slug: person, link_type: 'mentions' });
+ expect(fs[0].origin_slug).toBeUndefined();
+ });
+ test('ambiguous bare attendance names stay nonassertive without changing ordinary expansion', async () => {
+ const targets = new Map([[meeting, 'meeting'], ['demo-example', 'person'], ['đemo-example', 'person']]);
+ for (const body of ['Attendees: [[Đemo Example]]', 'See [[Đemo Example]]']) {
+ const shared = await extractPageLinks(meeting, body, {}, 'meeting', resolver, { targetType: slug => targets.get(slug) });
+ expect(shared.candidates.map(row => row.targetSlug).sort()).toEqual(['demo-example', 'đemo-example']);
+ expect(shared.candidates.every(row => row.linkType === 'mentions' && !row.canonicalAttendance)).toBe(true);
+ const fs = await extractLinksFromFile(`---\ntype: meeting\n---\n${body}`, `${meeting}.md`, new Set(targets.keys()), { pageTypes: targets });
+ expect(fs).toHaveLength(1);
+ expect(fs[0]).toMatchObject({ from_slug: meeting, to_slug: 'đemo-example', link_type: 'mentions' });
+ }
+ targets.delete('demo-example');
+ const body = 'Attendees: [[Đemo Example]]';
+ const shared = await extractPageLinks(meeting, body, {}, 'meeting', resolver, { targetType: slug => targets.get(slug) });
+ expect(shared.candidates.filter(row => row.canonicalAttendance).map(row => row.targetSlug)).toEqual(['đemo-example']);
+ const fs = await extractLinksFromFile(`---\ntype: meeting\n---\n${body}`, `${meeting}.md`, new Set(targets.keys()), { pageTypes: targets });
+ expect(fs[0]).toMatchObject({ from_slug: 'đemo-example', to_slug: meeting, link_type: 'attended' });
+ });
+ test('a canonical mention does not reverse a separate pack-owned edge to the same target', async () => {
+ const pack = parseSchemaPackManifest({ api_version: 'gbrain-schema-pack-v1', name: 'mixed-attendance',
+ version: '1.0.0', extends: null, page_types: [], frontmatter_links: [],
+ link_types: [{ name: 'attended', inference: { regex: '\\bpresent\\b' } }] });
+ const body = `present [Alice](../people/alice-example.md)\n\n${'Notes. '.repeat(100)}\n\n${positive}`;
+ const shared = await extractPageLinks(meeting, body, {}, 'meeting', resolver, { pack, targetType: slug => types.get(slug) });
+ expect(shared.candidates.filter(row => row.linkType === 'attended').map(row => row.canonicalAttendance ?? false).sort()).toEqual([false, true]);
+ const fs = await extractLinksFromFile(`---\ntype: meeting\n---\n${body}`, `${meeting}.md`, new Set(types.keys()), { pack, pageTypes: types });
+ expect(fs.filter(row => row.link_type === 'attended').map(row => row.from_slug).sort()).toEqual([meeting, person]);
+ });
+ const positiveBodies = [positive, 'Attendees: [Alice](people/alice-example.md)', 'Attendees: [[people/alice-example]]',
+ 'Attendees: [Alice](/people/alice-example.md)', '## Attendees\n- [Alice](../people/alice-example.md)\n\n## Notes\nDiscussed work.'];
+ for (const body of positiveBodies) test(body, async () => {
+ const shared = await extractPageLinks(meeting, body, {}, 'meeting', resolver, { targetType: slug => types.get(slug) });
+ expect(shared.candidates.some(row => row.linkType === 'attended' && row.canonicalAttendance)).toBe(true);
+ const fs = await extractLinksFromFile(`---\ntype: meeting\n---\n${body}`, `${meeting}.md`, new Set(types.keys()), { pageTypes: types });
+ expect(fs.some(row => row.link_type === 'attended' && row.from_slug === person && row.origin_slug === meeting)).toBe(true);
+ });
+ for (const body of ['Attendees: [Company](../people/company-example.md)', 'Attendees: [Missing](../people/missing.md)',
+ 'Attendees: [Alice](../people/alice-example.md) maybe', 'Attendees: `not` [Alice](../people/alice-example.md)',
+ '~~~md\nAttendees: [Alice](../people/alice-example.md)\n~~~', ' Attendees: [Alice](../people/alice-example.md)',
+ '## Attendees\n- [Alice](../people/alice-example.md)\nNobody attended.',
+ 'Reference to [Alice](../people/alice-example.md).\n## Attendees\nNobody attended.']) test(`not evidence: ${body}`, async () => {
+ const shared = await extractPageLinks(meeting, body, {}, 'meeting', resolver, { targetType: slug => types.get(slug) });
+ expect(shared.candidates.some(row => row.linkType === 'attended')).toBe(false);
+ const fs = await extractLinksFromFile(`---\ntype: meeting\n---\n${body}`, `${meeting}.md`, new Set(types.keys()), { pageTypes: types });
+ expect(fs.some(row => row.link_type === 'attended')).toBe(false);
+ });
+});
diff --git a/test/cli-recall-flag-ownership.test.ts b/test/cli-recall-flag-ownership.test.ts
new file mode 100644
index 0000000000..9f906614d2
--- /dev/null
+++ b/test/cli-recall-flag-ownership.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { buildFlagRegistry } from '../scripts/generate-flag-registry.ts';
+import { validateCommandFlags } from '../src/cli.ts';
+import { CLI_FLAG_REGISTRY } from '../src/core/cli-flag-registry.generated.ts';
+import { runCli } from './helpers/cli-spawn.ts';
+
+const serveFlags = ['--port', '--bind', '--print-admin-token', '--public-url', '--enable-dcr',
+ '--token-ttl', '--source-guard', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--log-full-params'];
+
+describe('recall and degraded serve flag ownership', () => {
+ test('fresh and committed recall registries reject serve-only flags', () => {
+ const fresh = buildFlagRegistry();
+ for (const flag of serveFlags) {
+ expect(fresh.recall).not.toContain(flag);
+ expect(CLI_FLAG_REGISTRY.recall).not.toContain(flag);
+ expect(validateCommandFlags('recall', [flag])).toBe(flag);
+ expect(fresh.serve).toContain(flag);
+ expect(validateCommandFlags('serve', [flag])).toBeNull();
+ }
+ });
+
+ test('recall retains budget policy and source selectors', () => {
+ for (const args of [
+ ['query', '--budget-policy', 'query_first', '--source-id', 'team-b'],
+ ['query', '--budget-policy=facts_first', '--source-id=default'],
+ ['query', '--budget-policy', 'query_first', '--source', 'team-b', '--budget-tokens', '1024', '--json'],
+ ]) expect(validateCommandFlags('recall', args)).toBeNull();
+ });
+
+ test('think retains valid flags without acquiring serve-only flags', () => {
+ expect(validateCommandFlags('think', ['query', '--with-calibration', '--rounds', '2', '--json'])).toBeNull();
+ for (const flag of serveFlags) expect(validateCommandFlags('think', [flag])).toBe(flag);
+ });
+
+ test.each(['--port', '--print-admin-token'])('real recall rejects %s before opening a brain', async flag => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-recall-flags-'));
+ try {
+ const result = await runCli(['recall', '--query', 'example', flag, '--json'], { home, cwd: home });
+ expect(result.exitCode).toBe(1);
+ expect(result.stderr).toContain(`unknown flag ${flag} for 'gbrain recall'`);
+ expect(JSON.parse(result.stdout)).toMatchObject({ status: 'error', reason: 'invalid_flag' });
+ expect(result.stderr).not.toContain('database_url is missing');
+ expect(result.stdout + result.stderr).not.toContain('Setting up brain schema');
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/test/derived-link-reconciliation.test.ts b/test/derived-link-reconciliation.test.ts
index 6a250a9f5f..bc99a97a34 100644
--- a/test/derived-link-reconciliation.test.ts
+++ b/test/derived-link-reconciliation.test.ts
@@ -71,6 +71,65 @@ for (const kind of ['pglite', ...(process.env.DATABASE_URL ? ['postgres'] : [])]
return { slug, sourceId, expectedRevision: snapshot.revision, sourceIncarnation: snapshot.sourceIncarnation };
}
+ test('reversed basename attendance requires the same origin, revision and person guards as Markdown attendance', async () => {
+ await seed('meetings/planning', 'meeting');
+ await seed('people/alice-example', 'person');
+ const scope = await origin('meetings/planning');
+ const person = (await engine.readPageSnapshot('people/alice-example', { sourceId }))!;
+ const row = { from_slug: person.page.slug, to_slug: scope.slug, link_type: 'attended', link_source: 'wikilink-resolved',
+ from_source_id: sourceId, to_source_id: sourceId, origin_slug: scope.slug, origin_source_id: sourceId };
+ await expect(engine.replaceDerivedLinks(scope, [row])).rejects.toThrow('revision-bound person endpoints');
+ expect(await graph()).toEqual([]);
+ const expectedEndpoints = [{ slug: person.page.slug, sourceId, revision: person.revision }];
+ expect(await engine.replaceDerivedLinks(scope, [row], { expectedEndpoints })).toEqual({ created: 1, removed: 0 });
+ await seed(person.page.slug, 'company');
+ const changed = (await engine.readPageSnapshot(person.page.slug, { sourceId }))!;
+ await expect(engine.replaceDerivedLinks(scope, [row], { expectedEndpoints })).rejects.toThrow('changed after type resolution');
+ await expect(engine.replaceDerivedLinks(scope, [row], { expectedEndpoints: [{ ...expectedEndpoints[0], revision: changed.revision }] }))
+ .rejects.toThrow('person endpoints');
+ });
+
+ test('retained frontmatter identities update and clear evidence metadata', async () => {
+ await seed('meetings/planning', 'meeting');
+ await seed('people/alice-example', 'person');
+ const scope = await origin('meetings/planning');
+ const row = { from_slug: scope.slug, to_slug: 'people/alice-example', link_type: 'attended',
+ link_source: 'frontmatter', from_source_id: sourceId, to_source_id: sourceId,
+ origin_slug: scope.slug, origin_source_id: sourceId, context: 'Original evidence', origin_field: 'attendees' };
+ await engine.replaceDerivedLinks(scope, [row], { preserveExisting: true });
+ const evidence = () => engine.executeRaw<{ id: number; context: string; origin_field: string | null }>(
+ `SELECT id,context,origin_field FROM links WHERE origin_page_id=(SELECT id FROM pages WHERE source_id=$1 AND slug=$2)`,
+ [sourceId, scope.slug]);
+ const before = await evidence();
+ expect(before).toHaveLength(1);
+ expect(await engine.replaceDerivedLinks(scope, [{ ...row, context: 'Updated evidence', origin_field: 'participants' }],
+ { preserveExisting: true })).toEqual({ created: 0, removed: 0 });
+ expect(await evidence()).toEqual([{ id: before[0].id, context: 'Updated evidence', origin_field: 'participants' }]);
+ expect(await engine.replaceDerivedLinks(scope, [{ ...row, context: undefined, origin_field: undefined }],
+ { preserveExisting: true })).toEqual({ created: 0, removed: 0 });
+ expect(await evidence()).toEqual([{ id: before[0].id, context: '', origin_field: null }]);
+ });
+
+ test('preserving replacement rolls back deleted and updated evidence when insertion fails', async () => {
+ await seed('meetings/planning', 'meeting');
+ for (const name of ['alice', 'bob', 'charlie']) await seed(`people/${name}-example`, 'person');
+ const scope = await origin('meetings/planning');
+ const row = (name: string, context: string) => ({ from_slug: scope.slug, to_slug: `people/${name}-example`,
+ link_type: 'attended', link_source: 'frontmatter', from_source_id: sourceId, to_source_id: sourceId,
+ origin_slug: scope.slug, origin_source_id: sourceId, origin_field: 'attendees', context });
+ await engine.replaceDerivedLinks(scope, [row('alice', 'Original evidence'), row('bob', 'Removed evidence')], { preserveExisting: true });
+ const evidence = () => engine.executeRaw(`SELECT * FROM links WHERE origin_page_id=(SELECT id FROM pages
+ WHERE source_id=$1 AND slug=$2) ORDER BY id`, [sourceId, scope.slug]);
+ const before = await evidence();
+ const add = engine.addLinksBatch;
+ engine.addLinksBatch = async () => { throw new Error('Injected insertion failure'); };
+ try {
+ await expect(engine.replaceDerivedLinks(scope, [row('alice', 'Updated evidence'), row('charlie', 'New evidence')],
+ { preserveExisting: true })).rejects.toThrow('Injected insertion failure');
+ } finally { engine.addLinksBatch = add; }
+ expect(await evidence()).toEqual(before);
+ });
+
test('full-source scans resolve new targets and retype unchanged origins without N+1 target reads', async () => {
await seed('rivals/rival-example', 'competitor', 'competes with [[organizations/company-example]].');
let result = await reconcileSourceLinks(engine, sourceId, { pack });
diff --git a/test/e2e/attendance-repair-postgres.test.ts b/test/e2e/attendance-repair-postgres.test.ts
new file mode 100644
index 0000000000..2ff1369aed
--- /dev/null
+++ b/test/e2e/attendance-repair-postgres.test.ts
@@ -0,0 +1 @@
+import '../attendance-repair.test.ts';
diff --git a/test/e2e/attendance-retrieval-postgres.test.ts b/test/e2e/attendance-retrieval-postgres.test.ts
new file mode 100644
index 0000000000..2f7655d07d
--- /dev/null
+++ b/test/e2e/attendance-retrieval-postgres.test.ts
@@ -0,0 +1 @@
+import '../attendance-retrieval.test.ts';
diff --git a/test/e2e/extract-timeline-attendance-postgres.test.ts b/test/e2e/extract-timeline-attendance-postgres.test.ts
new file mode 100644
index 0000000000..af5c0a3efd
--- /dev/null
+++ b/test/e2e/extract-timeline-attendance-postgres.test.ts
@@ -0,0 +1 @@
+import '../extract-timeline-attendance.test.ts';
diff --git a/test/extract-timeline-attendance.test.ts b/test/extract-timeline-attendance.test.ts
new file mode 100644
index 0000000000..ba65234836
--- /dev/null
+++ b/test/extract-timeline-attendance.test.ts
@@ -0,0 +1,154 @@
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { extractTimelineFromMeetings } from '../src/core/extract-timeline-from-meetings.ts';
+import { prepareAutomaticLinks } from '../src/core/persistence/links-preparation.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { resetPgliteState, resetPgliteStateNarrow } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const person = 'people/alice-example';
+const meeting = 'meetings/planning';
+
+for (const kind of ['pglite', ...(process.env.DATABASE_URL ? ['postgres'] : [])]) {
+ describe(`meeting timeline attendance roles (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: (() => Promise<void>) | undefined;
+
+ beforeAll(async () => {
+ if (kind === 'postgres') {
+ ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ } else {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ }
+ }, 240_000);
+
+ afterAll(async () => {
+ if (close) await close();
+ else await engine.disconnect();
+ });
+
+ beforeEach(async () => {
+ if (engine instanceof PGLiteEngine) await resetPgliteState(engine);
+ else await resetPgliteStateNarrow(engine, ['sources', 'config']);
+ await engine.executeRaw("INSERT INTO sources(id, name) VALUES ('team-b', 'Team B')");
+ });
+
+ async function seed(slug: string, type: string, sourceId = 'default', frontmatter: Record<string, unknown> = {}) {
+ await engine.putPage(slug, {
+ type, title: slug === meeting ? 'Planning' : slug,
+ compiled_truth: 'No entity names in this discussion.', timeline: '', frontmatter,
+ effective_date: new Date('2026-04-20T00:00:00Z'),
+ }, { sourceId });
+ }
+
+ async function attended(direction: string, meetingSource = 'default', personSource = 'default', target = person) {
+ const canonical = direction === 'canonical';
+ await engine.addLinksBatch([{
+ from_slug: canonical ? target : meeting,
+ from_source_id: canonical ? personSource : meetingSource,
+ to_slug: canonical ? meeting : target,
+ to_source_id: canonical ? meetingSource : personSource,
+ link_type: 'attended', link_source: 'manual',
+ }]);
+ }
+
+ const extract = (sourceIdFilter?: string) => extractTimelineFromMeetings(engine, {
+ gazetteer: new Map(), sourceIdFilter,
+ });
+
+ test.each([
+ ['gbrain-base-v2', person, meeting],
+ ['gbrain-base', meeting, person],
+ ])('%s qualified evidence reaches the attendee timeline', async (pack, from, to) => {
+ await engine.setConfig('schema_pack', pack);
+ await seed(person, 'person');
+ const page = {
+ type: 'meeting', title: 'Planning', compiled_truth: 'Attendees: [[people/alice-example]]',
+ timeline: '', frontmatter: {}, effective_date: new Date('2026-04-20T00:00:00Z'),
+ };
+ await engine.putPage(meeting, page);
+ const prepared = await prepareAutomaticLinks(engine, meeting, page, 'default');
+ await engine.transaction(async tx => {
+ await tx.lockPageKeys(prepared.pageKeys);
+ return prepared.apply(tx);
+ });
+ expect(await engine.executeRaw(`SELECT f.slug AS from_slug, t.slug AS to_slug FROM links l
+ JOIN pages f ON f.id=l.from_page_id JOIN pages t ON t.id=l.to_page_id
+ WHERE l.link_type='attended'`)).toEqual([{ from_slug: from, to_slug: to }]);
+ expect(await extract()).toMatchObject({ entries_created: 1, entities_touched: 1, batch_errors: 0 });
+ expect(await engine.getTimeline(person, { sourceId: 'default' })).toHaveLength(1);
+ expect(await engine.getTimeline(meeting, { sourceId: 'default' })).toHaveLength(0);
+ });
+
+ test.each(['canonical', 'outgoing'])('%s roles preserve legacy notes, source gates, and duplicate-slug isolation', async direction => {
+ for (const source of ['default', 'team-b']) {
+ await seed(person, 'person', source);
+ await seed(meeting, 'note', source, { legacy_type: 'meeting' });
+ }
+ await attended(direction, 'team-b', 'default');
+ const off = await withEnv({ GBRAIN_LINK_RESOLUTION_CROSS_SOURCE: undefined }, () => extract('team-b'));
+ expect(off).toMatchObject({ meetings_scanned: 1, entries_created: 0 });
+ expect(await withEnv({ GBRAIN_LINK_RESOLUTION_CROSS_SOURCE: '1' }, () => extract('default')))
+ .toMatchObject({ meetings_scanned: 1, entries_created: 0 });
+ expect(await withEnv({ GBRAIN_LINK_RESOLUTION_CROSS_SOURCE: '1' }, () => extract('team-b')))
+ .toMatchObject({ meetings_scanned: 1, entries_created: 1, entities_touched: 1 });
+ expect(await engine.getTimeline(person, { sourceId: 'default' })).toHaveLength(1);
+ expect(await engine.getTimeline(person, { sourceId: 'team-b' })).toHaveLength(0);
+ });
+
+ test.each(['canonical', 'outgoing'])('%s private meetings do not fan out', async direction => {
+ await seed(person, 'person');
+ await seed(meeting, 'meeting', 'default', { visibility: 'private' });
+ await attended(direction);
+ expect(await extract()).toMatchObject({ meetings_scanned: 0, entries_created: 0 });
+ expect(await engine.getTimeline(person, { sourceId: 'default' })).toHaveLength(0);
+ });
+
+ test('both orientations deduplicate with frontmatter dates and repeated extraction', async () => {
+ await seed(person, 'person');
+ await seed(meeting, 'note', 'default', { legacy_type: 'meeting', date: '2026-03-12' });
+ await engine.executeRaw('UPDATE pages SET effective_date=NULL WHERE slug=$1', [meeting]);
+ await attended('canonical');
+ await attended('outgoing');
+ expect(await extract()).toMatchObject({ meetings_scanned: 1, entries_created: 1, entities_touched: 1 });
+ expect(await extract()).toMatchObject({ entries_created: 0 });
+ expect(await engine.executeRaw('SELECT date::text AS date, source, summary FROM timeline_entries')).toEqual([{
+ date: '2026-03-12', source: `extract-timeline-from-meetings:${meeting}`, summary: 'Discussed in Planning',
+ }]);
+ });
+
+ test.each(['canonical', 'outgoing'])('%s attendance respects since and refuses import-only dates', async direction => {
+ await seed(person, 'person');
+ await seed(meeting, 'meeting');
+ await attended(direction);
+ await engine.executeRaw("UPDATE pages SET updated_at='2026-04-20T00:00:00Z' WHERE slug=$1", [meeting]);
+ expect(await extractTimelineFromMeetings(engine, { gazetteer: new Map(), since: '2026-04-20T00:00:00Z' }))
+ .toMatchObject({ meetings_scanned: 0, entries_created: 0 });
+ await engine.executeRaw('UPDATE pages SET effective_date=NULL WHERE slug=$1', [meeting]);
+ expect(await extract()).toMatchObject({ meetings_scanned: 0, entries_created: 0 });
+ expect(await engine.getTimeline(person, { sourceId: 'default' })).toHaveLength(0);
+ });
+
+ test.each(['canonical', 'outgoing'])('%s edges require a person attendee and a live typed meeting', async direction => {
+ await seed(person, 'person');
+ await seed(meeting, 'meeting');
+ for (const type of ['note', 'company', 'meeting']) {
+ const slug = `entities/${type}-example`;
+ await seed(slug, type);
+ await attended(direction, 'default', 'default', slug);
+ }
+ expect(await extract()).toMatchObject({ entries_created: 0 });
+ await attended(direction);
+ await engine.executeRaw('UPDATE pages SET deleted_at=NOW() WHERE slug=$1', [person]);
+ expect(await extract()).toMatchObject({ entries_created: 0 });
+ await engine.executeRaw('UPDATE pages SET deleted_at=NULL WHERE slug=$1', [person]);
+ await engine.executeRaw("UPDATE pages SET type='note' WHERE slug=$1", [meeting]);
+ expect(await extract()).toMatchObject({ entries_created: 0 });
+ await engine.executeRaw("UPDATE pages SET type='meeting', deleted_at=NOW() WHERE slug=$1", [meeting]);
+ expect(await extract()).toMatchObject({ entries_created: 0 });
+ });
+ });
+}
diff --git a/test/link-inference-constraints.test.ts b/test/link-inference-constraints.test.ts
index 65887d6d3a..707be75803 100644
--- a/test/link-inference-constraints.test.ts
+++ b/test/link-inference-constraints.test.ts
@@ -46,10 +46,14 @@ describe('conjunctive link inference', () => {
test('legacy meeting inference does not label decision or unknown links attended', async () => {
expect(inferLinkType('meeting', 'Attendees', undefined, 'decisions/choice')).toBe('mentions');
for (const active of [null, pack, { ...pack, link_types: [{ name: 'attended', inference: { page_type: 'meeting' } }] }]) {
- const result = await extractPageLinks('sessions/weekly', 'See [[choices/choice]] and [[members/alice-example]].', {}, 'meeting',
+ const result = await extractPageLinks('sessions/weekly', 'Attendees: [[choices/choice]], [[members/alice-example]]', {}, 'meeting',
{ resolve: async () => null }, { pack: active, targetType: slug => slug.startsWith('members/') ? 'person' : 'decision' });
expect(result.candidates.find(c => c.targetSlug === 'choices/choice')?.linkType).toBe('mentions');
expect(result.candidates.find(c => c.targetSlug === 'members/alice-example')?.linkType).toBe('attended');
+ const withoutEvidence = await extractPageLinks('sessions/weekly', 'See [[choices/choice]] and [[members/alice-example]].', {}, 'meeting',
+ { resolve: async () => null }, { pack: active, targetType: slug => slug.startsWith('members/') ? 'person' : 'decision' });
+ expect(withoutEvidence.candidates.find(c => c.targetSlug === 'choices/choice')?.linkType).toBe('mentions');
+ expect(withoutEvidence.candidates.find(c => c.targetSlug === 'members/alice-example')?.linkType).toBe(active ? 'attended' : 'mentions');
}
});
diff --git a/test/persistence-journal.test.ts b/test/persistence-journal.test.ts
index c7113f4ec3..0a3388e89c 100644
--- a/test/persistence-journal.test.ts
+++ b/test/persistence-journal.test.ts
@@ -133,6 +133,45 @@ describe('durable mutation journal', () => {
await cancelWriteRequest(engine, a.principal, a.requestId!);
});
+ test('Postgres admission progresses while short counter transactions keep the lock queue occupied', async () => {
+ const engine = engines.find(candidate => candidate.kind === 'postgres');
+ if (!engine) return;
+ const a = await admission(engine, 'admission-queue-progress');
+ await engine.executeRaw("INSERT INTO persistence_counters(key) VALUES('brain') ON CONFLICT DO NOTHING");
+ const [before] = await engine.executeRaw<{ lifetime_ids: string }>("SELECT lifetime_ids::text FROM persistence_counters WHERE key='brain'");
+ let stop = false;
+ let cycles = 0;
+ const lockers: Promise<void>[] = [];
+ const ready = Array.from({ length: 2 }, () => {
+ let held!: () => void;
+ const holding = new Promise<void>(resolve => { held = resolve; });
+ lockers.push((async () => {
+ while (!stop) await engine.transaction(async tx => {
+ await tx.executeRaw("SELECT key FROM persistence_counters WHERE key='brain' FOR UPDATE");
+ cycles++;
+ held();
+ await Bun.sleep(40);
+ });
+ })());
+ return holding;
+ });
+ let accepted: Awaited<ReturnType<typeof admitWrite>>;
+ try {
+ await Promise.all(ready);
+ accepted = await admitWrite(engine, a);
+ } finally {
+ stop = true;
+ await Promise.all(lockers);
+ }
+ expect(cycles).toBeGreaterThan(2);
+ expect(accepted.state).toBe('queued');
+ expect(accepted.request_id).toBe(a.requestId!);
+ expect((await admitWrite(engine, a)).id).toBe(accepted.id);
+ const [after] = await engine.executeRaw<{ lifetime_ids: string }>("SELECT lifetime_ids::text FROM persistence_counters WHERE key='brain'");
+ expect(Number(after.lifetime_ids) - Number(before.lifetime_ids)).toBe(1);
+ await cancelWriteRequest(engine, a.principal, a.requestId!);
+ }, 15000);
+
test('contended admissions release PostgreSQL pool capacity for reads before the counter unlocks', async () => {
const engine = engines.find(candidate => candidate.kind === 'postgres');
if (!engine) return;
diff --git a/test/protocol-document.test.ts b/test/protocol-document.test.ts
index edbf49b9ac..862c013bb3 100644
--- a/test/protocol-document.test.ts
+++ b/test/protocol-document.test.ts
@@ -21,6 +21,7 @@
import { describe, expect, test } from 'bun:test';
import { buildProtocolDocument } from '../src/commands/protocol.ts';
import { MEMORY_VERBS_VERSION, VERB_NAMES } from '../src/core/verbs.ts';
+import { validateAgainstSchema } from '../src/core/verbs/conformance.ts';
interface VerbEntry {
description: string;
@@ -121,4 +122,42 @@ describe('buildProtocolDocument — MEMORY_VERBS v1 document shape', () => {
// Error envelopes ride the same frozen version stamp.
expect(props.protocol_version.const).toBe(1);
});
+
+ test('recall advertises optional budget accounting without changing its required fields or version', () => {
+ const schema = verbs.recall.response_schema!;
+ expect(schema.required).toEqual(['facts', 'total', 'protocol_version']);
+ expect(validateAgainstSchema({ facts: [], total: 0, protocol_version: 1 }, schema)).toEqual([]);
+ const properties = schema.properties as Record<string, any>;
+ expect(properties.protocol_version.const).toBe(1);
+ expect(properties.budget_packing).toMatchObject({
+ type: 'object', required: ['policy', 'applied', 'reason', 'facts', 'results'],
+ properties: {
+ policy: { type: 'string', enum: ['facts_first', 'query_first'] },
+ applied: { type: 'boolean' },
+ reason: { type: 'string', enum: ['no_query', 'no_positive_finite_budget', 'budget_below_one', 'no_candidates', 'first_items_exceed_budget', 'packed'] },
+ },
+ });
+ for (const arm of ['facts', 'results']) {
+ expect(properties.budget_packing.properties[arm]).toMatchObject({
+ type: 'object', required: ['candidates', 'kept', 'dropped', 'used'],
+ properties: {
+ candidates: { type: 'integer' }, kept: { type: 'integer' },
+ dropped: { type: 'integer' }, used: { type: 'integer' },
+ },
+ });
+ }
+ });
+
+ test.each([
+ { policy: 'unknown' }, { applied: 'yes' }, { reason: 'unknown' },
+ { facts: { candidates: 1, kept: 1, dropped: 0, used: 0.5 } },
+ { results: { kept: 0, dropped: 0, used: 0 } },
+ ])('recall schema rejects malformed opted-in accounting: %j', invalid => {
+ const arm = { candidates: 0, kept: 0, dropped: 0, used: 0 };
+ const valid = { facts: [], total: 0, protocol_version: 1,
+ budget_packing: { policy: 'query_first', applied: true, reason: 'no_candidates', facts: arm, results: arm } };
+ expect(validateAgainstSchema(valid, verbs.recall.response_schema!)).toEqual([]);
+ expect(validateAgainstSchema({ ...valid, budget_packing: { ...valid.budget_packing, ...invalid } },
+ verbs.recall.response_schema!).length).toBeGreaterThan(0);
+ });
});
diff --git a/test/recall-budget-policy-thin-cli.test.ts b/test/recall-budget-policy-thin-cli.test.ts
new file mode 100644
index 0000000000..8856e054e3
--- /dev/null
+++ b/test/recall-budget-policy-thin-cli.test.ts
@@ -0,0 +1,216 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { runCli } from './helpers/cli-spawn.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';
+import { installFixtureChunks } from './helpers/page-projection.ts';
+import { ERROR_SCHEMA } from '../src/core/verbs.ts';
+import { validateAgainstSchema } from '../src/core/verbs/conformance.ts';
+
+const response = { facts: [], results: [], total: 0, protocol_version: 1,
+ budget_tokens: 0, budget_used: 0, dropped_count: 0,
+ budget_packing: { policy: 'query_first', applied: true, reason: 'budget_below_one',
+ facts: { candidates: 0, kept: 0, dropped: 0, used: 0 },
+ results: { candidates: 0, kept: 0, dropped: 0, used: 0 } } };
+
+async function thinCall(engine: 'postgres' | 'pglite', args: string[], options: {
+ source?: string; dispatch?: (args: Record<string, unknown>) => Promise<unknown>;
+} = {}) {
+ const calls: Array<{ name?: string; arguments?: Record<string, unknown> }> = [];
+ const server = Bun.serve({ hostname: '127.0.0.1', port: 0, async fetch(request): Promise<Response> {
+ const path = new URL(request.url).pathname;
+ const base = `http://127.0.0.1:${server.port}`;
+ if (path === '/.well-known/oauth-authorization-server') return Response.json({ issuer: base, token_endpoint: `${base}/token` });
+ if (path === '/token') return Response.json({ access_token: 'fixture', token_type: 'bearer', expires_in: 3600, scope: 'read' });
+ if (path !== '/mcp' || request.method !== 'POST') return new Response(null, { status: 405 });
+ const body = await request.json() as { id?: number; method: string;
+ params?: { protocolVersion?: string; name?: string; arguments?: Record<string, unknown> } };
+ if (body.id === undefined) return new Response(null, { status: 202 });
+ if (body.method === 'initialize') return Response.json({ jsonrpc: '2.0', id: body.id, result: {
+ protocolVersion: body.params?.protocolVersion, capabilities: { tools: {} }, serverInfo: { name: 'fixture', version: '1' },
+ } });
+ if (body.method !== 'tools/call') return new Response(null, { status: 400 });
+ calls.push({ name: body.params?.name, arguments: body.params?.arguments });
+ return Response.json({ jsonrpc: '2.0', id: body.id,
+ result: options.dispatch ? await options.dispatch(body.params?.arguments ?? {})
+ : { content: [{ type: 'text', text: JSON.stringify(response) }] } });
+ } });
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-recall-thin-cli-'));
+ const brain = join(home, '.gbrain');
+ const databasePath = join(brain, 'brain.pglite');
+ mkdirSync(brain);
+ writeFileSync(join(brain, 'config.json'), JSON.stringify({ engine, database_path: databasePath, remote_mcp: {
+ issuer_url: `http://127.0.0.1:${server.port}`, mcp_url: `http://127.0.0.1:${server.port}/mcp`,
+ oauth_client_id: 'fixture', oauth_client_secret: 'fixture',
+ } }));
+ try {
+ const result = await runCli(['recall', ...args], { home, cwd: home, timeoutMs: 20_000, env: {
+ GBRAIN_SOURCE: options.source, GBRAIN_BRAIN_ID: 'host', GBRAIN_NO_BANNER: '1', GBRAIN_MODEL_DISCOVERY: 'off',
+ ANTHROPIC_API_KEY: undefined, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined,
+ } });
+ return { ...result, calls, localStoreCreated: existsSync(databasePath) };
+ } finally {
+ await server.stop(true);
+ rmSync(home, { recursive: true, force: true });
+ }
+}
+
+for (const engine of ['postgres', 'pglite'] as const) {
+ test(`${engine}-shaped thin CLI forwards opted-in recall before opening a local database`, async () => {
+ const policy = engine === 'postgres' ? ['--budget-policy', 'query_first'] : ['--budget-policy=query_first'];
+ const result = await thinCall(engine, ['topics/example', '--query', 'zebra telescope', '--budget-tokens', '0.5',
+ ...policy, '--session-id', 'session-example', '--since', '2026-09-01', '--grep', 'needle',
+ '--supersessions', '--include-expired', '--pending', '--source', 'example', '--json']);
+ expect({ code: result.exitCode, stderr: result.stderr }).toMatchObject({ code: 0 });
+ expect(JSON.parse(result.stdout)).toEqual(response);
+ expect(result.calls).toEqual([{ name: 'recall', arguments: {
+ entity: 'topics/example', query: 'zebra telescope', budget_tokens: 0.5, budget_policy: 'query_first',
+ session_id: 'session-example', since: '2026-09-01T00:00:00.000Z', grep: 'needle',
+ supersessions: true, include_expired: true, include_pending: true, source_id: 'example', limit: 50,
+ } }]);
+ expect(result.localStoreCreated).toBe(false);
+ expect(result.stdout + result.stderr).not.toContain('Setting up brain schema');
+ });
+}
+
+test.each([
+ ['--budget-policy', '--json'],
+ ['--budget-policy=unknown', '--json'],
+ ['--budget-policy', 'query_first', '--watch', '10', '--json'],
+].map(args => [args]))('thin CLI rejects invalid policy requests before local or remote work: %j', async args => {
+ const result = await thinCall('postgres', args);
+ expect(result.exitCode).toBe(1);
+ expect(JSON.parse(result.stdout)).toMatchObject({ error: 'invalid_params' });
+ expect(result.calls).toEqual([]);
+ expect(result.localStoreCreated).toBe(false);
+});
+
+test('a query value spelling the policy flag does not opt a legacy thin call into new routing', async () => {
+ const result = await thinCall('postgres', ['--query', '--budget-policy', '--json']);
+ expect(result.exitCode).toBe(1);
+ expect(result.stderr).toContain('database_url is missing');
+ expect(result.calls).toEqual([]);
+ expect(result.localStoreCreated).toBe(false);
+});
+
+test('explicit thin brain selection fails before remote or local work', async () => {
+ const result = await thinCall('postgres', ['--budget-policy', 'query_first', '--brain', 'unregistered-example', '--json']);
+ expect(result.exitCode).toBe(1);
+ expect(result.stderr).toContain('--brain is not supported on a thin-client install');
+ expect(result.calls).toEqual([]);
+ expect(result.localStoreCreated).toBe(false);
+});
+
+test.each(['query_first', 'facts_first'])('thin %s JSON preserves a remote read error envelope without a mutation receipt', async policy => {
+ const error = { error: 'unavailable', message: 'Synthetic service unavailable', suggestion: 'Retry this read later.',
+ detail: 'fixture_read_failure', docs: 'https://example.test/help', protocol_version: 1 };
+ const result = await thinCall('postgres', ['--budget-policy', policy, '--json'], {
+ dispatch: async () => ({ isError: true, content: [{ type: 'text', text: JSON.stringify(error) }] }),
+ });
+ expect(result.exitCode).toBe(1);
+ expect(JSON.parse(result.stdout)).toEqual(error);
+ expect(validateAgainstSchema(JSON.parse(result.stdout), ERROR_SCHEMA)).toEqual([]);
+ expect(result.stderr).toContain('Synthetic service unavailable');
+ expect(result.calls).toHaveLength(1);
+ expect(result.localStoreCreated).toBe(false);
+});
+
+test('thin policy renders an unstructured remote failure as a stamped unavailable error', async () => {
+ const result = await thinCall('postgres', ['--budget-policy', 'query_first', '--json'], {
+ dispatch: async () => ({ isError: true, content: [{ type: 'text', text: 'Synthetic unstructured failure' }] }),
+ });
+ expect(result.exitCode).toBe(1);
+ const error = JSON.parse(result.stdout);
+ expect(error).toMatchObject({ error: 'unavailable', protocol_version: 1 });
+ expect(error.message).toContain('Synthetic unstructured failure');
+ expect(error.suggestion).toBeTruthy();
+ expect(validateAgainstSchema(error, ERROR_SCHEMA)).toEqual([]);
+ expect(result.localStoreCreated).toBe(false);
+});
+
+describe('actual remote source selection', () => {
+ let remote: PGLiteEngine;
+ beforeAll(async () => {
+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });
+ remote = new PGLiteEngine();
+ await remote.connect({});
+ await remote.initSchema();
+ });
+ afterAll(async () => {
+ await remote.disconnect();
+ resetGateway();
+ });
+ test('thin recall actually narrows both evidence arms on the remote dispatcher', async () => {
+ await remote.setConfig('search.track_retrieval', 'false');
+ await remote.setConfig('mcp.strict_params', 'reject');
+ for (const source of ['default', 'peer', 'denied']) {
+ if (source !== 'default') await remote.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [source]);
+ const text = `Telescope evidence from ${source}.`;
+ await remote.putPage('notes/telescope', { type: 'note', title: 'Telescope', compiled_truth: text }, { sourceId: source });
+ await installFixtureChunks(remote, 'notes/telescope', [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: text }], { sourceId: source });
+ await remote.insertFact({ fact: text, source: 'synthetic', visibility: 'world' }, { source_id: source });
+ }
+ await remote.executeRaw("INSERT INTO sources(id,name,archived) VALUES('archived-example','archived-example',true)");
+ const dispatch = (args: Record<string, unknown>) => dispatchToolCall(remote, 'recall', args, {
+ remote: true, sourceId: 'default', auth: { allowedSources: ['default', 'peer', 'ghost-example', 'archived-example'] }, config: {},
+ } as never);
+ const cases = [
+ { flags: [], ambient: undefined, expected: ['default', 'peer'], wire: undefined },
+ { flags: ['--source', 'default'], ambient: 'peer', expected: ['default'], wire: 'default' },
+ { flags: ['--source', 'peer'], ambient: undefined, expected: ['peer'], wire: 'peer' },
+ { flags: ['--source-id=peer'], ambient: undefined, expected: ['peer'], wire: 'peer' },
+ { flags: [], ambient: 'peer', expected: ['peer'], wire: 'peer' },
+ ];
+ for (const entry of cases) {
+ const result = await thinCall('postgres', ['--query', 'telescope', '--budget-policy', 'query_first', '--budget-tokens', '1000', '--json', ...entry.flags], { dispatch, source: entry.ambient });
+ expect({ code: result.exitCode, stderr: result.stderr }).toMatchObject({ code: 0 });
+ const body = JSON.parse(result.stdout);
+ const expected = entry.expected.map(source => `Telescope evidence from ${source}.`).sort();
+ expect(body.facts.map((row: any) => row.fact).sort()).toEqual(expected);
+ expect(body.results.map((row: any) => row.chunk).sort()).toEqual(expected);
+ expect(result.calls[0].arguments?.source_id).toBe(entry.wire);
+ expect(result.localStoreCreated).toBe(false);
+ }
+ const denied = await thinCall('postgres', ['--budget-policy', 'query_first', '--source', 'denied', '--json'], { dispatch });
+ expect(denied.exitCode).not.toBe(0);
+ expect(JSON.parse(denied.stdout)).toMatchObject({ error: 'scope_denied', detail: 'permission_denied', protocol_version: 1 });
+ expect(validateAgainstSchema(JSON.parse(denied.stdout), ERROR_SCHEMA)).toEqual([]);
+ expect(denied.stdout + denied.stderr).not.toContain('Telescope evidence from denied.');
+ expect(denied.localStoreCreated).toBe(false);
+ const allAmbient = await thinCall('postgres', ['--budget-policy', 'query_first', '--json'], { dispatch, source: '__all__' });
+ expect(allAmbient.exitCode).not.toBe(0);
+ expect(JSON.parse(allAmbient.stdout)).toMatchObject({ error: 'invalid_params', protocol_version: 1 });
+ expect(validateAgainstSchema(JSON.parse(allAmbient.stdout), ERROR_SCHEMA)).toEqual([]);
+ expect(allAmbient.stdout + allAmbient.stderr).toContain('invalid_params');
+ expect(allAmbient.stdout + allAmbient.stderr).not.toContain('Telescope evidence');
+ expect(allAmbient.localStoreCreated).toBe(false);
+ const allExplicit = await thinCall('postgres', ['--budget-policy', 'query_first', '--source', '__all__', '--json'], { dispatch });
+ expect(allExplicit.exitCode).not.toBe(0);
+ expect(JSON.parse(allExplicit.stdout)).toMatchObject({ error: 'invalid_params', protocol_version: 1 });
+ expect(validateAgainstSchema(JSON.parse(allExplicit.stdout), ERROR_SCHEMA)).toEqual([]);
+ expect(allExplicit.calls).toEqual([]);
+ expect(allExplicit.localStoreCreated).toBe(false);
+ for (const source of ['ghost-example', 'archived-example']) {
+ const missing = await thinCall('postgres', ['--budget-policy', 'query_first', '--source', source, '--json'], { dispatch });
+ expect(missing.exitCode).not.toBe(0);
+ const error = JSON.parse(missing.stdout);
+ expect(error).toMatchObject({ error: 'not_found', detail: 'unknown_source', protocol_version: 1 });
+ expect(validateAgainstSchema(error, ERROR_SCHEMA)).toEqual([]);
+ expect(missing.stdout + missing.stderr).not.toContain('Telescope evidence');
+ expect(missing.localStoreCreated).toBe(false);
+ }
+ for (const source of ['Bad Source', '__all__']) {
+ const invalid = await thinCall('postgres', ['--budget-policy', 'query_first', '--json'], { dispatch, source });
+ expect(invalid.exitCode).not.toBe(0);
+ const error = JSON.parse(invalid.stdout);
+ expect(error).toMatchObject({ error: 'invalid_params', protocol_version: 1 });
+ expect(validateAgainstSchema(error, ERROR_SCHEMA)).toEqual([]);
+ expect(invalid.calls).toEqual([]);
+ expect(invalid.localStoreCreated).toBe(false);
+ }
+ }, 90_000);
+});
diff --git a/test/recall-budget-policy-thin.serial.test.ts b/test/recall-budget-policy-thin.serial.test.ts
new file mode 100644
index 0000000000..71a45cd753
--- /dev/null
+++ b/test/recall-budget-policy-thin.serial.test.ts
@@ -0,0 +1,43 @@
+import { afterAll, beforeEach, expect, mock, test } from 'bun:test';
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-budget-thin-'));
+mkdirSync(join(home, '.gbrain'));
+writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite' }));
+process.env.GBRAIN_HOME = home;
+delete process.env.GBRAIN_SOURCE;
+const calls: Array<Record<string, unknown>> = [];
+const response = { facts: [], results: [], total: 0, budget_tokens: 0, budget_used: 0, dropped_count: 0,
+ budget_packing: { policy: 'query_first', applied: true, reason: 'budget_below_one' } };
+const realConfig = await import('../src/core/config.ts');
+mock.module('../src/core/config.ts', () => ({ ...realConfig, isThinClient: () => true }));
+const realMcp = await import('../src/core/mcp-client.ts');
+mock.module('../src/core/mcp-client.ts', () => ({ ...realMcp,
+ callRemoteTool: async (_config: unknown, name: string, params: Record<string, unknown>) => {
+ expect(name).toBe('recall');
+ calls.push(params);
+ return { content: [{ type: 'text', text: JSON.stringify(response) }] };
+ },
+}));
+const { runRecall } = await import('../src/commands/recall.ts');
+
+beforeEach(() => { calls.length = 0; });
+afterAll(() => { rmSync(home, { recursive: true, force: true }); });
+
+test('opt-in thin recall forwards fractional budgets and all fact filters without touching a local engine', async () => {
+ let output = '';
+ const write = process.stdout.write;
+ process.stdout.write = ((chunk: string) => { output += chunk; return true; }) as typeof write;
+ try {
+ await runRecall({} as never, ['topics/example', '--query', 'zebra telescope', '--budget-tokens', '0.5',
+ '--budget-policy', 'query_first', '--session-id', 'session-example', '--since', '2026-09-01',
+ '--grep', 'needle', '--supersessions', '--include-expired', '--pending', '--source', 'example', '--json']);
+ } finally { process.stdout.write = write; }
+ expect(calls).toHaveLength(1);
+ expect(calls[0]).toMatchObject({ entity: 'topics/example', query: 'zebra telescope', budget_tokens: 0.5,
+ budget_policy: 'query_first', session_id: 'session-example', since: '2026-09-01T00:00:00.000Z', grep: 'needle',
+ supersessions: true, include_expired: true, include_pending: true, source_id: 'example', limit: 50 });
+ expect(JSON.parse(output)).toEqual(response);
+});
diff --git a/test/recall-budget-policy-transports.test.ts b/test/recall-budget-policy-transports.test.ts
new file mode 100644
index 0000000000..99dcd58de8
--- /dev/null
+++ b/test/recall-budget-policy-transports.test.ts
@@ -0,0 +1,270 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { spawnSync } from 'node:child_process';
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';
+import { keylessBrainEnv } from './helpers/provider-env.ts';
+import { installFixtureChunks } from './helpers/page-projection.ts';
+import { ERROR_SCHEMA } from '../src/core/verbs.ts';
+import { validateAgainstSchema } from '../src/core/verbs/conformance.ts';
+
+let engine: PGLiteEngine;
+let home: string;
+let env: Record<string, string>;
+const cli = resolve('src/cli.ts');
+const params = { query: 'zebra telescope', budget_tokens: 75, budget_policy: 'query_first' };
+
+beforeAll(async () => {
+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });
+ home = mkdtempSync(join(tmpdir(), 'gbrain-recall-budget-transport-'));
+ const brain = join(home, '.gbrain');
+ mkdirSync(brain, { recursive: true });
+ const databasePath = join(brain, 'brain.pglite');
+ writeFileSync(join(brain, 'config.json'), JSON.stringify({ engine: 'pglite', database_path: databasePath }));
+ env = keylessBrainEnv(process.env, home, {
+ DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, GBRAIN_SOURCE: undefined,
+ GBRAIN_REMOTE_CLIENT_SECRET: undefined, GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_MODEL_DISCOVERY: 'off',
+ });
+ engine = new PGLiteEngine();
+ await engine.connect({ database_path: databasePath });
+ await engine.initSchema();
+ await engine.setConfig('search.track_retrieval', 'false');
+ const text = 'The zebra telescope calibration code is QX-17. Store it in the blue case.';
+ await engine.putPage('notes/telescope', { type: 'note', title: 'Zebra telescope', compiled_truth: text });
+ await installFixtureChunks(engine, 'notes/telescope', [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: text }]);
+ for (let i = 0; i < 4; i++) {
+ await engine.insertFact({
+ fact: `Garden observation ${i}: `.padEnd(144, 'x'), source: 'synthetic', visibility: 'world',
+ entity_slug: 'topics/garden', source_session: `garden-session-${i}`, valid_from: new Date(`2026-09-01T00:00:0${i}Z`),
+ }, { source_id: 'default' });
+ }
+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES('peer','peer'),('archived-example','archived-example')");
+ await engine.executeRaw("UPDATE sources SET config=jsonb_build_object('federated',false) WHERE id='peer'");
+ await engine.executeRaw("UPDATE sources SET archived=true, archived_at=now() WHERE id='archived-example'");
+ await engine.putPage('notes/telescope', { type: 'note', title: 'Zebra telescope', compiled_truth: 'Peer telescope evidence.' }, { sourceId: 'peer' });
+ await installFixtureChunks(engine, 'notes/telescope', [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Peer telescope evidence.' }], { sourceId: 'peer' });
+ await engine.insertFact({ fact: 'Peer source fact.', source: 'synthetic', visibility: 'world' }, { source_id: 'peer' });
+ await engine.disconnect();
+});
+
+afterAll(async () => {
+ if (engine) await engine.disconnect();
+ if (home) rmSync(home, { recursive: true, force: true });
+ resetGateway();
+});
+
+function call(args: string[], overrides: Record<string, string> = {}) {
+ return spawnSync(process.execPath, ['--no-env-file', cli, ...args], {
+ cwd: home, env: { ...env, ...overrides }, encoding: 'utf8', timeout: 60_000,
+ });
+}
+
+describe('recall policy through actual CLI and stdio MCP', () => {
+ test.each(['ghost-example', 'archived-example'])('local policy refuses an unavailable concrete source: %s', source => {
+ const result = call(['recall', '--budget-policy', 'query_first', '--source', source, '--json']);
+ expect(result.status).not.toBe(0);
+ const error = JSON.parse(result.stdout);
+ expect(error).toMatchObject({ error: 'not_found', detail: 'unknown_source', protocol_version: 1 });
+ expect(validateAgainstSchema(error, ERROR_SCHEMA)).toEqual([]);
+ });
+
+ test('local policy refuses an unknown ambient source instead of falling back to default', () => {
+ const result = call(['recall', '--budget-policy', 'query_first', '--json'], { GBRAIN_SOURCE: 'ghost-example' });
+ expect(result.status).not.toBe(0);
+ const error = JSON.parse(result.stdout);
+ expect(error).toMatchObject({ error: 'not_found', detail: 'unknown_source', protocol_version: 1 });
+ expect(validateAgainstSchema(error, ERROR_SCHEMA)).toEqual([]);
+ });
+
+ test.each(['__all__', 'Bad Source'])('local policy renders invalid explicit and ambient selector %s as v1 JSON', source => {
+ for (const result of [
+ call(['recall', '--budget-policy', 'query_first', '--source', source, '--json']),
+ call(['recall', '--budget-policy', 'query_first', '--json'], { GBRAIN_SOURCE: source }),
+ ]) {
+ expect(result.status).not.toBe(0);
+ const error = JSON.parse(result.stdout);
+ expect(error).toMatchObject({ error: 'invalid_params', protocol_version: 1 });
+ expect(validateAgainstSchema(error, ERROR_SCHEMA)).toEqual([]);
+ expect(result.stdout).not.toContain('Garden observation');
+ }
+ });
+
+ test('local fallback source failures are v1 JSON while omitted-policy fallback stays unchanged', async () => {
+ const database_path = join(home, '.gbrain', 'brain.pglite');
+ await engine.connect({ database_path });
+ await engine.setConfig('sources.default', 'archived-example');
+ await engine.disconnect();
+ try {
+ const result = call(['recall', '--budget-policy', 'query_first', '--json']);
+ expect(result.status).not.toBe(0);
+ const error = JSON.parse(result.stdout);
+ expect(error).toMatchObject({ error: 'not_found', detail: 'unknown_source', protocol_version: 1 });
+ expect(validateAgainstSchema(error, ERROR_SCHEMA)).toEqual([]);
+ const legacy = call(['recall', '--query', 'zebra telescope', '--json']);
+ expect(legacy.status).toBe(0);
+ expect(JSON.parse(legacy.stdout).facts).toHaveLength(4);
+ expect(legacy.stderr).toContain('Falling back to literal value');
+ } finally {
+ await engine.connect({ database_path });
+ await engine.setConfig('sources.default', 'default');
+ await engine.disconnect();
+ }
+ });
+
+ test('local policy explicit default overrides an ambient peer for both arms', () => {
+ const result = call(['recall', '--query', 'zebra telescope', '--budget-policy', 'query_first', '--source', 'default', '--json'],
+ { GBRAIN_SOURCE: 'peer' });
+ expect(result.status).toBe(0);
+ const body = JSON.parse(result.stdout);
+ expect(body.facts).toHaveLength(4);
+ expect(body.facts.some((row: any) => row.fact === 'Peer source fact.')).toBe(false);
+ expect(body.results.map((row: any) => row.chunk)).toEqual(['The zebra telescope calibration code is QX-17. Store it in the blue case.']);
+ });
+
+ test('gbrain protocol --json advertises optional recall input and response policy fields', () => {
+ const result = call(['protocol', '--json']);
+ expect(result.status).toBe(0);
+ const document = JSON.parse(result.stdout);
+ expect(document.protocol_version).toBe(1);
+ expect(document.verbs.recall.input_schema.properties.budget_policy.enum).toEqual(['facts_first', 'query_first']);
+ expect(document.verbs.recall.response_schema.required).toEqual(['facts', 'total', 'protocol_version']);
+ expect(document.verbs.recall.response_schema.properties.budget_packing.properties.policy.enum).toEqual(['facts_first', 'query_first']);
+ });
+
+ test.each([
+ ['--budget-policy', 'query_first', '--query', 'zebra telescope', '--budget-tokens', '75'],
+ ['--budget-tokens', '75', '--query', 'zebra telescope', '--budget-policy', 'query_first'],
+ ['--query', 'zebra telescope', '--budget-policy=query_first', '--budget-tokens', '75'],
+ ].map(args => [args]))('named recall forwards policy regardless of option order: %j', args => {
+ const result = call(['recall', ...args, '--json']);
+ expect(result.status).toBe(0);
+ const body = JSON.parse(result.stdout);
+ expect(body.results.map((r: any) => r.slug)).toEqual(['notes/telescope']);
+ expect(body.budget_used).toBe(59);
+ expect(body.budget_packing).toMatchObject({ policy: 'query_first', applied: true });
+ });
+
+ test.each([
+ ['--budget-policy', 'query_first', '--budget-tokens', '0.5', '--query', 'zebra telescope'],
+ ['--budget-tokens', '0.5', '--query', 'zebra telescope', '--budget-policy', 'query_first'],
+ ].map(args => [args]))('named query-first retains a positive sub-one budget until the operation floors it: %j', args => {
+ const result = call(['recall', ...args, '--json']);
+ expect(result.status).toBe(0);
+ expect(JSON.parse(result.stdout)).toMatchObject({
+ facts: [], results: [], total: 0, budget_tokens: 0, budget_used: 0, dropped_count: 5,
+ budget_packing: { policy: 'query_first', applied: true, reason: 'budget_below_one' },
+ });
+ });
+
+ test.each(['0.5', '75.9', '5e1', '75junk'])('omitted and explicit facts_first retain legacy budget parsing for %s', budget => {
+ const args = ['recall', '--query', 'zebra telescope', '--budget-tokens', budget, '--json'];
+ const omitted = call(args);
+ const explicit = call([...args, '--budget-policy', 'facts_first']);
+ expect(omitted.status).toBe(0);
+ expect(explicit.status).toBe(0);
+ const legacy = JSON.parse(omitted.stdout);
+ const { budget_packing, ...body } = JSON.parse(explicit.stdout);
+ expect(body).toEqual(legacy);
+ expect(budget_packing.policy).toBe('facts_first');
+ expect(legacy.budget_tokens).toBe(parseInt(budget, 10) || undefined);
+ expect(legacy).not.toHaveProperty('budget_packing');
+ });
+
+ test('no-query opt-in keeps the legacy CLI sub-one normalization and the filtered fact route', () => {
+ const result = call(['recall', 'topics/garden', '--budget-tokens', '0.5', '--budget-policy', 'query_first', '--json']);
+ expect(result.status).toBe(0);
+ const body = JSON.parse(result.stdout);
+ expect(body.facts).toHaveLength(4);
+ expect(body).not.toHaveProperty('budget_tokens');
+ expect(body).not.toHaveProperty('results');
+ expect(body.budget_packing).toMatchObject({ policy: 'facts_first', applied: false, reason: 'no_query' });
+ });
+
+ test('opt-in named recall forwards entity, since, session and grep before packing', () => {
+ const result = call(['recall', 'topics/garden', '--query', 'zebra telescope', '--budget-tokens', '75',
+ '--budget-policy', 'query_first', '--session-id', 'garden-session-1', '--since', '2026-09-01', '--grep', 'observation', '--json']);
+ expect(result.status).toBe(0);
+ const body = JSON.parse(result.stdout);
+ expect(body.facts).toHaveLength(1);
+ expect(body.facts[0].source_session).toBe('garden-session-1');
+ expect(body.budget_packing.facts.candidates).toBe(1);
+ expect(body.results).toHaveLength(1);
+ });
+
+ test.each([
+ ['--budget-policy', 'unknown'], ['--budget-policy', 'QUERY_FIRST'], ['--budget-policy', ''],
+ ['--budget-policy'], ['--budget-policy', '--json'], ['--budget-policy='],
+ ].map(args => [args]))('named recall rejects invalid or missing policy values: %j', args => {
+ const result = call(['recall', '--json', ...args]);
+ expect(result.status).not.toBe(0);
+ expect(JSON.parse(result.stdout)).toMatchObject({ error: 'invalid_params', protocol_version: 1 });
+ expect(result.stderr).toContain('invalid_params');
+ expect(result.stderr).toContain('facts_first');
+ expect(result.stderr).toContain('query_first');
+ });
+
+ test.each(['--watch', '--since-last-run', '--rollup', '--as-context'])('policy opt-in refuses unsupported CLI-only %s instead of silently ignoring it', flag => {
+ const result = call(['recall', '--budget-policy', 'query_first', flag]);
+ expect(result.status).not.toBe(0);
+ expect(result.stderr).toContain('invalid_params');
+ expect(result.stderr).toContain('--budget-policy cannot be combined');
+ });
+
+ test('a missing policy value preserves a following JSON flag', () => {
+ const result = call(['recall', '--budget-policy', '--json']);
+ expect(result.status).not.toBe(0);
+ expect(JSON.parse(result.stdout)).toMatchObject({ error: 'invalid_params', protocol_version: 1 });
+ });
+
+ test('gbrain call forwards query_first and preserves the legacy control on the same stored corpus', () => {
+ const legacy = call(['call', 'recall', JSON.stringify({ ...params, budget_policy: 'facts_first' })]);
+ expect(legacy.status).toBe(0);
+ const baseline = JSON.parse(legacy.stdout);
+ expect(baseline.results).toEqual([]);
+ expect(baseline.budget_used).toBe(72);
+ const candidate = call(['call', 'recall', JSON.stringify(params)]);
+ expect(candidate.status).toBe(0);
+ const result = JSON.parse(candidate.stdout);
+ expect(result.results.map((r: any) => r.slug)).toEqual(['notes/telescope']);
+ expect(result.budget_packing).toMatchObject({ policy: 'query_first', applied: true, reason: 'packed' });
+ expect(result.budget_used).toBe(59);
+ });
+
+ test('a fresh stdio process advertises the enum and returns identical packed evidence', async () => {
+ const transport = new StdioClientTransport({
+ command: process.execPath, args: ['--no-env-file', cli, 'serve', '--surface', 'verbs'],
+ cwd: home, env, stderr: 'pipe',
+ });
+ const client = new Client({ name: 'recall-budget-policy-test', version: '1.0.0' }, { capabilities: {} });
+ try {
+ await client.connect(transport);
+ const { tools } = await client.listTools();
+ const schema: any = tools.find(tool => tool.name === 'recall')!.inputSchema;
+ expect(schema.properties.budget_policy.enum).toEqual(['facts_first', 'query_first']);
+ const response = await client.callTool({ name: 'recall', arguments: params });
+ expect(response.isError).toBeFalsy();
+ const content = response.content as Array<{ type: string; text: string }>;
+ const result = JSON.parse(content.find(item => item.type === 'text')!.text);
+ expect(result.results.map((r: any) => r.slug)).toEqual(['notes/telescope']);
+ expect(result.budget_packing).toMatchObject({ policy: 'query_first', applied: true, reason: 'packed' });
+ expect(result.budget_used).toBe(59);
+ expect(result.dropped_count).toBe(3);
+ for (const [source_id, code] of [['ghost-example', 'scope_denied'], ['__all__', 'invalid_params'], ['Bad Source', 'invalid_params']]) {
+ const failure = await client.callTool({ name: 'recall', arguments: { source_id, budget_policy: 'query_first' } });
+ expect(failure.isError).toBe(true);
+ const error = JSON.parse((failure.content as Array<{ text: string }>)[0].text);
+ expect(error).toMatchObject({ error: code, protocol_version: 1 });
+ expect(validateAgainstSchema(error, ERROR_SCHEMA)).toEqual([]);
+ expect(JSON.stringify(error)).not.toContain('Garden observation');
+ }
+ } finally {
+ await client.close();
+ await transport.close();
+ }
+ });
+});
diff --git a/test/recall-budget-policy.test.ts b/test/recall-budget-policy.test.ts
new file mode 100644
index 0000000000..ef1ab6ac9f
--- /dev/null
+++ b/test/recall-budget-policy.test.ts
@@ -0,0 +1,396 @@
+import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { NewFact } from '../src/core/engine.ts';
+import { operationsByName, type OperationContext } from '../src/core/operations.ts';
+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { awaitPendingLastRetrievedWrites } from '../src/core/last-retrieved.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { buildToolDefs } from '../src/mcp/tool-defs.ts';
+import { estimateTokens } from '../src/core/search/token-budget.ts';
+import type { SearchResult } from '../src/core/types.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { installFixtureChunks } from './helpers/page-projection.ts';
+import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';
+import { ERROR_SCHEMA, RESPONSE_SCHEMAS } from '../src/core/verbs.ts';
+import { validateAgainstSchema } from '../src/core/verbs/conformance.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+beforeEach(async () => {
+ await awaitPendingLastRetrievedWrites();
+ await resetPgliteState(engine);
+ await engine.setConfig('search.track_retrieval', 'false');
+});
+
+afterAll(async () => {
+ await awaitPendingLastRetrievedWrites();
+ await engine.disconnect();
+ resetGateway();
+});
+
+function ctx(overrides: Partial<OperationContext> = {}): OperationContext {
+ return {
+ engine, config: {}, logger: { info() {}, warn() {}, error() {} },
+ dryRun: false, remote: false, sourceId: 'default', ...overrides,
+ } as OperationContext;
+}
+
+async function recall(params: Record<string, unknown>, overrides: Partial<OperationContext> = {}): Promise<any> {
+ return operationsByName.recall.handler(ctx(overrides), params);
+}
+
+async function fact(text: string, extra: Partial<NewFact> = {}, sourceId = 'default') {
+ return engine.insertFact({ fact: text, source: 'synthetic-budget-test', visibility: 'world', ...extra }, { source_id: sourceId });
+}
+
+async function page(slug: string, title: string, text: string, sourceId = 'default', frontmatter = {}) {
+ await engine.putPage(slug, { type: 'note', title, compiled_truth: text, frontmatter }, { sourceId });
+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: text }], { sourceId });
+}
+
+async function seedStarvation() {
+ await page('notes/telescope', 'Zebra telescope', 'The zebra telescope calibration code is QX-17. Store it in the blue case.');
+ for (let i = 0; i < 4; i++) {
+ await fact(`Garden observation ${i}: `.padEnd(144, 'x'), { valid_from: new Date(`2026-09-01T00:00:0${i}Z`) });
+ }
+}
+
+function withoutPacking(result: any) {
+ const { budget_packing, ...legacy } = result;
+ return legacy;
+}
+
+function assertAccounting(result: any) {
+ expect(validateAgainstSchema(result, RESPONSE_SCHEMAS.recall)).toEqual([]);
+ const packing = result.budget_packing;
+ expect(packing).toBeDefined();
+ const factsUsed = result.facts.reduce((n: number, f: any) => n + estimateTokens(f.fact), 0);
+ const resultsUsed = (result.results ?? []).reduce((n: number, r: any) => n + estimateTokens(r.title) + estimateTokens(r.chunk), 0);
+ expect(packing.facts.kept).toBe(result.facts.length);
+ expect(packing.results.kept).toBe((result.results ?? []).length);
+ expect(packing.facts.used).toBe(factsUsed);
+ expect(packing.results.used).toBe(resultsUsed);
+ for (const arm of [packing.facts, packing.results]) expect(arm.candidates).toBe(arm.kept + arm.dropped);
+ if (result.budget_used !== undefined) {
+ expect(result.budget_used).toBe(factsUsed + resultsUsed);
+ expect(result.dropped_count).toBe(packing.facts.dropped + packing.results.dropped);
+ }
+}
+
+test.each(['warn', 'reject'])('explicit recall source narrows both arms within grants under %s validation', async mode => {
+ await engine.setConfig('mcp.strict_params', mode);
+ for (const source of ['default', 'peer', 'denied']) {
+ if (source !== 'default') await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [source]);
+ await page('notes/telescope', 'Telescope', `Telescope evidence from ${source}.`, source);
+ await fact(`Telescope evidence from ${source}.`, {}, source);
+ }
+ const options = { remote: true, sourceId: 'default', auth: { allowedSources: ['default', 'peer'] }, config: {} } as never;
+ for (const source of [undefined, 'default', 'peer']) {
+ const result = await dispatchToolCall(engine, 'recall', { query: 'telescope', budget_policy: 'query_first',
+ budget_tokens: 1000, ...(source ? { source_id: source } : {}) }, options);
+ expect(result.isError).not.toBe(true);
+ expect(result._meta?.warnings).toBeUndefined();
+ const body = JSON.parse((result.content[0] as { text: string }).text);
+ const expected = (source ? [source] : ['default', 'peer']).map(id => `Telescope evidence from ${id}.`).sort();
+ expect(body.facts.map((row: any) => row.fact).sort()).toEqual(expected);
+ expect(body.results.map((row: any) => row.chunk).sort()).toEqual(expected);
+ }
+ for (const source of ['denied', 'missing']) {
+ const result = await dispatchToolCall(engine, 'recall', { source_id: source }, options);
+ expect(result.isError).toBe(true);
+ const error = JSON.parse((result.content[0] as { text: string }).text);
+ expect(error).toMatchObject({ error: 'scope_denied', detail: 'permission_denied', protocol_version: 1 });
+ expect(validateAgainstSchema(error, ERROR_SCHEMA)).toEqual([]);
+ }
+ await engine.executeRaw('UPDATE sources SET archived=TRUE WHERE id=$1', ['peer']);
+ const archived = await dispatchToolCall(engine, 'recall', { source_id: 'peer' }, options);
+ expect(archived.isError).toBe(true);
+ const error = JSON.parse((archived.content[0] as { text: string }).text);
+ expect(error).toMatchObject({ error: 'not_found', detail: 'unknown_source', protocol_version: 1 });
+ expect(validateAgainstSchema(error, ERROR_SCHEMA)).toEqual([]);
+});
+
+test.each(['__all__', 'Bad Source', 7, []].map(value => [value]))('invalid recall selector %j has a v1 error through direct and MCP calls', async source_id => {
+ let direct: any;
+ try { await recall({ source_id }); } catch (error: any) { direct = error.toJSON(); }
+ expect(direct).toMatchObject({ error: 'invalid_params', protocol_version: 1 });
+ expect(direct.suggestion).toBeTruthy();
+ expect(validateAgainstSchema(direct, ERROR_SCHEMA)).toEqual([]);
+ const result = await dispatchToolCall(engine, 'recall', { source_id }, { remote: true, sourceId: 'default' });
+ expect(result.isError).toBe(true);
+ const error = JSON.parse(result.content[0].text);
+ expect(error).toMatchObject({ error: 'invalid_params', protocol_version: 1 });
+ expect(validateAgainstSchema(error, ERROR_SCHEMA)).toEqual([]);
+});
+
+test('an authorized missing source keeps its v1 not-found envelope for direct callers', async () => {
+ let error: any;
+ try { await recall({ source_id: 'missing-example' }); } catch (caught: any) { error = caught.toJSON(); }
+ expect(error).toMatchObject({ error: 'not_found', detail: 'unknown_source', protocol_version: 1 });
+ expect(error.suggestion).toBeTruthy();
+ expect(validateAgainstSchema(error, ERROR_SCHEMA)).toEqual([]);
+});
+
+test.each([undefined, null])('an omitted selector %j preserves the legacy context-scope error', async source_id => {
+ let error: any;
+ try {
+ await recall({ source_id }, { remote: true, sourceId: undefined,
+ auth: { token: 'fixture', clientId: 'fixture', scopes: ['read'], allowedSources: [] } });
+ } catch (caught: any) {
+ error = JSON.parse(JSON.stringify(caught.toJSON()));
+ }
+ expect(error).toMatchObject({ error: 'permission_denied', message: 'No readable source is granted for this request.' });
+ expect(error).not.toHaveProperty('protocol_version');
+});
+
+describe('recall opt-in query-first budget packing', () => {
+ test('retains the matching note at 75 tokens while preserving omitted and explicit legacy output', async () => {
+ await seedStarvation();
+ const params = { query: 'zebra telescope', budget_tokens: 75 };
+ const legacy = await recall(params);
+ expect(legacy.results).toEqual([]);
+ expect(legacy.total).toBe(2);
+ expect(legacy.budget_used).toBe(72);
+ expect(legacy.dropped_count).toBe(3);
+ expect(legacy).not.toHaveProperty('budget_packing');
+ const explicit = await recall({ ...params, budget_policy: 'facts_first' });
+ expect(withoutPacking(explicit)).toEqual(legacy);
+ expect(explicit.budget_packing).toMatchObject({ policy: 'facts_first', applied: true, reason: 'packed' });
+ const candidate = await recall({ ...params, budget_policy: 'query_first' });
+ expect(candidate.results.map((r: any) => r.slug)).toEqual(['notes/telescope']);
+ expect(candidate.search_degraded).toBe('keyword_only_no_embedding_provider');
+ expect(candidate.budget_packing).toMatchObject({ policy: 'query_first', applied: true, reason: 'packed', facts: { candidates: 4 }, results: { candidates: 1 } });
+ expect(candidate.budget_used).toBeLessThanOrEqual(75);
+ assertAccounting(explicit);
+ assertAccounting(candidate);
+ });
+
+ test.each([undefined, '', ' '])('no query (%j) preserves exact legacy packing, even its sub-one quirk', async query => {
+ await seedStarvation();
+ const params = { query, budget_tokens: 0.5 };
+ const legacy = await recall(params);
+ expect(legacy.total).toBe(4);
+ expect(legacy.budget_tokens).toBe(0);
+ expect(legacy.budget_used).toBe(144);
+ const candidate = await recall({ ...params, budget_policy: 'query_first' });
+ expect(withoutPacking(candidate)).toEqual(legacy);
+ expect(candidate).not.toHaveProperty('results');
+ expect(candidate.budget_packing).toMatchObject({ policy: 'facts_first', applied: false, reason: 'no_query' });
+ assertAccounting(candidate);
+ });
+
+ test.each([undefined, null, 0, -1, NaN, Infinity, -Infinity, '75', true])('inactive direct-handler budget %j keeps unbudgeted arrays', async budget_tokens => {
+ await seedStarvation();
+ const params = { query: 'zebra telescope', budget_tokens };
+ const legacy = await recall(params);
+ const candidate = await recall({ ...params, budget_policy: 'query_first' });
+ expect(withoutPacking(candidate)).toEqual(legacy);
+ expect(candidate).not.toHaveProperty('budget_tokens');
+ expect(candidate.budget_packing).toMatchObject({ policy: 'facts_first', applied: false, reason: 'no_positive_finite_budget' });
+ expect(candidate.facts).toHaveLength(4);
+ expect(candidate.results).toHaveLength(1);
+ assertAccounting(candidate);
+ });
+
+ test('eligible sub-one budget empties both arms only under query_first', async () => {
+ await seedStarvation();
+ const params = { query: 'zebra telescope', budget_tokens: 0.5 };
+ const legacy = await recall(params);
+ const explicit = await recall({ ...params, budget_policy: 'facts_first' });
+ expect(withoutPacking(explicit)).toEqual(legacy);
+ expect(explicit.budget_used).toBe(144);
+ const candidate = await recall({ ...params, budget_policy: 'query_first' });
+ expect(candidate).toMatchObject({ facts: [], results: [], total: 0, budget_tokens: 0, budget_used: 0, dropped_count: 5 });
+ expect(candidate.budget_packing).toMatchObject({ policy: 'query_first', applied: true, reason: 'budget_below_one' });
+ assertAccounting(candidate);
+ });
+
+ test.each([undefined, 'zebra telescope'])('facts-first reports its preserved sub-one overrun honestly: %j', async query => {
+ await seedStarvation();
+ const params = { query, budget_tokens: 0.5 };
+ const legacy = await recall(params);
+ const explicit = await recall({ ...params, budget_policy: 'facts_first' });
+ expect(withoutPacking(explicit)).toEqual(legacy);
+ expect(explicit.budget_used).toBe(144);
+ expect(explicit.budget_packing).toMatchObject({ policy: 'facts_first', applied: false, reason: 'budget_below_one' });
+ assertAccounting(explicit);
+ });
+
+ test('exact page boundary and fractional floor leave zero facts on an exhausted remainder', async () => {
+ await seedStarvation();
+ const unbudgeted = await recall({ query: 'zebra telescope' });
+ const r = unbudgeted.results[0];
+ const cost = estimateTokens(r.title) + estimateTokens(r.chunk);
+ for (const budget_tokens of [cost, cost + 0.9]) {
+ const candidate = await recall({ query: 'zebra telescope', budget_policy: 'query_first', budget_tokens });
+ expect(candidate.facts).toEqual([]);
+ expect(candidate.results).toEqual(unbudgeted.results);
+ expect(candidate.budget_tokens).toBe(cost);
+ expect(candidate.budget_used).toBe(cost);
+ expect(candidate.dropped_count).toBe(4);
+ assertAccounting(candidate);
+ }
+ });
+
+ test('no page hits leaves the full budget for the same fact prefix', async () => {
+ await seedStarvation();
+ const params = { query: 'unmatched quasars', budget_tokens: 75 };
+ const legacy = await recall(params);
+ const candidate = await recall({ ...params, budget_policy: 'query_first' });
+ expect(withoutPacking(candidate)).toEqual(legacy);
+ expect(candidate.total).toBe(2);
+ expect(candidate.budget_packing.results).toEqual({ candidates: 0, kept: 0, dropped: 0, used: 0 });
+ assertAccounting(candidate);
+ });
+
+ test('empty arms report no candidates rather than a budget failure', async () => {
+ const result = await recall({ query: 'unmatched quasars', budget_tokens: 75, budget_policy: 'query_first' });
+ expect(result.budget_packing).toMatchObject({ policy: 'query_first', applied: true, reason: 'no_candidates' });
+ expect(result).toMatchObject({ facts: [], results: [], budget_used: 0, dropped_count: 0 });
+ assertAccounting(result);
+ });
+
+ test('oversized page head stops the page prefix, preserves its contents, and leaves facts the full budget', async () => {
+ await fact('Fits.');
+ const raw = [
+ { page_id: 1, slug: 'notes/large', title: 'Large', chunk_text: 'x'.repeat(400), score: 2, source_id: 'default' },
+ { page_id: 2, slug: 'notes/small', title: 'Small', chunk_text: 'Tiny', score: 1, source_id: 'default' },
+ ] as SearchResult[];
+ const search = spyOn(engine, 'searchKeyword').mockResolvedValue(raw);
+ try {
+ const result = await recall({ query: 'needle', budget_tokens: 10, budget_policy: 'query_first' });
+ expect(result.results).toEqual([]);
+ expect(result.facts.map((f: any) => f.fact)).toEqual(['Fits.']);
+ expect(raw.map(r => [r.slug, r.chunk_text])).toEqual([['notes/large', 'x'.repeat(400)], ['notes/small', 'Tiny']]);
+ expect(result.budget_packing.results).toEqual({ candidates: 2, kept: 0, dropped: 2, used: 0 });
+ assertAccounting(result);
+ } finally { search.mockRestore(); }
+ });
+
+ test('an oversized first fact cannot be skipped after pages; too-large first items explain an empty result', async () => {
+ await fact('Tiny', { valid_from: new Date('2026-09-01') });
+ await fact('x'.repeat(400), { valid_from: new Date('2026-09-02') });
+ await page('notes/short', 'Needle', 'Needle');
+ const result = await recall({ query: 'needle', budget_tokens: 10, budget_policy: 'query_first' });
+ expect(result.results).toHaveLength(1);
+ expect(result.facts).toEqual([]);
+ assertAccounting(result);
+ const empty = await recall({ query: 'needle', budget_tokens: 1, budget_policy: 'query_first' });
+ expect(empty.budget_packing.reason).toBe('first_items_exceed_budget');
+ expect(empty).toMatchObject({ facts: [], results: [], budget_used: 0, dropped_count: 3 });
+ assertAccounting(empty);
+ });
+
+ test('retains multiple required pages in their original order without changing candidates or per-arm limits', async () => {
+ await page('notes/canary-a', 'Canary rollout region', 'The canary rollout starts in region west.');
+ await page('notes/canary-b', 'Canary rollout rollback', 'The canary rollout stops at three percent errors.');
+ for (let i = 0; i < 4; i++) await fact(`Observation ${i}: `.padEnd(144, 'x'));
+ const all = await recall({ query: 'canary rollout' });
+ const result = await recall({ query: 'canary rollout', budget_tokens: 75, budget_policy: 'query_first' });
+ expect(result.results).toEqual(all.results);
+ expect(result.results).toHaveLength(2);
+ assertAccounting(result);
+ const limited = await recall({ query: 'canary rollout', limit: 1, budget_tokens: 75, budget_policy: 'query_first' });
+ expect(limited.budget_packing.facts.candidates).toBe(1);
+ expect(limited.budget_packing.results.candidates).toBe(1);
+ expect(await recall({ query: 'canary rollout' })).toEqual(all);
+ });
+
+ test('fact-focused callers keep their route; forcing query_first can favor an irrelevant page over the filtered fact', async () => {
+ await fact('Example prefers tea.', { entity_slug: 'people/example' });
+ await fact('Unrelated fact.', { entity_slug: 'people/other-example' });
+ await page('notes/tea-logistics', 'Tea logistics', 'Tea logistics discusses warehouse shelving. This note has no personal preference evidence.');
+ const params = { query: 'tea logistics', entity: 'people/example', budget_tokens: 27 };
+ const legacy = await recall(params);
+ expect(legacy.facts.map((f: any) => f.fact)).toEqual(['Example prefers tea.']);
+ const candidate = await recall({ ...params, budget_policy: 'query_first' });
+ expect(candidate.facts).toEqual([]);
+ expect(candidate.results).toHaveLength(1);
+ expect(candidate.budget_packing.facts.candidates).toBe(1);
+ expect(withoutPacking(await recall({ ...params, budget_policy: 'facts_first' }))).toEqual(legacy);
+ assertAccounting(candidate);
+ });
+
+ test('expiry, supersession, since, session, and grep filters remain before candidate accounting', async () => {
+ const active = await fact('needle active', { entity_slug: 'people/example', source_session: 'session-example', valid_from: new Date('2026-09-02') });
+ await fact('needle old', { entity_slug: 'people/example', source_session: 'session-example', valid_from: new Date('2026-08-01') });
+ await fact('needle other session', { entity_slug: 'people/example', source_session: 'other', valid_from: new Date('2026-09-02') });
+ const expired = await fact('needle expired', { entity_slug: 'people/example', source_session: 'session-example', valid_from: new Date('2026-09-02') });
+ const superseded = await fact('needle superseded', { entity_slug: 'people/example', source_session: 'session-example', valid_from: new Date('2026-09-02') });
+ await engine.executeRaw('UPDATE facts SET expired_at = $1 WHERE id IN ($2, $3)', [new Date('2026-09-03'), expired.id, superseded.id]);
+ await engine.executeRaw('UPDATE facts SET superseded_by = $1 WHERE id = $2', [active.id, superseded.id]);
+ await page('notes/needle', 'Needle', 'Needle answer');
+ const params = { query: 'needle', entity: 'people/example', since: '2026-09-01', session_id: 'session-example', grep: 'needle', budget_tokens: 1000, budget_policy: 'query_first' };
+ const result = await recall(params);
+ expect(result.facts.map((f: any) => f.fact)).toEqual(['needle active']);
+ expect(result.budget_packing.facts.candidates).toBe(1);
+ assertAccounting(result);
+ for (const extra of [{ include_expired: true }, { supersessions: true }]) {
+ const legacy = await recall({ ...params, ...extra, budget_policy: undefined });
+ const candidate = await recall({ ...params, ...extra });
+ expect(withoutPacking(candidate)).toEqual(legacy);
+ assertAccounting(candidate);
+ }
+ });
+
+ test('remote grants and private/safe-page filters apply before query-first packing across duplicate slugs', async () => {
+ for (const source of ['peer', 'denied']) await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1)', [source]);
+ await page('notes/compass', 'Compass public', 'Compass public answer.', 'peer');
+ await page('notes/compass', 'Compass denied', 'Compass denied answer.', 'denied');
+ await page('notes/private', 'Compass private', 'Compass private answer.', 'default', { visibility: 'private' });
+ await engine.putPage('notes/unsafe', { type: 'note', title: 'Compass unsafe', compiled_truth: 'Compass unsafe answer.' });
+ await fact('Public fact.', {}, 'peer');
+ await fact('Private fact.', { visibility: 'private' }, 'peer');
+ await fact('Denied fact.', {}, 'denied');
+ const overrides = { remote: true, auth: { allowedSources: ['default', 'peer'] } } as Partial<OperationContext>;
+ const params = { query: 'compass', budget_tokens: 75, budget_policy: 'query_first' };
+ const result = await recall(params, overrides);
+ expect(result.results.map((r: any) => r.title)).toEqual(['Compass public']);
+ expect(result.facts.map((r: any) => r.fact)).toEqual(['Public fact.']);
+ expect(result.budget_packing.facts.candidates).toBe(1);
+ expect(result.budget_packing.results.candidates).toBe(1);
+ assertAccounting(result);
+ });
+});
+
+describe('recall shared schema and MCP dispatch', () => {
+ test('the generated MCP tool exposes the optional enum and forwards it to the real handler', async () => {
+ await seedStarvation();
+ const schema: any = buildToolDefs([operationsByName.recall])[0].inputSchema;
+ expect(schema.properties.budget_policy).toMatchObject({ type: 'string', enum: ['facts_first', 'query_first'] });
+ expect(schema.required ?? []).not.toContain('budget_policy');
+ const response = await dispatchToolCall(engine, 'recall', { query: 'zebra telescope', budget_tokens: 75, budget_policy: 'query_first' }, { remote: true, sourceId: 'default' });
+ expect(response.isError).toBeFalsy();
+ const result = JSON.parse(response.content[0].text);
+ expect(result.results.map((r: any) => r.slug)).toEqual(['notes/telescope']);
+ expect(result.budget_packing.policy).toBe('query_first');
+ assertAccounting(result);
+ });
+
+ test.each([null, ''])('optional policy %j normalizes to omission without new response fields', async budget_policy => {
+ const options = { remote: true, sourceId: 'default' };
+ const legacy = await dispatchToolCall(engine, 'recall', {}, options);
+ const result = await dispatchToolCall(engine, 'recall', { budget_policy }, options);
+ expect(JSON.parse(result.content[0].text)).toEqual(JSON.parse(legacy.content[0].text));
+ expect(JSON.parse(result.content[0].text)).not.toHaveProperty('budget_packing');
+ });
+
+ test.each(['unknown', ' ', true, 1, []])('invalid policy %j is rejected by the existing validator', async budget_policy => {
+ const response = await dispatchToolCall(engine, 'recall', { budget_policy }, { remote: true, sourceId: 'default' });
+ expect(response.isError).toBe(true);
+ expect(JSON.parse(response.content[0].text).error).toBe('invalid_params');
+ });
+
+ test.each(['75', true, []])('invalid transported numeric budget %j remains invalid', async budget_tokens => {
+ const response = await dispatchToolCall(engine, 'recall', { budget_tokens, budget_policy: 'query_first' }, { remote: true, sourceId: 'default' });
+ expect(response.isError).toBe(true);
+ expect(JSON.parse(response.content[0].text).error).toBe('invalid_params');
+ });
+});
diff --git a/test/scripts/e2e-runner.test.ts b/test/scripts/e2e-runner.test.ts
index 79ff6760f4..9d8c90967f 100644
--- a/test/scripts/e2e-runner.test.ts
+++ b/test/scripts/e2e-runner.test.ts
@@ -44,6 +44,43 @@ describe('sequential E2E runner', () => {
expect(bad.stdout).toContain('Files: 2 total, 1 passed, 1 failed');
} finally { rmSync(root, { recursive: true, force: true }); }
});
+ for (const firstFails of [false, true]) test(`each file has a fresh home after a ${firstFails ? 'failing' : 'passing'} config writer`, () => {
+ const root = setup();
+ try {
+ const homes = join(root, 'homes.jsonl');
+ writeFileSync(join(root, 'test/e2e/a.test.ts'), `
+ import {test,expect} from 'bun:test';
+ import {writeFileSync,appendFileSync,mkdirSync} from 'node:fs';
+ import {join} from 'node:path';
+ test('write a schema and harness config',()=>{
+ expect(process.env.HOME).toBe(process.env.GBRAIN_HOME);
+ appendFileSync(${JSON.stringify(homes)},JSON.stringify(process.env.HOME)+'\\n');
+ mkdirSync(join(process.env.GBRAIN_HOME!,'.gbrain'),{recursive:true});
+ writeFileSync(join(process.env.GBRAIN_HOME!,'.gbrain/config.json'),'"example-schema-override"');
+ writeFileSync(join(process.env.HOME!,'harness-config'),'example');
+ expect(${JSON.stringify(firstFails)}).toBe(false);
+ });
+ `);
+ writeFileSync(join(root, 'test/e2e/b.test.ts'), `
+ import {test,expect} from 'bun:test';
+ import {existsSync,appendFileSync} from 'node:fs';
+ import {join} from 'node:path';
+ test('start without the preceding file configuration',()=>{
+ expect(process.env.HOME).toBe(process.env.GBRAIN_HOME);
+ appendFileSync(${JSON.stringify(homes)},JSON.stringify(process.env.HOME)+'\\n');
+ expect(existsSync(join(process.env.GBRAIN_HOME!,'.gbrain/config.json'))).toBe(false);
+ expect(existsSync(join(process.env.HOME!,'harness-config'))).toBe(false);
+ });
+ `);
+ const result = run(root, ['test/e2e/a.test.ts', 'test/e2e/b.test.ts']);
+ expect(result.status, result.stderr + result.stdout).toBe(firstFails ? 1 : 0);
+ expect(result.stdout).toContain(`Files: 2 total, ${firstFails ? 1 : 2} passed, ${firstFails ? 1 : 0} failed`);
+ const selected = readFileSync(homes, 'utf8').trim().split('\n').map(line => JSON.parse(line) as string);
+ expect(selected).toHaveLength(2);
+ expect(new Set(selected).size).toBe(2);
+ for (const home of selected) expect(existsSync(home)).toBe(false);
+ } finally { rmSync(root, { recursive: true, force: true }); }
+ });
test('cancellation terminates its owned interrupt-resistant child', async () => {
const root = setup();
let child: ReturnType<typeof Bun.spawn> | undefined;
diff --git a/test/select-e2e.test.ts b/test/select-e2e.test.ts
index 651f4f5eae..83c0e8b1e2 100644
--- a/test/select-e2e.test.ts
+++ b/test/select-e2e.test.ts
@@ -104,6 +104,36 @@ describe("classify", () => {
});
describe("selectTests", () => {
+ test.each([
+ "src/core/attendance-repair.ts",
+ "src/commands/extract-attendance-repair.ts",
+ ])("attendance repair changes select their PostgreSQL parity entry: %s", (path) => {
+ expect(selectTests({
+ changedFiles: [path],
+ allE2ETests: [
+ "test/e2e/attendance-repair-postgres.test.ts",
+ "test/e2e/attendance-retrieval-postgres.test.ts",
+ "test/e2e/graph-quality.test.ts",
+ ],
+ map: E2E_TEST_MAP,
+ })).toEqual(["test/e2e/attendance-repair-postgres.test.ts"]);
+ });
+
+ test("shared derived-link changes retain attendance retrieval and repair parity", () => {
+ expect(selectTests({
+ changedFiles: ["src/core/derived-links.ts"],
+ allE2ETests: [
+ "test/e2e/attendance-repair-postgres.test.ts",
+ "test/e2e/attendance-retrieval-postgres.test.ts",
+ "test/e2e/graph-quality.test.ts",
+ ],
+ map: E2E_TEST_MAP,
+ })).toEqual([
+ "test/e2e/attendance-repair-postgres.test.ts",
+ "test/e2e/attendance-retrieval-postgres.test.ts",
+ ]);
+ });
+
test("case 1: empty diff -> all E2E", () => {
expect(select([])).toEqual(ALL_E2E.slice().sort());
});