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