@parall/cli 1.59.0 → 1.61.0

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 (53) hide show
  1. package/dist/commands/agents.d.ts +9 -0
  2. package/dist/commands/agents.d.ts.map +1 -1
  3. package/dist/commands/agents.js +288 -8
  4. package/dist/commands/approvals.d.ts.map +1 -1
  5. package/dist/commands/approvals.js +19 -0
  6. package/dist/commands/chats.d.ts.map +1 -1
  7. package/dist/commands/chats.js +84 -0
  8. package/dist/commands/comments.d.ts +3 -0
  9. package/dist/commands/comments.d.ts.map +1 -1
  10. package/dist/commands/comments.js +44 -1
  11. package/dist/commands/labels.d.ts +5 -0
  12. package/dist/commands/labels.d.ts.map +1 -0
  13. package/dist/commands/labels.js +114 -0
  14. package/dist/commands/messages.d.ts.map +1 -1
  15. package/dist/commands/messages.js +35 -0
  16. package/dist/commands/projects.d.ts.map +1 -1
  17. package/dist/commands/projects.js +4 -2
  18. package/dist/commands/search.d.ts +5 -0
  19. package/dist/commands/search.d.ts.map +1 -1
  20. package/dist/commands/search.js +28 -1
  21. package/dist/commands/tasks.d.ts +13 -3
  22. package/dist/commands/tasks.d.ts.map +1 -1
  23. package/dist/commands/tasks.js +214 -8
  24. package/dist/commands/watch.d.ts.map +1 -1
  25. package/dist/commands/watch.js +7 -5
  26. package/dist/commands/wiki-comments.d.ts +6 -0
  27. package/dist/commands/wiki-comments.d.ts.map +1 -0
  28. package/dist/commands/wiki-comments.js +108 -0
  29. package/dist/commands/wiki.d.ts.map +1 -1
  30. package/dist/commands/wiki.js +2 -98
  31. package/dist/index.js +2 -0
  32. package/dist/lib/wiki-index.d.ts +67 -0
  33. package/dist/lib/wiki-index.d.ts.map +1 -0
  34. package/dist/lib/wiki-index.js +758 -0
  35. package/dist/lib/wiki-merge.d.ts +113 -6
  36. package/dist/lib/wiki-merge.d.ts.map +1 -1
  37. package/dist/lib/wiki-merge.js +236 -31
  38. package/dist/lib/wiki-propose.d.ts +43 -0
  39. package/dist/lib/wiki-propose.d.ts.map +1 -0
  40. package/dist/lib/wiki-propose.js +335 -0
  41. package/dist/lib/wiki-shared.d.ts +291 -0
  42. package/dist/lib/wiki-shared.d.ts.map +1 -0
  43. package/dist/lib/wiki-shared.js +407 -0
  44. package/dist/lib/wiki-sync.d.ts +109 -0
  45. package/dist/lib/wiki-sync.d.ts.map +1 -0
  46. package/dist/lib/wiki-sync.js +637 -0
  47. package/dist/lib/wiki-workspace.d.ts +58 -0
  48. package/dist/lib/wiki-workspace.d.ts.map +1 -0
  49. package/dist/lib/wiki-workspace.js +255 -0
  50. package/dist/lib/wiki.d.ts +6 -312
  51. package/dist/lib/wiki.d.ts.map +1 -1
  52. package/dist/lib/wiki.js +53 -2208
  53. package/package.json +4 -4
@@ -0,0 +1,758 @@
1
+ // Local wiki content index: node-section artifacts, search / query scoring,
2
+ // markdown heading parsing and the CJK-aware tokenizer.
3
+ // Entry point for consumers is ./wiki.ts, which re-exports the public surface.
4
+ import { promises as fs } from 'node:fs';
5
+ import path from 'node:path';
6
+ import { hasFrontMatter, parseFrontMatter } from './wiki-frontmatter.js';
7
+ import { PRLL_WIKI_DIR, compactWhitespace, enforceAllowedPrefix, matchesAllowedPrefix, normalizeRef, normalizeRequiredWikiPath, normalizeWikiPath, resolveLocalWikiMount, resolvePathInsideRoot, truncateSnippet, walkLocalMarkdownFiles, } from './wiki-shared.js';
8
+ /** Local wiki mount resolved from mount manifest V2 (REST-based). */
9
+ const MARKDOWN_HEADING_RE = /^\s{0,3}(#{1,6})[ \t]+(.+?)\s*$/;
10
+ const TRAILING_FENCE_RE = /\s+#+\s*$/;
11
+ // Bumped 2 → 3 for the frontmatter (type/description/tags) fields: invalidates
12
+ // caches built before frontmatter parsing so existing local mounts re-parse and
13
+ // pick up the metadata even when a file's size / mtime is unchanged.
14
+ const LOCAL_NODE_SECTION_ARTIFACT_VERSION = 3;
15
+ // ---------------------------------------------------------------------------
16
+ // Node section loading (unchanged logic, adapts to REST mount)
17
+ // ---------------------------------------------------------------------------
18
+ export async function loadWikiNodeSections(ctx, wiki, options = {}) {
19
+ const normalizedRef = normalizeRef(options.ref);
20
+ const normalizedPrefix = normalizeWikiPath(options.pathPrefix);
21
+ if (!normalizedRef) {
22
+ const local = await tryLoadLocalNodeSections(ctx, wiki, normalizedPrefix);
23
+ if (local) {
24
+ const sections = filterNodeSectionsByPathPrefix(flattenLocalNodeSectionFiles(local.files), normalizedPrefix);
25
+ return {
26
+ kind: 'local_mount',
27
+ generatedAt: local.generated_at,
28
+ fileCount: countMatchingMarkdownFiles(local.files, normalizedPrefix),
29
+ sections,
30
+ };
31
+ }
32
+ }
33
+ const artifact = await ctx.client.getWikiNodeSections(ctx.orgId, wiki.id, { ref: normalizedRef });
34
+ const sections = filterNodeSectionsByPathPrefix(artifact.nodes, normalizedPrefix);
35
+ return {
36
+ kind: 'api',
37
+ generatedAt: artifact.generated_at,
38
+ fileCount: countMatchingSectionFiles(artifact.nodes, normalizedPrefix),
39
+ sections,
40
+ };
41
+ }
42
+ export async function tryLoadLocalNodeSections(ctx, wiki, pathPrefix) {
43
+ const mount = await resolveLocalWikiMount(ctx, wiki);
44
+ if (!mount) {
45
+ return null;
46
+ }
47
+ if (pathPrefix) {
48
+ enforceAllowedPrefix(pathPrefix, []);
49
+ }
50
+ return loadOrBuildLocalNodeSectionArtifact(wiki, mount);
51
+ }
52
+ async function loadOrBuildLocalNodeSectionArtifact(wiki, mount) {
53
+ const artifactPath = path.join(mount.root, PRLL_WIKI_DIR, 'node-sections.json');
54
+ const descriptors = await collectLocalMarkdownDescriptors(mount.root, []);
55
+ const cached = await readLocalNodeSectionArtifact(artifactPath);
56
+ const artifact = {
57
+ version: LOCAL_NODE_SECTION_ARTIFACT_VERSION,
58
+ generated_at: new Date().toISOString(),
59
+ wiki_id: wiki.id,
60
+ wiki_slug: wiki.slug,
61
+ wiki_name: wiki.name,
62
+ file_count: descriptors.length,
63
+ files: await buildLocalNodeSectionFiles(wiki, mount.root, descriptors, cached),
64
+ };
65
+ await fs.mkdir(path.dirname(artifactPath), { recursive: true });
66
+ await fs.writeFile(artifactPath, JSON.stringify(artifact, null, 2), 'utf8');
67
+ return artifact;
68
+ }
69
+ async function readLocalNodeSectionArtifact(artifactPath) {
70
+ try {
71
+ const raw = await fs.readFile(artifactPath, 'utf8');
72
+ return JSON.parse(raw);
73
+ }
74
+ catch {
75
+ return null;
76
+ }
77
+ }
78
+ async function collectLocalMarkdownDescriptors(root, allowedPrefixes) {
79
+ const descriptors = [];
80
+ await walkLocalMarkdownFiles(root, root, async (fullPath, relativePath) => {
81
+ if (!matchesAllowedPrefix(relativePath, allowedPrefixes)) {
82
+ return;
83
+ }
84
+ const stat = await fs.stat(fullPath);
85
+ descriptors.push({
86
+ path: relativePath,
87
+ size: stat.size,
88
+ mtime_ms: stat.mtimeMs,
89
+ });
90
+ });
91
+ return descriptors.sort((a, b) => a.path.localeCompare(b.path));
92
+ }
93
+ async function buildLocalNodeSectionFiles(wiki, root, descriptors, cached) {
94
+ const cachedByPath = new Map();
95
+ if (cached &&
96
+ cached.version === LOCAL_NODE_SECTION_ARTIFACT_VERSION &&
97
+ cached.wiki_id === wiki.id &&
98
+ cached.wiki_slug === wiki.slug &&
99
+ cached.wiki_name === wiki.name) {
100
+ for (const file of cached.files) {
101
+ cachedByPath.set(file.path, file);
102
+ }
103
+ }
104
+ const files = [];
105
+ for (const descriptor of descriptors) {
106
+ const existing = cachedByPath.get(descriptor.path);
107
+ if (existing &&
108
+ existing.size === descriptor.size &&
109
+ existing.mtime_ms === descriptor.mtime_ms) {
110
+ files.push(existing);
111
+ continue;
112
+ }
113
+ const content = await fs.readFile(resolvePathInsideRoot(root, descriptor.path), 'utf8');
114
+ files.push({
115
+ ...descriptor,
116
+ nodes: parseMarkdownFile(wiki, {
117
+ path: descriptor.path,
118
+ content,
119
+ }),
120
+ });
121
+ }
122
+ return files.sort((a, b) => a.path.localeCompare(b.path));
123
+ }
124
+ function flattenLocalNodeSectionFiles(files) {
125
+ const sections = [];
126
+ for (const file of files) {
127
+ sections.push(...file.nodes);
128
+ }
129
+ sections.sort((a, b) => {
130
+ if (a.path === b.path) {
131
+ return a.start_line - b.start_line;
132
+ }
133
+ return a.path.localeCompare(b.path);
134
+ });
135
+ return sections;
136
+ }
137
+ export function findLocalNodeSection(artifact, nodeId) {
138
+ for (const file of artifact.files) {
139
+ const node = file.nodes.find((entry) => entry.node_id === nodeId);
140
+ if (node) {
141
+ return node;
142
+ }
143
+ }
144
+ return undefined;
145
+ }
146
+ function filterNodeSectionsByPathPrefix(sections, pathPrefix) {
147
+ if (!pathPrefix) {
148
+ return sections;
149
+ }
150
+ return sections.filter((section) => section.path === pathPrefix || section.path.startsWith(`${pathPrefix}/`));
151
+ }
152
+ function countMatchingMarkdownFiles(files, pathPrefix) {
153
+ if (!pathPrefix) {
154
+ return files.length;
155
+ }
156
+ return files.filter((file) => file.path === pathPrefix || file.path.startsWith(`${pathPrefix}/`))
157
+ .length;
158
+ }
159
+ function countMatchingSectionFiles(sections, pathPrefix) {
160
+ const paths = new Set();
161
+ for (const section of sections) {
162
+ if (!pathPrefix || section.path === pathPrefix || section.path.startsWith(`${pathPrefix}/`)) {
163
+ paths.add(section.path);
164
+ }
165
+ }
166
+ return paths.size;
167
+ }
168
+ // ---------------------------------------------------------------------------
169
+ // Search & index engine (unchanged)
170
+ // ---------------------------------------------------------------------------
171
+ export function stripNodeSectionContent(section) {
172
+ const { content: _content, ...node } = section;
173
+ return node;
174
+ }
175
+ export function buildIndexNodes(sections) {
176
+ const nodes = [];
177
+ // File-level frontmatter folds into only the first section of each file
178
+ // (matching the indexed search-indexer's section-0 gating) so a
179
+ // frontmatter-only query returns one hit per document, not one per section.
180
+ const seenFile = new Set();
181
+ for (const section of sections) {
182
+ const includeFrontmatter = !seenFile.has(section.path);
183
+ seenFile.add(section.path);
184
+ nodes.push(buildIndexedNode(section, includeFrontmatter));
185
+ }
186
+ return nodes;
187
+ }
188
+ export function parseMarkdownFile(wiki, file) {
189
+ const lines = file.content.split('\n');
190
+ const frontMatterEnd = detectFrontMatterEnd(lines);
191
+ const fm = parseFrontMatter(lines, frontMatterEnd);
192
+ const headings = extractMarkdownHeadings(lines, frontMatterEnd);
193
+ const fileTitle = defaultFileTitle(file.path);
194
+ if (headings.length === 0) {
195
+ const docNode = buildNodeSection(wiki, {
196
+ nodeId: `${file.path}:doc`,
197
+ path: file.path,
198
+ title: fileTitle,
199
+ headingPath: [],
200
+ level: 0,
201
+ startLine: findFirstNonEmptyLine(lines, frontMatterEnd + 1, lines.length),
202
+ endLine: lines.length,
203
+ content: lines.slice(frontMatterEnd).join('\n').trim(),
204
+ });
205
+ // Keep an empty-body doc node when it carries frontmatter, so a
206
+ // frontmatter-only page still exposes its metadata — matching the Go
207
+ // parser, which always returns the doc section for a no-heading file.
208
+ const keep = !!docNode.content || hasFrontMatter(fm);
209
+ return applyFrontMatter(keep ? [docNode] : [], fm);
210
+ }
211
+ const nodes = [];
212
+ const firstHeadingLine = headings[0].line;
213
+ const preface = lines
214
+ .slice(frontMatterEnd, firstHeadingLine - 1)
215
+ .join('\n')
216
+ .trim();
217
+ if (preface) {
218
+ nodes.push(buildNodeSection(wiki, {
219
+ nodeId: `${file.path}:preface`,
220
+ path: file.path,
221
+ title: fileTitle,
222
+ headingPath: [],
223
+ level: 0,
224
+ startLine: findFirstNonEmptyLine(lines, frontMatterEnd + 1, firstHeadingLine - 1),
225
+ endLine: firstHeadingLine - 1,
226
+ content: preface,
227
+ }));
228
+ }
229
+ for (let i = 0; i < headings.length; i += 1) {
230
+ const current = headings[i];
231
+ const nextLine = i + 1 < headings.length ? headings[i + 1].line : lines.length + 1;
232
+ nodes.push(buildNodeSection(wiki, {
233
+ nodeId: `${file.path}:L${current.line}`,
234
+ path: file.path,
235
+ title: current.title,
236
+ headingPath: current.path,
237
+ level: current.level,
238
+ startLine: current.line,
239
+ endLine: nextLine - 1,
240
+ content: lines
241
+ .slice(current.line, nextLine - 1)
242
+ .join('\n')
243
+ .trim(),
244
+ }));
245
+ }
246
+ return applyFrontMatter(nodes, fm);
247
+ }
248
+ // applyFrontMatter copies file-level frontmatter onto every section parsed from
249
+ // the file (frontmatter is a document-level property in OKF). Mirrors the Go
250
+ // implementation in server/pkg/markdown/section.go. No-op when empty.
251
+ function applyFrontMatter(sections, fm) {
252
+ if (!hasFrontMatter(fm)) {
253
+ return sections;
254
+ }
255
+ for (const section of sections) {
256
+ if (fm.type !== undefined)
257
+ section.type = fm.type;
258
+ if (fm.description !== undefined)
259
+ section.description = fm.description;
260
+ if (fm.tags !== undefined)
261
+ section.tags = fm.tags;
262
+ }
263
+ return sections;
264
+ }
265
+ function buildNodeSection(wiki, input) {
266
+ const content = input.content.trim();
267
+ const sectionPath = input.headingPath.length > 0 ? `${input.path} > ${input.headingPath.join(' > ')}` : input.path;
268
+ return {
269
+ wiki_id: wiki.id,
270
+ wiki_slug: wiki.slug,
271
+ wiki_name: wiki.name,
272
+ node_id: input.nodeId,
273
+ path: input.path,
274
+ title: input.title,
275
+ heading_path: input.headingPath.length > 0 ? [...input.headingPath] : undefined,
276
+ section_path: sectionPath,
277
+ level: input.level,
278
+ start_line: input.startLine,
279
+ end_line: input.endLine,
280
+ content,
281
+ };
282
+ }
283
+ function buildIndexedNode(section, includeFrontmatter) {
284
+ const searchText = [
285
+ section.path,
286
+ section.title,
287
+ section.heading_path?.join(' ') ?? '',
288
+ ...(includeFrontmatter
289
+ ? [section.type ?? '', section.description ?? '', section.tags?.join(' ') ?? '']
290
+ : []),
291
+ section.content,
292
+ ]
293
+ .join('\n')
294
+ .trim();
295
+ const termFreq = new Map();
296
+ const tokens = tokenize(searchText);
297
+ for (const token of tokens) {
298
+ termFreq.set(token, (termFreq.get(token) ?? 0) + 1);
299
+ }
300
+ return {
301
+ section,
302
+ content: section.content,
303
+ lowerPath: section.path.toLowerCase(),
304
+ lowerTitle: section.title.toLowerCase(),
305
+ lowerBody: section.content.toLowerCase(),
306
+ lowerJoined: section.section_path.toLowerCase(),
307
+ termFreq,
308
+ docLen: tokens.length,
309
+ };
310
+ }
311
+ export function scoreNodes(nodes, query, options) {
312
+ const queryTokens = tokenize(query);
313
+ if (queryTokens.length === 0) {
314
+ throw new Error('query did not contain searchable terms');
315
+ }
316
+ const docFreq = new Map();
317
+ let totalDocLen = 0;
318
+ for (const node of nodes) {
319
+ totalDocLen += node.docLen;
320
+ for (const token of node.termFreq.keys()) {
321
+ docFreq.set(token, (docFreq.get(token) ?? 0) + 1);
322
+ }
323
+ }
324
+ const avgDocLen = nodes.length > 0 ? Math.max(totalDocLen / nodes.length, 1) : 1;
325
+ const lowerQuery = query.toLowerCase();
326
+ const limit = options.limit && options.limit > 0 ? options.limit : 5;
327
+ const results = [];
328
+ for (const node of nodes) {
329
+ const score = scoreNode(node, queryTokens, lowerQuery, docFreq, nodes.length, avgDocLen);
330
+ if (score <= 0) {
331
+ continue;
332
+ }
333
+ results.push({
334
+ ...stripNodeSectionContent(node.section),
335
+ score,
336
+ snippet: buildSnippet(node, lowerQuery, queryTokens),
337
+ content: options.includeContent ? node.content : undefined,
338
+ source: options.source,
339
+ });
340
+ }
341
+ results.sort((a, b) => {
342
+ if (b.score === a.score) {
343
+ if (a.path === b.path) {
344
+ return a.start_line - b.start_line;
345
+ }
346
+ return a.path.localeCompare(b.path);
347
+ }
348
+ return b.score - a.score;
349
+ });
350
+ return results.slice(0, limit);
351
+ }
352
+ export function planWikiQuery(sections, query, options) {
353
+ const queryTokens = tokenize(query);
354
+ if (queryTokens.length === 0) {
355
+ throw new Error('query did not contain searchable terms');
356
+ }
357
+ const lowerQuery = query.toLowerCase();
358
+ const limit = options.limit && options.limit > 0 ? options.limit : 5;
359
+ const documents = buildIndexedDocuments(sections);
360
+ const rankedDocuments = scoreDocuments(documents, queryTokens, lowerQuery)
361
+ .filter((entry) => entry.score > 0)
362
+ .sort((a, b) => {
363
+ if (b.score === a.score) {
364
+ return a.document.path.localeCompare(b.document.path);
365
+ }
366
+ return b.score - a.score;
367
+ });
368
+ const shortlistedDocuments = rankedDocuments.slice(0, Math.max(limit * 2, 3));
369
+ const shortlistedNodes = buildIndexNodes(shortlistedDocuments.flatMap((entry) => entry.document.sections));
370
+ const docScoreByPath = new Map(shortlistedDocuments.map((entry) => [entry.document.path, entry.score]));
371
+ const results = [];
372
+ for (const node of shortlistedNodes) {
373
+ const documentScore = docScoreByPath.get(node.section.path) ?? 0;
374
+ const plan = scoreTreeAwareNode(node, queryTokens, lowerQuery, documentScore, shortlistedNodes);
375
+ if (plan.score <= 0) {
376
+ continue;
377
+ }
378
+ results.push({
379
+ ...stripNodeSectionContent(node.section),
380
+ score: plan.score,
381
+ document_score: documentScore,
382
+ snippet: buildSnippet(node, lowerQuery, queryTokens),
383
+ content: options.includeContent ? node.content : undefined,
384
+ source: options.source,
385
+ reasoning: plan.reasoning,
386
+ });
387
+ }
388
+ results.sort((a, b) => {
389
+ if (b.score === a.score) {
390
+ if (a.path === b.path) {
391
+ return a.start_line - b.start_line;
392
+ }
393
+ return a.path.localeCompare(b.path);
394
+ }
395
+ return b.score - a.score;
396
+ });
397
+ return {
398
+ documents: shortlistedDocuments.map(({ document, score }) => ({
399
+ path: document.path,
400
+ title: document.title,
401
+ score,
402
+ matched_headings: findMatchedHeadings(document, lowerQuery, queryTokens),
403
+ node_count: document.sections.length,
404
+ })),
405
+ sections: results.slice(0, limit),
406
+ };
407
+ }
408
+ function buildIndexedDocuments(sections) {
409
+ const byPath = new Map();
410
+ for (const section of sections) {
411
+ const bucket = byPath.get(section.path);
412
+ if (bucket) {
413
+ bucket.push(section);
414
+ }
415
+ else {
416
+ byPath.set(section.path, [section]);
417
+ }
418
+ }
419
+ const documents = [];
420
+ for (const [filePath, fileSections] of byPath.entries()) {
421
+ fileSections.sort((a, b) => a.start_line - b.start_line);
422
+ const headings = Array.from(new Set(fileSections.flatMap((section) => section.heading_path ?? []).filter(Boolean)));
423
+ const title = fileSections.find((section) => section.level === 0)?.title ?? defaultFileTitle(filePath);
424
+ const searchText = [filePath, title, headings.join(' ')].join('\n').trim();
425
+ const tokens = tokenize(searchText);
426
+ const termFreq = new Map();
427
+ for (const token of tokens) {
428
+ termFreq.set(token, (termFreq.get(token) ?? 0) + 1);
429
+ }
430
+ documents.push({
431
+ path: filePath,
432
+ title,
433
+ sections: fileSections,
434
+ lowerPath: filePath.toLowerCase(),
435
+ lowerTitle: title.toLowerCase(),
436
+ lowerJoined: `${filePath} ${title} ${headings.join(' ')}`.toLowerCase(),
437
+ headings,
438
+ termFreq,
439
+ docLen: tokens.length,
440
+ });
441
+ }
442
+ documents.sort((a, b) => a.path.localeCompare(b.path));
443
+ return documents;
444
+ }
445
+ function scoreDocuments(documents, queryTokens, lowerQuery) {
446
+ const docFreq = new Map();
447
+ let totalDocLen = 0;
448
+ for (const document of documents) {
449
+ totalDocLen += document.docLen;
450
+ for (const token of document.termFreq.keys()) {
451
+ docFreq.set(token, (docFreq.get(token) ?? 0) + 1);
452
+ }
453
+ }
454
+ const avgDocLen = documents.length > 0 ? Math.max(totalDocLen / documents.length, 1) : 1;
455
+ return documents.map((document) => {
456
+ const pseudoNode = {
457
+ section: {
458
+ wiki_id: document.sections[0]?.wiki_id ?? '',
459
+ wiki_slug: document.sections[0]?.wiki_slug ?? '',
460
+ wiki_name: document.sections[0]?.wiki_name ?? '',
461
+ node_id: `${document.path}:doc`,
462
+ path: document.path,
463
+ title: document.title,
464
+ heading_path: document.headings,
465
+ section_path: document.path,
466
+ level: 0,
467
+ start_line: 1,
468
+ end_line: 1,
469
+ content: '',
470
+ },
471
+ content: '',
472
+ lowerPath: document.lowerPath,
473
+ lowerTitle: document.lowerTitle,
474
+ lowerBody: '',
475
+ lowerJoined: document.lowerJoined,
476
+ termFreq: document.termFreq,
477
+ docLen: document.docLen,
478
+ };
479
+ return {
480
+ document,
481
+ score: scoreNode(pseudoNode, queryTokens, lowerQuery, docFreq, documents.length, avgDocLen),
482
+ };
483
+ });
484
+ }
485
+ function scoreTreeAwareNode(node, queryTokens, lowerQuery, documentScore, scope) {
486
+ const docFreq = new Map();
487
+ let totalDocLen = 0;
488
+ for (const entry of scope) {
489
+ totalDocLen += entry.docLen;
490
+ for (const token of entry.termFreq.keys()) {
491
+ docFreq.set(token, (docFreq.get(token) ?? 0) + 1);
492
+ }
493
+ }
494
+ const avgDocLen = scope.length > 0 ? Math.max(totalDocLen / scope.length, 1) : 1;
495
+ let score = scoreNode(node, queryTokens, lowerQuery, docFreq, scope.length, avgDocLen);
496
+ const reasoning = [];
497
+ if (documentScore > 0) {
498
+ score += documentScore * 0.35;
499
+ reasoning.push('selected from a high-scoring document');
500
+ }
501
+ if (lowerQuery && node.lowerTitle.includes(lowerQuery)) {
502
+ score += 2.5;
503
+ reasoning.push('section title directly matches the query');
504
+ }
505
+ const matchedAncestors = (node.section.heading_path ?? [])
506
+ .slice(0, -1)
507
+ .filter((heading) => heading.toLowerCase().includes(lowerQuery) ||
508
+ queryTokens.some((token) => heading.toLowerCase().includes(token)));
509
+ if (matchedAncestors.length > 0) {
510
+ score += matchedAncestors.length * 1.25;
511
+ reasoning.push('ancestor headings match the query context');
512
+ }
513
+ const headingTokenHits = queryTokens.filter((token) => (node.section.heading_path ?? []).some((heading) => heading.toLowerCase().includes(token))).length;
514
+ if (headingTokenHits > 0) {
515
+ score += headingTokenHits * 0.6;
516
+ reasoning.push('heading path overlaps with query terms');
517
+ }
518
+ if (node.section.level > 0 && node.section.level <= 2) {
519
+ score += 0.2;
520
+ }
521
+ return { score, reasoning };
522
+ }
523
+ function findMatchedHeadings(document, lowerQuery, queryTokens) {
524
+ return document.headings
525
+ .filter((heading) => {
526
+ const lower = heading.toLowerCase();
527
+ return ((lowerQuery && lower.includes(lowerQuery)) ||
528
+ queryTokens.some((token) => lower.includes(token)));
529
+ })
530
+ .slice(0, 5);
531
+ }
532
+ function scoreNode(node, queryTokens, lowerQuery, docFreq, totalDocs, avgDocLen) {
533
+ const k1 = 1.5;
534
+ const b = 0.75;
535
+ const docLen = Math.max(node.docLen, 1);
536
+ let score = 0;
537
+ for (const token of queryTokens) {
538
+ const tf = node.termFreq.get(token) ?? 0;
539
+ if (tf === 0) {
540
+ continue;
541
+ }
542
+ const df = docFreq.get(token) ?? 0;
543
+ if (df === 0) {
544
+ continue;
545
+ }
546
+ const idf = Math.log(1 + (totalDocs - df + 0.5) / (df + 0.5));
547
+ score += idf * ((tf * (k1 + 1)) / (tf + k1 * (1 - b + b * (docLen / avgDocLen))));
548
+ }
549
+ if (lowerQuery) {
550
+ if (node.lowerTitle.includes(lowerQuery)) {
551
+ score += 3;
552
+ }
553
+ else if (node.lowerJoined.includes(lowerQuery)) {
554
+ score += 2;
555
+ }
556
+ else if (node.lowerPath.includes(lowerQuery)) {
557
+ score += 1.5;
558
+ }
559
+ if (node.lowerBody.includes(lowerQuery)) {
560
+ score += 1;
561
+ }
562
+ }
563
+ return score;
564
+ }
565
+ function buildSnippet(node, lowerQuery, queryTokens) {
566
+ const lines = [node.section.title, ...node.content.split('\n')];
567
+ for (const line of lines) {
568
+ const compact = compactWhitespace(line);
569
+ if (!compact) {
570
+ continue;
571
+ }
572
+ const lower = compact.toLowerCase();
573
+ if (lowerQuery && lower.includes(lowerQuery)) {
574
+ return truncateSnippet(compact, 220);
575
+ }
576
+ }
577
+ for (const line of lines) {
578
+ const compact = compactWhitespace(line);
579
+ if (!compact) {
580
+ continue;
581
+ }
582
+ const lower = compact.toLowerCase();
583
+ if (queryTokens.some((token) => lower.includes(token))) {
584
+ return truncateSnippet(compact, 220);
585
+ }
586
+ }
587
+ return truncateSnippet(compactWhitespace(node.content || node.section.section_path), 220);
588
+ }
589
+ // ---------------------------------------------------------------------------
590
+ // Markdown parsing helpers
591
+ // ---------------------------------------------------------------------------
592
+ function extractMarkdownHeadings(lines, startIndex) {
593
+ const headings = [];
594
+ const stack = [];
595
+ let fenceMarker = '';
596
+ for (let i = startIndex; i < lines.length; i += 1) {
597
+ const trimmed = lines[i].trim();
598
+ const marker = parseFenceMarker(trimmed);
599
+ if (marker) {
600
+ if (!fenceMarker) {
601
+ fenceMarker = marker;
602
+ }
603
+ else if (trimmed.startsWith(fenceMarker)) {
604
+ fenceMarker = '';
605
+ }
606
+ continue;
607
+ }
608
+ if (fenceMarker) {
609
+ continue;
610
+ }
611
+ const match = lines[i].match(MARKDOWN_HEADING_RE);
612
+ if (!match) {
613
+ continue;
614
+ }
615
+ const level = match[1].length;
616
+ const title = normalizeHeadingTitle(match[2]);
617
+ if (!title) {
618
+ continue;
619
+ }
620
+ while (stack.length > 0 && stack[stack.length - 1].level >= level) {
621
+ stack.pop();
622
+ }
623
+ const headingPath = [...stack.map((entry) => entry.title), title];
624
+ headings.push({
625
+ title,
626
+ level,
627
+ line: i + 1,
628
+ path: headingPath,
629
+ });
630
+ stack.push({ title, level });
631
+ }
632
+ return headings;
633
+ }
634
+ // Exported for unit testing; mirrors server/pkg/markdown/section.go.
635
+ export function detectFrontMatterEnd(lines) {
636
+ if (lines.length === 0) {
637
+ return 0;
638
+ }
639
+ // Fences must sit at the line start; only trailing spaces / tabs / CR are
640
+ // allowed (right-trim, NOT trim). An indented ` ---` is legal content — e.g.
641
+ // inside a YAML block scalar — and must not open or close the block. Mirrors
642
+ // server/pkg/markdown/section.go and the micromark frontmatter grammar.
643
+ const rtrim = (s) => s.replace(/[ \t\r]+$/, '');
644
+ const first = rtrim(lines[0]);
645
+ if (first !== '---' && first !== '+++') {
646
+ return 0;
647
+ }
648
+ for (let i = 1; i < lines.length; i += 1) {
649
+ if (rtrim(lines[i]) === first) {
650
+ return i + 1;
651
+ }
652
+ }
653
+ return 0;
654
+ }
655
+ function normalizeHeadingTitle(raw) {
656
+ return raw
657
+ .replace(TRAILING_FENCE_RE, '')
658
+ .trim()
659
+ .replace(/^`+|`+$/g, '');
660
+ }
661
+ export function parseNodeId(nodeId) {
662
+ const match = nodeId.match(/^(.*):(doc|preface|L(\d+))$/);
663
+ if (!match || !match[1]) {
664
+ throw new Error(`invalid wiki node_id: ${nodeId}`);
665
+ }
666
+ const filePath = normalizeRequiredWikiPath(match[1]);
667
+ if (match[2] === 'doc') {
668
+ return { path: filePath, kind: 'doc' };
669
+ }
670
+ if (match[2] === 'preface') {
671
+ return { path: filePath, kind: 'preface' };
672
+ }
673
+ return {
674
+ path: filePath,
675
+ kind: 'line',
676
+ line: Number.parseInt(match[3], 10),
677
+ };
678
+ }
679
+ function parseFenceMarker(line) {
680
+ if (line.startsWith('```')) {
681
+ return '```';
682
+ }
683
+ if (line.startsWith('~~~')) {
684
+ return '~~~';
685
+ }
686
+ return '';
687
+ }
688
+ function defaultFileTitle(filePath) {
689
+ const base = path.posix.basename(filePath, path.posix.extname(filePath));
690
+ return base.replaceAll('-', ' ').replaceAll('_', ' ').trim() || filePath;
691
+ }
692
+ function findFirstNonEmptyLine(lines, startLine, endLine) {
693
+ const start = Math.max(startLine, 1);
694
+ const end = Math.min(endLine, lines.length);
695
+ for (let i = start; i <= end; i += 1) {
696
+ if (lines[i - 1]?.trim()) {
697
+ return i;
698
+ }
699
+ }
700
+ return start;
701
+ }
702
+ // ---------------------------------------------------------------------------
703
+ // Tokenizer (CJK-aware, for search/query)
704
+ // ---------------------------------------------------------------------------
705
+ function tokenize(text) {
706
+ const trimmed = text.trim();
707
+ if (!trimmed) {
708
+ return [];
709
+ }
710
+ const tokens = [];
711
+ let word = '';
712
+ let cjkRun = '';
713
+ const flushWord = () => {
714
+ if (!word) {
715
+ return;
716
+ }
717
+ tokens.push(word.toLowerCase());
718
+ word = '';
719
+ };
720
+ const flushCjk = () => {
721
+ if (!cjkRun) {
722
+ return;
723
+ }
724
+ const chars = Array.from(cjkRun.toLowerCase());
725
+ tokens.push(...chars);
726
+ if (chars.length > 1) {
727
+ for (let i = 0; i < chars.length - 1; i += 1) {
728
+ tokens.push(chars[i] + chars[i + 1]);
729
+ }
730
+ }
731
+ cjkRun = '';
732
+ };
733
+ for (const char of Array.from(trimmed)) {
734
+ if (isCjkChar(char)) {
735
+ flushWord();
736
+ cjkRun += char;
737
+ continue;
738
+ }
739
+ if (/[0-9\p{L}]/u.test(char)) {
740
+ flushCjk();
741
+ word += char.toLowerCase();
742
+ continue;
743
+ }
744
+ flushWord();
745
+ flushCjk();
746
+ }
747
+ flushWord();
748
+ flushCjk();
749
+ return tokens;
750
+ }
751
+ function isCjkChar(char) {
752
+ const codePoint = char.codePointAt(0) ?? 0;
753
+ return ((codePoint >= 0x4e00 && codePoint <= 0x9fff) ||
754
+ (codePoint >= 0x3400 && codePoint <= 0x4dbf) ||
755
+ (codePoint >= 0x3040 && codePoint <= 0x309f) ||
756
+ (codePoint >= 0x30a0 && codePoint <= 0x30ff) ||
757
+ (codePoint >= 0xac00 && codePoint <= 0xd7af));
758
+ }