@foldrun/core 17.3.0 → 18.0.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.
Files changed (65) hide show
  1. package/dist/src/approvals.js +3 -3
  2. package/dist/src/blob-cache.d.ts +58 -0
  3. package/dist/src/blob-cache.js +312 -0
  4. package/dist/src/blob-pins.d.ts +44 -0
  5. package/dist/src/blob-pins.js +61 -0
  6. package/dist/src/blob-store.d.ts +47 -0
  7. package/dist/src/blob-store.js +362 -0
  8. package/dist/src/blob-sweeper.d.ts +70 -0
  9. package/dist/src/blob-sweeper.js +282 -0
  10. package/dist/src/blob-types.d.ts +145 -0
  11. package/dist/src/blob-types.js +115 -0
  12. package/dist/src/evals.js +1 -1
  13. package/dist/src/history.d.ts +92 -9
  14. package/dist/src/history.js +168 -20
  15. package/dist/src/journal-store.d.ts +58 -0
  16. package/dist/src/journal-store.js +117 -0
  17. package/dist/src/manifest.d.ts +92 -0
  18. package/dist/src/manifest.js +239 -0
  19. package/dist/src/ops-log.js +26 -3
  20. package/dist/src/platform.d.ts +7 -0
  21. package/dist/src/platform.js +1 -0
  22. package/dist/src/publish.d.ts +134 -0
  23. package/dist/src/publish.js +434 -0
  24. package/dist/src/records.d.ts +72 -0
  25. package/dist/src/records.js +24 -0
  26. package/dist/src/revision-store.d.ts +161 -0
  27. package/dist/src/revision-store.js +378 -0
  28. package/dist/src/run-container.d.ts +20 -0
  29. package/dist/src/run-container.js +61 -0
  30. package/dist/src/runner.js +1 -1
  31. package/dist/src/s3-blob-store.d.ts +29 -0
  32. package/dist/src/s3-blob-store.js +531 -0
  33. package/dist/src/state-retention.d.ts +15 -0
  34. package/dist/src/state-retention.js +65 -0
  35. package/dist/src/storage.d.ts +29 -1
  36. package/dist/src/storage.js +331 -81
  37. package/dist/src/store.d.ts +41 -0
  38. package/dist/src/store.js +188 -5
  39. package/dist/src/trigger-log.js +17 -0
  40. package/dist/src/workspace-revisions.d.ts +269 -0
  41. package/dist/src/workspace-revisions.js +1382 -0
  42. package/package.json +1 -1
  43. package/src/approvals.ts +3 -3
  44. package/src/blob-cache.ts +357 -0
  45. package/src/blob-pins.ts +99 -0
  46. package/src/blob-store.ts +389 -0
  47. package/src/blob-sweeper.ts +336 -0
  48. package/src/blob-types.ts +216 -0
  49. package/src/evals.ts +1 -1
  50. package/src/history.ts +226 -19
  51. package/src/journal-store.ts +152 -0
  52. package/src/manifest.ts +274 -0
  53. package/src/ops-log.ts +25 -3
  54. package/src/platform.ts +8 -0
  55. package/src/publish.ts +520 -0
  56. package/src/records.ts +105 -0
  57. package/src/revision-store.ts +513 -0
  58. package/src/run-container.ts +62 -0
  59. package/src/runner.ts +1 -1
  60. package/src/s3-blob-store.ts +560 -0
  61. package/src/state-retention.ts +83 -0
  62. package/src/storage.ts +335 -81
  63. package/src/store.ts +178 -5
  64. package/src/trigger-log.ts +15 -0
  65. package/src/workspace-revisions.ts +1423 -0
@@ -54,6 +54,7 @@ import crypto from "node:crypto";
54
54
  import { Readable } from "node:stream";
55
55
  import { dataRoot, singleWorkspace } from "./paths.js";
56
56
  import { assertSafeName, workspaceDir, STORAGE_DIR, adoptLegacyFilesDir } from "./store.js";
57
+ import { records } from "./records.js";
57
58
  /** The directory a run sees, and the one this module mirrors into it.
58
59
  * Declared in store.ts, where saveWorkspace also needs it; re-exported so
59
60
  * callers of this module do not need to know that. */
@@ -174,6 +175,9 @@ export function mimeFor(rel) {
174
175
  export function readIndex(tenant, workspace) {
175
176
  if (!fileStoreEnabled())
176
177
  return { version: 1, files: [] };
178
+ const port = records(tenant, workspace);
179
+ if (port)
180
+ return { version: 1, files: port.fileList(tenant, workspace) };
177
181
  try {
178
182
  const raw = JSON.parse(fs.readFileSync(indexPath(tenant, workspace), "utf8"));
179
183
  if (!Array.isArray(raw?.files))
@@ -193,6 +197,23 @@ function writeIndex(tenant, workspace, index) {
193
197
  fs.writeFileSync(tmp, JSON.stringify(index, null, 2));
194
198
  fs.renameSync(tmp, file);
195
199
  }
200
+ /** Save one record, where `index` is the index it was read from (the file
201
+ * store rewrites the whole file; the database upserts one row, which is why
202
+ * two writers of different paths never touch each other). */
203
+ function indexPut(tenant, workspace, index, record) {
204
+ const port = records(tenant, workspace);
205
+ if (port)
206
+ return port.filePut(tenant, workspace, record);
207
+ writeIndex(tenant, workspace, { version: 1, files: [...index.files.filter((f) => f.path !== record.path), record] });
208
+ }
209
+ function indexRemove(tenant, workspace, index, rel) {
210
+ const port = records(tenant, workspace);
211
+ if (port) {
212
+ port.fileDelete(tenant, workspace, rel);
213
+ return;
214
+ }
215
+ writeIndex(tenant, workspace, { version: 1, files: index.files.filter((f) => f.path !== rel) });
216
+ }
196
217
  export function listStorage(tenant, workspace) {
197
218
  return readIndex(tenant, workspace).files.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
198
219
  }
@@ -416,12 +437,17 @@ function presign(cfg, creds, method, key, ttlSec, extraQuery = {}, now = new Dat
416
437
  return `${origin}${canonicalUri}?${canonicalQuery}&X-Amz-Signature=${signature}`;
417
438
  }
418
439
  /** The header-signed form, for the calls the platform itself makes. */
419
- async function s3Request(cfg, method, key, body, mime, extra = {}) {
440
+ export async function s3Request(cfg, method, key, body, mime, extra = {}, signal, opts = {}) {
420
441
  const creds = await credentials(cfg);
421
442
  const { host, origin, canonicalUri } = target(cfg, key);
422
443
  const { amzDate, dateStamp } = stamps(new Date());
423
444
  const scope = `${dateStamp}/${cfg.region}/s3/aws4_request`;
424
- const payloadHash = sha256(body ?? Buffer.alloc(0));
445
+ const streamed = body && !Buffer.isBuffer(body) ? body : null;
446
+ const payloadHash = streamed ? streamed.sha256 : sha256(body ?? Buffer.alloc(0));
447
+ const canonicalQuery = Object.keys(opts.query ?? {})
448
+ .sort()
449
+ .map((k) => `${uriEncode(k)}=${uriEncode(opts.query[k])}`)
450
+ .join("&");
425
451
  const headers = {
426
452
  host,
427
453
  "x-amz-content-sha256": payloadHash,
@@ -438,18 +464,23 @@ async function s3Request(cfg, method, key, body, mime, extra = {}) {
438
464
  const canonicalRequest = [
439
465
  method,
440
466
  canonicalUri,
441
- "",
467
+ canonicalQuery,
442
468
  canonicalHeaders,
443
469
  signedHeaders,
444
470
  payloadHash,
445
471
  ].join("\n");
446
472
  const stringToSign = ["AWS4-HMAC-SHA256", amzDate, scope, sha256(canonicalRequest)].join("\n");
447
473
  const signature = hmac(signingKey(cfg, creds, dateStamp), stringToSign).toString("hex");
448
- const res = await fetch(`${origin}${canonicalUri}`, {
474
+ const res = await fetch(`${origin}${canonicalUri}${canonicalQuery ? `?${canonicalQuery}` : ""}`, {
449
475
  method,
450
- body: body,
476
+ body: streamed
477
+ ? Readable.toWeb(Readable.from(streamed.stream, { objectMode: false }))
478
+ : body,
479
+ ...(streamed ? { duplex: "half" } : {}),
480
+ signal,
451
481
  headers: {
452
482
  ...headers,
483
+ ...(streamed ? { "content-length": String(streamed.length) } : {}),
453
484
  Authorization: `AWS4-HMAC-SHA256 Credential=${creds.accessKeyId}/${scope}, ` +
454
485
  `SignedHeaders=${signedHeaders}, Signature=${signature}`,
455
486
  },
@@ -547,6 +578,163 @@ export function driverFor(tenant, workspace) {
547
578
  }
548
579
  return fsDriver(tenant, workspace);
549
580
  }
581
+ // ---------- the per-workspace lock ----------
582
+ //
583
+ // The index is read, changed and written back by writers in DIFFERENT pods:
584
+ // the web pod (uploads, registerUpload, deleteFile) and the worker (a run's
585
+ // harvest) share the data volume. So an in-process mutex is not enough; the
586
+ // lock has to hold across processes. It is `lockFileExclusive`'s mechanism
587
+ // (`<file>.lock` opened O_EXCL — NFS 4.1 and EFS honour it) with three
588
+ // differences this module needs:
589
+ //
590
+ // async it waits with a timer, so a busy lock never blocks the event loop
591
+ // (the sync one parks the thread with Atomics.wait);
592
+ // fenced the lock file holds a token and release only removes its own, so
593
+ // a holder whose lock was taken over as stale cannot delete the new
594
+ // holder's lock;
595
+ // renewed the holder touches the lock while it works, so the stale limit
596
+ // only ever means "the holder died", not "the holder is slow".
597
+ //
598
+ // Core has no database, so a Postgres advisory lock is not available here;
599
+ // phase 2 replaces this index (and so this lock) with rows.
600
+ //
601
+ // The lock lives BESIDE the store directory, not in it, so a workspace delete
602
+ // or rename (which removes or moves that directory) cannot pull it out from
603
+ // under its own holder.
604
+ const LOCK_STALE_MS = 30_000;
605
+ const LOCK_RENEW_MS = 5_000;
606
+ const LOCK_WAIT_MS = 30_000;
607
+ const lockQueues = new Map();
608
+ const nap = (ms) => new Promise((r) => setTimeout(r, ms));
609
+ function lockFile(tenant, workspace) {
610
+ assertSafeName(tenant, "tenant");
611
+ assertSafeName(workspace, "workspace");
612
+ return path.join(dataRoot(), tenant, STORAGE_DIR, `.${workspace}.lock`);
613
+ }
614
+ /**
615
+ * Take over a lock whose holder died, without ever deleting a live one.
616
+ *
617
+ * Two processes can both see the same stale file. If each simply removed it,
618
+ * the slower one would remove the FRESH lock the faster one had just created,
619
+ * and both would run. So the file is moved aside with rename(2) — atomic, one
620
+ * caller wins, the others get ENOENT — and what was moved is read back: if it
621
+ * is not stale after all (we raced a new holder), it is put back with link(2),
622
+ * which cannot overwrite a lock someone else took in between.
623
+ */
624
+ async function clearStale(file) {
625
+ const aside = `${file}.stale.${process.pid}.${crypto.randomBytes(4).toString("hex")}`;
626
+ try {
627
+ fs.renameSync(file, aside);
628
+ }
629
+ catch {
630
+ return; // another process got there first, or it was released
631
+ }
632
+ try {
633
+ if (Date.now() - fs.statSync(aside).mtimeMs <= LOCK_STALE_MS) {
634
+ try {
635
+ fs.linkSync(aside, file); // not stale: we moved a live lock; restore it
636
+ }
637
+ catch {
638
+ // someone already took the free name; the live holder lost its file and
639
+ // will find out at release (token check). Rare, and not made worse.
640
+ }
641
+ }
642
+ }
643
+ catch {
644
+ // vanished: nothing to restore
645
+ }
646
+ finally {
647
+ fs.rmSync(aside, { force: true });
648
+ }
649
+ }
650
+ async function takeFileLock(file) {
651
+ fs.mkdirSync(path.dirname(file), { recursive: true });
652
+ const token = `${process.pid}.${crypto.randomBytes(8).toString("hex")}`;
653
+ const deadline = Date.now() + LOCK_WAIT_MS;
654
+ for (;;) {
655
+ try {
656
+ const fd = fs.openSync(file, "wx", 0o600);
657
+ fs.writeSync(fd, token);
658
+ fs.closeSync(fd);
659
+ break;
660
+ }
661
+ catch (err) {
662
+ if (err.code !== "EEXIST")
663
+ throw err;
664
+ try {
665
+ if (Date.now() - fs.statSync(file).mtimeMs > LOCK_STALE_MS) {
666
+ await clearStale(file);
667
+ continue;
668
+ }
669
+ }
670
+ catch {
671
+ continue; // released between the open and the stat
672
+ }
673
+ if (Date.now() > deadline)
674
+ throw new Error("the file store is busy — another change is being saved; try again");
675
+ await nap(15 + Math.floor(Math.random() * 20));
676
+ }
677
+ }
678
+ const renew = setInterval(() => {
679
+ try {
680
+ const now = new Date();
681
+ fs.utimesSync(file, now, now);
682
+ }
683
+ catch {
684
+ // gone: release() notices
685
+ }
686
+ }, LOCK_RENEW_MS);
687
+ renew.unref();
688
+ return () => {
689
+ clearInterval(renew);
690
+ try {
691
+ if (fs.readFileSync(file, "utf8") === token)
692
+ fs.rmSync(file, { force: true });
693
+ }
694
+ catch {
695
+ // already gone
696
+ }
697
+ };
698
+ }
699
+ /**
700
+ * Run `fn` as the only writer of this workspace's file index, in this process
701
+ * and every other one on the volume. Callers of the same workspace in this
702
+ * process queue on a promise chain first, so they do not poll the file against
703
+ * each other. Keep `fn` to index work and blob bookkeeping; bytes a caller
704
+ * already holds are uploaded BEFORE taking the lock (a blob is immutable and
705
+ * named by its hash, so that is safe) and then confirmed present inside it.
706
+ */
707
+ export async function withFileStoreLock(tenant, workspace, fn) {
708
+ if (!fileStoreEnabled())
709
+ return fn();
710
+ const port = records(tenant, workspace);
711
+ if (port)
712
+ return port.lock(`storage:${tenant}/${workspace}`, fn);
713
+ return withFileLock(lockFile(tenant, workspace), fn);
714
+ }
715
+ /** The same lock for any path: `file` is the lock file itself (its directory
716
+ * is created). Used by the local RevisionStore, which keeps its own state
717
+ * beside the data it guards. */
718
+ export async function withFileLock(file, fn) {
719
+ const prev = lockQueues.get(file) ?? Promise.resolve();
720
+ const run = prev.catch(() => { }).then(async () => {
721
+ const release = await takeFileLock(file);
722
+ try {
723
+ return await fn();
724
+ }
725
+ finally {
726
+ release();
727
+ }
728
+ });
729
+ lockQueues.set(file, run);
730
+ try {
731
+ return await run;
732
+ }
733
+ finally {
734
+ if (lockQueues.get(file) === run)
735
+ lockQueues.delete(file);
736
+ }
737
+ }
550
738
  // ---------- the store ----------
551
739
  /**
552
740
  * Record bytes the platform already holds. Used by the upload route on the fs
@@ -583,31 +771,53 @@ async function putFileQuietly(tenant, workspace, rel, body, by) {
583
771
  throw new Error(`${norm} is ${Math.round(body.length / 1e6)}MB — the limit is ${maxBytes() / 1e6}MB`);
584
772
  }
585
773
  const sha = sha256(body);
586
- const index = readIndex(tenant, workspace);
587
- const previous = index.files.find((f) => f.path === norm);
588
- if (previous?.sha === sha)
589
- return previous; // same bytes, same name: nothing happened
590
- const projected = usedBytes(tenant, workspace) - (previous?.size ?? 0) + body.length;
591
- if (projected > quotaBytes()) {
592
- throw new Error(`workspace file quota exceeded (${quotaBytes() / 1e6}MB)`);
593
- }
594
774
  const driver = driverFor(tenant, workspace);
595
- await driver.put(blobKey(tenant, workspace, sha), body, mimeFor(norm));
596
- const record = {
597
- path: norm,
598
- sha,
599
- size: body.length,
600
- mime: mimeFor(norm),
601
- updatedAt: new Date().toISOString(),
602
- by,
603
- };
604
- writeIndex(tenant, workspace, {
605
- version: 1,
606
- files: [...index.files.filter((f) => f.path !== norm), record],
775
+ const key = blobKey(tenant, workspace, sha);
776
+ // A cheap look before the bytes move; the check inside the lock is the one
777
+ // that counts, this one only saves uploading what will be refused.
778
+ {
779
+ const seen = readIndex(tenant, workspace);
780
+ const before = seen.files.find((f) => f.path === norm);
781
+ if (before?.sha !== sha && usedBytes(tenant, workspace) - (before?.size ?? 0) + body.length > quotaBytes()) {
782
+ throw new Error(`workspace file quota exceeded (${quotaBytes() / 1e6}MB)`);
783
+ }
784
+ }
785
+ // The upload happens outside the lock: it can be long, and a blob is
786
+ // immutable and named by its hash, so two writers uploading the same one are
787
+ // harmless. What the lock guards is the index, and the blob's presence while
788
+ // the index names it (see the confirm below).
789
+ await driver.put(key, body, mimeFor(norm));
790
+ return withFileStoreLock(tenant, workspace, async () => {
791
+ const index = readIndex(tenant, workspace);
792
+ const previous = index.files.find((f) => f.path === norm);
793
+ if (previous?.sha === sha)
794
+ return previous; // same bytes, same name: nothing happened
795
+ const projected = usedBytes(tenant, workspace) - (previous?.size ?? 0) + body.length;
796
+ if (projected > quotaBytes()) {
797
+ // Nothing names the blob we just put unless another record already does.
798
+ if (!index.files.some((f) => f.sha === sha))
799
+ await driver.remove(key).catch(() => { });
800
+ throw new Error(`workspace file quota exceeded (${quotaBytes() / 1e6}MB)`);
801
+ }
802
+ // A delete or replace that ran between our upload and now may have
803
+ // collected this very blob (it was unreferenced then). We hold the bytes,
804
+ // so put them back before the index points at them. put is a no-op when
805
+ // the object is there.
806
+ if (!(await driver.has(key)))
807
+ await driver.put(key, body, mimeFor(norm));
808
+ const record = {
809
+ path: norm,
810
+ sha,
811
+ size: body.length,
812
+ mime: mimeFor(norm),
813
+ updatedAt: new Date().toISOString(),
814
+ by,
815
+ };
816
+ indexPut(tenant, workspace, index, record);
817
+ if (previous)
818
+ await collectLocked(tenant, workspace, previous.sha);
819
+ return record;
607
820
  });
608
- if (previous)
609
- await collect(tenant, workspace, previous.sha);
610
- return record;
611
821
  }
612
822
  /** Register bytes a browser PUT straight to the bucket. Same bookkeeping as
613
823
  * putFile, minus the bytes — the platform never saw them.
@@ -624,41 +834,47 @@ export async function registerUpload(tenant, workspace, rel, sha, _claimed, by)
624
834
  requireWorkspace(tenant, workspace);
625
835
  const driver = driverFor(tenant, workspace);
626
836
  const key = blobKey(tenant, workspace, sha);
627
- // Trust nothing the browser said: not that the PUT landed, not its size.
628
- const size = await driver.size(key);
629
- if (size === null) {
630
- throw new Error("no object at that key — the upload did not complete");
631
- }
632
- const index = readIndex(tenant, workspace);
633
- const previous = index.files.find((f) => f.path === norm);
634
- const record = {
635
- path: norm,
636
- sha,
637
- size,
638
- mime: mimeFor(norm),
639
- updatedAt: new Date().toISOString(),
640
- by,
641
- };
642
- const files = [...index.files.filter((f) => f.path !== norm), record];
643
- // putFile's two limits, on the real length. A refused object is removed:
644
- // nothing names it, so it would sit in the bucket unreachable and billed —
645
- // unless a record already names these bytes, which are then not ours to drop.
646
- const refuse = async (message) => {
647
- if (!index.files.some((f) => f.sha === sha))
648
- await driver.remove(key).catch(() => { });
649
- throw new Error(message);
650
- };
651
- if (size > maxBytes()) {
652
- await refuse(`${norm} is ${Math.round(size / 1e6)}MB — the limit is ${maxBytes() / 1e6}MB`);
653
- }
654
- if (bytesOf(files) > quotaBytes() && bytesOf(files) > bytesOf(index.files)) {
655
- await refuse(`workspace file quota exceeded (${quotaBytes() / 1e6}MB)`);
656
- }
657
- writeIndex(tenant, workspace, { version: 1, files });
658
- if (previous && previous.sha !== sha)
659
- await collect(tenant, workspace, previous.sha);
660
- await announceFiles(tenant, workspace, [record.path], by);
661
- return record;
837
+ return withFileStoreLock(tenant, workspace, async () => {
838
+ // Inside the lock, so a collect cannot remove the object between the
839
+ // check that it is there and the index naming it.
840
+ // Trust nothing the browser said: not that the PUT landed, not its size.
841
+ const size = await driver.size(key);
842
+ if (size === null) {
843
+ throw new Error("no object at that key — the upload did not complete");
844
+ }
845
+ const index = readIndex(tenant, workspace);
846
+ const previous = index.files.find((f) => f.path === norm);
847
+ const record = {
848
+ path: norm,
849
+ sha,
850
+ size,
851
+ mime: mimeFor(norm),
852
+ updatedAt: new Date().toISOString(),
853
+ by,
854
+ };
855
+ const files = [...index.files.filter((f) => f.path !== norm), record];
856
+ // putFile's two limits, on the real length. A refused object is removed:
857
+ // nothing names it, so it would sit in the bucket unreachable and billed —
858
+ // unless a record already names these bytes, which are then not ours to drop.
859
+ const refuse = async (message) => {
860
+ if (!index.files.some((f) => f.sha === sha))
861
+ await driver.remove(key).catch(() => { });
862
+ throw new Error(message);
863
+ };
864
+ if (size > maxBytes()) {
865
+ await refuse(`${norm} is ${Math.round(size / 1e6)}MB — the limit is ${maxBytes() / 1e6}MB`);
866
+ }
867
+ if (bytesOf(files) > quotaBytes() && bytesOf(files) > bytesOf(index.files)) {
868
+ await refuse(`workspace file quota exceeded (${quotaBytes() / 1e6}MB)`);
869
+ }
870
+ indexPut(tenant, workspace, index, record);
871
+ if (previous && previous.sha !== sha)
872
+ await collectLocked(tenant, workspace, previous.sha);
873
+ return record;
874
+ }).then(async (record) => {
875
+ await announceFiles(tenant, workspace, [record.path], by);
876
+ return record;
877
+ });
662
878
  }
663
879
  export async function readFileBytes(tenant, workspace, rel) {
664
880
  const record = getFile(tenant, workspace, rel);
@@ -694,18 +910,24 @@ export async function openFile(tenant, workspace, rel, range) {
694
910
  }
695
911
  export async function deleteFile(tenant, workspace, rel) {
696
912
  const norm = assertFilePath(rel);
697
- const index = readIndex(tenant, workspace);
698
- const record = index.files.find((f) => f.path === norm);
699
- if (!record)
700
- return false;
701
- writeIndex(tenant, workspace, { version: 1, files: index.files.filter((f) => f.path !== norm) });
702
- await collect(tenant, workspace, record.sha);
703
- // The run mirror is a cache of the index, so it follows the index.
704
- fs.rmSync(path.join(workspaceDir(tenant, workspace), STORAGE_DIR, norm), { force: true });
705
- return true;
706
- }
707
- /** Drop a blob once the last record naming it is gone. */
708
- async function collect(tenant, workspace, sha) {
913
+ return withFileStoreLock(tenant, workspace, async () => {
914
+ const index = readIndex(tenant, workspace);
915
+ const record = index.files.find((f) => f.path === norm);
916
+ if (!record)
917
+ return false;
918
+ indexRemove(tenant, workspace, index, norm);
919
+ await collectLocked(tenant, workspace, record.sha);
920
+ // The run mirror is a cache of the index, so it follows the index.
921
+ fs.rmSync(path.join(workspaceDir(tenant, workspace), STORAGE_DIR, norm), { force: true });
922
+ return true;
923
+ });
924
+ }
925
+ /** Drop a blob once the last record naming it is gone. The caller holds the
926
+ * workspace lock: the reference check and the delete are one step, and a put
927
+ * that is about to name this blob waits for the lock and then confirms the
928
+ * blob is present before it does (putFileQuietly), so neither can strand the
929
+ * other. */
930
+ async function collectLocked(tenant, workspace, sha) {
709
931
  if (readIndex(tenant, workspace).files.some((f) => f.sha === sha))
710
932
  return;
711
933
  try {
@@ -783,8 +1005,16 @@ function storeDirOf(tenant, workspace) {
783
1005
  * unreachable), and a no-op when there is no store.
784
1006
  */
785
1007
  export async function purgeWorkspaceStorage(tenant, workspace) {
1008
+ if (!fileStoreEnabled())
1009
+ return;
1010
+ return withFileStoreLock(tenant, workspace, () => purgeUnlocked(tenant, workspace));
1011
+ }
1012
+ async function purgeUnlocked(tenant, workspace) {
786
1013
  const dir = storeDirOf(tenant, workspace);
787
- if (!dir || !fs.existsSync(dir))
1014
+ const port = records(tenant, workspace);
1015
+ // With the index in the database the folder need not exist (a bucket holds
1016
+ // the objects), so the rows decide whether there is anything to purge.
1017
+ if (!dir || (!fs.existsSync(dir) && !(port && port.fileList(tenant, workspace).length)))
788
1018
  return;
789
1019
  const driver = driverFor(tenant, workspace);
790
1020
  if (driver.kind !== "fs") {
@@ -792,6 +1022,9 @@ export async function purgeWorkspaceStorage(tenant, workspace) {
792
1022
  for (const sha of shas)
793
1023
  await driver.remove(blobKey(tenant, workspace, sha)).catch(() => { });
794
1024
  }
1025
+ if (port)
1026
+ for (const f of port.fileList(tenant, workspace))
1027
+ port.fileDelete(tenant, workspace, f.path);
795
1028
  fs.rmSync(dir, { recursive: true, force: true });
796
1029
  }
797
1030
  /**
@@ -809,13 +1042,26 @@ export async function purgeWorkspaceStorage(tenant, workspace) {
809
1042
  * workspace of that name that no longer exists, never to this one.
810
1043
  */
811
1044
  export async function moveWorkspaceStorage(tenant, from, to) {
1045
+ if (!fileStoreEnabled() || from === to)
1046
+ return;
1047
+ // Both names, in a fixed order: an upload to the NEW name must not land in a
1048
+ // store this call is about to replace, and two crossing renames must not
1049
+ // each hold one lock and wait for the other.
1050
+ const [first, second] = [from, to].sort();
1051
+ return withFileStoreLock(tenant, first, () => withFileStoreLock(tenant, second, () => moveUnlocked(tenant, from, to)));
1052
+ }
1053
+ async function moveUnlocked(tenant, from, to) {
812
1054
  const src = storeDirOf(tenant, from);
813
1055
  const dest = storeDirOf(tenant, to);
814
1056
  if (!src || !dest || src === dest)
815
1057
  return;
816
- if (fs.existsSync(dest))
817
- await purgeWorkspaceStorage(tenant, to);
818
- if (!fs.existsSync(src))
1058
+ const port = records(tenant, from);
1059
+ // Whatever a store under the new name held belonged to a workspace of that
1060
+ // name that no longer exists. (The file index has not moved yet: it moves
1061
+ // below, after the bytes, so rows under `to` are that stale store's.)
1062
+ if (fs.existsSync(dest) || (port && port.fileList(tenant, to).length))
1063
+ await purgeUnlocked(tenant, to);
1064
+ if (!fs.existsSync(src) && !(port && port.fileList(tenant, from).length))
819
1065
  return;
820
1066
  const driver = driverFor(tenant, from);
821
1067
  const shas = driver.kind === "fs" ? [] : [...new Set(readIndex(tenant, from).files.map((f) => f.sha))];
@@ -823,8 +1069,12 @@ export async function moveWorkspaceStorage(tenant, from, to) {
823
1069
  throw new Error(`the ${driver.kind} store cannot move files to a new workspace name`);
824
1070
  for (const sha of shas)
825
1071
  await driver.copy(blobKey(tenant, from, sha), blobKey(tenant, to, sha));
826
- fs.mkdirSync(path.dirname(dest), { recursive: true });
827
- fs.renameSync(src, dest);
1072
+ if (fs.existsSync(src)) {
1073
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
1074
+ fs.renameSync(src, dest);
1075
+ }
1076
+ // The index follows the bytes, once they are all across.
1077
+ port?.fileMove(tenant, from, to);
828
1078
  for (const sha of shas)
829
1079
  await driver.remove(blobKey(tenant, from, sha)).catch(() => { });
830
1080
  }
@@ -951,6 +951,14 @@ export declare function assertDeletable(tenant: string, workspace: string, rel:
951
951
  };
952
952
  export declare function deleteWorkspacePath(tenant: string, workspace: string, rel: string, meta?: ChangeMeta): void;
953
953
  export declare function deleteWorkspace(tenant: string, workspace: string): void;
954
+ /**
955
+ * deleteWorkspace, with the workspace's revisions: its history is dropped
956
+ * BEFORE the folder goes (a store that cannot be reached refuses the delete
957
+ * while it can still be retried) and once more after, for whatever a racing
958
+ * write made in between. A new workspace of the same name starts empty.
959
+ * Where nothing records revisions this is deleteWorkspace.
960
+ */
961
+ export declare function deleteWorkspaceAsync(tenant: string, workspace: string): Promise<void>;
954
962
  /**
955
963
  * What a rename would break, so the caller can say so before doing it.
956
964
  *
@@ -971,6 +979,14 @@ export declare function renameImpact(tenant: string, workspace: string): {
971
979
  * there is nothing to migrate and nothing to lose.
972
980
  */
973
981
  export declare function renameWorkspace(tenant: string, from: string, to: string): void;
982
+ /**
983
+ * renameWorkspace, with the workspace's revisions: queued changes are held
984
+ * while its history is re-keyed to the new name, then the folder moves; if the
985
+ * folder cannot move the history goes back. A store that cannot be reached
986
+ * refuses the rename before anything moved. Where nothing records revisions
987
+ * this is renameWorkspace.
988
+ */
989
+ export declare function renameWorkspaceAsync(tenant: string, from: string, to: string): Promise<void>;
974
990
  /** Set a workspace's description, in AGENTS.md, without touching anything else.
975
991
  *
976
992
  * 30 Oct 2026: the value was spliced in as `description: ${text}`, so a
@@ -1668,7 +1684,28 @@ export declare function listRunOutputs(tenant: string, workspace: string, runId:
1668
1684
  * the archive or names nothing — the API serves only what this returns. */
1669
1685
  export declare function runOutputPath(tenant: string, workspace: string, runId: string, agent: string, rel: string): string | null;
1670
1686
  export declare function readRun(tenant: string, workspace: string, runId: string): RunRecord | null;
1687
+ /** readRun without holding the event loop: asked of the database directly
1688
+ * where the port has async reads, otherwise the synchronous read. */
1689
+ export declare function readRunAsync(tenant: string, workspace: string, runId: string): Promise<RunRecord | null>;
1690
+ /** writeRun without holding the event loop (FOL-126 phase 4): for the callers
1691
+ * that are async anyway. Where the port writes asynchronously the record is
1692
+ * written when this resolves; everywhere else (files, a port without the
1693
+ * async write) it IS writeRun. The sync callers (the runner's save) are
1694
+ * untouched. */
1695
+ export declare function writeRunAsync(tenant: string, workspace: string, run: RunRecord): Promise<void>;
1671
1696
  export declare function writeRun(tenant: string, workspace: string, run: RunRecord): void;
1697
+ /** When a run's record last changed, as a string that differs whenever it
1698
+ * does — what a poller compares instead of a file's stat. Null: no such run
1699
+ * (or, for a file, gone for a moment — read to find out). */
1700
+ export declare function runStamp(tenant: string, workspace: string, runId: string): string | null;
1701
+ /** When a run's record was last written (epoch ms), or null when there is none. */
1702
+ export declare function runUpdatedMs(tenant: string, workspace: string, runId: string): number | null;
1703
+ /** A run's record as the JSON text a stream sends, or null when there is none. */
1704
+ export declare function readRunText(tenant: string, workspace: string, runId: string): string | null;
1705
+ /** Runs of one workspace that started at or after `sinceMs`, whole, newest
1706
+ * first. Off the records where there are any; the files otherwise read only
1707
+ * the names that say when they began. */
1708
+ export declare function runsStartedSince(tenant: string, workspace: string, sinceMs: number): RunRecord[];
1672
1709
  /**
1673
1710
  * The workspace's live runs — queued, running, or parked at a gate — read
1674
1711
  * whole, newest first. Off the run index: only the live records are opened,
@@ -1676,6 +1713,8 @@ export declare function writeRun(tenant: string, workspace: string, run: RunReco
1676
1713
  * periodic sweeps want (reconcile, the watchdog), and on a box that keeps
1677
1714
  * ninety days of runs that is a handful of files instead of thousands.
1678
1715
  */
1716
+ /** liveRuns without holding the event loop (see readRunAsync). */
1717
+ export declare function liveRunsAsync(tenant: string, workspace: string): Promise<RunRecord[]>;
1679
1718
  export declare function liveRuns(tenant: string, workspace: string): RunRecord[];
1680
1719
  export interface RunWithWorkspace extends RunRecord {
1681
1720
  workspace: string;
@@ -1763,6 +1802,8 @@ export declare function runFromSummary(s: RunSummary): RunRecord;
1763
1802
  * are re-read, and the index is rewritten if anything changed. A missing
1764
1803
  * or unreadable index is a full scan that leaves one behind.
1765
1804
  */
1805
+ /** listRunSummaries without holding the event loop (see readRunAsync). */
1806
+ export declare function listRunSummariesAsync(tenant: string, workspace: string): Promise<RunSummary[]>;
1766
1807
  export declare function listRunSummaries(tenant: string, workspace: string): RunSummary[];
1767
1808
  /** Every workspace's runs as summaries, tagged with the workspace. */
1768
1809
  export declare function listAllRunSummaries(tenant: string): (RunSummary & {