onbuzz 4.8.1 → 4.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -34,6 +34,147 @@ describe('ConversationCompactionService', () => {
34
34
  expect(service.compactionModelIndex).toBe(0);
35
35
  });
36
36
 
37
+ // ─── Compaction-input pre-tagging ─────────────────────────────────────
38
+ //
39
+ // The summarizer is fed PRE-TAGGED messages so it doesn't have to
40
+ // guess whether a `role: user` message is a real user typing or a
41
+ // tool-result wrapper. We pin the tagging rules here.
42
+
43
+ describe('_categorizeMessage — input pre-tagging', () => {
44
+ test('assistant role → AGENT', () => {
45
+ expect(service._categorizeMessage({ role: 'assistant', content: 'hi' })).toBe('AGENT');
46
+ });
47
+
48
+ test('system role → SYSTEM', () => {
49
+ expect(service._categorizeMessage({ role: 'system', content: 'note' })).toBe('SYSTEM');
50
+ });
51
+
52
+ test('user role with plain content → REAL_USER', () => {
53
+ expect(service._categorizeMessage({ role: 'user', content: 'please fix the board' })).toBe('REAL_USER');
54
+ });
55
+
56
+ test('user role with [Tool Results …] prefix → TOOL_RESULT', () => {
57
+ expect(service._categorizeMessage({
58
+ role: 'user',
59
+ content: '[Tool Results — 1 result] [filesystem] {...}',
60
+ })).toBe('TOOL_RESULT');
61
+ });
62
+
63
+ test('user role with [Previous Task …] prefix → PREVIOUS_TASK', () => {
64
+ expect(service._categorizeMessage({
65
+ role: 'user',
66
+ content: '[Previous Task — Final Tool Results] [jobdone] {...}',
67
+ })).toBe('PREVIOUS_TASK');
68
+ });
69
+
70
+ test('REGRESSION: leading whitespace before [Tool Results doesn\'t fool the categorizer', () => {
71
+ expect(service._categorizeMessage({
72
+ role: 'user',
73
+ content: '\n [Tool Results — 1] {}',
74
+ })).toBe('TOOL_RESULT');
75
+ });
76
+
77
+ test('non-string content (rare) is treated as REAL_USER (defensive)', () => {
78
+ // If content somehow isn't a string, we can't sniff the prefix —
79
+ // safest fallback is to treat it as a real user message so it
80
+ // surfaces in PASS 1 rather than being silently dropped.
81
+ expect(service._categorizeMessage({ role: 'user', content: { foo: 1 } })).toBe('REAL_USER');
82
+ });
83
+ });
84
+
85
+ // ─── Summary prompt contract — anti-lossy-compaction guard ────────────
86
+ //
87
+ // History: an earlier prompt told the summarizer to paraphrase user
88
+ // requests "under HIGH PRIORITY". The Talisman case study (May 2026)
89
+ // showed that paraphrasing alone caused the agent to lose track of
90
+ // literal user asks → off-track work (building a Settings screen
91
+ // nobody asked for). Then a verbatim-everything prompt fixed that
92
+ // half but ate the agent-side narrative — PASS 2 never reached.
93
+ // The final prompt (3-pass, pre-tagged input, EVENT LOG + STATE)
94
+ // was validated across 3 models × 7 variants. These tests pin it.
95
+
96
+ describe('_createSummaryPromptTemplate — three-pass contract', () => {
97
+ test('includes the {middle_segment} placeholder for interpolation', () => {
98
+ const tpl = service._createSummaryPromptTemplate();
99
+ expect(tpl).toContain('{middle_segment}');
100
+ });
101
+
102
+ test('declares the pre-tagging categories the summarizer can trust', () => {
103
+ // The prompt must list every category the categorizer emits, so
104
+ // the summarizer doesn't fall back to guessing from content.
105
+ const tpl = service._createSummaryPromptTemplate();
106
+ expect(tpl).toContain('[REAL_USER]');
107
+ expect(tpl).toContain('[TOOL_RESULT]');
108
+ expect(tpl).toContain('[PREVIOUS_TASK]');
109
+ expect(tpl).toContain('[AGENT]');
110
+ expect(tpl).toContain('[SYSTEM]');
111
+ });
112
+
113
+ test('mandates VERBATIM user-message transcription, NOT paraphrase', () => {
114
+ const tpl = service._createSummaryPromptTemplate();
115
+ expect(tpl).toMatch(/word[\s,-]?for[\s,-]?word/i);
116
+ expect(tpl).toMatch(/transcription/i);
117
+ expect(tpl).toMatch(/(do not|don't|never).*(paraphras|condens|omit)/i);
118
+ });
119
+
120
+ test('uses a 3-pass shape: USER VOICE → EVENT LOG → STATE NARRATIVE', () => {
121
+ const tpl = service._createSummaryPromptTemplate();
122
+ const userIdx = tpl.indexOf('USER VOICE');
123
+ const eventIdx = tpl.indexOf('EVENT LOG');
124
+ const stateIdx = tpl.indexOf('STATE NARRATIVE');
125
+ expect(userIdx).toBeGreaterThan(-1);
126
+ expect(eventIdx).toBeGreaterThan(-1);
127
+ expect(stateIdx).toBeGreaterThan(-1);
128
+ // User voice first, then event log, then narrative.
129
+ expect(userIdx).toBeLessThan(eventIdx);
130
+ expect(eventIdx).toBeLessThan(stateIdx);
131
+ });
132
+
133
+ test('PASS 1 forbids quoting non-REAL_USER tagged messages', () => {
134
+ // The most common failure mode in early experiments was the
135
+ // summarizer quoting tool-result wrappers as if they were user
136
+ // messages. The prompt explicitly forbids this.
137
+ const tpl = service._createSummaryPromptTemplate();
138
+ expect(tpl).toMatch(/only \[REAL_USER\] messages/i);
139
+ // And lists the categories it must NOT quote.
140
+ expect(tpl).toMatch(/do not quote.*\[TOOL_RESULT\]/i);
141
+ });
142
+
143
+ test('PASS 2 demands concrete details (file paths, tool names, line numbers)', () => {
144
+ const tpl = service._createSummaryPromptTemplate();
145
+ expect(tpl).toMatch(/file path/i);
146
+ expect(tpl).toMatch(/tool name/i);
147
+ expect(tpl).toMatch(/line number/i);
148
+ });
149
+
150
+ test('PASS 3 must explicitly map back to [REAL_USER] requests', () => {
151
+ // The Talisman bug was the agent doing work UNRELATED to the
152
+ // user's requests. PASS 3 must surface that misalignment when
153
+ // it exists — the prompt requires "name the gaps clearly".
154
+ const tpl = service._createSummaryPromptTemplate();
155
+ expect(tpl).toMatch(/map back/i);
156
+ expect(tpl).toMatch(/name the gaps/i);
157
+ });
158
+
159
+ test('forbids skipping a [REAL_USER] message on "already addressed" reasoning', () => {
160
+ const tpl = service._createSummaryPromptTemplate();
161
+ expect(tpl).toMatch(/(do not|don't|never).*skip.*\[?REAL_USER\]?/i);
162
+ expect(tpl).toMatch(/already addressed/i);
163
+ });
164
+
165
+ test('output contract: no preamble, exact headers', () => {
166
+ const tpl = service._createSummaryPromptTemplate();
167
+ expect(tpl).toMatch(/no preamble/i);
168
+ expect(tpl).toMatch(/exactly the section headers above/i);
169
+ });
170
+
171
+ test('REGRESSION: does NOT carry forward the lossy "HIGH PRIORITY paraphrase" guidance', () => {
172
+ const tpl = service._createSummaryPromptTemplate();
173
+ expect(tpl).not.toMatch(/HIGH PRIORITY \(Always Preserve\)/);
174
+ expect(tpl).not.toMatch(/PRESERVATION GUIDELINES/);
175
+ });
176
+ });
177
+
37
178
  // ─── compactConversation ─────────────────────────────────────────────
38
179
 
39
180
  test('compactConversation throws on empty messages array', async () => {
@@ -632,10 +632,27 @@ class ConversationCompactionService {
632
632
  };
633
633
  }
634
634
 
635
- // Format middle messages for summarization
635
+ // Format middle messages for summarization — PRE-TAG each message
636
+ // with a category the summarizer can trust without inference.
637
+ //
638
+ // Why pre-tag instead of letting the summarizer figure it out:
639
+ // tool-result wrappers carry `role: user` (they come back as
640
+ // user-role messages by convention in this codebase). A summarizer
641
+ // staring at raw `user:` prefixes can't reliably tell a literal
642
+ // user typing from a tool-result blob — and in our experiments
643
+ // both gpt-4.1-mini and gpt-4.1-nano routinely quoted tool blobs
644
+ // as if they were user messages, wasting budget and corrupting
645
+ // the user-voice section. Categorizing here eliminates that whole
646
+ // failure class. See _categorizeMessage for the rules.
636
647
  let middleContent = middleMessages
637
- .map(msg => `${msg.role}: ${typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content)}`)
638
- .join('\n\n');
648
+ .map(msg => {
649
+ const cat = this._categorizeMessage(msg);
650
+ const body = typeof msg.content === 'string'
651
+ ? msg.content
652
+ : JSON.stringify(msg.content);
653
+ return `[${cat}] ${body}`;
654
+ })
655
+ .join('\n\n────────\n\n');
639
656
 
640
657
  // Estimate input tokens
641
658
  const estimatedInputTokens = Math.ceil(middleContent.length / COMPACTION_CONFIG.CHARS_PER_TOKEN_ESTIMATE);
@@ -1128,55 +1145,112 @@ class ConversationCompactionService {
1128
1145
  }
1129
1146
 
1130
1147
  /**
1131
- * Create summary prompt template with preservation guidelines
1148
+ * Categorize one conversation message for compaction tagging.
1149
+ *
1150
+ * Returns one of:
1151
+ * REAL_USER — a literal user typing turn
1152
+ * TOOL_RESULT — a `[Tool Results …]` wrapper (carries role:user)
1153
+ * PREVIOUS_TASK — a `[Previous Task — Final Tool Results]` boundary
1154
+ * AGENT — assistant turn
1155
+ * SYSTEM — system message
1156
+ *
1157
+ * The categorization is deterministic — text-prefix sniffing on the
1158
+ * content, not heuristic. Matches the convention used everywhere
1159
+ * else in the CLI for marking tool-result envelopes.
1160
+ *
1161
+ * @param {object} msg - { role, content }
1162
+ * @returns {string} one of the categories above
1163
+ * @private
1164
+ */
1165
+ _categorizeMessage(msg) {
1166
+ if (msg.role === 'assistant') return 'AGENT';
1167
+ if (msg.role === 'system') return 'SYSTEM';
1168
+ // role === 'user' — could be a real user message OR a tool-result wrapper.
1169
+ const c = typeof msg.content === 'string' ? msg.content.trimStart() : '';
1170
+ if (c.startsWith('[Tool Results')) return 'TOOL_RESULT';
1171
+ if (c.startsWith('[Previous Task')) return 'PREVIOUS_TASK';
1172
+ return 'REAL_USER';
1173
+ }
1174
+
1175
+ /**
1176
+ * Create the compaction-summary prompt template.
1177
+ *
1178
+ * Why this prompt is shaped this way:
1179
+ * The previous "paraphrase-everything" template was found to drop
1180
+ * the user's literal asks during compaction (see the Talisman
1181
+ * case study: the agent paraphrased the user's 3-point UI request
1182
+ * into "redesign UI" and then went off and built a Settings
1183
+ * screen). Re-tested across 3 models × 5 prompt variants, this
1184
+ * two-pass shape was the highest-fidelity option that worked
1185
+ * uniformly well across gpt-4.1-mini, gpt-4.1-nano, and
1186
+ * FW-Kimi-K2.5. See tmp-compaction-experiment/ for the harness.
1187
+ *
1188
+ * PASS 1 is transcription. The summarizer is NOT allowed to filter
1189
+ * user messages by "I think the agent already handled this." That
1190
+ * determination belongs to the consumer agent reading the summary,
1191
+ * not to the summarizer itself — making the summarizer choose was
1192
+ * how completed-vs-open misjudgments crept in. The blockquote
1193
+ * format gives the consumer agent a strong visual signal to
1194
+ * anchor on those literal asks.
1195
+ *
1196
+ * PASS 2 is the narrative summary of the agent's work — files,
1197
+ * tools, decisions, state. Heavy compression OK here; only the
1198
+ * user-voice section is sacred.
1199
+ *
1132
1200
  * @private
1133
1201
  */
1134
1202
  _createSummaryPromptTemplate() {
1135
- return `You are compacting a conversation to preserve critical information while reducing token count.
1136
-
1137
- CONTEXT: You are summarizing the EARLIEST portion of a conversation. The most recent messages are preserved separately. Your summary should capture what was accomplished, key decisions, and any information still relevant for continuation. Focus on outcomes over process.
1138
-
1139
- PRESERVATION GUIDELINES:
1140
-
1141
- HIGH PRIORITY (Always Preserve):
1142
- - User requests and goals: What the user asked for, their stated preferences, and desired outcomes — these drive all ongoing work
1143
- - Current task and next steps: What the agent is actively working on and what remains to be done
1144
- - Recent achievements and current status: What was accomplished, what state the work is in now
1145
- - Files created or modified successfully: Full file paths that were written, created, or changed
1146
- - Meaningful tool invocations and their outcomes: Tool calls that produced important results or side effects
1147
- - Future reference value: Information likely to be referenced again
1148
- - Decisions and reasoning: WHY things were decided, not just what
1149
- - API signatures and interfaces: Function definitions, method calls
1150
- - Active dependencies: Information that ongoing work relies on
1151
- - Error patterns and solutions: What failed and how it was fixed
1152
- - Key facts and data: Specific numbers, names, configurations
1153
-
1154
- MEDIUM PRIORITY (Compress Intelligently):
1155
- - Code blocks: Keep function signatures + brief description, compress implementation details
1156
- - Working solutions: Essence and outcome, not every implementation step
1157
- - Failed attempts: Brief mention of what didn't work and why, skip detailed troubleshooting
1158
- - Repetitive content: Consolidate similar examples or explanations
1159
-
1160
- LOW PRIORITY (Heavily Compress/Remove):
1161
- - Completed calculations: Keep results, skip intermediate steps
1162
- - Verbose explanations: Summarize well-known concepts
1163
- - Debug output: Skip terminal logs and error messages that served their purpose
1164
- - Trial-and-error sequences: Skip multiple failed attempts with no lasting value
1165
- - Acknowledgments and pleasantries: Skip "thank you", "sure", "okay" type exchanges
1166
-
1167
- CONVERSATION SEGMENT TO SUMMARIZE:
1168
- {middle_segment}
1203
+ return `You are compacting an earlier portion of an agent-user conversation. The input has been PRE-TAGGED every message starts with one of:
1204
+
1205
+ [REAL_USER] — a literal user message; TRANSCRIBE VERBATIM in PASS 1
1206
+ [AGENT] — assistant turn (tool calls + reasoning)
1207
+ [TOOL_RESULT] — a tool's output; the consumer agent does NOT need these verbatim
1208
+ [PREVIOUS_TASK] — final tool-result block from a previous task boundary
1209
+ [SYSTEM] — system note
1169
1210
 
1170
- TASK: Create a concise summary that preserves logical flow and critical information. Focus on:
1171
- 1. Key decisions and their reasoning
1172
- 2. Important facts, data, and configurations
1173
- 3. Active context needed for continuation
1174
- 4. Problem-solving outcomes (skip the debugging process)
1175
- 5. Dependencies and interfaces that code/work relies on
1211
+ You DO NOT need to detect categories yourself. Trust the tags. The pre-tagging is deterministic.
1176
1212
 
1177
- Someone reading this should understand the conversation progression and have all information needed for effective continuation.
1213
+ Write the summary in THREE passes, in this exact order.
1214
+
1215
+ ──────────────────────────────────────────────
1216
+ PASS 1 — USER VOICE (transcription only, no judgment)
1217
+ ──────────────────────────────────────────────
1218
+
1219
+ For EVERY [REAL_USER] message — and ONLY [REAL_USER] messages — emit a blockquote:
1220
+
1221
+ > **User said (orig idx N):** "<exact text, word for word, all of it>"
1222
+
1223
+ Absolute rules:
1224
+ - Do NOT quote any [TOOL_RESULT], [AGENT], [PREVIOUS_TASK], or [SYSTEM] message here.
1225
+ - Do NOT condense, paraphrase, or omit any [REAL_USER] message.
1226
+ - Do NOT skip a [REAL_USER] message on the assumption "the agent already addressed it." That determination belongs to the consumer agent, not to you. Your job here is transcription.
1227
+ - Reproduce every [REAL_USER] message, in original order, including punctuation and typos.
1228
+ - If the input has no [REAL_USER] messages, write "(no user messages in this segment)" and proceed.
1229
+
1230
+ ──────────────────────────────────────────────
1231
+ PASS 2 — EVENT LOG (chronological bullets, concrete details)
1232
+ ──────────────────────────────────────────────
1233
+
1234
+ A bulleted list of every notable event between/after the user messages. ONE bullet per event:
1235
+
1236
+ - [orig idx N] <one-line description — include full file paths, tool names, line numbers, status, and outcome>
1237
+
1238
+ Cover: file writes, successful tool calls that changed state, decisions made by the agent, errors that affected outcome, task-list changes (especially destructive ones like 'removed: N tasks'). Skip: pure-read tool calls that didn't change state, repeated reads, pleasantries, verbose tool output dumps.
1239
+
1240
+ A consumer agent should be able to read this log and reconstruct the cause-and-effect chain — what happened to each [REAL_USER] request.
1241
+
1242
+ ──────────────────────────────────────────────
1243
+ PASS 3 — STATE NARRATIVE (2–4 sentences)
1244
+ ──────────────────────────────────────────────
1245
+
1246
+ Plain prose describing the situation at the end of this segment: what is done, what is mid-flight, what is open — and where possible, map back to which [REAL_USER] request each piece corresponds to. If [REAL_USER] requests are still open with no work toward them, say so explicitly. This is the place where lossy paraphrase is most dangerous — name the gaps clearly.
1247
+
1248
+ ──────────────────────────────────────────────
1249
+
1250
+ CONVERSATION SEGMENT TO COMPACT:
1251
+ {middle_segment}
1178
1252
 
1179
- OUTPUT: Provide ONLY the summary text without preamble, explanation, or meta-commentary.`;
1253
+ OUTPUT: PASS 1, PASS 2, PASS 3 in that order. Use exactly the section headers above. No preamble, no meta-commentary.`;
1180
1254
  }
1181
1255
  }
1182
1256
 
@@ -421,6 +421,35 @@ describe('ToolsRegistry', () => {
421
421
  expect(desc).toContain('persistent knowledge'); // memory
422
422
  expect(desc).toContain('step-by-step'); // taskmanager
423
423
  });
424
+
425
+ // REGRESSION: production observation — agents had 0 memory writes
426
+ // across 670-message sessions despite the previous wording asking
427
+ // them to "save when you recognize multi-turn work". Vague
428
+ // judgment-based triggers don't produce action. Tests pin that
429
+ // the new triggers are concrete and event-based.
430
+ test('REGRESSION: write-triggers are concrete events, not vague judgment', async () => {
431
+ await registry.registerTool(FakeMemoryTool);
432
+ const desc = registry.generateToolDescriptionsForPrompt(['memory']);
433
+ // The new wording should reference specific observable triggers,
434
+ // not "when you recognize" / "when you think".
435
+ expect(desc).toMatch(/numbered list|multi-bullet|substantive request/i);
436
+ expect(desc).toMatch(/before.*taskmanager.*sync|`taskmanager`.*sync/i);
437
+ expect(desc).toMatch(/non-obvious decision|tricky bug|unexpected error/i);
438
+ expect(desc).toMatch(/user gave you a preference/i);
439
+ // Should explicitly label the triggers as mandatory.
440
+ expect(desc).toMatch(/mandatory/i);
441
+ // And should NOT contain the old vague language.
442
+ expect(desc).not.toMatch(/when you recognize the work is multi-turn/i);
443
+ });
444
+
445
+ test('REGRESSION: write trigger mentions saving the user message VERBATIM', async () => {
446
+ // The Talisman bug was about losing the user's literal words.
447
+ // The trigger must instruct the agent to save the entire user
448
+ // message word-for-word, not a paraphrase of it.
449
+ await registry.registerTool(FakeMemoryTool);
450
+ const desc = registry.generateToolDescriptionsForPrompt(['memory']);
451
+ expect(desc).toMatch(/user'?s entire message verbatim/i);
452
+ });
424
453
  });
425
454
 
426
455
  // ── Per-model prompt shape: skip text docs for tools with native schemas
@@ -471,6 +471,185 @@ describe('CodeMapTool', () => {
471
471
  });
472
472
  });
473
473
 
474
+ // ─────────────────────────────────────────────────────────────────
475
+ // TypeScript / TSX coverage. The JS parser is the same parser used
476
+ // for .ts / .tsx / .mjs / .cjs (see _langOf); these tests pin which
477
+ // TypeScript-specific patterns the no-regex parser captures TODAY
478
+ // and which it MISSES, so a future tree-sitter migration (see the
479
+ // file-header comment in codeMapTool.js) has an explicit baseline
480
+ // to preserve / improve against.
481
+ // ─────────────────────────────────────────────────────────────────
482
+ describe('_parseJS — TypeScript / TSX coverage', () => {
483
+ const opts = { publicOnly: false, withComments: false, includeImports: false };
484
+ const sigs = (lines) =>
485
+ tool._parseJS(lines, opts).filter(e => e.kind === 'signature').map(e => e.text.trim());
486
+
487
+ // ── Captures we rely on (regressions here would break TS skeletons) ──
488
+
489
+ test('export interface — one-line', () => {
490
+ const out = sigs(['export interface User { id: string; name: string; }']);
491
+ expect(out.join('\n')).toMatch(/export interface User/);
492
+ });
493
+
494
+ test('export type alias', () => {
495
+ const out = sigs(['export type ID = string | number;']);
496
+ expect(out.join('\n')).toMatch(/export type ID/);
497
+ });
498
+
499
+ test('export enum', () => {
500
+ const out = sigs(['export enum Color { Red, Green, Blue }']);
501
+ expect(out.join('\n')).toMatch(/export enum Color/);
502
+ });
503
+
504
+ test('export interface multi-line opening', () => {
505
+ const out = sigs([
506
+ 'export interface User {',
507
+ ' id: string;',
508
+ ' name: string;',
509
+ '}',
510
+ ]);
511
+ expect(out.join('\n')).toMatch(/export interface User \{/);
512
+ });
513
+
514
+ test('abstract class — declaration + abstract method', () => {
515
+ const out = sigs([
516
+ 'abstract class Animal {',
517
+ ' abstract sound(): string;',
518
+ '}',
519
+ ]);
520
+ expect(out.join('\n')).toMatch(/abstract class Animal/);
521
+ expect(out.join('\n')).toMatch(/abstract sound\(\): string/);
522
+ });
523
+
524
+ test('generic function: identity<T>(x: T): T', () => {
525
+ const out = sigs(['function identity<T>(x: T): T { return x; }']);
526
+ expect(out.join('\n')).toMatch(/function identity<T>\(x: T\): T/);
527
+ });
528
+
529
+ test('generic class: Container<T>', () => {
530
+ const out = sigs([
531
+ 'class Container<T> {',
532
+ ' value: T;',
533
+ '}',
534
+ ]);
535
+ expect(out.join('\n')).toMatch(/class Container<T>/);
536
+ });
537
+
538
+ test('class method with TS return type annotation', () => {
539
+ const out = sigs([
540
+ 'class C {',
541
+ ' foo(x: number): string { return String(x); }',
542
+ '}',
543
+ ]);
544
+ expect(out.join('\n')).toMatch(/foo\(x: number\): string/);
545
+ });
546
+
547
+ test('TSX function component: () => JSX.Element', () => {
548
+ const out = sigs([
549
+ 'function App(): JSX.Element {',
550
+ ' return <div />;',
551
+ '}',
552
+ ]);
553
+ expect(out.join('\n')).toMatch(/function App\(\): JSX\.Element/);
554
+ });
555
+
556
+ test('ESM re-export: export { foo } from "./bar"', () => {
557
+ const out = sigs([`export { foo } from './bar';`]);
558
+ expect(out.join('\n')).toMatch(/export \{ foo \} from/);
559
+ });
560
+
561
+ test('ESM aliased re-export: export { foo as bar } from "./baz"', () => {
562
+ const out = sigs([`export { foo as bar } from './baz';`]);
563
+ expect(out.join('\n')).toMatch(/export \{ foo as bar \} from/);
564
+ });
565
+
566
+ test('decorator above class — class is still captured (decorator dropped is acceptable)', () => {
567
+ const out = sigs([
568
+ '@Component({ selector: "x" })',
569
+ 'class Foo {}',
570
+ ]);
571
+ expect(out.join('\n')).toMatch(/class Foo/);
572
+ });
573
+
574
+ test('literal-union return type', () => {
575
+ const out = sigs([`function getKind(): "a" | "b" { return "a"; }`]);
576
+ expect(out.join('\n')).toMatch(/function getKind\(\):/);
577
+ });
578
+
579
+ test('export const generic arrow: <T>(x: T): T => x', () => {
580
+ const out = sigs(['export const fn = <T>(x: T): T => x;']);
581
+ expect(out.join('\n')).toMatch(/export const fn/);
582
+ });
583
+
584
+ // ── Language detection on all declared TS/TSX/MJS/CJS extensions ──
585
+
586
+ test('_langOf maps .ts / .tsx / .mjs / .cjs / .jsx → "js"', () => {
587
+ expect(tool._langOf('a.ts')).toBe('js');
588
+ expect(tool._langOf('a.tsx')).toBe('js');
589
+ expect(tool._langOf('a.mjs')).toBe('js');
590
+ expect(tool._langOf('a.cjs')).toBe('js');
591
+ expect(tool._langOf('a.jsx')).toBe('js');
592
+ // Case-insensitive on the extension.
593
+ expect(tool._langOf('a.TS')).toBe('js');
594
+ });
595
+
596
+ // ── Known gaps. These tests pin CURRENT (limited) behavior so an
597
+ // improvement to the parser fails them — at which point you
598
+ // update the assertion. Each gap is real and worth fixing in a
599
+ // tree-sitter migration. ─────────────────────────────────────
600
+
601
+ describe('KNOWN GAPS — pin current limitations', () => {
602
+ test('GAP: bare `interface` (no `export`) is NOT captured', () => {
603
+ const out = sigs(['interface User { id: string; name: string; }']);
604
+ expect(out).toEqual([]);
605
+ });
606
+
607
+ test('GAP: bare `type` alias (no `export`) is NOT captured', () => {
608
+ const out = sigs(['type ID = string | number;']);
609
+ expect(out).toEqual([]);
610
+ });
611
+
612
+ test('GAP: bare `enum` (no `export`) is NOT captured', () => {
613
+ const out = sigs(['enum Color { Red, Green, Blue }']);
614
+ expect(out).toEqual([]);
615
+ });
616
+
617
+ test('GAP: bare multi-line `interface` (no `export`) is NOT captured', () => {
618
+ const out = sigs([
619
+ 'interface User {',
620
+ ' id: string;',
621
+ '}',
622
+ ]);
623
+ expect(out).toEqual([]);
624
+ });
625
+
626
+ test('GAP: typed arrow component `const App: React.FC = () => <div />` is NOT captured', () => {
627
+ // The `: React.FC` annotation between the identifier and `=`
628
+ // breaks the parser's "ident = arrow" recognition. Common in
629
+ // older React+TS codebases.
630
+ const out = sigs(['const App: React.FC = () => <div />;']);
631
+ expect(out).toEqual([]);
632
+ });
633
+
634
+ test('GAP: async generator `async function* foo()` is NOT captured', () => {
635
+ const out = sigs([
636
+ 'async function* stream(): AsyncIterableIterator<number> {',
637
+ ' yield 1;',
638
+ '}',
639
+ ]);
640
+ expect(out).toEqual([]);
641
+ });
642
+
643
+ test('GAP: destructured-arg arrow with type annotation is NOT captured', () => {
644
+ // `const fn = ({ name }: { name: string }): string => …`
645
+ // The destructured + typed parameter list trips the
646
+ // ident = arrow recognition.
647
+ const out = sigs([`const greet = ({ name }: { name: string }): string => \`hi \${name}\`;`]);
648
+ expect(out).toEqual([]);
649
+ });
650
+ });
651
+ });
652
+
474
653
  // ─────────────────────────────────────────────────────────────────
475
654
  // C / C++ — _parseC. Same approach as the JS path; we lock the
476
655
  // patterns the regex needs to handle on real-world C/CPP files so