Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(chunker): #5001 top-level call statements become __module__ chunks so their call edges survive
garrytan83e139360d2e
diff --git a/docs/architecture/key-files/core-services-1.md b/docs/architecture/key-files/core-services-1.mdindex f2eee14905..cf36f48aa9 100644--- a/docs/architecture/key-files/core-services-1.md+++ b/docs/architecture/key-files/core-services-1.md@@ -33,7 +33,9 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/chronicle/{contract,eligibility,config,reasons,ledger,ledger-stats,execute,publish,event-identity,invite-projection,backfill,campaign,job,upgrade-notice,extract-events,ontology,narrative}.ts` + `src/core/cycle/chronicle.ts` + `src/eval/chronicle/harness.ts` + `src/commands/eval-chronicle.ts` — Life Chronicle: the temporal spine. `contract.ts` holds the ledger columns, the extractor version (part of the ledger key: a bump makes extracted content new to discovery and backfill), the phase bounds and the phase result details. `reasons.ts` is the one reason table (`CHRONICLE_REASONS`: stage, meaning, stored fix Action with argv/preview_argv/consent/actor, never a stored `next`; `auto_chronicle_off` has no fix because it is off by choice) and builds the `chronicle_backstop` receipt field (`{pending:'next_cycle', daily_remaining}` or `{skipped, stage, why, fix}`, omitted for pages that are not chronicle-shaped); `docs/guides/life-chronicle.md` renders its table from it. `eligibility.isChronicleEligible` is the one eligibility function (meeting/conversation/calendar-event + directory rescue; diary and event pages NEVER eligible — privacy + anti-loop); with a time policy it also applies the invite end (`not_yet_happened`), the recency window on the page's own date (an authored `effective_date`, else frontmatter `date`/`start`; a `fallback` date counts as undated) and the settle window. `config.ts` owns the switch and knobs: `autoChronicleSetting` reads `auto_chronicle` as on when unset, on/off for true/false words, and `invalid` (off) for any other word; `chronicleSettings` reads `chronicle.job_budget_usd`/`auto_daily_limit`/`auto_recent_days`/`auto_settle_seconds`/`judge_max_tokens` with ranges (`CHRONICLE_NUMERIC_KEYS`, enforced by `config set`; a malformed stored row falls back and is listed in `invalid`) and `chronicle.activated_at` (stamped by the first write decision or phase run; earlier revisions are history); `autoChronicleNeedsAcknowledgement` is true while on and `chronicle.default_on_acknowledged` is unset (stamped by `config set auto_chronicle`). The opt-out is `gbrain config set auto_chronicle false` everywhere. `ledger.ts` owns `chronicle_page_state` (one row per source/page/content hash/extractor version: state, reason, trigger, deciding writer and request, `no_extract`, attempts, `next_attempt_at`, cost/unpriced, event slugs and hashes): `recordChronicleDecision` runs inside every coordinated publication that imports a page (from `queuePublicationEffects`), applies the shared writer-confinement predicate, `--no-extract`, the opt-out and eligibility, and puts `chronicle_backstop` on the outcome through `reasons.ts`; `reserveChronicleSlot` is the rolling 24 h reservation under a transaction advisory lock. `ledger-stats.ts` rolls up the ledger and reservations for doctor and the advisor. `upgrade-notice.ts` is the one-shot post-upgrade notice (`chronicle.default_on_notice_shown`). The global `chronicle` cycle phase (`cycle/chronicle.ts`) supersedes rows whose content is no longer live, discovers pages changed since activation with no row (unmanaged brains decide there; managed ones record `no_write_decision`), and executes settled rows round-robin across sources (≤50 judged items and a wall-time bound per run; automatic rows only while `auto_chronicle` is on, backfill rows always); no chat provider → no calls; the extract_atoms cost gate refuses an explicit cap on an unpriced model. `execute.ts` runs one row: live-content check, time rules, the reservation (automatic rows; attempts count), the judge in a `chronicle:<trigger>` BudgetTracker scope with the per-page cap and an explicit post-call cap check, failure classes (chat_error/budget → failed with backoff, no provider/no_pricing → failed until config changes, refused → skipped, only a parsed `[]` is `no_events`). `invite-projection.ts` stands in for the judge on an ended calendar invite (slug under `calendar/`/`cal/` or type `calendar-event`, with a title, `start` and `end`): one `Scheduled: <title>` event (`kind: meeting`, `captured_via: life-chronicle:invite`, not proof of attendance) with no chat call, no daily reservation and zero cost, through the same publication and ledger path. `publish.ts` publishes one generation against the pinned depth snapshot: each event write re-validates the depth revision, content hash, source incarnation, privacy and the deciding writer's grant (events also read as private when their `event.depth` origin is private by field or declared lineage, or missing, `search/private-visibility.ts`) (`managed_maintenance_chronicle_event`/`_retire` intents on managed brains, one transaction per event otherwise), stamps the depth's visibility, never overwrites an operator-edited event (live hash not in the ledger) or resurrects an operator-deleted one, and after a complete generation retires the previous generation's owned events (`retired_by: life-chronicle`; restored when produced again). `event-identity.ts` assigns final slugs before publication: events sharing a base slug `life/events/<day>-<hash8>` (who, what, depth) are told apart by instant, `where` and `kind`; one keeps the base slug and the rest get `-<hash6>` (identical copies `-2`…); assignment reads the pages already at the candidate slugs, so it is order-independent, keeps a page's existing slug across corrections and re-extractions, and a page extracted before disambiguation keeps its base slug. `extract-events.runChronicleExtract` is the direct-caller body over the same snapshot and publication path: deterministic when/who, injectable judge (default = chat gateway; output cap 4000 tokens by default, operator override `chronicle.judge_max_tokens`), an ALL-or-nothing parse barrier (`isValidProposal` requires a real parseable date), then `screenChronicleProposals` drops, never writes, each proposal without a day (`date_imprecise`: `when` is a year or month) or dated after the page's own day (`future_dated`: `chronicleEventCutoff` is the latest of the page's own date, a meeting's `end` and a conversation's last parsed message, as a day in `chronicle.tz`, capped at today); drops are counted in `events_dropped` (phase details, row outcome, direct result) and a page whose every proposal was dropped records the drop reason on its extracted ledger row instead of `no_events`; content-addressed `life/events/` pages + a `timeline_entries` projection. An unusable judge response is never recorded as `no_events`: truncation, unparseable output, a provider error and a refusal surface as `judge_truncated`/`judge_parse_failed`/`judge_chat_error`/`judge_refused`. `backfill.ts` (`chronicle_backfill`) queues `trigger='backfill'` ledger rows, exempt from the daily limit and recency (unless `--recent`), across types and rescue prefixes under one global `--limit`; `--since` is the update date, `--dated-since` the page date; a dry run reports `estimated_usd` and skip reasons; a live run needs `--yes`; content already extracted or queued is never re-queued, even after `gbrain jobs prune`. `--max-usd` (#6199, `campaign.ts`) is a queue-time bound: a page queues only while queued × (per-attempt cap + `chronicleCallCeilingUsd`) × max attempts fits, rows are stamped (`campaign_id`, `attempt_cap_usd`, `max_attempts`, `pricing_policy`, `campaign_max_usd`; migration `chronicle_campaign_stamps`) and `queueCampaignRow` never takes a row another backfill queued or an executor holds; an unpriced model under the cap refuses with `no_pricing`. Executors obey the stamp: `claimChronicleRow` consumes a campaign row's attempt with the lease and refuses it past `max_attempts`, the tracker uses the stamped cap, `finish` sums spend per attempt (`cost_attempts`, so a replay adds nothing) and applies the outcome only while its attempt is the latest (a stale completion is fenced), and `failExhaustedCampaignRows` fails a crashed row whose attempts are spent as `campaign_exhausted`; any other ledger write clears the stamp. `job.ts` drains `chronicle_extract` jobs from older releases through the same executor. `ontology.ts` carries the deterministic pieces of the bi-temporal per-entity ontology that RIDES THE `facts` TABLE (migration v122 adds `dimension`/`value`/`value_hash`/`dim_status`): `valueHash` (normalized, timestamp-free; the v188 dedup index adds the stint's `valid_from`, so a crash-retry conflicts while a same-provenance return to an earlier value records a new interval), `normalizeDimension` (seed alias lexicon), `isNovelDimension` (novel → quarantined, excluded from resolution/context until confirmed). The engine methods (`mergeOntologyFact` — corroborate on same value (noop when the same provenance already observed it during the current stint), forward-supersede via `valid_until`+`superseded_by` on a new value, backdated conflicts kept + flagged; `getOntology` with `--asof` valid-time travel; `discoverOntologyDimensions`; `findOntologyConflicts` — currently-open rows only) live in BOTH engines; both engines are on the R8 `valid_until` write allow-list (engine-layer, `dimension IS NOT NULL` rows only). Chronicle reads (`getTimelineForDate`/`getSince`/`getLastSeen`/`getOnThisDay`) JOIN the depth page (`deleted_at IS NULL`), hide soft-deleted event projections at READ time, and order by event `effective_date` for intra-day sequence. Ops: `chronicle_day`/`chronicle_since`/`chronicle_last_seen`/`chronicle_on_this_day`/`ontology_*`/`volunteer_chronicle` (agent orientation via `src/core/context/chronicle-context.ts`)/`chronicle_backfill` (admin, localOnly). Diary privacy: fail-closed for `ctx.remote !== false` callers — diary-sourced ontology + conflict values are redacted, the four timeline read ops (`chronicle_day`/`chronicle_since`/`chronicle_on_this_day` + `volunteer_chronicle`'s `recent_timeline`) drop rows whose depth page, event page, or `source` provenance lives under `life/diary/`, and `chronicle_last_seen` answers the never-seen shape (`last_date`/`last_event_slug`/`days_ago` all null) when the latest sighting is diary-sourced or a diary page is queried as the entity. Remote callers read only `visibility = 'world'` observations, like recall: `getOntology`/`findOntologyConflicts` take a `visibility` filter applied before resolution and the conflict HAVING. `ontology_propose` commits through `coordinatedDatabaseWrite` on a managed brain. Page visibility rides the same policy: `ontology_get`/`ontology_conflicts`/`volunteer_chronicle`'s ontologies resolve through `readPolicyOpts`, and both engines' `getOntology`/`findOntologyConflicts` apply `privateProvenanceFilterFragment` (an observation whose provenance page, looked up in the fact's own source, is `visibility: private` is dropped BEFORE per-dimension resolution and before the conflict HAVING, so an untrusted caller resolves the newest value they may see rather than a private value or a hole). The chronicle reads' event-page LEFT JOIN carries the caller's source scope in BOTH engines, so a scoped read can't surface another source's event pages through the join. Search: `applyChronicleTypeBoost` in `search/hybrid.ts` (bounded [1.0,1.25], fires only inside the `recency !== 'off'` post-fusion branch → non-temporal search bit-for-bit unchanged). Advisor collector `collect-chronicle.ts` (conflicts; coverage gap with a scoped `chronicle-backfill --since <date> --limit 50 --dry-run`; `auto_chronicle_default_on` ask_user until acknowledged; `auto_chronicle_invalid`; `chronicle_chat_unavailable`; `chronicle_extraction_failing`; `chronicle_daily_limit`); doctor `chronicle_projection_health` and `auto_chronicle` (`checks/auto-chronicle.ts`; BRAIN category). Eval: `gbrain eval chronicle` — deterministic, own in-memory PGLite, 6 gold tasks (day order, last-seen, supersession, asof, conflict, isolation), exit 0 iff 6/6. Tests: `test/chronicle-*.test.ts` (automatic path: `chronicle-auto-{decision,phase,unmanaged}`, `chronicle-date-quality`, `chronicle-event-privacy`, `chronicle-event-identity`, `chronicle-invite-projection`, `chronicle-backfill`, `chronicle-backfill-max-usd`, `chronicle-reasons-5876`; Postgres arms in `test/e2e/chronicle-*-postgres.test.ts`), `test/eval-chronicle.test.ts`, `test/auto-chronicle-surfaces-5876.test.ts`.-- `src/core/chunkers/` — markdown chunking (`recursive.ts`) and code chunking. `code.ts` is a tree-sitter-based semantic chunker for 30 languages (plus SQL via DerekStride/tree-sitter-sql) with embedded-asset WASMs (`src/assets/wasm/`), `@dqbd/tiktoken` cl100k_base tokenizer, small-sibling merging. `CHUNKER_VERSION` is folded into `importCodeFile`'s `content_hash` so chunker shape changes force clean re-chunks across releases; `GRAMMAR_REVISIONS` (per-language, `{ lua: 1 }` after the tree-sitter-grammars v0.3.0 swap that ended the `gbrain serve` Lua-fence hang) folds into that language's hash only, and `chunkerStamp()` (`8;lua=1`) is the `sources.chunker_version` gate value every sync path reads and writes, so a grammar swap walks each source once and re-imports only its own language's files while the cost gate (`grammarOnlyDrift`, `grammar_drift`) prices those files alone. Grammar provenance and the vendoring scripts: `src/assets/wasm/README.md`; pinned by `test/chunkers/code-lua.test.ts`. `extractSymbolName` has an inline SQL branch (`extractSqlSymbolName`) diving through DerekStride's `statement` wrapper into the inner DDL child (`create_table`/`create_function`/`create_view`/`create_index`/`create_procedure`/`create_type`/`create_schema`/`create_database`/`create_trigger`/`alter_table`/`alter_view`) and extracting the target identifier via the `name` field with identifier-shaped fallback; DML kinds (`select`/`insert`/`update`/`delete`/`merge`/`with`) deliberately return null so chunks emit unnamed (code-def is a DDL signal). `normalizeSymbolType` has parallel SQL branches mapping `create_table → 'table'`, `create_view → 'view'`, etc. `DEF_TYPES` (owned by `src/core/chunkers/def-types.ts`, re-exported by `src/commands/code-def.ts` — see that entry) carries the SQL kinds (`'table' | 'view' | 'index' | 'procedure' | 'schema' | 'database' | 'trigger'`) so the new chunks surface in `gbrain code-def <name>` queries.+- `src/core/chunkers/` — markdown chunking (`recursive.ts`) and code chunking. `code.ts` is a tree-sitter-based semantic chunker for 30 languages (plus SQL via DerekStride/tree-sitter-sql) with embedded-asset WASMs (`src/assets/wasm/`), `@dqbd/tiktoken` cl100k_base tokenizer, small-sibling merging. `CHUNKER_VERSION` is folded into `importCodeFile`'s `content_hash` so chunker shape changes force clean re-chunks across releases; `GRAMMAR_REVISIONS` (per-language chunker revisions: `lua: 1` after the tree-sitter-grammars v0.3.0 swap that ended the `gbrain serve` Lua-fence hang; `typescript`/`tsx`/`javascript`/`python`/`ruby: 1` for the #5001 `__module__` chunks) folds into that language's hash only, and `chunkerStamp()` (`8;lua=1;typescript=1;…`) is the `sources.chunker_version` gate value every sync path reads and writes, so a per-language change walks each source once and re-imports only that language's files while the cost gate (`grammarOnlyDrift`, `grammar_drift`) prices those files alone. Top-level statements that contain a call (`describe(...)`, `app.use(...)`, `print(f())`, Ruby `RSpec.describe ... do`) are chunked through `code-module-chunks.ts` (below) so their call edges have a chunk to hang on. Grammar provenance and the vendoring scripts: `src/assets/wasm/README.md`; pinned by `test/chunkers/code-lua.test.ts`. `extractSymbolName` has an inline SQL branch (`extractSqlSymbolName`) diving through DerekStride's `statement` wrapper into the inner DDL child (`create_table`/`create_function`/`create_view`/`create_index`/`create_procedure`/`create_type`/`create_schema`/`create_database`/`create_trigger`/`alter_table`/`alter_view`) and extracting the target identifier via the `name` field with identifier-shaped fallback; DML kinds (`select`/`insert`/`update`/`delete`/`merge`/`with`) deliberately return null so chunks emit unnamed (code-def is a DDL signal). `normalizeSymbolType` has parallel SQL branches mapping `create_table → 'table'`, `create_view → 'view'`, etc. `DEF_TYPES` (owned by `src/core/chunkers/def-types.ts`, re-exported by `src/commands/code-def.ts` — see that entry) carries the SQL kinds (`'table' | 'view' | 'index' | 'procedure' | 'schema' | 'database' | 'trigger'`) so the new chunks surface in `gbrain code-def <name>` queries.++- `src/core/chunkers/code-module-chunks.ts` — #5001 module-level statement chunks. `moduleStatementSymbol(node, language)` names a top-level node that is a statement containing a call (JS/TS/TSX and Python `expression_statement`, Ruby `call`) as `{ symbolName: '__module__', symbolType: 'module' }`; `code.ts` adds those nodes to its semantic set and emits them through the ordinary chunk path, with `moduleChunkQualifiedName` giving the edge identity `<file-basename>::__module__` (`vat-review.test::__module__`; a Ruby `module Foo` keeps its own name). `isModuleChunk` lets `mergeSmallSiblings` fold adjacent small statements (they are not definitions), and `mergedRunSymbol` keeps the `__module__` identity on a merged run that holds one, so `code-callers helper` lists the test body or route registration that calls `helper` instead of dropping the edge. A statement without a call (`x = 1`, a docstring) and every definition-only file are unchanged. The edge rows themselves come from `code-chunks.ts`'s `mapCodeEdges`, the one call-site → `code_edges_symbol` mapping shared by `importCodeFile` and the prepared apply. Pinned by `test/chunkers/code-module-level-calls.test.ts` (chunk inventory per language, merge identity, oversized split, PGLite import through `mapCodeEdges`, the per-language revision stamp).- `src/core/chunkers/def-types.ts` — `DEF_TYPES`: the ONE list of definition-shaped normalized (post-`normalizeSymbolType`) symbol types, shared by `gbrain code-def`'s lookup allowlist (`src/commands/code-def.ts` re-exports it) and the code chunker's small-sibling merge guard so the two can't drift — a symbol type code-def can resolve never has its `symbol_name` erased by merging a small definition into a neighbor. Includes the fallthrough forms `normalizeSymbolType` emits verbatim for tree-sitter node types it doesn't canonicalize (`'method declaration'`, `'struct specifier'`, `'record declaration'`, …) — most of an OO codebase's symbols arrive in those forms. Pinned by `test/chunkers/code-merge-defs.test.ts`.diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex d4645d58cb..f840885c50 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -17,7 +17,7 @@ src/core/cycle.ts 3293 ratchet +2 System One v1 S9: extract_facts phase tail runsrc/core/cycle/synthesize.ts 3228 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import)src/core/cycle/extract-atoms.ts 1654 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms prompt; +4 GBRA-75: octet_length-bounded body-length predicate (minCompiledTruthChars) for discovery and the backlog countsrc/core/engine.ts 2755 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts); +4 FactListOpts/TrajectoryOpts.excludePrivate fact-provenance visibility contract (interface fields cannot move)-src/core/import-file.ts 2049 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts); +2 #5984 single-write fast path: the coordinated existingSnapshot option (interface field) composes with the lane apply diet at 2202; +1 GBRA-69: a coordinated apply defers its chunker seal to the caller (sealImportedPage in page-state/projections.ts)+src/core/import-file.ts 2023 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts); +2 #5984 single-write fast path: the coordinated existingSnapshot option (interface field) composes with the lane apply diet at 2202; +1 GBRA-69: a coordinated apply defers its chunker seal to the caller (sealImportedPage in page-state/projections.ts); lowered to 2023: #5001 the edge-mapping loop moved to code-chunks.ts mapCodeEdges (shared with the prepared apply)src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullablesrc/core/operations.ts 239 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row; lowered GBRA-75 W11 cold start: OP_AREAS + finalize step moved to operation-load.ts (shared with the CLI per-op loader)src/core/pglite-engine.ts 3008 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts)diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex ca3f52118d..b8fd312714 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -378,6 +378,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.157.0', text: 'The dream `consolidate` phase no longer merges two facts that differ in a negation, number, date or amount ("Invoice A due Monday" and "Invoice B due Tuesday" stay two facts), and facts without a typed metric now need a 0.95 embedding match (the explicit-duplicate bar) instead of the 0.85 `cycle.consolidate.cluster_threshold`, which keeps governing typed metric facts. Expect fewer takes from untyped event facts. `gbrain dream --phase consolidate --dry-run` lists the clusters it would write under `details.clusters`. Facts an earlier run wrongly merged keep the `valid_until` that run stamped: previous intervals were not retained, so there is no exact undo; `gbrain recall` still returns the facts, and `remember … replaces` records a correction.' },{ since: '0.60.157.0', text: 'A write tool call (`add_timeline_entry`, `put_page`, `remember`, every tool marked mutating) that names a parameter the tool does not declare is now refused `invalid_params` with nothing written, in every `mcp.strict_params` mode; the suggestion names the submitted key and the declared one (`content` → `detail` on `add_timeline_entry`). Before, the default warn mode committed the row with the misnamed field dropped. Reads keep the warn grace period.' },{ since: '0.60.157.0', text: 'A `remember` (or any single-fact write) that repeats a fact already stored word for word for the same entity, or with no resolved entity at all, now returns the existing fact (`status: duplicate`) instead of inserting a second row, including on brains without an embedding key; a remote or unattributed caller never dedups against a fact that came from a private source. A write whose entity could not be resolved and fell back to slugifying the name now stores the fact with no entity instead of minting a placeholder entity slug, so the stub guard no longer refuses later writes about that name; search and `recall` still find the fact by its text.' },+ { since: '0.60.157.0', text: 'A top-level call statement in a JavaScript, TypeScript, TSX, Python or Ruby file (a `describe(...)` / `it(...)` block, `app.use(...)`, `print(helper())`, `RSpec.describe ... do`) is now its own chunk, `symbol_type` `module` and `symbol_name` `__module__`, so the calls inside it get edges: `code-callers helper` lists the test body as `<file-basename>::__module__`. Files with such statements gain chunks, so the next `gbrain sync` walks each source once and re-chunks and re-embeds only its files in those five languages (priced by the cost gate as `grammar_drift`); `gbrain reindex-code` does the same now. Definition-only files keep their chunks and vectors.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/chunkers/code-module-chunks.ts b/src/core/chunkers/code-module-chunks.tsnew file mode 100644index 0000000000..e78852d140--- /dev/null+++ b/src/core/chunkers/code-module-chunks.ts@@ -0,0 +1,83 @@+/**+ * #5001 — module-level statement chunks.+ *+ * The chunker emits definition nodes (`TOP_LEVEL_TYPES` in code.ts); a call site has to fall inside a chunk with a+ * qualified symbol name or both edge writers drop its edge. A top-level `describe(...)` / `it(...)`, `app.use(...)`,+ * `print(helper())` or `RSpec.describe ... do` block is an expression statement, so no chunk covered it and every call+ * inside a test body or route registration was lost from `code-callers`.+ *+ * A top-level statement that contains a call becomes a chunk with `symbolType: 'module'`, `symbolName: '__module__'`+ * and the file-qualified identity `<file-basename>::__module__`, for JS/TS/TSX, Python and Ruby (the languages whose+ * call edges get receiver resolution or RSpec-style top-level blocks). A run of small adjacent statements may merge+ * (`mergeSmallSiblings`); the merged chunk keeps the `__module__` identity so its edges survive. Definition-only files+ * are unchanged. The chunk-inventory change is gated per language through `GRAMMAR_REVISIONS` (code.ts).+ */+import type { CodeChunk, SupportedCodeLanguage } from './code.ts';++export const MODULE_SYMBOL_NAME = '__module__';+export const MODULE_SYMBOL_TYPE = 'module';++interface ModuleStatementConfig {+ /** Top-level node types that are statements rather than definitions. */+ statementTypes: ReadonlySet<string>;+ /** Call node types (the edge extractor's `CALL_CONFIG` for the language); a statement without one emits nothing. */+ callTypes: ReadonlySet<string>;+}++const JS_CONFIG: ModuleStatementConfig = { statementTypes: new Set(['expression_statement']), callTypes: new Set(['call_expression']) };++const MODULE_STATEMENTS: Partial<Record<SupportedCodeLanguage, ModuleStatementConfig>> = {+ typescript: JS_CONFIG,+ tsx: JS_CONFIG,+ javascript: JS_CONFIG,+ python: { statementTypes: new Set(['expression_statement']), callTypes: new Set(['call']) },+ // tree-sitter-ruby has no statement wrapper: a top-level call IS the node (`require 'x'`, `RSpec.describe Thing do … end`).+ ruby: { statementTypes: new Set(['call', 'method_call']), callTypes: new Set(['call', 'method_call']) },+};++const MODULE_SYMBOL = { symbolName: MODULE_SYMBOL_NAME, symbolType: MODULE_SYMBOL_TYPE } as const;++const isModuleSymbol = (symbol: { symbolName: string | null; symbolType: string }): boolean =>+ symbol.symbolType === MODULE_SYMBOL_TYPE && symbol.symbolName === MODULE_SYMBOL_NAME;++/**+ * The `__module__` symbol for a top-level node that is a statement containing a call in `language`; null for every+ * definition node and for statements with no call (`x = 1`, a docstring), which stay unchunked as before.+ */+export function moduleStatementSymbol(node: any, language: SupportedCodeLanguage): typeof MODULE_SYMBOL | null {+ const config = MODULE_STATEMENTS[language];+ if (!config || !config.statementTypes.has(node.type)) return null;+ const stack: any[] = [node];+ while (stack.length) {+ const current = stack.pop();+ if (config.callTypes.has(current.type)) return MODULE_SYMBOL;+ for (const child of current.namedChildren) stack.push(child);+ }+ return null;+}++/**+ * `<file-basename>::__module__`, the edge identity of a file's module-level statements (`vat-review.test::__module__`);+ * null for every other symbol (a Ruby `module Foo` is `symbolType: 'module'` with its own name and keeps the ordinary+ * qualified name).+ */+export function moduleChunkQualifiedName(input: { filePath: string; symbolName: string | null; symbolType: string }): string | null {+ if (!isModuleSymbol(input)) return null;+ const base = input.filePath.split(/[\\/]/).pop() ?? input.filePath;+ return `${base.replace(/\.[^.]+$/, '') || base}::${MODULE_SYMBOL_NAME}`;+}++export function isModuleChunk(chunk: CodeChunk): boolean {+ return isModuleSymbol(chunk.metadata);+}++/**+ * Identity of a merged small-sibling run. A run never holds a named definition (#4511), so one that holds a module+ * statement is module-level code: it keeps the `__module__` identity and its call edges. Any other run is the+ * anonymous `merged` chunk it always was.+ */+export function mergedRunSymbol(group: CodeChunk[]): Pick<CodeChunk['metadata'], 'symbolName' | 'symbolType' | 'symbolNameQualified'> {+ const module = group.find(isModuleChunk);+ if (!module) return { symbolName: null, symbolType: 'merged' };+ return { ...MODULE_SYMBOL, symbolNameQualified: module.metadata.symbolNameQualified };+}diff --git a/src/core/chunkers/code.ts b/src/core/chunkers/code.tsindex 1012bbf347..4278d30aa8 100644--- a/src/core/chunkers/code.ts+++ b/src/core/chunkers/code.ts@@ -21,6 +21,7 @@import { chunkText as recursiveChunk } from './recursive.ts';import { buildQualifiedName } from './qualified-names.ts';import { MERGE_PROTECTED_SYMBOL_TYPES, declaresFunctionValue } from './def-types.ts';+import { isModuleChunk, mergedRunSymbol, moduleChunkQualifiedName, moduleStatementSymbol } from './code-module-chunks.ts';import { estimateTokens, estimateEmbedTokens, estimateEmbedTokensCeiling, DEFAULT_MAX_CHUNK_TOKENS } from './token-estimate.ts';import { safeSplitIndex } from '../text-safe.ts';import {@@ -143,13 +144,14 @@ import G_ZIG from '../../assets/wasm/grammars/tree-sitter-zig.wasm' with { type:// v8 (N13-1): `const f = () => …` definitions keep their own named chunk.export const CHUNKER_VERSION = 8;/**- * Per-language grammar revisions, folded into that language's code-file hash- * and into `chunkerStamp()`. A grammar swap re-chunks only its own language's- * files instead of every code page in the brain (a CHUNKER_VERSION bump).+ * Per-language chunker revisions (a grammar swap or a language-specific emission rule), folded into that language's+ * code-file hash and into `chunkerStamp()`: a change re-chunks only its own language's files instead of every code+ * page in the brain (a CHUNKER_VERSION bump).* lua 1: tree-sitter-grammars v0.3.0 replaced a build whose scanner ran every* parse after the first on uninitialized state; Lua defs now become chunks.+ * typescript/tsx/javascript/python/ruby 1 (#5001): top-level call statements become `__module__` chunks (code-module-chunks.ts).*/-export const GRAMMAR_REVISIONS: Partial<Record<SupportedCodeLanguage, number>> = { lua: 1 };+export const GRAMMAR_REVISIONS: Partial<Record<SupportedCodeLanguage, number>> = { lua: 1, typescript: 1, tsx: 1, javascript: 1, python: 1, ruby: 1 };/** The `sources.chunker_version` gate value: a change forces the next sync to walk every file (hash compare, no re-import of unchanged hashes). */export const chunkerStamp = (): string => [String(CHUNKER_VERSION), ...Object.entries(GRAMMAR_REVISIONS).map(([lang, rev]) => `${lang}=${rev}`)].join(';');@@ -796,10 +798,8 @@ async function chunkParsedLanguage(}const root = (tree as any).rootNode;- const topLevelTypes = TOP_LEVEL_TYPES[language];- const semanticNodes = topLevelTypes- ? root.namedChildren.filter((n: any) => topLevelTypes.has(n.type))- : [];+ const topLevelTypes = TOP_LEVEL_TYPES[language]!;+ const semanticNodes = root.namedChildren.filter((n: any) => topLevelTypes.has(n.type) || moduleStatementSymbol(n, language) !== null);if (semanticNodes.length === 0) {return { chunks: fallbackChunks(source, filePath, language, opts), edges: [] };@@ -830,16 +830,17 @@ async function chunkParsedLanguage(// declaration; top-level chunk still uses the outer node's range// so the header shows the `export` keyword for completeness.const nestableNode = findNestableParent(node, nestedConfig);- const symbolName = extractSymbolName(nestableNode ?? node);+ const moduleSymbol = moduleStatementSymbol(node, language); // #5001: a top-level statement containing a call+ const symbolName = moduleSymbol?.symbolName ?? extractSymbolName(nestableNode ?? node);// For SQL `statement` wrappers, the meaningful type lives on the inner// child. extractSymbolName already dives in for the name; mirror that// here so chunk headers say "table users" not "statement users".// #3821: same for Python decorated_definition — the header must say// "function cached_fn" / "class Config", not "decorated definition".const typeNode = unwrapDecorated(nestableNode ?? node);- const symbolType = (typeNode.type === 'statement' && typeNode.namedChildCount === 1)+ const symbolType = moduleSymbol?.symbolType ?? ((typeNode.type === 'statement' && typeNode.namedChildCount === 1)? normalizeSymbolType(typeNode.namedChild(0).type)- : normalizeSymbolType(typeNode.type);+ : normalizeSymbolType(typeNode.type));if (nestableNode && symbolName && nestedConfig) {const before = chunks.length;@@ -935,9 +936,9 @@ async function chunkParsedLanguage(* the chunker respect the user's chunkSizeTokens budget instead of* letting the file's AST dictate it.*- * Merged chunks lose their individual symbolName (set to null) and- * get symbolType='merged'. The header shows the line range of the- * merged group. Single-chunk groups pass through unchanged.+ * Merged chunks lose their individual symbolName (set to null) and get symbolType='merged', except a run holding a+ * #5001 `__module__` statement, which keeps that identity (code-module-chunks.ts). The header shows the line range+ * of the merged group. Single-chunk groups pass through unchanged.*/function mergeSmallSiblings(chunks: CodeChunk[], chunkTarget: number): CodeChunk[] {if (chunks.length <= 1) return chunks;@@ -962,7 +963,7 @@ function mergeSmallSiblings(chunks: CodeChunk[], chunkTarget: number): CodeChunk// accumulated into one. The set is a derived view of code-def's DEF_TYPES// (def-types.ts), so the lookup allowlist and this guard cannot drift.const isDefChunk = (c: CodeChunk): boolean =>- c.metadata.symbolName != null &&+ c.metadata.symbolName != null && !isModuleChunk(c) &&(MERGE_PROTECTED_SYMBOL_TYPES.has(c.metadata.symbolType) || c.metadata.definesFunction === true);const merged: CodeChunk[] = [];let i = 0;@@ -1027,8 +1028,7 @@ function buildMergedChunk(group: CodeChunk[], index: number): CodeChunk {index,text: `${header}\n\n${mergedBody}`,metadata: {- symbolName: null,- symbolType: 'merged',+ ...mergedRunSymbol(group),filePath: first.metadata.filePath,language: first.metadata.language,startLine: first.metadata.startLine,@@ -1212,7 +1212,7 @@ function buildChunk(input: {const header = `[${displayLang(input.language)}] ${input.filePath}:${input.startLine}-${input.endLine} ${symbol}${parentPath}`;// v0.20.0 Cathedral II Layer 5 (A1): fold the qualified name into// metadata so edge extraction has a stable identity key.- const qualified = buildQualifiedName({+ const qualified = moduleChunkQualifiedName(input) ?? buildQualifiedName({language: input.language,symbolName: input.symbolName,symbolType: input.symbolType,diff --git a/src/core/code-chunks.ts b/src/core/code-chunks.tsindex 8629de2bbc..739c0e1b5e 100644--- a/src/core/code-chunks.ts+++ b/src/core/code-chunks.ts@@ -1,7 +1,7 @@import type { BrainEngine } from './engine.ts';import type { ChunkInput, CodeEdgeInput } from './types.ts';import { chunkCodeTextFull } from './chunkers/code.ts';-import { findChunkForOffset } from './chunkers/edge-extractor.ts';+import { findChunkForOffset, type ExtractedEdge } from './chunkers/edge-extractor.ts';import { sanitizeRemoteBody } from './remote-body.ts';import { credentialSafeProjection } from './credential-projection.ts';import { isEmbedSkipped } from './embed-skip.ts';@@ -31,14 +31,29 @@ export async function installCodeChunkEdges(engine: BrainEngine, slug: string, sawait engine.executeRaw('UPDATE content_chunks SET edges_backfilled_at=NULL WHERE id = ANY($1::int[])', [ids]);const ranges = stored.map(c => ({ id: c.id, startLine: c.start_line ?? 1,endLine: c.end_line ?? 1, symbol_name_qualified: c.symbol_name_qualified }));- const edges: CodeEdgeInput[] = [];- for (const edge of prepared.edges) {- const index = findChunkForOffset(edge.callSiteByteOffset, prepared.content, ranges);+ const edges = mapCodeEdges(prepared.edges, prepared.content, ranges, sourceId);+ if (edges.length) await engine.addCodeEdges(edges);+}++/**+ * The one mapping from extracted call sites to `code_edges_symbol` rows, shared by the inline import+ * (`importCodeFile`) and the prepared apply (`installCodeChunkEdges`). An edge hangs on the innermost persisted chunk+ * whose line range holds the call site; a site in a chunk with no id or no qualified symbol (a `merged` run) is+ * dropped. #5001: a site in a top-level statement lands on the file's `__module__` chunk. `source_id` is stamped from+ * the normalized import source ('default' for an unscoped import, never null): `getCallersOf` / `getCalleesOf` add+ * `AND source_id = <scoped>` under a worktree pin or `--source`, and a NULL stamp matched nothing.+ */+export function mapCodeEdges(edges: ExtractedEdge[], content: string,+ ranges: Array<{ id?: number; startLine: number; endLine: number; symbol_name_qualified?: string | null }>,+ sourceId: string): CodeEdgeInput[] {+ const out: CodeEdgeInput[] = [];+ for (const edge of edges) {+ const index = findChunkForOffset(edge.callSiteByteOffset, content, ranges);const from = index === null ? undefined : ranges[index];- if (!from?.symbol_name_qualified) continue;- edges.push({ from_chunk_id: from.id, to_chunk_id: null, from_symbol_qualified: from.symbol_name_qualified,+ if (!from?.id || !from.symbol_name_qualified) continue;+ out.push({ from_chunk_id: from.id, to_chunk_id: null, from_symbol_qualified: from.symbol_name_qualified,to_symbol_qualified: edge.toSymbol, edge_type: edge.edgeType, source_id: sourceId,...(edge.memberCall ? { edge_metadata: { member_call: true } } : {}) });}- if (edges.length) await engine.addCodeEdges(edges);+ return out;}diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex 9d4ed5b33b..9e2a6ea3b4 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -17,14 +17,13 @@ import type { FenceIssueWire } from './fence-repair/tier1.ts';import type { FenceFix } from './fence-repair/types.ts';import { classifyStoredType } from './schema-pack/type-usage.ts';import { prepareFenceAwareMarkdownChunks } from './markdown-chunks.ts';-import { prepareCodeChunks, installCodeChunkEdges } from './code-chunks.ts';+import { prepareCodeChunks, installCodeChunkEdges, mapCodeEdges } from './code-chunks.ts';import { detectCodeLanguage, CHUNKER_VERSION, GRAMMAR_REVISIONS, type SupportedCodeLanguage } from './chunkers/code.ts';import { sanitizeRemoteBody } from './remote-body.ts';import { installPageEmbeddings, installPageProjection, preparePageProjection, projectionBelowSafeFence, queuePageProjection, readProjectionSnapshot, resealSafeChunks,sealPageTextProjection, stampEmbeddingInputs, type ProjectionSnapshot } from './page-state/projections.ts';import { sanitizeText } from './batch-rows.ts';import { hasProtectedBody, safeChunksFilter } from './search/safe-chunks.ts';-import { findChunkForOffset } from './chunkers/edge-extractor.ts';import { planEmbeddingReuse } from './embed-reuse.ts';import { reuseStoredChunkVectors } from './import-chunk-reuse.ts';import { extractCodeRefs, imageOfCandidates } from './link-extraction.ts';@@ -1411,32 +1410,7 @@ export async function importCodeFile(};});- const edgeInputs: import('./types.ts').CodeEdgeInput[] = [];- for (const e of extractedEdges) {- const idx = findChunkForOffset(e.callSiteByteOffset, storageContent, rangeList);- if (idx == null) continue;- const from = rangeList[idx]!;- if (!from.id || !from.symbol_name_qualified) continue;- edgeInputs.push({- from_chunk_id: from.id,- to_chunk_id: null,- from_symbol_qualified: from.symbol_name_qualified,- to_symbol_qualified: e.toSymbol,- edge_type: e.edgeType, ...(e.memberCall ? { edge_metadata: { member_call: true } } : {}),- // Stamp the source: getCallersOf/getCalleesOf add- // `AND source_id = <scoped>` whenever a worktree pin / --source is- // in play, and a NULL here never matches that filter — so every- // scoped call-graph query silently returned 0 rows on- // multi-source brains even though the edges existed. The fallback- // is 'default', NOT null: an unscoped import lands its pages under- // the schema default (pages.source_id DEFAULT 'default'), so a- // NULL-stamped edge would be invisible to the matching scoped- // query getCallersOf(sym, { sourceId: 'default' }) — the same bug- // through the other door.- source_id: edgeSourceId,- });- }-+ const edgeInputs = mapCodeEdges(extractedEdges, storageContent, rangeList, edgeSourceId);if (edgeInputs.length > 0) {await engine.addCodeEdges(edgeInputs);}diff --git a/test/chunkers/code-lua.test.ts b/test/chunkers/code-lua.test.tsindex 644bdd9c29..6c88572d60 100644--- a/test/chunkers/code-lua.test.ts+++ b/test/chunkers/code-lua.test.ts@@ -111,7 +111,8 @@ describe('the grammar swap re-chunks Lua files only', () => {test('CHUNKER_VERSION is unchanged and the stamp carries the Lua grammar revision', () => {expect(CHUNKER_VERSION).toBe(8);expect(GRAMMAR_REVISIONS.lua).toBe(1);- expect(chunkerStamp()).toBe('8;lua=1');+ // #5001 added per-language revisions for the `__module__` chunks after `lua=1`; the Lua entry is unchanged.+ expect(chunkerStamp()).toBe('8;lua=1;typescript=1;tsx=1;javascript=1;python=1;ruby=1');});test('grammarOnlyDrift names the languages whose revision moved, and nothing on a version bump or a fresh source', () => {diff --git a/test/chunkers/code-module-level-calls.test.ts b/test/chunkers/code-module-level-calls.test.tsnew file mode 100644index 0000000000..291d6256cf--- /dev/null+++ b/test/chunkers/code-module-level-calls.test.ts@@ -0,0 +1,225 @@+/**+ * #5001 — call edges inside top-level `describe` / `it` blocks (and every other top-level call statement) were dropped.+ *+ * Contract protected: a call site in a top-level expression statement (a vitest/jest/mocha `describe(...)`, an Express+ * `app.use(...)`, a Python `print(helper())`, an RSpec `RSpec.describe ... do` block) gets a `calls` edge whose+ * `from_symbol_qualified` is `<file-basename>::__module__`, from a chunk with `symbol_type = 'module'` and+ * `symbol_name = '__module__'`. Before the fix `TOP_LEVEL_TYPES` had no entry for those statements, no chunk covered+ * them, `findChunkForOffset` returned null and both edge writers skipped the edge: `code-callers helper` listed a+ * caller inside a named function and nothing from the test body that called it.+ *+ * Regression that fails it: dropping the module-statement entry for a language, emitting the chunk without the+ * file-qualified name, or merging a run of top-level statements into an anonymous `merged` chunk again.+ *+ * Why existing coverage misses it: `test/chunkers/code.test.ts` and `test/edge-extractor.test.ts` chunk definition-only+ * fixtures (every call site sits inside a named function or method), and this test also pins that their inventory is+ * unchanged: a definition-only file emits no `__module__` chunk.+ *+ * The `__module__` attribution follows the suggestion in the issue thread.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { CHUNKER_VERSION, chunkCodeTextFull, chunkerStamp, GRAMMAR_REVISIONS } from '../../src/core/chunkers/code.ts';+import { findChunkForOffset } from '../../src/core/chunkers/edge-extractor.ts';+import { importCodeFile } from '../../src/core/import-file.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { grammarOnlyDrift } from '../../src/core/sync-cost-gate.ts';+import { resetPgliteState } from '../helpers/reset-pglite.ts';++const tsSource = `import { describe, it, expect } from 'bun:test';+const boxByKey = (k: string) => ({ k });+export function helper(x: number) { return boxByKey(String(x)); }+describe('vat', () => {+ it('boxes', () => { expect(boxByKey('a')).toBeDefined(); helper(1); });+ it('again', () => { boxByKey('b'); });+});+const list = [1, 2].map(x => boxByKey(String(x)));+`;+const pySource = `import os+def helper(x):+ return x + 1+class Thing:+ def run(self):+ return helper(2)+print(helper(1))+`;+const rbSource = `require 'spec_helper'+def helper(x)+ x + 1+end+RSpec.describe Thing do+ it 'works' do+ expect(helper(1)).to eq(2)+ end+end+`;++/** Call edges attributed the way both edge writers do it: innermost chunk by line, dropped without a qualified name. */+async function callEdges(source: string, path: string) {+ const { chunks, edges } = await chunkCodeTextFull(source, path);+ const ranges = chunks.map(c => ({ startLine: c.metadata.startLine, endLine: c.metadata.endLine }));+ const attributed: Array<{ to: string; from: string | null }> = [];+ for (const edge of edges) {+ if (edge.edgeType !== 'calls') continue;+ const index = findChunkForOffset(edge.callSiteByteOffset, source, ranges);+ attributed.push({ to: edge.toSymbol, from: index === null ? null : chunks[index]!.metadata.symbolNameQualified ?? null });+ }+ return { chunks, attributed };+}++const moduleChunks = (chunks: Awaited<ReturnType<typeof chunkCodeTextFull>>['chunks']) =>+ chunks.filter(c => c.metadata.symbolType === 'module' && c.metadata.symbolName === '__module__');++describe('#5001 top-level call statements become __module__ chunks and keep their call edges', () => {+ test.each([['typescript', 'src/vat-review.test.ts'], ['tsx', 'src/vat-review.test.tsx']])(+ '%s: the describe block is one module chunk and its calls to helper/boxByKey are attributed to it',+ async (_language, path) => {+ const { chunks, attributed } = await callEdges(tsSource, path);+ const modules = moduleChunks(chunks);+ expect(modules).toHaveLength(1);+ expect(modules[0]!.metadata.startLine).toBe(4);+ expect(modules[0]!.metadata.endLine).toBe(7);+ expect(modules[0]!.metadata.symbolNameQualified).toBe('vat-review.test::__module__');+ expect(modules[0]!.text).toContain("it('again', () => { boxByKey('b'); });");+ // Before the fix: the two calls inside `it` bodies and the `helper(1)` call had no chunk (from === null).+ expect(attributed.filter(e => e.to === 'helper')).toEqual([{ to: 'helper', from: 'vat-review.test::__module__' }]);+ expect(attributed.filter(e => e.to === 'boxByKey').map(e => e.from).sort()).toEqual(+ ['helper', 'list', 'vat-review.test::__module__', 'vat-review.test::__module__'],+ );+ expect(attributed.some(e => e.from === null)).toBe(false);+ // The definition chunks are the same ones as before.+ expect(chunks.filter(c => c.metadata.symbolType !== 'module').map(c => c.metadata.symbolName)).toEqual(['boxByKey', 'helper', 'list']);+ },+ );++ test('python: a top-level print(helper(1)) is a module chunk; the method call stays attributed to Thing.run', async () => {+ const { chunks, attributed } = await callEdges(pySource, 'pkg/app.py');+ const modules = moduleChunks(chunks);+ expect(modules.map(c => [c.metadata.startLine, c.metadata.endLine, c.metadata.symbolNameQualified])).toEqual([[7, 7, 'app::__module__']]);+ expect(attributed.filter(e => e.to === 'helper').map(e => e.from).sort()).toEqual(['Thing.run', 'app::__module__']);+ expect(attributed.find(e => e.to === 'print')?.from).toBe('app::__module__');+ });++ test('ruby: the RSpec.describe block and the require line are module chunks', async () => {+ const { chunks, attributed } = await callEdges(rbSource, 'spec/thing_spec.rb');+ const modules = moduleChunks(chunks);+ expect(modules.map(c => [c.metadata.startLine, c.metadata.endLine])).toEqual([[1, 1], [5, 9]]);+ expect(modules.every(c => c.metadata.symbolNameQualified === 'thing_spec::__module__')).toBe(true);+ expect(attributed.find(e => e.to === 'helper')?.from).toBe('thing_spec::__module__');+ expect(attributed.find(e => e.to === 'require')?.from).toBe('thing_spec::__module__');+ expect(chunks.find(c => c.metadata.symbolName === 'helper')?.metadata.symbolType).toBe('function');+ // A Ruby `module` definition is `symbolType: 'module'` too; it keeps its own name and qualified identity.+ const { chunks: named } = await chunkCodeTextFull('module Billing\n def self.run\n helper(1)\n end\nend\n', 'lib/billing.rb');+ expect(named.map(c => [c.metadata.symbolType, c.metadata.symbolName, c.metadata.symbolNameQualified])).toEqual([+ ['module', 'Billing', 'Billing'], ['function', 'run', 'Billing#run'],+ ]);+ expect(moduleChunks(named)).toHaveLength(0);+ });++ test('a top-level statement without a call is not a module chunk', async () => {+ const { chunks } = await chunkCodeTextFull('let counter = 0;\ncounter = 2;\ncounter += 1;\n`tagged`;\n', 'src/state.ts');+ expect(moduleChunks(chunks)).toHaveLength(0);+ const { chunks: py } = await chunkCodeTextFull('"""Module docstring."""\nx = 1\n', 'pkg/consts.py');+ expect(moduleChunks(py)).toHaveLength(0);+ });++ test('definition-only files keep their chunk inventory (no module chunk appears)', async () => {+ const ts = await chunkCodeTextFull('export function a() { return b(); }\nexport function b() { return 1; }\nexport class C { m() { return a(); } }\n', 'src/defs.ts');+ expect(ts.chunks.map(c => c.metadata.symbolType)).not.toContain('module');+ const py = await chunkCodeTextFull('import os\ndef a():\n return b()\ndef b():\n return 1\n', 'pkg/defs.py');+ expect(py.chunks.map(c => c.metadata.symbolType)).not.toContain('module');+ const go = await chunkCodeTextFull('package p\n\nfunc A() int { return B() }\nfunc B() int { return 1 }\n', 'p/defs.go');+ expect(go.chunks.map(c => c.metadata.symbolType)).not.toContain('module');+ });++ test('a run of small top-level call statements merges into one chunk that keeps the __module__ identity', async () => {+ const source = `import express from 'express';+const app = express();+app.use(cors());+app.use(json());+app.use(logger());+app.listen(3000);+export function shutdown() { return app.close(); }+`;+ const { chunks, attributed } = await callEdges(source, 'src/server.ts');+ const modules = moduleChunks(chunks);+ // The small `const app = express()` neighbour (a mergeable run type) folds into the run; a run never holds a named+ // definition (#4511), so module-level is the right identity for it and the `express` call keeps an edge.+ expect(modules).toHaveLength(1);+ expect(modules[0]!.metadata.startLine).toBe(2);+ expect(modules[0]!.metadata.endLine).toBe(6);+ expect(modules[0]!.metadata.symbolNameQualified).toBe('server::__module__');+ expect(modules[0]!.text).toContain('merged (5 siblings)');+ expect(chunks.some(c => c.metadata.symbolType === 'merged')).toBe(false);+ expect(attributed.filter(e => e.from === 'server::__module__').map(e => e.to).sort()).toEqual(['cors', 'express', 'json', 'listen', 'logger', 'use', 'use', 'use']);+ expect(chunks.find(c => c.metadata.symbolName === 'shutdown')?.metadata.symbolType).toBe('export statement');+ });++ test('an oversized describe block is split and every piece stays a file-qualified module chunk', async () => {+ const cases = Array.from({ length: 80 }, (_, i) => ` it('case ${i}', () => { expect(helper(${i})).toBe(${i + 1}); });`).join('\n');+ const source = `import { helper } from './helper.ts';\ndescribe('big', () => {\n${cases}\n});\n`;+ const { chunks } = await chunkCodeTextFull(source, 'src/big.test.ts', { maxChunkTokens: 300 });+ const modules = moduleChunks(chunks);+ expect(modules.length).toBeGreaterThan(1);+ expect(modules.every(c => c.metadata.symbolNameQualified === 'big.test::__module__')).toBe(true);+ expect(chunks.filter(c => c.metadata.symbolType !== 'module')).toHaveLength(0);+ });+});++describe('#5001 the five languages whose inventory grows re-chunk on their own, like the Lua grammar swap', () => {+ test('CHUNKER_VERSION is unchanged; typescript, tsx, javascript, python and ruby carry revision 1', () => {+ expect(CHUNKER_VERSION).toBe(8);+ for (const language of ['typescript', 'tsx', 'javascript', 'python', 'ruby'] as const) expect(GRAMMAR_REVISIONS[language]).toBe(1);+ expect(grammarOnlyDrift('8;lua=1', chunkerStamp())).toEqual(new Set(['typescript', 'tsx', 'javascript', 'python', 'ruby']));+ });+});++describe('#5001 importCodeFile persists the module-chunk edges (shared edge mapping)', () => {+ let engine: PGLiteEngine;++ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ });++ afterAll(async () => {+ await engine.disconnect();+ });++ beforeEach(async () => {+ await resetPgliteState(engine);+ });++ test('code-callers helper lists the test body as vat-review.test::__module__', async () => {+ await importCodeFile(engine, 'src/vat-review.test.ts', tsSource, { noEmbed: true });+ const callers = await engine.getCallersOf('helper', { allSources: true });+ expect(callers.filter(c => c.from_symbol_qualified === 'vat-review.test::__module__').map(c => c.edge_type)).toEqual(['calls']);+ // Two call sites, one persisted row: code_edges_symbol is unique per (from_chunk_id, to_symbol_qualified, edge_type).+ const boxCallers = await engine.getCallersOf('boxByKey', { allSources: true });+ expect(boxCallers.map(c => c.from_symbol_qualified).sort()).toEqual(['helper', 'list', 'vat-review.test::__module__']);+ const rows = await engine.executeRaw<{ symbol_type: string | null; symbol_name: string | null; symbol_name_qualified: string | null }>(+ `SELECT symbol_type, symbol_name, symbol_name_qualified FROM content_chunks WHERE symbol_type = 'module'`,+ );+ expect(rows).toEqual([{ symbol_type: 'module', symbol_name: '__module__', symbol_name_qualified: 'vat-review.test::__module__' }]);+ });++ test('the shared mapper drops an edge whose chunk has no persisted id or qualified name', async () => {+ const { mapCodeEdges } = await import('../../src/core/code-chunks.ts');+ const source = 'a();\nb();\nc();\n';+ const edges = [+ { callSiteByteOffset: 0, toSymbol: 'a', edgeType: 'calls' as const },+ { callSiteByteOffset: 5, toSymbol: 'b', edgeType: 'calls' as const, memberCall: true as const },+ { callSiteByteOffset: 10, toSymbol: 'c', edgeType: 'calls' as const },+ ];+ const ranges = [+ { id: 1, startLine: 1, endLine: 1, symbol_name_qualified: 'f::__module__' },+ { id: 2, startLine: 2, endLine: 2, symbol_name_qualified: 'f::__module__' },+ { id: undefined, startLine: 3, endLine: 3, symbol_name_qualified: 'f::__module__' },+ ];+ expect(mapCodeEdges(edges, source, ranges, 'src1')).toEqual([+ { from_chunk_id: 1, to_chunk_id: null, from_symbol_qualified: 'f::__module__', to_symbol_qualified: 'a', edge_type: 'calls', source_id: 'src1' },+ { from_chunk_id: 2, to_chunk_id: null, from_symbol_qualified: 'f::__module__', to_symbol_qualified: 'b', edge_type: 'calls', source_id: 'src1', edge_metadata: { member_call: true } },+ ]);+ expect(mapCodeEdges(edges, source, [{ id: 1, startLine: 1, endLine: 3, symbol_name_qualified: null }], 'src1')).toEqual([]);+ });+});