@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.
@@ -0,0 +1,335 @@
1
+ // Wiki changeset proposal: propose with stale-base recovery, next-action
2
+ // summaries and workspace reset. Entry point for consumers is ./wiki.ts.
3
+ import { promises as fs } from 'node:fs';
4
+ import path from 'node:path';
5
+ import { decideStaleRecovery, findStalePaths, formatStaleRecoveryError, formatUnresolvedMarkersError, hasDelimiterLine, isStaleBaseError, } from './wiki-merge.js';
6
+ import { TEXT_MAX_BYTES, looksBinary, normalizeOptionalString, pathExists, removeEmptyParents, requireLocalWikiMount, requireMountToken, resolvePathInsideRoot, resolveWikiRef, wikiServiceFetch, } from './wiki-shared.js';
7
+ import { computeLocalChanges, computeLocalDiff, loadBaselineContent, readLocalManifest, writeLocalManifest, } from './wiki-workspace.js';
8
+ import { removeConflictArtifacts, syncSingleWiki } from './wiki-sync.js';
9
+ // ---------------------------------------------------------------------------
10
+ // AFCS: propose changeset (REST-based)
11
+ // ---------------------------------------------------------------------------
12
+ export async function proposeWikiChangeset(ctx, wikiRef, options) {
13
+ const wiki = await resolveWikiRef(ctx, wikiRef);
14
+ const mount = await requireLocalWikiMount(ctx, wiki);
15
+ const title = options.title.trim();
16
+ if (!title) {
17
+ throw new Error('title is required');
18
+ }
19
+ // Stale-base recovery loop. A stale base (the server moved since the last
20
+ // sync) is recovered automatically: re-sync — a three-way merge that keeps
21
+ // local edits — then propose again, at most MAX_STALE_RECOVERIES times.
22
+ // Anything the merge could not settle (overlapping edits, download
23
+ // failures, a server that keeps moving) surfaces as an error that names the
24
+ // paths and the next step; the workspace is never rolled back.
25
+ let recovery = null;
26
+ for (let attempt = 0;; attempt++) {
27
+ const outcome = await proposeOnce(ctx, wiki, mount, title, options, recovery);
28
+ if (outcome.kind === 'submitted') {
29
+ return outcome.result;
30
+ }
31
+ recovery = await recoverFromStaleBase(ctx, wiki, mount, {
32
+ stale: outcome.stale,
33
+ detectedBy: outcome.detectedBy,
34
+ attempt,
35
+ });
36
+ }
37
+ }
38
+ /**
39
+ * Re-sync after a stale-base hit and decide whether propose may run again.
40
+ * Throws the agent-facing guidance when it may not.
41
+ */
42
+ async function recoverFromStaleBase(ctx, wiki, mount, input) {
43
+ const outcome = await syncSingleWiki(ctx, wiki, mount.root);
44
+ const decision = decideStaleRecovery({ attempt: input.attempt, outcome });
45
+ if (decision.kind === 'stop') {
46
+ throw new Error(formatStaleRecoveryError({ stale: input.stale, decision, outcome }));
47
+ }
48
+ return {
49
+ stale_paths: input.stale.map((s) => s.path),
50
+ detected_by: input.detectedBy,
51
+ sync: {
52
+ applied: outcome.applied,
53
+ fast_forwarded: outcome.fastForwarded,
54
+ merged: outcome.merged,
55
+ },
56
+ };
57
+ }
58
+ /**
59
+ * Stale-base precheck (fail-closed): compare each changed path's sync
60
+ * baseline against the server's CURRENT manifest. Proposing from a stale
61
+ * baseline would upload full content that silently rolls back concurrent
62
+ * edits. The server re-validates via base_sha (authoritative — this check
63
+ * just catches it earlier, with the complete file list).
64
+ */
65
+ async function findStalePathsAgainstServer(mount, diff) {
66
+ const serverManifest = (await wikiServiceFetch(mount.manifestUrl, requireMountToken(mount)));
67
+ const serverShaByPath = new Map(serverManifest.data.map((e) => [e.path, e.sha]));
68
+ return findStalePaths({
69
+ changedPaths: diff.changedPaths,
70
+ baseSha: (p) => diff.baseShaByPath.get(p),
71
+ serverSha: (p) => serverShaByPath.get(p),
72
+ });
73
+ }
74
+ async function proposeOnce(ctx, wiki, mount, title, options, recovery) {
75
+ const manifest = await readLocalManifest(mount.root);
76
+ const diff = await computeLocalDiff(mount, manifest);
77
+ if (diff.changedPaths.length === 0) {
78
+ if (recovery) {
79
+ throw new Error(`nothing left to propose for wiki ${wiki.slug}: the server already has your changes ` +
80
+ `(re-sync fast-forwarded ${recovery.stale_paths.join(', ')}).`);
81
+ }
82
+ throw new Error(`no changes to propose for wiki ${wiki.slug} — edit files under ${mount.root} first, ` +
83
+ 'then run `parall wiki diff` to confirm what will be proposed');
84
+ }
85
+ // Backstop for the in-file conflict markers `sync` writes: a file still
86
+ // carrying a `<<<<<<< mine (parall-merge)` … `>>>>>>> latest (parall-merge)` block
87
+ // (its own delimiter set — see wiki-merge.ts) is not a document yet.
88
+ // Local and fail-closed — checked before any network call so the agent gets
89
+ // the direct answer rather than a stale-base detour.
90
+ const unresolved = [];
91
+ for (const filePath of diff.changedPaths) {
92
+ const liveSet = manifest.files[filePath]?.conflict_set;
93
+ if (!liveSet)
94
+ continue; // no live block recorded → any marker-shaped text is content
95
+ const localPath = resolvePathInsideRoot(mount.root, filePath);
96
+ if (!(await pathExists(localPath)))
97
+ continue;
98
+ const content = await fs.readFile(localPath);
99
+ if (hasDelimiterLine(content.toString('utf8'), liveSet)) {
100
+ unresolved.push(filePath);
101
+ }
102
+ }
103
+ if (unresolved.length > 0) {
104
+ throw new Error(formatUnresolvedMarkersError(unresolved));
105
+ }
106
+ const stale = await findStalePathsAgainstServer(mount, diff);
107
+ if (stale.length > 0) {
108
+ return { kind: 'stale', stale, detectedBy: 'precheck' };
109
+ }
110
+ // Build file_changes for the changeset API
111
+ const fileChanges = [];
112
+ // The marker scan above ran before the network precheck; a file rewritten in
113
+ // that window (an editor, another agent) would otherwise ship its delimiter
114
+ // lines. Guard the exact buffer that gets encoded, not an earlier read.
115
+ const unresolvedAtEncode = [];
116
+ for (const filePath of diff.changedPaths) {
117
+ const localPath = resolvePathInsideRoot(mount.root, filePath);
118
+ const existsLocally = await pathExists(localPath);
119
+ const baseEntry = manifest.files[filePath];
120
+ if (!existsLocally) {
121
+ // Deleted
122
+ fileChanges.push({
123
+ path: filePath,
124
+ action: 'delete',
125
+ base_sha: baseEntry?.sha,
126
+ });
127
+ }
128
+ else {
129
+ const content = await fs.readFile(localPath);
130
+ // The changeset API is text-only (the server rejects binary with 422
131
+ // USE_UPLOAD, pointing at an endpoint the CLI does not wrap). Reject
132
+ // locally with a clear boundary statement instead.
133
+ if (looksBinary(content)) {
134
+ throw new Error(`cannot propose ${filePath}: wiki changesets support text files only. ` +
135
+ 'Remove the binary from the workspace (binary uploads go through the web UI).');
136
+ }
137
+ if (content.length > TEXT_MAX_BYTES) {
138
+ throw new Error(`cannot propose ${filePath}: file is ${content.length} bytes, ` +
139
+ `over the ${TEXT_MAX_BYTES}-byte changeset limit. Split the file or remove it from the workspace.`);
140
+ }
141
+ const liveSet = baseEntry?.conflict_set;
142
+ if (liveSet && hasDelimiterLine(content.toString('utf8'), liveSet)) {
143
+ unresolvedAtEncode.push(filePath);
144
+ continue;
145
+ }
146
+ fileChanges.push({
147
+ path: filePath,
148
+ action: baseEntry ? 'update' : 'create',
149
+ content_base64: content.toString('base64'),
150
+ base_sha: baseEntry?.sha,
151
+ });
152
+ }
153
+ }
154
+ if (unresolvedAtEncode.length > 0) {
155
+ throw new Error(formatUnresolvedMarkersError(unresolvedAtEncode));
156
+ }
157
+ let changeset;
158
+ const existingChangesetId = normalizeOptionalString(options.changesetId);
159
+ try {
160
+ if (existingChangesetId) {
161
+ // Re-propose: replace_files makes the workspace diff define the
162
+ // changeset's FULL content — the server resets the feature branch to
163
+ // default HEAD first, so a change withdrawn locally (file reverted to
164
+ // baseline) actually disappears from the proposal instead of silently
165
+ // surviving on the branch.
166
+ changeset = await ctx.client.updateWikiChangeset(ctx.orgId, wiki.id, existingChangesetId, {
167
+ title,
168
+ message: normalizeOptionalString(options.message),
169
+ file_changes: fileChanges,
170
+ replace_files: true,
171
+ });
172
+ }
173
+ else {
174
+ // Create new changeset via API
175
+ changeset = await ctx.client.createWikiChangeset(ctx.orgId, wiki.id, {
176
+ title,
177
+ message: normalizeOptionalString(options.message),
178
+ file_changes: fileChanges,
179
+ source_chat_id: normalizeOptionalString(options.sourceChatId),
180
+ source_message_id: normalizeOptionalString(options.sourceMessageId),
181
+ source_run_id: normalizeOptionalString(options.sourceRunId),
182
+ });
183
+ }
184
+ }
185
+ catch (error) {
186
+ // The server's base_sha check is authoritative and closes the window
187
+ // between the precheck and the write. Treat it exactly like a precheck
188
+ // hit: the caller re-syncs and retries.
189
+ if (!isStaleBaseError(error)) {
190
+ throw error;
191
+ }
192
+ return {
193
+ kind: 'stale',
194
+ stale: await findStalePathsAgainstServer(mount, diff),
195
+ detectedBy: 'server',
196
+ };
197
+ }
198
+ // The proposal carries what the agent decided, so the conflict artifacts
199
+ // (.mine / .remote) that helped decide it have served their purpose — and so
200
+ // has the recorded live set.
201
+ let manifestDirty = false;
202
+ for (const filePath of diff.changedPaths) {
203
+ await removeConflictArtifacts(mount.root, filePath);
204
+ const entry = manifest.files[filePath];
205
+ if (entry?.conflict_set) {
206
+ delete entry.conflict_set;
207
+ manifestDirty = true;
208
+ }
209
+ }
210
+ if (manifestDirty) {
211
+ await writeLocalManifest(mount.root, manifest);
212
+ }
213
+ const autoMerged = changeset.status === 'merged';
214
+ let postMergeSync = null;
215
+ let postMergeSyncError = null;
216
+ if (autoMerged) {
217
+ try {
218
+ postMergeSync = await syncSingleWiki(ctx, wiki, mount.root);
219
+ }
220
+ catch (error) {
221
+ postMergeSyncError = error instanceof Error ? error.message : String(error);
222
+ }
223
+ }
224
+ return {
225
+ kind: 'submitted',
226
+ result: {
227
+ wiki_id: wiki.id,
228
+ wiki_slug: wiki.slug,
229
+ wiki_name: wiki.name,
230
+ mount_path: mount.root,
231
+ changed_paths: diff.changedPaths,
232
+ diff_files: diff.diffFiles,
233
+ changeset,
234
+ status: changeset.status,
235
+ auto_merged: autoMerged,
236
+ requires_review: changesetRequiresReview(changeset),
237
+ next_action: describeProposeNextAction(changeset, postMergeSync, postMergeSyncError, recovery),
238
+ post_merge_sync: postMergeSync,
239
+ post_merge_sync_error: postMergeSyncError,
240
+ stale_recovery: recovery,
241
+ source: 'local_mount',
242
+ },
243
+ };
244
+ }
245
+ function changesetRequiresReview(changeset) {
246
+ return (changeset.status === 'proposed' ||
247
+ changeset.status === 'approval_pending' ||
248
+ changeset.status === 'approved');
249
+ }
250
+ function describeProposeNextAction(changeset, postMergeSync, postMergeSyncError, recovery) {
251
+ const prefix = recovery ? `${describeStaleRecovery(recovery)} ` : '';
252
+ return prefix + describeChangesetNextAction(changeset, postMergeSync, postMergeSyncError);
253
+ }
254
+ /** One sentence on what the automatic stale-base recovery did, for the agent's log. */
255
+ function describeStaleRecovery(recovery) {
256
+ const where = recovery.stale_paths.length > 0 ? ` (${recovery.stale_paths.join(', ')})` : '';
257
+ const merged = recovery.sync.merged.length > 0
258
+ ? `, merged the upstream changes into ${recovery.sync.merged.join(', ')} (no overlapping hunks)`
259
+ : '';
260
+ return `The server had moved since your last sync${where}: re-synced${merged}, then re-proposed automatically.`;
261
+ }
262
+ function describeChangesetNextAction(changeset, postMergeSync, postMergeSyncError) {
263
+ if (changeset.status === 'merged') {
264
+ if (postMergeSyncError) {
265
+ return 'Changeset auto-merged. Run `parall wiki sync` to refresh the local manifest.';
266
+ }
267
+ if (postMergeSync && (postMergeSync.conflicts.length > 0 || postMergeSync.failed.length > 0)) {
268
+ return 'Changeset auto-merged, but local sync reported conflicts or failures. Inspect `.parall-wiki/conflicts` and run `parall wiki status`.';
269
+ }
270
+ return 'Changeset auto-merged and the local wiki manifest was refreshed.';
271
+ }
272
+ if (changeset.status === 'conflict') {
273
+ return 'Auto-merge hit a merge conflict. Run `parall wiki sync`, resolve conflicts, then create a new changeset.';
274
+ }
275
+ if (changesetRequiresReview(changeset)) {
276
+ return 'Changeset is awaiting review because it touched a protected path or auto-merge was skipped.';
277
+ }
278
+ if (changeset.status === 'draft') {
279
+ return 'Changeset is still in draft. Run propose again without --update to submit it for review.';
280
+ }
281
+ return `Changeset is ${changeset.status}.`;
282
+ }
283
+ // ---------------------------------------------------------------------------
284
+ // AFCS: reset workspace
285
+ // ---------------------------------------------------------------------------
286
+ /**
287
+ * Discard all local changes and restore files to the last synced state.
288
+ * Restores from the local baseline object store (network only as a
289
+ * SHA-verified fallback for pre-objects mounts), so the workspace lands
290
+ * exactly on the manifest baseline — `wiki status` reports clean afterwards.
291
+ */
292
+ export async function resetWikiWorkspace(ctx, wikiRef) {
293
+ const wiki = await resolveWikiRef(ctx, wikiRef);
294
+ const mount = await requireLocalWikiMount(ctx, wiki);
295
+ const manifest = await readLocalManifest(mount.root);
296
+ // Only touch files that actually diverged from the baseline.
297
+ const changes = await computeLocalChanges(mount);
298
+ if (changes.length === 0) {
299
+ return { wiki_id: wiki.id, wiki_slug: wiki.slug, files_restored: 0, unrestorable_paths: [] };
300
+ }
301
+ let restored = 0;
302
+ const unrestorable = [];
303
+ for (const change of changes) {
304
+ const entry = manifest.files[change.path];
305
+ const fullPath = resolvePathInsideRoot(mount.root, change.path);
306
+ if (!entry) {
307
+ // Locally created file — discard.
308
+ await fs.rm(fullPath, { force: true });
309
+ await removeEmptyParents(mount.root, path.dirname(fullPath));
310
+ restored++;
311
+ continue;
312
+ }
313
+ const baseline = await loadBaselineContent(mount, change.path, entry.sha);
314
+ if (!baseline) {
315
+ // No baseline available (pre-objects mount, server moved on). Leave the
316
+ // local file untouched rather than overwriting it with non-baseline
317
+ // content; `parall wiki sync` is the path that reconciles this state.
318
+ unrestorable.push(change.path);
319
+ continue;
320
+ }
321
+ await fs.mkdir(path.dirname(fullPath), { recursive: true });
322
+ await fs.writeFile(fullPath, baseline);
323
+ restored++;
324
+ }
325
+ if (unrestorable.length > 0) {
326
+ console.warn(`[wiki reset] ${unrestorable.length} file(s) had no recoverable baseline and were left as-is: ` +
327
+ `${unrestorable.join(', ')} — run \`parall wiki sync\` to reconcile`);
328
+ }
329
+ return {
330
+ wiki_id: wiki.id,
331
+ wiki_slug: wiki.slug,
332
+ files_restored: restored,
333
+ unrestorable_paths: unrestorable,
334
+ };
335
+ }
@@ -0,0 +1,291 @@
1
+ import { type ParallClient, type Wiki, type WikiDiff, type WikiDiffFile } from '@parall/sdk';
2
+ export type ParallContext = {
3
+ client: ParallClient;
4
+ orgId: string;
5
+ agentId?: string;
6
+ /** Per-account wiki mount root. Takes priority over process.env.PRLL_WIKI_MOUNT_ROOT. */
7
+ mountRoot?: string;
8
+ /** Base URL of the wiki-service. Defaults to PRLL_WIKI_URL, then PRLL_API_URL. */
9
+ baseUrl?: string;
10
+ };
11
+ export type WikiSearchOptions = {
12
+ ref?: string;
13
+ pathPrefix?: string;
14
+ limit?: number;
15
+ includeContent?: boolean;
16
+ };
17
+ export type WikiNodeSection = {
18
+ wiki_id: string;
19
+ wiki_slug: string;
20
+ wiki_name: string;
21
+ node_id: string;
22
+ path: string;
23
+ title: string;
24
+ heading_path?: string[];
25
+ section_path: string;
26
+ level: number;
27
+ start_line: number;
28
+ end_line: number;
29
+ type?: string;
30
+ description?: string;
31
+ tags?: string[];
32
+ };
33
+ export type WikiOutlineResult = {
34
+ wiki_id: string;
35
+ wiki_slug: string;
36
+ wiki_name: string;
37
+ ref?: string;
38
+ path_prefix?: string;
39
+ generated_at: string;
40
+ file_count: number;
41
+ nodes: WikiNodeSection[];
42
+ source: WikiContentSource;
43
+ };
44
+ export type WikiQueryDocument = {
45
+ path: string;
46
+ title: string;
47
+ score: number;
48
+ matched_headings: string[];
49
+ node_count: number;
50
+ };
51
+ export type WikiQuerySectionResult = WikiSearchResult & {
52
+ document_score: number;
53
+ reasoning: string[];
54
+ };
55
+ export type WikiQueryResult = {
56
+ wiki_id: string;
57
+ wiki_slug: string;
58
+ wiki_name: string;
59
+ query: string;
60
+ ref?: string;
61
+ path_prefix?: string;
62
+ generated_at: string;
63
+ file_count: number;
64
+ source: WikiContentSource;
65
+ documents: WikiQueryDocument[];
66
+ sections: WikiQuerySectionResult[];
67
+ };
68
+ export type WikiSearchResult = WikiNodeSection & {
69
+ score: number;
70
+ snippet: string;
71
+ content?: string;
72
+ source: WikiContentSource;
73
+ };
74
+ export type WikiSectionResult = WikiNodeSection & {
75
+ content: string;
76
+ source: WikiContentSource;
77
+ };
78
+ export type WikiChangesetDiffResult = {
79
+ wiki_id: string;
80
+ wiki_slug: string;
81
+ wiki_name: string;
82
+ changeset_id: string;
83
+ diff: WikiDiff;
84
+ };
85
+ export type WikiWorkspaceStatusResult = {
86
+ wiki_id: string;
87
+ wiki_slug: string;
88
+ wiki_name: string;
89
+ mount_path: string;
90
+ mode: string;
91
+ default_ref: string;
92
+ changed_paths: string[];
93
+ diff_files: WikiDiffFile[];
94
+ dirty: boolean;
95
+ source: 'local_mount';
96
+ };
97
+ export type WikiWorkspaceDiffResult = {
98
+ wiki_id: string;
99
+ wiki_slug: string;
100
+ wiki_name: string;
101
+ mount_path: string;
102
+ changed_paths: string[];
103
+ diff_files: WikiDiffFile[];
104
+ patch: string;
105
+ source: 'local_mount';
106
+ };
107
+ export type MarkdownFile = {
108
+ path: string;
109
+ content: string;
110
+ };
111
+ export type WikiContentSource = 'local_mount' | 'api';
112
+ export type LocalWikiMount = {
113
+ root: string;
114
+ wikiId: string;
115
+ token?: string;
116
+ manifestUrl: string;
117
+ blobUrl: string;
118
+ bulkDownloadUrl: string;
119
+ changesetsUrl: string;
120
+ };
121
+ /** Persisted manifest tracking synced file state on disk. */
122
+ export type LocalManifest = {
123
+ wiki_id: string;
124
+ synced_at: string;
125
+ files: Record<string, LocalManifestFileEntry>;
126
+ };
127
+ export type LocalManifestFileEntry = {
128
+ sha: string;
129
+ size: number;
130
+ /**
131
+ * Set when sync wrote conflict markers into this path's working file: the
132
+ * (1-based) delimiter set of that live block. The propose guard and sync's
133
+ * nested-marker check refuse on ANY remaining delimiter line of exactly this
134
+ * set (a half-deleted block counts), while every other set — a page quoting
135
+ * a lower-numbered block verbatim — is content. Cleared once the path is
136
+ * clean, fast-forwarded, proposed, or the last such line is edited away.
137
+ * Additive; absent on entries written by older CLIs.
138
+ */
139
+ conflict_set?: number;
140
+ };
141
+ /** Server manifest entry returned from GET manifest_url. */
142
+ export type ServerManifestEntry = {
143
+ path: string;
144
+ sha: string;
145
+ size: number;
146
+ };
147
+ /** Bulk download response entry. */
148
+ type BulkDownloadEntry = {
149
+ path: string;
150
+ sha: string;
151
+ content_base64: string;
152
+ size: number;
153
+ error?: string;
154
+ };
155
+ export declare const LOCAL_MANIFEST_FILE = "manifest.json";
156
+ export declare const PRLL_WIKI_DIR = ".parall-wiki";
157
+ export declare const TEXT_MAX_BYTES: number;
158
+ /** A wiki the CLI may operate on: readable (not a degraded listing stub) and
159
+ * therefore always slugged. Everything downstream of listWikis/resolveWikiRef
160
+ * works in this narrowed type. */
161
+ export type ReadableWiki = Wiki & {
162
+ slug: string;
163
+ };
164
+ /** Degraded listing entries (discoverable-but-unreadable libraries) carry no
165
+ * slug and no content access — they exist only so the Web join browser can
166
+ * offer them. The CLI never mounts, syncs or enumerates them. */
167
+ export declare function isReadableWiki(wiki_: Wiki): wiki_ is ReadableWiki;
168
+ export declare function listWikis(ctx: ParallContext): Promise<ReadableWiki[]>;
169
+ export declare function resolveWikiRef(ctx: ParallContext, wikiRef?: string): Promise<ReadableWiki>;
170
+ /**
171
+ * Resolve wiki reference. If wikiRef is omitted or empty, auto-resolves to
172
+ * the org's single wiki. Errors if the org has zero or multiple wikis without
173
+ * a ref specified.
174
+ */
175
+ export declare function resolveWikiRefOrDefault(ctx: ParallContext, wikiRef?: string): Promise<ReadableWiki>;
176
+ export type SyncConflict = {
177
+ path: string;
178
+ /** Which sides moved. */
179
+ reason: 'remote-changed-local-edited' | 'remote-deleted-local-edited' | 'remote-added-local-collides' | 'remote-changed-local-deleted';
180
+ /**
181
+ * What sync left in the working tree. In every case the path's baseline has
182
+ * ALREADY moved to the server's current state (blob, or absent), so the next
183
+ * propose carries a current base_sha — the agent only edits and proposes:
184
+ *
185
+ * - `in-file-markers` — overlapping hunks are wrapped in `<<<<<<< mine (parall-merge)` /
186
+ * `======= (parall-merge)` / `>>>>>>> latest (parall-merge)` inside the working
187
+ * file; `mineCopyPath` holds the pre-merge copy.
188
+ * - `upstream-copy` — could not merge in place (binary, LFS, budget,
189
+ * markers still unresolved from an earlier sync,
190
+ * …); the working file is untouched and the server's
191
+ * bytes are at `remoteCopyPath`.
192
+ * - `local-delete-kept` — you deleted it, the server changed it; the
193
+ * working tree stays without the file (a pending
194
+ * delete) and the server's bytes are at
195
+ * `remoteCopyPath` for review.
196
+ * - `local-file-kept` — the server deleted it, you edited it; the file
197
+ * stays (a pending create). No artifact.
198
+ */
199
+ resolution: 'in-file-markers' | 'upstream-copy' | 'local-delete-kept' | 'local-file-kept';
200
+ /** Absolute path of the server's copy under .parall-wiki/conflicts/, when one was written. */
201
+ remoteCopyPath: string | null;
202
+ /** Absolute path of your pre-merge copy under .parall-wiki/conflicts/, when one was written. */
203
+ mineCopyPath: string | null;
204
+ /** `in-file-markers` only: how many marker blocks the file now contains. */
205
+ conflictRegions?: number;
206
+ /**
207
+ * `upstream-copy`: why the merge could not be written into the file. Also set
208
+ * (`unresolved-markers`) on `local-file-kept` when the server deleted a path
209
+ * whose kept file still carries an unresolved block — its baseline and live
210
+ * set stay recorded until the block is gone.
211
+ */
212
+ notMergeableReason?: 'binary' | 'lfs-pointer' | 'too-complex' | 'delimiter-sets-exhausted' | 'unresolved-markers' | 'no-baseline' | 'moved-since-snapshot';
213
+ };
214
+ export type SyncFailure = {
215
+ path: string;
216
+ /**
217
+ * Reason classification:
218
+ * - 'download' — bulk-download endpoint surfaced a per-file error.
219
+ * - 'shape-conflict' — local working tree has an incompatible file/directory
220
+ * shape at this path (e.g. local `foo` is a directory
221
+ * while remote treats `foo` as a file, or vice versa
222
+ * when remote is `foo/bar.md` but local has `foo` as
223
+ * a regular file).
224
+ */
225
+ reason: 'download' | 'shape-conflict';
226
+ /** Server-supplied error string or local errno, when available. */
227
+ detail?: string;
228
+ };
229
+ export type WikiSyncOutcome = {
230
+ applied: number;
231
+ fastForwarded: number;
232
+ conflicts: SyncConflict[];
233
+ /** Per-path failures that prevented a planned action from running. Manifest is left unchanged for these — next sync retries. */
234
+ failed: SyncFailure[];
235
+ /**
236
+ * Paths both sides edited whose changes did not overlap: the upstream
237
+ * change was merged into the working copy at line level and the manifest
238
+ * advanced to the remote blob. Local edits stay pending for propose.
239
+ */
240
+ merged: string[];
241
+ };
242
+ export declare function resolveApiToken(ctx?: ParallContext): string;
243
+ /**
244
+ * Resolve the wiki-service base URL (trailing slashes trimmed): explicit ctx
245
+ * override, then PRLL_WIKI_URL, then PRLL_API_URL. SSOT for the raw-fetch wiki
246
+ * endpoints (sync / bulk-download / binary file download). Hosted/staging/prod
247
+ * collapse these to one gateway host; local dev can split api (:8080) and wiki
248
+ * (:8090). Returns '' when none is set — callers decide whether that's fatal.
249
+ */
250
+ export declare function resolveWikiServiceBaseUrl(ctx: ParallContext): string;
251
+ export declare function requireMountToken(mount: LocalWikiMount): string;
252
+ export declare function wikiServiceFetch(url: string, token: string, options?: {
253
+ method?: string;
254
+ body?: string;
255
+ }): Promise<unknown>;
256
+ export declare function bulkDownloadFiles(bulkDownloadUrl: string, token: string, paths: string[]): Promise<BulkDownloadEntry[]>;
257
+ export declare function computeGitBlobSHA(content: Buffer): string;
258
+ /**
259
+ * Mirror of the server's text classifier (filetype.IsText): content-type
260
+ * magic sniff, valid UTF-8, and no NUL bytes — kept aligned so content the
261
+ * CLI accepts cannot bounce off the server's 422 USE_UPLOAD later. The
262
+ * shared fixture table (test/testdata/text-classifier-cases.json) is
263
+ * verified by both this implementation's tests and the Go package's tests.
264
+ */
265
+ export declare function isWikiTextContent(content: Buffer): boolean;
266
+ export declare function looksBinary(content: Buffer): boolean;
267
+ /** Walk all files (not just markdown) under a root, excluding .parall-wiki. */
268
+ export declare function walkLocalFiles(root: string, dir: string, visitor: (fullPath: string, relativePath: string) => Promise<void>): Promise<void>;
269
+ /** Walk only markdown files under a root. */
270
+ export declare function walkLocalMarkdownFiles(root: string, dir: string, visitor: (fullPath: string, relativePath: string) => Promise<void>): Promise<void>;
271
+ /** Remove empty parent directories up to (but not including) root. */
272
+ export declare function removeEmptyParents(root: string, dir: string): Promise<void>;
273
+ export declare function resolveLocalWikiMount(ctx: ParallContext, wiki: ReadableWiki): Promise<LocalWikiMount | null>;
274
+ export declare function requireLocalWikiMount(ctx: ParallContext, wiki: ReadableWiki): Promise<LocalWikiMount>;
275
+ export declare function normalizeRef(ref?: string): string | undefined;
276
+ export declare function normalizeWikiPath(value?: string): string;
277
+ export declare function normalizeRequiredWikiPath(value: string): string;
278
+ export declare function resolveAgentId(explicit?: string): string | undefined;
279
+ export declare function resolveMountPath(mountPath: string, mountRoot?: string): string;
280
+ export declare function resolvePathInsideRoot(root: string, relativePath: string): string;
281
+ export declare function enforceAllowedPrefix(_pathPrefix: string, _allowedPrefixes: string[]): void;
282
+ export declare function matchesAllowedPrefix(_filePath: string, _allowedPrefixes: string[]): boolean;
283
+ export declare function isMarkdownFile(filePath: string): boolean;
284
+ export declare function compactWhitespace(value: string): string;
285
+ export declare function truncateSnippet(value: string, limit: number): string;
286
+ export declare function toPosix(value: string): string;
287
+ export declare function normalizeOptionalString(value?: string | null): string | undefined;
288
+ export declare function pathExists(target: string): Promise<boolean>;
289
+ export declare function requireAgentId(ctx: ParallContext): string;
290
+ export {};
291
+ //# sourceMappingURL=wiki-shared.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wiki-shared.d.ts","sourceRoot":"","sources":["../../src/lib/wiki-shared.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,KAAK,YAAY,EAAE,KAAK,IAAI,EAAE,KAAK,QAAQ,EAAE,KAAK,YAAY,EAAE,MAAM,aAAa,CAAC;AAK7F,MAAM,MAAM,aAAa,GAAG;IAC1B,MAAM,EAAE,YAAY,CAAC;IACrB,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,yFAAyF;IACzF,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,kFAAkF;IAClF,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF,MAAM,MAAM,iBAAiB,GAAG;IAC9B,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,cAAc,CAAC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