@foldrun/core 15.0.0 → 16.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 (63) hide show
  1. package/dist/src/a2a-publish.d.ts +7 -0
  2. package/dist/src/a2a-publish.js +15 -1
  3. package/dist/src/a2a-reach.d.ts +156 -0
  4. package/dist/src/a2a-reach.js +446 -0
  5. package/dist/src/browse-egress.d.ts +1 -1
  6. package/dist/src/browse-egress.js +7 -6
  7. package/dist/src/capture.js +2 -1
  8. package/dist/src/env-names.d.ts +12 -0
  9. package/dist/src/env-names.js +49 -0
  10. package/dist/src/failure.d.ts +92 -0
  11. package/dist/src/failure.js +294 -0
  12. package/dist/src/frontmatter-fields.js +1 -1
  13. package/dist/src/install-helper.js +10 -5
  14. package/dist/src/mail.js +2 -1
  15. package/dist/src/network.js +1 -1
  16. package/dist/src/notify.js +12 -7
  17. package/dist/src/ops-log.d.ts +55 -0
  18. package/dist/src/ops-log.js +393 -0
  19. package/dist/src/otel.d.ts +16 -1
  20. package/dist/src/otel.js +121 -5
  21. package/dist/src/run-container.d.ts +55 -3
  22. package/dist/src/run-container.js +109 -17
  23. package/dist/src/run-event.d.ts +179 -0
  24. package/dist/src/run-event.js +473 -0
  25. package/dist/src/runner.js +14 -5
  26. package/dist/src/runtime.d.ts +113 -16
  27. package/dist/src/runtime.js +528 -44
  28. package/dist/src/scan.js +80 -18
  29. package/dist/src/secrets.js +4 -3
  30. package/dist/src/starter.js +1 -1
  31. package/dist/src/step-exec.d.ts +4 -2
  32. package/dist/src/step-exec.js +10 -4
  33. package/dist/src/storage.js +2 -1
  34. package/dist/src/store.d.ts +25 -3
  35. package/dist/src/store.js +40 -10
  36. package/dist/src/triggers.js +6 -5
  37. package/dist/src/webhook.js +3 -2
  38. package/package.json +2 -1
  39. package/src/a2a-publish.ts +19 -1
  40. package/src/a2a-reach.ts +503 -0
  41. package/src/browse-egress.ts +8 -7
  42. package/src/capture.ts +2 -1
  43. package/src/env-names.ts +53 -0
  44. package/src/failure.ts +368 -0
  45. package/src/frontmatter-fields.ts +1 -1
  46. package/src/install-helper.ts +10 -5
  47. package/src/mail.ts +2 -1
  48. package/src/network.ts +1 -1
  49. package/src/notify.ts +12 -9
  50. package/src/ops-log.ts +403 -0
  51. package/src/otel.ts +122 -7
  52. package/src/run-container.ts +112 -21
  53. package/src/run-event.ts +563 -0
  54. package/src/runner.ts +14 -5
  55. package/src/runtime.ts +543 -45
  56. package/src/scan.ts +91 -20
  57. package/src/secrets.ts +4 -5
  58. package/src/starter.ts +1 -1
  59. package/src/step-exec.ts +10 -4
  60. package/src/storage.ts +2 -1
  61. package/src/store.ts +59 -11
  62. package/src/triggers.ts +6 -5
  63. package/src/webhook.ts +3 -2
package/src/scan.ts CHANGED
@@ -33,7 +33,9 @@ import { resolveNetwork } from "./network.ts";
33
33
  import { frontmatterProblems, schemaKindOf } from "./frontmatter-schema.ts";
34
34
  import { parseRemotes } from "./a2a-remotes.ts";
35
35
  import { isA2aPublished } from "./a2a-publish.ts";
36
+ import { a2aTree, flowSecretCode, type A2aTree } from "./a2a-reach.ts";
36
37
  import { parseFlow, resolveEffort, parseMaxOutputTokens, type FlowStep } from "./store.ts";
38
+ import { reservedEnvName } from "./env-names.ts";
37
39
 
38
40
  export type ScanLevel = "error" | "warn" | "info";
39
41
  export type ScanCategory = "secret" | "security" | "content" | "supply-chain" | "config";
@@ -154,14 +156,33 @@ export const SCAN_RULES: readonly ScanRule[] = [
154
156
  id: "security/published-flow-trifecta",
155
157
  category: "security",
156
158
  level: "warn",
157
- title: "A flow published over A2A runs an agent that holds private data and can send it out",
159
+ title: "A flow published over A2A runs an agent that holds private data — its answer, or its network, can carry it out",
158
160
  help:
159
- "An outside agent's message is untrusted input to every step of a published flow. A step whose agent also holds a secret, " +
160
- "an API or an MCP server, and can reach an open network, an outward tool or an API it may write to, can be told by the caller " +
161
- "where to send what it holds. Take a leg away from that agent (network: { level: trusted, allow: [...] }, split it, a hooks: gate), " +
162
- "or do not publish the flow.",
161
+ "An outside agent's message is untrusted input to every step of a published flow, and the flow's answer goes back to that caller — " +
162
+ "so the answer is a way out too (5 Nov 2026). A step whose agent holds a secret, an API or an MCP server can be told by the caller " +
163
+ "to put what it holds or reads in its answer, or to send it to an open network, an outward tool or an API it may write to. A hooks: " +
164
+ "gate guards tool calls, not the answer. Give that agent only what a stranger may see, move the private part to a flow that is not " +
165
+ "published, or do not publish the flow.",
163
166
  owasp: ["ASI01", "ASI02", "ASI03"],
164
167
  },
168
+ {
169
+ // 5 Nov 2026 (FOL-112): the answer is a way out. A published flow's last
170
+ // step answers the outside caller, and an agent that holds a secret in
171
+ // its sandbox and may run code can be told to put the secret in it —
172
+ // no network needed. The platform refuses to publish such a flow unless
173
+ // an admin names the agent under `a2a.accept_risk`; this is check's half.
174
+ id: "security/published-flow-secret-code",
175
+ category: "security",
176
+ level: "warn",
177
+ title: "A flow published over A2A runs an agent that holds a secret and can run code",
178
+ help:
179
+ "Its answer goes back to the outside caller, and code (Bash) can read every secret in the sandbox's environment — so a caller can ask " +
180
+ "for the secret in the reply. Take Bash away from that agent (disallowedTools: [Bash], or a step without code), take the secret away " +
181
+ "(or bind it to its sites with `foldrun secrets sites NAME host` so it never enters the sandbox), or have an admin accept the risk: " +
182
+ "`a2a: { accept_risk: [<agent>] }` (`foldrun a2a publish <flow> --accept-risk <agent>`). Until one of those, the platform refuses to " +
183
+ "publish the flow and refuses new A2A tasks for it.",
184
+ owasp: ["ASI01", "ASI03"],
185
+ },
165
186
  {
166
187
  id: "security/published-flow-ungated",
167
188
  category: "security",
@@ -349,6 +370,20 @@ export const SCAN_RULES: readonly ScanRule[] = [
349
370
  "and the value itself is deployed and versioned in plain text. Put it in the vault (`foldrun secrets set NAME`), write the name, and rotate it.",
350
371
  owasp: ["ASI03"],
351
372
  },
373
+ {
374
+ // 5 Nov 2026 (FOL-130): a secret is exported to the sandbox under its name.
375
+ id: "secret/reserved-env-name",
376
+ category: "security",
377
+ level: "warn",
378
+ title: "A secret named after a variable that steers every program",
379
+ help:
380
+ "A secret reaches the sandbox as an environment variable of the same name, so one called LD_PRELOAD, PATH, BASH_ENV, IFS, " +
381
+ "NODE_OPTIONS or PYTHONPATH replaces what every program the agent starts loads or looks up — almost never what was meant, and " +
382
+ "a value pointing into a folder the agent writes runs whatever is put there. Root's start-up never reads the step's environment, " +
383
+ "so this is the agent's own sandbox at stake, not the platform. Give the secret a name of its own (`STRIPE_KEY`, `CRM_TOKEN`) " +
384
+ "and have the script read that.",
385
+ owasp: ["ASI03", "ASI05"],
386
+ },
352
387
  {
353
388
  id: "check/ignore-needs-reason",
354
389
  category: "config",
@@ -759,6 +794,28 @@ function docKind(p: string): Kind {
759
794
  return null;
760
795
  }
761
796
 
797
+ // ── secret names that are not data ─────────────────────────────────────────
798
+
799
+ /** secret/reserved-env-name: an agent's or a tool's `secrets:` naming a
800
+ * variable that steers programs (env-names.ts). `${NAME}` reads as NAME. */
801
+ function scanSecretNames(f: ScanFile, data: Record<string, unknown>, lines: string[], push: Push): void {
802
+ const raw = data.secrets;
803
+ const names = (Array.isArray(raw) ? raw : typeof raw === "string" ? [raw] : [])
804
+ .filter((n): n is string => typeof n === "string")
805
+ .map((n) => n.trim().replace(/^\$\{(.*)\}$/, "$1"));
806
+ for (const name of new Set(names)) {
807
+ const why = reservedEnvName(name);
808
+ if (!why) continue;
809
+ const word = new RegExp(`(^|[^A-Za-z0-9_])${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}([^A-Za-z0-9_]|$)`);
810
+ const from = keyLine(lines, "secrets");
811
+ const at = from ? (lines.slice(from - 1).findIndex((l) => word.test(l)) + from) || from : undefined;
812
+ push(
813
+ "secret/reserved-env-name", f.path, at, `reserved-env ${name}`,
814
+ `secrets: ${name} — the secret is exported under that name, and ${why}. Rename it (and what reads it) to a name of its own`,
815
+ );
816
+ }
817
+ }
818
+
762
819
  // ── agents: what one can reach, taken together ─────────────────────────────
763
820
 
764
821
  const WRITE_METHODS = /\b(?:POST|PUT|PATCH|DELETE)\b/i;
@@ -882,28 +939,41 @@ function stepAgents(s: FlowStep): string[] {
882
939
  * what it holds (the trifecta, with the caller as the untrusted leg), and a
883
940
  * step that acts outside the workspace with no person before it.
884
941
  */
885
- function scanPublishedFlows(flows: FlowFacts[], legs: Map<string, AgentLegs>, push: Push) {
942
+ function scanPublishedFlows(flows: FlowFacts[], legs: Map<string, AgentLegs>, tree: A2aTree, push: Push) {
886
943
  for (const fl of flows) {
887
944
  let info: ReturnType<typeof parseFlow>;
888
945
  try {
889
- info = parseFlow(fl.file, fl.content);
946
+ info = parseFlow(fl.file.replace(/^.*\//, ""), fl.content); // named as the platform names it: leads, not flows/leads
890
947
  } catch {
891
948
  continue; // a flow that does not parse is check's finding
892
949
  }
893
950
  if (!isA2aPublished(info.a2a)) continue;
894
951
  const at = keyLine(fl.lines, "a2a");
895
- const said = new Set<string>();
896
- for (const step of info.steps) {
897
- for (const name of stepAgents(step)) {
898
- const l = legs.get(name);
899
- if (!l || said.has(name) || l.gated || !l.privateLeg.length || !l.outLeg.length) continue;
900
- said.add(name);
901
- push(
902
- "security/published-flow-trifecta", fl.file, step.line ?? at, `published trifecta ${name}`,
903
- `${info.name} is published over A2A, so what an outside caller sends reaches ${name}, which holds ${l.privateLeg.slice(0, 3).join(", ")}${l.privateLeg.length > 3 ? ", …" : ""} ` +
904
- `and can reach ${l.outLeg.slice(0, 2).join(" and ")} — a caller can tell it where to send what it holds. Take a leg away from ${name}, or do not publish the flow`,
905
- );
906
- }
952
+ // Each agent at the first step line that runs it; a sub-agent or a
953
+ // subflow's agent at the a2a: line.
954
+ const lineOf = (name: string) => info.steps.find((s) => !s.subflow && [s.agent, s.onFail, ...(s.delegate ?? [])].includes(name))?.line ?? at;
955
+ // The answer goes back to the caller (FOL-112): any private leg is
956
+ // enough, and a hooks: gate (which guards tool calls) does not close it.
957
+ for (const name of tree.flows.get(info.name)?.file === fl.file ? tree.agentsOf(info.name) : []) {
958
+ const l = legs.get(name);
959
+ if (!l || !l.privateLeg.length) continue;
960
+ const out = !l.gated && l.outLeg.length ? ` and can reach ${l.outLeg.slice(0, 2).join(" and ")}` : "";
961
+ push(
962
+ "security/published-flow-trifecta", fl.file, lineOf(name), `published trifecta ${name}`,
963
+ `${info.name} is published over A2A, so what an outside caller sends reaches ${name}, which holds ${l.privateLeg.slice(0, 3).join(", ")}${l.privateLeg.length > 3 ? ", …" : ""}${out} — ` +
964
+ `and the flow's answer goes back to that caller, so a caller can ask for what it holds. Give ${name} only what a stranger may see, or do not publish the flow`,
965
+ );
966
+ }
967
+ for (const e of flowSecretCode(tree, info.name)) {
968
+ const held = `${e.secrets.slice(0, 3).join(", ")}${e.secrets.length > 3 ? ", …" : ""}`;
969
+ push(
970
+ "security/published-flow-secret-code", fl.file, lineOf(e.agent), `published secret-code ${e.agent}`,
971
+ e.accepted
972
+ ? `${e.agent} holds ${held} and can run code, and ${info.name} is published over A2A — accepted by an admin (a2a: accept_risk: [${e.agent}])`
973
+ : `${e.agent} holds ${held} and can run code (Bash), and ${info.name} is published over A2A — its answer goes back to the outside caller, who can ask for the secret in it. ` +
974
+ `Take Bash or the secret away from ${e.agent}, or have an admin accept it (a2a: accept_risk: [${e.agent}]); until then the platform refuses new A2A tasks for ${info.name}`,
975
+ e.accepted ? "info" : undefined,
976
+ );
907
977
  }
908
978
  // Groups in order. A gate (an approval, or ask:, which is one with a
909
979
  // question) on any step of a group parks the run before ANY step of that
@@ -1237,6 +1307,7 @@ export function scanFiles(files: ScanFile[], options: ScanOptions = {}): ScanFin
1237
1307
  }
1238
1308
  const kind = docKind(f.path);
1239
1309
  if (!kind) continue;
1310
+ if (kind === "agent" || kind === "tool") scanSecretNames(f, data, lines, push);
1240
1311
  if (kind === "agent") {
1241
1312
  const rel = f.path.replace(/^library\//, "");
1242
1313
  const name = /^agents\/([^/]+)\//.exec(rel)?.[1] ?? rel.replace(/^.*\/|\.md$/g, "");
@@ -1252,7 +1323,7 @@ export function scanFiles(files: ScanFile[], options: ScanOptions = {}): ScanFin
1252
1323
  // project.md is the older name the runtime still reads (Codex review, FOL-58).
1253
1324
  const workspaceMd = files.find((f) => f.path === "AGENTS.md") ?? files.find((f) => f.path === "project.md");
1254
1325
  const legs = scanAgents(agents, outward, toolDefs, push, { account: options.accountNetwork, workspace: workspaceMd ? frontOf(workspaceMd.content, "AGENTS.md")?.network : undefined });
1255
- scanPublishedFlows(flows, legs, push);
1326
+ scanPublishedFlows(flows, legs, a2aTree(files.filter((f) => isText(f) && !RUNTIME_WRITTEN.test(f.path)), { accountNetwork: options.accountNetwork }), push);
1256
1327
  // A workspace that names its own provider: does not run on the account's
1257
1328
  // choice, so the account's models say nothing about its efforts.
1258
1329
  const ownWorkspaceProvider = Boolean(workspaceMd && frontOf(workspaceMd.content, "AGENTS.md")?.provider);
package/src/secrets.ts CHANGED
@@ -19,6 +19,7 @@
19
19
  // Secrets are injected as environment variables into the agent's tools at run
20
20
  // time and are never returned by the API.
21
21
 
22
+ import { opsLog, withOpsReason } from "./ops-log.ts";
22
23
  import fs from "node:fs";
23
24
  import path from "node:path";
24
25
  import { dataRoot } from "./paths.ts";
@@ -71,7 +72,7 @@ export function installKeyMaterial(): string {
71
72
  // so; without this, asking for it would quietly mint a NEW random key on
72
73
  // the shared data volume — a second root key nobody chose.
73
74
  if (process.env.FOLDRUN_INSTALL_KEY_ABSENT === "1") {
74
- throw new Error("this process runs without the install key (FOLDRUN_INSTALL_KEY_ABSENT=1) — whatever asked for it belongs in the worker");
75
+ throw withOpsReason(new Error("this process runs without the install key (FOLDRUN_INSTALL_KEY_ABSENT=1) — whatever asked for it belongs in the worker"), "install_key_absent");
75
76
  }
76
77
  fs.mkdirSync(dataRoot(), { recursive: true });
77
78
  if (!fs.existsSync(keyFile())) {
@@ -549,10 +550,8 @@ function decrypt(tenant: string, rec: StoredSecret | undefined, aad?: Buffer): s
549
550
  // "no such secret" — a process that forgot to load the account keys
550
551
  // would look exactly like an account that never set one, which is the
551
552
  // most expensive kind of wrong answer to debug.
552
- console.error(
553
- `[secrets] ${tenant} has account-keyed secrets but no key is loaded — ` +
554
- `call loadTenantKeys() before reading, or the value will read as absent`,
555
- );
553
+ // loadTenantKeys() was not called before reading: the value reads as absent.
554
+ opsLog("error", "secrets.account_key_not_loaded", { tenant });
556
555
  return null;
557
556
  }
558
557
  key = own;
package/src/starter.ts CHANGED
@@ -439,7 +439,7 @@ effort: low
439
439
  overlap: skip # skip | queue — what a second run does while one is live
440
440
  priority: normal # high | normal | low — where its runs stand in the queue
441
441
  compute: { vcpu: 4, memory: 8Gi, disk: 40Gi } # optional: what one run may hold at once
442
- a2a: { publish: false } # true: outside agents may call it over A2A (admin only; callers need an A2A key)
442
+ a2a: { publish: false } # true: outside agents may call it over A2A (admin only; callers need an A2A key; an agent with a secret and Bash needs accept_risk: [agent])
443
443
  ---
444
444
 
445
445
  1. [[researcher]] — Find three sources on {{topic}}.
package/src/step-exec.ts CHANGED
@@ -8,6 +8,7 @@
8
8
  // results. That is what lets the same function run somewhere the vault, the
9
9
  // library and the account do not exist.
10
10
 
11
+ import { opsError } from "./ops-log.ts";
11
12
  import { judgeVerdict, JUDGE_VERDICT_INSTRUCTION } from "./judge-verdict.ts";
12
13
  import { runHook, runToolCallHooks, matchesTool, hookLine, resolveHooks, type HookDef, type HookRecord } from "./hooks.ts";
13
14
  import fs from "node:fs";
@@ -1381,16 +1382,21 @@ function runVerify(
1381
1382
  * A model process's failure as a person should read it: one short line. The
1382
1383
  * SDK's error for a CLI that died carries the CLI's stderr, which can be KBs
1383
1384
  * of its minified bundle — internal prompt text included (FOL-107) — so that
1384
- * part goes to the server log, never to an eval result or a trace. An error
1385
- * that is already short (an API error the model answered) is kept as it is.
1385
+ * part goes neither to an eval result or a trace, nor to a hosted log
1386
+ * (FOL-121): there the log line is the failure's class and our frames. An
1387
+ * error that is already short (an API error the model answered) is kept as
1388
+ * it is.
1386
1389
  */
1387
1390
  export function modelProcessError(err: unknown, where: string): Error {
1388
1391
  const full = err instanceof Error ? err.message : String(err);
1389
1392
  const at = full.indexOf(" stderr:");
1390
1393
  if (at < 0 && full.length <= 500) return err instanceof Error ? err : new Error(full);
1391
- console.error(`[foldrun] ${where}: ${full}`);
1394
+ // Inside the hosted boundary this is the class, name and our frames only:
1395
+ // the stderr is the CLI's, and can carry the prompt (FOL-107, FOL-121).
1396
+ // On a laptop the full text comes along, for the person it belongs to.
1397
+ opsError("model.process_failed", err, { where: where.replace(/\W+/g, "_").toLowerCase(), errorClass: "model_error" });
1392
1398
  const head = (at >= 0 ? full.slice(0, at) : full.slice(0, 300)).trim().replace(/[.:]$/, "");
1393
- return new Error(`${head} — the model process failed; the details are in the server log`);
1399
+ return new Error(`${head} — the model process failed`);
1394
1400
  }
1395
1401
 
1396
1402
  export function sdkEnv(base: Record<string, string | undefined> | undefined, extra: Record<string, string> = {}): Record<string, string | undefined> {
package/src/storage.ts CHANGED
@@ -48,6 +48,7 @@
48
48
  // FOLDRUN_STORAGE_MAX_MB per object, default 512
49
49
  // FOLDRUN_STORAGE_QUOTA_MB per workspace, default 5120
50
50
 
51
+ import { opsError } from "./ops-log.ts";
51
52
  import fs from "node:fs";
52
53
  import path from "node:path";
53
54
  import crypto from "node:crypto";
@@ -686,7 +687,7 @@ async function announceFiles(tenant: string, workspace: string, paths: string[],
686
687
  const { fireStorageTriggers } = await import("./triggers.ts");
687
688
  await fireStorageTriggers(tenant, workspace, paths, by);
688
689
  } catch (err) {
689
- console.error(`[foldrun] storage trigger ${tenant}/${workspace}:`, err instanceof Error ? err.message : err);
690
+ opsError("trigger.storage_failed", err, { tenant, workspace });
690
691
  }
691
692
  }
692
693
 
package/src/store.ts CHANGED
@@ -53,6 +53,7 @@ import { checkFilter } from "./trigger-filter.ts";
53
53
  import { parseA2aPublish, type A2aPublication } from "./a2a-publish.ts";
54
54
  import { parseRemotes, remoteNetworkHosts, A2A_LIMIT_KEY, type RemoteSpec } from "./a2a-remotes.ts";
55
55
  import { parseBudget, budgetProblem } from "./budget.ts";
56
+ import { explainFailure, failureFactsOf, type FailureExplained, type FailureFacts } from "./failure.ts";
56
57
  import { timezoneProblem } from "./clock.ts";
57
58
  import { parseStepLimits, readLimits } from "./limits.ts";
58
59
  import { networkEnforceWanted, networkProblems, resolveNetwork, type NetworkPolicy } from "./network.ts";
@@ -3367,6 +3368,10 @@ export interface RunEvent {
3367
3368
  /** Set on a tool event a SUB-AGENT made (`subagents:`): its name. The
3368
3369
  * trace labels the call with it; cost stays the step's. */
3369
3370
  subagent?: string;
3371
+ /** Set on the error a platform security control wrote (failure.ts
3372
+ * securityStopEvent) — host-side only, never from a sandbox's output.
3373
+ * The customer is told the generic sentence and nothing else. */
3374
+ security?: true;
3370
3375
  /** Set on an error a failed check wrote — `verify:` (its headline and its
3371
3376
  * detail), `output: json`, a schema. What the runner reads to decline a
3372
3377
  * retry of an outward step whose tools already ran. */
@@ -3751,6 +3756,11 @@ export interface StepRecord {
3751
3756
  * #STARTUP_PHASES). Only the phases this step went through; null from
3752
3757
  * an executor that marks none, absent on steps from before 17 Oct 2026. */
3753
3758
  startup?: Record<string, number> | null;
3759
+ /** When the executor began the attempt those marks belong to — what they
3760
+ * count from, so a mark is an instant (FOL-122's run funnel). Set beside
3761
+ * `startup`; null where it is; absent before 5 Nov 2026, when readers
3762
+ * fall back to the attempt's own start, an estimate. */
3763
+ startupAt?: string | null;
3754
3764
  /** Which reservation class the sandbox held (small | large), and the
3755
3765
  * actual limits it held, as numbers. Facts of the step: a price is per
3756
3766
  * core-second, so what was reserved must come from the record, never
@@ -3758,6 +3768,10 @@ export interface StepRecord {
3758
3768
  * from before sizes existed — billing falls back to the flat rate. */
3759
3769
  size?: "small" | "large" | "heavy";
3760
3770
  reserved?: { cpus: number; memGiB: number; diskGiB?: number } | null;
3771
+ /** Only on a record rebuilt from the runs index (runFromSummary), for a
3772
+ * failed step: the figures and refused sites its failure message names,
3773
+ * which a full record carries in `reserved`, `actual` and its events. */
3774
+ failureFacts?: FailureFacts;
3761
3775
  /** The agent's `resources:` as applied (resources.ts), when it set any:
3762
3776
  * why `reserved` differs from the class's figures. Absent before 26 Oct
3763
3777
  * 2026 and on steps of an agent that wrote none. */
@@ -3988,16 +4002,22 @@ export function runFilePath(tenant: string, workspace: string, runId: string) {
3988
4002
  * the same append-only file the charge lives in. The balance is untouched;
3989
4003
  * the story is complete.
3990
4004
  */
3991
- export function deleteRun(tenant: string, workspace: string, runId: string): boolean {
4005
+ export function deleteRun(tenant: string, workspace: string, runId: string, opts: { pruned?: boolean } = {}): boolean {
3992
4006
  const file = runFilePath(tenant, workspace, runId);
3993
- if (!fs.existsSync(file)) return false;
4007
+ const dir = path.join(workspaceDir(tenant, workspace), "runs", runId);
4008
+ const had = fs.existsSync(file);
4009
+ if (!had && !fs.existsSync(dir)) return false;
4010
+ // The folder first (archived outputs, captured calls), the record last:
4011
+ // a delete that fails halfway leaves the record, so a retry finds the run
4012
+ // and finishes — the other order left the content with nothing pointing
4013
+ // at it (Codex review, FOL-124).
4014
+ fs.rmSync(dir, { recursive: true, force: true });
3994
4015
  fs.rmSync(file, { force: true });
3995
- fs.rmSync(path.join(workspaceDir(tenant, workspace), "runs", runId), {
3996
- recursive: true,
3997
- force: true,
3998
- });
3999
4016
  noteRunDeleted(path.dirname(file), runId);
4000
- onRunDeleted?.(tenant, workspace, runId);
4017
+ if (!had) return true;
4018
+ // The retention window's prune (`pruned`) is policy, not a person erasing
4019
+ // history: no per-run ledger note. The charge stands either way.
4020
+ if (!opts.pruned) onRunDeleted?.(tenant, workspace, runId);
4001
4021
  return true;
4002
4022
  }
4003
4023
 
@@ -4166,6 +4186,9 @@ export interface RunSummaryStep {
4166
4186
  skipReason?: string;
4167
4187
  /** The last error event, for a failed step — what runFailure reads. */
4168
4188
  error?: string;
4189
+ /** For a failed step: the figures and refused sites runFailure's message
4190
+ * names (failure.ts). Absent before 5 Nov 2026. */
4191
+ failureFacts?: FailureFacts;
4169
4192
  item?: string;
4170
4193
  waitFor?: "event";
4171
4194
  ask?: string;
@@ -4249,7 +4272,12 @@ export function summarizeRun(run: RunRecord): RunSummary {
4249
4272
  ...(run.a2a ? { a2a: run.a2a } : {}),
4250
4273
  awaitingApproval: run.steps.some((s) => s.status === "awaiting-approval" && s.waitFor !== "event"),
4251
4274
  steps: run.steps.map((s) => {
4252
- const error = s.status === "failed" ? s.events.filter((e) => e.type === "error").at(-1)?.text : undefined;
4275
+ // A failed step's last error — and, on a run that failed between
4276
+ // groups, the budget's error the runner wrote onto the step before
4277
+ // (runFailure reads it from there; FOL-124, Codex review).
4278
+ const last = s.events.filter((e) => e.type === "error").at(-1)?.text;
4279
+ const error = s.status === "failed" || (run.status === "failed" && last !== undefined && /^over budget/.test(last)) ? last : undefined;
4280
+ const failureFacts = s.status === "failed" ? failureFactsOf(s) : undefined;
4253
4281
  return {
4254
4282
  agent: s.agent,
4255
4283
  group: s.group,
@@ -4259,6 +4287,7 @@ export function summarizeRun(run: RunRecord): RunSummary {
4259
4287
  ...(s.computeSecs !== undefined ? { computeSecs: s.computeSecs } : {}),
4260
4288
  ...(s.skipReason ? { skipReason: s.skipReason } : {}),
4261
4289
  ...(error ? { error: error.slice(0, 500) } : {}),
4290
+ ...(failureFacts ? { failureFacts } : {}),
4262
4291
  ...(s.item ? { item: s.item } : {}),
4263
4292
  ...(s.waitFor ? { waitFor: s.waitFor } : {}),
4264
4293
  ...(s.ask ? { ask: s.ask } : {}),
@@ -4574,15 +4603,34 @@ export function runDurationSecs(run: RunRecord): number | null {
4574
4603
  * sentence — "failed" with no reason makes every diagnosis start by opening
4575
4604
  * the run, and the answer was sitting in the record all along.
4576
4605
  */
4577
- export function runFailure(run: RunRecord): { agent: string; reason: string } | null {
4606
+ export function runFailure(run: RunRecord): RunFailure | null {
4578
4607
  if (run.status !== "failed") return null;
4579
4608
  const step = run.steps.find((s) => s.status === "failed");
4580
- if (!step) return null;
4609
+ if (!step) {
4610
+ // A run can fail with no failed step: a budget hit or a stop between
4611
+ // groups writes its error onto the last step that ran (FOL-124).
4612
+ if (run.stopRequested) {
4613
+ const reason = `stopped by ${run.stoppedBy ?? "a person"}`;
4614
+ return { agent: run.steps.findLast((s) => s.status === "completed")?.agent ?? run.steps[0]?.agent ?? "run", reason, ...explainFailure(reason, null) };
4615
+ }
4616
+ const holder = run.steps.findLast((s) => s.events.some((e) => e.type === "error" && /^over budget/.test(e.text)));
4617
+ const text = holder?.events.filter((e) => e.type === "error" && /^over budget/.test(e.text)).at(-1)?.text;
4618
+ if (holder && text) return { agent: holder.agent, reason: text, ...explainFailure(text, null) };
4619
+ return null;
4620
+ }
4581
4621
  const errors = step.events.filter((e) => e.type === "error");
4582
4622
  const last = errors[errors.length - 1];
4583
- return { agent: step.agent, reason: last?.text ?? "failed without an error event" };
4623
+ const raw = last?.text ?? "failed without an error event";
4624
+ // The customer's sentence, its class and its fix (failure.ts, FOL-124).
4625
+ // A security stop's reason is that sentence too: nothing else is said.
4626
+ const explained = explainFailure(raw, step);
4627
+ return { agent: step.agent, reason: explained.kind === "security" ? explained.message : raw, ...explained };
4584
4628
  }
4585
4629
 
4630
+ /** Why a failed run failed: the step, its last error, and what that means
4631
+ * for the customer (failure.ts). */
4632
+ export type RunFailure = { agent: string; reason: string } & FailureExplained;
4633
+
4586
4634
  /**
4587
4635
  * The one-line outcome, pulled out of the reply that already says it.
4588
4636
  *
package/src/triggers.ts CHANGED
@@ -12,6 +12,7 @@
12
12
  // read that run's fields; it receives what the run concluded, as text, and
13
13
  // an agent reads it — the same rule as every other handoff in the format.
14
14
 
15
+ import { opsLog, opsError } from "./ops-log.ts";
15
16
  import crypto from "node:crypto";
16
17
  import { platform } from "./platform.ts";
17
18
  import { refusalCode } from "./trigger-log.ts";
@@ -93,7 +94,7 @@ export async function fireChainedFlows(tenant: string, workspace: string, finish
93
94
  try {
94
95
  const gate = await platform.admitTrigger(tenant, workspace, flow, { body, tag: "previous_run", fields: chainFields(finished) });
95
96
  if (!gate.admit) {
96
- console.log(`[foldrun] trigger: flow — ${tenant}/${workspace}/${flow.name} not started: ${gate.detail}`);
97
+ opsLog("info", "trigger.flow_not_started", { tenant, workspace, flow: flow.name, reason: gate.reason });
97
98
  continue;
98
99
  }
99
100
  try {
@@ -103,13 +104,13 @@ export async function fireChainedFlows(tenant: string, workspace: string, finish
103
104
  `after:${finished.flow}`,
104
105
  ], null, finished.test ? { test: true } : {});
105
106
  started.push(run.id);
106
- console.log(`[foldrun] trigger: flow — ${tenant}/${workspace}/${flow.name} started after ${finished.flow} ${finished.status}`);
107
+ opsLog("info", "trigger.flow_started", { tenant, workspace, flow: flow.name, runId: run.id, kind: "previous_run", outcome: finished.status });
107
108
  } catch (err) {
108
109
  await platform.rollbackTrigger(tenant, workspace, flow, { reason: err instanceof Error ? err.message : String(err), code: refusalCode(err) });
109
110
  throw err;
110
111
  }
111
112
  } catch (err) {
112
- console.error(`[foldrun] trigger: flow — ${tenant}/${workspace}/${flow.name}:`, err instanceof Error ? err.message : err);
113
+ opsError("trigger.flow_failed", err, { tenant, workspace, flow: flow.name });
113
114
  }
114
115
  }
115
116
  return started;
@@ -158,7 +159,7 @@ export async function fireStorageTriggers(
158
159
  // forty runs — which is exactly what `debounce:` is for.
159
160
  const gate = await platform.admitTrigger(tenant, workspace, flow, { body, tag: "storage_event", fields: { by, paths: hits } });
160
161
  if (!gate.admit) {
161
- console.log(`[foldrun] trigger: storage — ${tenant}/${workspace}/${flow.name} not started: ${gate.detail}`);
162
+ opsLog("info", "trigger.storage_not_started", { tenant, workspace, flow: flow.name, reason: gate.reason });
162
163
  continue;
163
164
  }
164
165
  try {
@@ -171,7 +172,7 @@ export async function fireStorageTriggers(
171
172
  throw err;
172
173
  }
173
174
  } catch (err) {
174
- console.error(`[foldrun] trigger: storage — ${tenant}/${workspace}/${flow.name}:`, err instanceof Error ? err.message : err);
175
+ opsError("trigger.storage_failed", err, { tenant, workspace, flow: flow.name });
175
176
  }
176
177
  }
177
178
  return started;
package/src/webhook.ts CHANGED
@@ -2,6 +2,7 @@
2
2
  // identity under the install's secret key. Stable across restarts, unique
3
3
  // per flow, and rotating FOLDRUN_SECRET_KEY invalidates every hook at once.
4
4
 
5
+ import { opsLog } from "./ops-log.ts";
5
6
  import fs from "node:fs";
6
7
  import path from "node:path";
7
8
  import { workspaceDir } from "./store.ts";
@@ -225,8 +226,8 @@ function noteRefusal(tenant: string, workspace: string, delivery: HookDelivery)
225
226
  seen.since++;
226
227
  return;
227
228
  }
228
- const more = seen?.since ? ` (and ${seen.since} more since the last note)` : "";
229
- console.warn(`[hooks] refused a delivery to ${key}/${delivery.flow}: ${delivery.outcome}${more}`);
229
+ // count: this one and those refused since the last note.
230
+ opsLog("warn", "webhook.delivery_refused", { tenant, workspace, flow: delivery.flow, outcome: delivery.outcome, count: (seen?.since ?? 0) + 1 });
230
231
  refusalNotes.set(key, { at: now, since: 0 });
231
232
  if (refusalNotes.size > 10_000) refusalNotes.clear(); // bounded: a note lost beats memory
232
233
  }