@foldrun/core 19.1.0 → 19.2.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/src/data-import.d.ts +156 -0
- package/dist/src/data-import.js +670 -0
- package/package.json +1 -1
- package/src/data-import.ts +764 -0
|
@@ -0,0 +1,764 @@
|
|
|
1
|
+
// The data importer (FOL-126 phase 8): an old-style /data folder's workspace
|
|
2
|
+
// content in, as revisions + blobs.
|
|
3
|
+
//
|
|
4
|
+
// scanSource read the folder (never writes to it) and say what is in it
|
|
5
|
+
// runImport publish every workspace's authored files and `state/` through
|
|
6
|
+
// the publish protocol, each side on its own head
|
|
7
|
+
// verifyImport compare every workspace's heads with the folder by path,
|
|
8
|
+
// sha256 and mode, write a per-workspace pass/fail report
|
|
9
|
+
//
|
|
10
|
+
// What it is NOT: runs, the trigger log and the storage index moved into
|
|
11
|
+
// their tables in FOL-152 (foldrun-platform records-import.ts) and are not
|
|
12
|
+
// read here. Run output folders (runs/<id>/) are only counted, so the report
|
|
13
|
+
// says what is still on the volume; phase 5 decides where they go. Secrets
|
|
14
|
+
// are not opened: a secrets file is reported by name and size like any other
|
|
15
|
+
// file nothing maps.
|
|
16
|
+
//
|
|
17
|
+
// Why it exists beside the boot reconcile (workspace-revisions.ts): the
|
|
18
|
+
// reconcile records text only and never adds a binary file to a head; this
|
|
19
|
+
// carries binaries, executable bits and `state/`, as one verified first head
|
|
20
|
+
// authored `import:data-folder`.
|
|
21
|
+
//
|
|
22
|
+
// What it promises:
|
|
23
|
+
// - The source folder is only ever read. No rename, no ".imported" marker:
|
|
24
|
+
// a failed cutover must be able to start over from the same folder.
|
|
25
|
+
// - Dry-run is the default and writes nothing. Without a destination it only
|
|
26
|
+
// reads the folder; with one it also reads (never writes) the heads to say
|
|
27
|
+
// what is already there.
|
|
28
|
+
// - Idempotent and resumable per workspace: every publish is keyed by the
|
|
29
|
+
// content of its change set, so a rerun that finds the same bytes commits
|
|
30
|
+
// nothing, and one that died halfway finishes the rest. A workspace whose
|
|
31
|
+
// history holds a revision NOT made by the importer (someone has used it
|
|
32
|
+
// since, or the reconcile recorded it) is skipped unless `force`, so a
|
|
33
|
+
// rerun after cutover cannot undo real work. Even forced, an import only
|
|
34
|
+
// adds and overwrites; it deletes nothing unless `mirror`.
|
|
35
|
+
// - A path that cannot be a manifest path is REPORTED, never guessed at:
|
|
36
|
+
// symlinks (refused, not followed), names that are not NFC or too long,
|
|
37
|
+
// top-level folders that are in neither the authored nor the state list.
|
|
38
|
+
// Two names that differ only by case cannot share a manifest: the first
|
|
39
|
+
// (byte order) keeps its name, the others are kept as conflict copies,
|
|
40
|
+
// like a conflict anywhere else — nothing is dropped.
|
|
41
|
+
// - A file is never read whole into memory unless it is small: a large one
|
|
42
|
+
// is streamed to the store from disk (pinned first, as a publish pins) and
|
|
43
|
+
// a deep verify streams it back to a temporary file.
|
|
44
|
+
//
|
|
45
|
+
// Imports nothing from the database: the destination is a Deps (BlobStore +
|
|
46
|
+
// RevisionStore), so the same code runs against the local implementations in
|
|
47
|
+
// a test and against Postgres + S3 on dev.
|
|
48
|
+
|
|
49
|
+
import fs from "node:fs";
|
|
50
|
+
import os from "node:os";
|
|
51
|
+
import path from "node:path";
|
|
52
|
+
import crypto from "node:crypto";
|
|
53
|
+
import { pipeline } from "node:stream/promises";
|
|
54
|
+
import {
|
|
55
|
+
AUTHORED_DIRS,
|
|
56
|
+
MAX_MANIFEST_FILES,
|
|
57
|
+
MODE_EXEC,
|
|
58
|
+
MODE_FILE,
|
|
59
|
+
assertManifestPath,
|
|
60
|
+
blobObjectKey,
|
|
61
|
+
conflictPath,
|
|
62
|
+
diffManifests,
|
|
63
|
+
emptyManifest,
|
|
64
|
+
sha256Hex,
|
|
65
|
+
sideOf,
|
|
66
|
+
type Changes,
|
|
67
|
+
type Manifest,
|
|
68
|
+
} from "./manifest.ts";
|
|
69
|
+
import { headsOf, manifestsAt, publish, requestDigest, type Deps } from "./publish.ts";
|
|
70
|
+
import { BlobNotFound, BlobSourceError, downloadToFile, fileSource } from "./blob-store.ts";
|
|
71
|
+
import type { Revision, WorkspaceRef } from "./revision-store.ts";
|
|
72
|
+
import { isPlatformPath } from "./store.ts";
|
|
73
|
+
|
|
74
|
+
// store.ts keeps this pattern private; a name that fails it is not an account or workspace.
|
|
75
|
+
const SAFE_NAME = /^[a-z0-9]+(-[a-z0-9]+)*$/;
|
|
76
|
+
|
|
77
|
+
export const IMPORT_BY = "import:data-folder";
|
|
78
|
+
|
|
79
|
+
/** Files at or under this are read whole for the publish; a larger one is
|
|
80
|
+
* streamed from disk. */
|
|
81
|
+
export const LARGE_FILE_BYTES = 8 * 1024 * 1024;
|
|
82
|
+
/** How long the importer's own pin on a streamed blob lives (a publish's is
|
|
83
|
+
* shorter); released as soon as the publish is done. */
|
|
84
|
+
const LARGE_PIN_TTL_MS = 30 * 60_000;
|
|
85
|
+
|
|
86
|
+
// ------------------------------------------------------------- scan
|
|
87
|
+
|
|
88
|
+
export interface SourceFile {
|
|
89
|
+
/** The manifest path (a conflict copy's path differs from `from`). */
|
|
90
|
+
path: string;
|
|
91
|
+
abs: string;
|
|
92
|
+
sha: string;
|
|
93
|
+
size: number;
|
|
94
|
+
mode: number;
|
|
95
|
+
side: "authored" | "state";
|
|
96
|
+
/** Set when this file is kept under a conflict-copy name; the path it wanted. */
|
|
97
|
+
from?: string;
|
|
98
|
+
}
|
|
99
|
+
export interface Unmapped {
|
|
100
|
+
path: string;
|
|
101
|
+
reason: string;
|
|
102
|
+
/** Files inside (a folder), when counted. */
|
|
103
|
+
files?: number;
|
|
104
|
+
bytes?: number;
|
|
105
|
+
}
|
|
106
|
+
export interface WorkspaceScan {
|
|
107
|
+
tenant: string;
|
|
108
|
+
workspace: string;
|
|
109
|
+
dir: string;
|
|
110
|
+
files: SourceFile[];
|
|
111
|
+
bytes: number;
|
|
112
|
+
unmapped: Unmapped[];
|
|
113
|
+
conflicts: { path: string; keptAs: string }[];
|
|
114
|
+
/** What runs/ holds on the volume, counted and never read: record files
|
|
115
|
+
* (FOL-152 moved those to rows) and output folders (runs/<id>/). */
|
|
116
|
+
runs: { recordFiles: number; outputFolders: number; outputFiles: number; outputBytes: number };
|
|
117
|
+
/** Set when the workspace cannot be imported at all (reason). */
|
|
118
|
+
error?: string;
|
|
119
|
+
}
|
|
120
|
+
export interface TenantScan {
|
|
121
|
+
tenant: string;
|
|
122
|
+
workspaces: WorkspaceScan[];
|
|
123
|
+
/** Account-level folders and files nothing maps here (library/, .history/, storage/, secrets …). */
|
|
124
|
+
unmapped: Unmapped[];
|
|
125
|
+
}
|
|
126
|
+
export interface SourceScan {
|
|
127
|
+
source: string;
|
|
128
|
+
tenants: TenantScan[];
|
|
129
|
+
scannedAt: string;
|
|
130
|
+
}
|
|
131
|
+
export interface ScanOptions {
|
|
132
|
+
source: string;
|
|
133
|
+
/** Only these accounts / "account/workspace" pairs. */
|
|
134
|
+
tenants?: string[];
|
|
135
|
+
workspaces?: string[];
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export async function hashFile(abs: string): Promise<string> {
|
|
139
|
+
const h = crypto.createHash("sha256");
|
|
140
|
+
await pipeline(fs.createReadStream(abs), h);
|
|
141
|
+
return h.digest("hex");
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Count what is under a folder without following links or reading content. */
|
|
145
|
+
function tally(abs: string, limit = 200_000): { files: number; bytes: number } {
|
|
146
|
+
let files = 0;
|
|
147
|
+
let bytes = 0;
|
|
148
|
+
const stack = [abs];
|
|
149
|
+
while (stack.length && files < limit) {
|
|
150
|
+
const d = stack.pop()!;
|
|
151
|
+
let ents: fs.Dirent[] = [];
|
|
152
|
+
try {
|
|
153
|
+
ents = fs.readdirSync(d, { withFileTypes: true });
|
|
154
|
+
} catch {
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
for (const e of ents) {
|
|
158
|
+
const p = path.join(d, e.name);
|
|
159
|
+
if (e.isDirectory()) stack.push(p);
|
|
160
|
+
else {
|
|
161
|
+
files++;
|
|
162
|
+
try {
|
|
163
|
+
bytes += fs.lstatSync(p).size;
|
|
164
|
+
} catch {
|
|
165
|
+
// gone meanwhile
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
return { files, bytes };
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const inExecBit = (st: fs.Stats) => ((st.mode & 0o111) !== 0 ? MODE_EXEC : MODE_FILE);
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Two names that differ only by case cannot share a manifest. The first in
|
|
177
|
+
* byte order keeps its name; each later one is kept as a conflict copy beside
|
|
178
|
+
* it (deterministic, so a rerun names the same file). `rels` must be sorted.
|
|
179
|
+
* Pure, because a case-insensitive disk (a Mac) cannot hold the pair to test
|
|
180
|
+
* the scanner with.
|
|
181
|
+
*/
|
|
182
|
+
export function placeCaseVariants(rels: string[], seed: string): { rel: string; from?: string }[] {
|
|
183
|
+
const byLower = new Set<string>();
|
|
184
|
+
return rels.map((rel) => {
|
|
185
|
+
let out = rel;
|
|
186
|
+
let from: string | undefined;
|
|
187
|
+
if (byLower.has(rel.toLowerCase())) {
|
|
188
|
+
const op = `import-case-${sha256Hex(`${seed}/${rel}`).slice(0, 16)}`;
|
|
189
|
+
for (let n = 0; ; n++) {
|
|
190
|
+
const c = conflictPath(rel, op, n);
|
|
191
|
+
if (!byLower.has(c.toLowerCase())) {
|
|
192
|
+
out = c;
|
|
193
|
+
break;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
from = rel;
|
|
197
|
+
}
|
|
198
|
+
byLower.add(out.toLowerCase());
|
|
199
|
+
return { rel: out, ...(from ? { from } : {}) };
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const byName = (a: fs.Dirent, b: fs.Dirent) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
204
|
+
|
|
205
|
+
/** What a workspace folder holds that is not workspace content, and why it is left. */
|
|
206
|
+
const PLATFORM_MARKERS: Record<string, string> = {
|
|
207
|
+
"trigger-log.jsonl": "trigger log (moved into Postgres by FOL-152; not read here)",
|
|
208
|
+
"trigger-log.jsonl.tmp": "trigger log temp file (not read here)",
|
|
209
|
+
"hooks.json": "webhook tokens (platform file; not mapped)",
|
|
210
|
+
"hook-deliveries.jsonl": "hook delivery log (not mapped)",
|
|
211
|
+
".repo.json": "platform file; not workspace content",
|
|
212
|
+
once: "operation markers (the unique keys decide now; not imported)",
|
|
213
|
+
".foldrun": "platform folder; not workspace content",
|
|
214
|
+
storage: "workspace-local storage folder (the storage index moved in FOL-152; not read here)",
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
async function scanWorkspace(tenant: string, workspace: string, dir: string): Promise<WorkspaceScan> {
|
|
218
|
+
const ws: WorkspaceScan = {
|
|
219
|
+
tenant, workspace, dir, files: [], bytes: 0, unmapped: [], conflicts: [],
|
|
220
|
+
runs: { recordFiles: 0, outputFolders: 0, outputFiles: 0, outputBytes: 0 },
|
|
221
|
+
};
|
|
222
|
+
const found: { rel: string; abs: string; st: fs.Stats }[] = [];
|
|
223
|
+
|
|
224
|
+
const walk = (rel: string) => {
|
|
225
|
+
const abs = path.join(dir, ...rel.split("/"));
|
|
226
|
+
let ents: fs.Dirent[];
|
|
227
|
+
try {
|
|
228
|
+
ents = fs.readdirSync(abs, { withFileTypes: true });
|
|
229
|
+
} catch (err) {
|
|
230
|
+
ws.unmapped.push({ path: rel, reason: `unreadable folder (${(err as NodeJS.ErrnoException).code ?? "error"})` });
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
for (const e of ents.sort(byName)) {
|
|
234
|
+
const r = `${rel}/${e.name}`;
|
|
235
|
+
const a = path.join(abs, e.name);
|
|
236
|
+
let st: fs.Stats;
|
|
237
|
+
try {
|
|
238
|
+
st = fs.lstatSync(a);
|
|
239
|
+
} catch {
|
|
240
|
+
continue;
|
|
241
|
+
}
|
|
242
|
+
if (st.isSymbolicLink()) ws.unmapped.push({ path: r, reason: "symbolic link (refused, never followed)" });
|
|
243
|
+
else if (st.isDirectory()) walk(r);
|
|
244
|
+
else if (st.isFile()) found.push({ rel: r, abs: a, st });
|
|
245
|
+
else ws.unmapped.push({ path: r, reason: "not a regular file" });
|
|
246
|
+
}
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
let top: fs.Dirent[];
|
|
250
|
+
try {
|
|
251
|
+
top = fs.readdirSync(dir, { withFileTypes: true });
|
|
252
|
+
} catch (err) {
|
|
253
|
+
ws.error = `workspace folder unreadable (${(err as NodeJS.ErrnoException).code ?? "error"})`;
|
|
254
|
+
return ws;
|
|
255
|
+
}
|
|
256
|
+
for (const e of top.sort(byName)) {
|
|
257
|
+
const name = e.name;
|
|
258
|
+
const abs = path.join(dir, name);
|
|
259
|
+
let st: fs.Stats;
|
|
260
|
+
try {
|
|
261
|
+
st = fs.lstatSync(abs);
|
|
262
|
+
} catch {
|
|
263
|
+
continue;
|
|
264
|
+
}
|
|
265
|
+
if (st.isSymbolicLink()) {
|
|
266
|
+
ws.unmapped.push({ path: name, reason: "symbolic link (refused, never followed)" });
|
|
267
|
+
} else if (st.isDirectory() && (AUTHORED_DIRS.includes(name) || name === "state")) {
|
|
268
|
+
walk(name);
|
|
269
|
+
} else if (st.isFile() && sideOf(name) === "authored") {
|
|
270
|
+
found.push({ rel: name, abs, st });
|
|
271
|
+
} else if (name === "runs" && st.isDirectory()) {
|
|
272
|
+
// Counted, never read: records are rows now; output folders wait for phase 5.
|
|
273
|
+
for (const r of fs.readdirSync(abs, { withFileTypes: true })) {
|
|
274
|
+
if (r.isDirectory()) {
|
|
275
|
+
const t = tally(path.join(abs, r.name));
|
|
276
|
+
ws.runs.outputFolders++;
|
|
277
|
+
ws.runs.outputFiles += t.files;
|
|
278
|
+
ws.runs.outputBytes += t.bytes;
|
|
279
|
+
} else ws.runs.recordFiles++;
|
|
280
|
+
}
|
|
281
|
+
} else if (/^secrets\.json(\.|$)/.test(name)) {
|
|
282
|
+
// The vault and its lock/temp files: never opened. Named, with a size, like any unmapped file.
|
|
283
|
+
ws.unmapped.push({ path: name, reason: "secrets (never opened here; they move with the vault)", files: 1, bytes: st.size });
|
|
284
|
+
} else if (PLATFORM_MARKERS[name]) {
|
|
285
|
+
const t = st.isDirectory() ? tally(abs) : { files: 1, bytes: st.size };
|
|
286
|
+
ws.unmapped.push({ path: name, reason: PLATFORM_MARKERS[name], ...t });
|
|
287
|
+
} else {
|
|
288
|
+
const t = st.isDirectory() ? tally(abs) : { files: 1, bytes: st.size };
|
|
289
|
+
ws.unmapped.push({ path: name, reason: "not part of a workspace manifest (in neither the authored nor the state list)", ...t });
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// Which of the found files can be a manifest path; case collisions.
|
|
294
|
+
const mapped: { rel: string; abs: string; st: fs.Stats }[] = [];
|
|
295
|
+
for (const f of found) {
|
|
296
|
+
if (isPlatformPath(f.rel)) {
|
|
297
|
+
ws.unmapped.push({ path: f.rel, reason: "platform or engine file, not workspace content", files: 1, bytes: f.st.size });
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
try {
|
|
301
|
+
assertManifestPath(f.rel);
|
|
302
|
+
} catch (err) {
|
|
303
|
+
ws.unmapped.push({ path: f.rel, reason: (err as Error).message.replace(`${f.rel} `, "").replace(/^illegal manifest path:? ?/, "not a valid manifest path ") || "not a valid manifest path", files: 1, bytes: f.st.size });
|
|
304
|
+
continue;
|
|
305
|
+
}
|
|
306
|
+
mapped.push(f);
|
|
307
|
+
}
|
|
308
|
+
mapped.sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0));
|
|
309
|
+
const placed = placeCaseVariants(mapped.map((f) => f.rel), `${tenant}/${workspace}`);
|
|
310
|
+
for (const [i, f] of mapped.entries()) {
|
|
311
|
+
const { rel, from } = placed[i];
|
|
312
|
+
const side = sideOf(f.rel)!;
|
|
313
|
+
if (from) ws.conflicts.push({ path: from, keptAs: rel });
|
|
314
|
+
let sha: string;
|
|
315
|
+
try {
|
|
316
|
+
sha = await hashFile(f.abs);
|
|
317
|
+
} catch (err) {
|
|
318
|
+
ws.unmapped.push({ path: f.rel, reason: `unreadable (${(err as NodeJS.ErrnoException).code ?? "error"})`, files: 1, bytes: f.st.size });
|
|
319
|
+
continue;
|
|
320
|
+
}
|
|
321
|
+
ws.files.push({ path: rel, abs: f.abs, sha, size: f.st.size, mode: inExecBit(f.st), side, ...(from ? { from } : {}) });
|
|
322
|
+
ws.bytes += f.st.size;
|
|
323
|
+
}
|
|
324
|
+
for (const side of ["authored", "state"] as const) {
|
|
325
|
+
if (ws.files.filter((f) => f.side === side).length > MAX_MANIFEST_FILES) ws.error = `more than ${MAX_MANIFEST_FILES} ${side} files (a manifest holds at most that many)`;
|
|
326
|
+
}
|
|
327
|
+
return ws;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
export async function scanSource(opts: ScanOptions): Promise<SourceScan> {
|
|
331
|
+
const source = path.resolve(opts.source);
|
|
332
|
+
if (!fs.existsSync(source) || !fs.statSync(source).isDirectory()) throw new Error(`source is not a folder: ${source}`);
|
|
333
|
+
const tenants: TenantScan[] = [];
|
|
334
|
+
const names = fs.readdirSync(source).filter((n) => SAFE_NAME.test(n)).sort();
|
|
335
|
+
for (const tenant of names) {
|
|
336
|
+
const troot = path.join(source, tenant);
|
|
337
|
+
let st: fs.Stats;
|
|
338
|
+
try {
|
|
339
|
+
st = fs.lstatSync(troot);
|
|
340
|
+
} catch {
|
|
341
|
+
continue;
|
|
342
|
+
}
|
|
343
|
+
if (!st.isDirectory() || st.isSymbolicLink()) continue;
|
|
344
|
+
if ((opts.tenants?.length || opts.workspaces?.length) && !opts.tenants?.includes(tenant) && !opts.workspaces?.some((w) => w.startsWith(`${tenant}/`))) continue;
|
|
345
|
+
const t: TenantScan = { tenant, workspaces: [], unmapped: [] };
|
|
346
|
+
// The legacy home first: a workspace in both is the projects/ one, the
|
|
347
|
+
// copy workspaceDir (store.ts) resolves and the platform actually uses.
|
|
348
|
+
const homes = ["projects", "workspaces"].map((n) => path.join(troot, n));
|
|
349
|
+
const seen = new Set<string>();
|
|
350
|
+
for (const home of homes) {
|
|
351
|
+
// The home itself is checked before it is read: readdir follows a link,
|
|
352
|
+
// and a linked projects/ or workspaces/ would scan a folder outside the
|
|
353
|
+
// source (Codex review).
|
|
354
|
+
try {
|
|
355
|
+
if (fs.lstatSync(home).isSymbolicLink()) {
|
|
356
|
+
t.unmapped.push({ path: path.basename(home), reason: "symbolic link (refused, never followed)" });
|
|
357
|
+
continue;
|
|
358
|
+
}
|
|
359
|
+
} catch {
|
|
360
|
+
continue;
|
|
361
|
+
}
|
|
362
|
+
let wsNames: string[] = [];
|
|
363
|
+
try {
|
|
364
|
+
wsNames = fs.readdirSync(home).filter((n) => SAFE_NAME.test(n)).sort();
|
|
365
|
+
} catch {
|
|
366
|
+
continue;
|
|
367
|
+
}
|
|
368
|
+
for (const w of wsNames) {
|
|
369
|
+
// A workspace under the legacy name wins, as workspaceDir resolves it.
|
|
370
|
+
if (seen.has(w)) continue;
|
|
371
|
+
const dir = path.join(home, w);
|
|
372
|
+
let wst: fs.Stats;
|
|
373
|
+
try {
|
|
374
|
+
wst = fs.lstatSync(dir);
|
|
375
|
+
} catch {
|
|
376
|
+
continue;
|
|
377
|
+
}
|
|
378
|
+
if (!wst.isDirectory() || wst.isSymbolicLink()) continue;
|
|
379
|
+
if (opts.workspaces?.length && !opts.workspaces.includes(`${tenant}/${w}`) && !opts.tenants?.includes(tenant)) continue;
|
|
380
|
+
seen.add(w);
|
|
381
|
+
t.workspaces.push(await scanWorkspace(tenant, w, dir));
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
for (const e of fs.readdirSync(troot, { withFileTypes: true }).sort(byName)) {
|
|
385
|
+
if (e.name === "workspaces" || e.name === "projects") continue;
|
|
386
|
+
const p = path.join(troot, e.name);
|
|
387
|
+
const tl = e.isDirectory() ? tally(p) : { files: 1, bytes: fs.lstatSync(p).size };
|
|
388
|
+
const reason = e.name === ".history" ? "old history snapshots (revisions start from the imported tree)"
|
|
389
|
+
: /^secrets\.json(\.|$)/.test(e.name) ? "account secrets (never opened here; they move with the vault)"
|
|
390
|
+
: e.name === "storage" || e.name === "files" ? "the storage index and its blobs (moved in FOL-152; not read here)"
|
|
391
|
+
: "account-level, nothing maps it here";
|
|
392
|
+
t.unmapped.push({ path: e.name, reason, ...tl });
|
|
393
|
+
}
|
|
394
|
+
tenants.push(t);
|
|
395
|
+
}
|
|
396
|
+
return { source, tenants, scannedAt: new Date().toISOString() };
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
// ------------------------------------------------------------- import
|
|
400
|
+
|
|
401
|
+
export interface ImportOptions {
|
|
402
|
+
deps: Deps;
|
|
403
|
+
/** Delete head paths the folder does not have. Default off: an import never
|
|
404
|
+
* removes anything from the destination. */
|
|
405
|
+
mirror?: boolean;
|
|
406
|
+
/** Import a workspace whose history has revisions the importer did not make. */
|
|
407
|
+
force?: boolean;
|
|
408
|
+
by?: string;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
export type WorkspaceStatus = "imported" | "unchanged" | "skipped" | "failed" | "empty";
|
|
412
|
+
export interface WorkspaceResult {
|
|
413
|
+
tenant: string;
|
|
414
|
+
workspace: string;
|
|
415
|
+
status: WorkspaceStatus;
|
|
416
|
+
reason?: string;
|
|
417
|
+
revisions: string[];
|
|
418
|
+
conflictsKept: number;
|
|
419
|
+
filesPublished: number;
|
|
420
|
+
/** Files streamed from disk (over LARGE_FILE_BYTES) rather than read whole. */
|
|
421
|
+
filesStreamed: number;
|
|
422
|
+
}
|
|
423
|
+
export interface ImportReport {
|
|
424
|
+
startedAt: string;
|
|
425
|
+
finishedAt: string;
|
|
426
|
+
results: WorkspaceResult[];
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
const wsRef = (w: Pick<WorkspaceScan, "tenant" | "workspace">): WorkspaceRef => ({ tenant: w.tenant, workspace: w.workspace });
|
|
430
|
+
|
|
431
|
+
/** Revisions anyone but this importer made, newest first per side. The whole
|
|
432
|
+
* history is read, page by page, until one is found: the promise is about ANY
|
|
433
|
+
* such revision, not the last 200 (Codex review). Only the importer's own
|
|
434
|
+
* author name counts as the importer, not any name starting "import". */
|
|
435
|
+
async function foreignRevisions(deps: Deps, ref: WorkspaceRef, by: string = IMPORT_BY): Promise<Revision[]> {
|
|
436
|
+
const out: Revision[] = [];
|
|
437
|
+
for (const scope of ["workspace", "state"] as const) {
|
|
438
|
+
let before: number | undefined;
|
|
439
|
+
for (;;) {
|
|
440
|
+
const page = await deps.revisions.revisions({ ...ref, scope }, { limit: 500, ...(before !== undefined ? { before } : {}) });
|
|
441
|
+
const foreign = page.filter((r) => r.by !== by);
|
|
442
|
+
if (foreign.length) {
|
|
443
|
+
out.push(...foreign);
|
|
444
|
+
break;
|
|
445
|
+
}
|
|
446
|
+
if (page.length < 500) break;
|
|
447
|
+
before = Math.min(...page.map((r) => r.seq));
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
return out;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
function wantManifest(scan: WorkspaceScan): Manifest {
|
|
454
|
+
const m = emptyManifest();
|
|
455
|
+
for (const f of scan.files) m.files[f.path] = { sha: f.sha, size: f.size, mode: f.mode };
|
|
456
|
+
return m;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
export async function importWorkspace(scan: WorkspaceScan, opts: ImportOptions): Promise<WorkspaceResult> {
|
|
460
|
+
const { deps } = opts;
|
|
461
|
+
const ref = wsRef(scan);
|
|
462
|
+
const res: WorkspaceResult = { tenant: scan.tenant, workspace: scan.workspace, status: "imported", revisions: [], conflictsKept: scan.conflicts.length, filesPublished: 0, filesStreamed: 0 };
|
|
463
|
+
if (scan.error) return { ...res, status: "failed", reason: scan.error };
|
|
464
|
+
let holder: { kind: "publish"; id: string } | null = null;
|
|
465
|
+
try {
|
|
466
|
+
if (!opts.force) {
|
|
467
|
+
const foreign = await foreignRevisions(deps, ref, opts.by ?? IMPORT_BY);
|
|
468
|
+
if (foreign.length) return { ...res, status: "skipped", reason: `${foreign.length} revision(s) were made after the import (latest by ${foreign[0].by}); rerun with force to import over them` };
|
|
469
|
+
}
|
|
470
|
+
const heads = await headsOf(deps, ref);
|
|
471
|
+
const have = await manifestsAt(deps, scan.tenant, heads);
|
|
472
|
+
const haveAll: Manifest = { v: 1, files: { ...have.authored.files, ...have.state.files } };
|
|
473
|
+
const want = wantManifest(scan);
|
|
474
|
+
let changes: Changes = diffManifests(haveAll, want);
|
|
475
|
+
if (!opts.mirror) changes = Object.fromEntries(Object.entries(changes).filter(([, c]) => c.op === "put"));
|
|
476
|
+
if (!Object.keys(changes).length) return { ...res, status: scan.files.length ? "unchanged" : "empty" };
|
|
477
|
+
|
|
478
|
+
// The heads it starts from are part of the operation: the same changes
|
|
479
|
+
// from a different head (A → B, back to A, then A → B again) are a new
|
|
480
|
+
// import, not a retry of the first — which publish would replay, leaving
|
|
481
|
+
// A in place and reporting success (Codex review). A real retry starts
|
|
482
|
+
// from the same heads and still finds its operation.
|
|
483
|
+
const opId = `import-${requestDigest("import", { changes, heads: [heads.workspace?.id ?? null, heads.state?.id ?? null] }).slice(0, 32)}`;
|
|
484
|
+
const bySha = new Map(scan.files.map((f) => [f.sha, f]));
|
|
485
|
+
|
|
486
|
+
// A large file goes up from disk, pinned first (as a publish pins what it
|
|
487
|
+
// uploads), so it is never held whole in memory; the publish then finds it
|
|
488
|
+
// in the store and does not ask for its bytes.
|
|
489
|
+
const large = [...new Set(Object.values(changes).filter((c) => c.op === "put" && c.size > LARGE_FILE_BYTES).map((c) => (c.op === "put" ? c.sha : "")))];
|
|
490
|
+
if (large.length) {
|
|
491
|
+
holder = { kind: "publish", id: `${opId}-large` };
|
|
492
|
+
await deps.pins?.pinBlobs(scan.tenant, large, holder, { ttlMs: LARGE_PIN_TTL_MS });
|
|
493
|
+
for (const sha of large) {
|
|
494
|
+
const f = bySha.get(sha);
|
|
495
|
+
if (!f) throw new Error(`no source file for ${sha.slice(0, 12)}…`);
|
|
496
|
+
if (await hashFile(f.abs) !== sha) throw new Error(`${f.path} changed while it was being imported`);
|
|
497
|
+
await deps.blobs.putSourceIfAbsent(blobObjectKey(scan.tenant, sha), fileSource(f.abs), { sha256: sha });
|
|
498
|
+
res.filesStreamed++;
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
const out = await publish(deps, {
|
|
503
|
+
ws: ref,
|
|
504
|
+
opId,
|
|
505
|
+
by: opts.by ?? IMPORT_BY,
|
|
506
|
+
message: "imported from a data folder",
|
|
507
|
+
changes,
|
|
508
|
+
bytesOf: async (sha) => {
|
|
509
|
+
const f = bySha.get(sha);
|
|
510
|
+
if (!f) throw new Error(`no source file for ${sha.slice(0, 12)}…`);
|
|
511
|
+
const b = fs.readFileSync(f.abs);
|
|
512
|
+
if (sha256Hex(b) !== sha) throw new Error(`${f.path} changed while it was being imported`);
|
|
513
|
+
return b;
|
|
514
|
+
},
|
|
515
|
+
});
|
|
516
|
+
res.filesPublished = Object.values(changes).filter((c) => c.op === "put").length;
|
|
517
|
+
if (out.status !== "unchanged" && out.revision) res.revisions.push(out.revision.id);
|
|
518
|
+
if (out.stateRevision) res.revisions.push(out.stateRevision.id);
|
|
519
|
+
res.conflictsKept += out.conflicts.length;
|
|
520
|
+
return res;
|
|
521
|
+
} catch (err) {
|
|
522
|
+
return { ...res, status: "failed", reason: (err as Error).message };
|
|
523
|
+
} finally {
|
|
524
|
+
if (holder) await deps.pins?.release(scan.tenant, holder).catch(() => {});
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
export async function runImport(scan: SourceScan, opts: ImportOptions): Promise<ImportReport> {
|
|
529
|
+
const startedAt = new Date().toISOString();
|
|
530
|
+
const results: WorkspaceResult[] = [];
|
|
531
|
+
for (const t of scan.tenants) for (const w of t.workspaces) results.push(await importWorkspace(w, opts));
|
|
532
|
+
return { startedAt, finishedAt: new Date().toISOString(), results };
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
// ------------------------------------------------------------- dry-run
|
|
536
|
+
|
|
537
|
+
export interface PlanWorkspace {
|
|
538
|
+
tenant: string;
|
|
539
|
+
workspace: string;
|
|
540
|
+
files: number;
|
|
541
|
+
bytes: number;
|
|
542
|
+
authoredFiles: number;
|
|
543
|
+
stateFiles: number;
|
|
544
|
+
revisionsToMake: number | "unknown";
|
|
545
|
+
alreadyThere: "yes" | "partly" | "no" | "unknown";
|
|
546
|
+
note?: string;
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/** What an import would do, per workspace. Reads the destination's heads when
|
|
550
|
+
* given a Deps (never writes); without one, "unknown". */
|
|
551
|
+
export async function planImport(scan: SourceScan, deps?: Deps): Promise<PlanWorkspace[]> {
|
|
552
|
+
const out: PlanWorkspace[] = [];
|
|
553
|
+
for (const t of scan.tenants) {
|
|
554
|
+
for (const w of t.workspaces) {
|
|
555
|
+
const p: PlanWorkspace = {
|
|
556
|
+
tenant: w.tenant, workspace: w.workspace, files: w.files.length, bytes: w.bytes,
|
|
557
|
+
authoredFiles: w.files.filter((f) => f.side === "authored").length, stateFiles: w.files.filter((f) => f.side === "state").length,
|
|
558
|
+
revisionsToMake: "unknown", alreadyThere: "unknown",
|
|
559
|
+
};
|
|
560
|
+
if (w.error) p.note = `cannot import: ${w.error}`;
|
|
561
|
+
else if (deps) {
|
|
562
|
+
try {
|
|
563
|
+
const have = await manifestsAt(deps, w.tenant, await headsOf(deps, wsRef(w)));
|
|
564
|
+
const all = { ...have.authored.files, ...have.state.files };
|
|
565
|
+
const want = wantManifest(w).files;
|
|
566
|
+
const same = Object.keys(want).filter((k) => all[k]?.sha === want[k].sha && all[k]?.mode === want[k].mode).length;
|
|
567
|
+
p.alreadyThere = !Object.keys(want).length ? "yes" : same === Object.keys(want).length ? "yes" : same ? "partly" : "no";
|
|
568
|
+
const sides = new Set(Object.keys(want).filter((k) => !(all[k]?.sha === want[k].sha && all[k]?.mode === want[k].mode)).map((k) => w.files.find((f) => f.path === k)!.side));
|
|
569
|
+
p.revisionsToMake = sides.size;
|
|
570
|
+
const foreign = await foreignRevisions(deps, wsRef(w));
|
|
571
|
+
if (foreign.length) p.note = `${foreign.length} revision(s) by someone else (latest by ${foreign[0].by}): an import skips this workspace unless --force`;
|
|
572
|
+
} catch (err) {
|
|
573
|
+
p.note = `could not read the destination: ${(err as Error).message}`;
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
out.push(p);
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
return out;
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
const kb = (n: number) => (n >= 1 << 20 ? `${(n / (1 << 20)).toFixed(1)} MiB` : n >= 1024 ? `${(n / 1024).toFixed(1)} KiB` : `${n} B`);
|
|
583
|
+
|
|
584
|
+
export function renderPlan(scan: SourceScan, plan: PlanWorkspace[]): string {
|
|
585
|
+
const L: string[] = [`DRY RUN — nothing was written. Source: ${scan.source}`, ""];
|
|
586
|
+
let files = 0;
|
|
587
|
+
let bytes = 0;
|
|
588
|
+
for (const t of scan.tenants) {
|
|
589
|
+
L.push(`account ${t.tenant} (${t.workspaces.length} workspace(s))`);
|
|
590
|
+
for (const u of t.unmapped) L.push(` can't map ${u.path}: ${u.reason} (${u.files ?? 0} files, ${kb(u.bytes ?? 0)})`);
|
|
591
|
+
for (const w of t.workspaces) {
|
|
592
|
+
const p = plan.find((x) => x.tenant === w.tenant && x.workspace === w.workspace)!;
|
|
593
|
+
files += w.files.length;
|
|
594
|
+
bytes += w.bytes;
|
|
595
|
+
L.push(` ${w.workspace}: ${w.files.length} files, ${kb(w.bytes)} (${p.authoredFiles} authored, ${p.stateFiles} state) → revisions to make: ${p.revisionsToMake}; already in destination: ${p.alreadyThere}`);
|
|
596
|
+
if (p.note) L.push(` ! ${p.note}`);
|
|
597
|
+
L.push(` runs/ on the volume: ${w.runs.recordFiles} record file(s) (rows since FOL-152); output folders (not imported here): ${w.runs.outputFolders} (${w.runs.outputFiles} files, ${kb(w.runs.outputBytes)})`);
|
|
598
|
+
for (const c of w.conflicts) L.push(` conflict ${c.path} collides by case with another name; kept as ${c.keptAs}`);
|
|
599
|
+
for (const u of w.unmapped) L.push(` can't map ${u.path}: ${u.reason}${u.files ? ` (${u.files} files, ${kb(u.bytes ?? 0)})` : ""}`);
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
L.push("", `Total: ${files} workspace files, ${kb(bytes)}.`);
|
|
603
|
+
return L.join("\n") + "\n";
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
// ------------------------------------------------------------- verify
|
|
607
|
+
|
|
608
|
+
export interface VerifyWorkspace {
|
|
609
|
+
tenant: string;
|
|
610
|
+
workspace: string;
|
|
611
|
+
pass: boolean;
|
|
612
|
+
expected: number;
|
|
613
|
+
inHead: number;
|
|
614
|
+
matched: number;
|
|
615
|
+
missing: string[];
|
|
616
|
+
mismatched: string[];
|
|
617
|
+
extra: string[];
|
|
618
|
+
/** Absent from the store, the wrong size, or (deep) bytes that do not hash to their name. */
|
|
619
|
+
badBlobs: string[];
|
|
620
|
+
notes: string[];
|
|
621
|
+
}
|
|
622
|
+
export interface VerifyReport {
|
|
623
|
+
verifiedAt: string;
|
|
624
|
+
source: string;
|
|
625
|
+
pass: boolean;
|
|
626
|
+
workspaces: VerifyWorkspace[];
|
|
627
|
+
}
|
|
628
|
+
export interface VerifyOptions {
|
|
629
|
+
deps: Deps;
|
|
630
|
+
/** Stream every blob back and hash it (default: confirm each exists with the right size). */
|
|
631
|
+
deep?: boolean;
|
|
632
|
+
/** Paths in the head that the folder does not have are fine. */
|
|
633
|
+
allowExtra?: boolean;
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
/** Compare every workspace's heads with the folder, by path, sha256 and mode —
|
|
637
|
+
* the folder's hashes are taken again now, not trusted from the scan. */
|
|
638
|
+
export async function verifyImport(scan: SourceScan, opts: VerifyOptions): Promise<VerifyReport> {
|
|
639
|
+
const { deps } = opts;
|
|
640
|
+
const workspaces: VerifyWorkspace[] = [];
|
|
641
|
+
const tmp = opts.deep ? fs.mkdtempSync(path.join(os.tmpdir(), "foldrun-verify-")) : null;
|
|
642
|
+
try {
|
|
643
|
+
for (const t of scan.tenants) {
|
|
644
|
+
for (const w of t.workspaces) {
|
|
645
|
+
const v: VerifyWorkspace = { tenant: w.tenant, workspace: w.workspace, pass: true, expected: w.files.length, inHead: 0, matched: 0, missing: [], mismatched: [], extra: [], badBlobs: [], notes: [] };
|
|
646
|
+
try {
|
|
647
|
+
if (w.error) throw new Error(w.error);
|
|
648
|
+
// The folder as it is NOW — its paths and modes, not the scan's:
|
|
649
|
+
// a file added, or an exec bit changed, since the scan must fail
|
|
650
|
+
// the check, not pass it on stale data (Codex review).
|
|
651
|
+
const current = await scanWorkspace(w.tenant, w.workspace, w.dir);
|
|
652
|
+
if (current.error) throw new Error(current.error);
|
|
653
|
+
v.expected = current.files.length;
|
|
654
|
+
const have = await manifestsAt(deps, w.tenant, await headsOf(deps, wsRef(w)));
|
|
655
|
+
const all = { ...have.authored.files, ...have.state.files };
|
|
656
|
+
v.inHead = Object.keys(all).length;
|
|
657
|
+
const checked = new Set<string>();
|
|
658
|
+
// A file the import had that the folder no longer gives back — gone,
|
|
659
|
+
// or now unreadable (the scan lists those apart, not as files) —
|
|
660
|
+
// is a mismatch, as before the rescan; never a quietly smaller set.
|
|
661
|
+
const nowThere = new Set(current.files.map((f) => f.path));
|
|
662
|
+
for (const f of w.files) {
|
|
663
|
+
if (nowThere.has(f.path)) continue;
|
|
664
|
+
v.notes.push(`${f.path}: the source file can no longer be read`);
|
|
665
|
+
v.mismatched.push(f.path);
|
|
666
|
+
}
|
|
667
|
+
for (const f of current.files) {
|
|
668
|
+
let now: string;
|
|
669
|
+
try {
|
|
670
|
+
now = await hashFile(f.abs);
|
|
671
|
+
} catch {
|
|
672
|
+
v.notes.push(`${f.path}: the source file can no longer be read`);
|
|
673
|
+
v.mismatched.push(f.path);
|
|
674
|
+
continue;
|
|
675
|
+
}
|
|
676
|
+
const e = all[f.path];
|
|
677
|
+
if (!e) v.missing.push(f.path);
|
|
678
|
+
else if (e.sha !== now || e.mode !== f.mode) v.mismatched.push(f.path);
|
|
679
|
+
else {
|
|
680
|
+
v.matched++;
|
|
681
|
+
try {
|
|
682
|
+
const key = blobObjectKey(w.tenant, e.sha);
|
|
683
|
+
const h = await deps.blobs.head(key);
|
|
684
|
+
if (!h || h.size !== e.size) v.badBlobs.push(f.path);
|
|
685
|
+
else if (tmp && !checked.has(e.sha)) {
|
|
686
|
+
checked.add(e.sha);
|
|
687
|
+
const dest = path.join(tmp, e.sha);
|
|
688
|
+
try {
|
|
689
|
+
await downloadToFile(deps.blobs, key, dest, { sha256: e.sha });
|
|
690
|
+
} finally {
|
|
691
|
+
fs.rmSync(dest, { force: true });
|
|
692
|
+
fs.rmSync(`${dest}.part`, { force: true });
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
} catch (err) {
|
|
696
|
+
if (err instanceof BlobNotFound || err instanceof BlobSourceError) v.badBlobs.push(f.path);
|
|
697
|
+
else throw err;
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
const wanted = new Set(current.files.map((f) => f.path));
|
|
702
|
+
v.extra = Object.keys(all).filter((p) => !wanted.has(p)).sort();
|
|
703
|
+
v.pass = !v.missing.length && !v.mismatched.length && !v.badBlobs.length && (opts.allowExtra || !v.extra.length);
|
|
704
|
+
if (!opts.allowExtra && v.extra.length) v.notes.push(`${v.extra.length} path(s) in the head are not in the source (work done after the import, or --mirror was not used)`);
|
|
705
|
+
} catch (err) {
|
|
706
|
+
v.pass = false;
|
|
707
|
+
v.notes.push((err as Error).message);
|
|
708
|
+
}
|
|
709
|
+
workspaces.push(v);
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
} finally {
|
|
713
|
+
if (tmp) fs.rmSync(tmp, { recursive: true, force: true });
|
|
714
|
+
}
|
|
715
|
+
return { verifiedAt: new Date().toISOString(), source: scan.source, pass: workspaces.every((x) => x.pass), workspaces };
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
export function renderVerify(r: VerifyReport): string {
|
|
719
|
+
const L = [`Import verification ${r.pass ? "PASSED" : "FAILED"} — ${r.verifiedAt}`, `Source: ${r.source}`, ""];
|
|
720
|
+
for (const w of r.workspaces) {
|
|
721
|
+
L.push(`${w.pass ? "PASS" : "FAIL"} ${w.tenant}/${w.workspace}: ${w.matched}/${w.expected} files match (head holds ${w.inHead})`);
|
|
722
|
+
const list = (label: string, xs: string[]) => xs.length && L.push(` ${label}: ${xs.slice(0, 10).join(", ")}${xs.length > 10 ? ` … +${xs.length - 10}` : ""}`);
|
|
723
|
+
list("missing from head", w.missing);
|
|
724
|
+
list("different sha256 or mode", w.mismatched);
|
|
725
|
+
list("blob missing or wrong in the store", w.badBlobs);
|
|
726
|
+
list("extra in head", w.extra);
|
|
727
|
+
for (const n of w.notes) L.push(` note: ${n}`);
|
|
728
|
+
}
|
|
729
|
+
L.push("", `${r.workspaces.filter((w) => w.pass).length} of ${r.workspaces.length} workspace(s) passed.`);
|
|
730
|
+
return L.join("\n") + "\n";
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
/** A path with every link resolved, for a folder that may not exist yet: the
|
|
734
|
+
* nearest existing ancestor's real path plus the rest. */
|
|
735
|
+
function canonical(p: string): string {
|
|
736
|
+
let head = path.resolve(p);
|
|
737
|
+
const rest: string[] = [];
|
|
738
|
+
for (;;) {
|
|
739
|
+
try {
|
|
740
|
+
return path.join(fs.realpathSync(head), ...rest);
|
|
741
|
+
} catch {
|
|
742
|
+
const up = path.dirname(head);
|
|
743
|
+
if (up === head) return path.resolve(p);
|
|
744
|
+
rest.unshift(path.basename(head));
|
|
745
|
+
head = up;
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
/** Write import-verify.json and import-verify.txt. Refuses a folder inside the
|
|
751
|
+
* source, compared by real paths, so a link cannot point the report into it
|
|
752
|
+
* (Codex review). */
|
|
753
|
+
export function writeVerifyReport(dir: string, source: string, r: VerifyReport): { json: string; txt: string } {
|
|
754
|
+
const out = path.resolve(dir);
|
|
755
|
+
const src = canonical(source);
|
|
756
|
+
const real = canonical(dir);
|
|
757
|
+
if (real === src || real.startsWith(src + path.sep)) throw new Error("the report folder must be outside the source folder");
|
|
758
|
+
fs.mkdirSync(out, { recursive: true });
|
|
759
|
+
const json = path.join(out, "import-verify.json");
|
|
760
|
+
const txt = path.join(out, "import-verify.txt");
|
|
761
|
+
fs.writeFileSync(json, JSON.stringify(r, null, 2) + "\n");
|
|
762
|
+
fs.writeFileSync(txt, renderVerify(r));
|
|
763
|
+
return { json, txt };
|
|
764
|
+
}
|