Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(chunker): replace the Lua grammar that hung gbrain serve; re-chunk Lua files only
garrytancdb61440794d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 104831931c..985d59150e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,26 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [0.60.132.0] - 2026-10-09++**A page with ` ```lua ` fences no longer stalls the writer: the Lua grammar is replaced, Lua definitions become semantic chunks for the first time, and only Lua files re-chunk on upgrade.**++GBRA-49's LongMemEval scoreboard found `gbrain serve --surface starter` on PGLite at 99.5% CPU for 9.5 hours after a `put_page` had been admitted, never reading stdin again, with `[persistence] phase=preparation reason=deadline_exceeded` repeating (376 times) and 47 later writes queued behind it. The page was an exported chat whose assistant turns wrapped shell commands in ChatGPT-style ` ```lua ` fences (`sudo aa-status`, `sudo aa-status | grep snap.discord.discord`). The vendored Lua grammar (the `tree-sitter-wasms` build of the unmaintained Azganoth/tree-sitter-lua 2.1.3) allocated its external scanner state with `malloc` and reset it only when `deserialize` was handed two bytes, so every parse after the first in a process started from whatever the recycled heap held: `x = 1` misparsed as an error, and the fence texts spun inside the parser until the chunker's 30 s timeout. Five fences made each preparation attempt about 150 s of blocked event loop (a CPU profile puts about 80% in the runtime's parse loop driven by the scanner), past its 30 s deadline, so the consumer abandoned and retried it. On 0.60.106.0 that loop never ended; since #6278 (`persistence.max_preparation_attempts`, default 2) the request fails `preparation_stalled` after two attempts, which still costs five minutes of unresponsive serve and loses the write. Reproduced on current master before the fix. Independently, no Lua definition had ever become a semantic chunk, because the old grammar's node types never matched `TOP_LEVEL_TYPES.lua`.++### What you see++| Where | What changed |+|---|---|+| A page or file with Lua fences or `.lua` code | Chunks in milliseconds, on every parse, with `function`, `local function` and `function M.f()` definitions as named semantic chunks (`code-def` / `code-callers` work for Lua). |+| `gbrain serve` writing such a page | The write commits as any other; no preparation deadline, no retry loop, stdin keeps being read. |+| Existing indexes, on the next sync | Each source is walked once (hash compare) and only its `.lua` files re-import, re-chunk and re-embed; every other code page keeps its hash and its chunks. `CHUNKER_VERSION` stays 8. The sync cost gate prices the walk by the Lua files alone (`grammar_drift`), not the whole tree. Lua fences inside Markdown pages already indexed stay text chunks until the page changes or `gbrain sync --source <id> --full`. |++### Itemized changes++- `src/assets/wasm/grammars/tree-sitter-lua.wasm`: the official tree-sitter-grammars/tree-sitter-lua v0.3.0 release asset (ABI 14, the newest the pinned `[email protected]` accepts; v0.4.0+ are ABI 15), SHA-256 `8fe0afe3…ee0d`; `scripts/vendor-lua-wasm.sh` downloads it and checks the checksum before writing; provenance in `src/assets/wasm/README.md`.+- `src/core/chunkers/code.ts`: `GRAMMAR_REVISIONS` (`{ lua: 1 }`) and `chunkerStamp()` (`8;lua=1`). `import-file.ts` folds a language's grammar revision into that language's code-file hash only. The `sources.chunker_version` gate (`sync/preflight.ts`, `sync/full.ts`, `sync/finalize.ts`, `persistence/sync-prepare.ts`, the doctor's extraction check) reads and writes the stamp. `sync-cost-gate.ts`: `grammarOnlyDrift` and a per-language estimate for a stamp whose version is unchanged.+- Tests: `test/chunkers/code-lua.test.ts` (ABI and import check; forced probes: the same text parses identically on every parser instance, the stuck page's five fences chunk in under a second with a 1.5 s per-fence timeout pinned, a conversation page with them prepares in one pass, Lua definitions become named chunks; all five fail on the previous grammar; the stamp, `grammarOnlyDrift`, and the cost gate pricing a grammar drift by Lua files alone). End to end on a fresh keyless PGLite brain, `gbrain put` of the stuck page: 1.8 s committed (previous grammar on current master: the CLI's wait ran out after 92 s with the request still `queued` and `deadline_exceeded` on stderr).+## [0.60.131.0] - 2026-10-09**Vector search scoped to one source now finds that source's true nearest chunks, and a remote reader's scoped search no longer runs for seconds. Unscoped search runs the same statement as before. Rescoring fetches embeddings about twice as fast.**diff --git a/docs/architecture/key-files/core-services-1.md b/docs/architecture/key-files/core-services-1.mdindex 0a3b3af8ef..eb6bbd2d2e 100644--- a/docs/architecture/key-files/core-services-1.md+++ b/docs/architecture/key-files/core-services-1.md@@ -33,7 +33,7 @@ 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. `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, `{ 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/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/vendor-lua-wasm.sh b/scripts/vendor-lua-wasm.shnew file mode 100755index 0000000000..cad7afe8ea--- /dev/null+++ b/scripts/vendor-lua-wasm.sh@@ -0,0 +1,16 @@+#!/usr/bin/env bash+set -euo pipefail++REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"+WORK="$(mktemp -d)"+trap 'rm -rf "$WORK"' EXIT++# tree-sitter-grammars/tree-sitter-lua v0.3.0: the newest release built at language ABI 14,+# which the pinned [email protected] runtime accepts (v0.4.0 and later are ABI 15).+curl --fail --location --silent --show-error \+ https://github.com/tree-sitter-grammars/tree-sitter-lua/releases/download/v0.3.0/tree-sitter-lua.wasm \+ -o "$WORK/tree-sitter-lua.wasm"+printf '%s %s\n' \+ 8fe0afe3238dad43a1dd541ba3024c28d3cd23466b031fe0a39d8f9d7e81ee0d \+ "$WORK/tree-sitter-lua.wasm" | shasum -a 256 --check+cp "$WORK/tree-sitter-lua.wasm" "$REPO_ROOT/src/assets/wasm/grammars/tree-sitter-lua.wasm"diff --git a/src/assets/wasm/README.md b/src/assets/wasm/README.mdindex 1e97e71c4b..8fad015278 100644--- a/src/assets/wasm/README.md+++ b/src/assets/wasm/README.md@@ -38,6 +38,45 @@ That gate does not force a full walk when new commits are present; use`gbrain sync --source <id> --full` to recover all previously affected files inan active repository rather than relying on an incremental sync.+## Lua (`gbrain serve` hang, GBRA-49 Q1 scoreboard)++`grammars/tree-sitter-lua.wasm` is the official+[`tree-sitter-grammars/tree-sitter-lua` v0.3.0 release asset](https://github.com/tree-sitter-grammars/tree-sitter-lua/releases/tag/v0.3.0),+replacing the `tree-sitter-wasms` bundle's build of the unmaintained+`Azganoth/tree-sitter-lua` 2.1.3.++- Upstream source tag: `v0.3.0`, commit+ `534c461d2b75b0887ec968ef9635f4460b0878b7` (MIT license).+- SHA-256: `8fe0afe3238dad43a1dd541ba3024c28d3cd23466b031fe0a39d8f9d7e81ee0d`.+- Size: 48,189 bytes. Language ABI: 14, compatible with the pinned+ `[email protected]` runtime (ABI 13–14). v0.4.0 and later are ABI 15.+- Why: the previous grammar's external scanner allocated its state with+ `malloc` and only reset it in `deserialize` when handed a 2-byte buffer, so a+ fresh parse (which deserializes an empty buffer) started from whatever the+ recycled heap held. The first Lua parse in a process was sound; every later+ one began "inside" a string or long bracket, misparsed `x = 1` as an error,+ or spun until the chunker timeout (30 s per fence). A conversation page with+ five ChatGPT-style ```` ```lua ```` fences around shell commands kept+ `gbrain serve` at 100% CPU for 9.5 hours: each preparation attempt blocked+ the event loop for about 150 s, exceeded its deadline, and was retried.+ The maintained grammar uses `calloc` and resets state on every parse.+- The node types also changed (`function_declaration` for every+ `function` / `local function` / `function M.f()` form), which is what+ `TOP_LEVEL_TYPES.lua` expected all along: Lua definitions become semantic+ chunks for the first time. `GRAMMAR_REVISIONS.lua = 1` in+ `src/core/chunkers/code.ts` folds into Lua code-file hashes and into the+ `sources.chunker_version` stamp (`8;lua=1`), so the next sync walks each+ source and re-imports only its Lua files; `CHUNKER_VERSION` stays 8 and no+ other code page re-chunks or re-embeds.++Re-vendor the pinned official asset, verifying its checksum before replacement:++```sh+bash scripts/vendor-lua-wasm.sh+bun test test/chunkers/code-lua.test.ts+bun run check:wasm+```+## Dart (#3356)`grammars/tree-sitter-dart.wasm` is the one grammar not taken from thediff --git a/src/assets/wasm/grammars/tree-sitter-lua.wasm b/src/assets/wasm/grammars/tree-sitter-lua.wasmindex 6783ea0c04..f850c9e97b 100755Binary files a/src/assets/wasm/grammars/tree-sitter-lua.wasm and b/src/assets/wasm/grammars/tree-sitter-lua.wasm differdiff --git a/src/commands/doctor/checks/extraction-sync.ts b/src/commands/doctor/checks/extraction-sync.tsindex 1328a6a24f..da16fd20b5 100644--- a/src/commands/doctor/checks/extraction-sync.ts+++ b/src/commands/doctor/checks/extraction-sync.ts@@ -12,7 +12,7 @@ import { probeSourceGitState } from '../../../core/git-head.ts';// this pure comparator (no git subprocess on the HTTP MCP doctor path).import { lagFromContentMs, loadSyncFreshnessSources, resolveStalenessCeilingSeconds } from '../../../core/source-health.ts';import { resolveEnvNumber, resolveHoursEnv, warnOnceForEnv } from '../../../core/env-number.ts';-import { CHUNKER_VERSION } from '../../../core/chunkers/code.ts';+import { chunkerStamp } from '../../../core/chunkers/code.ts';import { effectiveLinkExtractorWatermark, smallBrainBacklogNote } from '../../../core/link-extraction-watermark.ts';import { previewMentionPass } from '../../../core/mentions/stale.ts';import { isUndefinedColumnError } from '../../../core/utils.ts';@@ -1235,8 +1235,8 @@ export async function checkSyncFreshness(// v0.41.27.0: D7 narrowed predicate. The CHUNKER_VERSION caller-side// check mirrors sync.ts:1057's chunker-version gate so doctor agrees// with sync on "is there work to do?". `sources.chunker_version` is- // a TEXT column storing String(CHUNKER_VERSION).- const currentChunkerVersion = String(CHUNKER_VERSION);+ // a TEXT column storing chunkerStamp().+ const currentChunkerVersion = chunkerStamp();const issues: string[] = [];let ownedContent = new Set<string>();diff --git a/src/commands/sync/finalize.ts b/src/commands/sync/finalize.tsindex 6660d34136..fff6159637 100644--- a/src/commands/sync/finalize.ts+++ b/src/commands/sync/finalize.ts@@ -4,7 +4,7 @@* gate, the shared failure-ledger bookmark gate, and the post-advance* extract / facts / embed passes.*/-import { CHUNKER_VERSION } from '../../core/chunkers/code.ts';+import { chunkerStamp } from '../../core/chunkers/code.ts';import { serr, slog } from '../../core/console-prefix.ts';import type { BrainEngine } from '../../core/engine.ts';import { clearOpCheckpoint } from '../../core/op-checkpoint.ts';@@ -67,7 +67,7 @@ export async function finishWithoutChanges(// completes cleanly here).await writeSyncAnchor(engine, opts.sourceId, 'last_commit', pin, commitTimeMs(gitContextRoot, pin), gitContextRoot);await engine.setConfig('sync.last_run', new Date().toISOString());- await writeChunkerVersion(engine, opts.sourceId, String(CHUNKER_VERSION));+ await writeChunkerVersion(engine, opts.sourceId, chunkerStamp());if (!company) { await clearOpCheckpoint(engine, ckpt.paths); await clearOpCheckpoint(engine, ckpt.target); }// A commit whose ONLY changes are malformed filenames lands here with// totalChanges === 0 — the anchor advances past those files forever, so@@ -291,7 +291,7 @@ async function applyBookmarkGate(await writeSyncAnchor(engine, opts.sourceId, 'last_commit', pin, commitTimeMs(gitContextRoot, pin), gitContextRoot);await engine.setConfig('sync.last_run', new Date().toISOString());await writeSyncAnchor(engine, opts.sourceId, 'repo_path', anchorPath);- await writeChunkerVersion(engine, opts.sourceId, String(CHUNKER_VERSION));+ await writeChunkerVersion(engine, opts.sourceId, chunkerStamp());if (!company) { await clearOpCheckpoint(engine, ckpt.paths); await clearOpCheckpoint(engine, ckpt.target); }};diff --git a/src/commands/sync/full.ts b/src/commands/sync/full.tsindex 3a683357f2..08f3678b75 100644--- a/src/commands/sync/full.ts+++ b/src/commands/sync/full.ts@@ -23,7 +23,7 @@ import {DEFAULT_SOURCE_ID,RENAME_SENTINEL_PREFIX,} from '../../core/sync.ts';-import { CHUNKER_VERSION } from '../../core/chunkers/code.ts';+import { chunkerStamp } from '../../core/chunkers/code.ts';import { autoConcurrency } from '../../core/sync-concurrency.ts';import { slog, serr } from '../../core/console-prefix.ts';import { newestCommitMs } from '../../core/source-health.ts';@@ -160,7 +160,7 @@ export async function performFullSync(await writeSyncAnchor(engine, opts.sourceId, 'last_commit', headCommit, newestCommitMs(gitContextRoot), gitContextRoot);await engine.setConfig('sync.last_run', new Date().toISOString());await writeSyncAnchor(engine, opts.sourceId, 'repo_path', anchorPath);- await writeChunkerVersion(engine, opts.sourceId, String(CHUNKER_VERSION));+ await writeChunkerVersion(engine, opts.sourceId, chunkerStamp());};const fullGate = await applySyncFailureGate({diff --git a/src/commands/sync/preflight.ts b/src/commands/sync/preflight.tsindex e1c9db656c..8ce9eadc8c 100644--- a/src/commands/sync/preflight.ts+++ b/src/commands/sync/preflight.ts@@ -8,7 +8,7 @@*/import { existsSync, realpathSync } from 'fs';import { resolve as pathResolve, join } from 'path';-import { CHUNKER_VERSION } from '../../core/chunkers/code.ts';+import { chunkerStamp } from '../../core/chunkers/code.ts';import { currentCompanyBrainSync } from '../../core/company-brain/profile.ts';import { serr, slog } from '../../core/console-prefix.ts';import type { BrainEngine } from '../../core/engine.ts';@@ -837,7 +837,7 @@ async function resolveWorkingTreeScope(// population, etc.). Without this, upgraded brains silently stay on// the old chunks — the whole reason we bumped the version.const storedVersion = await readChunkerVersion(engine, opts.sourceId);- const currentVersion = String(CHUNKER_VERSION);+ const currentVersion = chunkerStamp();const versionMismatch = storedVersion !== null && storedVersion !== currentVersion;const versionNeverSet = storedVersion === null && opts.sourceId !== undefined;// Untracked-gap fix: the working-tree manifest is now built for attacheddiff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex acd25034b5..1390e20ceb 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -350,6 +350,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }// Budgeted delivery PR 1. `since` equals the branch's VERSION; the integrator sets it to the merge-slot stamp by hand (release:restamp does not rewrite this table).{ since: '0.60.124.0', text: 'A token budget passed under `auto` evidence delivery (`token_budget` on query, search and assemble_evidence, `budget_tokens` on recall with `return_unit: "auto"`) is now a hard cap on the delivered titles and evidence: the best hit comes first, and conversations or notes that do not fit are listed in `delivery.dropped_reasons` instead of being appended as extra chunks. A budget below 32 tokens is refused with `invalid_params`. Calls without a budget, and a bare query `token_budget` (legacy chunk budgeting), are unchanged. `gbrain config set search.auto_packing off` restores the uncapped behavior.' },{ since: '0.60.126.0', text: '`context_pack` cards now list the newest pages that mention each entity and are dated after the entity\'s own page (up to 8 per card, 2,000 characters per card and 6,000 per pack, each with its date, slug, title and preview), so a later mail or note that corrects the page reaches the agent on its first call. A remote caller never sees a private page or another source there, and the section packs last under `budget_tokens`. `gbrain config set mentions.newer_on_cards false` turns it off.' },+ // Lua grammar replacement (GBRA-64, from GBRA-49's serve-hang report); `since` is a placeholder until the merge-slot stamp.+ { since: '0.60.132.0', text: 'Lua code (`.lua` files and ```lua fences) now parses with tree-sitter-grammars/tree-sitter-lua v0.3.0: every parse is sound (the previous grammar started each parse after the first from uninitialized scanner state, misparsing or spinning until the 30 s chunker timeout, which left `gbrain serve` unresponsive on a page of mislabelled shell fences), and `function` / `local function` / `function M.f()` definitions become named semantic chunks for the first time. On the next sync each source is walked once and only its `.lua` files re-chunk and re-embed (priced by the cost gate as `grammar_drift`); other code pages keep their chunks. `gbrain sync --source <id> --full` also refreshes Lua fences inside already indexed Markdown pages.' },{ since: '0.60.131.0', text: 'Vector search scoped to a source that holds a small part of the brain now returns its true nearest chunks: a source with up to about 25,000 chunks is scanned exactly instead of through the HNSW index, and a larger one falls back to that scan when the index comes back short. Unscoped search is unchanged; scoped results can differ from earlier releases where the index had missed closer matches.' },];diff --git a/src/core/chunkers/code.ts b/src/core/chunkers/code.tsindex 7bda4e454c..1012bbf347 100644--- a/src/core/chunkers/code.ts+++ b/src/core/chunkers/code.ts@@ -142,6 +142,16 @@ import G_ZIG from '../../assets/wasm/grammars/tree-sitter-zig.wasm' with { type:// erased symbols.// 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).+ * 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.+ */+export const GRAMMAR_REVISIONS: Partial<Record<SupportedCodeLanguage, number>> = { lua: 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(';');// Lazy-loaded tree-sitter module (v0.22.x API: Parser is default export)let Parser: typeof import('web-tree-sitter') | null = null;diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex e254d49691..f88a8f9174 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -18,7 +18,7 @@ import type { FenceFix } from './fence-repair/types.ts';import { classifyStoredType } from './schema-pack/type-usage.ts';import { prepareMarkdownChunks } from './markdown-chunks.ts';import { prepareCodeChunks, installCodeChunkEdges } from './code-chunks.ts';-import { detectCodeLanguage, CHUNKER_VERSION } from './chunkers/code.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, embeddingWriteTarget, embeddingInputContext, type ProjectionSnapshot } from './page-state/projections.ts';@@ -1348,9 +1348,12 @@ export async function importCodeFile(});// Hash for idempotency. CHUNKER_VERSION is folded in so chunker shape- // changes across releases force clean re-chunks without a forced re-import.+ // changes across releases force clean re-chunks without a forced re-import;+ // a language's grammar revision is folded in for that language only, so a+ // grammar swap re-chunks its own files and leaves every other hash alone.+ const grammarRevision = GRAMMAR_REVISIONS[lang as SupportedCodeLanguage];const hash = createHash('sha256')- .update(JSON.stringify({ title, type: 'code', content, lang, chunker_version: CHUNKER_VERSION }))+ .update(JSON.stringify({ title, type: 'code', content, lang, chunker_version: CHUNKER_VERSION, ...(grammarRevision ? { grammar_revision: grammarRevision } : {}) })).digest('hex');// Scoped to the exact (source_id, slug) row the writes below target —diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex 9d9409fe4c..c7f44db323 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -37,7 +37,7 @@ import { companyBrainPolicyFingerprint } from '../company-brain/policy.ts';import { isUnboundSourcePage, UNBOUND_COLLISION_MESSAGE } from './unbound-source.ts';import { checkpointRetryCommand, findIncompleteSyncReceipt } from './checkpoint-validation.ts';import { frontmatterSlugConflictMessage } from './verb-errors.ts';-import { CHUNKER_VERSION } from '../chunkers/code.ts';+import { chunkerStamp } from '../chunkers/code.ts';import { clearGitHold, countGitHolds, recordSyncImportProvenance } from './sync-holds.ts';import { fenceWhere } from '../fence-repair/refusal.ts';import { fencesNormalizeEnabled } from '../fence-repair/config.ts';@@ -397,7 +397,7 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wrif (!changed.length) throw syncPublicationRefusal('revision_conflict', 'The source checkpoint changed during this sync.', row, p,`Another sync moved the commit checkpoint of ${row.source_id} while this run published.`);// #5566: a full walk re-chunked every stale page, so acknowledge the chunker version as the legacy gate does.- if (p.from === null || p.syncOptions?.full === true) await tx.executeRaw('UPDATE sources SET chunker_version=$2 WHERE id=$1', [row.source_id, String(CHUNKER_VERSION)]);+ if (p.from === null || p.syncOptions?.full === true) await tx.executeRaw('UPDATE sources SET chunker_version=$2 WHERE id=$1', [row.source_id, chunkerStamp()]);await tx.executeRaw("UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,done}','true'::jsonb),updated_at=now() WHERE op='managed-sync' AND fingerprint=$1", [p.cursorKey]);for (const path of p.releasedHolds ?? []) await releaseHold(tx, path);return { status: 'synced', source_id: row.source_id, committed_pages: p.total };diff --git a/src/core/sync-cost-gate.ts b/src/core/sync-cost-gate.tsindex e1dd89b540..7131381f1e 100644--- a/src/core/sync-cost-gate.ts+++ b/src/core/sync-cost-gate.ts@@ -22,7 +22,7 @@ import {formatUsdLimit,resolveSpendPosture,} from './spend-posture.ts';-import { estimateTokens, CHUNKER_VERSION } from './chunkers/code.ts';+import { estimateTokens, chunkerStamp, detectCodeLanguage } from './chunkers/code.ts';import {estimateEmbeddingCostUsd,getEmbeddingModelName,@@ -77,6 +77,39 @@ export function estimateSourceTreeTokens(return { tokens, files };}+/**+ * The languages whose grammar revision differs between a stored chunker stamp and+ * the current one, when CHUNKER_VERSION itself is unchanged; null when the drift+ * is the version (every code page re-chunks) or the stamp is unreadable.+ */+export function grammarOnlyDrift(stored: string | null, current: string): Set<string> | null {+ if (stored === null) return null;+ const parse = (stamp: string) => { const [version, ...revs] = stamp.split(';'); return { version, revs: new Map(revs.map(r => r.split('=') as [string, string])) }; };+ const a = parse(stored), b = parse(current);+ if (a.version !== b.version) return null;+ const langs = new Set<string>();+ for (const [lang, rev] of b.revs) if (a.revs.get(lang) !== rev) langs.add(lang);+ for (const lang of a.revs.keys()) if (!b.revs.has(lang)) langs.add(lang);+ return langs;+}++/** Tokens of the source's files in the given languages only (a grammar-revision drift re-chunks nothing else). */+function estimateLanguageTokens(localPath: string, strategy: 'markdown' | 'code' | 'auto', languages: Set<string>): { tokens: number; files: number } {+ let tokens = 0, files = 0;+ try {+ for (const fullPath of collectSyncableFiles(localPath, { strategy })) {+ const lang = detectCodeLanguage(fullPath);+ if (!lang || !languages.has(lang)) continue;+ try {+ if (statSync(fullPath).size > 5_000_000) continue;+ tokens += estimateTokens(readFileSync(fullPath, 'utf-8'));+ files++;+ } catch { /* best-effort per file, as the tree walk */ }+ }+ } catch { /* best-effort: an unreadable source contributes 0 */ }+ return { tokens, files };+}+/** Sum tokens for an explicit set of repo-relative paths read at live working-tree content. */function estimateDeltaTokens(localPath: string, relPaths: string[]): number {let tokens = 0;@@ -156,7 +189,7 @@ export interface InlineEstimate {changedSources: number;unchangedSources: number;estimateKind: EstimateKind;- /** Per-source ceiling reasons (chunker_drift / first_sync / git_unavailable) for honest labeling. */+ /** Per-source ceiling reasons (chunker_drift / grammar_drift / first_sync / git_unavailable) for honest labeling. */ceilingReasons: string[];}@@ -169,6 +202,9 @@ export interface InlineEstimate {* 2. chunker drift (stored !== current) → full-tree CEILING (a drift forces* performFullSync → full re-chunk → full re-embed; a delta would* underestimate by the whole corpus). kind: ceiling_chunker_drift+ * A drift in a language's grammar revision alone (`GRAMMAR_REVISIONS`,+ * CHUNKER_VERSION unchanged) prices only that language's files: the+ * walk re-imports nothing else. kind: ceiling_grammar_drift* 3. last_commit === fetch target → 0 (mirrors `up_to_date` at* sync.ts:1402 — NO clean-working-tree requirement; a dirty tree whose* commits are caught up imports nothing). kind: unchanged@@ -224,7 +260,17 @@ export function estimateInlineNewTokens(}// Rung 2: chunker drift forces a full re-chunk → full re-embed. CEILING.+ // A drift in grammar revisions alone re-chunks only those languages' files:+ // the walk compares hashes and every other file's hash is unchanged.if (src.chunker_version !== currentChunkerVersion) {+ const languages = grammarOnlyDrift(src.chunker_version, currentChunkerVersion);+ if (languages) {+ tokens += estimateLanguageTokens(localPath, strategy, languages).tokens;+ changedSources++;+ hadCeiling = true;+ ceilingReasons.push('grammar_drift');+ continue;+ }ceiling(localPath, strategy, 'chunker_drift');continue;}@@ -498,7 +544,7 @@ export async function runInlineCostGate(}// ── Inline path ───────────────────────────────────────────────- const inline = estimateInlineNewTokens(sources, String(CHUNKER_VERSION), {+ const inline = estimateInlineNewTokens(sources, chunkerStamp(), {forceFullTree: ctx.includeGitignored === true,});// D7A: `--full` runs `performFullSync` → `runEmbedCore({stale:true})`, whichdiff --git a/test/chunkers/code-lua.test.ts b/test/chunkers/code-lua.test.tsnew file mode 100644index 0000000000..af4dc24bfe--- /dev/null+++ b/test/chunkers/code-lua.test.ts@@ -0,0 +1,138 @@+/**+ * The `gbrain serve` hang GBRA-49's LongMemEval scoreboard hit on 0.60.106.0 (PGLite, 99.5% CPU for 9.5 h after a+ * committed put_page, stdin never read again). The page held five ChatGPT-style ```lua fences around shell commands.+ * The vendored Lua grammar (the `tree-sitter-wasms` build of Azganoth/tree-sitter-lua 2.1.3) allocated its external+ * scanner state with `malloc` and reset it only when `deserialize` was handed two bytes, so every parse after the first+ * in a process started from recycled heap: `x = 1` misparsed as an error, and the fence texts spun until the chunker's+ * 30 s timeout, five times per preparation attempt, with the event loop blocked throughout. The grammar is now+ * tree-sitter-grammars/tree-sitter-lua v0.3.0 (ABI 14), whose scanner uses `calloc` and resets on every parse.+ *+ * Forced probes: against the previous grammar, the repeated parse comes back with an ERROR root, the fence set takes+ * longer than the short timeout this test pins, and no Lua definition ever becomes a semantic chunk.+ *+ * The grammar swap re-chunks Lua files only: `GRAMMAR_REVISIONS.lua` is folded into Lua code-file hashes and into the+ * `sources.chunker_version` stamp, CHUNKER_VERSION stays 8, and the sync cost gate prices a grammar-only drift by the+ * affected language's files instead of the whole tree.+ */+import { describe, expect, test } from 'bun:test';+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import Parser from 'web-tree-sitter';+import { CHUNKER_VERSION, chunkCodeText, chunkCodeTextFull, chunkerStamp, GRAMMAR_REVISIONS } from '../../src/core/chunkers/code.ts';+import { prepareMarkdownChunks } from '../../src/core/markdown-chunks.ts';+import { estimateInlineNewTokens, grammarOnlyDrift } from '../../src/core/sync-cost-gate.ts';+import { withEnv } from '../helpers/with-env.ts';++const assets = join(import.meta.dir, '../../src/assets/wasm');+const source = `-- header comment+local M = {}+local function helper(a, b)+ return a + b+end+function M.add(x, y)+ return helper(x, y)+end+function M:method()+ return self+end+local s = [==[+long string with ]] inside+]==]+--[[ long+comment ]]+return M+`;+/** The stuck page's fences in order: shell commands a chat model labelled as Lua. */+const fences = ['sudo aa-status', 'sudo snap debug sandbox-features discord', 'sudo snap debug sandbox-features discord.discord',+ 'sudo aa-status | grep snap.discord.discord', 'sudo aa-status | grep snap.discord.discord'];+/** A short per-fence parse timeout keeps the failing run of these probes bounded (production: 30 s). */+const SHORT_TIMEOUT = { GBRAIN_CHUNKER_TIMEOUT_MS: '1500' };++describe('Lua grammar: sound across parses, no spin on mislabelled shell fences', () => {+ test('the vendored grammar is the ABI-14 release and has no unresolved normal-path libc imports', async () => {+ const runtime = await WebAssembly.compile(readFileSync(join(assets, 'tree-sitter.wasm')));+ const exports = new Set(WebAssembly.Module.exports(runtime).map(e => e.name));+ const grammar = await WebAssembly.compile(readFileSync(join(assets, 'grammars/tree-sitter-lua.wasm')));+ const missing = WebAssembly.Module.imports(grammar).filter(i => i.module === 'env' && i.kind === 'function' && !exports.has(i.name) && !exports.has('_' + i.name));+ expect(missing.map(i => i.name)).toEqual([]);+ await Parser.init({ locateFile: () => join(assets, 'tree-sitter.wasm') });+ const language = await Parser.Language.load(join(assets, 'grammars/tree-sitter-lua.wasm'));+ expect(language.version).toBe(14);+ });++ test('forced probe: the same text parses the same way on every parser instance, not only the first in the process', async () => {+ await Parser.init({ locateFile: () => join(assets, 'tree-sitter.wasm') });+ const language = await Parser.Language.load(join(assets, 'grammars/tree-sitter-lua.wasm'));+ const trees: string[] = [];+ for (let i = 0; i < 4; i++) {+ const parser = new Parser();+ try {+ parser.setLanguage(language);+ const tree = parser.parse('x = 1');+ try { trees.push(tree.rootNode.toString()); expect(tree.rootNode.hasError).toBe(false); } finally { tree.delete(); }+ } finally { parser.delete(); }+ }+ expect(new Set(trees).size).toBe(1);+ });++ test('forced probe: the stuck page\'s five Lua fences chunk in well under one timeout each', () => withEnv(SHORT_TIMEOUT, async () => {+ const started = performance.now();+ for (const fence of fences) {+ const chunks = await chunkCodeText(fence, 'fence.lua');+ expect(chunks.length).toBeGreaterThanOrEqual(1);+ }+ // Before the fix three of the five fences each ran to the 1.5 s timeout pinned here (30 s in production).+ expect(performance.now() - started).toBeLessThan(1_000);+ }));++ test('a conversation page with the mislabelled fences prepares in one short pass', () => withEnv(SHORT_TIMEOUT, async () => {+ const page = fences.map((fence, i) => `Step ${i + 1}:\n\`\`\`lua\n${fence}\n\`\`\``).join('\n');+ const started = performance.now();+ const chunks = await prepareMarkdownChunks({ compiled_truth: page });+ expect(performance.now() - started).toBeLessThan(1_000);+ expect(chunks.filter(c => c.chunk_source === 'fenced_code')).toHaveLength(fences.length);+ }));++ test('Lua definitions become semantic chunks (function, method and local function), repeatedly', async () => {+ for (let i = 0; i < 2; i++) {+ const { chunks } = await chunkCodeTextFull(source, 'module.lua');+ const names = chunks.map(c => c.metadata.symbolName);+ expect(names).toEqual(['helper', 'M.add', 'M:method']);+ expect(chunks.every(c => c.metadata.symbolType === 'function' && c.metadata.language === 'lua')).toBe(true);+ expect(chunks.find(c => c.metadata.symbolName === 'helper')?.text).toContain('return a + b');+ }+ });+});++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');+ });++ test('grammarOnlyDrift names the languages whose revision moved, and nothing on a version bump or a fresh source', () => {+ expect(grammarOnlyDrift('8', '8;lua=1')).toEqual(new Set(['lua']));+ expect(grammarOnlyDrift('8;lua=1', '8;lua=1')).toEqual(new Set());+ expect(grammarOnlyDrift('8;lua=1', '8;lua=2;zig=1')).toEqual(new Set(['lua', 'zig']));+ expect(grammarOnlyDrift('7', '8;lua=1')).toBeNull();+ expect(grammarOnlyDrift(null, '8;lua=1')).toBeNull();+ });++ test('the sync cost gate prices a grammar-only drift by the affected language\'s files, not the whole tree', () => {+ const repo = mkdtempSync(join(tmpdir(), 'gbrain-lua-drift-'));+ try {+ mkdirSync(join(repo, 'src'));+ writeFileSync(join(repo, 'src/big.ts'), `export const words = ${JSON.stringify('lorem ipsum '.repeat(2000))};\n`);+ writeFileSync(join(repo, 'src/init.lua'), source);+ const sources = [{ local_path: repo, config: { strategy: 'code' as const }, last_commit: null, chunker_version: '8' }];+ const grammar = estimateInlineNewTokens(sources, '8;lua=1');+ const version = estimateInlineNewTokens(sources, '9');+ expect(grammar.ceilingReasons).toEqual(['grammar_drift']);+ expect(version.ceilingReasons).toEqual(['chunker_drift']);+ expect(grammar.tokens).toBeGreaterThan(0);+ expect(grammar.tokens).toBeLessThan(version.tokens / 10);+ } finally { rmSync(repo, { recursive: true, force: true }); }+ });+});