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