@foldrun/core 21.0.0 → 21.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/src/secrets.ts CHANGED
@@ -503,6 +503,7 @@ export function setSecretSites(tenant: string, name: string, sites: string[], wo
503
503
  }
504
504
  let found = false;
505
505
  mutateVault(tenant, workspace, (all) => {
506
+ found = false; // a store may run this again against a newer read
506
507
  const rec = all[name];
507
508
  if (!rec) return null;
508
509
  found = true;
@@ -692,6 +693,7 @@ export function setSecretWorkspaces(
692
693
  const expected = opts.ifWorkspaces === undefined ? undefined : cleanWorkspaceList(opts.ifWorkspaces);
693
694
  let found = false;
694
695
  mutateVault(tenant, undefined, (all) => {
696
+ found = false; // a store may run this again against a newer read
695
697
  const rec = all[name];
696
698
  if (!rec) return null;
697
699
  found = true;
@@ -865,8 +867,9 @@ export function masterKeySource(): { source: "env" | "file"; path: string | null
865
867
  : { source: "file", path: keyFile() };
866
868
  }
867
869
 
868
- /** Every secrets.json under an account: the account's, then each workspace's. */
869
- function secretFiles(tenant: string): { file: string; workspace?: string }[] {
870
+ /** The secrets.json files that exist under an account: the account's (named
871
+ * even where there is none), then each workspace's. */
872
+ function diskSecretFiles(tenant: string): { file: string; workspace?: string }[] {
870
873
  const out: { file: string; workspace?: string }[] = [{ file: secretsFile(tenant) }];
871
874
  for (const dirName of ["workspaces", "projects"]) {
872
875
  const dir = path.join(dataRoot(), tenant, dirName);
@@ -877,6 +880,35 @@ function secretFiles(tenant: string): { file: string; workspace?: string }[] {
877
880
  if (fs.existsSync(f)) out.push({ file: f, workspace: entry.name });
878
881
  }
879
882
  }
883
+ return out;
884
+ }
885
+
886
+ /** Every vault scope that has a FILE on this volume, across all accounts:
887
+ * what a fleet check or a move to a store starts from. Never opens one. */
888
+ export function vaultFileScopes(): { tenant: string; workspace?: string }[] {
889
+ const out: { tenant: string; workspace?: string }[] = [];
890
+ if (!fs.existsSync(dataRoot())) return out;
891
+ for (const e of fs.readdirSync(dataRoot(), { withFileTypes: true })) {
892
+ if (!e.isDirectory()) continue;
893
+ try {
894
+ assertSafeName(e.name, "tenant");
895
+ } catch {
896
+ continue; // not an account's folder
897
+ }
898
+ for (const { file, workspace } of diskSecretFiles(e.name)) if (fs.existsSync(file)) out.push({ tenant: e.name, ...(workspace ? { workspace } : {}) });
899
+ }
900
+ return out;
901
+ }
902
+
903
+ /** Does this stored record open for its place with this process's keys? True
904
+ * or false: the value is never handed out. */
905
+ export function vaultRecordOpens(tenant: string, workspace: string | undefined, name: string, rec: SecretsFile[string]): boolean {
906
+ return openRecord(tenant, workspace, name, rec) !== null;
907
+ }
908
+
909
+ /** Every secrets.json under an account: the account's, then each workspace's. */
910
+ function secretFiles(tenant: string): { file: string; workspace?: string }[] {
911
+ const out = diskSecretFiles(tenant);
880
912
  // Scopes in the platform's store have no file; they are named by where
881
913
  // the file would be (the result's `file` is a label, never opened).
882
914
  for (const workspace of VAULT.store?.workspaces(tenant) ?? []) {
@@ -921,7 +953,10 @@ export function rotateMasterKey(
921
953
 
922
954
  for (const { file, workspace } of secretFiles(tenant)) {
923
955
  let count = 0;
956
+ const seen = unreadable.length;
924
957
  mutateVault(tenant, workspace, (all) => {
958
+ count = 0; // a store may run this again against a newer read
959
+ unreadable.length = seen;
925
960
  const next: SecretsFile = {};
926
961
  for (const [name, rec] of Object.entries(all)) {
927
962
  // A record under the ACCOUNT's key is not under the install key, so
@@ -1109,6 +1144,7 @@ export function replaceOAuth2RefreshToken(tenant: string, name: string, workspac
1109
1144
  for (const scope of workspace ? [workspace, undefined] : [undefined]) {
1110
1145
  let replaced = false;
1111
1146
  mutateVault(tenant, scope, (all) => {
1147
+ replaced = false; // a store may run this again against a newer read
1112
1148
  const rec = all[name];
1113
1149
  if (rec && openRecord(tenant, scope, name, rec) === usedValue) {
1114
1150
  // Built whole, not spread over the old record: a spread kept a stale
@@ -1962,7 +1998,11 @@ export function sealVaultBindings(tenant: string): { sealed: number; unreadable:
1962
1998
  let sealed = 0;
1963
1999
  const unreadable: string[] = [];
1964
2000
  for (const { workspace } of secretFiles(tenant)) {
2001
+ const [sealedBefore, seen] = [sealed, unreadable.length];
1965
2002
  mutateVault(tenant, workspace, (all) => {
2003
+ // a store may run this again against a newer read: count it once
2004
+ sealed = sealedBefore;
2005
+ unreadable.length = seen;
1966
2006
  const plain = new Map<string, string>();
1967
2007
  const bad: string[] = [];
1968
2008
  for (const [name, rec] of Object.entries(all)) {
@@ -2006,7 +2046,11 @@ export function rewrapTenantSecrets(tenant: string): { moved: number; unreadable
2006
2046
  for (const { workspace } of secretFiles(tenant)) {
2007
2047
  // Under the vault's lock: every pod runs this at boot, and a save made
2008
2048
  // between our read and our write must not be lost.
2049
+ const [movedBefore, seen] = [moved, unreadable.length];
2009
2050
  mutateVault(tenant, workspace, (all) => {
2051
+ // a store may run this again against a newer read: count it once
2052
+ moved = movedBefore;
2053
+ unreadable.length = seen;
2010
2054
  const plain = new Map<string, string>();
2011
2055
  const unreadableHere: string[] = [];
2012
2056
  for (const [name, rec] of Object.entries(all)) {
package/src/store.ts CHANGED
@@ -31,6 +31,7 @@ import { processState } from "./process-state.ts";
31
31
  import { dataRoot, singleWorkspace, singleAccountRoot, entriesNoFollow } from "./paths.ts";
32
32
  import { platform } from "./platform.ts";
33
33
  import { records } from "./records.ts";
34
+ import { docRows, docStore, quietly } from "./workspace-docs.ts";
34
35
  import { toLF, asRaw } from "./eol.ts";
35
36
  import type { TestEffect } from "./test-mode.ts";
36
37
  import type { OperatorEvent } from "./operator.ts";
@@ -4065,6 +4066,7 @@ export interface RunRecord {
4065
4066
  // runs/<run>/). The runner writes them, secrets already masked.
4066
4067
 
4067
4068
  const SAFE_ID = /^[A-Za-z0-9_.-]{1,128}$/;
4069
+ const CALL_KIND = "call";
4068
4070
 
4069
4071
  function capturedCallFile(workspaceRoot: string, runId: string, callId: string): string | null {
4070
4072
  if (!SAFE_ID.test(runId) || !SAFE_ID.test(callId) || callId.startsWith(".") || runId.startsWith(".")) return null;
@@ -4073,9 +4075,14 @@ function capturedCallFile(workspaceRoot: string, runId: string, callId: string):
4073
4075
 
4074
4076
  /** Merge one part (the input, on the call; the output, on its completion)
4075
4077
  * into the call's file. */
4076
- export function writeCapturedCall(workspaceRoot: string, runId: string, part: CapturedCall): void {
4078
+ export function writeCapturedCall(workspaceRoot: string, runId: string, part: CapturedCall, scope?: { tenant: string; workspace: string }): void {
4077
4079
  const file = capturedCallFile(workspaceRoot, runId, part.id);
4078
4080
  if (!file) return;
4081
+ // A row when the platform keeps them (FOL-126): the two parts of a call
4082
+ // merge in one statement, and the web's copies read it wherever they run.
4083
+ // `truncated` is only ever sent true, so a merge keeps it once set.
4084
+ const store = scope ? docStore(scope.tenant, scope.workspace) : null;
4085
+ if (store && scope) return store.merge(scope.tenant, scope.workspace, CALL_KIND, `${runId}/${part.id}`, part as unknown as Record<string, unknown>);
4079
4086
  let prev: Partial<CapturedCall> = {};
4080
4087
  try {
4081
4088
  prev = JSON.parse(fs.readFileSync(file, "utf8")) as CapturedCall;
@@ -4094,11 +4101,20 @@ export function writeCapturedCall(workspaceRoot: string, runId: string, part: Ca
4094
4101
  export function readCapturedCall(tenant: string, workspace: string, runId: string, callId: string): CapturedCall | null {
4095
4102
  const file = capturedCallFile(workspaceDir(tenant, workspace), runId, callId);
4096
4103
  if (!file) return null;
4104
+ const row = quietly(() => docRows(tenant, workspace)?.get(tenant, workspace, CALL_KIND, `${runId}/${callId}`), undefined) as CapturedCall | undefined;
4105
+ let onFile: CapturedCall | undefined;
4097
4106
  try {
4098
- return JSON.parse(fs.readFileSync(file, "utf8")) as CapturedCall;
4107
+ onFile = JSON.parse(fs.readFileSync(file, "utf8")) as CapturedCall;
4099
4108
  } catch {
4100
- return null;
4109
+ /* none */
4110
+ }
4111
+ // A switch between a call's two parts leaves one part in each place: both, merged.
4112
+ if (row && onFile) {
4113
+ const merged: CapturedCall = { ...onFile, ...row, truncated: Boolean(onFile.truncated || row.truncated) || undefined };
4114
+ if (!merged.truncated) delete merged.truncated;
4115
+ return merged;
4101
4116
  }
4117
+ return row ?? onFile ?? null;
4102
4118
  }
4103
4119
 
4104
4120
  export function runFilePath(tenant: string, workspace: string, runId: string) {
@@ -4138,6 +4154,8 @@ export function deleteRun(tenant: string, workspace: string, runId: string, opts
4138
4154
  // and finishes — the other order left the content with nothing pointing
4139
4155
  // at it (Codex review, FOL-124).
4140
4156
  fs.rmSync(dir, { recursive: true, force: true });
4157
+ // Its captured calls kept as rows go the same way, before the record.
4158
+ if (SAFE_ID.test(runId)) docRows(tenant, workspace)?.dropPrefix(tenant, workspace, CALL_KIND, `${runId}/`);
4141
4159
  if (port) port.runDelete(tenant, workspace, runId);
4142
4160
  else {
4143
4161
  fs.rmSync(file, { force: true });
package/src/webhook.ts CHANGED
@@ -8,6 +8,8 @@ import path from "node:path";
8
8
  import { workspaceDir } from "./store.ts";
9
9
  import { installKeyMaterial } from "./secrets.ts";
10
10
  import crypto from "node:crypto";
11
+ import { docRows, docStore, quietly } from "./workspace-docs.ts";
12
+ import type { DocsPort } from "./records.ts";
11
13
 
12
14
  /**
13
15
  * The install's secret key. Every derived token — flow hooks, git secrets,
@@ -49,19 +51,37 @@ function readHooks(tenant: string, workspace: string): Record<string, HookState>
49
51
  }
50
52
  }
51
53
 
54
+ /** The hook's generation: the greater of the row's and the file's, so a
55
+ * rotation made while `records.docs_store` was on (a row) or off (the file)
56
+ * holds whichever way the switch stands now — an old URL never comes back.
57
+ * A database that cannot answer fails the call: guessing from the file could
58
+ * accept a token that was rotated away. */
52
59
  export function hookGeneration(tenant: string, workspace: string, flow: string): number {
53
- return readHooks(tenant, workspace)[flow]?.gen ?? 0;
60
+ const file = readHooks(tenant, workspace)[flow]?.gen ?? 0;
61
+ const row = (docRows(tenant, workspace)?.get(tenant, workspace, HOOK_KIND, flow) as HookState | undefined)?.gen ?? 0;
62
+ return Math.max(file, row);
54
63
  }
55
64
 
65
+ const HOOK_KIND = "hook";
66
+ const DELIVERY_KIND = "hook-delivery";
67
+
56
68
  /** Invalidate a hook's URL and mint the next one. Returns the new path. */
57
69
  export function rotateWebhook(tenant: string, workspace: string, flow: string): string {
58
70
  const hooks = readHooks(tenant, workspace);
59
- hooks[flow] = { gen: (hooks[flow]?.gen ?? 0) + 1, rotatedAt: new Date().toISOString() };
60
71
  const file = hooksFile(tenant, workspace);
61
72
  // Into a workspace that exists, never making one (30 Oct 2026): the mkdir
62
73
  // here turned a rotate under a mistyped name into a workspace holding only
63
74
  // hooks.json, past the plan's workspace count.
64
75
  if (!fs.existsSync(path.dirname(file))) throw Object.assign(new Error(`workspace ${workspace} not found`), { status: 404 });
76
+ const rotatedAt = new Date().toISOString();
77
+ const store = docStore(tenant, workspace);
78
+ if (store) {
79
+ // One statement moves the row past both its own value and the file's.
80
+ store.raise(tenant, workspace, HOOK_KIND, flow, "gen", (hooks[flow]?.gen ?? 0) + 1, { rotatedAt });
81
+ return webhookPath(tenant, workspace, flow);
82
+ }
83
+ // On the file: still past whatever a row holds (hookGeneration reads both).
84
+ hooks[flow] = { gen: hookGeneration(tenant, workspace, flow) + 1, rotatedAt };
65
85
  fs.writeFileSync(file, JSON.stringify(hooks, null, 2));
66
86
  return webhookPath(tenant, workspace, flow);
67
87
  }
@@ -184,6 +204,8 @@ const KEEP_DELIVERIES = 500;
184
204
  export function recordDelivery(tenant: string, workspace: string, delivery: HookDelivery) {
185
205
  const file = deliveriesFile(tenant, workspace);
186
206
  if (!fs.existsSync(path.dirname(file))) return; // no workspace, nothing to log against
207
+ const store = docStore(tenant, workspace);
208
+ if (store) return recordDeliveryRow(store, tenant, workspace, delivery);
187
209
  if (UNAUTHENTICATED.includes(delivery.outcome)) return recordRefusal(file, tenant, workspace, delivery);
188
210
  fs.appendFileSync(file, JSON.stringify(delivery) + "\n");
189
211
  // Bounded: compact to the newest KEEP when it doubles. Amortised cheap,
@@ -200,6 +222,34 @@ export function recordDelivery(tenant: string, workspace: string, delivery: Hook
200
222
  }
201
223
  }
202
224
 
225
+ /** The same log as rows: an append that keeps the newest KEEP, and a refusal
226
+ * folded into the newest entry when that is a refusal too (so a flood is one
227
+ * row). The fold is read-then-replace: two refusals at once may count one
228
+ * short, never push a real delivery out. */
229
+ function recordDeliveryRow(store: DocsPort, tenant: string, workspace: string, delivery: HookDelivery) {
230
+ if (UNAUTHENTICATED.includes(delivery.outcome)) {
231
+ const [last] = store.tail(tenant, workspace, DELIVERY_KIND, 1);
232
+ const prev = last?.data as HookDelivery | undefined;
233
+ if (last && prev && UNAUTHENTICATED.includes(prev.outcome)) {
234
+ store.replace(tenant, workspace, DELIVERY_KIND, last.id, foldRefusal(prev, delivery));
235
+ return;
236
+ }
237
+ }
238
+ store.append(tenant, workspace, DELIVERY_KIND, delivery, KEEP_DELIVERIES);
239
+ }
240
+
241
+ /** A refusal folded into the refusal before it. The flow name is not part of
242
+ * the match: it comes from the URL, so a flood that varies it would
243
+ * otherwise never collapse. */
244
+ function foldRefusal(last: HookDelivery, delivery: HookDelivery): HookDelivery {
245
+ return {
246
+ ...delivery,
247
+ count: (last.count ?? 1) + 1,
248
+ first: last.first ?? last.t,
249
+ ...(last.detail === "more than one flow name" || last.flow !== delivery.flow ? { detail: "more than one flow name" } : {}),
250
+ };
251
+ }
252
+
203
253
  /**
204
254
  * A refusal — anyone's to send — never changes the workspace's directory: no
205
255
  * new file, no tmp file, no rename. The directory's mtime is the workspace's
@@ -252,12 +302,7 @@ function collapseInto(file: string, delivery: HookDelivery): boolean {
252
302
  return false;
253
303
  }
254
304
  if (!UNAUTHENTICATED.includes(last.outcome)) return false;
255
- const merged: HookDelivery = {
256
- ...delivery,
257
- count: (last.count ?? 1) + 1,
258
- first: last.first ?? last.t,
259
- ...(last.detail === "more than one flow name" || last.flow !== delivery.flow ? { detail: "more than one flow name" } : {}),
260
- };
305
+ const merged = foldRefusal(last, delivery);
261
306
  const line = Buffer.from(JSON.stringify(merged) + "\n");
262
307
  const at = Buffer.byteLength(end.slice(0, cut));
263
308
  const fd = fs.openSync(file, "r+");
@@ -271,6 +316,16 @@ function collapseInto(file: string, delivery: HookDelivery): boolean {
271
316
  }
272
317
 
273
318
  export function readDeliveries(tenant: string, workspace: string, limit = 20): HookDelivery[] {
319
+ // Rows and the file both: the log may have been written either way.
320
+ const rows = quietly(() => docRows(tenant, workspace)?.tail(tenant, workspace, DELIVERY_KIND, limit) ?? [], []).map((r) => r.data as HookDelivery);
321
+ const lines = readDeliveryLines(tenant, workspace, limit);
322
+ if (!rows.length) return lines;
323
+ if (!lines.length) return rows;
324
+ // Stable: equal times keep each source's own newest-first order.
325
+ return [...rows, ...lines].sort((a, b) => String(b.t).localeCompare(String(a.t))).slice(0, limit);
326
+ }
327
+
328
+ function readDeliveryLines(tenant: string, workspace: string, limit: number): HookDelivery[] {
274
329
  const file = deliveriesFile(tenant, workspace);
275
330
  if (!fs.existsSync(file)) return [];
276
331
  return fs
@@ -0,0 +1,33 @@
1
+ // Where a workspace's small state lives (FOL-126): rows through the records
2
+ // port when the platform registered one that has them, the folder otherwise.
3
+ //
4
+ // Two answers, because a switch must never lose what is already written:
5
+ // `docStore` is where a WRITE goes (rows only while `records.docs_store` is
6
+ // on), `docRows` is what a READ also asks (rows whenever the port has them,
7
+ // on or off). Every caller reads both places and keeps the newer; nothing is
8
+ // copied between them.
9
+
10
+ import { records, type DocsPort } from "./records.ts";
11
+
12
+ /** Rows to read: the port's, whatever the switch says. Null on a laptop, the
13
+ * CLI, and for a workspace whose records are still files. */
14
+ export function docRows(tenant: string, workspace: string): DocsPort | null {
15
+ return records(tenant, workspace)?.docs ?? null;
16
+ }
17
+
18
+ /** Rows to write to, or null: write the folder. */
19
+ export function docStore(tenant: string, workspace: string): DocsPort | null {
20
+ const port = records(tenant, workspace);
21
+ if (!port?.docs || !port.docsOn?.()) return null;
22
+ return port.docs;
23
+ }
24
+
25
+ /** A read that must not take the caller down with the database: these are
26
+ * logs and markers beside the work, never the work. */
27
+ export function quietly<T>(fn: () => T, fallback: T): T {
28
+ try {
29
+ return fn();
30
+ } catch {
31
+ return fallback;
32
+ }
33
+ }