@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
|
@@ -0,0 +1,637 @@
|
|
|
1
|
+
// Wiki sync engine: mount sync / watch, the three-way sync planner, conflict
|
|
2
|
+
// settlement into the working tree and stale mount cleanup.
|
|
3
|
+
// Entry point for consumers is ./wiki.ts, which re-exports the public surface.
|
|
4
|
+
import { promises as fs } from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { hasDelimiterLine, mergeTextThreeWay } from './wiki-merge.js';
|
|
7
|
+
import { LOCAL_MANIFEST_FILE, PRLL_WIKI_DIR, bulkDownloadFiles, computeGitBlobSHA, isReadableWiki, isWikiTextContent, pathExists, removeEmptyParents, requireAgentId, resolveApiToken, resolveMountPath, resolvePathInsideRoot, resolveWikiRef, resolveWikiServiceBaseUrl, walkLocalFiles, wikiServiceFetch, } from './wiki-shared.js';
|
|
8
|
+
import { ensureBaselineObjects, gcBaselineObjects, probeLocalGitBlob, readBaselineObject, readLocalManifest, writeLocalManifest, } from './wiki-workspace.js';
|
|
9
|
+
const CONFLICTS_DIR = 'conflicts';
|
|
10
|
+
const REMOTE_CONFLICT_SUFFIX = '.remote';
|
|
11
|
+
/** Your pre-merge working copy, kept next to a file sync rewrote with conflict markers. */
|
|
12
|
+
const MINE_COPY_SUFFIX = '.mine';
|
|
13
|
+
/** Legacy (pre in-file markers) marker for "server deleted, you edited"; only ever cleaned up now. */
|
|
14
|
+
const REMOTE_DELETED_MARKER_SUFFIX = '.remote-deleted';
|
|
15
|
+
const CONFLICT_ARTIFACT_SUFFIXES = [
|
|
16
|
+
MINE_COPY_SUFFIX,
|
|
17
|
+
REMOTE_CONFLICT_SUFFIX,
|
|
18
|
+
REMOTE_DELETED_MARKER_SUFFIX,
|
|
19
|
+
];
|
|
20
|
+
/**
|
|
21
|
+
* Sync wiki workspaces via REST (manifest comparison + bulk download).
|
|
22
|
+
* Without `wikiRef`: every accessible wiki is synced and stale mount
|
|
23
|
+
* directories are pruned. With `wikiRef`: only that wiki is synced and
|
|
24
|
+
* pruning is skipped — other wikis' workspaces must survive a scoped sync.
|
|
25
|
+
* Mount path is determined client-side: {mountRoot}/{slug}/
|
|
26
|
+
*/
|
|
27
|
+
export async function syncAllMounts(ctx, wikiRef) {
|
|
28
|
+
const allWikis = (await ctx.client.getWikis(ctx.orgId)).filter(isReadableWiki);
|
|
29
|
+
const target = wikiRef?.trim() ? await resolveWikiRef(ctx, wikiRef) : undefined;
|
|
30
|
+
const wikis = target ? allWikis.filter((w) => w.id === target.id) : allWikis;
|
|
31
|
+
const mountRoot = ctx.mountRoot?.trim() || process.env.PRLL_WIKI_MOUNT_ROOT?.trim();
|
|
32
|
+
const activeMountPaths = new Set();
|
|
33
|
+
const synced = [];
|
|
34
|
+
for (const wiki of wikis) {
|
|
35
|
+
const mountPath = resolveMountPath(wiki.slug, mountRoot);
|
|
36
|
+
activeMountPaths.add(mountPath);
|
|
37
|
+
const outcome = await syncSingleWiki(ctx, wiki, mountPath);
|
|
38
|
+
synced.push({
|
|
39
|
+
slug: wiki.slug,
|
|
40
|
+
path: mountPath,
|
|
41
|
+
applied: outcome.applied,
|
|
42
|
+
fastForwarded: outcome.fastForwarded,
|
|
43
|
+
conflicts: outcome.conflicts,
|
|
44
|
+
failed: outcome.failed,
|
|
45
|
+
merged: outcome.merged,
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
if (!target) {
|
|
49
|
+
await pruneStaleMounts(mountRoot, activeMountPaths);
|
|
50
|
+
}
|
|
51
|
+
const ok = synced.every((s) => s.failed.length === 0);
|
|
52
|
+
return { ok, mounts: wikis.length, synced };
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Run {@link syncAllMounts} in a loop, sleeping `intervalSec` between
|
|
56
|
+
* iterations. Returns a `stop` callback to break the loop.
|
|
57
|
+
*/
|
|
58
|
+
export function watchMounts(ctx, intervalSec) {
|
|
59
|
+
requireAgentId(ctx); // fail fast if agentId missing
|
|
60
|
+
let stopped = false;
|
|
61
|
+
const doSync = async () => {
|
|
62
|
+
try {
|
|
63
|
+
await syncAllMounts(ctx);
|
|
64
|
+
}
|
|
65
|
+
catch (err) {
|
|
66
|
+
process.stderr.write(`wiki refresh failed: ${err instanceof Error ? err.message : String(err)}\n`);
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
const timer = setInterval(doSync, intervalSec * 1000);
|
|
70
|
+
const stop = () => {
|
|
71
|
+
if (stopped)
|
|
72
|
+
return;
|
|
73
|
+
stopped = true;
|
|
74
|
+
clearInterval(timer);
|
|
75
|
+
};
|
|
76
|
+
process.on('SIGINT', stop);
|
|
77
|
+
process.on('SIGTERM', stop);
|
|
78
|
+
return { stop };
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Pure three-way sync planner. Decides what to do per-path given the base
|
|
82
|
+
* (manifest entry from last successful sync), the current local working tree
|
|
83
|
+
* sha, and the latest remote sha. No I/O.
|
|
84
|
+
*/
|
|
85
|
+
export function planSyncActions(input) {
|
|
86
|
+
const actions = [];
|
|
87
|
+
for (const p of input.paths) {
|
|
88
|
+
const baseSha = input.baseSha(p);
|
|
89
|
+
const remote = input.remote(p);
|
|
90
|
+
const remoteSha = remote?.sha ?? null;
|
|
91
|
+
const localSha = input.localSha(p);
|
|
92
|
+
if (baseSha === remoteSha) {
|
|
93
|
+
actions.push({ kind: 'noop', path: p });
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
const cleanLocal = localSha === baseSha;
|
|
97
|
+
if (cleanLocal) {
|
|
98
|
+
if (remoteSha === null) {
|
|
99
|
+
actions.push({ kind: 'apply-delete', path: p });
|
|
100
|
+
}
|
|
101
|
+
else {
|
|
102
|
+
actions.push({ kind: 'apply-write', path: p, remoteSha, remoteSize: remote.size });
|
|
103
|
+
}
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
if (localSha !== null && localSha === remoteSha) {
|
|
107
|
+
actions.push({ kind: 'fast-forward', path: p, remoteSha, remoteSize: remote.size });
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
if (localSha === null && remoteSha === null) {
|
|
111
|
+
actions.push({ kind: 'fast-forward-delete', path: p });
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
if (remoteSha === null) {
|
|
115
|
+
actions.push({ kind: 'conflict-delete', path: p, baseSha: baseSha });
|
|
116
|
+
}
|
|
117
|
+
else {
|
|
118
|
+
actions.push({
|
|
119
|
+
kind: 'conflict-write',
|
|
120
|
+
path: p,
|
|
121
|
+
remoteSha,
|
|
122
|
+
remoteSize: remote.size,
|
|
123
|
+
baseSha,
|
|
124
|
+
localSha,
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return actions;
|
|
129
|
+
}
|
|
130
|
+
export async function syncSingleWiki(ctx, wiki, mountPath) {
|
|
131
|
+
await fs.mkdir(mountPath, { recursive: true });
|
|
132
|
+
const metaDir = path.join(mountPath, PRLL_WIKI_DIR);
|
|
133
|
+
await fs.mkdir(metaDir, { recursive: true });
|
|
134
|
+
const token = resolveApiToken(ctx);
|
|
135
|
+
const baseUrl = resolveWikiServiceBaseUrl(ctx);
|
|
136
|
+
const manifestUrl = `${baseUrl}/wiki/v1/orgs/${ctx.orgId}/wikis/${wiki.id}/manifest`;
|
|
137
|
+
const bulkDownloadUrl = `${baseUrl}/wiki/v1/orgs/${ctx.orgId}/wikis/${wiki.id}/files/bulk-download`;
|
|
138
|
+
// 1. Fetch server manifest + read local manifest.
|
|
139
|
+
const manifestResp = (await wikiServiceFetch(manifestUrl, token));
|
|
140
|
+
const serverEntries = manifestResp.data;
|
|
141
|
+
const serverByPath = new Map(serverEntries.map((e) => [e.path, e]));
|
|
142
|
+
const localManifest = await readLocalManifest(mountPath);
|
|
143
|
+
// 2. Build the union of paths from server + local manifest + working tree.
|
|
144
|
+
const allPaths = new Set();
|
|
145
|
+
for (const e of serverEntries)
|
|
146
|
+
allPaths.add(e.path);
|
|
147
|
+
for (const p of Object.keys(localManifest.files))
|
|
148
|
+
allPaths.add(p);
|
|
149
|
+
await walkLocalFiles(mountPath, mountPath, async (_full, rel) => {
|
|
150
|
+
allPaths.add(rel);
|
|
151
|
+
});
|
|
152
|
+
// 3. Snapshot working-tree shas so the planner stays pure. Paths whose local
|
|
153
|
+
// shape is incompatible with a regular-file read (e.g. local has a directory
|
|
154
|
+
// where remote treats this as a file, or a parent path is a regular file
|
|
155
|
+
// while remote nests under it) are routed to a 'shape-conflict' failure
|
|
156
|
+
// instead of crashing the whole sync — they need human/agent intervention.
|
|
157
|
+
const localShaCache = new Map();
|
|
158
|
+
const shapeConflictByPath = new Map();
|
|
159
|
+
for (const p of allPaths) {
|
|
160
|
+
const probe = await probeLocalGitBlob(mountPath, p);
|
|
161
|
+
if (probe.kind === 'shape-conflict') {
|
|
162
|
+
shapeConflictByPath.set(p, probe.detail);
|
|
163
|
+
localShaCache.set(p, null);
|
|
164
|
+
}
|
|
165
|
+
else {
|
|
166
|
+
localShaCache.set(p, probe.sha);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
const actions = planSyncActions({
|
|
170
|
+
paths: allPaths,
|
|
171
|
+
baseSha: (p) => localManifest.files[p]?.sha ?? null,
|
|
172
|
+
localSha: (p) => localShaCache.get(p) ?? null,
|
|
173
|
+
remote: (p) => {
|
|
174
|
+
const r = serverByPath.get(p);
|
|
175
|
+
return r ? { sha: r.sha, size: r.size } : null;
|
|
176
|
+
},
|
|
177
|
+
});
|
|
178
|
+
// 4. Fetch all bytes we need (apply-write + conflict-write) in one bulk call.
|
|
179
|
+
const fetchPaths = actions
|
|
180
|
+
.filter((a) => a.kind === 'apply-write' || a.kind === 'conflict-write')
|
|
181
|
+
.map((a) => a.path);
|
|
182
|
+
const contentByPath = new Map();
|
|
183
|
+
const downloadErrorByPath = new Map();
|
|
184
|
+
if (fetchPaths.length > 0) {
|
|
185
|
+
const downloaded = await bulkDownloadFiles(bulkDownloadUrl, token, fetchPaths);
|
|
186
|
+
const returnedPaths = new Set();
|
|
187
|
+
for (const entry of downloaded) {
|
|
188
|
+
returnedPaths.add(entry.path);
|
|
189
|
+
if (entry.error) {
|
|
190
|
+
downloadErrorByPath.set(entry.path, entry.error);
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
contentByPath.set(entry.path, Buffer.from(entry.content_base64, 'base64'));
|
|
194
|
+
}
|
|
195
|
+
// Anything we asked for but the server omitted entirely is also a failure.
|
|
196
|
+
for (const p of fetchPaths) {
|
|
197
|
+
if (!returnedPaths.has(p)) {
|
|
198
|
+
downloadErrorByPath.set(p, 'missing from bulk-download response');
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
// 5. Apply actions and start with the previous manifest, mutating per action.
|
|
203
|
+
const newFiles = { ...localManifest.files };
|
|
204
|
+
const downloadedBySha = new Map();
|
|
205
|
+
const conflicts = [];
|
|
206
|
+
const failed = [];
|
|
207
|
+
const merged = [];
|
|
208
|
+
let applied = 0;
|
|
209
|
+
let fastForwarded = 0;
|
|
210
|
+
/**
|
|
211
|
+
* Settle "the server changed a path you also touched" (edit/edit, add/add,
|
|
212
|
+
* or you deleted it). One invariant for every shape: the path's baseline
|
|
213
|
+
* moves to the server's blob NOW, and the working tree keeps what you meant.
|
|
214
|
+
* Overlapping text edits become `<<<<<<< mine (parall-merge)` … `>>>>>>> latest (parall-merge)` blocks in
|
|
215
|
+
* the file (your pre-merge copy is kept as `.mine`); anything that cannot
|
|
216
|
+
* be merged in place leaves the file alone and drops the server's bytes as
|
|
217
|
+
* `.remote`. Either way the next propose sends a current base_sha, so the
|
|
218
|
+
* agent's only job is to make the file say what it wants.
|
|
219
|
+
*/
|
|
220
|
+
const settleWriteConflict = async (target, remote) => {
|
|
221
|
+
await removeConflictArtifacts(mountPath, target.path);
|
|
222
|
+
const previousLiveSet = localManifest.files[target.path]?.conflict_set;
|
|
223
|
+
const advance = (conflictSet) => {
|
|
224
|
+
newFiles[target.path] = {
|
|
225
|
+
sha: target.remoteSha,
|
|
226
|
+
size: target.remoteSize,
|
|
227
|
+
...(conflictSet ? { conflict_set: conflictSet } : {}),
|
|
228
|
+
};
|
|
229
|
+
downloadedBySha.set(target.remoteSha, remote);
|
|
230
|
+
};
|
|
231
|
+
// Reason classification:
|
|
232
|
+
// - base null + local present → both sides added the same path with different bytes
|
|
233
|
+
// - base present + local null → you deleted locally, the server changed it
|
|
234
|
+
// - base present + local present (and ≠ both) → concurrent edit whose changes overlap
|
|
235
|
+
let reason;
|
|
236
|
+
if (target.baseSha === null) {
|
|
237
|
+
reason = 'remote-added-local-collides';
|
|
238
|
+
}
|
|
239
|
+
else if (target.localSha === null) {
|
|
240
|
+
reason = 'remote-changed-local-deleted';
|
|
241
|
+
}
|
|
242
|
+
else {
|
|
243
|
+
reason = 'remote-changed-local-edited';
|
|
244
|
+
}
|
|
245
|
+
if (target.localSha === null) {
|
|
246
|
+
// Your delete stands; the server's newer bytes are kept for review only.
|
|
247
|
+
const remoteCopy = await writeConflictMarker(mountPath, target.path, REMOTE_CONFLICT_SUFFIX, remote);
|
|
248
|
+
advance();
|
|
249
|
+
conflicts.push({
|
|
250
|
+
path: target.path,
|
|
251
|
+
reason,
|
|
252
|
+
resolution: 'local-delete-kept',
|
|
253
|
+
remoteCopyPath: remoteCopy,
|
|
254
|
+
mineCopyPath: null,
|
|
255
|
+
});
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
const localPath = resolvePathInsideRoot(mountPath, target.path);
|
|
259
|
+
const local = await fs.readFile(localPath);
|
|
260
|
+
const upstreamCopy = async (notMergeableReason) => {
|
|
261
|
+
const remoteCopy = await writeConflictMarker(mountPath, target.path, REMOTE_CONFLICT_SUFFIX, remote);
|
|
262
|
+
advance();
|
|
263
|
+
conflicts.push({
|
|
264
|
+
path: target.path,
|
|
265
|
+
reason,
|
|
266
|
+
resolution: 'upstream-copy',
|
|
267
|
+
remoteCopyPath: remoteCopy,
|
|
268
|
+
mineCopyPath: null,
|
|
269
|
+
notMergeableReason,
|
|
270
|
+
});
|
|
271
|
+
};
|
|
272
|
+
if (computeGitBlobSHA(local) !== target.localSha) {
|
|
273
|
+
// Edited between the snapshot and now — never merge into a moving file.
|
|
274
|
+
await upstreamCopy('moved-since-snapshot');
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
if (previousLiveSet && hasDelimiterLine(local.toString('utf8'), previousLiveSet)) {
|
|
278
|
+
// An earlier sync's block (of the set it recorded) is still in the file;
|
|
279
|
+
// merging again would nest blocks inside blocks. Leave the file, hand
|
|
280
|
+
// over the newer server bytes, and keep the live set on record.
|
|
281
|
+
const remoteCopy = await writeConflictMarker(mountPath, target.path, REMOTE_CONFLICT_SUFFIX, remote);
|
|
282
|
+
advance(previousLiveSet);
|
|
283
|
+
conflicts.push({
|
|
284
|
+
path: target.path,
|
|
285
|
+
reason,
|
|
286
|
+
resolution: 'upstream-copy',
|
|
287
|
+
remoteCopyPath: remoteCopy,
|
|
288
|
+
mineCopyPath: null,
|
|
289
|
+
notMergeableReason: 'unresolved-markers',
|
|
290
|
+
});
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
// add/add has no common ancestor: merge against an empty base so the block
|
|
294
|
+
// shows both whole files, exactly as git does for a two-way add.
|
|
295
|
+
const base = target.baseSha === null
|
|
296
|
+
? Buffer.alloc(0)
|
|
297
|
+
: await readBaselineObject(mountPath, target.baseSha);
|
|
298
|
+
if (!base) {
|
|
299
|
+
await upstreamCopy('no-baseline');
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
const merge = mergeTextThreeWay({ base, local, remote, isText: isWikiTextContent });
|
|
303
|
+
if (merge.kind === 'not-mergeable') {
|
|
304
|
+
await upstreamCopy(merge.reason);
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
if (merge.kind === 'clean') {
|
|
308
|
+
await fs.writeFile(localPath, merge.merged);
|
|
309
|
+
advance();
|
|
310
|
+
merged.push(target.path);
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
const mineCopy = await writeConflictMarker(mountPath, target.path, MINE_COPY_SUFFIX, local);
|
|
314
|
+
await fs.writeFile(localPath, merge.marked);
|
|
315
|
+
advance(merge.set);
|
|
316
|
+
conflicts.push({
|
|
317
|
+
path: target.path,
|
|
318
|
+
reason,
|
|
319
|
+
resolution: 'in-file-markers',
|
|
320
|
+
remoteCopyPath: null,
|
|
321
|
+
mineCopyPath: mineCopy,
|
|
322
|
+
conflictRegions: merge.conflictRegions,
|
|
323
|
+
});
|
|
324
|
+
};
|
|
325
|
+
/**
|
|
326
|
+
* Settle "the server deleted a path you edited": the baseline becomes
|
|
327
|
+
* "absent" so your file is now a pending create, exactly what you meant by
|
|
328
|
+
* keeping it. Deleting it locally accepts the removal — a plain rm, no sync
|
|
329
|
+
* dance.
|
|
330
|
+
*/
|
|
331
|
+
const settleDeleteConflict = async (target) => {
|
|
332
|
+
// An earlier sync's block (of the set it recorded) may still be in the kept
|
|
333
|
+
// file. Dropping the manifest entry would drop that record with it, and
|
|
334
|
+
// propose — which only scans paths with a recorded set — would ship the
|
|
335
|
+
// block as a brand-new file. So while the block is there the entry (old
|
|
336
|
+
// baseline + live set) and the `.mine` copy stay put; once the agent edits
|
|
337
|
+
// the block away, propose's stale precheck sees a baseline the server
|
|
338
|
+
// deleted, re-syncs, and this branch drops the entry as usual.
|
|
339
|
+
const previousLiveSet = localManifest.files[target]?.conflict_set;
|
|
340
|
+
if (previousLiveSet) {
|
|
341
|
+
const kept = await fs.readFile(resolvePathInsideRoot(mountPath, target)).catch(() => null);
|
|
342
|
+
if (kept && hasDelimiterLine(kept.toString('utf8'), previousLiveSet)) {
|
|
343
|
+
conflicts.push({
|
|
344
|
+
path: target,
|
|
345
|
+
reason: 'remote-deleted-local-edited',
|
|
346
|
+
resolution: 'local-file-kept',
|
|
347
|
+
remoteCopyPath: null,
|
|
348
|
+
mineCopyPath: null,
|
|
349
|
+
notMergeableReason: 'unresolved-markers',
|
|
350
|
+
});
|
|
351
|
+
return;
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
await removeConflictArtifacts(mountPath, target);
|
|
355
|
+
delete newFiles[target];
|
|
356
|
+
conflicts.push({
|
|
357
|
+
path: target,
|
|
358
|
+
reason: 'remote-deleted-local-edited',
|
|
359
|
+
resolution: 'local-file-kept',
|
|
360
|
+
remoteCopyPath: null,
|
|
361
|
+
mineCopyPath: null,
|
|
362
|
+
});
|
|
363
|
+
};
|
|
364
|
+
// Surface shape conflicts as sync failures up front so we don't try to write
|
|
365
|
+
// through them. Manifest stays pinned (the path's manifest entry is left as-is).
|
|
366
|
+
for (const [p, detail] of shapeConflictByPath) {
|
|
367
|
+
failed.push({ path: p, reason: 'shape-conflict', detail });
|
|
368
|
+
}
|
|
369
|
+
for (const action of actions) {
|
|
370
|
+
if (shapeConflictByPath.has(action.path)) {
|
|
371
|
+
// Already reported. Don't attempt apply / write — would crash on EISDIR/ENOTDIR.
|
|
372
|
+
continue;
|
|
373
|
+
}
|
|
374
|
+
switch (action.kind) {
|
|
375
|
+
case 'noop': {
|
|
376
|
+
// Preserve manifest entry unchanged. A path whose working copy is back
|
|
377
|
+
// on its baseline no longer needs its conflict artifacts or live set.
|
|
378
|
+
const entry = localManifest.files[action.path];
|
|
379
|
+
const clean = (localShaCache.get(action.path) ?? null) === (entry?.sha ?? null);
|
|
380
|
+
if (clean) {
|
|
381
|
+
await removeConflictArtifacts(mountPath, action.path);
|
|
382
|
+
}
|
|
383
|
+
if (entry?.conflict_set && newFiles[action.path]) {
|
|
384
|
+
// The block was written by an earlier sync; once the agent has
|
|
385
|
+
// edited it away (or the file is clean), the live set is history.
|
|
386
|
+
const stillMarked = !clean &&
|
|
387
|
+
(localShaCache.get(action.path) ?? null) !== null &&
|
|
388
|
+
hasDelimiterLine((await fs.readFile(resolvePathInsideRoot(mountPath, action.path))).toString('utf8'), entry.conflict_set);
|
|
389
|
+
if (!stillMarked) {
|
|
390
|
+
const { conflict_set: _dropped, ...rest } = newFiles[action.path];
|
|
391
|
+
newFiles[action.path] = rest;
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
break;
|
|
395
|
+
}
|
|
396
|
+
case 'apply-write': {
|
|
397
|
+
const buf = contentByPath.get(action.path);
|
|
398
|
+
if (!buf) {
|
|
399
|
+
failed.push({
|
|
400
|
+
path: action.path,
|
|
401
|
+
reason: 'download',
|
|
402
|
+
detail: downloadErrorByPath.get(action.path),
|
|
403
|
+
});
|
|
404
|
+
break;
|
|
405
|
+
}
|
|
406
|
+
// TOCTOU re-check: the snapshot was taken before the bulk-download
|
|
407
|
+
// network round-trip. If the user/agent edited (or deleted) this path
|
|
408
|
+
// in that window, demote to a conflict so we don't silently overwrite.
|
|
409
|
+
const snapshotSha = localShaCache.get(action.path) ?? null;
|
|
410
|
+
const reprobe = await probeLocalGitBlob(mountPath, action.path);
|
|
411
|
+
if (reprobe.kind === 'shape-conflict') {
|
|
412
|
+
failed.push({ path: action.path, reason: 'shape-conflict', detail: reprobe.detail });
|
|
413
|
+
break;
|
|
414
|
+
}
|
|
415
|
+
const currentSha = reprobe.sha;
|
|
416
|
+
if (currentSha === action.remoteSha) {
|
|
417
|
+
// Local converged on remote during the window — manifest-only fast-forward.
|
|
418
|
+
newFiles[action.path] = { sha: action.remoteSha, size: action.remoteSize };
|
|
419
|
+
fastForwarded++;
|
|
420
|
+
break;
|
|
421
|
+
}
|
|
422
|
+
if (currentSha !== snapshotSha) {
|
|
423
|
+
// Local diverged after snapshot. Settle it like any other conflict
|
|
424
|
+
// instead of overwriting. planSyncActions only emits apply-write when
|
|
425
|
+
// localSha === baseSha, so snapshotSha is the baseline here.
|
|
426
|
+
await settleWriteConflict({
|
|
427
|
+
path: action.path,
|
|
428
|
+
remoteSha: action.remoteSha,
|
|
429
|
+
remoteSize: action.remoteSize,
|
|
430
|
+
baseSha: snapshotSha,
|
|
431
|
+
localSha: currentSha,
|
|
432
|
+
}, buf);
|
|
433
|
+
break;
|
|
434
|
+
}
|
|
435
|
+
const fullPath = resolvePathInsideRoot(mountPath, action.path);
|
|
436
|
+
await fs.mkdir(path.dirname(fullPath), { recursive: true });
|
|
437
|
+
await fs.writeFile(fullPath, buf);
|
|
438
|
+
newFiles[action.path] = { sha: action.remoteSha, size: action.remoteSize };
|
|
439
|
+
downloadedBySha.set(action.remoteSha, buf);
|
|
440
|
+
applied++;
|
|
441
|
+
break;
|
|
442
|
+
}
|
|
443
|
+
case 'apply-delete': {
|
|
444
|
+
// TOCTOU re-check before deleting. The action only fires when the
|
|
445
|
+
// snapshot saw clean local matching the (now-deleted) base; if the
|
|
446
|
+
// user re-created or edited the file after the snapshot, demote to
|
|
447
|
+
// conflict-delete instead of dropping their work.
|
|
448
|
+
const snapshotSha = localShaCache.get(action.path) ?? null;
|
|
449
|
+
const reprobe = await probeLocalGitBlob(mountPath, action.path);
|
|
450
|
+
if (reprobe.kind === 'shape-conflict') {
|
|
451
|
+
failed.push({ path: action.path, reason: 'shape-conflict', detail: reprobe.detail });
|
|
452
|
+
break;
|
|
453
|
+
}
|
|
454
|
+
const currentSha = reprobe.sha;
|
|
455
|
+
if (currentSha === null) {
|
|
456
|
+
// Convergence: user also deleted the file during the TOCTOU window.
|
|
457
|
+
// Both sides agree — fast-forward the manifest delete.
|
|
458
|
+
delete newFiles[action.path];
|
|
459
|
+
fastForwarded++;
|
|
460
|
+
break;
|
|
461
|
+
}
|
|
462
|
+
if (currentSha !== snapshotSha) {
|
|
463
|
+
await settleDeleteConflict(action.path);
|
|
464
|
+
break;
|
|
465
|
+
}
|
|
466
|
+
const fullPath = resolvePathInsideRoot(mountPath, action.path);
|
|
467
|
+
await fs.rm(fullPath, { force: true });
|
|
468
|
+
await removeEmptyParents(mountPath, path.dirname(fullPath));
|
|
469
|
+
delete newFiles[action.path];
|
|
470
|
+
applied++;
|
|
471
|
+
break;
|
|
472
|
+
}
|
|
473
|
+
case 'fast-forward':
|
|
474
|
+
// Local already matches remote — only sync the manifest pointer.
|
|
475
|
+
newFiles[action.path] = { sha: action.remoteSha, size: action.remoteSize };
|
|
476
|
+
await removeConflictArtifacts(mountPath, action.path);
|
|
477
|
+
fastForwarded++;
|
|
478
|
+
break;
|
|
479
|
+
case 'fast-forward-delete':
|
|
480
|
+
delete newFiles[action.path];
|
|
481
|
+
await removeConflictArtifacts(mountPath, action.path);
|
|
482
|
+
fastForwarded++;
|
|
483
|
+
break;
|
|
484
|
+
case 'conflict-write': {
|
|
485
|
+
const buf = contentByPath.get(action.path);
|
|
486
|
+
if (!buf) {
|
|
487
|
+
failed.push({
|
|
488
|
+
path: action.path,
|
|
489
|
+
reason: 'download',
|
|
490
|
+
detail: downloadErrorByPath.get(action.path),
|
|
491
|
+
});
|
|
492
|
+
break;
|
|
493
|
+
}
|
|
494
|
+
await settleWriteConflict(action, buf);
|
|
495
|
+
break;
|
|
496
|
+
}
|
|
497
|
+
case 'conflict-delete': {
|
|
498
|
+
await settleDeleteConflict(action.path);
|
|
499
|
+
break;
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
// 6. Persist new manifest + refresh the baseline object store so diff and
|
|
504
|
+
// reset can always reproduce the exact synced content locally.
|
|
505
|
+
const newManifest = {
|
|
506
|
+
wiki_id: wiki.id,
|
|
507
|
+
synced_at: new Date().toISOString(),
|
|
508
|
+
files: newFiles,
|
|
509
|
+
};
|
|
510
|
+
await writeLocalManifest(mountPath, newManifest);
|
|
511
|
+
await ensureBaselineObjects(mountPath, newFiles, downloadedBySha);
|
|
512
|
+
await gcBaselineObjects(mountPath, newFiles);
|
|
513
|
+
for (const p of merged) {
|
|
514
|
+
console.warn(`[wiki sync] merged upstream changes into ${p} (no overlapping hunks)`);
|
|
515
|
+
}
|
|
516
|
+
if (conflicts.length > 0) {
|
|
517
|
+
for (const c of conflicts) {
|
|
518
|
+
const artifact = c.mineCopyPath ?? c.remoteCopyPath;
|
|
519
|
+
const where = artifact ? ` → ${path.relative(mountPath, artifact)}` : '';
|
|
520
|
+
console.warn(`[wiki sync] conflict on ${c.path} (${c.reason}, ${c.resolution})${where}`);
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
if (failed.length > 0) {
|
|
524
|
+
for (const f of failed) {
|
|
525
|
+
const detail = f.detail ? ` — ${f.detail}` : '';
|
|
526
|
+
console.warn(`[wiki sync] failed to ${f.reason} ${f.path}${detail} — manifest unchanged, will retry next sync`);
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
return { applied, fastForwarded, conflicts, failed, merged };
|
|
530
|
+
}
|
|
531
|
+
/**
|
|
532
|
+
* Write a sync conflict marker under .parall-wiki/conflicts/, mirroring the
|
|
533
|
+
* source path so the agent (or user) can locate the upstream copy next to the
|
|
534
|
+
* local edit. Returns the absolute path written.
|
|
535
|
+
*/
|
|
536
|
+
export async function writeConflictMarker(mountRoot, sourcePath, suffix, content) {
|
|
537
|
+
// Validate sourcePath under the mount root before we use it as a key under
|
|
538
|
+
// .parall-wiki/conflicts. The planner only feeds us paths the server returned
|
|
539
|
+
// (so traversal segments are not expected today), but the rest of the sync
|
|
540
|
+
// pipeline always goes through resolvePathInsideRoot and we want this branch
|
|
541
|
+
// to fail closed too — defense in depth, not exploitation today.
|
|
542
|
+
resolvePathInsideRoot(mountRoot, sourcePath);
|
|
543
|
+
const conflictsRoot = path.join(mountRoot, PRLL_WIKI_DIR, CONFLICTS_DIR);
|
|
544
|
+
const target = resolvePathInsideRoot(conflictsRoot, sourcePath + suffix);
|
|
545
|
+
await fs.mkdir(path.dirname(target), { recursive: true });
|
|
546
|
+
await fs.writeFile(target, content);
|
|
547
|
+
return target;
|
|
548
|
+
}
|
|
549
|
+
/**
|
|
550
|
+
* Drop every conflict artifact sync may have left for `sourcePath` (`.mine`,
|
|
551
|
+
* `.remote`, and the legacy `.remote-deleted` marker), pruning empty conflict
|
|
552
|
+
* directories on the way up. Idempotent; missing files are fine.
|
|
553
|
+
*
|
|
554
|
+
* The suffix layout is not injective: a wiki directory literally named
|
|
555
|
+
* `a.mine/` mirrors to `conflicts/a.mine/`, the same location `a`'s `.mine`
|
|
556
|
+
* artifact would take. Cleanup therefore only ever removes a regular file —
|
|
557
|
+
* a directory at an artifact location belongs to someone else's paths and is
|
|
558
|
+
* left alone.
|
|
559
|
+
*/
|
|
560
|
+
export async function removeConflictArtifacts(mountRoot, sourcePath) {
|
|
561
|
+
resolvePathInsideRoot(mountRoot, sourcePath);
|
|
562
|
+
const conflictsRoot = path.join(mountRoot, PRLL_WIKI_DIR, CONFLICTS_DIR);
|
|
563
|
+
for (const suffix of CONFLICT_ARTIFACT_SUFFIXES) {
|
|
564
|
+
const target = resolvePathInsideRoot(conflictsRoot, sourcePath + suffix);
|
|
565
|
+
let stat;
|
|
566
|
+
try {
|
|
567
|
+
stat = await fs.lstat(target);
|
|
568
|
+
}
|
|
569
|
+
catch {
|
|
570
|
+
continue; // nothing there
|
|
571
|
+
}
|
|
572
|
+
if (stat.isDirectory())
|
|
573
|
+
continue;
|
|
574
|
+
await fs.rm(target, { force: true });
|
|
575
|
+
}
|
|
576
|
+
const parent = path.dirname(resolvePathInsideRoot(conflictsRoot, sourcePath));
|
|
577
|
+
if (parent !== conflictsRoot) {
|
|
578
|
+
await removeEmptyParents(conflictsRoot, parent);
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
// ---------------------------------------------------------------------------
|
|
582
|
+
// Stale mount cleanup
|
|
583
|
+
// ---------------------------------------------------------------------------
|
|
584
|
+
async function pruneStaleMounts(mountRoot, activePaths) {
|
|
585
|
+
const root = mountRoot?.trim();
|
|
586
|
+
if (!root)
|
|
587
|
+
return;
|
|
588
|
+
const absRoot = path.resolve(root);
|
|
589
|
+
if (!(await pathExists(absRoot)))
|
|
590
|
+
return;
|
|
591
|
+
const stat = await fs.stat(absRoot);
|
|
592
|
+
if (!stat.isDirectory()) {
|
|
593
|
+
throw new Error(`mount root "${absRoot}" is not a directory`);
|
|
594
|
+
}
|
|
595
|
+
const activeArr = Array.from(activePaths);
|
|
596
|
+
const staleDirs = [];
|
|
597
|
+
await findStaleMountDirs(absRoot, absRoot, activePaths, activeArr, staleDirs);
|
|
598
|
+
// NEVER delete: since existence filtering landed, "absent from the list"
|
|
599
|
+
// no longer implies "deleted" — a library switched to private disappears
|
|
600
|
+
// from the list entirely (by design, indistinguishable from absent), and
|
|
601
|
+
// recursively removing its mount would destroy uncommitted local edits.
|
|
602
|
+
// Retain and report; reclaiming is a deliberate manual act until a
|
|
603
|
+
// positive deletion signal exists.
|
|
604
|
+
for (const staleDir of staleDirs) {
|
|
605
|
+
console.warn(`[wiki sync] mount "${staleDir}" no longer maps to a visible library — retained (delete manually if the library was removed)`);
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
async function findStaleMountDirs(absRoot, dir, activePaths, activeArr, staleDirs) {
|
|
609
|
+
let names;
|
|
610
|
+
try {
|
|
611
|
+
names = await fs.readdir(dir);
|
|
612
|
+
}
|
|
613
|
+
catch {
|
|
614
|
+
return;
|
|
615
|
+
}
|
|
616
|
+
for (const name of names) {
|
|
617
|
+
const fullPath = path.join(dir, name);
|
|
618
|
+
const stat = await fs.lstat(fullPath).catch(() => null);
|
|
619
|
+
if (!stat?.isDirectory() || stat.isSymbolicLink())
|
|
620
|
+
continue;
|
|
621
|
+
if (name === PRLL_WIKI_DIR) {
|
|
622
|
+
const mountDir = path.dirname(fullPath);
|
|
623
|
+
if (mountDir === absRoot)
|
|
624
|
+
continue;
|
|
625
|
+
if (activePaths.has(mountDir))
|
|
626
|
+
continue;
|
|
627
|
+
const prefix = mountDir + path.sep;
|
|
628
|
+
if (activeArr.some((ap) => ap.startsWith(prefix)))
|
|
629
|
+
continue;
|
|
630
|
+
if (await pathExists(path.join(fullPath, LOCAL_MANIFEST_FILE))) {
|
|
631
|
+
staleDirs.push(mountDir);
|
|
632
|
+
}
|
|
633
|
+
continue;
|
|
634
|
+
}
|
|
635
|
+
await findStaleMountDirs(absRoot, fullPath, activePaths, activeArr, staleDirs);
|
|
636
|
+
}
|
|
637
|
+
}
|