Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(chunker): const arrow/function-expression definitions keep their named chunk (N13-1)
garrytan02b0d0f457ec
diff --git a/src/core/chunkers/code.ts b/src/core/chunkers/code.tsindex 6a80b359a6..6bdf77c562 100644--- a/src/core/chunkers/code.ts+++ b/src/core/chunkers/code.ts@@ -140,7 +140,12 @@ import G_ZIG from '../../assets/wasm/grammars/tree-sitter-zig.wasm' with { type:// top-level defs indexed to ZERO symbols). Chunk boundaries change for every// previously-merged file, so the bump forces a re-chunk that recovers the// erased symbols.-export const CHUNKER_VERSION = 7;+//+// v8 (gbrain-evals N13-1): short `const f = () => …` / `let g = function …`+// definitions no longer fold into anonymous merged chunks (code-def missed 9+// of 50 pathe functions). The bump re-chunks files whose merged runs held+// function-valued declarations.+export const CHUNKER_VERSION = 8;// Lazy-loaded tree-sitter module (v0.22.x API: Parser is default export)let Parser: typeof import('web-tree-sitter') | null = null;@@ -184,6 +189,13 @@ export interface CodeChunkMetadata {* Null when symbolName is missing (merged chunks, module-level fallback).*/symbolNameQualified?: string | null;+ /**+ * gbrain-evals N13-1: set on a const/let/var declaration whose value is a+ * function (`const f = () => …`, `let g = function () {…}`). Its symbol+ * type is a mergeable run form, but it is a named function definition, so+ * mergeSmallSiblings must keep it (and its symbol_name) on its own chunk.+ */+ definesFunction?: boolean;}export interface CodeChunk {@@ -835,13 +847,15 @@ async function chunkParsedLanguage(}if (estimateTokens(nodeText) <= largeThreshold) {- chunks.push(buildChunk({+ const chunk = buildChunk({body: nodeText, filePath, language, symbolName, symbolType,startLine: node.startPosition.row + 1,endLine: endNode.endPosition.row + 1,index: chunks.length,parentSymbolPath: [],- }));+ });+ if (declaresFunctionValue(typeNode)) chunk.metadata.definesFunction = true;+ chunks.push(chunk);continue;}@@ -947,7 +961,8 @@ 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 && MERGE_PROTECTED_SYMBOL_TYPES.has(c.metadata.symbolType);+ c.metadata.symbolName != null &&+ (MERGE_PROTECTED_SYMBOL_TYPES.has(c.metadata.symbolType) || c.metadata.definesFunction === true);const merged: CodeChunk[] = [];let i = 0;while (i < chunks.length) {@@ -1458,6 +1473,20 @@ function extractSymbolName(node: any): string | null {return null;}+const FUNCTION_VALUE_TYPES = new Set(['arrow_function', 'function_expression', 'function', 'generator_function']);++/**+ * N13-1: a TS/JS `lexical_declaration` / `variable_declaration` whose+ * declarator value is a function — a named function definition wearing a+ * mergeable run type (see CodeChunkMetadata.definesFunction).+ */+function declaresFunctionValue(node: any): boolean {+ if (node.type !== 'lexical_declaration' && node.type !== 'variable_declaration') return false;+ return node.namedChildren.some(+ (child: any) => child.type === 'variable_declarator' && FUNCTION_VALUE_TYPES.has(child.childForFieldName('value')?.type),+ );+}+// See the wrapper dive in extractSymbolName (#3789).const NAME_WRAPPER_TYPES = new Set(['variable_declaration', 'variable_declarator', 'init_declarator',diff --git a/test/chunker-version-gate.test.ts b/test/chunker-version-gate.test.tsindex 75d9a10792..8ef52e2c35 100644--- a/test/chunker-version-gate.test.ts+++ b/test/chunker-version-gate.test.ts@@ -15,7 +15,7 @@ import { describe, test, expect } from 'bun:test';import { CHUNKER_VERSION } from '../src/core/chunkers/code.ts';describe('Layer 12 — CHUNKER_VERSION constant', () => {- test('bumped to 7 for the compatible Bash grammar (#5082)', () => {+ test('bumped to 8 for function-valued declarations (N13-1, after #5082 at 7)', () => {// v3: v0.19.0 Chonkie parity (tokenizer + small-sibling merge).// v4: v0.20.0 Cathedral II (qualified names + parent scope + doc_comment// + fence extraction + chunk-grain FTS). Folded into content_hash@@ -25,14 +25,16 @@ describe('Layer 12 — CHUNKER_VERSION constant', () => {// v6: #4511 mergeSmallSiblings stopped erasing symbol_name on short// definitions; the bump re-chunks previously-merged files so the// lost symbols come back.- expect(CHUNKER_VERSION).toBe(7);+ // v7: #5082 compatible Bash grammar.+ // v8: N13-1 `const f = () => …` definitions keep their own named chunk.+ expect(CHUNKER_VERSION).toBe(8);});test('is stable across imports (not recomputed at call time)', async () => {const a = (await import('../src/core/chunkers/code.ts')).CHUNKER_VERSION;const b = (await import('../src/core/chunkers/code.ts')).CHUNKER_VERSION;expect(a).toBe(b);- expect(a).toBe(7);+ expect(a).toBe(8);});});diff --git a/test/chunkers/code-merge-defs.test.ts b/test/chunkers/code-merge-defs.test.tsindex f9b7fad1e4..ecba680983 100644--- a/test/chunkers/code-merge-defs.test.ts+++ b/test/chunkers/code-merge-defs.test.ts@@ -66,6 +66,30 @@ describe('#4511 — short flat definitions keep their symbol names', () => {expect(named[0]!.metadata.symbolType).toBe('function');});+ // gbrain-evals N13-1: `const name = (...) => ...` is a named function+ // definition even though its node is a lexical declaration (a mergeable+ // run form). 9 of 50 pathe functions were folded into nameless chunks.+ test('typescript: short const arrow functions keep their names (N13-1)', async () => {+ const src = [+ 'const ALPHABET = "abcdefghijklmnopqrstuvwxyz";', '',+ 'const int2alpha = (int: number): string => {', ' let alpha = "";', ' while (int > 0) {', ' alpha = ALPHABET[(int - 1) % 26] + alpha;', ' int = Math.floor((int - 1) / 26);', ' }', ' return alpha;', '};', '',+ 'const alpha2int = (str: string): number => {', ' let int = 0;', ' for (const char of str) int = int * 26 + ALPHABET.indexOf(char) + 1;', ' return int;', '};', '',+ 'let legacy = function (v: number) { return v; };', '',+ 'export function roundTrip(n: number): number {', ' return alpha2int(int2alpha(n));', '}', '',+ ].join('\n');+ const chunks = await chunkCodeText(src, 'sample.ts');+ const names = chunks.map((c) => c.metadata.symbolName);+ expect(names).toEqual(expect.arrayContaining(['int2alpha', 'alpha2int', 'legacy', 'roundTrip']));+ expect(chunks.some((c) => c.metadata.symbolType === 'merged' && /int2alpha =|alpha2int =|legacy =/.test(c.text))).toBe(false);+ });++ test('javascript: const value runs still merge (only function values are protected)', async () => {+ const src = Array.from({ length: 6 }, (_, i) => `const K${i} = ${i};`).join('\n') + '\n';+ const chunks = await chunkCodeText(src, 'consts.js');+ expect(chunks).toHaveLength(1);+ expect(chunks[0]!.metadata.symbolType).toBe('merged');+ });+test('import runs still merge (the pass keeps its stated purpose)', async () => {const src = Array.from({ length: 8 }, (_, i) => `import mod_${i}`).join('\n') + '\n';const chunks = await chunkCodeText(src, 'imports.py');@@ -77,6 +101,10 @@ describe('#4511 — short flat definitions keep their symbol names', () => {expect(CHUNKER_VERSION).toBeGreaterThanOrEqual(6);});+ test('CHUNKER_VERSION bumped to 8 so files with merged arrow functions re-chunk (N13-1)', () => {+ expect(CHUNKER_VERSION).toBeGreaterThanOrEqual(8);+ });+test('merge guard is a derived view of code-def DEF_TYPES (single shared list)', () => {// Same array object via both import paths — not a hand-copied duplicate.expect(DEF_TYPES_VIA_CODE_DEF).toBe(DEF_TYPES);diff --git a/test/chunkers/code.test.ts b/test/chunkers/code.test.tsindex 2ef4d541cf..05c27cbdcb 100644--- a/test/chunkers/code.test.ts+++ b/test/chunkers/code.test.ts@@ -10,8 +10,8 @@ import { describe, test, expect } from 'bun:test';import { chunkCodeText, detectCodeLanguage, CHUNKER_VERSION } from '../../src/core/chunkers/code.ts';describe('CHUNKER_VERSION', () => {- test('#5082 Bash grammar refresh bumped to 7', () => {- expect(CHUNKER_VERSION).toBe(7);+ test('N13-1 function-valued declarations bumped to 8 (after #5082 Bash grammar refresh at 7)', () => {+ expect(CHUNKER_VERSION).toBe(8);});});