Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
docs+ratchet: relation direction, canonical attendance under shipped packs, tier-7 default rationale, re-derivation path; move ownsAttendanceInference to link-inference
garrytan49acbc3b3b79
diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.mdindex 7ece7abed6..5c99feca76 100644--- a/docs/architecture/key-files/core-search-1.md+++ b/docs/architecture/key-files/core-search-1.md@@ -68,6 +68,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/read-policy-sql.ts` — shared internal concrete-page SQL policy (`PageReadScope` in `types.ts`): nonempty federated grants precede scalar source; `excludePrivate` is resolved by `ops/context.ts:readPolicyOpts`, never an MCP override. Optional live-page filtering excludes deleted/quarantined pages and archived sources. Both engines apply policy inside content, version, timeline, graph and identity reads before limits. While page privacy is enforced, history requires both current-page and snapshot visibility. Links/timeline projections independently authorize originating pages.+- `src/core/search/relational-recall.ts` — the relational recall arm: `parseRelationalQuery` → seed resolution per in-scope source → `relationalFanout` → hydrate, fail-open. Seeds resolve through `resolveEntitySlugWithSource` and a `fallback_slugify` result is dropped (confidence gate D3). The entity resolver never returns meetings, so for an incoming `attended` relation (`Who attended <meeting>?`) a live `meeting` or `event` page whose title is exactly the seed phrase (case-insensitive, unique in the source) is the seed; other relations never seed from titles. Pinned by `test/relational-recall.test.ts` and `test/pack-relation-direction-engine.test.ts`.+- `src/core/search/relational-rerank-pin.ts` — relational-arm rows bypass reranker DEMOTION (ranker wave, receipt R1 in `scripts/r1-namedthing-rerank-ab.ts`: on NamedThingBench's 39 graph-relationship questions the shipped `balanced` default lost hit@1 21/39 → 3/39 and hit@3 27/39 → 5/39 with the reranker on — 19 and 22 paired losses — because the cross-encoder scores chunk TEXT and an edge-derived answer's text need not mention the query's entity; with the pin at its default 3, measured with `--autocut on`, the shape that shipped before rule R2 turned autocut off, the same paired run shows 0 hit@1 / 0 hit@3 losses, 21/39 and 27/39, and the 11 non-relational core queries show 0 losses — one hard-negative gain, hit@1 10/11 → 11/11). `pinRelationalRows(reranked, relationalList, {max, fusedOrder?, onPin?})` is a pure PERMUTATION of the post-rerank pool: relational rows (page key `(source_id, slug)` in the arm's list; ONE row per page — its first, highest-ranked occurrence) claim `min(fused_rank, reranked_rank)` (fused rank = position among relational rows in `fusedOrder`, the pre-rerank `deduped` pool; arm order for rows absent from it), claims sort ascending with ties resolved to the FUSED order then the reranked position, the first `max` claimants form the top block in that order, every other row follows in reranked order (an unpinned row lands at its reranked position or up to `pinned.length` lower, never higher). Pinned rows are shallow copies stamped `relational_pinned: true`; no row is added or removed (re-injecting rows dropped upstream stays `ensureRelationalEvidenceSlot`'s job). Every no-op path (`max <= 0`, empty pool, empty arm, no relational page in the pool) returns the input array itself. `normalizeRelationalRerankPin` is the ONE range contract for the knob (non-negative integer `<= 10` or a string parsing to one → that integer; the literals `off` / `false` (any case) or boolean `false` → 0; anything else → `undefined` = fall through), shared by `mode.ts:loadOverridesFromConfig` and both per-call seams in `hybrid.ts`; `DEFAULT_RELATIONAL_RERANK_PIN` (3) and `RELATIONAL_RERANK_PIN_MAX` (10) are exported. `RelationalRerankPinDecision` (`{max, relational_in_pool, pinned:[{slug, source_id, from_rank, to_rank, fused_rank}], moved}`) is surfaced as `HybridSearchMeta.relational_rerank_pin` for `--explain`. Wired in `hybridSearch` immediately after `applyReranker` and before the alias hop, gated on the reranker having actually reordered (`reranked !== deduped` — `applyReranker` returns its input on every fail-open / skip / pass-through path, and the fused order already carries the arm) and on non-image modality; autocut's `scoreOf` ignores pinned rows and its preserve predicate keeps them, so text-row autocut is byte-identical to the pre-pin behavior. Known cost: a false-positive arm (relational shape parsed AND a real seed resolved, but wrong/stale edges) now puts up to `max` edge pages at ranks 1..max instead of one at `limit`; mitigations are the arm's `fallback_slugify` confidence gate, the tier-2 resolution-margin TODO, config `search.relational_rerank_pin off`, and per-call `SearchOpts.relationalRerankPin`. Pinned by `test/search/relational-rerank-pin.test.ts` (pure contract + tie policy) and `test/search/relational-rerank-pin-hybrid.serial.test.ts` (hermetic PGLite on the relational corpus through the REAL gateway rerank path behind `__setRerankTransportForTests` with an inverted-relevance stub: pin 0 reproduces the regression, pin 3 restores hit@1/hit@3 on all 8 who-invested questions, non-relational queries and reranker-off runs are byte-identical).- `src/core/search/rerank.ts` — the call-site abstraction. `applyReranker(query, results, opts)` slots between `dedupResults()` and `enforceTokenBudget()` in `src/core/search/hybrid.ts`. Slices `opts.topNIn` (default 30) by current RRF order, caps each document via `capRerankDoc` (`RERANK_MAX_DOC_CHARS=6000` then a measured-ratio shrink to `RERANK_MAX_DOC_TOKENS=1400` — a 2048-ubatch llama-server minus query/template headroom minus a Qwen-tokenizer margin; every cut through `truncateUtf8` so no lone surrogate reaches the JSON body; docs under 1400 chars skip the tokenizer; applies to hosted providers too, so code/CJK chunks at the chunker ceiling lose part of their tail while prose is untouched), sends to `gateway.rerank()`, reorders by `relevanceScore` desc (within a run of exactly equal finite scores the fused input order decides, so provider tie order never leaks; rows never cross a different score), appends the un-reranked tail unchanged (recall protection). Fail-open on every `RerankError.reason`: any error logs via `logRerankFailure` and returns the input array unchanged — except the SKIP class `no_key` (`RerankSkipReason`), which returns the input immediately WITHOUT a per-query audit row (the gateway already wrote the one per-process-per-model row) and fires `opts.onSkip(reason)`; every OTHER thrown failure (HTTP error, network, timeout, budget) is audited and fires `opts.onFailure(reason)` with `RerankFailedReason` `timeout | budget | provider_error`, which `hybrid.ts` stamps as `{stage: 'rerank_failed', reason}` (recall-affecting, like `rerank_passthrough`; the LongMemEval reranker gate and the R1 script count it as un-reranked); `hybrid.ts` passes an `onSkip` that stamps `{stage: 'reranker_skipped', reason}` into `HybridSearchMeta.degraded` (closed vocabulary in `types.ts`), which `--explain` renders as `degraded: reranker_skipped (no_key)` via `formatDegradedSummary` — the only place a silently skipped reranker is visible from the CLI. `types.ts` classifies the stage as ranking-only: `RANKING_ONLY_DEGRADED_STAGES` (= `{reranker_skipped}`) + `affectsRecall(entry)` — consumers that ask "was recall impaired?" filter through it (the CLI `No results.` line in `cli.ts:describeEmptyRetrieval` and the MCP empty-result block in `dispatch.ts:buildEmptyRetrievalBlock` keep saying "clean miss"; the degraded cache-TTL rule below uses the same predicate), while consumers that report what did not run (`--explain`, telemetry, eval rows) keep it; pinned by `test/degraded-stages-recall.test.ts`. `hybridSearchCached` excludes `reranker_skipped` from the short degraded-TTL rule (it is a config state, not a transient limp: a keyless balanced brain keeps the full `cache.ttl_seconds`, and the stored meta still carries the stamp). Stamps `rerank_score` onto reordered items so downstream telemetry sees the new ordering signal. `topNOut: null` is the explicit "don't truncate" signal — semantically distinct from `undefined` ("fall through to mode bundle"). Test seam: `opts.rerankerFn` stubs `gateway.rerank` without the network. Document cap pinned by `test/rerank-doc-cap.test.ts`.diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.mdindex fa4c322b43..ec4ad52f01 100644--- a/docs/architecture/key-files/graph-and-facts.md+++ b/docs/architecture/key-files/graph-and-facts.md@@ -7,7 +7,12 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGELThe shared and filesystem extractors recognize canonical attendance only fromsupported explicit lists and uniquely resolved person targets when no pack owns-the relationship. Callers resolve source identities before+the relationship. A pack owns it only when an `attended` rule has a phrase+regex (`ownsAttendanceInference`); the shipped page-type-bound rule in+`gbrain-base` and `company-brain` mirrors the in-code meeting prior and gets+canonical attendance. Pack `frontmatter_links` take their direction from the+verb's `FRONTMATTER_LINK_MAP` counterpart for the page type (outgoing when it+has none), so pack meeting `attendees` are canonical person -> meeting too. Callers resolve source identities before`resolvedLinkCandidate` orients a Markdown or uniquely resolved bare-wikilink claim as person-to-meeting with themeeting as its origin.Only parsed link targets can make canonical body claims; display-label slugs staydiff --git a/docs/architecture/schema-packs.md b/docs/architecture/schema-packs.mdindex 702b1752d4..ed23880803 100644--- a/docs/architecture/schema-packs.md+++ b/docs/architecture/schema-packs.md@@ -110,6 +110,37 @@ this chain top-down. First match wins.| 6 | `~/.gbrain/config.json` `schema_pack` field | What `gbrain schema use` (and `gbrain init`, which sets `gbrain-base-v2`) writes. || 7 | Default: `gbrain-base` | Always present. |+Tier 7 stays `gbrain-base`, not `gbrain-base-v2`. A brain with no pack+configured anywhere was created before `gbrain init` started writing+`schema_pack`, and its pages carry the legacy 24-type taxonomy. Pointing the+fallback at v2 would change type inference, alias closure and enrichment for+those brains without running v2's `migration_from` retype rules, which+`gbrain schema upgrade` applies as a reviewed step. The relationship+behaviors that used to differ between the two (backwards frontmatter+relations and attendance typed from any meeting link) are fixed in the+extractor instead, so both packs store the same edges; see+[Relation direction](#relation-direction).++## Relation direction++A pack's `frontmatter_links` entry names a field and a verb, not a+direction. The direction comes from the verb's declared counterpart in+`FRONTMATTER_LINK_MAP` (`src/core/link-extraction.ts`) for the same page+type: company `investors`, `key_people` and `partner`, deal `investors` and+`lead`, and meeting `attendees` are incoming (the person, fund or company is+the subject, so `investors: [people/bob-example]` on a company stores Bob ->+company). A verb with no declared counterpart, such as company-brain's+`owned_by`, is outgoing (page -> target).++On a meeting page, a pack's `attended` rule bound only to the page type (and+optionally a `person` target), as `gbrain-base` and `company-brain` ship, is+the in-code meeting prior. Meeting links then follow canonical attendance:+only an explicit attendee list makes a person an attendee, stored person ->+meeting (see [attendance evidence](../guides/attendance-evidence.md)). A pack+that gives `attended` a phrase `regex` decides attendance itself and keeps its+outgoing semantics. Brains extracted before this rule re-derive with+`gbrain extract links --source db --include-frontmatter`.+## How the agent uses the active packEvery read + write path consults the active pack at runtime:diff --git a/docs/guides/attendance-evidence.md b/docs/guides/attendance-evidence.mdindex c36f64e6dd..51679b4c56 100644--- a/docs/guides/attendance-evidence.md+++ b/docs/guides/attendance-evidence.md@@ -107,16 +107,28 @@ sweep reports a link/timeline pass error. Local publication still accepts thenote but reports an automatic-link error and preserves the prior graph. Repairor 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.+The shipped `gbrain-base` and `company-brain` packs declare `attended` bound+only to the meeting page type and map meeting `attendees` to `attended`. Both+follow the canonical rules above: frontmatter and body attendance are stored+person -> meeting, and a person only mentioned in the notes stays a mention.+This also covers brains with no `schema_pack` configured, which resolve+`gbrain-base`. A pack whose `attended` rule has a phrase `regex` decides+attendance itself; its body links keep that pack's outgoing semantics and+historical repair reports them as `pack_semantics_preserved`.++Links extracted before this rule (stored meeting -> person, or typed attended+from a notes mention) re-derive on the next `gbrain extract --stale` sweep,+because the extractor version changed. Frontmatter edges re-derive only when+frontmatter is included, so run this once per source:-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.+```bash+gbrain extract links --source db --include-frontmatter --source-id <id>+```++It replaces each page's own derived links (markdown, wikilink and frontmatter+producers) in one transaction per page; manual links and links other pages+created are untouched. A repair on a real brain still deserves a verified full+database backup; a Markdown export is not a rollback image.## Preview-bound historical repair@@ -191,8 +203,10 @@ not physical MVCC page-scan or total-process-memory guarantees. At most 20diagnostic details are retained, alongside aggregate counts. Retained originreceipts 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+Repair preserves outgoing attendance only for a pack whose `attended` rule+has a phrase `regex`; shipped base and company-brain meetings repair to+person -> meeting like a brain with no pack override. Missing packs are+report-only. It never guessesownership for NULL, unknown or manual producers. Legacy outgoing Markdown iseligible only when authoritative source text proves the same resolved person'sattendance. Other derived/manual links keep their row IDs and evidence.diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 35c1a096f4..6f283ecbc4 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -8,7 +8,7 @@ src/commands/autopilot.ts 1633 ratchet refactor wave 1 split target (W4 autopilosrc/commands/doctor.ts 653 ratchet refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.tssrc/commands/embed.ts 2187 ratchet lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pagessrc/commands/extract-conversation-facts.ts 2146 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); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts)-src/commands/extract.ts 2621 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked+src/commands/extract.ts 2623 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference)src/commands/jobs.ts 658 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2)src/commands/serve-http.ts 915 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.tssrc/core/ai/gateway.ts 4365 ratchet +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state)@@ -31,7 +31,7 @@ src/core/minions/handlers/subagent.ts 1918 ratchet merged: master v131 settle resrc/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 semanticssrc/core/minions/worker.ts 1764 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retrysrc/commands/sources.ts 2013 ratchet +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); 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; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts)-src/core/link-extraction.ts 2133 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note+src/core/link-extraction.ts 2143 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump notesrc/core/embedding-migration.ts 1525 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embedsrc/core/github-source.ts 1530 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; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refreshsrc/commands/hook.ts 1903 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; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail readdiff --git a/src/commands/extract.ts b/src/commands/extract.tsindex 9fe84de827..5eddb80514 100644--- a/src/commands/extract.ts+++ b/src/commands/extract.ts@@ -51,7 +51,7 @@ export { reconcileSourceLinks, type SourceLinkReconciliationResult } from '../coexport { extractMarkdownLinks } from '../core/link-extraction.ts';import {extractPageLinks, parseTimelineEntries, deriveTimelineAnchor, inferLinkType, makeResolver,- attendanceEvidenceRanges, hasAttendanceEvidence, resolvedLinkCandidate, orientCanonicalAttendance, extractMarkdownLinks, ownsAttendanceInference,+ attendanceEvidenceRanges, hasAttendanceEvidence, resolvedLinkCandidate, orientCanonicalAttendance, extractMarkdownLinks,extractFrontmatterLinks, isGlobalBasenameEnabled, isCrossSourceLinksEnabled, LINK_EXTRACTOR_VERSION_TS,WIKILINK_BASENAME_LINK_TYPE,buildBasenameIndex, queryBasenameIndex, stripCodeBlocks, normalizeBasename,@@ -61,7 +61,7 @@ import {// #3190: pack-aware link typing on every extract surface (db/stale/fs).import { loadActivePackForLocalEngine } from '../core/schema-pack/best-effort.ts';import { resolveIncludeFrontmatter } from '../core/extract-frontmatter.ts';-import { inferLinkTypeFromPack } from '../core/schema-pack/link-inference.ts';+import { inferLinkTypeFromPack, ownsAttendanceInference } from '../core/schema-pack/link-inference.ts';import { PageRegexBudget } from '../core/schema-pack/redos-guard.ts';export { extractTimelineFromContent, type ExtractedTimelineEntry } from '../core/timeline-extract.ts';import { extractTimelineFromContent, pruneTimelineOrphans, retractRemovedTimelineEntries, type ExtractedTimelineEntry } from '../core/timeline-extract.ts';diff --git a/src/core/attendance-repair.ts b/src/core/attendance-repair.tsindex 90815dd86d..24f020b831 100644--- a/src/core/attendance-repair.ts+++ b/src/core/attendance-repair.ts@@ -1,12 +1,13 @@import { createHash, randomUUID } from 'node:crypto';import type { BrainEngine, LinkBatchInput } from './engine.ts';import { extractPageLinks, extractEntityRefs, attendanceEvidenceRanges, hasAttendanceEvidence,- resolvedLinkCandidate, normalizeBasename, ownsAttendanceInference, LINK_EXTRACTOR_VERSION_TS,+ 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 { ownsAttendanceInference } from './schema-pack/link-inference.ts';import { executeRawJsonb } from './sql-query.ts';import { applyAttendanceDelta } from './derived-links.ts';diff --git a/src/core/link-extraction.ts b/src/core/link-extraction.tsindex 5e9549dc17..c92edd5664 100644--- a/src/core/link-extraction.ts+++ b/src/core/link-extraction.ts@@ -25,7 +25,7 @@ import { isIdentityEntity, sameEntityName } from './entities/resolve.ts';// #3190: pack-aware link typing. link-inference imports only manifest-v1// (zod) + redos-guard (node:vm) — no cycle back into this module.import type { SchemaPackManifest } from './schema-pack/manifest-v1.ts';-import { inferLinkTypeFromPack, frontmatterLinkTypeFromPack } from './schema-pack/link-inference.ts';+import { inferLinkTypeFromPack, frontmatterLinkTypeFromPack, ownsAttendanceInference } from './schema-pack/link-inference.ts';import { PageRegexBudget } from './schema-pack/redos-guard.ts';/**@@ -619,17 +619,6 @@ export interface PageLinksResult {attendanceComplete: boolean;}-/**- * True when a pack decides meeting attendance itself: one of its `attended`- * rules matches a phrase regex. A rule bound only to the meeting page type- * (and optionally a person target), as gbrain-base and company-brain ship,- * mirrors the in-code meeting prior, so meeting links follow canonical- * evidence-gated attendance (person -> meeting) instead.- */-export function ownsAttendanceInference(pack: Pick<LinkExtractionPack, 'link_types'> | null | undefined): boolean {- return !!pack?.link_types.some(lt => lt.name === 'attended' && lt.inference?.regex);-}-/*** Extract all link candidates from a page.*diff --git a/src/core/schema-pack/link-inference.ts b/src/core/schema-pack/link-inference.tsindex 8ff42d1ec5..8f02ff03e4 100644--- a/src/core/schema-pack/link-inference.ts+++ b/src/core/schema-pack/link-inference.ts@@ -95,6 +95,17 @@ export function inferLinkTypeFromPack(return null;}+/**+ * True when a pack decides meeting attendance itself: one of its `attended`+ * rules matches a phrase regex. A rule bound only to the meeting page type+ * (and optionally a person target), as gbrain-base and company-brain ship,+ * mirrors the in-code meeting prior, so meeting links follow canonical+ * evidence-gated attendance (person -> meeting) instead.+ */+export function ownsAttendanceInference(pack: Pick<SchemaPackManifest, 'link_types'> | null | undefined): boolean {+ return !!pack?.link_types.some(lt => lt.name === 'attended' && lt.inference?.regex);+}+/*** Frontmatter-field → link-verb resolution from a pack manifest.* Mirrors the legacy `FRONTMATTER_LINK_MAP` table; pack-aware variant