pi-charset 0.1.4 → 0.1.6

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.
Files changed (71) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/CHANGELOG.zh-CN.md +64 -0
  3. package/CONTRIBUTING.md +33 -0
  4. package/CONTRIBUTING.zh-CN.md +33 -0
  5. package/README.md +35 -6
  6. package/README.zh-CN.md +35 -6
  7. package/docs/ACCEPTANCE.md +30 -2
  8. package/docs/COMPATIBILITY.md +6 -1
  9. package/docs/CONFIG-GUIDE.md +4 -1
  10. package/docs/DESIGN-REVIEW.md +54 -0
  11. package/docs/EDIT-ENGINE.md +46 -0
  12. package/docs/EDITING-PLAN.md +16 -0
  13. package/docs/MCP-AND-MULTI-AGENT.md +111 -0
  14. package/docs/MODEL-EVAL.md +92 -0
  15. package/docs/PROGRESS.md +311 -0
  16. package/docs/RELEASING.md +4 -2
  17. package/docs/zh-CN/ACCEPTANCE.md +30 -2
  18. package/docs/zh-CN/COMPATIBILITY.md +6 -1
  19. package/docs/zh-CN/CONFIG-GUIDE.md +4 -1
  20. package/docs/zh-CN/DESIGN-REVIEW.md +54 -0
  21. package/docs/zh-CN/EDIT-ENGINE.md +46 -0
  22. package/docs/zh-CN/EDITING-PLAN.md +415 -0
  23. package/docs/zh-CN/MCP-AND-MULTI-AGENT.md +111 -0
  24. package/docs/zh-CN/MODEL-EVAL.md +92 -0
  25. package/docs/zh-CN/PROGRESS.md +311 -0
  26. package/docs/zh-CN/RELEASING.md +4 -2
  27. package/docs/zh-CN/editing-plan-architecture.png +0 -0
  28. package/examples/all-utf8.jsonc +1 -0
  29. package/examples/embedded-c.jsonc +1 -0
  30. package/examples/legacy-java-web.jsonc +1 -0
  31. package/examples/mixed-repo.jsonc +1 -0
  32. package/package.json +14 -2
  33. package/prompts/charset-setup.md +3 -3
  34. package/schema/pi-charset.schema.json +118 -0
  35. package/skills/charset-rules/SKILL.md +8 -2
  36. package/src/config.ts +524 -185
  37. package/src/edit/apply-patch-core.ts +275 -0
  38. package/src/edit/apply-patch.ts +78 -0
  39. package/src/edit/diagnostics.ts +48 -0
  40. package/src/edit/hashline.ts +438 -0
  41. package/src/edit/patch.ts +655 -0
  42. package/src/edit/paths.ts +42 -0
  43. package/src/edit/plan.ts +107 -0
  44. package/src/edit/tool.ts +451 -0
  45. package/src/edit-preview.ts +48 -277
  46. package/src/encoding/classify.ts +235 -65
  47. package/src/encoding/common-scripts.ts +66 -0
  48. package/src/encoding/converter.ts +114 -16
  49. package/src/encoding/fast-codec.ts +469 -0
  50. package/src/encoding/file-stamp.ts +55 -0
  51. package/src/encoding/line-endings.ts +66 -73
  52. package/src/encoding/mime.ts +12 -43
  53. package/src/encoding/stream-transcode.ts +135 -30
  54. package/src/grep-core.ts +687 -0
  55. package/src/grep.ts +25 -463
  56. package/src/index.ts +458 -49
  57. package/src/journal.ts +459 -0
  58. package/src/maintenance.ts +375 -0
  59. package/src/mcp/server.ts +651 -0
  60. package/src/operations.ts +759 -127
  61. package/src/read-view.ts +924 -0
  62. package/src/resolve.ts +113 -101
  63. package/src/scaffold.ts +9 -4
  64. package/src/shell-guard.ts +617 -0
  65. package/src/shell.ts +85 -33
  66. package/src/sysnote.ts +4 -6
  67. package/src/version.ts +1 -1
  68. package/tools/charset-core.mjs +251 -0
  69. package/tools/pi-charset-cli.mjs +369 -0
  70. package/tools/pi-charset-mcp.mjs +103 -0
  71. package/tools/scan-encoding.mjs +30 -28
@@ -0,0 +1,924 @@
1
+ // Pure, zero-dependency token-efficient file views for `read`:
2
+ // - Multi-range slicing (`ranges: [[start, end], ...]`) in one read pass with optional Hashline tags.
3
+ // - Structural outline extraction (`outline: true`) emitting `<line>:<2-hex>| <declaration>` so agents
4
+ // can navigate large GBK/UTF-8 files in ~1-2% of full-file tokens and jump directly to ranges or Hashline edits.
5
+ import * as path from "node:path";
6
+ import { indexLines, lineHash, type LineSpan } from "./edit/hashline";
7
+
8
+ export type LineRange = readonly [number, number];
9
+
10
+ export interface NormalizedRange {
11
+ readonly start: number; // 1-based inclusive
12
+ readonly end: number; // 1-based inclusive
13
+ }
14
+
15
+ /** Validate, clamp to [1..totalLines], sort, and merge overlapping or adjacent 1-based inclusive ranges. */
16
+ export function normalizeLineRanges(ranges: readonly LineRange[], totalLines: number): NormalizedRange[] {
17
+ if (!Array.isArray(ranges) || ranges.length === 0) {
18
+ throw new Error("ranges must be a non-empty array of [startLine, endLine] pairs.");
19
+ }
20
+ const parsed: { start: number; end: number }[] = [];
21
+ for (let i = 0; i < ranges.length; i++) {
22
+ const item = ranges[i];
23
+ if (!Array.isArray(item) || item.length !== 2) {
24
+ throw new Error(`ranges[${i}] must be a [startLine, endLine] pair.`);
25
+ }
26
+ const rawStart = Math.floor(Number(item[0]));
27
+ const rawEnd = Math.floor(Number(item[1]));
28
+ if (!Number.isFinite(rawStart) || !Number.isFinite(rawEnd) || rawStart < 1 || rawEnd < rawStart) {
29
+ throw new Error(`ranges[${i}] [${item[0]}, ${item[1]}] is invalid (require 1 <= start <= end).`);
30
+ }
31
+ if (totalLines === 0 || rawStart > totalLines) continue;
32
+ parsed.push({ start: rawStart, end: Math.min(rawEnd, totalLines) });
33
+ }
34
+ parsed.sort((a, b) => a.start - b.start || a.end - b.end);
35
+ const merged: { start: number; end: number }[] = [];
36
+ for (const r of parsed) {
37
+ const prev = merged[merged.length - 1];
38
+ if (prev && r.start <= prev.end + 1) {
39
+ if (r.end > prev.end) prev.end = r.end;
40
+ } else {
41
+ merged.push({ ...r });
42
+ }
43
+ }
44
+ return merged;
45
+ }
46
+
47
+ const DEFAULT_MAX_VIEW_BYTES = 48 * 1024;
48
+
49
+ /** Strip a single leading UTF-8 BOM (U+FEFF) so line 1 hashes and outline matchers align with loadSnapshot(). */
50
+ const stripLeadingBom = (text: string) => (text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);
51
+
52
+ /** Count total 1-based lines matching indexLines(text).length without allocating any LineSpan objects. */
53
+ function countTotalLines(clean: string): number {
54
+ const len = clean.length;
55
+ if (len === 0) return 0;
56
+ let lines = 1;
57
+ let pos = 0;
58
+ while (pos < len) {
59
+ const nl = clean.indexOf("\n", pos);
60
+ if (nl === -1) break;
61
+ pos = nl + 1;
62
+ if (pos < len) lines++;
63
+ }
64
+ return lines;
65
+ }
66
+
67
+ /**
68
+ * Extract multiple disjoint line ranges from decoded `text` in a single zero-span-allocation linear pass
69
+ * that stops immediately after the last requested line (O(maxEnd) extraction, O(1) extra memory).
70
+ * When `hashlines` is true, prefixes each emitted line with `<line>:<2-hex>|`.
71
+ */
72
+ export function formatLineRanges(
73
+ text: string,
74
+ ranges: readonly LineRange[],
75
+ hashlines = false,
76
+ maxBytes = DEFAULT_MAX_VIEW_BYTES,
77
+ ): { text: string; totalLines: number; emittedLines: number; truncated: boolean } {
78
+ const clean = stripLeadingBom(text);
79
+ const totalLines = countTotalLines(clean);
80
+ const merged = normalizeLineRanges(ranges, totalLines);
81
+ if (totalLines === 0) {
82
+ return { text: "(empty file)", totalLines: 0, emittedLines: 0, truncated: false };
83
+ }
84
+ if (merged.length === 0) {
85
+ return {
86
+ text: `[All requested ranges are beyond end of file (${totalLines} lines).]`,
87
+ totalLines,
88
+ emittedLines: 0,
89
+ truncated: false,
90
+ };
91
+ }
92
+
93
+ const out: string[] = [];
94
+ let bytes = 0;
95
+ let emittedLines = 0;
96
+ let truncated = false;
97
+
98
+ const push = (line: string): boolean => {
99
+ const b = Buffer.byteLength(line) + (out.length ? 1 : 0);
100
+ if (bytes + b > maxBytes && out.length > 0) {
101
+ truncated = true;
102
+ return false;
103
+ }
104
+ out.push(line);
105
+ bytes += b;
106
+ return true;
107
+ };
108
+
109
+ const len = clean.length;
110
+ const maxWanted = merged[merged.length - 1].end;
111
+ let ri = 0;
112
+ let headerEmitted = false;
113
+ let pos = 0;
114
+ let ln = 1;
115
+
116
+ while (pos < len && ln <= maxWanted && ri < merged.length && !truncated) {
117
+ const nl = clean.indexOf("\n", pos);
118
+ const bodyEnd = nl === -1 ? len : nl > pos && clean.charCodeAt(nl - 1) === 13 ? nl - 1 : nl;
119
+ const nextPos = nl === -1 ? len : nl + 1;
120
+
121
+ const r = merged[ri];
122
+ if (ln >= r.start && ln <= r.end) {
123
+ if (!headerEmitted) {
124
+ headerEmitted = true;
125
+ if (merged.length > 1 || r.start > 1 || r.end < totalLines) {
126
+ if (!push(`--- L${r.start}..${r.end} (of ${totalLines}) ---`)) break;
127
+ }
128
+ }
129
+ const body = clean.slice(pos, bodyEnd);
130
+ const formatted = hashlines ? `${ln}:${lineHash(body)}|${body}` : body;
131
+ if (!push(formatted)) break;
132
+ emittedLines++;
133
+ if (ln === r.end) {
134
+ ri++;
135
+ headerEmitted = false;
136
+ }
137
+ }
138
+ pos = nextPos;
139
+ ln++;
140
+ }
141
+
142
+ if (truncated) {
143
+ out.push(`\n[Output truncated at ${Math.round(maxBytes / 1024)}KB. Narrow ranges to see remaining lines.]`);
144
+ }
145
+ return { text: out.join("\n"), totalLines, emittedLines, truncated };
146
+ }
147
+
148
+ type LangFamily =
149
+ | "c"
150
+ | "js"
151
+ | "py"
152
+ | "java"
153
+ | "go"
154
+ | "rust"
155
+ | "md"
156
+ | "shell"
157
+ | "cmake"
158
+ | "ruby"
159
+ | "lua"
160
+ | "elixir"
161
+ | "sql"
162
+ | "schema"
163
+ | "css"
164
+ | "config"
165
+ | "generic";
166
+
167
+ interface LangInfo {
168
+ readonly family: LangFamily;
169
+ readonly isHeader: boolean;
170
+ readonly isMarkupScript: boolean;
171
+ }
172
+
173
+ const EXT_LANG: Record<string, LangFamily> = {
174
+ ".cmake": "cmake", ".h": "c", ".hpp": "c", ".hh": "c", ".hxx": "c", ".c": "c", ".cpp": "c", ".cc": "c", ".cxx": "c", ".ino": "c", ".s": "c", ".asm": "c",
175
+ ".vue": "js", ".svelte": "js", ".ts": "js", ".tsx": "js", ".js": "js", ".jsx": "js", ".mjs": "js", ".cjs": "js", ".mts": "js", ".cts": "js",
176
+ ".py": "py", ".pyi": "py", ".go": "go", ".rs": "rust", ".rb": "ruby", ".rake": "ruby", ".lua": "lua", ".ex": "elixir", ".exs": "elixir", ".sql": "sql",
177
+ ".java": "java", ".cs": "java", ".kt": "java", ".kts": "java", ".scala": "java", ".swift": "java", ".php": "java", ".dart": "java",
178
+ ".md": "md", ".mdx": "md", ".markdown": "md", ".rst": "md",
179
+ ".sh": "shell", ".bash": "shell", ".zsh": "shell", ".ps1": "shell", ".psm1": "shell", ".bat": "shell", ".cmd": "shell", ".mk": "shell",
180
+ ".proto": "schema", ".graphql": "schema", ".gql": "schema",
181
+ ".css": "css", ".scss": "css", ".sass": "css", ".less": "css",
182
+ ".json": "config", ".jsonc": "config", ".yaml": "config", ".yml": "config", ".toml": "config", ".ini": "config", ".cfg": "config", ".conf": "config", ".properties": "config",
183
+ };
184
+ const C_HEADERS = new Set([".h", ".hpp", ".hh", ".hxx"]);
185
+
186
+ function detectLang(filePath: string): LangInfo {
187
+ const base = path.basename(filePath).toLowerCase();
188
+ if (base === "cmakelists.txt") return { family: "cmake", isHeader: false, isMarkupScript: false };
189
+ if (base === "makefile" || base === "gnumakefile") return { family: "shell", isHeader: false, isMarkupScript: false };
190
+ const ext = path.extname(base);
191
+ const family = EXT_LANG[ext] ?? "generic";
192
+ return { family, isHeader: C_HEADERS.has(ext) || base.endsWith(".d.ts"), isMarkupScript: ext === ".vue" || ext === ".svelte" };
193
+ }
194
+
195
+ const C_STYLE_COMMENT_LANGS = new Set<LangFamily>(["c", "js", "java", "go", "rust", "schema", "css"]);
196
+
197
+ interface CStyleState {
198
+ commentDepth: number;
199
+ braceDepth: number;
200
+ /** Closing delimiter of an active multi-line template/raw/triple-quoted/verbatim string, or null when in code. */
201
+ multilineClose: string | null;
202
+ /** True when the active multi-line string interprets backslash escapes (JS template literals, Java text blocks). */
203
+ multilineEscape: boolean;
204
+ /** True when the active multi-line string escapes double quotes via `""` (C# verbatim @"..." strings). */
205
+ multilineDoubleQuoteEscape: boolean;
206
+ /** True while scanning continuation lines of a C/C++ backslash-continued preprocessor directive (`#define ... \`). */
207
+ inMacroContinuation: boolean;
208
+ /** Brace depths where JS `${...}` template interpolations opened, so matching `}` resumes the template. */
209
+ templateBraces: number[];
210
+ /** Active C++ `class`/`struct`/`namespace` brace depths (1-based depth inside the opening `{`). */
211
+ typeScopeDepths: number[];
212
+ /** True after a C++ `class`/`struct`/`namespace` header awaiting its opening `{` (supports Allman style). */
213
+ pendingTypeScope: boolean;
214
+ }
215
+
216
+ const isIdentChar = (c: number) =>
217
+ (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || (c >= 48 && c <= 57) || c === 95 || c === 36;
218
+
219
+ const JS_REGEX_PRECEDERS = new Set([0, 40, 91, 123, 44, 59, 58, 61, 33, 38, 124, 63, 126, 94, 43, 45, 42, 37, 60, 62]);
220
+ const JS_REGEX_KEYWORDS = new Set(["return", "case", "throw", "typeof", "void", "delete", "in", "of", "await", "yield", "else"]);
221
+ const C_TYPE_SCOPE_RE = /^(?:template\s*<[^>]{1,120}>\s*)?(?:(?:virtual|static|inline|explicit|const|export)\s+)*(?:class|struct|namespace)\b/;
222
+
223
+ function canStartJsRegex(body: string, slashIdx: number, prevNonSpace: number, prevNonSpaceIdx: number): boolean {
224
+ if (JS_REGEX_PRECEDERS.has(prevNonSpace)) return true;
225
+ if (prevNonSpaceIdx >= 0 && isIdentChar(prevNonSpace)) {
226
+ let start = prevNonSpaceIdx;
227
+ while (start > 0 && isIdentChar(body.charCodeAt(start - 1))) start--;
228
+ return JS_REGEX_KEYWORDS.has(body.slice(start, prevNonSpaceIdx + 1));
229
+ }
230
+ return slashIdx === 0;
231
+ }
232
+
233
+ function skipJsRegexLiteral(body: string, startSlash: number): number {
234
+ let inClass = false;
235
+ for (let i = startSlash + 1; i < body.length; i++) {
236
+ const c = body.charCodeAt(i);
237
+ if (c === 92) { i++; continue; } // escaped char
238
+ if (c === 91) { inClass = true; continue; } // [
239
+ if (c === 93) { inClass = false; continue; } // ]
240
+ if (c === 47 && !inClass) return i; // closing /
241
+ }
242
+ return startSlash; // unclosed: not a regex literal
243
+ }
244
+
245
+ /**
246
+ * Advance block-comment, multi-line string (JS templates, Go/Rust/C++ raw strings, Java text blocks),
247
+ * and brace/type-scope state across one source line in O(line) time.
248
+ */
249
+ function scanCStyleLine(
250
+ body: string,
251
+ trimmed: string,
252
+ state: CStyleState,
253
+ lang: LangFamily,
254
+ ): { startedInBlock: boolean; hasCode: boolean; braceBefore: number; inTypeScope: boolean } {
255
+ const startedInBlock = state.commentDepth > 0 || state.multilineClose !== null || state.inMacroContinuation;
256
+ const braceBefore = state.braceDepth;
257
+ const inTypeScope =
258
+ state.typeScopeDepths.length > 0 && state.typeScopeDepths[state.typeScopeDepths.length - 1] === braceBefore;
259
+ const nestedComments = lang === "rust";
260
+ const skipSingleQuotes = lang !== "rust";
261
+ let hasCode = false;
262
+ let prevNonSpace = 0;
263
+ let prevNonSpaceIdx = -1;
264
+ const len = body.length;
265
+
266
+ // C/C++ backslash-continued preprocessor directives (`#define ... \`) are skipped on continuation lines so
267
+ // multi-line macro bodies neither emit fake declarations nor drift brace depth.
268
+ if (lang === "c") {
269
+ const continues = body.trimEnd().endsWith("\\");
270
+ if (state.inMacroContinuation) {
271
+ state.inMacroContinuation = continues;
272
+ return { startedInBlock: true, hasCode: false, braceBefore, inTypeScope };
273
+ }
274
+ if (!startedInBlock && trimmed.startsWith("#")) {
275
+ state.inMacroContinuation = continues;
276
+ return { startedInBlock: false, hasCode: true, braceBefore, inTypeScope };
277
+ }
278
+ }
279
+
280
+ if (lang === "c" && !startedInBlock && C_TYPE_SCOPE_RE.test(trimmed) && !trimmed.endsWith(";")) {
281
+ state.pendingTypeScope = true;
282
+ }
283
+
284
+ for (let i = 0; i < len; i++) {
285
+ const c = body.charCodeAt(i);
286
+ const n = i + 1 < len ? body.charCodeAt(i + 1) : 0;
287
+
288
+ if (state.commentDepth > 0) {
289
+ if (nestedComments && c === 47 && n === 42) { // /*
290
+ state.commentDepth++;
291
+ i++;
292
+ } else if (c === 42 && n === 47) { // */
293
+ state.commentDepth--;
294
+ i++;
295
+ }
296
+ continue;
297
+ }
298
+
299
+ if (state.multilineClose !== null) {
300
+ if (state.multilineEscape && c === 92) { // backslash escape
301
+ i++;
302
+ continue;
303
+ }
304
+ if (state.multilineDoubleQuoteEscape && c === 34 && n === 34) { // C# verbatim "" escape
305
+ i++;
306
+ continue;
307
+ }
308
+ if (lang === "js" && state.multilineClose === "`" && c === 36 && n === 123) { // ${
309
+ state.templateBraces.push(state.braceDepth);
310
+ state.braceDepth++;
311
+ state.multilineClose = null;
312
+ state.multilineEscape = false;
313
+ state.multilineDoubleQuoteEscape = false;
314
+ prevNonSpace = 123;
315
+ prevNonSpaceIdx = i + 1;
316
+ i++;
317
+ continue;
318
+ }
319
+ if (body.startsWith(state.multilineClose, i)) {
320
+ i += state.multilineClose.length - 1;
321
+ state.multilineClose = null;
322
+ state.multilineEscape = false;
323
+ state.multilineDoubleQuoteEscape = false;
324
+ prevNonSpace = 34;
325
+ prevNonSpaceIdx = i;
326
+ }
327
+ continue;
328
+ }
329
+
330
+ if (c === 47 && n === 47) break; // // line comment
331
+ if (c === 47 && n === 42) { // /* block comment
332
+ state.commentDepth++;
333
+ i++;
334
+ continue;
335
+ }
336
+
337
+ if (c > 32) hasCode = true;
338
+
339
+ // JS/TS regex literals (`/pattern/`) so embedded backticks, quotes, or `/*` never corrupt state.
340
+ if (lang === "js" && c === 47 && canStartJsRegex(body, i, prevNonSpace, prevNonSpaceIdx)) {
341
+ const end = skipJsRegexLiteral(body, i);
342
+ if (end > i) {
343
+ i = end;
344
+ prevNonSpace = 47;
345
+ prevNonSpaceIdx = i;
346
+ continue;
347
+ }
348
+ }
349
+
350
+ // JS/TS template literals (`...`) with `${...}` nesting and Go raw strings (`...`).
351
+ if (c === 96 && (lang === "js" || lang === "go")) {
352
+ state.multilineClose = "`";
353
+ state.multilineEscape = lang === "js";
354
+ continue;
355
+ }
356
+
357
+ // Java/Kotlin/Swift/C# triple-quoted multi-line strings ("""...""").
358
+ if (lang === "java" && c === 34 && body.startsWith('"""', i)) {
359
+ state.multilineClose = '"""';
360
+ state.multilineEscape = true;
361
+ state.multilineDoubleQuoteEscape = false;
362
+ i += 2;
363
+ continue;
364
+ }
365
+
366
+ // C# verbatim strings (@"..." / $@"..." / @$"...") where `""` escapes a literal quote.
367
+ if (lang === "java" && c === 64 && n === 34) {
368
+ state.multilineClose = '"';
369
+ state.multilineEscape = false;
370
+ state.multilineDoubleQuoteEscape = true;
371
+ i++;
372
+ continue;
373
+ }
374
+
375
+ // Rust raw strings: r"...", r#"..."#, br#"..."#, cr#"..."#.
376
+ if (lang === "rust" && c === 114) {
377
+ const prev = i > 0 ? body.charCodeAt(i - 1) : 0;
378
+ const prev2 = i > 1 ? body.charCodeAt(i - 2) : 0;
379
+ const validPrefix = !isIdentChar(prev) || ((prev === 98 || prev === 99) && !isIdentChar(prev2));
380
+ if (validPrefix) {
381
+ let hashes = 0;
382
+ while (i + 1 + hashes < len && body.charCodeAt(i + 1 + hashes) === 35) hashes++;
383
+ if (i + 1 + hashes < len && body.charCodeAt(i + 1 + hashes) === 34) {
384
+ state.multilineClose = '"' + "#".repeat(hashes);
385
+ state.multilineEscape = false;
386
+ i += 1 + hashes;
387
+ continue;
388
+ }
389
+ }
390
+ }
391
+
392
+ // C++ raw strings: R"delim(...)delim" (with optional u8/u/U/L prefix).
393
+ if (lang === "c" && c === 82 && n === 34) {
394
+ const prev = i > 0 ? body.charCodeAt(i - 1) : 0;
395
+ const prev2 = i > 1 ? body.charCodeAt(i - 2) : 0;
396
+ const prev3 = i > 2 ? body.charCodeAt(i - 3) : 0;
397
+ const validPrefix =
398
+ !isIdentChar(prev) ||
399
+ ((prev === 76 || prev === 85 || prev === 117) && !isIdentChar(prev2)) ||
400
+ (prev === 56 && prev2 === 117 && !isIdentChar(prev3));
401
+ if (validPrefix) {
402
+ let lp = -1;
403
+ const maxDelim = Math.min(len, i + 19);
404
+ for (let k = i + 2; k < maxDelim; k++) {
405
+ const dc = body.charCodeAt(k);
406
+ if (dc === 40) { lp = k; break; } // (
407
+ if (dc <= 32 || dc === 41 || dc === 92) break;
408
+ }
409
+ if (lp !== -1) {
410
+ state.multilineClose = `)${body.slice(i + 2, lp)}"`;
411
+ state.multilineEscape = false;
412
+ i = lp;
413
+ continue;
414
+ }
415
+ }
416
+ }
417
+
418
+ // Skip single-line string literals so /*, //, {, } inside strings do not corrupt syntax tracking.
419
+ if (c === 34 || c === 96 || (skipSingleQuotes && c === 39)) { // ", `, '
420
+ const quote = c;
421
+ i++;
422
+ while (i < len) {
423
+ const sc = body.charCodeAt(i);
424
+ if (sc === 92) { i += 2; continue; } // backslash escape
425
+ if (sc === quote) break;
426
+ i++;
427
+ }
428
+ prevNonSpace = quote;
429
+ prevNonSpaceIdx = Math.min(i, len - 1);
430
+ continue;
431
+ }
432
+
433
+ if (c === 123) { // {
434
+ state.braceDepth++;
435
+ if (state.pendingTypeScope) {
436
+ state.typeScopeDepths.push(state.braceDepth);
437
+ state.pendingTypeScope = false;
438
+ }
439
+ } else if (c === 125) { // }
440
+ if (state.braceDepth > 0) state.braceDepth--;
441
+ while (state.typeScopeDepths.length > 0 && state.typeScopeDepths[state.typeScopeDepths.length - 1] > state.braceDepth) {
442
+ state.typeScopeDepths.pop();
443
+ }
444
+ if (lang === "js" && state.templateBraces.length > 0 && state.templateBraces[state.templateBraces.length - 1] === state.braceDepth) {
445
+ state.templateBraces.pop();
446
+ state.multilineClose = "`";
447
+ state.multilineEscape = true;
448
+ }
449
+ } else if (c === 59 && state.pendingTypeScope) { // ; cancels pending type scope
450
+ state.pendingTypeScope = false;
451
+ }
452
+
453
+ if (c > 32) {
454
+ prevNonSpace = c;
455
+ prevNonSpaceIdx = i;
456
+ }
457
+ }
458
+
459
+ return { startedInBlock, hasCode, braceBefore, inTypeScope };
460
+ }
461
+
462
+ /** Track Python triple-quoted strings (""" / ''') so docstring examples never produce false outline hits. */
463
+ function scanPythonLine(body: string, triple: '"""' | "'''" | null): { startedInTriple: boolean; nextTriple: '"""' | "'''" | null } {
464
+ const startedInTriple = triple !== null;
465
+ let cur = triple;
466
+ const len = body.length;
467
+ for (let i = 0; i < len; i++) {
468
+ const c = body[i];
469
+ if (cur !== null) {
470
+ if (c === "\\") { i++; continue; }
471
+ if (body.startsWith(cur, i)) {
472
+ cur = null;
473
+ i += 2;
474
+ }
475
+ continue;
476
+ }
477
+ if (c === "#") break;
478
+ if (body.startsWith('"""', i)) { cur = '"""'; i += 2; continue; }
479
+ if (body.startsWith("'''", i)) { cur = "'''"; i += 2; continue; }
480
+ if (c === '"' || c === "'") {
481
+ const q = c;
482
+ i++;
483
+ while (i < len) {
484
+ if (body[i] === "\\") { i += 2; continue; }
485
+ if (body[i] === q) break;
486
+ i++;
487
+ }
488
+ }
489
+ }
490
+ return { startedInTriple, nextTriple: cur };
491
+ }
492
+
493
+ const MAX_LOOKAHEAD = 8;
494
+
495
+ /**
496
+ * Bounded O(1) lookahead from the first `(` on `spans[lineIdx]` until its matching `)`.
497
+ * Returns the trimmed tail after `)` (plus the first non-empty token of the next line for Allman `{`).
498
+ * Returns null if no balanced `)` is reached within MAX_LOOKAHEAD lines.
499
+ */
500
+ function tailAfterBalancedParen(clean: string, spans: readonly LineSpan[], lineIdx: number): string | null {
501
+ const first = clean.slice(spans[lineIdx].start, spans[lineIdx].bodyEnd);
502
+ const openPos = first.indexOf("(");
503
+ if (openPos === -1) return null;
504
+
505
+ let depth = 0;
506
+ const maxLine = Math.min(spans.length - 1, lineIdx + MAX_LOOKAHEAD);
507
+ for (let li = lineIdx; li <= maxLine; li++) {
508
+ const line = li === lineIdx ? first : clean.slice(spans[li].start, spans[li].bodyEnd);
509
+ const startCol = li === lineIdx ? openPos : 0;
510
+ for (let j = startCol; j < line.length; j++) {
511
+ const c = line.charCodeAt(j);
512
+ const n = j + 1 < line.length ? line.charCodeAt(j + 1) : 0;
513
+ if (c === 47 && n === 47) break; // //
514
+ if (c === 34 || c === 39 || c === 96) {
515
+ const q = c;
516
+ j++;
517
+ while (j < line.length) {
518
+ if (line.charCodeAt(j) === 92) { j += 2; continue; }
519
+ if (line.charCodeAt(j) === q) break;
520
+ j++;
521
+ }
522
+ continue;
523
+ }
524
+ if (c === 40) depth++; // (
525
+ else if (c === 41) { // )
526
+ depth--;
527
+ if (depth === 0) {
528
+ let tail = line.slice(j + 1).replace(/\/\/.*$/, "").trim();
529
+ // Support Allman-style opening brace or trailing `=>` / `throws ... {` on the next line.
530
+ if (li + 1 < spans.length && (!tail || /^(?:const|noexcept|override|final|throws\b|where\b|:\s*\S|->\s*\S)/.test(tail)) && !tail.includes("{") && !tail.includes(";") && !tail.includes("=>")) {
531
+ const next = clean.slice(spans[li + 1].start, spans[li + 1].bodyEnd).replace(/\/\/.*$/, "").trim();
532
+ if (next) tail = tail ? `${tail} ${next}` : next;
533
+ }
534
+ return tail;
535
+ }
536
+ }
537
+ }
538
+ }
539
+ return null;
540
+ }
541
+
542
+ // Conservative, linear-time (ReDoS-free) declaration matchers per language family.
543
+ const CONTROL_KW_RE = /^(?:if|for|while|switch|else|return|case|goto|do|sizeof|catch|throw|delete|new|typeof|await|yield|assert|elif|except|try|finally|with|match)\b/;
544
+
545
+ const C_SINGLE_DECL_RE = /^(?:#\s*define\s+[A-Za-z_]\w*|typedef\s+|(?:static|inline|extern|const|volatile|unsigned|signed|struct|enum|union|class|namespace)\b[^;]{1,120}(?:\([^;]*\)\s*(?:\{|const\b|$)|\{)|template\s*<[^>]{1,120}>|[A-Za-z_]\w*(?:\s*\*+)?\s+[A-Za-z_~]\w*(?:::[A-Za-z_~]\w*)?\s*\([^;]*\)\s*(?:\{|$))/;
546
+ const C_QUALIFIED_SIG_START_RE = /^(?:(?:static|inline|extern|virtual|explicit|constexpr|consteval|friend|const|volatile|unsigned|signed|struct|enum|union)\s+)*[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*(?:<[^>\n]{1,60}>)?(?:\s*[*&]+)?\s+[A-Za-z_~]\w*(?:::[A-Za-z_~]\w*)?\s*\(/;
547
+ const C_CTOR_DTOR_START_RE = /^(?:(?:virtual|explicit|inline|constexpr)\s+)*~?[A-Za-z_]\w*(?:::[A-Za-z_~]\w*)?\s*\(/;
548
+ const C_RETURN_TYPE_ONLY_RE = /^(?:(?:static|inline|extern|virtual|constexpr|const|volatile|unsigned|signed|struct|enum|union)\s+)*[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*(?:\s*[*&]+)?$/;
549
+ const C_INDENTED_TYPE_RE = /^(?: |\t)(?:virtual\s+|static\s+|inline\s+|explicit\s+|const\s+)*(?:class|struct|enum|namespace)\b/;
550
+
551
+ const JS_DECL_RE = /^ {0,4}(?:export\s+(?:default\s+)?)?(?:declare\s+)?(?:abstract\s+)?(?:async\s+)?(?:function\b|class\b|interface\b|type\s+[A-Za-z_$]\w*(?:<[^>\n]{1,60}>)?\s*=|enum\b|namespace\b|const\s+\w+\s*=\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_]\w*)\s*=>|const\s+\w+\s*=\s*(?:async\s+)?function\b)/;
552
+ const JS_ARROW_START_RE = /^ {0,4}(?:export\s+)?const\s+[A-Za-z_$]\w*(?:\s*:\s*[^=\n]{1,80})?\s*=\s*(?:async\s+)?(?:<[^>\n]{1,60}>)?\s*\(/;
553
+ const JS_METHOD_START_RE = /^(?: {2,8}|\t{1,3})(?:(?:public|private|protected|static|readonly|override|abstract|async|get|set)\s+)*\*?[A-Za-z_#$]\w*(?:<[^>\n]{1,60}>)?\s*\(/;
554
+ const VUE_BLOCK_RE = /^<(?:template|script|style)(?:\s|>)/i;
555
+
556
+ const PY_DECL_RE = /^\s*(?:async\s+def|def|class)\s+[A-Za-z_]\w*/;
557
+ const JAVA_TYPE_RE = /^\s*(?:(?:public|private|protected|internal|static|final|abstract|synchronized|override|open|sealed|data|value|inline|virtual|async|partial|readonly|extern|unsafe|fileprivate|mutating|nonmutating)\s+)*(?:class|interface|enum|record|struct|object|trait|protocol|extension|actor|namespace|delegate|fun|func|function|def)\b/;
558
+ const JAVA_METHOD_START_RE = /^\s*(?:(?:public|private|protected|internal|static|final|abstract|synchronized|override|open|sealed|suspend|inline|virtual|async|native|default|fileprivate)\s+)+[^(;={]{1,100}\s+[A-Za-z_]\w*(?:<[^>\n]{1,60}>)?\s*\(/;
559
+
560
+ const GO_DECL_RE = /^(?:func\s+|type\s+[A-Za-z_]\w*\b|package\s+)/;
561
+ const RUST_DECL_RE = /^\s*(?:pub(?:\([^)]*\))?\s+)?(?:default\s+)?(?:const\s+)?(?:async\s+)?(?:unsafe\s+)?(?:extern\s+(?:"[^"]*"\s+)?)?(?:fn|struct|enum|trait|impl|mod|type|macro_rules!|static)\b/;
562
+ const MD_DECL_RE = /^#{1,6}\s+\S/;
563
+ const SHELL_DECL_RE = /^(?:function\s+[A-Za-z_]\w*|[A-Za-z_]\w*\s*\(\s*\)\s*\{?|[A-Za-z0-9_./-]+:(?!=))/;
564
+ const CMAKE_DECL_RE = /^(?:project|add_executable|add_library|function|macro|set_target_properties)\s*\(/i;
565
+ const RUBY_DECL_RE = /^\s*(?:module|class|def)\s+[A-Za-z_]\w*/;
566
+ const LUA_DECL_RE = /^\s*(?:local\s+)?function\s+[A-Za-z_][\w.:]*/;
567
+ const ELIXIR_DECL_RE = /^\s*(?:defmodule|defprotocol|defimpl|defmacro|defmacrop|defstruct|defp|def)\s+[A-Za-z_]\w*/;
568
+ const SQL_DECL_RE = /^\s*create\s+(?:or\s+replace\s+)?(?:temp(?:orary)?\s+)?(?:unique\s+)?(?:materialized\s+)?(?:table|view|index|function|procedure|trigger|type|schema)\b/i;
569
+ const SCHEMA_DECL_RE = /^\s*(?:message|service|rpc|enum|oneof|type|interface|input|union|scalar|query|mutation|subscription|extend\s+type)\s+[A-Za-z_]\w*/;
570
+ const CSS_DECL_RE = /^(?:@(?:media|keyframes|mixin|layer|supports|font-face)\b|[.#A-Za-z_*:\[][^{;]{0,100}\{\s*$)/;
571
+ const CONFIG_DECL_RE = /^(?:\[[^\]\n]{1,120}\]|"[^"\n]{1,100}"\s*:| "[^"\n]{1,100}"\s*:|[^\s":#;][^:\n]{0,80}\s*:(?:\s|$))/;
572
+
573
+ function matchCLine(
574
+ clean: string,
575
+ spans: readonly LineSpan[],
576
+ idx: number,
577
+ body: string,
578
+ trimmed: string,
579
+ braceBefore: number,
580
+ inTypeScope: boolean,
581
+ isHeader: boolean,
582
+ ): boolean {
583
+ if (CONTROL_KW_RE.test(trimmed)) return false;
584
+ const indented = body.charCodeAt(0) === 32 || body.charCodeAt(0) === 9;
585
+
586
+ if (!indented) {
587
+ if (C_SINGLE_DECL_RE.test(trimmed)) return true;
588
+ // Multi-line function signature or header prototype: `static int foo(\n int a\n) {`
589
+ if (C_QUALIFIED_SIG_START_RE.test(trimmed)) {
590
+ const tail = tailAfterBalancedParen(clean, spans, idx);
591
+ if (tail !== null && (tail.includes("{") || (isHeader && tail.startsWith(";")))) return true;
592
+ }
593
+ // Two-line return type + function name: previous non-empty line is a return type, current starts `name(`.
594
+ if (idx > 0 && C_CTOR_DTOR_START_RE.test(trimmed)) {
595
+ const prev = clean.slice(spans[idx - 1].start, spans[idx - 1].bodyEnd).replace(/\/\/.*$/, "").trim();
596
+ if (prev && !CONTROL_KW_RE.test(prev) && C_RETURN_TYPE_ONLY_RE.test(prev)) {
597
+ const tail = tailAfterBalancedParen(clean, spans, idx);
598
+ if (tail !== null && (tail.includes("{") || (isHeader && tail.startsWith(";")))) return true;
599
+ }
600
+ }
601
+ return false;
602
+ }
603
+
604
+ // Indented C++ declarations inside class/struct/namespace bodies (not deep inside function bodies).
605
+ if (C_INDENTED_TYPE_RE.test(body)) return true;
606
+ if (braceBefore >= 1 && braceBefore <= 2 && (C_QUALIFIED_SIG_START_RE.test(trimmed) || C_CTOR_DTOR_START_RE.test(trimmed))) {
607
+ // Reject obvious function calls like `foo(a, b);` in .c/.cpp; allow C++ constructors/methods inside type scopes
608
+ // or qualified methods/header declarations.
609
+ const tail = tailAfterBalancedParen(clean, spans, idx);
610
+ if (tail === null || /^(?:&&|\|\||\?|,|\.)/.test(tail)) return false;
611
+ if (inTypeScope && (tail.includes("{") || /^(?:const|override|final|noexcept|:\s*\S|= 0|= default|= delete)/.test(tail))) {
612
+ return true;
613
+ }
614
+ if (tail.includes("{") && !/^[A-Za-z_]\w*\s*\([^)]*\)\s*\{/.test(trimmed)) return true;
615
+ if (/^(?:virtual|static|inline|explicit|constexpr|friend)\b/.test(trimmed) && (tail.includes("{") || tail.startsWith(";") || /^(?:const|override|final|noexcept|= 0|= default|= delete)/.test(tail))) {
616
+ return true;
617
+ }
618
+ if (C_QUALIFIED_SIG_START_RE.test(trimmed) && (tail.includes("{") || (isHeader && (tail.startsWith(";") || /^(?:const|override|final|noexcept)/.test(tail))))) {
619
+ return true;
620
+ }
621
+ }
622
+ return false;
623
+ }
624
+
625
+ function isJsMethodTail(tail: string, isHeader: boolean): boolean {
626
+ if (tail.startsWith("{")) return true;
627
+ if (isHeader && tail.startsWith(";")) return true;
628
+ // TypeScript return type annotation before `{` (or `;` in `.d.ts`), excluding ternary calls like `foo(a) : bar({ ... })`.
629
+ if (tail.startsWith(":") && !/^:\s*[A-Za-z_$]\w*\s*\(/.test(tail)) {
630
+ return tail.includes("{") || (isHeader && tail.includes(";"));
631
+ }
632
+ return false;
633
+ }
634
+
635
+ function matchJsLine(
636
+ clean: string,
637
+ spans: readonly LineSpan[],
638
+ idx: number,
639
+ body: string,
640
+ trimmed: string,
641
+ braceBefore: number,
642
+ isMarkupScript: boolean,
643
+ isHeader: boolean,
644
+ ): boolean {
645
+ if (isMarkupScript && VUE_BLOCK_RE.test(trimmed)) return true;
646
+ if (CONTROL_KW_RE.test(trimmed)) return false;
647
+ if (JS_DECL_RE.test(body)) return true;
648
+ // Multi-line arrow function: `export const fn = async (\n a: number\n) =>`
649
+ if (JS_ARROW_START_RE.test(body)) {
650
+ const tail = tailAfterBalancedParen(clean, spans, idx);
651
+ if (tail !== null && tail.includes("=>")) return true;
652
+ }
653
+ // Single- or multi-line class/object method: ` async execute(\n ...\n): Promise<R> {`
654
+ if (braceBefore >= 1 && JS_METHOD_START_RE.test(body)) {
655
+ const tail = tailAfterBalancedParen(clean, spans, idx);
656
+ if (tail !== null && isJsMethodTail(tail, isHeader)) return true;
657
+ }
658
+ return false;
659
+ }
660
+
661
+ function matchJavaLine(
662
+ clean: string,
663
+ spans: readonly LineSpan[],
664
+ idx: number,
665
+ body: string,
666
+ trimmed: string,
667
+ ): boolean {
668
+ if (CONTROL_KW_RE.test(trimmed)) return false;
669
+ if (JAVA_TYPE_RE.test(body)) return true;
670
+ if (JAVA_METHOD_START_RE.test(body)) {
671
+ const tail = tailAfterBalancedParen(clean, spans, idx);
672
+ if (tail !== null && (tail.includes("{") || tail.startsWith(";") || /^(?:throws|where)\b/.test(tail))) return true;
673
+ }
674
+ return false;
675
+ }
676
+
677
+ const MAX_OUTLINE_ITEMS = 250;
678
+ const MAX_OUTLINE_LINE_LEN = 140;
679
+
680
+ export interface OutlineOptions {
681
+ /** Optional 1-based start line to paginate large outlines (>250 symbols). */
682
+ readonly offset?: number;
683
+ /** Optional maximum number of symbols to emit (clamped to MAX_OUTLINE_ITEMS). */
684
+ readonly limit?: number;
685
+ /** Optional compact encoding/EOL label (e.g. "GBK CRLF") surfaced in the outline header. */
686
+ readonly encodingLabel?: string;
687
+ }
688
+
689
+ interface OutlineHit {
690
+ readonly line: number;
691
+ readonly hash: string;
692
+ readonly display: string;
693
+ endLine?: number;
694
+ }
695
+
696
+ /**
697
+ * Produce a compact, deterministic structural outline with `<line>:<2-hex>|` Hashline anchors and exact `[..endLine]`
698
+ * block ranges for multi-line declarations. Supports offset/limit pagination on huge files.
699
+ */
700
+ export function buildFileOutline(
701
+ text: string,
702
+ filePath: string,
703
+ opts?: OutlineOptions,
704
+ ): { text: string; totalLines: number; symbols: number } {
705
+ const clean = stripLeadingBom(text);
706
+ const spans = indexLines(clean);
707
+ const totalLines = spans.length;
708
+ if (totalLines === 0) {
709
+ return { text: "[outline: 0 lines (empty file)]", totalLines: 0, symbols: 0 };
710
+ }
711
+
712
+ const { family: lang, isHeader, isMarkupScript } = detectLang(filePath);
713
+ const usesCStyleComments = C_STYLE_COMMENT_LANGS.has(lang);
714
+ const cState: CStyleState = {
715
+ commentDepth: 0,
716
+ braceDepth: 0,
717
+ multilineClose: null,
718
+ multilineEscape: false,
719
+ multilineDoubleQuoteEscape: false,
720
+ inMacroContinuation: false,
721
+ templateBraces: [],
722
+ typeScopeDepths: [],
723
+ pendingTypeScope: false,
724
+ };
725
+ let pyTriple: '"""' | "'''" | null = null;
726
+ let mdFenceChar = "";
727
+ let mdFenceLen = 0;
728
+
729
+ const minLine = opts?.offset && opts.offset > 1 ? Math.floor(opts.offset) : 1;
730
+ const maxItems = opts?.limit && opts.limit >= 1 ? Math.min(Math.floor(opts.limit), MAX_OUTLINE_ITEMS) : MAX_OUTLINE_ITEMS;
731
+
732
+ const hits: OutlineHit[] = [];
733
+ const openBraces: { hit: OutlineHit; targetDepth: number; opened: boolean }[] = [];
734
+ const openPyBlocks: { hit: OutlineHit; indent: number }[] = [];
735
+ let totalMatched = 0;
736
+ let totalVisible = 0;
737
+
738
+ for (let i = 0; i < totalLines; i++) {
739
+ const sp = spans[i];
740
+ const body = clean.slice(sp.start, sp.bodyEnd);
741
+ const trimmed = body.trimStart();
742
+
743
+ // Close Python indentation-scoped symbol ranges once indentation returns to <= header indent.
744
+ if (lang === "py" && trimmed && !trimmed.startsWith("#") && pyTriple === null && openPyBlocks.length > 0) {
745
+ const indent = body.length - trimmed.length;
746
+ while (openPyBlocks.length > 0 && indent <= openPyBlocks[openPyBlocks.length - 1].indent) {
747
+ const closed = openPyBlocks.pop()!;
748
+ let endLn = sp.line - 1;
749
+ while (endLn > closed.hit.line && clean.slice(spans[endLn - 1].start, spans[endLn - 1].bodyEnd).trim() === "") {
750
+ endLn--;
751
+ }
752
+ if (endLn > closed.hit.line) closed.hit.endLine = endLn;
753
+ }
754
+ }
755
+
756
+ // Language-specific block-state updates run on every line (even long lines) so state never drifts.
757
+ if (lang === "md") {
758
+ const fence = /^(`{3,}|~{3,})/.exec(trimmed);
759
+ if (fence) {
760
+ const ch = fence[1][0];
761
+ const len = fence[1].length;
762
+ if (!mdFenceChar) {
763
+ mdFenceChar = ch;
764
+ mdFenceLen = len;
765
+ continue;
766
+ }
767
+ if (ch === mdFenceChar && len >= mdFenceLen && trimmed.slice(len).trim() === "") {
768
+ mdFenceChar = "";
769
+ mdFenceLen = 0;
770
+ continue;
771
+ }
772
+ }
773
+ if (mdFenceChar) continue;
774
+ }
775
+
776
+ let braceBefore = 0;
777
+ let inTypeScope = false;
778
+ if (usesCStyleComments) {
779
+ const scan = scanCStyleLine(body, trimmed, cState, lang);
780
+ braceBefore = scan.braceBefore;
781
+ inTypeScope = scan.inTypeScope;
782
+ // Update any open brace-delimited symbol ranges whose block just opened or closed on this line.
783
+ for (let k = openBraces.length - 1; k >= 0; k--) {
784
+ const ob = openBraces[k];
785
+ if (!ob.opened && cState.braceDepth > ob.targetDepth) {
786
+ ob.opened = true;
787
+ } else if (!ob.opened && cState.braceDepth === ob.targetDepth && trimmed.includes(";")) {
788
+ openBraces.splice(k, 1);
789
+ continue;
790
+ }
791
+ if (ob.opened && cState.braceDepth <= ob.targetDepth) {
792
+ if (sp.line > ob.hit.line) ob.hit.endLine = sp.line;
793
+ openBraces.splice(k, 1);
794
+ }
795
+ }
796
+ if (scan.startedInBlock || !scan.hasCode) continue;
797
+ }
798
+
799
+ if (lang === "py") {
800
+ const scan = scanPythonLine(body, pyTriple);
801
+ pyTriple = scan.nextTriple;
802
+ if (scan.startedInTriple) continue;
803
+ }
804
+
805
+ if (!trimmed || body.length > 400) continue;
806
+
807
+ let matched = false;
808
+ switch (lang) {
809
+ case "c":
810
+ matched = matchCLine(clean, spans, i, body, trimmed, braceBefore, inTypeScope, isHeader);
811
+ break;
812
+ case "js":
813
+ matched = matchJsLine(clean, spans, i, body, trimmed, braceBefore, isMarkupScript, isHeader);
814
+ break;
815
+ case "py":
816
+ matched = PY_DECL_RE.test(body);
817
+ break;
818
+ case "java":
819
+ matched = matchJavaLine(clean, spans, i, body, trimmed);
820
+ break;
821
+ case "go":
822
+ matched = GO_DECL_RE.test(body);
823
+ break;
824
+ case "rust":
825
+ matched = RUST_DECL_RE.test(body);
826
+ break;
827
+ case "md":
828
+ matched = MD_DECL_RE.test(body);
829
+ break;
830
+ case "shell":
831
+ matched = !trimmed.startsWith("#") && SHELL_DECL_RE.test(body);
832
+ break;
833
+ case "cmake":
834
+ matched = !trimmed.startsWith("#") && CMAKE_DECL_RE.test(trimmed);
835
+ break;
836
+ case "ruby":
837
+ matched = !trimmed.startsWith("#") && RUBY_DECL_RE.test(body);
838
+ break;
839
+ case "lua":
840
+ matched = !trimmed.startsWith("--") && LUA_DECL_RE.test(body);
841
+ break;
842
+ case "elixir":
843
+ matched = !trimmed.startsWith("#") && ELIXIR_DECL_RE.test(body);
844
+ break;
845
+ case "sql":
846
+ matched = !trimmed.startsWith("--") && SQL_DECL_RE.test(body);
847
+ break;
848
+ case "schema":
849
+ matched = !trimmed.startsWith("#") && SCHEMA_DECL_RE.test(body);
850
+ break;
851
+ case "css":
852
+ matched = braceBefore === 0 && CSS_DECL_RE.test(body);
853
+ break;
854
+ case "config":
855
+ matched = !trimmed.startsWith("#") && !trimmed.startsWith(";") && !trimmed.startsWith("//") && CONFIG_DECL_RE.test(body);
856
+ break;
857
+ default:
858
+ matched = MD_DECL_RE.test(body) || /^(?:export\s+)?(?:async\s+)?(?:function|class|def|func|fn|struct|interface|type)\s+\w+/.test(trimmed);
859
+ break;
860
+ }
861
+
862
+ if (matched) {
863
+ totalMatched++;
864
+ if (sp.line >= minLine) {
865
+ totalVisible++;
866
+ if (hits.length < maxItems) {
867
+ const display = body.length > MAX_OUTLINE_LINE_LEN ? body.slice(0, MAX_OUTLINE_LINE_LEN - 1) + "…" : body;
868
+ const hit: OutlineHit = { line: sp.line, hash: lineHash(body), display };
869
+ hits.push(hit);
870
+ if (usesCStyleComments) {
871
+ const openedOnLine = cState.braceDepth > braceBefore;
872
+ const hasSingleLineBody = !openedOnLine && body.includes("{") && body.includes("}");
873
+ if (!hasSingleLineBody && !trimmed.startsWith("#")) {
874
+ openBraces.push({ hit, targetDepth: braceBefore, opened: openedOnLine });
875
+ }
876
+ } else if (lang === "py") {
877
+ openPyBlocks.push({ hit, indent: body.length - trimmed.length });
878
+ }
879
+ }
880
+ }
881
+ }
882
+ }
883
+
884
+ // Close any Python blocks reaching EOF.
885
+ if (lang === "py" && openPyBlocks.length > 0) {
886
+ let lastNonEmpty = totalLines;
887
+ while (lastNonEmpty > 1 && clean.slice(spans[lastNonEmpty - 1].start, spans[lastNonEmpty - 1].bodyEnd).trim() === "") {
888
+ lastNonEmpty--;
889
+ }
890
+ for (const ob of openPyBlocks) {
891
+ if (lastNonEmpty > ob.hit.line) ob.hit.endLine = lastNonEmpty;
892
+ }
893
+ }
894
+
895
+ const encTag = opts?.encodingLabel ? ` · ${opts.encodingLabel}` : "";
896
+ if (hits.length === 0) {
897
+ if (minLine > 1 && totalMatched > 0) {
898
+ return {
899
+ text: `[outline: no symbols from L${minLine}..${totalLines} (${totalMatched} total symbols${encTag})]`,
900
+ totalLines,
901
+ symbols: totalMatched,
902
+ };
903
+ }
904
+ // Fallback for plain data/prose files: emit first 10 lines with anchors so caller still gets orientation cheaply.
905
+ const headCount = Math.min(10, totalLines);
906
+ const sample: string[] = [];
907
+ for (let i = 0; i < headCount; i++) {
908
+ const sp = spans[i];
909
+ const body = clean.slice(sp.start, sp.bodyEnd);
910
+ const display = body.length > MAX_OUTLINE_LINE_LEN ? body.slice(0, MAX_OUTLINE_LINE_LEN - 1) + "…" : body;
911
+ sample.push(`${sp.line}:${lineHash(body)}|${display}`);
912
+ }
913
+ const footer = totalLines > headCount ? `\n[outline: no symbols in ${totalLines} lines${encTag}; showing L1..${headCount}. Use ranges or offset/limit.]` : "";
914
+ return { text: sample.join("\n") + footer, totalLines, symbols: 0 };
915
+ }
916
+
917
+ const formatted = hits.map((h) => `${h.line}:${h.hash}|${h.display}${h.endLine ? ` [..${h.endLine}]` : ""}`);
918
+ const omitted = totalVisible - hits.length;
919
+ const nextOffset = omitted > 0 ? hits[hits.length - 1].line + 1 : 0;
920
+ const extra = omitted > 0 ? `\n... (${omitted} more symbols omitted; pass offset=${nextOffset})` : "";
921
+ const rangeTag = minLine > 1 ? ` from L${minLine}` : "";
922
+ const header = `[outline: ${totalLines} lines, ${totalMatched} symbols${rangeTag}${encTag}; use read(ranges) or edit(hashlines)]`;
923
+ return { text: `${header}\n${formatted.join("\n")}${extra}`, totalLines, symbols: totalMatched };
924
+ }