@parall/cli 1.58.2 → 1.60.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.
package/dist/lib/wiki.js CHANGED
@@ -1,76 +1,17 @@
1
- import { createHash } from 'node:crypto';
2
1
  import { promises as fs } from 'node:fs';
3
- import path from 'node:path';
4
2
  import { ApiError, } from '@parall/sdk';
5
- import { structuredPatch } from 'diff';
6
- import { hasFrontMatter, parseFrontMatter } from './wiki-frontmatter.js';
3
+ import { enforceAllowedPrefix, isMarkdownFile, looksBinary, normalizeRef, normalizeRequiredWikiPath, normalizeWikiPath, requireLocalWikiMount, resolveAgentId, resolveLocalWikiMount, resolvePathInsideRoot, resolveWikiRef, toPosix, } from './wiki-shared.js';
4
+ import { computeLocalChanges, computeLocalDiff, readLocalManifest } from './wiki-workspace.js';
5
+ import { buildIndexNodes, findLocalNodeSection, loadWikiNodeSections, parseMarkdownFile, parseNodeId, planWikiQuery, scoreNodes, stripNodeSectionContent, tryLoadLocalNodeSections, } from './wiki-index.js';
7
6
  // Re-exported so consumers (and tests) can reach the frontmatter parser via the
8
7
  // wiki module surface alongside detectFrontMatterEnd.
9
8
  export { parseFrontMatter } from './wiki-frontmatter.js';
10
- // ---------------------------------------------------------------------------
11
- // Constants
12
- // ---------------------------------------------------------------------------
13
- const MARKDOWN_HEADING_RE = /^\s{0,3}(#{1,6})[ \t]+(.+?)\s*$/;
14
- const TRAILING_FENCE_RE = /\s+#+\s*$/;
15
- // Bumped 2 → 3 for the frontmatter (type/description/tags) fields: invalidates
16
- // caches built before frontmatter parsing so existing local mounts re-parse and
17
- // pick up the metadata even when a file's size / mtime is unchanged.
18
- const LOCAL_NODE_SECTION_ARTIFACT_VERSION = 3;
19
- const LOCAL_MANIFEST_FILE = 'manifest.json';
20
- const PRLL_WIKI_DIR = '.parall-wiki';
21
- const CONFLICTS_DIR = 'conflicts';
22
- const OBJECTS_DIR = 'objects';
23
- const REMOTE_CONFLICT_SUFFIX = '.remote';
24
- const REMOTE_DELETED_MARKER_SUFFIX = '.remote-deleted';
25
- /** Server-side text ceiling for changeset file content (mirrors filetype.TextMaxBytes). */
26
- export const TEXT_MAX_BYTES = 10 * 1024 * 1024;
27
- /** Degraded listing entries (discoverable-but-unreadable libraries) carry no
28
- * slug and no content access — they exist only so the Web join browser can
29
- * offer them. The CLI never mounts, syncs or enumerates them. */
30
- function isReadableWiki(wiki_) {
31
- return !wiki_.degraded && typeof wiki_.slug === 'string' && wiki_.slug.length > 0;
32
- }
33
- export async function listWikis(ctx) {
34
- return (await ctx.client.getWikis(ctx.orgId)).filter(isReadableWiki);
35
- }
36
- export async function resolveWikiRef(ctx, wikiRef) {
37
- const normalized = wikiRef?.trim() ?? '';
38
- if (!normalized) {
39
- return resolveWikiRefOrDefault(ctx);
40
- }
41
- const wikis = await listWikis(ctx);
42
- const exact = wikis.find((wiki) => wiki.id === normalized || wiki.slug === normalized);
43
- if (exact) {
44
- return exact;
45
- }
46
- const lower = normalized.toLowerCase();
47
- const fuzzy = wikis.find((wiki) => wiki.slug.toLowerCase() === lower || wiki.name.toLowerCase() === lower);
48
- if (fuzzy) {
49
- return fuzzy;
50
- }
51
- const available = wikis.length > 0
52
- ? ` Available wikis: ${wikis.map((w) => w.slug).join(', ')}`
53
- : ' This organization has no wikis yet.';
54
- throw new Error(`wiki not found: ${wikiRef}.${available}`);
55
- }
56
- /**
57
- * Resolve wiki reference. If wikiRef is omitted or empty, auto-resolves to
58
- * the org's single wiki. Errors if the org has zero or multiple wikis without
59
- * a ref specified.
60
- */
61
- export async function resolveWikiRefOrDefault(ctx, wikiRef) {
62
- if (wikiRef?.trim()) {
63
- return resolveWikiRef(ctx, wikiRef);
64
- }
65
- const wikis = await listWikis(ctx);
66
- if (wikis.length === 1) {
67
- return wikis[0];
68
- }
69
- if (wikis.length === 0) {
70
- throw new Error('No wikis found in this organization. Create one first.');
71
- }
72
- throw new Error(`Multiple wikis found. Specify which one:\n${wikis.map((w) => ` ${w.slug} (${w.name})`).join('\n')}`);
73
- }
9
+ // The public surface moved into domain files; this module stays the entry
10
+ // point so every existing importer keeps working unchanged.
11
+ export { TEXT_MAX_BYTES, computeGitBlobSHA, isWikiTextContent, listWikis, normalizeRequiredWikiPath, resolveApiToken, resolveWikiRef, resolveWikiRefOrDefault, resolveWikiServiceBaseUrl, } from './wiki-shared.js';
12
+ export { planSyncActions, removeConflictArtifacts, syncAllMounts, syncSingleWiki, watchMounts, writeConflictMarker, } from './wiki-sync.js';
13
+ export { proposeWikiChangeset, resetWikiWorkspace, } from './wiki-propose.js';
14
+ export { detectFrontMatterEnd } from './wiki-index.js';
74
15
  // ---------------------------------------------------------------------------
75
16
  // Wiki tree / blob (API fallback for non-mounted content)
76
17
  // ---------------------------------------------------------------------------
@@ -337,220 +278,6 @@ export async function getAfcsDiff(ctx, wikiRef) {
337
278
  patch: diff.patch,
338
279
  };
339
280
  }
340
- // ---------------------------------------------------------------------------
341
- // AFCS: propose changeset (REST-based)
342
- // ---------------------------------------------------------------------------
343
- export async function proposeWikiChangeset(ctx, wikiRef, options) {
344
- const wiki = await resolveWikiRef(ctx, wikiRef);
345
- const mount = await requireLocalWikiMount(ctx, wiki);
346
- const title = options.title.trim();
347
- if (!title) {
348
- throw new Error('title is required');
349
- }
350
- const manifest = await readLocalManifest(mount.root);
351
- const diff = await computeLocalDiff(mount, manifest);
352
- if (diff.changedPaths.length === 0) {
353
- throw new Error(`no changes to propose for wiki ${wiki.slug} — edit files under ${mount.root} first, ` +
354
- 'then run `parall wiki diff` to confirm what will be proposed');
355
- }
356
- // Stale-base precheck (fail-closed): compare each changed path's sync
357
- // baseline against the server's CURRENT manifest. Proposing from a stale
358
- // baseline would upload full content that silently rolls back concurrent
359
- // edits. The server re-validates via base_sha (authoritative — this check
360
- // just fails earlier with the complete file list).
361
- const serverManifest = (await wikiServiceFetch(mount.manifestUrl, requireMountToken(mount)));
362
- const serverShaByPath = new Map(serverManifest.data.map((e) => [e.path, e.sha]));
363
- const staleLines = [];
364
- for (const filePath of diff.changedPaths) {
365
- const baseSha = diff.baseShaByPath.get(filePath);
366
- const serverSha = serverShaByPath.get(filePath);
367
- if (baseSha === undefined) {
368
- // Locally created file — stale if the server got one in the meantime.
369
- if (serverSha !== undefined) {
370
- staleLines.push(`${filePath} (created on the server since your last sync)`);
371
- }
372
- }
373
- else if (serverSha === undefined) {
374
- staleLines.push(`${filePath} (deleted on the server since your last sync)`);
375
- }
376
- else if (serverSha !== baseSha) {
377
- staleLines.push(`${filePath} (modified on the server since your last sync)`);
378
- }
379
- }
380
- if (staleLines.length > 0) {
381
- throw new Error(`cannot propose: ${staleLines.length} file(s) changed on the server since your last sync:\n` +
382
- staleLines.map((l) => ` ${l}`).join('\n') +
383
- '\nRun `parall wiki sync` to pull the latest content (your local edits are preserved; ' +
384
- 'conflicting files get a marker under .parall-wiki/conflicts/), resolve if needed, then propose again.');
385
- }
386
- // Build file_changes for the changeset API
387
- const fileChanges = [];
388
- for (const filePath of diff.changedPaths) {
389
- const localPath = resolvePathInsideRoot(mount.root, filePath);
390
- const existsLocally = await pathExists(localPath);
391
- const baseEntry = manifest.files[filePath];
392
- if (!existsLocally) {
393
- // Deleted
394
- fileChanges.push({
395
- path: filePath,
396
- action: 'delete',
397
- base_sha: baseEntry?.sha,
398
- });
399
- }
400
- else {
401
- const content = await fs.readFile(localPath);
402
- // The changeset API is text-only (the server rejects binary with 422
403
- // USE_UPLOAD, pointing at an endpoint the CLI does not wrap). Reject
404
- // locally with a clear boundary statement instead.
405
- if (looksBinary(content)) {
406
- throw new Error(`cannot propose ${filePath}: wiki changesets support text files only. ` +
407
- 'Remove the binary from the workspace (binary uploads go through the web UI).');
408
- }
409
- if (content.length > TEXT_MAX_BYTES) {
410
- throw new Error(`cannot propose ${filePath}: file is ${content.length} bytes, ` +
411
- `over the ${TEXT_MAX_BYTES}-byte changeset limit. Split the file or remove it from the workspace.`);
412
- }
413
- fileChanges.push({
414
- path: filePath,
415
- action: baseEntry ? 'update' : 'create',
416
- content_base64: content.toString('base64'),
417
- base_sha: baseEntry?.sha,
418
- });
419
- }
420
- }
421
- let changeset;
422
- const existingChangesetId = normalizeOptionalString(options.changesetId);
423
- if (existingChangesetId) {
424
- // Re-propose: replace_files makes the workspace diff define the
425
- // changeset's FULL content — the server resets the feature branch to
426
- // default HEAD first, so a change withdrawn locally (file reverted to
427
- // baseline) actually disappears from the proposal instead of silently
428
- // surviving on the branch.
429
- changeset = await ctx.client.updateWikiChangeset(ctx.orgId, wiki.id, existingChangesetId, {
430
- title,
431
- message: normalizeOptionalString(options.message),
432
- file_changes: fileChanges,
433
- replace_files: true,
434
- });
435
- }
436
- else {
437
- // Create new changeset via API
438
- changeset = await ctx.client.createWikiChangeset(ctx.orgId, wiki.id, {
439
- title,
440
- message: normalizeOptionalString(options.message),
441
- file_changes: fileChanges,
442
- source_chat_id: normalizeOptionalString(options.sourceChatId),
443
- source_message_id: normalizeOptionalString(options.sourceMessageId),
444
- source_run_id: normalizeOptionalString(options.sourceRunId),
445
- });
446
- }
447
- const autoMerged = changeset.status === 'merged';
448
- let postMergeSync = null;
449
- let postMergeSyncError = null;
450
- if (autoMerged) {
451
- try {
452
- postMergeSync = await syncSingleWiki(ctx, wiki, mount.root);
453
- }
454
- catch (error) {
455
- postMergeSyncError = error instanceof Error ? error.message : String(error);
456
- }
457
- }
458
- return {
459
- wiki_id: wiki.id,
460
- wiki_slug: wiki.slug,
461
- wiki_name: wiki.name,
462
- mount_path: mount.root,
463
- changed_paths: diff.changedPaths,
464
- diff_files: diff.diffFiles,
465
- changeset,
466
- status: changeset.status,
467
- auto_merged: autoMerged,
468
- requires_review: changesetRequiresReview(changeset),
469
- next_action: describeProposeNextAction(changeset, postMergeSync, postMergeSyncError),
470
- post_merge_sync: postMergeSync,
471
- post_merge_sync_error: postMergeSyncError,
472
- source: 'local_mount',
473
- };
474
- }
475
- function changesetRequiresReview(changeset) {
476
- return (changeset.status === 'proposed' ||
477
- changeset.status === 'approval_pending' ||
478
- changeset.status === 'approved');
479
- }
480
- function describeProposeNextAction(changeset, postMergeSync, postMergeSyncError) {
481
- if (changeset.status === 'merged') {
482
- if (postMergeSyncError) {
483
- return 'Changeset auto-merged. Run `parall wiki sync` to refresh the local manifest.';
484
- }
485
- if (postMergeSync && (postMergeSync.conflicts.length > 0 || postMergeSync.failed.length > 0)) {
486
- return 'Changeset auto-merged, but local sync reported conflicts or failures. Inspect `.parall-wiki/conflicts` and run `parall wiki status`.';
487
- }
488
- return 'Changeset auto-merged and the local wiki manifest was refreshed.';
489
- }
490
- if (changeset.status === 'conflict') {
491
- return 'Auto-merge hit a merge conflict. Run `parall wiki sync`, resolve conflicts, then create a new changeset.';
492
- }
493
- if (changesetRequiresReview(changeset)) {
494
- return 'Changeset is awaiting review because it touched a protected path or auto-merge was skipped.';
495
- }
496
- if (changeset.status === 'draft') {
497
- return 'Changeset is still in draft. Run propose again without --update to submit it for review.';
498
- }
499
- return `Changeset is ${changeset.status}.`;
500
- }
501
- // ---------------------------------------------------------------------------
502
- // AFCS: reset workspace
503
- // ---------------------------------------------------------------------------
504
- /**
505
- * Discard all local changes and restore files to the last synced state.
506
- * Restores from the local baseline object store (network only as a
507
- * SHA-verified fallback for pre-objects mounts), so the workspace lands
508
- * exactly on the manifest baseline — `wiki status` reports clean afterwards.
509
- */
510
- export async function resetWikiWorkspace(ctx, wikiRef) {
511
- const wiki = await resolveWikiRef(ctx, wikiRef);
512
- const mount = await requireLocalWikiMount(ctx, wiki);
513
- const manifest = await readLocalManifest(mount.root);
514
- // Only touch files that actually diverged from the baseline.
515
- const changes = await computeLocalChanges(mount);
516
- if (changes.length === 0) {
517
- return { wiki_id: wiki.id, wiki_slug: wiki.slug, files_restored: 0, unrestorable_paths: [] };
518
- }
519
- let restored = 0;
520
- const unrestorable = [];
521
- for (const change of changes) {
522
- const entry = manifest.files[change.path];
523
- const fullPath = resolvePathInsideRoot(mount.root, change.path);
524
- if (!entry) {
525
- // Locally created file — discard.
526
- await fs.rm(fullPath, { force: true });
527
- await removeEmptyParents(mount.root, path.dirname(fullPath));
528
- restored++;
529
- continue;
530
- }
531
- const baseline = await loadBaselineContent(mount, change.path, entry.sha);
532
- if (!baseline) {
533
- // No baseline available (pre-objects mount, server moved on). Leave the
534
- // local file untouched rather than overwriting it with non-baseline
535
- // content; `parall wiki sync` is the path that reconciles this state.
536
- unrestorable.push(change.path);
537
- continue;
538
- }
539
- await fs.mkdir(path.dirname(fullPath), { recursive: true });
540
- await fs.writeFile(fullPath, baseline);
541
- restored++;
542
- }
543
- if (unrestorable.length > 0) {
544
- console.warn(`[wiki reset] ${unrestorable.length} file(s) had no recoverable baseline and were left as-is: ` +
545
- `${unrestorable.join(', ')} — run \`parall wiki sync\` to reconcile`);
546
- }
547
- return {
548
- wiki_id: wiki.id,
549
- wiki_slug: wiki.slug,
550
- files_restored: restored,
551
- unrestorable_paths: unrestorable,
552
- };
553
- }
554
281
  export async function listWikiChangesets(ctx, wikiRef) {
555
282
  const wiki = await resolveWikiRef(ctx, wikiRef);
556
283
  const allChangesets = await ctx.client.getWikiChangesets(ctx.orgId, wiki.id);
@@ -651,1143 +378,64 @@ export async function getWikiLog(ctx, wikiRef, filePath) {
651
378
  entries,
652
379
  };
653
380
  }
654
- /**
655
- * Sync wiki workspaces via REST (manifest comparison + bulk download).
656
- * Without `wikiRef`: every accessible wiki is synced and stale mount
657
- * directories are pruned. With `wikiRef`: only that wiki is synced and
658
- * pruning is skipped — other wikis' workspaces must survive a scoped sync.
659
- * Mount path is determined client-side: {mountRoot}/{slug}/
660
- */
661
- export async function syncAllMounts(ctx, wikiRef) {
662
- const allWikis = (await ctx.client.getWikis(ctx.orgId)).filter(isReadableWiki);
663
- const target = wikiRef?.trim() ? await resolveWikiRef(ctx, wikiRef) : undefined;
664
- const wikis = target ? allWikis.filter((w) => w.id === target.id) : allWikis;
665
- const mountRoot = ctx.mountRoot?.trim() || process.env.PRLL_WIKI_MOUNT_ROOT?.trim();
666
- const activeMountPaths = new Set();
667
- const synced = [];
668
- for (const wiki of wikis) {
669
- const mountPath = resolveMountPath(wiki.slug, mountRoot);
670
- activeMountPaths.add(mountPath);
671
- const outcome = await syncSingleWiki(ctx, wiki, mountPath);
672
- synced.push({
673
- slug: wiki.slug,
674
- path: mountPath,
675
- applied: outcome.applied,
676
- fastForwarded: outcome.fastForwarded,
677
- conflicts: outcome.conflicts,
678
- failed: outcome.failed,
679
- });
680
- }
681
- if (!target) {
682
- await pruneStaleMounts(mountRoot, activeMountPaths);
683
- }
684
- const ok = synced.every((s) => s.failed.length === 0);
685
- return { ok, mounts: wikis.length, synced };
686
- }
687
- /**
688
- * Run {@link syncAllMounts} in a loop, sleeping `intervalSec` between
689
- * iterations. Returns a `stop` callback to break the loop.
690
- */
691
- export function watchMounts(ctx, intervalSec) {
692
- requireAgentId(ctx); // fail fast if agentId missing
693
- let stopped = false;
694
- const doSync = async () => {
695
- try {
696
- await syncAllMounts(ctx);
697
- }
698
- catch (err) {
699
- process.stderr.write(`wiki refresh failed: ${err instanceof Error ? err.message : String(err)}\n`);
700
- }
701
- };
702
- const timer = setInterval(doSync, intervalSec * 1000);
703
- const stop = () => {
704
- if (stopped)
705
- return;
706
- stopped = true;
707
- clearInterval(timer);
708
- };
709
- process.on('SIGINT', stop);
710
- process.on('SIGTERM', stop);
711
- return { stop };
712
- }
713
- /**
714
- * Pure three-way sync planner. Decides what to do per-path given the base
715
- * (manifest entry from last successful sync), the current local working tree
716
- * sha, and the latest remote sha. No I/O.
717
- */
718
- export function planSyncActions(input) {
719
- const actions = [];
720
- for (const p of input.paths) {
721
- const baseSha = input.baseSha(p);
722
- const remote = input.remote(p);
723
- const remoteSha = remote?.sha ?? null;
724
- const localSha = input.localSha(p);
725
- if (baseSha === remoteSha) {
726
- actions.push({ kind: 'noop', path: p });
727
- continue;
728
- }
729
- const cleanLocal = localSha === baseSha;
730
- if (cleanLocal) {
731
- if (remoteSha === null) {
732
- actions.push({ kind: 'apply-delete', path: p });
733
- }
734
- else {
735
- actions.push({ kind: 'apply-write', path: p, remoteSha, remoteSize: remote.size });
736
- }
737
- continue;
738
- }
739
- if (localSha !== null && localSha === remoteSha) {
740
- actions.push({ kind: 'fast-forward', path: p, remoteSha, remoteSize: remote.size });
741
- continue;
742
- }
743
- if (localSha === null && remoteSha === null) {
744
- actions.push({ kind: 'fast-forward-delete', path: p });
745
- continue;
746
- }
747
- if (remoteSha === null) {
748
- actions.push({ kind: 'conflict-delete', path: p, baseSha: baseSha });
749
- }
750
- else {
751
- actions.push({
752
- kind: 'conflict-write',
753
- path: p,
754
- remoteSha,
755
- remoteSize: remote.size,
756
- baseSha,
757
- localSha,
758
- });
759
- }
760
- }
761
- return actions;
762
- }
763
- export async function syncSingleWiki(ctx, wiki, mountPath) {
764
- await fs.mkdir(mountPath, { recursive: true });
765
- const metaDir = path.join(mountPath, PRLL_WIKI_DIR);
766
- await fs.mkdir(metaDir, { recursive: true });
767
- const token = resolveApiToken(ctx);
768
- const baseUrl = resolveWikiServiceBaseUrl(ctx);
769
- const manifestUrl = `${baseUrl}/wiki/v1/orgs/${ctx.orgId}/wikis/${wiki.id}/manifest`;
770
- const bulkDownloadUrl = `${baseUrl}/wiki/v1/orgs/${ctx.orgId}/wikis/${wiki.id}/files/bulk-download`;
771
- // 1. Fetch server manifest + read local manifest.
772
- const manifestResp = (await wikiServiceFetch(manifestUrl, token));
773
- const serverEntries = manifestResp.data;
774
- const serverByPath = new Map(serverEntries.map((e) => [e.path, e]));
775
- const localManifest = await readLocalManifest(mountPath);
776
- // 2. Build the union of paths from server + local manifest + working tree.
777
- const allPaths = new Set();
778
- for (const e of serverEntries)
779
- allPaths.add(e.path);
780
- for (const p of Object.keys(localManifest.files))
781
- allPaths.add(p);
782
- await walkLocalFiles(mountPath, mountPath, async (_full, rel) => {
783
- allPaths.add(rel);
784
- });
785
- // 3. Snapshot working-tree shas so the planner stays pure. Paths whose local
786
- // shape is incompatible with a regular-file read (e.g. local has a directory
787
- // where remote treats this as a file, or a parent path is a regular file
788
- // while remote nests under it) are routed to a 'shape-conflict' failure
789
- // instead of crashing the whole sync — they need human/agent intervention.
790
- const localShaCache = new Map();
791
- const shapeConflictByPath = new Map();
792
- for (const p of allPaths) {
793
- const probe = await probeLocalGitBlob(mountPath, p);
794
- if (probe.kind === 'shape-conflict') {
795
- shapeConflictByPath.set(p, probe.detail);
796
- localShaCache.set(p, null);
797
- }
798
- else {
799
- localShaCache.set(p, probe.sha);
800
- }
801
- }
802
- const actions = planSyncActions({
803
- paths: allPaths,
804
- baseSha: (p) => localManifest.files[p]?.sha ?? null,
805
- localSha: (p) => localShaCache.get(p) ?? null,
806
- remote: (p) => {
807
- const r = serverByPath.get(p);
808
- return r ? { sha: r.sha, size: r.size } : null;
809
- },
810
- });
811
- // 4. Fetch all bytes we need (apply-write + conflict-write) in one bulk call.
812
- const fetchPaths = actions
813
- .filter((a) => a.kind === 'apply-write' || a.kind === 'conflict-write')
814
- .map((a) => a.path);
815
- const contentByPath = new Map();
816
- const downloadErrorByPath = new Map();
817
- if (fetchPaths.length > 0) {
818
- const downloaded = await bulkDownloadFiles(bulkDownloadUrl, token, fetchPaths);
819
- const returnedPaths = new Set();
820
- for (const entry of downloaded) {
821
- returnedPaths.add(entry.path);
822
- if (entry.error) {
823
- downloadErrorByPath.set(entry.path, entry.error);
824
- continue;
825
- }
826
- contentByPath.set(entry.path, Buffer.from(entry.content_base64, 'base64'));
827
- }
828
- // Anything we asked for but the server omitted entirely is also a failure.
829
- for (const p of fetchPaths) {
830
- if (!returnedPaths.has(p)) {
831
- downloadErrorByPath.set(p, 'missing from bulk-download response');
832
- }
833
- }
834
- }
835
- // 5. Apply actions and start with the previous manifest, mutating per action.
836
- const newFiles = { ...localManifest.files };
837
- const downloadedBySha = new Map();
838
- const conflicts = [];
839
- const failed = [];
840
- let applied = 0;
841
- let fastForwarded = 0;
842
- // Surface shape conflicts as sync failures up front so we don't try to write
843
- // through them. Manifest stays pinned (the path's manifest entry is left as-is).
844
- for (const [p, detail] of shapeConflictByPath) {
845
- failed.push({ path: p, reason: 'shape-conflict', detail });
846
- }
847
- for (const action of actions) {
848
- if (shapeConflictByPath.has(action.path)) {
849
- // Already reported. Don't attempt apply / write — would crash on EISDIR/ENOTDIR.
850
- continue;
851
- }
852
- switch (action.kind) {
853
- case 'noop':
854
- // Preserve manifest entry unchanged.
855
- break;
856
- case 'apply-write': {
857
- const buf = contentByPath.get(action.path);
858
- if (!buf) {
859
- failed.push({
860
- path: action.path,
861
- reason: 'download',
862
- detail: downloadErrorByPath.get(action.path),
863
- });
864
- break;
865
- }
866
- // TOCTOU re-check: the snapshot was taken before the bulk-download
867
- // network round-trip. If the user/agent edited (or deleted) this path
868
- // in that window, demote to a conflict so we don't silently overwrite.
869
- const snapshotSha = localShaCache.get(action.path) ?? null;
870
- const reprobe = await probeLocalGitBlob(mountPath, action.path);
871
- if (reprobe.kind === 'shape-conflict') {
872
- failed.push({ path: action.path, reason: 'shape-conflict', detail: reprobe.detail });
873
- break;
874
- }
875
- const currentSha = reprobe.sha;
876
- if (currentSha === action.remoteSha) {
877
- // Local converged on remote during the window — manifest-only fast-forward.
878
- newFiles[action.path] = { sha: action.remoteSha, size: action.remoteSize };
879
- fastForwarded++;
880
- break;
881
- }
882
- if (currentSha !== snapshotSha) {
883
- // Local diverged after snapshot. Surface as a conflict instead of overwriting.
884
- const remoteCopy = await writeConflictMarker(mountPath, action.path, REMOTE_CONFLICT_SUFFIX, buf);
885
- let reason;
886
- // Defense-in-depth: planSyncActions only emits apply-write when
887
- // localSha === baseSha (both non-null), so snapshotSha should never
888
- // be null here. The branch is kept to safely classify any race that
889
- // creates a file between snapshot and apply.
890
- if (snapshotSha === null && currentSha !== null) {
891
- reason = 'remote-added-local-collides';
892
- }
893
- else if (currentSha === null) {
894
- reason = 'remote-changed-local-deleted';
895
- }
896
- else {
897
- reason = 'remote-changed-local-edited';
898
- }
899
- conflicts.push({ path: action.path, remoteCopyPath: remoteCopy, reason });
900
- break;
901
- }
902
- const fullPath = resolvePathInsideRoot(mountPath, action.path);
903
- await fs.mkdir(path.dirname(fullPath), { recursive: true });
904
- await fs.writeFile(fullPath, buf);
905
- newFiles[action.path] = { sha: action.remoteSha, size: action.remoteSize };
906
- downloadedBySha.set(action.remoteSha, buf);
907
- applied++;
908
- break;
909
- }
910
- case 'apply-delete': {
911
- // TOCTOU re-check before deleting. The action only fires when the
912
- // snapshot saw clean local matching the (now-deleted) base; if the
913
- // user re-created or edited the file after the snapshot, demote to
914
- // conflict-delete instead of dropping their work.
915
- const snapshotSha = localShaCache.get(action.path) ?? null;
916
- const reprobe = await probeLocalGitBlob(mountPath, action.path);
917
- if (reprobe.kind === 'shape-conflict') {
918
- failed.push({ path: action.path, reason: 'shape-conflict', detail: reprobe.detail });
919
- break;
920
- }
921
- const currentSha = reprobe.sha;
922
- if (currentSha === null) {
923
- // Convergence: user also deleted the file during the TOCTOU window.
924
- // Both sides agree — fast-forward the manifest delete.
925
- delete newFiles[action.path];
926
- fastForwarded++;
927
- break;
928
- }
929
- if (currentSha !== snapshotSha) {
930
- await writeConflictMarker(mountPath, action.path, REMOTE_DELETED_MARKER_SUFFIX, Buffer.alloc(0));
931
- conflicts.push({
932
- path: action.path,
933
- remoteCopyPath: null,
934
- reason: 'remote-deleted-local-edited',
935
- });
936
- break;
937
- }
938
- const fullPath = resolvePathInsideRoot(mountPath, action.path);
939
- await fs.rm(fullPath, { force: true });
940
- await removeEmptyParents(mountPath, path.dirname(fullPath));
941
- delete newFiles[action.path];
942
- applied++;
943
- break;
944
- }
945
- case 'fast-forward':
946
- // Local already matches remote — only sync the manifest pointer.
947
- newFiles[action.path] = { sha: action.remoteSha, size: action.remoteSize };
948
- fastForwarded++;
949
- break;
950
- case 'fast-forward-delete':
951
- delete newFiles[action.path];
952
- fastForwarded++;
953
- break;
954
- case 'conflict-write': {
955
- const buf = contentByPath.get(action.path);
956
- if (!buf) {
957
- failed.push({
958
- path: action.path,
959
- reason: 'download',
960
- detail: downloadErrorByPath.get(action.path),
961
- });
962
- break;
963
- }
964
- const remoteCopy = await writeConflictMarker(mountPath, action.path, REMOTE_CONFLICT_SUFFIX, buf);
965
- // Reason classification:
966
- // - base null + local present → both sides added the same path with different bytes
967
- // - base present + local null → user deleted locally, server changed it
968
- // - base present + local present (and ≠ both) → genuine concurrent edit
969
- let reason;
970
- if (action.baseSha === null) {
971
- reason = 'remote-added-local-collides';
972
- }
973
- else if (action.localSha === null) {
974
- reason = 'remote-changed-local-deleted';
975
- }
976
- else {
977
- reason = 'remote-changed-local-edited';
978
- }
979
- conflicts.push({ path: action.path, remoteCopyPath: remoteCopy, reason });
980
- // Manifest entry stays at its pre-sync value so the next sync still
981
- // recognises the local edit and re-tries the merge.
982
- break;
983
- }
984
- case 'conflict-delete': {
985
- // Server deleted a file the user has local edits for. Drop a marker
986
- // so the agent surfaces the divergence without overwriting local.
987
- await writeConflictMarker(mountPath, action.path, REMOTE_DELETED_MARKER_SUFFIX, Buffer.alloc(0));
988
- conflicts.push({
989
- path: action.path,
990
- remoteCopyPath: null,
991
- reason: 'remote-deleted-local-edited',
992
- });
993
- break;
994
- }
381
+ async function loadWikiMarkdownFile(ctx, wiki, filePath, ref) {
382
+ const normalizedRef = normalizeRef(ref);
383
+ const normalizedPath = normalizeRequiredWikiPath(filePath);
384
+ if (!normalizedRef) {
385
+ const local = await tryLoadLocalMarkdownFile(ctx, wiki, normalizedPath);
386
+ if (local) {
387
+ return { kind: 'local_mount', file: local };
995
388
  }
996
389
  }
997
- // 6. Persist new manifest + refresh the baseline object store so diff and
998
- // reset can always reproduce the exact synced content locally.
999
- const newManifest = {
1000
- wiki_id: wiki.id,
1001
- synced_at: new Date().toISOString(),
1002
- files: newFiles,
390
+ return {
391
+ kind: 'api',
392
+ file: await loadRemoteMarkdownFile(ctx, wiki, normalizedRef, normalizedPath),
1003
393
  };
1004
- await writeLocalManifest(mountPath, newManifest);
1005
- await ensureBaselineObjects(mountPath, newFiles, downloadedBySha);
1006
- await gcBaselineObjects(mountPath, newFiles);
1007
- if (conflicts.length > 0) {
1008
- for (const c of conflicts) {
1009
- const where = c.remoteCopyPath ? ` → ${path.relative(mountPath, c.remoteCopyPath)}` : '';
1010
- console.warn(`[wiki sync] conflict on ${c.path} (${c.reason})${where}`);
1011
- }
1012
- }
1013
- if (failed.length > 0) {
1014
- for (const f of failed) {
1015
- const detail = f.detail ? ` — ${f.detail}` : '';
1016
- console.warn(`[wiki sync] failed to ${f.reason} ${f.path}${detail} — manifest unchanged, will retry next sync`);
1017
- }
1018
- }
1019
- return { applied, fastForwarded, conflicts, failed };
1020
- }
1021
- /** Compute the git blob SHA of a working-tree file, or null if absent. */
1022
- async function readLocalGitBlobSha(mountRoot, relPath) {
1023
- const probe = await probeLocalGitBlob(mountRoot, relPath);
1024
- if (probe.kind === 'shape-conflict') {
1025
- // Surface as throw at this entry point — the caller (computeLocalChanges /
1026
- // computeLocalDiff) doesn't currently model shape conflicts. syncSingleWiki
1027
- // uses probeLocalGitBlob directly so it can route the failure structurally.
1028
- throw new Error(`shape conflict at ${relPath}: ${probe.detail}`);
1029
- }
1030
- return probe.sha;
1031
- }
1032
- /**
1033
- * Read a working-tree file as a git blob, returning a structured shape so
1034
- * callers can distinguish "absent" from "shape mismatch" (directory where a
1035
- * file is expected, or a parent path is a file blocking nested reads).
1036
- */
1037
- async function probeLocalGitBlob(mountRoot, relPath) {
1038
- let fullPath;
1039
- try {
1040
- fullPath = resolvePathInsideRoot(mountRoot, relPath);
1041
- }
1042
- catch {
1043
- return { kind: 'absent', sha: null };
1044
- }
1045
- try {
1046
- const buf = await fs.readFile(fullPath);
1047
- return { kind: 'file', sha: computeGitBlobSHA(buf) };
1048
- }
1049
- catch (err) {
1050
- const code = err.code;
1051
- if (code === 'ENOENT')
1052
- return { kind: 'absent', sha: null };
1053
- if (code === 'EISDIR' || code === 'ENOTDIR') {
1054
- return { kind: 'shape-conflict', detail: code };
1055
- }
1056
- throw err;
1057
- }
1058
- }
1059
- /**
1060
- * Write a sync conflict marker under .parall-wiki/conflicts/, mirroring the
1061
- * source path so the agent (or user) can locate the upstream copy next to the
1062
- * local edit. Returns the absolute path written.
1063
- */
1064
- export async function writeConflictMarker(mountRoot, sourcePath, suffix, content) {
1065
- // Validate sourcePath under the mount root before we use it as a key under
1066
- // .parall-wiki/conflicts. The planner only feeds us paths the server returned
1067
- // (so traversal segments are not expected today), but the rest of the sync
1068
- // pipeline always goes through resolvePathInsideRoot and we want this branch
1069
- // to fail closed too — defense in depth, not exploitation today.
1070
- resolvePathInsideRoot(mountRoot, sourcePath);
1071
- const conflictsRoot = path.join(mountRoot, PRLL_WIKI_DIR, CONFLICTS_DIR);
1072
- const target = resolvePathInsideRoot(conflictsRoot, sourcePath + suffix);
1073
- await fs.mkdir(path.dirname(target), { recursive: true });
1074
- await fs.writeFile(target, content);
1075
- return target;
1076
- }
1077
- // ---------------------------------------------------------------------------
1078
- // Local manifest I/O
1079
- // ---------------------------------------------------------------------------
1080
- async function readLocalManifest(mountRoot) {
1081
- const manifestPath = path.join(mountRoot, PRLL_WIKI_DIR, LOCAL_MANIFEST_FILE);
1082
- try {
1083
- const raw = await fs.readFile(manifestPath, 'utf8');
1084
- return JSON.parse(raw);
1085
- }
1086
- catch {
1087
- return { wiki_id: '', synced_at: '', files: {} };
1088
- }
1089
- }
1090
- async function writeLocalManifest(mountRoot, manifest) {
1091
- const metaDir = path.join(mountRoot, PRLL_WIKI_DIR);
1092
- await fs.mkdir(metaDir, { recursive: true });
1093
- await fs.writeFile(path.join(metaDir, LOCAL_MANIFEST_FILE), JSON.stringify(manifest, null, 2), 'utf8');
1094
- }
1095
- // ---------------------------------------------------------------------------
1096
- // Baseline object store (.parall-wiki/objects/<sha>)
1097
- //
1098
- // Content-addressed copies of the last-synced version of every manifest file.
1099
- // diff/status/reset read the true sync baseline from here instead of fetching
1100
- // the server's CURRENT content (which is the wrong base whenever the server
1101
- // has moved past the local sync point).
1102
- // ---------------------------------------------------------------------------
1103
- function baselineObjectPath(mountRoot, sha) {
1104
- return path.join(mountRoot, PRLL_WIKI_DIR, OBJECTS_DIR, sha);
1105
- }
1106
- async function readBaselineObject(mountRoot, sha) {
1107
- try {
1108
- return await fs.readFile(baselineObjectPath(mountRoot, sha));
1109
- }
1110
- catch {
1111
- return null;
1112
- }
1113
394
  }
1114
- async function writeBaselineObject(mountRoot, sha, content) {
1115
- const target = baselineObjectPath(mountRoot, sha);
1116
- await fs.mkdir(path.dirname(target), { recursive: true });
1117
- await fs.writeFile(target, content);
1118
- }
1119
- /**
1120
- * Make sure every manifest entry has its baseline object on disk.
1121
- * Content sources, in order: bytes downloaded during this sync
1122
- * (`contentBySha`), then the local working-tree file when its blob SHA still
1123
- * matches the manifest (clean file — typical for pre-objects mounts being
1124
- * upgraded). Files that are locally dirty AND missing an object stay absent;
1125
- * diff falls back per-file (see loadBaselineContent).
1126
- */
1127
- async function ensureBaselineObjects(mountRoot, files, contentBySha) {
1128
- for (const [relPath, entry] of Object.entries(files)) {
1129
- if (await pathExists(baselineObjectPath(mountRoot, entry.sha))) {
1130
- continue;
1131
- }
1132
- const downloaded = contentBySha?.get(entry.sha);
1133
- if (downloaded) {
1134
- await writeBaselineObject(mountRoot, entry.sha, downloaded);
1135
- continue;
1136
- }
1137
- const probe = await probeLocalGitBlob(mountRoot, relPath);
1138
- if (probe.kind === 'file' && probe.sha === entry.sha) {
1139
- const fullPath = resolvePathInsideRoot(mountRoot, relPath);
1140
- await writeBaselineObject(mountRoot, entry.sha, await fs.readFile(fullPath));
1141
- }
1142
- }
1143
- }
1144
- /** Drop baseline objects no longer referenced by any manifest entry. */
1145
- async function gcBaselineObjects(mountRoot, files) {
1146
- const objectsDir = path.join(mountRoot, PRLL_WIKI_DIR, OBJECTS_DIR);
1147
- let names;
1148
- try {
1149
- names = await fs.readdir(objectsDir);
1150
- }
1151
- catch {
1152
- return;
1153
- }
1154
- const live = new Set(Object.values(files).map((e) => e.sha));
1155
- for (const name of names) {
1156
- if (!live.has(name)) {
1157
- await fs.rm(path.join(objectsDir, name), { force: true });
1158
- }
1159
- }
1160
- }
1161
- /**
1162
- * Load the baseline (last-synced) content for a manifest entry. Objects store
1163
- * first; when absent (mount predates the objects store and the file is
1164
- * locally dirty), fall back to downloading the server's current content and
1165
- * accept it ONLY if its blob SHA matches the manifest base — otherwise the
1166
- * server has moved and no true baseline is available (returns null).
1167
- */
1168
- async function loadBaselineContent(mount, relPath, expectedSha) {
1169
- const cached = await readBaselineObject(mount.root, expectedSha);
1170
- if (cached) {
1171
- return cached;
1172
- }
1173
- if (!mount.token) {
395
+ async function tryLoadLocalMarkdownFile(ctx, wiki, filePath) {
396
+ const mount = await resolveLocalWikiMount(ctx, wiki);
397
+ if (!mount) {
1174
398
  return null;
1175
399
  }
1176
- try {
1177
- const entries = await bulkDownloadFiles(mount.bulkDownloadUrl, mount.token, [relPath]);
1178
- const entry = entries[0];
1179
- if (!entry || entry.error) {
1180
- return null;
1181
- }
1182
- const content = Buffer.from(entry.content_base64, 'base64');
1183
- if (computeGitBlobSHA(content) !== expectedSha) {
1184
- return null;
1185
- }
1186
- await writeBaselineObject(mount.root, expectedSha, content);
1187
- return content;
1188
- }
1189
- catch {
1190
- return null;
400
+ enforceAllowedPrefix(filePath, []);
401
+ const target = resolvePathInsideRoot(mount.root, filePath);
402
+ const stat = await fs.stat(target).catch(() => null);
403
+ if (!stat) {
404
+ throw new Error(`wiki file not found in local mount: ${filePath}`);
1191
405
  }
1192
- }
1193
- // ---------------------------------------------------------------------------
1194
- // REST helpers for wiki-service
1195
- // ---------------------------------------------------------------------------
1196
- // Exported so the binary-file raw-byte download (wiki-files.ts) authenticates
1197
- // the same way as sync/bulk-download — bearer from the client or PRLL_API_KEY.
1198
- export function resolveApiToken(ctx) {
1199
- const token = ctx?.client.getToken()?.trim() || process.env.PRLL_API_KEY?.trim();
1200
- if (!token) {
1201
- throw new Error('API token is required via ctx.client.getToken() or PRLL_API_KEY for wiki operations');
406
+ if (!stat.isFile()) {
407
+ throw new Error(`wiki path is not a file: ${filePath}`);
1202
408
  }
1203
- return token;
1204
- }
1205
- /**
1206
- * Resolve the wiki-service base URL (trailing slashes trimmed): explicit ctx
1207
- * override, then PRLL_WIKI_URL, then PRLL_API_URL. SSOT for the raw-fetch wiki
1208
- * endpoints (sync / bulk-download / binary file download). Hosted/staging/prod
1209
- * collapse these to one gateway host; local dev can split api (:8080) and wiki
1210
- * (:8090). Returns '' when none is set — callers decide whether that's fatal.
1211
- */
1212
- export function resolveWikiServiceBaseUrl(ctx) {
1213
- return (ctx.baseUrl ?? process.env.PRLL_WIKI_URL ?? process.env.PRLL_API_URL ?? '').replace(/\/+$/, '');
1214
- }
1215
- function tryResolveApiToken(ctx) {
1216
- return ctx?.client.getToken()?.trim() || process.env.PRLL_API_KEY?.trim() || undefined;
1217
- }
1218
- function requireMountToken(mount) {
1219
- if (!mount.token) {
1220
- throw new Error('API token is required for wiki-service operations on a local mount');
409
+ if (!isMarkdownFile(filePath)) {
410
+ throw new Error(`wiki section requires a Markdown file: ${filePath}`);
1221
411
  }
1222
- return mount.token;
1223
- }
1224
- async function wikiServiceFetch(url, token, options = {}) {
1225
- const method = options.method ?? 'GET';
1226
- const headers = {
1227
- Authorization: `Bearer ${token}`,
1228
- 'Content-Type': 'application/json',
412
+ return {
413
+ path: toPosix(filePath),
414
+ content: await fs.readFile(target, 'utf8'),
1229
415
  };
1230
- if (process.env.PRLL_SWIMLANE_NAME) {
1231
- headers['X-Prll-Swimlane'] = process.env.PRLL_SWIMLANE_NAME;
416
+ }
417
+ async function loadRemoteMarkdownFile(ctx, wiki, ref, filePath) {
418
+ if (!isMarkdownFile(filePath)) {
419
+ throw new Error(`wiki section requires a Markdown file: ${filePath}`);
1232
420
  }
1233
- const response = await fetch(url, {
1234
- method,
1235
- headers,
1236
- body: options.body,
421
+ const blob = await ctx.client.getWikiBlob(ctx.orgId, wiki.id, {
422
+ path: filePath,
423
+ ref,
1237
424
  });
1238
- if (!response.ok) {
1239
- const text = await response.text().catch(() => '');
1240
- throw new Error(`wiki-service ${method} ${url}: ${response.status} ${response.statusText}${text ? ` — ${text}` : ''}`);
1241
- }
1242
- return response.json();
1243
- }
1244
- async function bulkDownloadFiles(bulkDownloadUrl, token, paths) {
1245
- // Batch in chunks to avoid overly large requests
1246
- const BATCH_SIZE = 100;
1247
- const results = [];
1248
- for (let i = 0; i < paths.length; i += BATCH_SIZE) {
1249
- const batch = paths.slice(i, i + BATCH_SIZE);
1250
- const raw = (await wikiServiceFetch(bulkDownloadUrl, token, {
1251
- method: 'POST',
1252
- body: JSON.stringify({ paths: batch }),
1253
- }));
1254
- results.push(...raw.data);
425
+ // Markdown files should always come back as utf-8 text. Any other
426
+ // encoding (signed_url, legacy base64) means the backend served a
427
+ // binary for a markdown path — surface clearly rather than passing
428
+ // encoded bytes or undefined into downstream parsers.
429
+ if (blob.encoding !== 'utf-8' || blob.content == null) {
430
+ throw new Error(`wiki markdown file unexpectedly returned as non-utf8 content (encoding=${blob.encoding}): ${filePath}`);
1255
431
  }
1256
- return results;
432
+ return {
433
+ path: filePath,
434
+ content: blob.content,
435
+ };
1257
436
  }
1258
437
  // ---------------------------------------------------------------------------
1259
- // Local change detection (manifest-based)
1260
- // ---------------------------------------------------------------------------
1261
- export function computeGitBlobSHA(content) {
1262
- // Manifest SHAs come from Gitea's Git blob object IDs, not raw content hashes.
1263
- // This matches Git's current SHA-1 blob format; if the server ever switches to
1264
- // SHA-256 object IDs, this helper must change in lockstep.
1265
- const header = Buffer.from(`blob ${content.length}\0`, 'utf8');
1266
- return createHash('sha1').update(header).update(content).digest('hex');
1267
- }
1268
- // Exact mirror of the magic signatures where the server's classifier
1269
- // (filetype.IsText → Go http.DetectContentType → isBinaryContentType)
1270
- // rejects content that could still be NUL-free, UTF-8-decodable bytes.
1271
- // Signatures whose match requires NUL or non-UTF-8 bytes (PNG, JPEG, OGG,
1272
- // MIDI, ICO, …) are deliberately omitted — the UTF-8 + NUL checks below
1273
- // already cover them. Keep this table in lockstep with the Go sniffing
1274
- // rules; test/testdata/text-classifier-cases.json is the shared contract
1275
- // both sides verify against.
1276
- const BINARY_MAGIC_PREFIXES = [
1277
- Buffer.from('GIF87a'), // image/gif
1278
- Buffer.from('GIF89a'), // image/gif
1279
- Buffer.from('%PDF-'), // application/pdf
1280
- Buffer.from('BM'), // image/bmp (yes, bare "BM" — Go sniffs it as BMP)
1281
- Buffer.from('ID3'), // audio/mpeg
1282
- Buffer.from([0x50, 0x4b, 0x03, 0x04]), // application/zip
1283
- Buffer.from([0x1f, 0x8b, 0x08]), // application/x-gzip
1284
- ];
1285
- // Container formats Go sniffs via offset-masked signatures: 4-byte container
1286
- // tag at offset 0, format tag at offset 8.
1287
- const BINARY_CONTAINER_SIGS = [
1288
- { head: 'RIFF', at8: 'WAVE' }, // audio/wave
1289
- { head: 'RIFF', at8: 'AVI ' }, // video/avi
1290
- { head: 'RIFF', at8: 'WEBPVP' }, // image/webp
1291
- { head: 'FORM', at8: 'AIFF' }, // audio/aiff
1292
- ];
1293
- const utf8Strict = new TextDecoder('utf-8', { fatal: true });
1294
- /**
1295
- * Mirror of the server's text classifier (filetype.IsText): content-type
1296
- * magic sniff, valid UTF-8, and no NUL bytes — kept aligned so content the
1297
- * CLI accepts cannot bounce off the server's 422 USE_UPLOAD later. The
1298
- * shared fixture table (test/testdata/text-classifier-cases.json) is
1299
- * verified by both this implementation's tests and the Go package's tests.
1300
- */
1301
- export function isWikiTextContent(content) {
1302
- for (const magic of BINARY_MAGIC_PREFIXES) {
1303
- if (content.subarray(0, magic.length).equals(magic)) {
1304
- return false;
1305
- }
1306
- }
1307
- for (const sig of BINARY_CONTAINER_SIGS) {
1308
- if (content.subarray(0, 4).equals(Buffer.from(sig.head)) &&
1309
- content.subarray(8, 8 + sig.at8.length).equals(Buffer.from(sig.at8))) {
1310
- return false;
1311
- }
1312
- }
1313
- if (content.includes(0)) {
1314
- return false;
1315
- }
1316
- try {
1317
- utf8Strict.decode(content);
1318
- }
1319
- catch {
1320
- return false;
1321
- }
1322
- return true;
1323
- }
1324
- function looksBinary(content) {
1325
- return !isWikiTextContent(content);
1326
- }
1327
- /** Compute list of changed files by comparing local disk to local manifest. */
1328
- async function computeLocalChanges(mount) {
1329
- const manifest = await readLocalManifest(mount.root);
1330
- const diff = await computeLocalDiff(mount, manifest);
1331
- return diff.diffFiles;
1332
- }
1333
- /**
1334
- * Compute the local workspace diff against the last-synced baseline. Base
1335
- * content comes from the local objects store (with a SHA-verified network
1336
- * fallback for pre-objects mounts), so the diff base is always the true sync
1337
- * point — never the server's current content.
1338
- */
1339
- async function computeLocalDiff(mount, manifest) {
1340
- const diffFiles = [];
1341
- const patchParts = [];
1342
- const visited = new Set();
1343
- const baseShaByPath = new Map();
1344
- const loadBase = async (relPath, entry) => {
1345
- const base = await loadBaselineContent(mount, relPath, entry.sha);
1346
- // A missing baseline (pre-objects mount with a locally dirty file and a
1347
- // server that has since moved) degrades to an empty base: the patch shows
1348
- // the full local content as additions. propose() still carries the right
1349
- // base_sha, so staleness is caught server-side regardless.
1350
- return base ? base.toString('utf8') : '';
1351
- };
1352
- // Walk local files to find modified/added
1353
- await walkLocalFiles(mount.root, mount.root, async (fullPath, relativePath) => {
1354
- visited.add(relativePath);
1355
- const localContent = await fs.readFile(fullPath);
1356
- const localSha = computeGitBlobSHA(localContent);
1357
- const manifestEntry = manifest.files[relativePath];
1358
- if (!manifestEntry) {
1359
- // New file
1360
- const localText = localContent.toString('utf8');
1361
- appendFileDiff(diffFiles, patchParts, relativePath, '', localText, 'create');
1362
- }
1363
- else if (localSha !== manifestEntry.sha) {
1364
- // Modified file
1365
- baseShaByPath.set(relativePath, manifestEntry.sha);
1366
- const baseText = await loadBase(relativePath, manifestEntry);
1367
- appendFileDiff(diffFiles, patchParts, relativePath, baseText, localContent.toString('utf8'), 'update');
1368
- }
1369
- });
1370
- // Find deleted files
1371
- for (const [filePath, entry] of Object.entries(manifest.files)) {
1372
- if (!visited.has(filePath)) {
1373
- baseShaByPath.set(filePath, entry.sha);
1374
- const baseText = await loadBase(filePath, entry);
1375
- appendFileDiff(diffFiles, patchParts, filePath, baseText, '', 'delete');
1376
- }
1377
- }
1378
- diffFiles.sort((a, b) => a.path.localeCompare(b.path));
1379
- const changedPaths = diffFiles.map((f) => f.path);
1380
- const patch = patchParts.join('');
1381
- return { changedPaths, diffFiles, patch, baseShaByPath };
1382
- }
1383
- /** Append one file's real (Myers) unified diff and +/- counts. */
1384
- function appendFileDiff(diffFiles, patchParts, filePath, oldText, newText, action) {
1385
- const hunks = structuredPatch(filePath, filePath, oldText, newText, undefined, undefined, {
1386
- context: 3,
1387
- }).hunks;
1388
- let additions = 0;
1389
- let deletions = 0;
1390
- const parts = [`diff --git a/${filePath} b/${filePath}\n`];
1391
- if (action === 'create') {
1392
- parts.push('new file mode 100644\n');
1393
- }
1394
- else if (action === 'delete') {
1395
- parts.push('deleted file mode 100644\n');
1396
- }
1397
- parts.push(`--- ${action === 'create' ? '/dev/null' : `a/${filePath}`}\n`);
1398
- parts.push(`+++ ${action === 'delete' ? '/dev/null' : `b/${filePath}`}\n`);
1399
- for (const hunk of hunks) {
1400
- parts.push(`@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@\n`);
1401
- for (const line of hunk.lines) {
1402
- parts.push(`${line}\n`);
1403
- if (line.startsWith('+'))
1404
- additions++;
1405
- else if (line.startsWith('-'))
1406
- deletions++;
1407
- }
1408
- }
1409
- diffFiles.push({ path: filePath, action, additions, deletions });
1410
- // An empty-file create/delete produces zero hunks but is still a real
1411
- // change — emit the header-only entry so the patch lists every changed
1412
- // path. Only a hunk-less UPDATE (identical content, e.g. mode-only noise)
1413
- // is genuinely nothing to show.
1414
- if (hunks.length > 0 || action !== 'update') {
1415
- patchParts.push(parts.join(''));
1416
- }
1417
- }
1418
- // ---------------------------------------------------------------------------
1419
- // File system helpers
1420
- // ---------------------------------------------------------------------------
1421
- /** Walk all files (not just markdown) under a root, excluding .parall-wiki. */
1422
- async function walkLocalFiles(root, dir, visitor) {
1423
- const entries = await fs.readdir(dir, { withFileTypes: true });
1424
- for (const entry of entries) {
1425
- if (entry.isDirectory()) {
1426
- if (entry.name === PRLL_WIKI_DIR) {
1427
- continue;
1428
- }
1429
- await walkLocalFiles(root, path.join(dir, entry.name), visitor);
1430
- continue;
1431
- }
1432
- if (!entry.isFile()) {
1433
- continue;
1434
- }
1435
- const fullPath = path.join(dir, entry.name);
1436
- const relativePath = toPosix(path.relative(root, fullPath));
1437
- await visitor(fullPath, relativePath);
1438
- }
1439
- }
1440
- /** Walk only markdown files under a root. */
1441
- async function walkLocalMarkdownFiles(root, dir, visitor) {
1442
- const entries = await fs.readdir(dir, { withFileTypes: true });
1443
- for (const entry of entries) {
1444
- if (entry.isDirectory()) {
1445
- if (entry.name === PRLL_WIKI_DIR) {
1446
- continue;
1447
- }
1448
- await walkLocalMarkdownFiles(root, path.join(dir, entry.name), visitor);
1449
- continue;
1450
- }
1451
- if (!entry.isFile()) {
1452
- continue;
1453
- }
1454
- const fullPath = path.join(dir, entry.name);
1455
- const relativePath = toPosix(path.relative(root, fullPath));
1456
- if (!isMarkdownFile(relativePath)) {
1457
- continue;
1458
- }
1459
- await visitor(fullPath, relativePath);
1460
- }
1461
- }
1462
- /** Remove files not present in manifest. */
1463
- async function removeFilesNotInManifest(root, manifest) {
1464
- await walkLocalFiles(root, root, async (fullPath, relativePath) => {
1465
- if (!(relativePath in manifest.files)) {
1466
- await fs.rm(fullPath, { force: true });
1467
- await removeEmptyParents(root, path.dirname(fullPath));
1468
- }
1469
- });
1470
- }
1471
- /** Remove empty parent directories up to (but not including) root. */
1472
- async function removeEmptyParents(root, dir) {
1473
- const absRoot = path.resolve(root);
1474
- let current = path.resolve(dir);
1475
- while (current !== absRoot && current.startsWith(absRoot)) {
1476
- try {
1477
- const entries = await fs.readdir(current);
1478
- if (entries.length > 0)
1479
- break;
1480
- await fs.rmdir(current);
1481
- current = path.dirname(current);
1482
- }
1483
- catch {
1484
- break;
1485
- }
1486
- }
1487
- }
1488
- // ---------------------------------------------------------------------------
1489
- // Mount resolution
1490
- // ---------------------------------------------------------------------------
1491
- async function resolveLocalWikiMount(ctx, wiki) {
1492
- const mountRoot = ctx.mountRoot ?? process.env.PRLL_WIKI_MOUNT_ROOT;
1493
- let root;
1494
- try {
1495
- root = resolveMountPath(wiki.slug, mountRoot);
1496
- }
1497
- catch {
1498
- return null;
1499
- }
1500
- if (!(await pathExists(root))) {
1501
- return null;
1502
- }
1503
- const baseUrl = resolveWikiServiceBaseUrl(ctx);
1504
- const wikiBase = `${baseUrl}/wiki/v1/orgs/${ctx.orgId}/wikis/${wiki.id}`;
1505
- return {
1506
- root,
1507
- wikiId: wiki.id,
1508
- token: tryResolveApiToken(ctx),
1509
- manifestUrl: `${wikiBase}/manifest`,
1510
- blobUrl: `${wikiBase}/files`,
1511
- bulkDownloadUrl: `${wikiBase}/files/bulk-download`,
1512
- changesetsUrl: `${wikiBase}/changesets`,
1513
- };
1514
- }
1515
- async function requireLocalWikiMount(ctx, wiki) {
1516
- const mount = await resolveLocalWikiMount(ctx, wiki);
1517
- if (!mount) {
1518
- throw new Error(`wiki ${wiki.slug} has no local workspace yet — run \`parall wiki sync\` to download it ` +
1519
- '(the sync output prints the workspace path)');
1520
- }
1521
- return mount;
1522
- }
1523
- // ---------------------------------------------------------------------------
1524
- // Node section loading (unchanged logic, adapts to REST mount)
1525
- // ---------------------------------------------------------------------------
1526
- async function loadWikiNodeSections(ctx, wiki, options = {}) {
1527
- const normalizedRef = normalizeRef(options.ref);
1528
- const normalizedPrefix = normalizeWikiPath(options.pathPrefix);
1529
- if (!normalizedRef) {
1530
- const local = await tryLoadLocalNodeSections(ctx, wiki, normalizedPrefix);
1531
- if (local) {
1532
- const sections = filterNodeSectionsByPathPrefix(flattenLocalNodeSectionFiles(local.files), normalizedPrefix);
1533
- return {
1534
- kind: 'local_mount',
1535
- generatedAt: local.generated_at,
1536
- fileCount: countMatchingMarkdownFiles(local.files, normalizedPrefix),
1537
- sections,
1538
- };
1539
- }
1540
- }
1541
- const artifact = await ctx.client.getWikiNodeSections(ctx.orgId, wiki.id, { ref: normalizedRef });
1542
- const sections = filterNodeSectionsByPathPrefix(artifact.nodes, normalizedPrefix);
1543
- return {
1544
- kind: 'api',
1545
- generatedAt: artifact.generated_at,
1546
- fileCount: countMatchingSectionFiles(artifact.nodes, normalizedPrefix),
1547
- sections,
1548
- };
1549
- }
1550
- async function loadWikiMarkdownFile(ctx, wiki, filePath, ref) {
1551
- const normalizedRef = normalizeRef(ref);
1552
- const normalizedPath = normalizeRequiredWikiPath(filePath);
1553
- if (!normalizedRef) {
1554
- const local = await tryLoadLocalMarkdownFile(ctx, wiki, normalizedPath);
1555
- if (local) {
1556
- return { kind: 'local_mount', file: local };
1557
- }
1558
- }
1559
- return {
1560
- kind: 'api',
1561
- file: await loadRemoteMarkdownFile(ctx, wiki, normalizedRef, normalizedPath),
1562
- };
1563
- }
1564
- async function tryLoadLocalMarkdownFile(ctx, wiki, filePath) {
1565
- const mount = await resolveLocalWikiMount(ctx, wiki);
1566
- if (!mount) {
1567
- return null;
1568
- }
1569
- enforceAllowedPrefix(filePath, []);
1570
- const target = resolvePathInsideRoot(mount.root, filePath);
1571
- const stat = await fs.stat(target).catch(() => null);
1572
- if (!stat) {
1573
- throw new Error(`wiki file not found in local mount: ${filePath}`);
1574
- }
1575
- if (!stat.isFile()) {
1576
- throw new Error(`wiki path is not a file: ${filePath}`);
1577
- }
1578
- if (!isMarkdownFile(filePath)) {
1579
- throw new Error(`wiki section requires a Markdown file: ${filePath}`);
1580
- }
1581
- return {
1582
- path: toPosix(filePath),
1583
- content: await fs.readFile(target, 'utf8'),
1584
- };
1585
- }
1586
- async function loadRemoteMarkdownFile(ctx, wiki, ref, filePath) {
1587
- if (!isMarkdownFile(filePath)) {
1588
- throw new Error(`wiki section requires a Markdown file: ${filePath}`);
1589
- }
1590
- const blob = await ctx.client.getWikiBlob(ctx.orgId, wiki.id, {
1591
- path: filePath,
1592
- ref,
1593
- });
1594
- // Markdown files should always come back as utf-8 text. Any other
1595
- // encoding (signed_url, legacy base64) means the backend served a
1596
- // binary for a markdown path — surface clearly rather than passing
1597
- // encoded bytes or undefined into downstream parsers.
1598
- if (blob.encoding !== 'utf-8' || blob.content == null) {
1599
- throw new Error(`wiki markdown file unexpectedly returned as non-utf8 content (encoding=${blob.encoding}): ${filePath}`);
1600
- }
1601
- return {
1602
- path: filePath,
1603
- content: blob.content,
1604
- };
1605
- }
1606
- async function tryLoadLocalNodeSections(ctx, wiki, pathPrefix) {
1607
- const mount = await resolveLocalWikiMount(ctx, wiki);
1608
- if (!mount) {
1609
- return null;
1610
- }
1611
- if (pathPrefix) {
1612
- enforceAllowedPrefix(pathPrefix, []);
1613
- }
1614
- return loadOrBuildLocalNodeSectionArtifact(wiki, mount);
1615
- }
1616
- async function loadOrBuildLocalNodeSectionArtifact(wiki, mount) {
1617
- const artifactPath = path.join(mount.root, PRLL_WIKI_DIR, 'node-sections.json');
1618
- const descriptors = await collectLocalMarkdownDescriptors(mount.root, []);
1619
- const cached = await readLocalNodeSectionArtifact(artifactPath);
1620
- const artifact = {
1621
- version: LOCAL_NODE_SECTION_ARTIFACT_VERSION,
1622
- generated_at: new Date().toISOString(),
1623
- wiki_id: wiki.id,
1624
- wiki_slug: wiki.slug,
1625
- wiki_name: wiki.name,
1626
- file_count: descriptors.length,
1627
- files: await buildLocalNodeSectionFiles(wiki, mount.root, descriptors, cached),
1628
- };
1629
- await fs.mkdir(path.dirname(artifactPath), { recursive: true });
1630
- await fs.writeFile(artifactPath, JSON.stringify(artifact, null, 2), 'utf8');
1631
- return artifact;
1632
- }
1633
- async function readLocalNodeSectionArtifact(artifactPath) {
1634
- try {
1635
- const raw = await fs.readFile(artifactPath, 'utf8');
1636
- return JSON.parse(raw);
1637
- }
1638
- catch {
1639
- return null;
1640
- }
1641
- }
1642
- async function collectLocalMarkdownDescriptors(root, allowedPrefixes) {
1643
- const descriptors = [];
1644
- await walkLocalMarkdownFiles(root, root, async (fullPath, relativePath) => {
1645
- if (!matchesAllowedPrefix(relativePath, allowedPrefixes)) {
1646
- return;
1647
- }
1648
- const stat = await fs.stat(fullPath);
1649
- descriptors.push({
1650
- path: relativePath,
1651
- size: stat.size,
1652
- mtime_ms: stat.mtimeMs,
1653
- });
1654
- });
1655
- return descriptors.sort((a, b) => a.path.localeCompare(b.path));
1656
- }
1657
- async function buildLocalNodeSectionFiles(wiki, root, descriptors, cached) {
1658
- const cachedByPath = new Map();
1659
- if (cached &&
1660
- cached.version === LOCAL_NODE_SECTION_ARTIFACT_VERSION &&
1661
- cached.wiki_id === wiki.id &&
1662
- cached.wiki_slug === wiki.slug &&
1663
- cached.wiki_name === wiki.name) {
1664
- for (const file of cached.files) {
1665
- cachedByPath.set(file.path, file);
1666
- }
1667
- }
1668
- const files = [];
1669
- for (const descriptor of descriptors) {
1670
- const existing = cachedByPath.get(descriptor.path);
1671
- if (existing &&
1672
- existing.size === descriptor.size &&
1673
- existing.mtime_ms === descriptor.mtime_ms) {
1674
- files.push(existing);
1675
- continue;
1676
- }
1677
- const content = await fs.readFile(resolvePathInsideRoot(root, descriptor.path), 'utf8');
1678
- files.push({
1679
- ...descriptor,
1680
- nodes: parseMarkdownFile(wiki, {
1681
- path: descriptor.path,
1682
- content,
1683
- }),
1684
- });
1685
- }
1686
- return files.sort((a, b) => a.path.localeCompare(b.path));
1687
- }
1688
- function flattenLocalNodeSectionFiles(files) {
1689
- const sections = [];
1690
- for (const file of files) {
1691
- sections.push(...file.nodes);
1692
- }
1693
- sections.sort((a, b) => {
1694
- if (a.path === b.path) {
1695
- return a.start_line - b.start_line;
1696
- }
1697
- return a.path.localeCompare(b.path);
1698
- });
1699
- return sections;
1700
- }
1701
- function findLocalNodeSection(artifact, nodeId) {
1702
- for (const file of artifact.files) {
1703
- const node = file.nodes.find((entry) => entry.node_id === nodeId);
1704
- if (node) {
1705
- return node;
1706
- }
1707
- }
1708
- return undefined;
1709
- }
1710
- function filterNodeSectionsByPathPrefix(sections, pathPrefix) {
1711
- if (!pathPrefix) {
1712
- return sections;
1713
- }
1714
- return sections.filter((section) => section.path === pathPrefix || section.path.startsWith(`${pathPrefix}/`));
1715
- }
1716
- function countMatchingMarkdownFiles(files, pathPrefix) {
1717
- if (!pathPrefix) {
1718
- return files.length;
1719
- }
1720
- return files.filter((file) => file.path === pathPrefix || file.path.startsWith(`${pathPrefix}/`))
1721
- .length;
1722
- }
1723
- function countMatchingSectionFiles(sections, pathPrefix) {
1724
- const paths = new Set();
1725
- for (const section of sections) {
1726
- if (!pathPrefix || section.path === pathPrefix || section.path.startsWith(`${pathPrefix}/`)) {
1727
- paths.add(section.path);
1728
- }
1729
- }
1730
- return paths.size;
1731
- }
1732
- // ---------------------------------------------------------------------------
1733
- // Stale mount cleanup
1734
- // ---------------------------------------------------------------------------
1735
- async function pruneStaleMounts(mountRoot, activePaths) {
1736
- const root = mountRoot?.trim();
1737
- if (!root)
1738
- return;
1739
- const absRoot = path.resolve(root);
1740
- if (!(await pathExists(absRoot)))
1741
- return;
1742
- const stat = await fs.stat(absRoot);
1743
- if (!stat.isDirectory()) {
1744
- throw new Error(`mount root "${absRoot}" is not a directory`);
1745
- }
1746
- const activeArr = Array.from(activePaths);
1747
- const staleDirs = [];
1748
- await findStaleMountDirs(absRoot, absRoot, activePaths, activeArr, staleDirs);
1749
- // NEVER delete: since existence filtering landed, "absent from the list"
1750
- // no longer implies "deleted" — a library switched to private disappears
1751
- // from the list entirely (by design, indistinguishable from absent), and
1752
- // recursively removing its mount would destroy uncommitted local edits.
1753
- // Retain and report; reclaiming is a deliberate manual act until a
1754
- // positive deletion signal exists.
1755
- for (const staleDir of staleDirs) {
1756
- console.warn(`[wiki sync] mount "${staleDir}" no longer maps to a visible library — retained (delete manually if the library was removed)`);
1757
- }
1758
- }
1759
- async function findStaleMountDirs(absRoot, dir, activePaths, activeArr, staleDirs) {
1760
- let names;
1761
- try {
1762
- names = await fs.readdir(dir);
1763
- }
1764
- catch {
1765
- return;
1766
- }
1767
- for (const name of names) {
1768
- const fullPath = path.join(dir, name);
1769
- const stat = await fs.lstat(fullPath).catch(() => null);
1770
- if (!stat?.isDirectory() || stat.isSymbolicLink())
1771
- continue;
1772
- if (name === PRLL_WIKI_DIR) {
1773
- const mountDir = path.dirname(fullPath);
1774
- if (mountDir === absRoot)
1775
- continue;
1776
- if (activePaths.has(mountDir))
1777
- continue;
1778
- const prefix = mountDir + path.sep;
1779
- if (activeArr.some((ap) => ap.startsWith(prefix)))
1780
- continue;
1781
- if (await pathExists(path.join(fullPath, LOCAL_MANIFEST_FILE))) {
1782
- staleDirs.push(mountDir);
1783
- }
1784
- continue;
1785
- }
1786
- await findStaleMountDirs(absRoot, fullPath, activePaths, activeArr, staleDirs);
1787
- }
1788
- }
1789
- // ---------------------------------------------------------------------------
1790
- // Changeset summary helper
438
+ // Changeset summary helper
1791
439
  // ---------------------------------------------------------------------------
1792
440
  function toChangesetSummary(cs) {
1793
441
  return {
@@ -1800,706 +448,3 @@ function toChangesetSummary(cs) {
1800
448
  updated_at: cs.updated_at,
1801
449
  };
1802
450
  }
1803
- // ---------------------------------------------------------------------------
1804
- // Search & index engine (unchanged)
1805
- // ---------------------------------------------------------------------------
1806
- function stripNodeSectionContent(section) {
1807
- const { content: _content, ...node } = section;
1808
- return node;
1809
- }
1810
- function buildIndexNodes(sections) {
1811
- const nodes = [];
1812
- // File-level frontmatter folds into only the first section of each file
1813
- // (matching the indexed search-indexer's section-0 gating) so a
1814
- // frontmatter-only query returns one hit per document, not one per section.
1815
- const seenFile = new Set();
1816
- for (const section of sections) {
1817
- const includeFrontmatter = !seenFile.has(section.path);
1818
- seenFile.add(section.path);
1819
- nodes.push(buildIndexedNode(section, includeFrontmatter));
1820
- }
1821
- return nodes;
1822
- }
1823
- function parseMarkdownFile(wiki, file) {
1824
- const lines = file.content.split('\n');
1825
- const frontMatterEnd = detectFrontMatterEnd(lines);
1826
- const fm = parseFrontMatter(lines, frontMatterEnd);
1827
- const headings = extractMarkdownHeadings(lines, frontMatterEnd);
1828
- const fileTitle = defaultFileTitle(file.path);
1829
- if (headings.length === 0) {
1830
- const docNode = buildNodeSection(wiki, {
1831
- nodeId: `${file.path}:doc`,
1832
- path: file.path,
1833
- title: fileTitle,
1834
- headingPath: [],
1835
- level: 0,
1836
- startLine: findFirstNonEmptyLine(lines, frontMatterEnd + 1, lines.length),
1837
- endLine: lines.length,
1838
- content: lines.slice(frontMatterEnd).join('\n').trim(),
1839
- });
1840
- // Keep an empty-body doc node when it carries frontmatter, so a
1841
- // frontmatter-only page still exposes its metadata — matching the Go
1842
- // parser, which always returns the doc section for a no-heading file.
1843
- const keep = !!docNode.content || hasFrontMatter(fm);
1844
- return applyFrontMatter(keep ? [docNode] : [], fm);
1845
- }
1846
- const nodes = [];
1847
- const firstHeadingLine = headings[0].line;
1848
- const preface = lines
1849
- .slice(frontMatterEnd, firstHeadingLine - 1)
1850
- .join('\n')
1851
- .trim();
1852
- if (preface) {
1853
- nodes.push(buildNodeSection(wiki, {
1854
- nodeId: `${file.path}:preface`,
1855
- path: file.path,
1856
- title: fileTitle,
1857
- headingPath: [],
1858
- level: 0,
1859
- startLine: findFirstNonEmptyLine(lines, frontMatterEnd + 1, firstHeadingLine - 1),
1860
- endLine: firstHeadingLine - 1,
1861
- content: preface,
1862
- }));
1863
- }
1864
- for (let i = 0; i < headings.length; i += 1) {
1865
- const current = headings[i];
1866
- const nextLine = i + 1 < headings.length ? headings[i + 1].line : lines.length + 1;
1867
- nodes.push(buildNodeSection(wiki, {
1868
- nodeId: `${file.path}:L${current.line}`,
1869
- path: file.path,
1870
- title: current.title,
1871
- headingPath: current.path,
1872
- level: current.level,
1873
- startLine: current.line,
1874
- endLine: nextLine - 1,
1875
- content: lines
1876
- .slice(current.line, nextLine - 1)
1877
- .join('\n')
1878
- .trim(),
1879
- }));
1880
- }
1881
- return applyFrontMatter(nodes, fm);
1882
- }
1883
- // applyFrontMatter copies file-level frontmatter onto every section parsed from
1884
- // the file (frontmatter is a document-level property in OKF). Mirrors the Go
1885
- // implementation in server/pkg/markdown/section.go. No-op when empty.
1886
- function applyFrontMatter(sections, fm) {
1887
- if (!hasFrontMatter(fm)) {
1888
- return sections;
1889
- }
1890
- for (const section of sections) {
1891
- if (fm.type !== undefined)
1892
- section.type = fm.type;
1893
- if (fm.description !== undefined)
1894
- section.description = fm.description;
1895
- if (fm.tags !== undefined)
1896
- section.tags = fm.tags;
1897
- }
1898
- return sections;
1899
- }
1900
- function buildNodeSection(wiki, input) {
1901
- const content = input.content.trim();
1902
- const sectionPath = input.headingPath.length > 0 ? `${input.path} > ${input.headingPath.join(' > ')}` : input.path;
1903
- return {
1904
- wiki_id: wiki.id,
1905
- wiki_slug: wiki.slug,
1906
- wiki_name: wiki.name,
1907
- node_id: input.nodeId,
1908
- path: input.path,
1909
- title: input.title,
1910
- heading_path: input.headingPath.length > 0 ? [...input.headingPath] : undefined,
1911
- section_path: sectionPath,
1912
- level: input.level,
1913
- start_line: input.startLine,
1914
- end_line: input.endLine,
1915
- content,
1916
- };
1917
- }
1918
- function buildIndexedNode(section, includeFrontmatter) {
1919
- const searchText = [
1920
- section.path,
1921
- section.title,
1922
- section.heading_path?.join(' ') ?? '',
1923
- ...(includeFrontmatter
1924
- ? [section.type ?? '', section.description ?? '', section.tags?.join(' ') ?? '']
1925
- : []),
1926
- section.content,
1927
- ]
1928
- .join('\n')
1929
- .trim();
1930
- const termFreq = new Map();
1931
- const tokens = tokenize(searchText);
1932
- for (const token of tokens) {
1933
- termFreq.set(token, (termFreq.get(token) ?? 0) + 1);
1934
- }
1935
- return {
1936
- section,
1937
- content: section.content,
1938
- lowerPath: section.path.toLowerCase(),
1939
- lowerTitle: section.title.toLowerCase(),
1940
- lowerBody: section.content.toLowerCase(),
1941
- lowerJoined: section.section_path.toLowerCase(),
1942
- termFreq,
1943
- docLen: tokens.length,
1944
- };
1945
- }
1946
- function scoreNodes(nodes, query, options) {
1947
- const queryTokens = tokenize(query);
1948
- if (queryTokens.length === 0) {
1949
- throw new Error('query did not contain searchable terms');
1950
- }
1951
- const docFreq = new Map();
1952
- let totalDocLen = 0;
1953
- for (const node of nodes) {
1954
- totalDocLen += node.docLen;
1955
- for (const token of node.termFreq.keys()) {
1956
- docFreq.set(token, (docFreq.get(token) ?? 0) + 1);
1957
- }
1958
- }
1959
- const avgDocLen = nodes.length > 0 ? Math.max(totalDocLen / nodes.length, 1) : 1;
1960
- const lowerQuery = query.toLowerCase();
1961
- const limit = options.limit && options.limit > 0 ? options.limit : 5;
1962
- const results = [];
1963
- for (const node of nodes) {
1964
- const score = scoreNode(node, queryTokens, lowerQuery, docFreq, nodes.length, avgDocLen);
1965
- if (score <= 0) {
1966
- continue;
1967
- }
1968
- results.push({
1969
- ...stripNodeSectionContent(node.section),
1970
- score,
1971
- snippet: buildSnippet(node, lowerQuery, queryTokens),
1972
- content: options.includeContent ? node.content : undefined,
1973
- source: options.source,
1974
- });
1975
- }
1976
- results.sort((a, b) => {
1977
- if (b.score === a.score) {
1978
- if (a.path === b.path) {
1979
- return a.start_line - b.start_line;
1980
- }
1981
- return a.path.localeCompare(b.path);
1982
- }
1983
- return b.score - a.score;
1984
- });
1985
- return results.slice(0, limit);
1986
- }
1987
- function planWikiQuery(sections, query, options) {
1988
- const queryTokens = tokenize(query);
1989
- if (queryTokens.length === 0) {
1990
- throw new Error('query did not contain searchable terms');
1991
- }
1992
- const lowerQuery = query.toLowerCase();
1993
- const limit = options.limit && options.limit > 0 ? options.limit : 5;
1994
- const documents = buildIndexedDocuments(sections);
1995
- const rankedDocuments = scoreDocuments(documents, queryTokens, lowerQuery)
1996
- .filter((entry) => entry.score > 0)
1997
- .sort((a, b) => {
1998
- if (b.score === a.score) {
1999
- return a.document.path.localeCompare(b.document.path);
2000
- }
2001
- return b.score - a.score;
2002
- });
2003
- const shortlistedDocuments = rankedDocuments.slice(0, Math.max(limit * 2, 3));
2004
- const shortlistedNodes = buildIndexNodes(shortlistedDocuments.flatMap((entry) => entry.document.sections));
2005
- const docScoreByPath = new Map(shortlistedDocuments.map((entry) => [entry.document.path, entry.score]));
2006
- const results = [];
2007
- for (const node of shortlistedNodes) {
2008
- const documentScore = docScoreByPath.get(node.section.path) ?? 0;
2009
- const plan = scoreTreeAwareNode(node, queryTokens, lowerQuery, documentScore, shortlistedNodes);
2010
- if (plan.score <= 0) {
2011
- continue;
2012
- }
2013
- results.push({
2014
- ...stripNodeSectionContent(node.section),
2015
- score: plan.score,
2016
- document_score: documentScore,
2017
- snippet: buildSnippet(node, lowerQuery, queryTokens),
2018
- content: options.includeContent ? node.content : undefined,
2019
- source: options.source,
2020
- reasoning: plan.reasoning,
2021
- });
2022
- }
2023
- results.sort((a, b) => {
2024
- if (b.score === a.score) {
2025
- if (a.path === b.path) {
2026
- return a.start_line - b.start_line;
2027
- }
2028
- return a.path.localeCompare(b.path);
2029
- }
2030
- return b.score - a.score;
2031
- });
2032
- return {
2033
- documents: shortlistedDocuments.map(({ document, score }) => ({
2034
- path: document.path,
2035
- title: document.title,
2036
- score,
2037
- matched_headings: findMatchedHeadings(document, lowerQuery, queryTokens),
2038
- node_count: document.sections.length,
2039
- })),
2040
- sections: results.slice(0, limit),
2041
- };
2042
- }
2043
- function buildIndexedDocuments(sections) {
2044
- const byPath = new Map();
2045
- for (const section of sections) {
2046
- const bucket = byPath.get(section.path);
2047
- if (bucket) {
2048
- bucket.push(section);
2049
- }
2050
- else {
2051
- byPath.set(section.path, [section]);
2052
- }
2053
- }
2054
- const documents = [];
2055
- for (const [filePath, fileSections] of byPath.entries()) {
2056
- fileSections.sort((a, b) => a.start_line - b.start_line);
2057
- const headings = Array.from(new Set(fileSections.flatMap((section) => section.heading_path ?? []).filter(Boolean)));
2058
- const title = fileSections.find((section) => section.level === 0)?.title ?? defaultFileTitle(filePath);
2059
- const searchText = [filePath, title, headings.join(' ')].join('\n').trim();
2060
- const tokens = tokenize(searchText);
2061
- const termFreq = new Map();
2062
- for (const token of tokens) {
2063
- termFreq.set(token, (termFreq.get(token) ?? 0) + 1);
2064
- }
2065
- documents.push({
2066
- path: filePath,
2067
- title,
2068
- sections: fileSections,
2069
- lowerPath: filePath.toLowerCase(),
2070
- lowerTitle: title.toLowerCase(),
2071
- lowerJoined: `${filePath} ${title} ${headings.join(' ')}`.toLowerCase(),
2072
- headings,
2073
- termFreq,
2074
- docLen: tokens.length,
2075
- });
2076
- }
2077
- documents.sort((a, b) => a.path.localeCompare(b.path));
2078
- return documents;
2079
- }
2080
- function scoreDocuments(documents, queryTokens, lowerQuery) {
2081
- const docFreq = new Map();
2082
- let totalDocLen = 0;
2083
- for (const document of documents) {
2084
- totalDocLen += document.docLen;
2085
- for (const token of document.termFreq.keys()) {
2086
- docFreq.set(token, (docFreq.get(token) ?? 0) + 1);
2087
- }
2088
- }
2089
- const avgDocLen = documents.length > 0 ? Math.max(totalDocLen / documents.length, 1) : 1;
2090
- return documents.map((document) => {
2091
- const pseudoNode = {
2092
- section: {
2093
- wiki_id: document.sections[0]?.wiki_id ?? '',
2094
- wiki_slug: document.sections[0]?.wiki_slug ?? '',
2095
- wiki_name: document.sections[0]?.wiki_name ?? '',
2096
- node_id: `${document.path}:doc`,
2097
- path: document.path,
2098
- title: document.title,
2099
- heading_path: document.headings,
2100
- section_path: document.path,
2101
- level: 0,
2102
- start_line: 1,
2103
- end_line: 1,
2104
- content: '',
2105
- },
2106
- content: '',
2107
- lowerPath: document.lowerPath,
2108
- lowerTitle: document.lowerTitle,
2109
- lowerBody: '',
2110
- lowerJoined: document.lowerJoined,
2111
- termFreq: document.termFreq,
2112
- docLen: document.docLen,
2113
- };
2114
- return {
2115
- document,
2116
- score: scoreNode(pseudoNode, queryTokens, lowerQuery, docFreq, documents.length, avgDocLen),
2117
- };
2118
- });
2119
- }
2120
- function scoreTreeAwareNode(node, queryTokens, lowerQuery, documentScore, scope) {
2121
- const docFreq = new Map();
2122
- let totalDocLen = 0;
2123
- for (const entry of scope) {
2124
- totalDocLen += entry.docLen;
2125
- for (const token of entry.termFreq.keys()) {
2126
- docFreq.set(token, (docFreq.get(token) ?? 0) + 1);
2127
- }
2128
- }
2129
- const avgDocLen = scope.length > 0 ? Math.max(totalDocLen / scope.length, 1) : 1;
2130
- let score = scoreNode(node, queryTokens, lowerQuery, docFreq, scope.length, avgDocLen);
2131
- const reasoning = [];
2132
- if (documentScore > 0) {
2133
- score += documentScore * 0.35;
2134
- reasoning.push('selected from a high-scoring document');
2135
- }
2136
- if (lowerQuery && node.lowerTitle.includes(lowerQuery)) {
2137
- score += 2.5;
2138
- reasoning.push('section title directly matches the query');
2139
- }
2140
- const matchedAncestors = (node.section.heading_path ?? [])
2141
- .slice(0, -1)
2142
- .filter((heading) => heading.toLowerCase().includes(lowerQuery) ||
2143
- queryTokens.some((token) => heading.toLowerCase().includes(token)));
2144
- if (matchedAncestors.length > 0) {
2145
- score += matchedAncestors.length * 1.25;
2146
- reasoning.push('ancestor headings match the query context');
2147
- }
2148
- const headingTokenHits = queryTokens.filter((token) => (node.section.heading_path ?? []).some((heading) => heading.toLowerCase().includes(token))).length;
2149
- if (headingTokenHits > 0) {
2150
- score += headingTokenHits * 0.6;
2151
- reasoning.push('heading path overlaps with query terms');
2152
- }
2153
- if (node.section.level > 0 && node.section.level <= 2) {
2154
- score += 0.2;
2155
- }
2156
- return { score, reasoning };
2157
- }
2158
- function findMatchedHeadings(document, lowerQuery, queryTokens) {
2159
- return document.headings
2160
- .filter((heading) => {
2161
- const lower = heading.toLowerCase();
2162
- return ((lowerQuery && lower.includes(lowerQuery)) ||
2163
- queryTokens.some((token) => lower.includes(token)));
2164
- })
2165
- .slice(0, 5);
2166
- }
2167
- function scoreNode(node, queryTokens, lowerQuery, docFreq, totalDocs, avgDocLen) {
2168
- const k1 = 1.5;
2169
- const b = 0.75;
2170
- const docLen = Math.max(node.docLen, 1);
2171
- let score = 0;
2172
- for (const token of queryTokens) {
2173
- const tf = node.termFreq.get(token) ?? 0;
2174
- if (tf === 0) {
2175
- continue;
2176
- }
2177
- const df = docFreq.get(token) ?? 0;
2178
- if (df === 0) {
2179
- continue;
2180
- }
2181
- const idf = Math.log(1 + (totalDocs - df + 0.5) / (df + 0.5));
2182
- score += idf * ((tf * (k1 + 1)) / (tf + k1 * (1 - b + b * (docLen / avgDocLen))));
2183
- }
2184
- if (lowerQuery) {
2185
- if (node.lowerTitle.includes(lowerQuery)) {
2186
- score += 3;
2187
- }
2188
- else if (node.lowerJoined.includes(lowerQuery)) {
2189
- score += 2;
2190
- }
2191
- else if (node.lowerPath.includes(lowerQuery)) {
2192
- score += 1.5;
2193
- }
2194
- if (node.lowerBody.includes(lowerQuery)) {
2195
- score += 1;
2196
- }
2197
- }
2198
- return score;
2199
- }
2200
- function buildSnippet(node, lowerQuery, queryTokens) {
2201
- const lines = [node.section.title, ...node.content.split('\n')];
2202
- for (const line of lines) {
2203
- const compact = compactWhitespace(line);
2204
- if (!compact) {
2205
- continue;
2206
- }
2207
- const lower = compact.toLowerCase();
2208
- if (lowerQuery && lower.includes(lowerQuery)) {
2209
- return truncateSnippet(compact, 220);
2210
- }
2211
- }
2212
- for (const line of lines) {
2213
- const compact = compactWhitespace(line);
2214
- if (!compact) {
2215
- continue;
2216
- }
2217
- const lower = compact.toLowerCase();
2218
- if (queryTokens.some((token) => lower.includes(token))) {
2219
- return truncateSnippet(compact, 220);
2220
- }
2221
- }
2222
- return truncateSnippet(compactWhitespace(node.content || node.section.section_path), 220);
2223
- }
2224
- // ---------------------------------------------------------------------------
2225
- // Markdown parsing helpers
2226
- // ---------------------------------------------------------------------------
2227
- function extractMarkdownHeadings(lines, startIndex) {
2228
- const headings = [];
2229
- const stack = [];
2230
- let fenceMarker = '';
2231
- for (let i = startIndex; i < lines.length; i += 1) {
2232
- const trimmed = lines[i].trim();
2233
- const marker = parseFenceMarker(trimmed);
2234
- if (marker) {
2235
- if (!fenceMarker) {
2236
- fenceMarker = marker;
2237
- }
2238
- else if (trimmed.startsWith(fenceMarker)) {
2239
- fenceMarker = '';
2240
- }
2241
- continue;
2242
- }
2243
- if (fenceMarker) {
2244
- continue;
2245
- }
2246
- const match = lines[i].match(MARKDOWN_HEADING_RE);
2247
- if (!match) {
2248
- continue;
2249
- }
2250
- const level = match[1].length;
2251
- const title = normalizeHeadingTitle(match[2]);
2252
- if (!title) {
2253
- continue;
2254
- }
2255
- while (stack.length > 0 && stack[stack.length - 1].level >= level) {
2256
- stack.pop();
2257
- }
2258
- const headingPath = [...stack.map((entry) => entry.title), title];
2259
- headings.push({
2260
- title,
2261
- level,
2262
- line: i + 1,
2263
- path: headingPath,
2264
- });
2265
- stack.push({ title, level });
2266
- }
2267
- return headings;
2268
- }
2269
- // Exported for unit testing; mirrors server/pkg/markdown/section.go.
2270
- export function detectFrontMatterEnd(lines) {
2271
- if (lines.length === 0) {
2272
- return 0;
2273
- }
2274
- // Fences must sit at the line start; only trailing spaces / tabs / CR are
2275
- // allowed (right-trim, NOT trim). An indented ` ---` is legal content — e.g.
2276
- // inside a YAML block scalar — and must not open or close the block. Mirrors
2277
- // server/pkg/markdown/section.go and the micromark frontmatter grammar.
2278
- const rtrim = (s) => s.replace(/[ \t\r]+$/, '');
2279
- const first = rtrim(lines[0]);
2280
- if (first !== '---' && first !== '+++') {
2281
- return 0;
2282
- }
2283
- for (let i = 1; i < lines.length; i += 1) {
2284
- if (rtrim(lines[i]) === first) {
2285
- return i + 1;
2286
- }
2287
- }
2288
- return 0;
2289
- }
2290
- function normalizeHeadingTitle(raw) {
2291
- return raw
2292
- .replace(TRAILING_FENCE_RE, '')
2293
- .trim()
2294
- .replace(/^`+|`+$/g, '');
2295
- }
2296
- function parseNodeId(nodeId) {
2297
- const match = nodeId.match(/^(.*):(doc|preface|L(\d+))$/);
2298
- if (!match || !match[1]) {
2299
- throw new Error(`invalid wiki node_id: ${nodeId}`);
2300
- }
2301
- const filePath = normalizeRequiredWikiPath(match[1]);
2302
- if (match[2] === 'doc') {
2303
- return { path: filePath, kind: 'doc' };
2304
- }
2305
- if (match[2] === 'preface') {
2306
- return { path: filePath, kind: 'preface' };
2307
- }
2308
- return {
2309
- path: filePath,
2310
- kind: 'line',
2311
- line: Number.parseInt(match[3], 10),
2312
- };
2313
- }
2314
- function parseFenceMarker(line) {
2315
- if (line.startsWith('```')) {
2316
- return '```';
2317
- }
2318
- if (line.startsWith('~~~')) {
2319
- return '~~~';
2320
- }
2321
- return '';
2322
- }
2323
- function defaultFileTitle(filePath) {
2324
- const base = path.posix.basename(filePath, path.posix.extname(filePath));
2325
- return base.replaceAll('-', ' ').replaceAll('_', ' ').trim() || filePath;
2326
- }
2327
- function findFirstNonEmptyLine(lines, startLine, endLine) {
2328
- const start = Math.max(startLine, 1);
2329
- const end = Math.min(endLine, lines.length);
2330
- for (let i = start; i <= end; i += 1) {
2331
- if (lines[i - 1]?.trim()) {
2332
- return i;
2333
- }
2334
- }
2335
- return start;
2336
- }
2337
- // ---------------------------------------------------------------------------
2338
- // Path & string utilities
2339
- // ---------------------------------------------------------------------------
2340
- function normalizeRef(ref) {
2341
- const value = ref?.trim();
2342
- return value ? value : undefined;
2343
- }
2344
- function normalizeWikiPath(value) {
2345
- if (!value) {
2346
- return '';
2347
- }
2348
- const normalized = toPosix(value.trim())
2349
- .replace(/^\.?\//, '')
2350
- .replace(/^\/+/, '');
2351
- return normalized === '.' ? '' : normalized.replace(/\/+$/, '');
2352
- }
2353
- // Exported so the binary-file helpers (wiki-files.ts) normalize repo paths
2354
- // through the exact same rules as every other CLI path entry point.
2355
- export function normalizeRequiredWikiPath(value) {
2356
- const normalized = normalizeWikiPath(value);
2357
- if (!normalized) {
2358
- throw new Error('path is required');
2359
- }
2360
- return normalized;
2361
- }
2362
- function resolveAgentId(explicit) {
2363
- const value = explicit?.trim() || process.env.PRLL_AGENT_ID?.trim() || process.env.AGENT_ID?.trim();
2364
- return value || undefined;
2365
- }
2366
- function resolveMountPath(mountPath, mountRoot) {
2367
- const trimmedMountPath = mountPath.trim();
2368
- if (!trimmedMountPath) {
2369
- throw new Error('mount path is required');
2370
- }
2371
- if (mountRoot?.trim()) {
2372
- const absoluteRoot = path.resolve(mountRoot.trim());
2373
- const candidate = path.isAbsolute(trimmedMountPath)
2374
- ? path.resolve(trimmedMountPath)
2375
- : path.resolve(absoluteRoot, trimmedMountPath);
2376
- const relative = path.relative(absoluteRoot, candidate);
2377
- if (!relative ||
2378
- relative === '.' ||
2379
- relative === '..' ||
2380
- relative.startsWith(`..${path.sep}`)) {
2381
- throw new Error(`mount path "${mountPath}" escapes PRLL_WIKI_MOUNT_ROOT`);
2382
- }
2383
- return candidate;
2384
- }
2385
- if (path.isAbsolute(trimmedMountPath)) {
2386
- throw new Error('absolute mount path requires PRLL_WIKI_MOUNT_ROOT');
2387
- }
2388
- return path.resolve(trimmedMountPath);
2389
- }
2390
- function resolvePathInsideRoot(root, relativePath) {
2391
- const normalized = normalizeWikiPath(relativePath);
2392
- const candidate = path.resolve(root, normalized);
2393
- const relative = path.relative(root, candidate);
2394
- if (relative === '' ||
2395
- relative === '.' ||
2396
- relative === '..' ||
2397
- relative.startsWith(`..${path.sep}`)) {
2398
- throw new Error(`path "${relativePath}" escapes wiki root`);
2399
- }
2400
- return candidate;
2401
- }
2402
- // ACL is now enforced server-side via path_scopes. These helpers are no-ops.
2403
- function enforceAllowedPrefix(_pathPrefix, _allowedPrefixes) {
2404
- // No-op: server handles ACL via path_scopes.
2405
- }
2406
- function matchesAllowedPrefix(_filePath, _allowedPrefixes) {
2407
- // Server manifest already filters by ACL — all returned files are readable.
2408
- return true;
2409
- }
2410
- function isMarkdownFile(filePath) {
2411
- const ext = path.posix.extname(toPosix(filePath)).toLowerCase();
2412
- return ext === '.md' || ext === '.markdown' || ext === '.mdx';
2413
- }
2414
- function compactWhitespace(value) {
2415
- return value.trim().split(/\s+/).filter(Boolean).join(' ');
2416
- }
2417
- function truncateSnippet(value, limit) {
2418
- if (value.length <= limit) {
2419
- return value;
2420
- }
2421
- if (limit <= 3) {
2422
- return value.slice(0, limit);
2423
- }
2424
- return `${value.slice(0, limit - 3)}...`;
2425
- }
2426
- function toPosix(value) {
2427
- return value.split(path.sep).join(path.posix.sep);
2428
- }
2429
- function normalizeOptionalString(value) {
2430
- const normalized = value?.trim();
2431
- return normalized ? normalized : undefined;
2432
- }
2433
- async function pathExists(target) {
2434
- try {
2435
- await fs.access(target);
2436
- return true;
2437
- }
2438
- catch {
2439
- return false;
2440
- }
2441
- }
2442
- function requireAgentId(ctx) {
2443
- const agentId = resolveAgentId(ctx.agentId);
2444
- if (!agentId) {
2445
- throw new Error('wiki write tools require PRLL_AGENT_ID or an explicit agentId');
2446
- }
2447
- return agentId;
2448
- }
2449
- // ---------------------------------------------------------------------------
2450
- // Tokenizer (CJK-aware, for search/query)
2451
- // ---------------------------------------------------------------------------
2452
- function tokenize(text) {
2453
- const trimmed = text.trim();
2454
- if (!trimmed) {
2455
- return [];
2456
- }
2457
- const tokens = [];
2458
- let word = '';
2459
- let cjkRun = '';
2460
- const flushWord = () => {
2461
- if (!word) {
2462
- return;
2463
- }
2464
- tokens.push(word.toLowerCase());
2465
- word = '';
2466
- };
2467
- const flushCjk = () => {
2468
- if (!cjkRun) {
2469
- return;
2470
- }
2471
- const chars = Array.from(cjkRun.toLowerCase());
2472
- tokens.push(...chars);
2473
- if (chars.length > 1) {
2474
- for (let i = 0; i < chars.length - 1; i += 1) {
2475
- tokens.push(chars[i] + chars[i + 1]);
2476
- }
2477
- }
2478
- cjkRun = '';
2479
- };
2480
- for (const char of Array.from(trimmed)) {
2481
- if (isCjkChar(char)) {
2482
- flushWord();
2483
- cjkRun += char;
2484
- continue;
2485
- }
2486
- if (/[0-9\p{L}]/u.test(char)) {
2487
- flushCjk();
2488
- word += char.toLowerCase();
2489
- continue;
2490
- }
2491
- flushWord();
2492
- flushCjk();
2493
- }
2494
- flushWord();
2495
- flushCjk();
2496
- return tokens;
2497
- }
2498
- function isCjkChar(char) {
2499
- const codePoint = char.codePointAt(0) ?? 0;
2500
- return ((codePoint >= 0x4e00 && codePoint <= 0x9fff) ||
2501
- (codePoint >= 0x3400 && codePoint <= 0x4dbf) ||
2502
- (codePoint >= 0x3040 && codePoint <= 0x309f) ||
2503
- (codePoint >= 0x30a0 && codePoint <= 0x30ff) ||
2504
- (codePoint >= 0xac00 && codePoint <= 0xd7af));
2505
- }