agenttwin 0.3.32 → 0.3.34

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 (119) hide show
  1. package/dist/api.js +14217 -2453
  2. package/dist/dashboard/assets/next/static/chunks/{1937-6c86fddc443de922.js → 1937-2369d8ef2eae7700.js} +1 -1
  3. package/dist/dashboard/assets/next/static/chunks/app/_not-found/{page-5d1ba67144da5868.js → page-b60a5aad66f3bf1d.js} +1 -1
  4. package/dist/dashboard/assets/next/static/chunks/app/about/page-a30c6925cc9ac983.js +1 -0
  5. package/dist/dashboard/assets/next/static/chunks/app/account/password/page-0478a7f18cc5e31b.js +1 -0
  6. package/dist/dashboard/assets/next/static/chunks/app/api-policy/page-91ad6c5e4226778f.js +1 -0
  7. package/dist/dashboard/assets/next/static/chunks/app/auth/page-91ad6c5e4226778f.js +1 -0
  8. package/dist/dashboard/assets/next/static/chunks/app/blog/agenttwin-vs-mockoon/page-46b9ffc514b56c84.js +1 -0
  9. package/dist/dashboard/assets/next/static/chunks/app/blog/agenttwin-vs-pact/page-46b9ffc514b56c84.js +1 -0
  10. package/dist/dashboard/assets/next/static/chunks/app/blog/agenttwin-vs-testcontainers/page-46b9ffc514b56c84.js +1 -0
  11. package/dist/dashboard/assets/next/static/chunks/app/blog/agenttwin-vs-wiremock/page-46b9ffc514b56c84.js +1 -0
  12. package/dist/dashboard/assets/next/static/chunks/app/blog/choose-first-agent-workflow-test/page-46b9ffc514b56c84.js +1 -0
  13. package/dist/dashboard/assets/next/static/chunks/app/blog/clean-baseline-before-fault-injection/page-46b9ffc514b56c84.js +1 -0
  14. package/dist/dashboard/assets/next/static/chunks/app/blog/idempotency-keys-and-safe-retries/page-46b9ffc514b56c84.js +1 -0
  15. package/dist/dashboard/assets/next/static/chunks/app/blog/keep-real-service-tests-with-digital-twins/page-46b9ffc514b56c84.js +1 -0
  16. package/dist/dashboard/assets/next/static/chunks/app/blog/keploy-alternatives-for-database-and-payment-workflows/page-46b9ffc514b56c84.js +1 -0
  17. package/dist/dashboard/assets/next/static/chunks/app/blog/layout-6c159db381b82832.js +1 -0
  18. package/dist/dashboard/assets/next/static/chunks/app/blog/page-46b9ffc514b56c84.js +1 -0
  19. package/dist/dashboard/assets/next/static/chunks/app/blog/read-workflow-test-receipts/page-46b9ffc514b56c84.js +1 -0
  20. package/dist/dashboard/assets/next/static/chunks/app/blog/reset-test-environment-between-runs/page-46b9ffc514b56c84.js +1 -0
  21. package/dist/dashboard/assets/next/static/chunks/app/blog/simulate-timeouts-and-duplicate-events/page-46b9ffc514b56c84.js +1 -0
  22. package/dist/dashboard/assets/next/static/chunks/app/blog/test-boundaries-for-ai-agents/page-46b9ffc514b56c84.js +1 -0
  23. package/dist/dashboard/assets/next/static/chunks/app/blog/timeout-retry-double-charge/page-46b9ffc514b56c84.js +1 -0
  24. package/dist/dashboard/assets/next/static/chunks/app/blog/we-ran-50-real-incidents-through-agenttwin/page-46b9ffc514b56c84.js +1 -0
  25. package/dist/dashboard/assets/next/static/chunks/app/blog/why-ai-agents-delete-production-databases/page-46b9ffc514b56c84.js +1 -0
  26. package/dist/dashboard/assets/next/static/chunks/app/blog/workflow-testing-evaluation-checklist/page-46b9ffc514b56c84.js +1 -0
  27. package/dist/dashboard/assets/next/static/chunks/app/blog/write-better-workflow-assertions/page-46b9ffc514b56c84.js +1 -0
  28. package/dist/dashboard/assets/next/static/chunks/app/compare/page-91ad6c5e4226778f.js +1 -0
  29. package/dist/dashboard/assets/next/static/chunks/app/contact/page-91ad6c5e4226778f.js +1 -0
  30. package/dist/dashboard/assets/next/static/chunks/app/dashboard/layout-0050f308b9f77c24.js +1 -0
  31. package/dist/dashboard/assets/next/static/chunks/app/dashboard/page-6245aa3ad5d7f527.js +1 -0
  32. package/dist/dashboard/assets/next/static/chunks/app/demo/{page-ef75632088a6ea0b.js → page-ac6e235c635cb130.js} +1 -1
  33. package/dist/dashboard/assets/next/static/chunks/app/developers/page-91ad6c5e4226778f.js +1 -0
  34. package/dist/dashboard/assets/next/static/chunks/app/docs/[[...slug]]/page-5afd0649dd30ef88.js +1 -0
  35. package/dist/dashboard/assets/next/static/chunks/app/dpa/page-91ad6c5e4226778f.js +1 -0
  36. package/dist/dashboard/assets/next/static/chunks/app/enterprise/{page-91c6176f28dfdccd.js → page-11514cc52285b7f3.js} +1 -1
  37. package/dist/dashboard/assets/next/static/chunks/app/guides/page-91ad6c5e4226778f.js +1 -0
  38. package/dist/dashboard/assets/next/static/chunks/app/{layout-be64d3e50db4b7a9.js → layout-8aa153f632f0aa20.js} +1 -1
  39. package/dist/dashboard/assets/next/static/chunks/app/login/page-99ebb4d265222728.js +1 -0
  40. package/dist/dashboard/assets/next/static/chunks/app/not-found-91ad6c5e4226778f.js +1 -0
  41. package/dist/dashboard/assets/next/static/chunks/app/onboarding/page-9e59af0296c9366b.js +1 -0
  42. package/dist/dashboard/assets/next/static/chunks/app/{page-ede77810f4904ea5.js → page-76277dc68b6a22bd.js} +1 -1
  43. package/dist/dashboard/assets/next/static/chunks/app/{blog/layout-b095a34d742bd1fd.js → pricing/page-c7015af858f4db8e.js} +1 -1
  44. package/dist/dashboard/assets/next/static/chunks/app/privacy/page-91ad6c5e4226778f.js +1 -0
  45. package/dist/dashboard/assets/next/static/chunks/app/sandbox/page-91ad6c5e4226778f.js +1 -0
  46. package/dist/dashboard/assets/next/static/chunks/app/scoreboard/page-91ad6c5e4226778f.js +1 -0
  47. package/dist/dashboard/assets/next/static/chunks/app/security/page-91ad6c5e4226778f.js +1 -0
  48. package/dist/dashboard/assets/next/static/chunks/app/signup/page-99ebb4d265222728.js +1 -0
  49. package/dist/dashboard/assets/next/static/chunks/app/sitemap.xml/route-46b9ffc514b56c84.js +1 -0
  50. package/dist/dashboard/assets/next/static/chunks/app/status/{page-569ae36bd08d867c.js → page-fd41c4e7838d9949.js} +1 -1
  51. package/dist/dashboard/assets/next/static/chunks/app/subprocessors/page-91ad6c5e4226778f.js +1 -0
  52. package/dist/dashboard/assets/next/static/chunks/app/terms/page-91ad6c5e4226778f.js +1 -0
  53. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/{layout-b92ad482b0164f93.js → layout-a79d128eb3b0b7d2.js} +1 -1
  54. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/page-a9fa05c9ae5c24dc.js +1 -0
  55. package/dist/dashboard/assets/next/static/chunks/app/v2/layout-2e97381ae7a59ba0.js +1 -0
  56. package/dist/dashboard/assets/next/static/chunks/app/v2/login/page-57afbac97afd31fa.js +1 -0
  57. package/dist/dashboard/assets/next/static/chunks/app/v2/onboarding/{page-79cd80f87d39230d.js → page-7c08d2c43f0be9d5.js} +1 -1
  58. package/dist/dashboard/assets/next/static/chunks/app/v2/page-35998431fb40a9c9.js +1 -0
  59. package/dist/dashboard/assets/next/static/chunks/app/v2/signup/page-57afbac97afd31fa.js +1 -0
  60. package/dist/dashboard/assets/next/static/chunks/app/what-is-agenttwin/page-91ad6c5e4226778f.js +1 -0
  61. package/dist/dashboard/assets/next/static/chunks/{main-app-b4faf61f2e1c2b6d.js → main-app-4051d8ba998bea15.js} +1 -1
  62. package/dist/dashboard/assets/next/static/chunks/{webpack-53525dd96c1c1e70.js → webpack-57e0c1e343bdc899.js} +1 -1
  63. package/dist/dashboard/assets/next/static/p_5KE1JZcErklSND_EYv3/_buildManifest.js +1 -0
  64. package/dist/dashboard/index.html +2 -2
  65. package/dist/engine.js +1358 -565
  66. package/dist/gateway.js +14235 -2467
  67. package/dist/twins/catalog.json +113 -113
  68. package/dist/twins/packs/stripe/index.mjs +8 -8
  69. package/dist/worker.js +97 -20
  70. package/dist/world-host.js +140 -26
  71. package/package.json +1 -1
  72. package/dist/dashboard/assets/next/static/chunks/app/about/page-b09a2d8452522c20.js +0 -1
  73. package/dist/dashboard/assets/next/static/chunks/app/account/password/page-b9ca284314cace59.js +0 -1
  74. package/dist/dashboard/assets/next/static/chunks/app/api-policy/page-94d508052ae30dcb.js +0 -1
  75. package/dist/dashboard/assets/next/static/chunks/app/auth/page-94d508052ae30dcb.js +0 -1
  76. package/dist/dashboard/assets/next/static/chunks/app/blog/agenttwin-vs-mockoon/page-11a5fdc2662ff51d.js +0 -1
  77. package/dist/dashboard/assets/next/static/chunks/app/blog/agenttwin-vs-pact/page-11a5fdc2662ff51d.js +0 -1
  78. package/dist/dashboard/assets/next/static/chunks/app/blog/agenttwin-vs-testcontainers/page-11a5fdc2662ff51d.js +0 -1
  79. package/dist/dashboard/assets/next/static/chunks/app/blog/agenttwin-vs-wiremock/page-11a5fdc2662ff51d.js +0 -1
  80. package/dist/dashboard/assets/next/static/chunks/app/blog/choose-first-agent-workflow-test/page-11a5fdc2662ff51d.js +0 -1
  81. package/dist/dashboard/assets/next/static/chunks/app/blog/clean-baseline-before-fault-injection/page-11a5fdc2662ff51d.js +0 -1
  82. package/dist/dashboard/assets/next/static/chunks/app/blog/idempotency-keys-and-safe-retries/page-11a5fdc2662ff51d.js +0 -1
  83. package/dist/dashboard/assets/next/static/chunks/app/blog/keep-real-service-tests-with-digital-twins/page-11a5fdc2662ff51d.js +0 -1
  84. package/dist/dashboard/assets/next/static/chunks/app/blog/keploy-alternatives-for-database-and-payment-workflows/page-11a5fdc2662ff51d.js +0 -1
  85. package/dist/dashboard/assets/next/static/chunks/app/blog/page-11a5fdc2662ff51d.js +0 -1
  86. package/dist/dashboard/assets/next/static/chunks/app/blog/read-workflow-test-receipts/page-11a5fdc2662ff51d.js +0 -1
  87. package/dist/dashboard/assets/next/static/chunks/app/blog/reset-test-environment-between-runs/page-11a5fdc2662ff51d.js +0 -1
  88. package/dist/dashboard/assets/next/static/chunks/app/blog/simulate-timeouts-and-duplicate-events/page-11a5fdc2662ff51d.js +0 -1
  89. package/dist/dashboard/assets/next/static/chunks/app/blog/test-boundaries-for-ai-agents/page-11a5fdc2662ff51d.js +0 -1
  90. package/dist/dashboard/assets/next/static/chunks/app/blog/workflow-testing-evaluation-checklist/page-11a5fdc2662ff51d.js +0 -1
  91. package/dist/dashboard/assets/next/static/chunks/app/blog/write-better-workflow-assertions/page-11a5fdc2662ff51d.js +0 -1
  92. package/dist/dashboard/assets/next/static/chunks/app/compare/page-94d508052ae30dcb.js +0 -1
  93. package/dist/dashboard/assets/next/static/chunks/app/contact/page-94d508052ae30dcb.js +0 -1
  94. package/dist/dashboard/assets/next/static/chunks/app/dashboard/layout-820e83f47c1bfe08.js +0 -1
  95. package/dist/dashboard/assets/next/static/chunks/app/dashboard/page-8b436163bc85e182.js +0 -1
  96. package/dist/dashboard/assets/next/static/chunks/app/developers/page-94d508052ae30dcb.js +0 -1
  97. package/dist/dashboard/assets/next/static/chunks/app/docs/[[...slug]]/page-c25a8cab5ab065c4.js +0 -1
  98. package/dist/dashboard/assets/next/static/chunks/app/dpa/page-94d508052ae30dcb.js +0 -1
  99. package/dist/dashboard/assets/next/static/chunks/app/guides/page-94d508052ae30dcb.js +0 -1
  100. package/dist/dashboard/assets/next/static/chunks/app/login/page-7ee25051f2743d68.js +0 -1
  101. package/dist/dashboard/assets/next/static/chunks/app/not-found-94d508052ae30dcb.js +0 -1
  102. package/dist/dashboard/assets/next/static/chunks/app/onboarding/page-26b963fb1dc02cc7.js +0 -1
  103. package/dist/dashboard/assets/next/static/chunks/app/pricing/page-535834810dc4bee1.js +0 -1
  104. package/dist/dashboard/assets/next/static/chunks/app/privacy/page-94d508052ae30dcb.js +0 -1
  105. package/dist/dashboard/assets/next/static/chunks/app/sandbox/page-94d508052ae30dcb.js +0 -1
  106. package/dist/dashboard/assets/next/static/chunks/app/scoreboard/page-94d508052ae30dcb.js +0 -1
  107. package/dist/dashboard/assets/next/static/chunks/app/security/page-94d508052ae30dcb.js +0 -1
  108. package/dist/dashboard/assets/next/static/chunks/app/signup/page-7ee25051f2743d68.js +0 -1
  109. package/dist/dashboard/assets/next/static/chunks/app/sitemap.xml/route-11a5fdc2662ff51d.js +0 -1
  110. package/dist/dashboard/assets/next/static/chunks/app/subprocessors/page-94d508052ae30dcb.js +0 -1
  111. package/dist/dashboard/assets/next/static/chunks/app/terms/page-94d508052ae30dcb.js +0 -1
  112. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/page-b1341267b2478360.js +0 -1
  113. package/dist/dashboard/assets/next/static/chunks/app/v2/layout-edb84faba63372b4.js +0 -1
  114. package/dist/dashboard/assets/next/static/chunks/app/v2/login/page-bfbe86a28adc6d30.js +0 -1
  115. package/dist/dashboard/assets/next/static/chunks/app/v2/page-1391f1ae01a91dc0.js +0 -1
  116. package/dist/dashboard/assets/next/static/chunks/app/v2/signup/page-bfbe86a28adc6d30.js +0 -1
  117. package/dist/dashboard/assets/next/static/chunks/app/what-is-agenttwin/page-94d508052ae30dcb.js +0 -1
  118. package/dist/dashboard/assets/next/static/dQPcd2gl7ABZiL9lr9ruM/_buildManifest.js +0 -1
  119. /package/dist/dashboard/assets/next/static/{dQPcd2gl7ABZiL9lr9ruM → p_5KE1JZcErklSND_EYv3}/_ssgManifest.js +0 -0
package/dist/engine.js CHANGED
@@ -290,7 +290,7 @@ var init_package = __esm({
290
290
  "package.json"() {
291
291
  package_default = {
292
292
  name: "agenttwin",
293
- version: "0.3.32",
293
+ version: "0.3.34",
294
294
  description: "AgentTwin builds digital twins for testing AI agents. The current CLI prepares supported Node.js workflows with synthetic services, failures, and outcome checks.",
295
295
  mcpName: "io.github.AgentTwin/agenttwin",
296
296
  keywords: [
@@ -619,14 +619,14 @@ import { execFile as execFile2 } from "child_process";
619
619
  import { promisify } from "util";
620
620
  async function captureGit(cwd, previousHead) {
621
621
  const exec11 = promisify(execFile2);
622
- const git2 = async (...args) => (await exec11("git", args, { cwd, timeout: 5e3, maxBuffer: 1024 * 1024 })).stdout.trim();
622
+ const git3 = async (...args) => (await exec11("git", args, { cwd, timeout: 5e3, maxBuffer: 1024 * 1024 })).stdout.trim();
623
623
  try {
624
- const head = await git2("rev-parse", "HEAD");
625
- const [branch, total, status, history] = await Promise.all([git2("branch", "--show-current"), git2("rev-list", "--count", "HEAD"), git2("status", "--porcelain", "--untracked-files=no"), git2("log", "--since=14 days ago", "-100", "--format=%H %cI")]);
626
- let changed = await git2("diff", "--name-only", "HEAD");
624
+ const head = await git3("rev-parse", "HEAD");
625
+ const [branch, total, status, history] = await Promise.all([git3("branch", "--show-current"), git3("rev-list", "--count", "HEAD"), git3("status", "--porcelain", "--untracked-files=no"), git3("log", "--since=14 days ago", "-100", "--format=%H %cI")]);
626
+ let changed = await git3("diff", "--name-only", "HEAD");
627
627
  if (previousHead && /^[a-f0-9]{40,64}$/.test(previousHead) && previousHead !== head) {
628
628
  try {
629
- changed += "\n" + await git2("diff", "--name-only", previousHead, head);
629
+ changed += "\n" + await git3("diff", "--name-only", previousHead, head);
630
630
  } catch {
631
631
  previousHead = void 0;
632
632
  }
@@ -2454,6 +2454,7 @@ function parseWorld(value3) {
2454
2454
  if (v.applicationClock !== void 0 && !validApplicationClock(v.applicationClock)) invalid("applicationClock requires only now as a canonical UTC timestamp with milliseconds");
2455
2455
  if (!Array.isArray(v.services) || !v.services.length || v.services.length > 10) invalid("services must contain 1\u201310 HTTP services");
2456
2456
  const services = /* @__PURE__ */ new Map();
2457
+ const requestPathFaults = /* @__PURE__ */ new Set();
2457
2458
  for (const service of v.services) {
2458
2459
  if (!object(service) || typeof service.name !== "string" || !namePattern.test(service.name) || services.has(service.name)) invalid("service names must be unique lowercase identifiers");
2459
2460
  const item = service;
@@ -2472,6 +2473,7 @@ function parseWorld(value3) {
2472
2473
  if (item.account !== void 0 && (!isPackAdapter(item.adapter) || !object(item.account) || Object.keys(item.account).length > 10 || !Object.entries(item.account).every(([k, val]) => /^_?[a-z][a-z0-9_]{0,40}$/.test(k) && ["string", "number", "boolean"].includes(typeof val) && String(val).length <= 200))) invalid("account is for twin packs only: up to 10 simple fields with string, number or boolean values");
2473
2474
  if (item.doorRecords !== void 0 && (!isPackAdapter(item.adapter) || !Array.isArray(item.doorRecords) || item.doorRecords.length > 5 || !item.doorRecords.every((r) => object(r) && typeof r.type === "string" && /^[a-z][a-z0-9_]{0,40}$/.test(r.type) && typeof r.id === "string" && /^[A-Za-z0-9_.:-]{1,80}$/.test(r.id) && object(r.fields) && JSON.stringify(r.fields).length <= 2e4))) invalid("doorRecords is for twin packs only: up to 5 records with a type, an id and their fields");
2474
2475
  services.set(item.name, /* @__PURE__ */ new Set([...paths, ...optional]));
2476
+ if (typeof item.adapter === "string" && ADAPTER_COLLECTIONS[item.adapter] && !["stripe", "slack", "json-collection"].includes(item.adapter)) requestPathFaults.add(item.name);
2475
2477
  }
2476
2478
  const known2 = (entry) => typeof entry.service === "string" && typeof entry.path === "string" && services.get(entry.service)?.has(entry.path);
2477
2479
  if (!Array.isArray(v.assertions) || !v.assertions.length || v.assertions.length > 100) invalid("at least one final-state assertion is required (maximum 100)");
@@ -2517,7 +2519,7 @@ function parseWorld(value3) {
2517
2519
  }
2518
2520
  }
2519
2521
  if (v.fault !== void 0) {
2520
- if (!object(v.fault) || !known2(v.fault) || !FAULT_TYPES.includes(v.fault.type)) invalid("fault requires an existing service/path and a supported type: timeout-after-write, blackhole, server-error, duplicate-write or slow-response");
2522
+ if (!object(v.fault) || !(known2(v.fault) || requestPathFaults.has(String(v.fault.service)) && typeof v.fault.path === "string" && /^\/[a-zA-Z0-9_.:/-]+$/.test(v.fault.path) && !v.fault.path.includes("//")) || !FAULT_TYPES.includes(v.fault.type)) invalid("fault requires an existing service/path and a supported type: timeout-after-write, blackhole, server-error, duplicate-write or slow-response");
2521
2523
  const f = v.fault;
2522
2524
  const allowed = ["service", "path", "type"];
2523
2525
  const count = f.count, windowMs = f.windowMs;
@@ -2965,6 +2967,368 @@ var init_run_summary = __esm({
2965
2967
  }
2966
2968
  });
2967
2969
 
2970
+ // src/runtime/generic-calls.ts
2971
+ import { createHash as createHash5 } from "crypto";
2972
+ function canonical2(value3) {
2973
+ return Array.isArray(value3) ? `[${value3.map(canonical2).join(",")}]` : value3 && typeof value3 === "object" ? `{${Object.keys(value3).sort().map((k) => `${JSON.stringify(k)}:${canonical2(value3[k])}`).join(",")}}` : JSON.stringify(value3 ?? null);
2974
+ }
2975
+ function resourceOf2(method, path2) {
2976
+ const segments = path2.split("?")[0].split("/").filter(Boolean).map((s) => {
2977
+ try {
2978
+ return decodeURIComponent(s);
2979
+ } catch {
2980
+ return s;
2981
+ }
2982
+ });
2983
+ let resourceId2;
2984
+ const template = segments.map((s, i) => {
2985
+ const last = i === segments.length - 1, byMethod = last && ["PUT", "PATCH", "DELETE"].includes(method) && segments.length > 1;
2986
+ if (idLike(s) || byMethod) {
2987
+ if (last || !resourceId2 || idLike(s)) resourceId2 = s;
2988
+ return "{id}";
2989
+ }
2990
+ return s;
2991
+ });
2992
+ return { resourcePath: "/" + template.join("/"), ...resourceId2 ? { resourceId: resourceId2 } : {} };
2993
+ }
2994
+ function keyFrom(headers, body) {
2995
+ for (const name of KEY_HEADERS) {
2996
+ const v = headers?.[name];
2997
+ if (typeof v === "string" && v) return digest(v);
2998
+ }
2999
+ if (body && typeof body === "object") {
3000
+ for (const [k, v] of Object.entries(body)) if (KEY_FIELDS.test(k) && typeof v === "string" && v) return digest(v);
3001
+ }
3002
+ }
3003
+ function normalizeCall(raw) {
3004
+ const method = raw.method.toUpperCase(), path2 = raw.path.split("?")[0] || "/", { resourcePath, resourceId: resourceId2 } = resourceOf2(method, path2);
3005
+ const graphqlRead = /graphql/i.test(path2) && typeof raw.body?.query === "string" && !/^\s*mutation\b/.test(raw.body.query);
3006
+ const isWrite = WRITE_METHODS.has(method) && !READ_LIKE.test(path2) && !MODEL_HOST.test(raw.host) && !String(raw.service ?? "").startsWith("model:") && !graphqlRead;
3007
+ const outcome2 = raw.outcome ?? outcomeOf(raw.status), key3 = keyFrom(raw.headers, raw.body), source = parseSource(raw.source);
3008
+ return {
3009
+ sequence: raw.sequence,
3010
+ service: raw.service ?? raw.host,
3011
+ host: raw.host,
3012
+ method,
3013
+ path: path2,
3014
+ resourcePath,
3015
+ ...method === "POST" && raw.createdId ? { resourceId: raw.createdId } : resourceId2 ? { resourceId: resourceId2 } : {},
3016
+ isWrite,
3017
+ ...key3 ? { idempotencyKey: key3 } : {},
3018
+ ...raw.body !== void 0 ? { requestDigest: digest(stable(raw.body)), body: raw.body } : {},
3019
+ ...raw.response !== void 0 ? { responseDigest: digest(stable(raw.response)) } : {},
3020
+ outcome: outcome2,
3021
+ ...raw.status !== void 0 ? { status: raw.status } : {},
3022
+ committed: raw.committed ?? (isWrite ? outcome2 === "ok" : void 0),
3023
+ ...raw.duplicated ? { duplicated: true } : {},
3024
+ ...raw.retryAfterMs !== void 0 ? { retryAfterMs: raw.retryAfterMs } : {},
3025
+ ...raw.at !== void 0 ? { at: raw.at } : {},
3026
+ ...source ? { source } : {},
3027
+ ...raw.tier ? { tier: raw.tier } : {}
3028
+ };
3029
+ }
3030
+ function callsFromWorldEvents(events, tierOf = () => void 0) {
3031
+ const calls = [], seen = /* @__PURE__ */ new Set();
3032
+ const last = (service) => [...calls].reverse().find((c) => c.service === service && c.isWrite);
3033
+ for (const e of events) {
3034
+ const tier = tierOf(e.service), key3 = e.idempotencyKey;
3035
+ const base = (method, path2, extra) => normalizeCall({ sequence: e.sequence, host: e.service, service: e.service, method, path: path2, ...tier ? { tier } : {}, ...e.source ? { source: e.source } : {}, ...extra });
3036
+ const withKey = (c) => key3 ? { ...c, idempotencyKey: key3 } : c;
3037
+ if (e.operation === "write") {
3038
+ const id2 = e.record?.id === void 0 ? void 0 : String(e.record.id), path2 = e.path, recordKey = `${e.service}${path2}:${id2}`;
3039
+ const method = /^(POST|PUT|PATCH|DELETE)\b/.exec(e.detail)?.[1] ?? (id2 && seen.has(recordKey) ? "PATCH" : "POST");
3040
+ if (id2) seen.add(recordKey);
3041
+ const c = base(method, method === "POST" ? path2 : `${path2}/${id2 ?? ""}`, { body: e.record, committed: true, ...id2 ? { createdId: id2 } : {} });
3042
+ calls.push(withKey({ ...c, resourcePath: resourceOf2("GET", path2).resourcePath, ...id2 ? { resourceId: id2 } : {} }));
3043
+ } else if (e.operation === "replay") calls.push(withKey(base("POST", e.path, { outcome: "replayed", committed: false })));
3044
+ else if (e.operation === "auth-denied") calls.push(base("POST", e.path.split("?")[0], { outcome: "unauthorized", committed: false }));
3045
+ else if (e.operation === "fault") {
3046
+ const prior = last(e.service), method = /\((POST|PUT|PATCH|DELETE|GET)\)\s*$/.exec(e.detail)?.[1];
3047
+ if (/^write committed|^slow-response: write/.test(e.detail) && prior) {
3048
+ prior.outcome = "timeout";
3049
+ prior.committed = true;
3050
+ } else if (/^duplicate-write: (one write committed as two|a single write was delivered twice)/.test(e.detail) && prior) prior.duplicated = true;
3051
+ else if (/^server-error/.test(e.detail)) calls.push(withKey(base(method ?? "POST", e.path, { outcome: "server-error", committed: false })));
3052
+ else if (/^blackhole/.test(e.detail)) calls.push(withKey(base(method ?? "POST", e.path, { outcome: "timeout", committed: false })));
3053
+ }
3054
+ }
3055
+ return calls;
3056
+ }
3057
+ function textOf(body, depth = 0) {
3058
+ if (!body || typeof body !== "object" || depth > 3) return "";
3059
+ return Object.entries(body).map(([k, v]) => typeof v === "string" && TEXT_FIELDS.test(k) ? v : v && typeof v === "object" ? textOf(v, depth + 1) : "").filter(Boolean).join(" ").trim();
3060
+ }
3061
+ function recipientsOf(body, depth = 0) {
3062
+ if (!body || typeof body !== "object" || depth > 3) return [];
3063
+ return Object.entries(body).flatMap(([k, v]) => RECIPIENT.test(k) ? (Array.isArray(v) ? v : [v]).filter((x) => typeof x === "string" && !!x) : v && typeof v === "object" ? recipientsOf(v, depth + 1) : []);
3064
+ }
3065
+ function claimsOf(calls, output = []) {
3066
+ const claims = calls.filter(isAnnouncement).map((c) => {
3067
+ const text3 = textOf(c.body);
3068
+ return { sequence: c.sequence, text: text3, polarity: polarityOf(text3), via: c.sequence, ...c.source ? { source: c.source } : {} };
3069
+ });
3070
+ const end = Math.max(0, ...calls.map((c) => c.sequence)) + 1;
3071
+ output.map((t) => t.trim()).filter(Boolean).slice(0, 50).forEach((text3, i) => claims.push({ sequence: end + i, text: text3.slice(0, 500), polarity: polarityOf(text3) }));
3072
+ return claims;
3073
+ }
3074
+ function moneyOf(body, depth = 0) {
3075
+ if (!body || typeof body !== "object" || depth > 3) return;
3076
+ const row = body, currency = Object.entries(row).find(([k, v]) => /^currency(_code)?$/i.test(k) && typeof v === "string" && /^[a-z]{3}$/i.test(v))?.[1];
3077
+ for (const [k, v] of Object.entries(row)) {
3078
+ const n = typeof v === "number" ? v : typeof v === "string" && /^\d+(\.\d+)?$/.test(v) ? Number(v) : NaN;
3079
+ if (AMOUNT.test(k) && Number.isFinite(n) && n > 0 && currency) return { amount: /cents|minor/i.test(k) ? n / 100 : n, currency: currency.toUpperCase() };
3080
+ }
3081
+ for (const v of Object.values(row)) {
3082
+ const nested = v && typeof v === "object" ? moneyOf(v, depth + 1) : void 0;
3083
+ if (nested) return nested;
3084
+ }
3085
+ }
3086
+ function impactOf(calls, extra, fallback, hint) {
3087
+ const money2 = calls.map((c) => moneyOf(c.body)).find(Boolean), recipients = [...new Set(calls.flatMap((c) => recipientsOf(c.body)))];
3088
+ if (money2 && extra > 0) return { kind: "money", amount: money2.amount * extra, currency: money2.currency, count: extra, summary: `${formatMoney({ amount: money2.amount * extra, currency: money2.currency })} moved more than intended (${formatMoney(money2)} each)` };
3089
+ const messaging = calls.some((c) => MESSAGING.test(c.path.split("?")[0]));
3090
+ if (recipients.length && extra > 0 && !messaging) {
3091
+ const noun = (calls[0]?.path.split("?")[0].split("/").filter(Boolean).pop() ?? "record").replace(/\.json$/, "").replace(/ies$/, "y").replace(/s$/, "");
3092
+ return { kind: "data-integrity", recipients, count: extra, summary: `${extra + 1} ${noun} records would exist for ${recipients[0]} instead of 1` };
3093
+ }
3094
+ if (recipients.length && (extra > 0 && messaging || fallback === "customer-facing")) return { kind: "customer-facing", recipients, count: Math.max(1, extra), summary: `${recipients.slice(0, 3).join(", ")} ${extra > 0 ? `would have received ${extra + 1} copies` : "would have been told something untrue"}` };
3095
+ return { kind: fallback, count: Math.max(1, extra), summary: hint };
3096
+ }
3097
+ function faultWords(c) {
3098
+ const who = c.service;
3099
+ return c.outcome === "lost-response" ? `${who} saved the write but the reply was lost` : c.outcome === "timeout" ? `${who} ${c.committed ? "saved the write but answered after the client timeout" : "never answered"}` : c.outcome === "server-error" ? `${who} returned ${c.status ?? 500}` : c.outcome === "rate-limited" ? `${who} rate-limited the call (429)` : c.outcome === "unauthorized" ? `${who} rejected the credential (${c.status ?? 401})` : c.outcome === "client-error" ? `${who} rejected the request (${c.status ?? 400})` : `${who} failed`;
3100
+ }
3101
+ function genericChecks(calls, opts = {}) {
3102
+ const out = [], covered = opts.covered ?? (() => false);
3103
+ const ordered = [...calls].sort((a, b) => a.sequence - b.sequence), writes = ordered.filter((c) => c.isWrite && c.outcome !== "blocked");
3104
+ const claims = opts.claims ?? claimsOf(ordered, opts.output);
3105
+ const announcementSeqs = new Set(claims.map((c) => c.via).filter((v) => v !== void 0));
3106
+ for (const group of groupsOf(writes)) {
3107
+ if (group.length < 2 && !group[0].duplicated) continue;
3108
+ const first = group[0], made = group.reduce((n, c) => n + effects(c), 0), keys = new Set(group.map((c) => c.idempotencyKey));
3109
+ const fault = group.find((c, i) => AMBIGUOUS.includes(c.outcome) && i < group.length - 1);
3110
+ const keyed = keys.size === 1 && !keys.has(void 0);
3111
+ const announce = announcementSeqs.has(first.sequence) || isAnnouncement(first);
3112
+ const when = fault ? ` after ${faultWords(fault)}` : opts.duplicateDelivery ? " when the trigger was delivered twice" : first.duplicated ? ` when ${first.service} received the request twice` : "";
3113
+ if (made >= 2 && (first.method === "POST" || first.method === "DELETE" || announce) && !covered(first.service, "duplicate-write")) {
3114
+ const noun = first.method === "POST" ? "saved" : "applied";
3115
+ out.push({
3116
+ check: "duplicate-write",
3117
+ service: first.service,
3118
+ resource: `${first.method} ${first.path}`,
3119
+ calls: group.map((c) => c.sequence),
3120
+ finding: `${label(first)} was ${group.length > 1 ? `sent ${times(group.length)}` : "sent once"} and ${noun} ${times(made)}${when}${keyed ? " (the key was not honored)" : group.some((c) => c.idempotencyKey) ? " with different idempotency keys" : " without an idempotency key"}`,
3121
+ impact: impactOf(group, made - 1, "data-integrity", `the same ${first.resourcePath.split("/").filter((s) => s !== "{id}").pop() ?? "record"} exists ${times(made)} downstream`),
3122
+ ...group[group.length - 1].source ? { source: group[group.length - 1].source } : {},
3123
+ writeSites: sites(group),
3124
+ fix: announce ? "check-before-resend" : "idempotency-key",
3125
+ ...group.length === 1 && first.duplicated && !first.idempotencyKey && !opts.duplicateDelivery ? { advisory: true } : {}
3126
+ });
3127
+ continue;
3128
+ }
3129
+ if (fault && !keyed && made >= 2 && !covered(first.service, "retry-without-key")) {
3130
+ const retry = group.find((c) => c.sequence > fault.sequence);
3131
+ out.push({
3132
+ check: "retry-without-key",
3133
+ service: first.service,
3134
+ resource: `${first.method} ${first.path}`,
3135
+ calls: group.map((c) => c.sequence),
3136
+ finding: `${label(first)} was sent ${times(group.length)}${when}, ${retry.idempotencyKey ? "with a new idempotency key" : "without an idempotency key"}`,
3137
+ impact: made >= 2 ? impactOf(group, made - 1, "data-integrity", "the write was applied more than once") : { kind: "reliability", count: 1, summary: `a retry without a stable key can apply ${first.method} ${first.resourcePath} twice when the first attempt was saved` },
3138
+ ...retry.source ? { source: retry.source } : {},
3139
+ writeSites: sites(group),
3140
+ fix: announce ? "check-before-resend" : "idempotency-key"
3141
+ });
3142
+ }
3143
+ }
3144
+ for (const limited of ordered.filter((c) => c.outcome === "rate-limited" && c.retryAfterMs && c.at !== void 0)) {
3145
+ const next = ordered.find((c) => c.sequence > limited.sequence && c.service === limited.service && c.at !== void 0 && sameRequest(limited, c));
3146
+ if (next && next.at - limited.at < limited.retryAfterMs * 0.9 && !covered(limited.service, "retry-after-ignored"))
3147
+ out.push({
3148
+ check: "retry-after-ignored",
3149
+ service: limited.service,
3150
+ resource: `${limited.method} ${limited.path}`,
3151
+ calls: [limited.sequence, next.sequence],
3152
+ finding: `${label(limited)} was retried after ${next.at - limited.at}ms although ${limited.service} asked to wait ${Math.round(limited.retryAfterMs / 1e3)}s (Retry-After)`,
3153
+ impact: { kind: "reliability", count: 1, summary: "ignoring Retry-After prolongs rate limiting and can get the credential throttled or banned" },
3154
+ ...next.source ? { source: next.source } : {},
3155
+ fix: "respect-retry-after"
3156
+ });
3157
+ }
3158
+ const unrecoveredBefore = (seq, via) => writes.filter((w) => w.sequence < seq && !(via && sameRequest(w, via) && succeeded(via)) && !announcementSeqs.has(w.sequence) && FAILED.includes(w.outcome) && w.outcome !== "lost-response" && !(w.outcome === "timeout" && w.committed) && !writes.some((r) => r.sequence > w.sequence && r.sequence < seq && sameRequest(w, r) && succeeded(r)));
3159
+ for (const claim of claims.filter((c) => c.polarity === "success")) {
3160
+ const via = claim.via !== void 0 ? ordered.find((c) => c.sequence === claim.via) : void 0, failed = unrecoveredBefore(claim.sequence, via)[0];
3161
+ if (!failed || covered(via?.service ?? failed.service, "announce-after-failed-write")) continue;
3162
+ out.push({
3163
+ check: "announce-after-failed-write",
3164
+ service: via?.service ?? failed.service,
3165
+ resource: via ? `${via.method} ${via.path}` : "agent output",
3166
+ calls: [failed.sequence, ...via ? [via.sequence] : []],
3167
+ finding: `Your agent said "${claim.text.slice(0, 80)}"${via ? ` (${label(via)})` : ""} after ${label(failed)} failed (${faultWords(failed)}) and never succeeded`,
3168
+ impact: impactOf(via ? [via] : [], 0, "customer-facing", "the agent reports work that never happened"),
3169
+ ...claim.source ?? via?.source ? { source: claim.source ?? via?.source } : {},
3170
+ fix: "confirm-before-announce"
3171
+ });
3172
+ break;
3173
+ }
3174
+ for (const claim of claims.filter((c) => c.polarity === "failure")) {
3175
+ const later = writes.find((w) => w.sequence > claim.sequence && !announcementSeqs.has(w.sequence) && effects(w) > 0);
3176
+ if (!later || covered(later.service, "write-after-reported-failure")) continue;
3177
+ out.push({
3178
+ check: "write-after-reported-failure",
3179
+ service: later.service,
3180
+ resource: `${later.method} ${later.path}`,
3181
+ calls: [...claim.via ? [claim.via] : [], later.sequence],
3182
+ finding: `Your agent reported "${claim.text.slice(0, 80)}" and then still sent ${label(later)}`,
3183
+ impact: impactOf([later], 0, "data-integrity", "the system changed after the agent told someone it had not"),
3184
+ ...later.source ? { source: later.source } : {}
3185
+ });
3186
+ break;
3187
+ }
3188
+ if (opts.readBack) for (const claim of claims.filter((c) => c.polarity === "success")) {
3189
+ for (const w of writes.filter((w2) => w2.sequence < claim.sequence && w2.resourceId && w2.method !== "POST" && new RegExp(`(^|[^\\w-])${w2.resourceId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}([^\\w-]|$)`).test(claim.text))) {
3190
+ const rb = opts.readBack(w);
3191
+ if (!rb || covered(w.service, "claimed-change-unchanged")) continue;
3192
+ const unchanged = w.method === "DELETE" ? rb.after !== void 0 : canonical2(stable(rb.before)) === canonical2(stable(rb.after));
3193
+ if (!unchanged) continue;
3194
+ out.push({
3195
+ check: "claimed-change-unchanged",
3196
+ service: w.service,
3197
+ resource: `${w.method} ${w.path}`,
3198
+ calls: [w.sequence, ...claim.via ? [claim.via] : []],
3199
+ finding: `Your agent said "${claim.text.slice(0, 80)}", but ${w.service} ${w.path} is unchanged at read-back`,
3200
+ impact: { kind: "data-integrity", count: 1, summary: `${w.resourcePath.split("/").filter((s) => s !== "{id}").pop() ?? "record"} ${w.resourceId} was reported changed but is not` },
3201
+ ...claim.source ?? w.source ? { source: claim.source ?? w.source } : {},
3202
+ fix: "confirm-before-announce"
3203
+ });
3204
+ break;
3205
+ }
3206
+ }
3207
+ for (const failed of writes.filter((w) => FAILED.includes(w.outcome) && !(w.outcome === "timeout" && w.committed) && w.outcome !== "lost-response" && !announcementSeqs.has(w.sequence) && !isAnnouncement(w) && !MESSAGING.test(w.path))) {
3208
+ if (writes.some((r) => r.sequence > failed.sequence && sameRequest(failed, r) && succeeded(r))) continue;
3209
+ const committed = writes.find((a) => a.sequence < failed.sequence && a.service !== failed.service && effects(a) > 0 && !announcementSeqs.has(a.sequence) && !isAnnouncement(a) && !writes.some((x) => x.sequence > failed.sequence && x.service === a.service && (x.resourceId ? x.resourceId === a.resourceId : x.resourcePath === a.resourcePath) && effects(x) > 0));
3210
+ if (!committed || covered(committed.service, "partial-commit")) continue;
3211
+ out.push({
3212
+ check: "partial-commit",
3213
+ service: committed.service,
3214
+ resource: `${committed.method} ${committed.path}`,
3215
+ calls: [committed.sequence, failed.sequence],
3216
+ finding: `${label(committed)} was saved, then ${label(failed)} failed (${faultWords(failed)}) and nothing undid the first write`,
3217
+ impact: impactOf([committed], 0, "data-integrity", `${committed.service} and ${failed.service} disagree: one recorded the change, the other did not`),
3218
+ ...failed.source ? { source: failed.source } : {}
3219
+ });
3220
+ break;
3221
+ }
3222
+ return out;
3223
+ }
3224
+ function worldReadBack(ctx) {
3225
+ return (c) => {
3226
+ const find = (state) => (state?.[c.service]?.[c.resourcePath.replace(/\/\{id\}$/, "")] ?? []).find((r) => r && typeof r === "object" && String(r.id) === c.resourceId);
3227
+ return { before: find(ctx.initialState), after: find(ctx.finalState) };
3228
+ };
3229
+ }
3230
+ function genericWorldChecks(covers) {
3231
+ const rules = ["retry-without-key", "announce-after-failed-write", "write-after-reported-failure", "claimed-change-unchanged", "partial-commit"];
3232
+ return rules.map((rule) => ({
3233
+ id: `generic.${rule}`,
3234
+ title: GENERIC_TITLES[rule][0],
3235
+ expected: GENERIC_TITLES[rule][1],
3236
+ path: "/",
3237
+ impact: rule === "announce-after-failed-write" ? "customer-facing" : rule === "retry-without-key" ? "reliability" : "data-integrity",
3238
+ impactHint: GENERIC_TITLES[rule][1],
3239
+ run(ctx) {
3240
+ if (["openai", "anthropic", "google-oauth", "postgres"].includes(ctx.service.adapter ?? "")) return [];
3241
+ const adapterOf = (name) => ctx.services.find((s) => s.name === name)?.adapter;
3242
+ const calls = callsFromWorldEvents(ctx.events).filter((c) => !["openai", "anthropic", "google-oauth"].includes(adapterOf(c.service) ?? ""));
3243
+ return genericChecks(calls, { readBack: worldReadBack(ctx), duplicateDelivery: ctx.duplicateDelivery, covered: (service, check) => check !== rule || covers(adapterOf(service), check) }).filter((v) => v.check === rule && v.service === ctx.service.name).map((v) => ({ path: v.resource.split(" ")[1] ?? "/", actual: { resource: v.resource, calls: v.calls }, finding: v.finding, impact: { kind: v.impact.kind, count: v.impact.count, ...v.impact.amount ? { amount: Math.round(v.impact.amount * 100), currency: v.impact.currency } : {} }, evidence: v.calls }));
3244
+ }
3245
+ }));
3246
+ }
3247
+ function proofFindings(violations, calls) {
3248
+ return violations.map((v, i) => {
3249
+ const involved = new Set(v.calls), first = calls.find((c) => c.sequence === v.calls[0]);
3250
+ const kind = v.check === "duplicate-write" || v.check === "retry-without-key" ? "duplicate-effect" : v.check === "announce-after-failed-write" || v.check === "claimed-change-unchanged" ? "unconfirmed-announce" : v.check === "partial-commit" ? "partial-commit" : "changed-state";
3251
+ const failed = calls.find((c) => involved.has(c.sequence) && FAILED.includes(c.outcome));
3252
+ return {
3253
+ id: `generic_${v.check.replace(/-/g, "_")}_${i + 1}`,
3254
+ kind,
3255
+ service: v.service,
3256
+ path: v.resource.split(" ")[1] ?? "/",
3257
+ title: v.finding,
3258
+ records: [],
3259
+ timeline: calls.slice(0, 200).map((c) => ({ sequence: c.sequence, service: c.service, operation: c.isWrite ? "write" : "read", path: c.path, detail: `${c.method} ${c.outcome}${c.idempotencyKey ? " keyed" : ""}`, ...c.source ? { source: `${c.source.file}:${c.source.line}` } : {}, highlight: involved.has(c.sequence) })),
3260
+ ...v.source ? { source: v.source } : {},
3261
+ ...v.writeSites?.length ? { writeSites: v.writeSites } : {},
3262
+ ...failed ? { fault: { type: failed.outcome, service: failed.service, path: failed.path, triggered: true } } : {},
3263
+ ...kind === "duplicate-effect" ? { expected: 1, actual: Math.max(2, v.impact.count !== void 0 ? v.impact.count + 1 : 2) } : {},
3264
+ adapter: first?.tier ?? "generic",
3265
+ ...v.fix ? { hint: v.fix } : {},
3266
+ ...failed?.source && v.check === "announce-after-failed-write" ? { relatedSource: { file: failed.source.file, line: failed.source.line } } : {}
3267
+ };
3268
+ });
3269
+ }
3270
+ var WRITE_METHODS, READ_LIKE, MODEL_HOST, VOLATILE, KEY_HEADERS, KEY_FIELDS, digest, stable, idLike, outcomeOf, parseSource, SUCCESS, FAILURE, TEXT_FIELDS, MESSAGING, polarityOf, RECIPIENT, isAnnouncement, AMOUNT, times, FAILED, AMBIGUOUS, label, sameRequest, succeeded, effects, sites, groupsOf, GENERIC_TITLES;
3271
+ var init_generic_calls = __esm({
3272
+ "src/runtime/generic-calls.ts"() {
3273
+ "use strict";
3274
+ init_run_summary();
3275
+ WRITE_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
3276
+ READ_LIKE = /\/(search|query|lookup|count|batch\/read|completions|embeddings|responses|count_tokens|graphql\/query)$/i;
3277
+ MODEL_HOST = /(^|\.)(openai\.com|anthropic\.com|generativelanguage\.googleapis\.com|mistral\.ai|groq\.com|cohere\.ai)$/i;
3278
+ VOLATILE = /^(id|ts|created|created_at|updated_at|createdAt|updatedAt|timestamp|request_id|requestId|nonce|uuid|sequence|object|livemode)$|_at$/;
3279
+ KEY_HEADERS = ["idempotency-key", "x-idempotency-key", "x-request-id", "x-amz-client-token"];
3280
+ KEY_FIELDS = /^(idempotency_?key|ClientToken|ClientRequestToken|MessageDeduplicationId|client_token|request_id)$/i;
3281
+ digest = (value3) => `sha256:${createHash5("sha256").update(typeof value3 === "string" ? value3 : canonical2(value3)).digest("hex").slice(0, 16)}`;
3282
+ stable = (value3) => Array.isArray(value3) ? value3.map(stable) : value3 && typeof value3 === "object" ? Object.fromEntries(Object.entries(value3).filter(([k]) => !VOLATILE.test(k) && !KEY_FIELDS.test(k)).map(([k, v]) => [k, stable(v)])) : value3;
3283
+ idLike = (segment) => /^\d+$/.test(segment) || /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(segment) || segment.length >= 3 && /\d/.test(segment) && /^[A-Za-z0-9_\-:.]+$/.test(segment) && !/^v\d+(\.\d+)*$/i.test(segment) && !/^\d{4}-\d{2}-\d{2}$/.test(segment) && !/^[A-Za-z]+\.(json|xml)$/.test(segment);
3284
+ outcomeOf = (status) => status === void 0 ? "ok" : status === 401 || status === 403 ? "unauthorized" : status === 429 ? "rate-limited" : status >= 500 ? "server-error" : status >= 400 ? "client-error" : "ok";
3285
+ parseSource = (s) => {
3286
+ if (!s) return;
3287
+ if (typeof s !== "string") return s;
3288
+ try {
3289
+ const v = JSON.parse(s);
3290
+ return typeof v?.file === "string" ? v : void 0;
3291
+ } catch {
3292
+ return;
3293
+ }
3294
+ };
3295
+ SUCCESS = /\b(done|complete[d]?|success(ful(ly)?)?|refunded|closed|created|updated|sent|processed|confirmed|welcome|paid|invoiced|won|approved|resolved|scheduled|saved|booked|cancell?ed|shipped|delivered)\b/i;
3296
+ FAILURE = /\b(fail(ed|ure)?|error|unable|could ?n[o']t|cannot|can't|did ?n[o']t|not (?:been )?(?:\w+ed)|retry(ing)?|escalat\w*|pending|try again|sorry)\b/i;
3297
+ TEXT_FIELDS = /^(text|body|message|content|subject|summary|description|Body|Message|html|markdown|note|comment)$/;
3298
+ MESSAGING = /(message|messages|sms|mail|email|emails|notification|notifications|notify|send|postMessage|comments?|reply|replies)(\.json)?$/i;
3299
+ polarityOf = (text3) => FAILURE.test(text3) ? "failure" : SUCCESS.test(text3) ? "success" : "neutral";
3300
+ RECIPIENT = /^(to|recipient|recipients|email|phone|phone_number|channel|cc|bcc|To|chat_id|user_id)$/;
3301
+ isAnnouncement = (c) => c.isWrite && !!textOf(c.body) && (MESSAGING.test(c.path) || recipientsOf(c.body).length > 0);
3302
+ AMOUNT = /^(amount|total|price|unit_amount|amount_total|grand_total|subtotal|value|amount_cents|amount_minor|total_cents|price_cents)$/i;
3303
+ times = (n) => n === 2 ? "twice" : `${n} times`;
3304
+ FAILED = ["server-error", "lost-response", "timeout", "client-error", "unauthorized", "rate-limited"];
3305
+ AMBIGUOUS = ["server-error", "lost-response", "timeout"];
3306
+ label = (c) => `${c.method} ${c.path} on ${c.service}`;
3307
+ sameRequest = (a, b) => a.service === b.service && a.method === b.method && a.resourcePath === b.resourcePath && (a.method === "POST" || a.resourceId === b.resourceId) && (!a.requestDigest || !b.requestDigest || a.requestDigest === b.requestDigest);
3308
+ succeeded = (c) => c.outcome === "ok" || c.outcome === "replayed";
3309
+ effects = (c) => c.committed === false || c.outcome === "replayed" || c.outcome === "blocked" ? 0 : (c.committed || c.outcome === "ok" ? 1 : 0) * (c.duplicated ? 2 : 1);
3310
+ sites = (calls) => [...new Map(calls.filter((c) => c.source).map((c) => [`${c.source.file}:${c.source.line}`, c.source])).values()];
3311
+ groupsOf = (writes) => {
3312
+ const groups2 = [];
3313
+ for (const c of writes) {
3314
+ const g = groups2.find((g2) => sameRequest(g2[0], c));
3315
+ if (g) g.push(c);
3316
+ else groups2.push([c]);
3317
+ }
3318
+ return groups2;
3319
+ };
3320
+ GENERIC_TITLES = {
3321
+ "duplicate-write": ["World-changing calls take effect once", "each create, charge or send is applied once, even under retries and redelivery"],
3322
+ "retry-without-key": ["Retries after a fault reuse the idempotency key", "a write retried after an ambiguous failure carries the same idempotency key"],
3323
+ "retry-after-ignored": ["Rate-limited calls wait for Retry-After", "a 429 is retried no sooner than its Retry-After"],
3324
+ "announce-after-failed-write": ["Success is announced only after the write succeeded", "the agent claims success only when every write it depends on succeeded"],
3325
+ "write-after-reported-failure": ["No writes after the agent reported failure", "after the agent reports a failure it changes nothing else"],
3326
+ "claimed-change-unchanged": ["Claimed changes are visible at read-back", "every resource the agent says it changed is changed when read back"],
3327
+ "partial-commit": ["Multi-service writes commit together or compensate", "when a later write fails, earlier writes in other services are undone"]
3328
+ };
3329
+ }
3330
+ });
3331
+
2968
3332
  // src/runtime/repair-proof-page.ts
2969
3333
  function diffHtml(diff) {
2970
3334
  return diff.trimEnd().split("\n").map((line) => `<span class="${line.startsWith("@@") ? "h" : line.startsWith("+++") || line.startsWith("---") ? "f" : line.startsWith("+") ? "add" : line.startsWith("-") ? "del" : ""}">${esc(line) || " "}</span>`).join("\n");
@@ -3666,7 +4030,9 @@ function esbuildBinary(real){const match=real.match(/^(.*[\/\\]node_modules[\/\\
3666
4030
  // the same name inside a project or earlier on PATH is still reported.
3667
4031
  const SYSTEM_INFO_BINARIES=new Set(['/usr/bin/uname','/bin/uname','/usr/bin/sw_vers','/usr/bin/arch','/usr/bin/nproc','/usr/bin/getconf']);
3668
4032
  function systemInfoBinary(real){return process.platform!=='win32'&&SYSTEM_INFO_BINARIES.has(real);}
3669
- function trustedExecutable(file,options){const real=nodeFs.realpathSync(file);const key=real+'\0'+String(envPath((options&&options.env)||process.env)||'');if(executableTrust.has(key))return executableTrust.get(key);let trusted=real===nodeReal||esbuildBinary(real)||systemInfoBinary(real);if(!trusted&&isRunnable(real)){const fd=nodeFs.openSync(real,'r');try{const head=Buffer.alloc(256);const read=nodeFs.readSync(fd,head,0,256,0);trusted=nodeShebang(head.subarray(0,read).toString('latin1'),options);}finally{nodeFs.closeSync(fd);}}if(executableTrust.size<1000)executableTrust.set(key,trusted);return trusted;}
4033
+ // pnpm's node_modules/.bin entries are sh scripts that exec node on the package's JS: the child is Node and loads the hook.
4034
+ function pnpmNodeShim(real,text){if(!/[\\/]node_modules[\\/]\.bin[\\/]/.test(real)||!/^#!\/bin\/sh/.test(text))return false;const execs=[...text.matchAll(/\bexec\s+(\S+)/g)].map(m=>m[1]);return execs.length>0&&execs.every(e=>/^(?:node|"\$basedir\/node)(?:\.exe)?"?$/.test(e));}
4035
+ function trustedExecutable(file,options){const real=nodeFs.realpathSync(file);const key=real+'\0'+String(envPath((options&&options.env)||process.env)||'');if(executableTrust.has(key))return executableTrust.get(key);let trusted=real===nodeReal||esbuildBinary(real)||systemInfoBinary(real);if(!trusted&&isRunnable(real)){const fd=nodeFs.openSync(real,'r');try{const head=Buffer.alloc(8192);const read=nodeFs.readSync(fd,head,0,8192,0);const text=head.subarray(0,read).toString('latin1');trusted=nodeShebang(text.slice(0,256),options)||pnpmNodeShim(real,text);}finally{nodeFs.closeSync(fd);}}if(executableTrust.size<1000)executableTrust.set(key,trusted);return trusted;}
3670
4036
  const reportedSubprocesses=new Set();
3671
4037
  function hookedEnv(options){const env={...((options&&options.env)||process.env)};const current=env.NODE_OPTIONS||'';if(!current.includes(__filename))env.NODE_OPTIONS=(current+' '+hookOption).trim();env.AGENTTWIN_HOOK_CHILD='1';return {...(options||{}),env};}
3672
4038
  // Never throws: an unclassifiable command is reported, and the application's spawn proceeds unchanged.
@@ -3698,7 +4064,9 @@ if(originalFetch)globalThis.fetch=async function(input,init){
3698
4064
  const target=route?route.endpoint+url.pathname+url.search:url.href;
3699
4065
  // Forward the body as bytes: copying a keepalive Request whose body is a stream throws in Node's fetch.
3700
4066
  const body=request.method==='GET'||request.method==='HEAD'?undefined:await request.arrayBuffer();
3701
- return originalFetch(target,{method:request.method,headers,body,signal:request.signal,redirect:'error'});
4067
+ const signal=init?.signal??(input instanceof Request?input.signal:undefined),sent=originalFetch(target,{method:request.method,headers,body,signal:request.signal,redirect:'error'});
4068
+ if(!signal)return sent;if(signal.aborted)throw signal.reason;
4069
+ return new Promise((resolve,reject)=>{const stop=()=>reject(signal.reason);signal.addEventListener('abort',stop,{once:true});sent.then(v=>{signal.removeEventListener('abort',stop);resolve(v);},e=>{signal.removeEventListener('abort',stop);reject(e);});});
3702
4070
  };
3703
4071
  const plainHttp={request:http.request,get:http.get};
3704
4072
  const loopback=host=>['127.0.0.1','localhost','::1','[::1]'].includes(host);
@@ -4173,7 +4541,7 @@ var init_composio_twin = __esm({
4173
4541
  });
4174
4542
 
4175
4543
  // src/runtime/google-oauth-twin.ts
4176
- import { createHash as createHash5 } from "crypto";
4544
+ import { createHash as createHash6 } from "crypto";
4177
4545
  var googleOAuthOperation;
4178
4546
  var init_google_oauth_twin = __esm({
4179
4547
  "src/runtime/google-oauth-twin.ts"() {
@@ -4190,7 +4558,7 @@ var init_google_oauth_twin = __esm({
4190
4558
  const grant = data["/grants"].find((row) => row.refresh_token === params.refresh_token && row.client_id === params.client_id);
4191
4559
  if (!grant || !synthetic(grant.refresh_token) || grant.active !== true) return error(400, "invalid_grant");
4192
4560
  if (typeof grant.scope !== "string" || !grant.scope || !Number.isInteger(grant.expires_in) || Number(grant.expires_in) < 1 || Number(grant.expires_in) > 86400) return;
4193
- const access_token = "synthetic-access-" + createHash5("sha256").update(JSON.stringify([params.client_id, params.refresh_token, sequence])).digest("hex").slice(0, 24);
4561
+ const access_token = "synthetic-access-" + createHash6("sha256").update(JSON.stringify([params.client_id, params.refresh_token, sequence])).digest("hex").slice(0, 24);
4194
4562
  const body = { access_token, token_type: "Bearer", expires_in: grant.expires_in, scope: grant.scope };
4195
4563
  const record5 = { id: "issuance_" + sequence, client_id: params.client_id, ...body };
4196
4564
  data["/tokens"].push(record5);
@@ -4337,7 +4705,7 @@ var init_resp = __esm({
4337
4705
 
4338
4706
  // src/runtime/engines/redis-lua.ts
4339
4707
  import { createRequire } from "module";
4340
- import { createHash as createHash6 } from "crypto";
4708
+ import { createHash as createHash7 } from "crypto";
4341
4709
  var vm, load, toLua, fromLua, RedisScripts, WRITE_HINT;
4342
4710
  var init_redis_lua = __esm({
4343
4711
  "src/runtime/engines/redis-lua.ts"() {
@@ -4376,7 +4744,7 @@ var init_redis_lua = __esm({
4376
4744
  return this.execute(source, args.slice(2, 2 + count), args.slice(2 + count), name.endsWith("_ro"));
4377
4745
  }
4378
4746
  store(source) {
4379
- const sha6 = createHash6("sha1").update(Buffer.from(source, "latin1")).digest("hex");
4747
+ const sha6 = createHash7("sha1").update(Buffer.from(source, "latin1")).digest("hex");
4380
4748
  this.cache.set(sha6, source);
4381
4749
  return sha6;
4382
4750
  }
@@ -5818,7 +6186,7 @@ var init_gmail_mime = __esm({
5818
6186
  });
5819
6187
 
5820
6188
  // src/runtime/rest-adapters.ts
5821
- import { createHash as createHash7 } from "crypto";
6189
+ import { createHash as createHash8 } from "crypto";
5822
6190
  function githubOperation(method, path2, params, _headers, data, sequence) {
5823
6191
  const errors = (status, message, extra) => ({ status, body: { message, documentation_url: "https://docs.github.com/rest", ...extra ?? {} }, collection: "/repos" });
5824
6192
  if (path2 === "/repos") return method === "GET" ? ok("/repos", rows(data, "/repos").map((row) => structuredClone(row))) : void 0;
@@ -6948,7 +7316,7 @@ var init_rest_adapters = __esm({
6948
7316
  init_gmail_mime();
6949
7317
  EPOCH2 = 17e8;
6950
7318
  iso2 = (epoch = EPOCH2) => new Date(twinNowMs(epoch * 1e3)).toISOString();
6951
- sha2 = (value3) => createHash7("sha256").update(value3).digest("hex");
7319
+ sha2 = (value3) => createHash8("sha256").update(value3).digest("hex");
6952
7320
  detUuid = (seed) => {
6953
7321
  const hex = sha2(seed).slice(0, 32).split("");
6954
7322
  hex[12] = "4";
@@ -7324,12 +7692,12 @@ __export(http_world_exports, {
7324
7692
  import { createServer as createServer3 } from "http";
7325
7693
  import { createServer as createNetServer } from "net";
7326
7694
  import { isDeepStrictEqual as isDeepStrictEqual2 } from "util";
7327
- import { createHash as createHash8 } from "crypto";
7695
+ import { createHash as createHash9 } from "crypto";
7328
7696
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
7329
7697
  import { mkdir as mkdir4, mkdtemp as mkdtemp5, rm as rm8, writeFile as writeFile7 } from "fs/promises";
7330
7698
  import { tmpdir as tmpdir5 } from "os";
7331
7699
  import { join as join14 } from "path";
7332
- var slackDirectMessageId, idempotencyKeyDigest, HttpWorld;
7700
+ var KEYED_PACKS, slackDirectMessageId, idempotencyKeyDigest, HttpWorld;
7333
7701
  var init_http_world = __esm({
7334
7702
  "src/runtime/http-world.ts"() {
7335
7703
  "use strict";
@@ -7346,8 +7714,9 @@ var init_http_world = __esm({
7346
7714
  init_pack_log();
7347
7715
  init_pack_aliases();
7348
7716
  init_compatible_packs();
7349
- slackDirectMessageId = (user) => `D${createHash8("sha256").update(user).digest("hex").slice(0, 16).toUpperCase()}`;
7350
- idempotencyKeyDigest = (key3) => typeof key3 === "string" && key3 ? `sha256:${createHash8("sha256").update(key3).digest("hex").slice(0, 16)}` : void 0;
7717
+ KEYED_PACKS = /* @__PURE__ */ new Set(["resend"]);
7718
+ slackDirectMessageId = (user) => `D${createHash9("sha256").update(user).digest("hex").slice(0, 16).toUpperCase()}`;
7719
+ idempotencyKeyDigest = (key3) => typeof key3 === "string" && key3 ? `sha256:${createHash9("sha256").update(key3).digest("hex").slice(0, 16)}` : void 0;
7351
7720
  HttpWorld = class {
7352
7721
  /** The one-command flow runs apps that hard-code their own model key: the model twins then accept any credential. */
7353
7722
  constructor(spec, seed, options = {}) {
@@ -7744,7 +8113,7 @@ var init_http_world = __esm({
7744
8113
  return;
7745
8114
  }
7746
8115
  }
7747
- if (!this.fired && result2.operation === "write" && fault?.type === "timeout-after-write" && fault.service === service.name && fault.path === result2.collection) {
8116
+ if (!this.fired && result2.operation === "write" && fault?.type === "timeout-after-write" && fault.service === service.name && (fault.path === result2.collection || matchesFault(normalPath(req.url ?? "/", req.method)))) {
7748
8117
  this.fired = true;
7749
8118
  this.faultActions++;
7750
8119
  this.record(service.name, "fault", result2.collection, `write committed; response delayed ${fault.delayMs}ms`);
@@ -7906,6 +8275,8 @@ var init_http_world = __esm({
7906
8275
  rawServers = [];
7907
8276
  /** Each pack service's plain-TCP port for clients that open their own TLS sockets (see startPack). */
7908
8277
  packTcp = /* @__PURE__ */ Object.create(null);
8278
+ /** Saved responses by service, path and Idempotency-Key, for packs whose vendor replays keyed requests. */
8279
+ packReplays = /* @__PURE__ */ new Map();
7909
8280
  /**
7910
8281
  * A twin pack served behind this world: the run token is checked and swapped for the credential the pack issued,
7911
8282
  * seeded fault schedules apply around the pack's own handler, and every action the pack logs becomes evidence — writes
@@ -8013,7 +8384,7 @@ var init_http_world = __esm({
8013
8384
  const row = { id: id2, ...a.fields ?? {} };
8014
8385
  if (removed) {
8015
8386
  if (at >= 0) rows2.splice(at, 1);
8016
- } else if (at >= 0) rows2[at] = row;
8387
+ } else if (at >= 0) rows2[at] = { ...rows2[at], ...row };
8017
8388
  else rows2.push(row);
8018
8389
  if (!evidence) continue;
8019
8390
  const byApp = a.actor?.kind === "agent" && !byWorld;
@@ -8086,7 +8457,7 @@ var init_http_world = __esm({
8086
8457
  return;
8087
8458
  }
8088
8459
  const attempt = Number(last.envelope.retry_attempt ?? 0) + 1;
8089
- const again = { ...last.envelope, envelope_id: createHash8("sha256").update(`${String(last.envelope.envelope_id)}:${attempt}`).digest("hex").replace(/^(.{8})(.{4})(.{4})(.{4})(.{12}).*/, "$1-$2-$3-$4-$5"), retry_attempt: attempt, retry_reason: "timeout" };
8460
+ const again = { ...last.envelope, envelope_id: createHash9("sha256").update(`${String(last.envelope.envelope_id)}:${attempt}`).digest("hex").replace(/^(.{8})(.{4})(.{4})(.{4})(.{12}).*/, "$1-$2-$3-$4-$5"), retry_attempt: attempt, retry_reason: "timeout" };
8090
8461
  last.send(JSON.stringify(again));
8091
8462
  this.record(service.name, "twin", path2, `redelivered ${String(last.envelope.type ?? "envelope")} (retry_attempt ${attempt}, as after a lost acknowledgment)`);
8092
8463
  json3(200, { ok: true, retry_attempt: attempt });
@@ -8160,6 +8531,13 @@ var init_http_world = __esm({
8160
8531
  return { status: r.status, headers: r.headers, bytes: model.restore(Buffer.from(await r.arrayBuffer())), actions: log.drain() };
8161
8532
  };
8162
8533
  if (workspace && method !== "GET") this.causing[service.name] = 1;
8534
+ const replayKey = !workspace && method === "POST" && typeof requestKey === "string" && requestKey && KEYED_PACKS.has(name) ? `${service.name}:${path2}:${requestKey}` : void 0;
8535
+ const replay = replayKey ? this.packReplays.get(replayKey) : void 0;
8536
+ if (replay) {
8537
+ this.record(service.name, "twin", path2, `replayed the first response for Idempotency-Key ${requestKey}; nothing written`);
8538
+ respond(replay.status, replay.out, replay.bytes);
8539
+ return;
8540
+ }
8163
8541
  const first = await serialized(call2).finally(() => {
8164
8542
  if (workspace) this.causing[service.name] = 0;
8165
8543
  });
@@ -8205,13 +8583,14 @@ var init_http_world = __esm({
8205
8583
  first.headers.forEach((v, k) => {
8206
8584
  if (!/^(content-length|transfer-encoding|connection)$/i.test(k)) out[k] = v;
8207
8585
  });
8208
- if (target && !this.fired && fault?.type === "timeout-after-write" && fault.service === service.name && matchesFault(target)) {
8586
+ if (replayKey && first.status < 500) this.packReplays.set(replayKey, { status: first.status, out, bytes: first.bytes });
8587
+ if (target && !this.fired && fault?.type === "timeout-after-write" && fault.service === service.name && (matchesFault(target) || matchesFault(path2))) {
8209
8588
  this.fired = true;
8210
8589
  this.faultActions++;
8211
8590
  this.record(service.name, "fault", target, `write committed; response delayed ${fault.delayMs}ms`);
8212
8591
  this.keyed(requestKey);
8213
8592
  later(fault.delayMs, () => send(first.status, out, first.bytes));
8214
- } else if (fault?.type === "slow-response" && faultOrdinalsFor && matchesFault(target ?? path2) && faultOrdinalsFor.includes(this.candidateIndex(faultKey))) {
8593
+ } else if (fault?.type === "slow-response" && faultOrdinalsFor && (matchesFault(target ?? path2) || matchesFault(path2)) && faultOrdinalsFor.includes(this.candidateIndex(faultKey))) {
8215
8594
  this.faultActions++;
8216
8595
  this.record(service.name, "fault", target ?? path2, `slow-response: ${target ? "write" : "request"} applied; response delayed ${fault.delayMs}ms`);
8217
8596
  this.keyed(requestKey);
@@ -8413,7 +8792,7 @@ function evaluateProperty(policy, final, events) {
8413
8792
  const keyed = /* @__PURE__ */ new Map();
8414
8793
  for (const row of rows2) {
8415
8794
  if (row[field2] === void 0) continue;
8416
- const key3 = JSON.stringify(canonical2(row[field2]));
8795
+ const key3 = JSON.stringify(canonical3(row[field2]));
8417
8796
  keyed.set(key3, [...keyed.get(key3) ?? [], row.id ?? row]);
8418
8797
  }
8419
8798
  const duplicates = [...keyed.entries()].filter(([, list4]) => list4.length > 1);
@@ -8422,7 +8801,7 @@ function evaluateProperty(policy, final, events) {
8422
8801
  passed: duplicates.length === 0,
8423
8802
  expected: 0,
8424
8803
  actual: duplicates.length,
8425
- evidence: { field: field2, duplicates: duplicates.map(([key3, ids]) => ({ value: short(key3), ids: ids.map(String) })), eventSequences: eventsFor2("write").filter((e) => e.record !== void 0 && e.record[field2] !== void 0 && duplicates.some(([key3]) => key3 === JSON.stringify(canonical2(e.record[field2])))).map((e) => e.sequence) }
8804
+ evidence: { field: field2, duplicates: duplicates.map(([key3, ids]) => ({ value: short(key3), ids: ids.map(String) })), eventSequences: eventsFor2("write").filter((e) => e.record !== void 0 && e.record[field2] !== void 0 && duplicates.some(([key3]) => key3 === JSON.stringify(canonical3(e.record[field2])))).map((e) => e.sequence) }
8426
8805
  };
8427
8806
  }
8428
8807
  if (policy.kind === "no-loss") {
@@ -8455,12 +8834,12 @@ function evaluateProperty(policy, final, events) {
8455
8834
  evidence: { operation, eventSequences: hits.map((e) => e.sequence), evidenceGap: unknown }
8456
8835
  };
8457
8836
  }
8458
- var matches2, canonical2, short, escape;
8837
+ var matches2, canonical3, short, escape;
8459
8838
  var init_evaluation = __esm({
8460
8839
  "src/runtime/evaluation.ts"() {
8461
8840
  "use strict";
8462
8841
  matches2 = (row, where) => !where || Object.entries(where).every(([k, v]) => isDeepStrictEqual3(row[k], v));
8463
- canonical2 = (value3) => Array.isArray(value3) ? value3.map(canonical2) : typeof value3 === "object" && value3 !== null ? Object.fromEntries(Object.keys(value3).sort().map((key3) => [key3, canonical2(value3[key3])])) : value3;
8842
+ canonical3 = (value3) => Array.isArray(value3) ? value3.map(canonical3) : typeof value3 === "object" && value3 !== null ? Object.fromEntries(Object.keys(value3).sort().map((key3) => [key3, canonical3(value3[key3])])) : value3;
8464
8843
  short = (value3, limit2 = 120) => value3.length <= limit2 ? value3 : `${value3.slice(0, limit2)}\u2026`;
8465
8844
  escape = (value3) => value3.replace(/~/g, "~0").replace(/\//g, "~1");
8466
8845
  }
@@ -8787,367 +9166,6 @@ var init_contracts = __esm({
8787
9166
  }
8788
9167
  });
8789
9168
 
8790
- // src/runtime/generic-calls.ts
8791
- import { createHash as createHash9 } from "crypto";
8792
- function canonical3(value3) {
8793
- return Array.isArray(value3) ? `[${value3.map(canonical3).join(",")}]` : value3 && typeof value3 === "object" ? `{${Object.keys(value3).sort().map((k) => `${JSON.stringify(k)}:${canonical3(value3[k])}`).join(",")}}` : JSON.stringify(value3 ?? null);
8794
- }
8795
- function resourceOf2(method, path2) {
8796
- const segments = path2.split("?")[0].split("/").filter(Boolean).map((s) => {
8797
- try {
8798
- return decodeURIComponent(s);
8799
- } catch {
8800
- return s;
8801
- }
8802
- });
8803
- let resourceId2;
8804
- const template = segments.map((s, i) => {
8805
- const last = i === segments.length - 1, byMethod = last && ["PUT", "PATCH", "DELETE"].includes(method) && segments.length > 1;
8806
- if (idLike(s) || byMethod) {
8807
- if (last || !resourceId2 || idLike(s)) resourceId2 = s;
8808
- return "{id}";
8809
- }
8810
- return s;
8811
- });
8812
- return { resourcePath: "/" + template.join("/"), ...resourceId2 ? { resourceId: resourceId2 } : {} };
8813
- }
8814
- function keyFrom(headers, body) {
8815
- for (const name of KEY_HEADERS) {
8816
- const v = headers?.[name];
8817
- if (typeof v === "string" && v) return digest(v);
8818
- }
8819
- if (body && typeof body === "object") {
8820
- for (const [k, v] of Object.entries(body)) if (KEY_FIELDS.test(k) && typeof v === "string" && v) return digest(v);
8821
- }
8822
- }
8823
- function normalizeCall(raw) {
8824
- const method = raw.method.toUpperCase(), path2 = raw.path.split("?")[0] || "/", { resourcePath, resourceId: resourceId2 } = resourceOf2(method, path2);
8825
- const graphqlRead = /graphql/i.test(path2) && typeof raw.body?.query === "string" && !/^\s*mutation\b/.test(raw.body.query);
8826
- const isWrite = WRITE_METHODS.has(method) && !READ_LIKE.test(path2) && !MODEL_HOST.test(raw.host) && !String(raw.service ?? "").startsWith("model:") && !graphqlRead;
8827
- const outcome2 = raw.outcome ?? outcomeOf(raw.status), key3 = keyFrom(raw.headers, raw.body), source = parseSource(raw.source);
8828
- return {
8829
- sequence: raw.sequence,
8830
- service: raw.service ?? raw.host,
8831
- host: raw.host,
8832
- method,
8833
- path: path2,
8834
- resourcePath,
8835
- ...method === "POST" && raw.createdId ? { resourceId: raw.createdId } : resourceId2 ? { resourceId: resourceId2 } : {},
8836
- isWrite,
8837
- ...key3 ? { idempotencyKey: key3 } : {},
8838
- ...raw.body !== void 0 ? { requestDigest: digest(stable(raw.body)), body: raw.body } : {},
8839
- ...raw.response !== void 0 ? { responseDigest: digest(stable(raw.response)) } : {},
8840
- outcome: outcome2,
8841
- ...raw.status !== void 0 ? { status: raw.status } : {},
8842
- committed: raw.committed ?? (isWrite ? outcome2 === "ok" : void 0),
8843
- ...raw.duplicated ? { duplicated: true } : {},
8844
- ...raw.retryAfterMs !== void 0 ? { retryAfterMs: raw.retryAfterMs } : {},
8845
- ...raw.at !== void 0 ? { at: raw.at } : {},
8846
- ...source ? { source } : {},
8847
- ...raw.tier ? { tier: raw.tier } : {}
8848
- };
8849
- }
8850
- function callsFromWorldEvents(events, tierOf = () => void 0) {
8851
- const calls = [], seen = /* @__PURE__ */ new Set();
8852
- const last = (service) => [...calls].reverse().find((c) => c.service === service && c.isWrite);
8853
- for (const e of events) {
8854
- const tier = tierOf(e.service), key3 = e.idempotencyKey;
8855
- const base = (method, path2, extra) => normalizeCall({ sequence: e.sequence, host: e.service, service: e.service, method, path: path2, ...tier ? { tier } : {}, ...e.source ? { source: e.source } : {}, ...extra });
8856
- const withKey = (c) => key3 ? { ...c, idempotencyKey: key3 } : c;
8857
- if (e.operation === "write") {
8858
- const id2 = e.record?.id === void 0 ? void 0 : String(e.record.id), path2 = e.path, recordKey = `${e.service}${path2}:${id2}`;
8859
- const method = /^(POST|PUT|PATCH|DELETE)\b/.exec(e.detail)?.[1] ?? (id2 && seen.has(recordKey) ? "PATCH" : "POST");
8860
- if (id2) seen.add(recordKey);
8861
- const c = base(method, method === "POST" ? path2 : `${path2}/${id2 ?? ""}`, { body: e.record, committed: true, ...id2 ? { createdId: id2 } : {} });
8862
- calls.push(withKey({ ...c, resourcePath: resourceOf2("GET", path2).resourcePath, ...id2 ? { resourceId: id2 } : {} }));
8863
- } else if (e.operation === "replay") calls.push(withKey(base("POST", e.path, { outcome: "replayed", committed: false })));
8864
- else if (e.operation === "auth-denied") calls.push(base("POST", e.path.split("?")[0], { outcome: "unauthorized", committed: false }));
8865
- else if (e.operation === "fault") {
8866
- const prior = last(e.service), method = /\((POST|PUT|PATCH|DELETE|GET)\)\s*$/.exec(e.detail)?.[1];
8867
- if (/^write committed|^slow-response: write/.test(e.detail) && prior) {
8868
- prior.outcome = "timeout";
8869
- prior.committed = true;
8870
- } else if (/^duplicate-write: (one write committed as two|a single write was delivered twice)/.test(e.detail) && prior) prior.duplicated = true;
8871
- else if (/^server-error/.test(e.detail)) calls.push(withKey(base(method ?? "POST", e.path, { outcome: "server-error", committed: false })));
8872
- else if (/^blackhole/.test(e.detail)) calls.push(withKey(base(method ?? "POST", e.path, { outcome: "timeout", committed: false })));
8873
- }
8874
- }
8875
- return calls;
8876
- }
8877
- function textOf(body, depth = 0) {
8878
- if (!body || typeof body !== "object" || depth > 3) return "";
8879
- return Object.entries(body).map(([k, v]) => typeof v === "string" && TEXT_FIELDS.test(k) ? v : v && typeof v === "object" ? textOf(v, depth + 1) : "").filter(Boolean).join(" ").trim();
8880
- }
8881
- function recipientsOf(body, depth = 0) {
8882
- if (!body || typeof body !== "object" || depth > 3) return [];
8883
- return Object.entries(body).flatMap(([k, v]) => RECIPIENT.test(k) ? (Array.isArray(v) ? v : [v]).filter((x) => typeof x === "string" && !!x) : v && typeof v === "object" ? recipientsOf(v, depth + 1) : []);
8884
- }
8885
- function claimsOf(calls, output = []) {
8886
- const claims = calls.filter(isAnnouncement).map((c) => {
8887
- const text3 = textOf(c.body);
8888
- return { sequence: c.sequence, text: text3, polarity: polarityOf(text3), via: c.sequence, ...c.source ? { source: c.source } : {} };
8889
- });
8890
- const end = Math.max(0, ...calls.map((c) => c.sequence)) + 1;
8891
- output.map((t) => t.trim()).filter(Boolean).slice(0, 50).forEach((text3, i) => claims.push({ sequence: end + i, text: text3.slice(0, 500), polarity: polarityOf(text3) }));
8892
- return claims;
8893
- }
8894
- function moneyOf(body, depth = 0) {
8895
- if (!body || typeof body !== "object" || depth > 3) return;
8896
- const row = body, currency = Object.entries(row).find(([k, v]) => /^currency(_code)?$/i.test(k) && typeof v === "string" && /^[a-z]{3}$/i.test(v))?.[1];
8897
- for (const [k, v] of Object.entries(row)) {
8898
- const n = typeof v === "number" ? v : typeof v === "string" && /^\d+(\.\d+)?$/.test(v) ? Number(v) : NaN;
8899
- if (AMOUNT.test(k) && Number.isFinite(n) && n > 0 && currency) return { amount: /cents|minor/i.test(k) ? n / 100 : n, currency: currency.toUpperCase() };
8900
- }
8901
- for (const v of Object.values(row)) {
8902
- const nested = v && typeof v === "object" ? moneyOf(v, depth + 1) : void 0;
8903
- if (nested) return nested;
8904
- }
8905
- }
8906
- function impactOf(calls, extra, fallback, hint) {
8907
- const money2 = calls.map((c) => moneyOf(c.body)).find(Boolean), recipients = [...new Set(calls.flatMap((c) => recipientsOf(c.body)))];
8908
- if (money2 && extra > 0) return { kind: "money", amount: money2.amount * extra, currency: money2.currency, count: extra, summary: `${formatMoney({ amount: money2.amount * extra, currency: money2.currency })} moved more than intended (${formatMoney(money2)} each)` };
8909
- const messaging = calls.some((c) => MESSAGING.test(c.path.split("?")[0]));
8910
- if (recipients.length && extra > 0 && !messaging) {
8911
- const noun = (calls[0]?.path.split("?")[0].split("/").filter(Boolean).pop() ?? "record").replace(/\.json$/, "").replace(/ies$/, "y").replace(/s$/, "");
8912
- return { kind: "data-integrity", recipients, count: extra, summary: `${extra + 1} ${noun} records would exist for ${recipients[0]} instead of 1` };
8913
- }
8914
- if (recipients.length && (extra > 0 && messaging || fallback === "customer-facing")) return { kind: "customer-facing", recipients, count: Math.max(1, extra), summary: `${recipients.slice(0, 3).join(", ")} ${extra > 0 ? `would have received ${extra + 1} copies` : "would have been told something untrue"}` };
8915
- return { kind: fallback, count: Math.max(1, extra), summary: hint };
8916
- }
8917
- function faultWords(c) {
8918
- const who = c.service;
8919
- return c.outcome === "lost-response" ? `${who} saved the write but the reply was lost` : c.outcome === "timeout" ? `${who} ${c.committed ? "saved the write but answered after the client timeout" : "never answered"}` : c.outcome === "server-error" ? `${who} returned ${c.status ?? 500}` : c.outcome === "rate-limited" ? `${who} rate-limited the call (429)` : c.outcome === "unauthorized" ? `${who} rejected the credential (${c.status ?? 401})` : c.outcome === "client-error" ? `${who} rejected the request (${c.status ?? 400})` : `${who} failed`;
8920
- }
8921
- function genericChecks(calls, opts = {}) {
8922
- const out = [], covered = opts.covered ?? (() => false);
8923
- const ordered = [...calls].sort((a, b) => a.sequence - b.sequence), writes = ordered.filter((c) => c.isWrite && c.outcome !== "blocked");
8924
- const claims = opts.claims ?? claimsOf(ordered, opts.output);
8925
- const announcementSeqs = new Set(claims.map((c) => c.via).filter((v) => v !== void 0));
8926
- for (const group of groupsOf(writes)) {
8927
- if (group.length < 2 && !group[0].duplicated) continue;
8928
- const first = group[0], made = group.reduce((n, c) => n + effects(c), 0), keys = new Set(group.map((c) => c.idempotencyKey));
8929
- const fault = group.find((c, i) => AMBIGUOUS.includes(c.outcome) && i < group.length - 1);
8930
- const keyed = keys.size === 1 && !keys.has(void 0);
8931
- const announce = announcementSeqs.has(first.sequence) || isAnnouncement(first);
8932
- const when = fault ? ` after ${faultWords(fault)}` : opts.duplicateDelivery ? " when the trigger was delivered twice" : first.duplicated ? ` when ${first.service} received the request twice` : "";
8933
- if (made >= 2 && (first.method === "POST" || first.method === "DELETE" || announce) && !covered(first.service, "duplicate-write")) {
8934
- const noun = first.method === "POST" ? "saved" : "applied";
8935
- out.push({
8936
- check: "duplicate-write",
8937
- service: first.service,
8938
- resource: `${first.method} ${first.path}`,
8939
- calls: group.map((c) => c.sequence),
8940
- finding: `${label(first)} was ${group.length > 1 ? `sent ${times(group.length)}` : "sent once"} and ${noun} ${times(made)}${when}${keyed ? " (the key was not honored)" : group.some((c) => c.idempotencyKey) ? " with different idempotency keys" : " without an idempotency key"}`,
8941
- impact: impactOf(group, made - 1, "data-integrity", `the same ${first.resourcePath.split("/").filter((s) => s !== "{id}").pop() ?? "record"} exists ${times(made)} downstream`),
8942
- ...group[group.length - 1].source ? { source: group[group.length - 1].source } : {},
8943
- writeSites: sites(group),
8944
- fix: announce ? "check-before-resend" : "idempotency-key"
8945
- });
8946
- continue;
8947
- }
8948
- if (fault && !keyed && made >= 2 && !covered(first.service, "retry-without-key")) {
8949
- const retry = group.find((c) => c.sequence > fault.sequence);
8950
- out.push({
8951
- check: "retry-without-key",
8952
- service: first.service,
8953
- resource: `${first.method} ${first.path}`,
8954
- calls: group.map((c) => c.sequence),
8955
- finding: `${label(first)} was sent ${times(group.length)}${when}, ${retry.idempotencyKey ? "with a new idempotency key" : "without an idempotency key"}`,
8956
- impact: made >= 2 ? impactOf(group, made - 1, "data-integrity", "the write was applied more than once") : { kind: "reliability", count: 1, summary: `a retry without a stable key can apply ${first.method} ${first.resourcePath} twice when the first attempt was saved` },
8957
- ...retry.source ? { source: retry.source } : {},
8958
- writeSites: sites(group),
8959
- fix: announce ? "check-before-resend" : "idempotency-key"
8960
- });
8961
- }
8962
- }
8963
- for (const limited of ordered.filter((c) => c.outcome === "rate-limited" && c.retryAfterMs && c.at !== void 0)) {
8964
- const next = ordered.find((c) => c.sequence > limited.sequence && c.service === limited.service && c.at !== void 0 && sameRequest(limited, c));
8965
- if (next && next.at - limited.at < limited.retryAfterMs * 0.9 && !covered(limited.service, "retry-after-ignored"))
8966
- out.push({
8967
- check: "retry-after-ignored",
8968
- service: limited.service,
8969
- resource: `${limited.method} ${limited.path}`,
8970
- calls: [limited.sequence, next.sequence],
8971
- finding: `${label(limited)} was retried after ${next.at - limited.at}ms although ${limited.service} asked to wait ${Math.round(limited.retryAfterMs / 1e3)}s (Retry-After)`,
8972
- impact: { kind: "reliability", count: 1, summary: "ignoring Retry-After prolongs rate limiting and can get the credential throttled or banned" },
8973
- ...next.source ? { source: next.source } : {},
8974
- fix: "respect-retry-after"
8975
- });
8976
- }
8977
- const unrecoveredBefore = (seq) => writes.filter((w) => w.sequence < seq && !announcementSeqs.has(w.sequence) && FAILED.includes(w.outcome) && w.outcome !== "lost-response" && !(w.outcome === "timeout" && w.committed) && !writes.some((r) => r.sequence > w.sequence && r.sequence < seq && sameRequest(w, r) && succeeded(r)));
8978
- for (const claim of claims.filter((c) => c.polarity === "success")) {
8979
- const failed = unrecoveredBefore(claim.sequence)[0], via = claim.via !== void 0 ? ordered.find((c) => c.sequence === claim.via) : void 0;
8980
- if (!failed || covered(via?.service ?? failed.service, "announce-after-failed-write")) continue;
8981
- out.push({
8982
- check: "announce-after-failed-write",
8983
- service: via?.service ?? failed.service,
8984
- resource: via ? `${via.method} ${via.path}` : "agent output",
8985
- calls: [failed.sequence, ...via ? [via.sequence] : []],
8986
- finding: `Your agent said "${claim.text.slice(0, 80)}"${via ? ` (${label(via)})` : ""} after ${label(failed)} failed (${faultWords(failed)}) and never succeeded`,
8987
- impact: impactOf(via ? [via] : [], 0, "customer-facing", "the agent reports work that never happened"),
8988
- ...claim.source ?? via?.source ? { source: claim.source ?? via?.source } : {},
8989
- fix: "confirm-before-announce"
8990
- });
8991
- break;
8992
- }
8993
- for (const claim of claims.filter((c) => c.polarity === "failure")) {
8994
- const later = writes.find((w) => w.sequence > claim.sequence && !announcementSeqs.has(w.sequence) && effects(w) > 0);
8995
- if (!later || covered(later.service, "write-after-reported-failure")) continue;
8996
- out.push({
8997
- check: "write-after-reported-failure",
8998
- service: later.service,
8999
- resource: `${later.method} ${later.path}`,
9000
- calls: [...claim.via ? [claim.via] : [], later.sequence],
9001
- finding: `Your agent reported "${claim.text.slice(0, 80)}" and then still sent ${label(later)}`,
9002
- impact: impactOf([later], 0, "data-integrity", "the system changed after the agent told someone it had not"),
9003
- ...later.source ? { source: later.source } : {}
9004
- });
9005
- break;
9006
- }
9007
- if (opts.readBack) for (const claim of claims.filter((c) => c.polarity === "success")) {
9008
- for (const w of writes.filter((w2) => w2.sequence < claim.sequence && w2.resourceId && w2.method !== "POST" && new RegExp(`(^|[^\\w-])${w2.resourceId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}([^\\w-]|$)`).test(claim.text))) {
9009
- const rb = opts.readBack(w);
9010
- if (!rb || covered(w.service, "claimed-change-unchanged")) continue;
9011
- const unchanged = w.method === "DELETE" ? rb.after !== void 0 : canonical3(stable(rb.before)) === canonical3(stable(rb.after));
9012
- if (!unchanged) continue;
9013
- out.push({
9014
- check: "claimed-change-unchanged",
9015
- service: w.service,
9016
- resource: `${w.method} ${w.path}`,
9017
- calls: [w.sequence, ...claim.via ? [claim.via] : []],
9018
- finding: `Your agent said "${claim.text.slice(0, 80)}", but ${w.service} ${w.path} is unchanged at read-back`,
9019
- impact: { kind: "data-integrity", count: 1, summary: `${w.resourcePath.split("/").filter((s) => s !== "{id}").pop() ?? "record"} ${w.resourceId} was reported changed but is not` },
9020
- ...claim.source ?? w.source ? { source: claim.source ?? w.source } : {},
9021
- fix: "confirm-before-announce"
9022
- });
9023
- break;
9024
- }
9025
- }
9026
- for (const failed of writes.filter((w) => FAILED.includes(w.outcome) && !(w.outcome === "timeout" && w.committed) && w.outcome !== "lost-response")) {
9027
- if (writes.some((r) => r.sequence > failed.sequence && sameRequest(failed, r) && succeeded(r))) continue;
9028
- const committed = writes.find((a) => a.sequence < failed.sequence && a.service !== failed.service && effects(a) > 0 && !announcementSeqs.has(a.sequence) && !isAnnouncement(a) && !writes.some((x) => x.sequence > failed.sequence && x.service === a.service && (x.resourceId ? x.resourceId === a.resourceId : x.resourcePath === a.resourcePath) && effects(x) > 0));
9029
- if (!committed || covered(committed.service, "partial-commit")) continue;
9030
- out.push({
9031
- check: "partial-commit",
9032
- service: committed.service,
9033
- resource: `${committed.method} ${committed.path}`,
9034
- calls: [committed.sequence, failed.sequence],
9035
- finding: `${label(committed)} was saved, then ${label(failed)} failed (${faultWords(failed)}) and nothing undid the first write`,
9036
- impact: impactOf([committed], 0, "data-integrity", `${committed.service} and ${failed.service} disagree: one recorded the change, the other did not`),
9037
- ...failed.source ? { source: failed.source } : {}
9038
- });
9039
- break;
9040
- }
9041
- return out;
9042
- }
9043
- function worldReadBack(ctx) {
9044
- return (c) => {
9045
- const find = (state) => (state?.[c.service]?.[c.resourcePath.replace(/\/\{id\}$/, "")] ?? []).find((r) => r && typeof r === "object" && String(r.id) === c.resourceId);
9046
- return { before: find(ctx.initialState), after: find(ctx.finalState) };
9047
- };
9048
- }
9049
- function genericWorldChecks(covers) {
9050
- const rules = ["retry-without-key", "announce-after-failed-write", "write-after-reported-failure", "claimed-change-unchanged", "partial-commit"];
9051
- return rules.map((rule) => ({
9052
- id: `generic.${rule}`,
9053
- title: GENERIC_TITLES[rule][0],
9054
- expected: GENERIC_TITLES[rule][1],
9055
- path: "/",
9056
- impact: rule === "announce-after-failed-write" ? "customer-facing" : rule === "retry-without-key" ? "reliability" : "data-integrity",
9057
- impactHint: GENERIC_TITLES[rule][1],
9058
- run(ctx) {
9059
- if (["openai", "anthropic", "google-oauth", "postgres"].includes(ctx.service.adapter ?? "")) return [];
9060
- const adapterOf = (name) => ctx.services.find((s) => s.name === name)?.adapter;
9061
- const calls = callsFromWorldEvents(ctx.events).filter((c) => !["openai", "anthropic", "google-oauth"].includes(adapterOf(c.service) ?? ""));
9062
- return genericChecks(calls, { readBack: worldReadBack(ctx), duplicateDelivery: ctx.duplicateDelivery, covered: (service, check) => check !== rule || covers(adapterOf(service), check) }).filter((v) => v.check === rule && v.service === ctx.service.name).map((v) => ({ path: v.resource.split(" ")[1] ?? "/", actual: { resource: v.resource, calls: v.calls }, finding: v.finding, impact: { kind: v.impact.kind, count: v.impact.count, ...v.impact.amount ? { amount: Math.round(v.impact.amount * 100), currency: v.impact.currency } : {} }, evidence: v.calls }));
9063
- }
9064
- }));
9065
- }
9066
- function proofFindings(violations, calls) {
9067
- return violations.map((v, i) => {
9068
- const involved = new Set(v.calls), first = calls.find((c) => c.sequence === v.calls[0]);
9069
- const kind = v.check === "duplicate-write" || v.check === "retry-without-key" ? "duplicate-effect" : v.check === "announce-after-failed-write" || v.check === "claimed-change-unchanged" ? "unconfirmed-announce" : v.check === "partial-commit" ? "partial-commit" : "changed-state";
9070
- const failed = calls.find((c) => involved.has(c.sequence) && FAILED.includes(c.outcome));
9071
- return {
9072
- id: `generic_${v.check.replace(/-/g, "_")}_${i + 1}`,
9073
- kind,
9074
- service: v.service,
9075
- path: v.resource.split(" ")[1] ?? "/",
9076
- title: v.finding,
9077
- records: [],
9078
- timeline: calls.slice(0, 200).map((c) => ({ sequence: c.sequence, service: c.service, operation: c.isWrite ? "write" : "read", path: c.path, detail: `${c.method} ${c.outcome}${c.idempotencyKey ? " keyed" : ""}`, ...c.source ? { source: `${c.source.file}:${c.source.line}` } : {}, highlight: involved.has(c.sequence) })),
9079
- ...v.source ? { source: v.source } : {},
9080
- ...v.writeSites?.length ? { writeSites: v.writeSites } : {},
9081
- ...failed ? { fault: { type: failed.outcome, service: failed.service, path: failed.path, triggered: true } } : {},
9082
- ...kind === "duplicate-effect" ? { expected: 1, actual: Math.max(2, v.impact.count !== void 0 ? v.impact.count + 1 : 2) } : {},
9083
- adapter: first?.tier ?? "generic",
9084
- ...v.fix ? { hint: v.fix } : {},
9085
- ...failed?.source && v.check === "announce-after-failed-write" ? { relatedSource: { file: failed.source.file, line: failed.source.line } } : {}
9086
- };
9087
- });
9088
- }
9089
- var WRITE_METHODS, READ_LIKE, MODEL_HOST, VOLATILE, KEY_HEADERS, KEY_FIELDS, digest, stable, idLike, outcomeOf, parseSource, SUCCESS, FAILURE, TEXT_FIELDS, MESSAGING, polarityOf, RECIPIENT, isAnnouncement, AMOUNT, times, FAILED, AMBIGUOUS, label, sameRequest, succeeded, effects, sites, groupsOf, GENERIC_TITLES;
9090
- var init_generic_calls = __esm({
9091
- "src/runtime/generic-calls.ts"() {
9092
- "use strict";
9093
- init_run_summary();
9094
- WRITE_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
9095
- READ_LIKE = /\/(search|query|lookup|count|batch\/read|completions|embeddings|responses|count_tokens|graphql\/query)$/i;
9096
- MODEL_HOST = /(^|\.)(openai\.com|anthropic\.com|generativelanguage\.googleapis\.com|mistral\.ai|groq\.com|cohere\.ai)$/i;
9097
- VOLATILE = /^(id|ts|created|created_at|updated_at|createdAt|updatedAt|timestamp|request_id|requestId|nonce|uuid|sequence|object|livemode)$|_at$/;
9098
- KEY_HEADERS = ["idempotency-key", "x-idempotency-key", "x-request-id", "x-amz-client-token"];
9099
- KEY_FIELDS = /^(idempotency_?key|ClientToken|ClientRequestToken|MessageDeduplicationId|client_token|request_id)$/i;
9100
- digest = (value3) => `sha256:${createHash9("sha256").update(typeof value3 === "string" ? value3 : canonical3(value3)).digest("hex").slice(0, 16)}`;
9101
- stable = (value3) => Array.isArray(value3) ? value3.map(stable) : value3 && typeof value3 === "object" ? Object.fromEntries(Object.entries(value3).filter(([k]) => !VOLATILE.test(k) && !KEY_FIELDS.test(k)).map(([k, v]) => [k, stable(v)])) : value3;
9102
- idLike = (segment) => /^\d+$/.test(segment) || /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(segment) || segment.length >= 3 && /\d/.test(segment) && /^[A-Za-z0-9_\-:.]+$/.test(segment) && !/^v\d+(\.\d+)*$/i.test(segment) && !/^\d{4}-\d{2}-\d{2}$/.test(segment) && !/^[A-Za-z]+\.(json|xml)$/.test(segment);
9103
- outcomeOf = (status) => status === void 0 ? "ok" : status === 401 || status === 403 ? "unauthorized" : status === 429 ? "rate-limited" : status >= 500 ? "server-error" : status >= 400 ? "client-error" : "ok";
9104
- parseSource = (s) => {
9105
- if (!s) return;
9106
- if (typeof s !== "string") return s;
9107
- try {
9108
- const v = JSON.parse(s);
9109
- return typeof v?.file === "string" ? v : void 0;
9110
- } catch {
9111
- return;
9112
- }
9113
- };
9114
- SUCCESS = /\b(done|complete[d]?|success(ful(ly)?)?|refunded|closed|created|updated|sent|processed|confirmed|welcome|paid|invoiced|won|approved|resolved|scheduled|saved|booked|cancell?ed|shipped|delivered)\b/i;
9115
- FAILURE = /\b(fail(ed|ure)?|error|unable|could ?n[o']t|cannot|can't|did ?n[o']t|not (?:been )?(?:\w+ed)|retry(ing)?|escalat\w*|pending|try again|sorry)\b/i;
9116
- TEXT_FIELDS = /^(text|body|message|content|subject|summary|description|Body|Message|html|markdown|note|comment)$/;
9117
- MESSAGING = /(message|messages|sms|mail|email|emails|notification|notifications|notify|send|postMessage|comments?|reply|replies)(\.json)?$/i;
9118
- polarityOf = (text3) => FAILURE.test(text3) ? "failure" : SUCCESS.test(text3) ? "success" : "neutral";
9119
- RECIPIENT = /^(to|recipient|recipients|email|phone|phone_number|channel|cc|bcc|To|chat_id|user_id)$/;
9120
- isAnnouncement = (c) => c.isWrite && !!textOf(c.body) && (MESSAGING.test(c.path) || recipientsOf(c.body).length > 0);
9121
- AMOUNT = /^(amount|total|price|unit_amount|amount_total|grand_total|subtotal|value|amount_cents|amount_minor|total_cents|price_cents)$/i;
9122
- times = (n) => n === 2 ? "twice" : `${n} times`;
9123
- FAILED = ["server-error", "lost-response", "timeout", "client-error", "unauthorized", "rate-limited"];
9124
- AMBIGUOUS = ["server-error", "lost-response", "timeout"];
9125
- label = (c) => `${c.method} ${c.path} on ${c.service}`;
9126
- sameRequest = (a, b) => a.service === b.service && a.method === b.method && a.resourcePath === b.resourcePath && (a.method === "POST" || a.resourceId === b.resourceId) && (!a.requestDigest || !b.requestDigest || a.requestDigest === b.requestDigest);
9127
- succeeded = (c) => c.outcome === "ok" || c.outcome === "replayed";
9128
- effects = (c) => c.committed === false || c.outcome === "replayed" || c.outcome === "blocked" ? 0 : (c.committed || c.outcome === "ok" ? 1 : 0) * (c.duplicated ? 2 : 1);
9129
- sites = (calls) => [...new Map(calls.filter((c) => c.source).map((c) => [`${c.source.file}:${c.source.line}`, c.source])).values()];
9130
- groupsOf = (writes) => {
9131
- const groups2 = [];
9132
- for (const c of writes) {
9133
- const g = groups2.find((g2) => sameRequest(g2[0], c));
9134
- if (g) g.push(c);
9135
- else groups2.push([c]);
9136
- }
9137
- return groups2;
9138
- };
9139
- GENERIC_TITLES = {
9140
- "duplicate-write": ["World-changing calls take effect once", "each create, charge or send is applied once, even under retries and redelivery"],
9141
- "retry-without-key": ["Retries after a fault reuse the idempotency key", "a write retried after an ambiguous failure carries the same idempotency key"],
9142
- "retry-after-ignored": ["Rate-limited calls wait for Retry-After", "a 429 is retried no sooner than its Retry-After"],
9143
- "announce-after-failed-write": ["Success is announced only after the write succeeded", "the agent claims success only when every write it depends on succeeded"],
9144
- "write-after-reported-failure": ["No writes after the agent reported failure", "after the agent reports a failure it changes nothing else"],
9145
- "claimed-change-unchanged": ["Claimed changes are visible at read-back", "every resource the agent says it changed is changed when read back"],
9146
- "partial-commit": ["Multi-service writes commit together or compensate", "when a later write fails, earlier writes in other services are undone"]
9147
- };
9148
- }
9149
- });
9150
-
9151
9169
  // src/runtime/default-checks.ts
9152
9170
  function addedRows(initial, final) {
9153
9171
  const rows2 = (list4) => list4.filter((r) => !!r && typeof r === "object" && !Array.isArray(r));
@@ -9238,7 +9256,7 @@ function defaultChecksFor(services, opts = {}) {
9238
9256
  }
9239
9257
  function runDefaultChecks(input) {
9240
9258
  const services = input.spec.services.map((s) => ({ name: s.name, adapter: s.adapter ?? "json-collection", collections: s.collections }));
9241
- return defaultChecksFor(services, { postgres: !!input.database && !!input.spec.postgres }).map(({ service, check }) => {
9259
+ return defaultChecksFor(services, { postgres: !!input.database }).map(({ service, check }) => {
9242
9260
  const violations = check.run({ service, services, initialState: input.initialState, finalState: input.finalState, events: input.events, fault: input.fault, database: input.database, duplicateDelivery: input.duplicateDelivery });
9243
9261
  const base = { id: `default.${check.id}.${service.name}`, kind: "default", check: check.id, title: check.title, service: service.name, expected: check.expected };
9244
9262
  if (!violations.length) return { ...base, path: check.path, passed: true, actual: "no violations" };
@@ -9273,7 +9291,9 @@ function defaultFaultMatrix(services, opts = {}) {
9273
9291
  presets.push(
9274
9292
  { name: `${base}-timeout`, label: `${who} ${path2}: write saved, reply lost (timeout after write)`, type: "timeout-after-write", service: s.name, path: path2, supported: true, fault: { service: s.name, path: path2, type: "timeout-after-write", delayMs } },
9275
9293
  { name: `${base}-5xx`, label: `${who} ${path2}: first request answers 500, nothing saved`, type: "server-error", service: s.name, path: path2, supported: true, fault: { service: s.name, path: path2, type: "server-error", count: 1, schedule: "first" } },
9276
- { name: `${base}-slow`, label: `${who} ${path2}: request applied, reply slower than the client timeout`, type: "slow-response", service: s.name, path: path2, supported: true, fault: { service: s.name, path: path2, type: "slow-response", delayMs, count: 1, schedule: "first" } }
9294
+ { name: `${base}-slow`, label: `${who} ${path2}: request applied, reply slower than the client timeout`, type: "slow-response", service: s.name, path: path2, supported: true, fault: { service: s.name, path: path2, type: "slow-response", delayMs, count: 1, schedule: "first" } },
9295
+ // An outage outlasts the client's own retries (Stripe's SDK retries a 500): the action really fails.
9296
+ { name: `${base}-down`, label: `${who} ${path2}: service down, every attempt answers 500`, type: "server-error", service: s.name, path: path2, supported: true, fault: { service: s.name, path: path2, type: "server-error", count: 20, schedule: "first" } }
9277
9297
  );
9278
9298
  }
9279
9299
  }
@@ -9285,7 +9305,7 @@ function defaultFaultMatrix(services, opts = {}) {
9285
9305
  entries.push({ name: `postgres-${type}`, label: `Postgres ${type}`, type, service: "postgres", supported: false, reason: "SQL fault injection is not implemented; Postgres default checks still run on Docker runs with a disposable database" });
9286
9306
  return entries;
9287
9307
  }
9288
- var PROVIDER, displayName, rowsOf, VOLATILE2, volatileKey, canonical4, contentSignature, writeSequences, times2, money, stripeRefundOnce, stripeNoDuplicatePayment, stripeIdempotentRetries, NEGATIVE, gmailText, postgresUpdateApplied, postgresNoDuplicateInsert, NOT_EFFECTS, genericRepeat, DEFAULT_CHECKS, VENDOR_COVERS, registryFor, refOf, WRITE_PATHS, slug;
9308
+ var PROVIDER, displayName, rowsOf, VOLATILE2, volatileKey, canonical4, contentSignature, writeSequences, times2, money, stripeRefundOnce, stripeNoDuplicatePayment, stripeIdempotentRetries, NEGATIVE, gmailText, TARGETED, postgresUpdateApplied, postgresNoDuplicateInsert, RELATIVE_SET, postgresNoRepeatedRelativeUpdate, UNSCOPED, postgresNoUnscopedDestructive, NOT_EFFECTS, genericRepeat, DEFAULT_CHECKS, VENDOR_COVERS, registryFor, refOf, WRITE_PATHS, slug;
9289
9309
  var init_default_checks = __esm({
9290
9310
  "src/runtime/default-checks.ts"() {
9291
9311
  "use strict";
@@ -9298,9 +9318,14 @@ var init_default_checks = __esm({
9298
9318
  };
9299
9319
  rowsOf = (state, service, path2) => (state?.[service]?.[path2] ?? []).filter((r) => !!r && typeof r === "object" && !Array.isArray(r));
9300
9320
  VOLATILE2 = /* @__PURE__ */ new Set(["id", "ts", "created", "created_at", "updated_at", "inserted_at", "createdAt", "updatedAt", "internalDate", "historyId", "threadId", "number", "iid", "latest_charge", "object", "sequence", "uuid"]);
9301
- volatileKey = (key3) => VOLATILE2.has(key3) || /_at$|At$/.test(key3);
9321
+ volatileKey = (key3) => VOLATILE2.has(key3) || /_at$|At$/.test(key3) || /^(?:sid|guid|etag|uri|self|href)$/i.test(key3) || /^date_|_date$|^(?:created|updated|modified|sent)(?:_on|_time|_date)?$/i.test(key3) || /^(?:ending|starting|running|resulting)_?balance$|^balance_?after$/i.test(key3);
9302
9322
  canonical4 = (value3) => Array.isArray(value3) ? `[${value3.map(canonical4).join(",")}]` : value3 && typeof value3 === "object" ? `{${Object.keys(value3).sort().map((k) => `${JSON.stringify(k)}:${canonical4(value3[k])}`).join(",")}}` : JSON.stringify(value3 ?? null);
9303
- contentSignature = (row) => canonical4(Object.fromEntries(Object.entries(row).filter(([k]) => !volatileKey(k))));
9323
+ contentSignature = (row, collection) => {
9324
+ const type = (collection?.split("/").filter(Boolean).pop() ?? "").toLowerCase().replace(/[^a-z]/g, "").replace(/ies$/, "y").replace(/s$/, "");
9325
+ const ownId = (k) => !!type && k.toLowerCase().replace(/[^a-z]/g, "") === type + "id";
9326
+ const own = Object.entries(row).filter(([k, v]) => (volatileKey(k) || ownId(k)) && typeof v === "string" && v.length >= 6).map(([, v]) => v);
9327
+ return canonical4(Object.fromEntries(Object.entries(row).filter(([k, v]) => !volatileKey(k) && !ownId(k) && !own.some((id2) => JSON.stringify(v ?? null).includes(id2)))));
9328
+ };
9304
9329
  writeSequences = (ctx, service, ids) => ctx.events.filter((e) => e.service === service && e.operation === "write" && ids.includes(e.record?.id)).map((e) => e.sequence);
9305
9330
  times2 = (n) => n === 2 ? "twice" : `${n} times`;
9306
9331
  money = (amount, currency) => formatMoney({ amount: amount / 100, currency: currency.toUpperCase() });
@@ -9309,6 +9334,7 @@ var init_default_checks = __esm({
9309
9334
  title: "Each charge refunded at most once per request",
9310
9335
  path: "/v1/refunds",
9311
9336
  coversDuplicates: true,
9337
+ duplicatePaths: ["/v1/refunds"],
9312
9338
  expected: "each charge refunded at most once for the same amount and reason; refund total \u2264 charge amount",
9313
9339
  impact: "money",
9314
9340
  impactHint: "duplicated refund amount is money paid out twice",
@@ -9343,6 +9369,7 @@ var init_default_checks = __esm({
9343
9369
  title: "No duplicate charges, customers or subscriptions for one request",
9344
9370
  path: "/v1/payment_intents",
9345
9371
  coversDuplicates: true,
9372
+ duplicatePaths: ["/v1/payment_intents", "/v1/charges", "/v1/customers", "/v1/subscriptions"],
9346
9373
  expected: "one payment intent per amount/currency/customer/payment method and one customer per email",
9347
9374
  impact: "money",
9348
9375
  impactHint: "a duplicated succeeded payment charges the customer twice",
@@ -9416,6 +9443,7 @@ var init_default_checks = __esm({
9416
9443
  const header3 = (name) => headers.find((h2) => h2.name?.toLowerCase() === name)?.value ?? "";
9417
9444
  return { to: header3("to"), subject: header3("subject"), body: String(r.payload?.body?.data ?? r.snippet ?? "") };
9418
9445
  };
9446
+ TARGETED = /\bwhere\b[\s\S]*=\s*\$\d/i;
9419
9447
  postgresUpdateApplied = {
9420
9448
  id: "postgres.update-applied",
9421
9449
  title: "Updates the agent ran actually changed rows",
@@ -9424,7 +9452,7 @@ var init_default_checks = __esm({
9424
9452
  impact: "data-integrity",
9425
9453
  impactHint: "the agent believes a record changed when it did not",
9426
9454
  run(ctx) {
9427
- return (ctx.database?.statements ?? []).filter((st) => /^(UPDATE|DELETE)$/i.test(st.command ?? "") && st.count === 0).map((st) => {
9455
+ return (ctx.database?.statements ?? []).filter((st) => st.count === 0 && (/^UPDATE$/i.test(st.command ?? "") || !ctx.duplicateDelivery && /^DELETE$/i.test(st.command ?? "") && TARGETED.test(st.text))).map((st) => {
9428
9456
  const table4 = /^\s*(?:update|delete\s+from)\s+(?:only\s+)?"?([\w.]+)"?/i.exec(st.text)?.[1] ?? "a table";
9429
9457
  return {
9430
9458
  path: `/${table4}`,
@@ -9448,7 +9476,7 @@ var init_default_checks = __esm({
9448
9476
  if (!ctx.database?.final) return out;
9449
9477
  for (const table4 of ctx.database.final.tables) {
9450
9478
  const before = ctx.database.initial.tables.find((t) => t.name === table4.name)?.rows ?? [];
9451
- for (const group of groups(addedRows(before, table4.rows), contentSignature))
9479
+ for (const group of groups(addedRows(before, table4.rows), (r) => contentSignature(r, table4.name)))
9452
9480
  out.push({
9453
9481
  path: `/${table4.name}`,
9454
9482
  actual: { table: table4.name, rows: group.length, row: group[0] },
@@ -9459,6 +9487,55 @@ var init_default_checks = __esm({
9459
9487
  return out;
9460
9488
  }
9461
9489
  };
9490
+ RELATIVE_SET = /\bset\b[\s\S]*?"?(\w+)"?\s*=\s*(?:"?\w+"?\.)?"?\1"?\s*[-+]/i;
9491
+ postgresNoRepeatedRelativeUpdate = {
9492
+ id: "postgres.no-repeated-relative-update",
9493
+ title: "A redelivered trigger does not apply a balance change twice",
9494
+ path: "/",
9495
+ coversDuplicates: true,
9496
+ expected: "an UPDATE that adds to or subtracts from a value runs once when the same trigger arrives twice",
9497
+ impact: "money",
9498
+ impactHint: "credits, balances or counters change twice for one event",
9499
+ run(ctx) {
9500
+ if (!ctx.duplicateDelivery) return [];
9501
+ const applied = (ctx.database?.statements ?? []).filter((st) => /^UPDATE$/i.test(st.command ?? "") && (st.count ?? 0) > 0 && RELATIVE_SET.test(st.text));
9502
+ const byText = /* @__PURE__ */ new Map();
9503
+ for (const st of applied) byText.set(st.text, (byText.get(st.text) ?? 0) + 1);
9504
+ return [...byText].filter(([, n]) => n >= 2).map(([text3, n]) => {
9505
+ const table4 = /^\s*update\s+(?:only\s+)?"?([\w.]+)"?/i.exec(text3)?.[1] ?? "a table", column = RELATIVE_SET.exec(text3)?.[1] ?? "a value";
9506
+ return {
9507
+ path: `/${table4}`,
9508
+ actual: { statement: text3.slice(0, 200), applied: n },
9509
+ finding: `Your agent changed ${table4}.${column} ${times2(n)} when the same trigger was delivered twice`,
9510
+ impact: { count: n - 1 }
9511
+ };
9512
+ });
9513
+ }
9514
+ };
9515
+ UNSCOPED = /^\s*(?:(delete\s+from|update)\s+(?:only\s+)?"?([\w.]+)"?(?![\s\S]*\bwhere\b)|(truncate)(?:\s+table)?\s+"?([\w.]+)"?|(drop)\s+(?:table|schema|database)\s+(?:if\s+exists\s+)?"?([\w.]+)"?)/i;
9516
+ postgresNoUnscopedDestructive = {
9517
+ id: "postgres.no-unscoped-destructive",
9518
+ title: "No statement wipes or rewrites a whole table",
9519
+ path: "/",
9520
+ expected: "every DELETE and UPDATE is limited by a WHERE clause; no TRUNCATE or DROP",
9521
+ impact: "data-integrity",
9522
+ impactHint: "every row in the table is deleted or overwritten, not just the ones the action is about",
9523
+ run(ctx) {
9524
+ const out = [];
9525
+ for (const st of ctx.database?.statements ?? []) {
9526
+ const m = UNSCOPED.exec(st.text);
9527
+ if (!m) continue;
9528
+ const verb = (m[1] ?? m[3] ?? m[5]).toUpperCase().replace(/\s+FROM$/, ""), table4 = m[2] ?? m[4] ?? m[6];
9529
+ out.push({
9530
+ path: `/${table4}`,
9531
+ actual: { statement: st.text.slice(0, 200), rowsAffected: st.count ?? null },
9532
+ finding: verb === "DROP" ? `Your agent dropped ${table4}` : verb === "TRUNCATE" ? `Your agent emptied the whole ${table4} table` : `Your agent ran ${verb} on every row of ${table4} (no WHERE clause)`,
9533
+ impact: { count: 1 }
9534
+ });
9535
+ }
9536
+ return out;
9537
+ }
9538
+ };
9462
9539
  NOT_EFFECTS = /* @__PURE__ */ new Set(["openai", "anthropic", "google-oauth"]);
9463
9540
  genericRepeat = {
9464
9541
  id: "generic.no-repeat-after-fault",
@@ -9469,11 +9546,13 @@ var init_default_checks = __esm({
9469
9546
  impactHint: "the same record exists twice downstream",
9470
9547
  run(ctx) {
9471
9548
  const s = ctx.service.name, out = [];
9472
- if (NOT_EFFECTS.has(ctx.service.adapter ?? "") || registryFor(ctx.service.adapter).some((c) => c.coversDuplicates)) return out;
9549
+ const covering = registryFor(ctx.service.adapter).filter((c) => c.coversDuplicates);
9550
+ if (NOT_EFFECTS.has(ctx.service.adapter ?? "") || covering.some((c) => !c.duplicatePaths)) return out;
9551
+ const judged = new Set(covering.flatMap((c) => c.duplicatePaths ?? []));
9473
9552
  const faults = ctx.events.filter((e) => e.operation === "fault").map((e) => e.sequence);
9474
9553
  if (!faults.length && !ctx.duplicateDelivery) return out;
9475
- for (const path2 of Object.keys(ctx.finalState?.[s] ?? {})) {
9476
- for (const group of groups(addedRows(rowsOf(ctx.initialState, s, path2), rowsOf(ctx.finalState, s, path2)), contentSignature)) {
9554
+ for (const path2 of Object.keys(ctx.finalState?.[s] ?? {}).filter((p) => !judged.has(p))) {
9555
+ for (const group of groups(addedRows(rowsOf(ctx.initialState, s, path2), rowsOf(ctx.finalState, s, path2)), (r) => contentSignature(r, path2))) {
9477
9556
  const seq = writeSequences(ctx, s, group.map((r) => r.id));
9478
9557
  if (!ctx.duplicateDelivery && seq.length && !faults.some((f) => f < Math.max(...seq))) continue;
9479
9558
  const label2 = path2.split("/").filter(Boolean).pop() ?? "record";
@@ -9493,7 +9572,7 @@ var init_default_checks = __esm({
9493
9572
  stripe: [stripeRefundOnce, stripeNoDuplicatePayment, stripeIdempotentRetries],
9494
9573
  slack: messageChecks("slack", "/messages"),
9495
9574
  gmail: messageChecks("gmail", "/gmail/v1/users/me/messages"),
9496
- postgres: [postgresUpdateApplied, postgresNoDuplicateInsert],
9575
+ postgres: [postgresUpdateApplied, postgresNoDuplicateInsert, postgresNoRepeatedRelativeUpdate, postgresNoUnscopedDestructive],
9497
9576
  "*": [genericRepeat]
9498
9577
  };
9499
9578
  VENDOR_COVERS = { "retry-without-key": /\.idempotent-retries$/, "announce-after-failed-write": /\.announce-after-success$/ };
@@ -9720,7 +9799,7 @@ function twinRoutes(services, world, models) {
9720
9799
  continue;
9721
9800
  }
9722
9801
  if (!credential || !PROVIDER_HOSTS[adapter] || models && (adapter === "openai" || adapter === "anthropic")) continue;
9723
- for (const entry of PROVIDER_HOSTS[adapter]) for (const host of entry.hosts) if (!routes2.some((r) => r.host === host && r.pathPrefix === entry.pathPrefix)) routes2.push({ host, ...entry.pathPrefix ? { pathPrefix: entry.pathPrefix } : {}, ...entry.strip ? { strip: entry.strip } : {}, ...entry.add ? { add: entry.add } : {}, target: credential.endpoint, token: credential.token, auth: entry.auth, service: service.name });
9802
+ for (const entry of PROVIDER_HOSTS[adapter]) for (const host of entry.hosts) if (!routes2.some((r) => r.host === host && r.pathPrefix === entry.pathPrefix)) routes2.push({ host, ...entry.suffix ? { suffix: true } : {}, ...entry.pathPrefix ? { pathPrefix: entry.pathPrefix } : {}, ...entry.strip ? { strip: entry.strip } : {}, ...entry.add ? { add: entry.add } : {}, target: credential.endpoint, token: credential.token, auth: entry.auth, service: service.name });
9724
9803
  }
9725
9804
  if (models) for (const provider of ["openai", "anthropic"]) for (const entry of PROVIDER_HOSTS[provider]) for (const host of entry.hosts) routes2.push({ host, target: models.targets[provider].endpoint, token: models.targets[provider].token, auth: entry.auth, service: `model:${provider}` });
9726
9805
  return routes2;
@@ -9822,7 +9901,13 @@ var init_twin_routing = __esm({
9822
9901
  linear: [{ hosts: ["api.linear.app"], auth: "bearer" }],
9823
9902
  notion: [{ hosts: ["api.notion.com"], auth: "bearer" }],
9824
9903
  hubspot: [{ hosts: ["api.hubapi.com"], auth: "bearer" }],
9825
- twilio: [{ hosts: ["api.twilio.com"], auth: "bearer" }]
9904
+ twilio: [{ hosts: ["api.twilio.com"], auth: "bearer" }],
9905
+ // Hand-built twins reached on a customer's own subdomain.
9906
+ zendesk: [{ hosts: ["zendesk.com"], suffix: true, auth: "bearer" }],
9907
+ jira: [{ hosts: ["atlassian.net"], suffix: true, auth: "bearer" }],
9908
+ shopify: [{ hosts: ["myshopify.com"], suffix: true, auth: "bearer" }],
9909
+ gitlab: [{ hosts: ["gitlab.com"], auth: "bearer" }],
9910
+ datadog: [{ hosts: ["api.datadoghq.com", "api.datadoghq.eu", "api.us5.datadoghq.com"], auth: "bearer" }]
9826
9911
  };
9827
9912
  KNOWN_PROVIDER_SUFFIXES = {
9828
9913
  "openai.com": "openai",
@@ -9875,11 +9960,16 @@ const SECRET=['authorization','x-api-key','cookie','proxy-authorization','host']
9875
9960
  function rewrite(r,p){if(r.strip&&p.startsWith(r.strip))p=p.slice(r.strip.length)||'/';if(r.add&&!p.startsWith(r.add))p=r.add+(p==='/'?'':p);return p;}
9876
9961
  function credential(r){return r.auth==='passthrough'?['x-agenttwin-token',r.token]:r.auth==='x-api-key'?['x-api-key',r.token]:['authorization','Bearer '+r.token];}
9877
9962
  const removed=r=>r.auth==='passthrough'?['host']:SECRET;
9963
+ // The caller's own timeout or abort ends a routed request exactly when it would against the real service: the app's
9964
+ // AbortSignal.timeout is what makes a lost reply turn into a retry, so it must never be lost on the way to a twin.
9965
+ function abortable(signal,promise){if(!signal)return promise;if(signal.aborted)return Promise.reject(signal.reason);return new Promise((resolve,reject)=>{const stop=()=>reject(signal.reason);signal.addEventListener('abort',stop,{once:true});promise.then(v=>{signal.removeEventListener('abort',stop);resolve(v);},e=>{signal.removeEventListener('abort',stop);reject(e);});});}
9878
9966
  const originalFetch=globalThis.fetch;
9879
9967
  if(originalFetch)globalThis.fetch=async function(input,init){
9880
9968
  let url;try{url=new URL(typeof input==='string'||input instanceof URL?String(input):input.url);}catch{return originalFetch(input,init);}
9881
9969
  if((url.protocol!=='http:'&&url.protocol!=='https:')||loopback(url.hostname))return originalFetch(input,init);
9882
9970
  const method=String(init?.method||input?.method||'GET').toUpperCase(),r=match(url.hostname,url.pathname);
9971
+ // Web fonts a framework downloads while it renders (next/font): an empty stylesheet or font, so rendering goes on offline.
9972
+ if(!r&&/^fonts\.(googleapis|gstatic)\.com$/.test(bare(url.hostname)))return new Response('',{status:200,headers:{'content-type':/googleapis/.test(url.hostname)?'text/css':'font/woff2'}});
9883
9973
  if(!r)throw blocked('fetch',url.hostname,url.port||(url.protocol==='https:'?443:80),method);
9884
9974
  if(process.env.AGENTTWIN_DEBUG_ROUTES)console.error('route-match '+url.hostname+' auth='+r.auth+' service='+r.service);
9885
9975
  const request=new Request(input,init),headers=new Headers(request.headers);
@@ -9889,7 +9979,7 @@ if(originalFetch)globalThis.fetch=async function(input,init){
9889
9979
  // Forward the body as bytes: copying a keepalive Request whose body is a stream throws in Node's fetch (Upstash's
9890
9980
  // client sets keepalive on every call).
9891
9981
  const body=request.body===null?undefined:Buffer.from(await request.arrayBuffer());
9892
- return originalFetch(r.target+rewrite(r,url.pathname)+url.search,{method:request.method,headers,...(body===undefined?{}:{body}),redirect:'manual',signal:request.signal});
9982
+ return abortable(init?.signal??(input instanceof Request?input.signal:undefined),originalFetch(r.target+rewrite(r,url.pathname)+url.search,{method:request.method,headers,...(body===undefined?{}:{body}),redirect:'manual',signal:request.signal}));
9893
9983
  };
9894
9984
  const originalHttpRequest=http.request;
9895
9985
  for(const [mod,scheme] of [[http,'http'],[https,'https']]){
@@ -9904,6 +9994,15 @@ for(const [mod,scheme] of [[http,'http'],[https,'https']]){
9904
9994
  if(loopback(host))return original.apply(this,args);
9905
9995
  const method=String(options.method||'GET').toUpperCase(),requestPath=options.path||(url?url.pathname+url.search:'/');
9906
9996
  const r=match(host,String(requestPath).split('?')[0]);
9997
+ // Web fonts (next/font) over http(s): an empty answer from an in-memory socket, so rendering goes on offline.
9998
+ if(!r&&/^fonts\.(googleapis|gstatic)\.com$/.test(bare(host))){
9999
+ const {Duplex}=require('node:stream'),type=/googleapis/.test(host)?'text/css':'font/woff2';let sent=false;
10000
+ const socket=new Duplex({read(){},write(chunk,enc,done){if(!sent&&/\r\n\r\n/.test(String(chunk))){sent=true;this.push('HTTP/1.1 200 OK\r\nContent-Type: '+type+'\r\nContent-Length: 0\r\nConnection: close\r\n\r\n');this.push(null);}done();}});
10001
+ socket.setTimeout=()=>socket;socket.setNoDelay=()=>socket;socket.setKeepAlive=()=>socket;socket.ref=()=>socket;socket.unref=()=>socket;
10002
+ const {agent:_a,...plain}=options;
10003
+ const req=originalHttpRequest({...plain,method,path:requestPath,host:'127.0.0.1',port:9,createConnection:()=>socket},callback);
10004
+ return req;
10005
+ }
9907
10006
  if(!r)throw blocked(scheme,host,options.port||url?.port||(scheme==='https'?443:80),method);
9908
10007
  const target=new URL(r.target),headers={};
9909
10008
  const given=options.headers||{};
@@ -10041,6 +10140,7 @@ async function startPostgresEngine(options = {}) {
10041
10140
  const createOptions = (extra = {}) => ({ ...extra, ...Object.keys(extensions).length ? { extensions } : {} });
10042
10141
  let db = await PGlite.create(createOptions());
10043
10142
  const version = String((await db.query("show server_version")).rows[0]?.server_version ?? "17");
10143
+ const statements = [];
10044
10144
  const events = [], unsupported3 = [], gate = new FaultGate("postgres", events), listeners = [];
10045
10145
  const lockWaitMs = options.lockWaitMs ?? 5e3;
10046
10146
  const conns = /* @__PURE__ */ new Set();
@@ -10141,6 +10241,19 @@ async function startPostgresEngine(options = {}) {
10141
10241
  const outputs = [];
10142
10242
  for (const m of prepared) outputs.push(await raw(msg(m.type, m.body)));
10143
10243
  const out = Buffer.concat(outputs), { tags, status, failed } = scan(out);
10244
+ const executed = batch.flatMap((m) => {
10245
+ if (m.type === "Q") return [m.body.toString("utf8", 0, m.body.length - 1)];
10246
+ if (m.type !== "B") return [];
10247
+ const pEnd = m.body.indexOf(0), sEnd = m.body.indexOf(0, pEnd + 1), stmt = m.body.toString("utf8", pEnd + 1, sEnd);
10248
+ const q3 = stmt ? conn.names.get(stmt) : conn.unnamed;
10249
+ return q3 ? [q3] : [];
10250
+ });
10251
+ const cmdTags = tags.filter((t) => !/^(BEGIN|COMMIT|ROLLBACK|SET)$/.test(t));
10252
+ executed.forEach((text3, i) => {
10253
+ if (!isWriteSql(text3) || statements.length >= 1e3) return;
10254
+ const tag = executed.length === cmdTags.length ? cmdTags[i] : void 0, m = tag ? /^(\w+)(?:\s+\d+)?\s+(\d+)$/.exec(tag) : null;
10255
+ statements.push({ text: text3.slice(0, 2048), ...tag ? { command: tag.split(" ")[0] } : {}, ...m ? { count: Number(m[2]) } : {} });
10256
+ });
10144
10257
  for (const t of writeTables) conn.txnTables.add(t);
10145
10258
  const binds = batch.filter((m) => m.type === "B").map((m) => {
10146
10259
  const pEnd = m.body.indexOf(0), sEnd = m.body.indexOf(0, pEnd + 1), stmt = m.body.toString("utf8", pEnd + 1, sEnd);
@@ -10377,6 +10490,7 @@ async function startPostgresEngine(options = {}) {
10377
10490
  startupMs: Date.now() - started,
10378
10491
  events,
10379
10492
  unsupported: unsupported3,
10493
+ statements,
10380
10494
  env: { DATABASE_URL: url, POSTGRES_URL: url, PG_URL: url, PGHOST: "127.0.0.1", PGPORT: String(port), PGUSER: "agenttwin", PGPASSWORD: "agenttwin", PGDATABASE: "agenttwin", PGSSLMODE: "disable" },
10381
10495
  get faultTriggered() {
10382
10496
  return gate.triggered;
@@ -10545,6 +10659,7 @@ async function startLocalEngines(app, spec) {
10545
10659
  const final = await snapshotPublicTables(postgres2).catch(() => void 0);
10546
10660
  return final && { engine: "embedded-postgres", extensions: [...spec.postgres?.extensions ?? []], initial: initialTables, final };
10547
10661
  },
10662
+ statements: () => [...postgres2?.statements ?? []],
10548
10663
  unsupported: () => started.flatMap((e) => e.unsupported.map((u) => `${e.kind}: ${u}`)),
10549
10664
  stop
10550
10665
  };
@@ -10781,9 +10896,10 @@ async function executeLocal(app, spec, signal, existingWorld, seed, extraEnv = {
10781
10896
  }
10782
10897
  const assertions = world.assertions();
10783
10898
  const evaluation = evaluateState(spec, initialState, world.state, world.events);
10784
- const defaultChecks = runDefaultChecks({ spec, initialState, finalState: world.state, events: world.events, fault: spec.fault ? { ...spec.fault, triggered: world.faultTriggered } : null });
10785
10899
  const infrastructureAssertions = await engines2.evaluate();
10786
10900
  const embeddedDatabase = await engines2.databaseEvidence();
10901
+ const database = embeddedDatabase ? { initial: embeddedDatabase.initial, final: embeddedDatabase.final, statements: engines2.statements() } : void 0;
10902
+ const defaultChecks = runDefaultChecks({ spec, initialState, finalState: world.state, events: world.events, fault: spec.fault ? { ...spec.fault, triggered: world.faultTriggered } : null, ...database ? { database } : {} });
10787
10903
  const unsupported3 = [...world.unsupported, ...engines2.unsupported()];
10788
10904
  const status = blockedFetches.length || unsupported3.length || spec.fault && !world.faultTriggered ? "incomplete" : timedOut || server && !server.ready || exitCode !== 0 && !(server && !server.passed) ? "error" : server?.passed === false || background?.passed === false || browser?.passed === false ? "failed" : evaluation.outcome === "passed" && defaultChecks.every((c) => c.passed) && infrastructureAssertions.every((a) => a.passed) ? "passed" : "failed";
10789
10905
  return { schema: "agenttwin/run-v1", name: spec.name, workflowId: spec.workflowId, status, applicationClock: applicationClockEvidence(spec.applicationClock), twinClock: twinClockEvidence(world.twinClock), browser, ...server ? { server } : {}, background, executionError, application: { command: spec.command, exitCode, timedOut, stdout, stderr }, assertions, evaluation, defaultChecks, contracts: operationMatrix(spec), scenario: spec.scenario, infrastructureAssertions, ...embeddedDatabase ? { embeddedDatabase } : {}, fault: spec.fault ? { ...spec.fault, triggered: world.faultTriggered } : null, seed: world.seed, reproducibility: spec.applicationClock ? "Explicit Date clock fixed; timers, performance clocks and scheduling remain real. Twin randomness uses the recorded seed." : "Seed " + world.seed + " deterministically drives twin-side fault scheduling, latency jitter and test credentials. The seed does not control the application's own randomness, wall-clock behavior or threading; compare runs only over twin events and final state.", initialState, finalState: world.snapshot(), events: structuredClone(world.events), blockedFetches, unsupported: unsupported3, durationMs: Date.now() - started, coverage: "CLI Node execution with fresh in-process HTTP collections and advertised provider subsets. Optional Chromium browser steps and bounded collection-state background completion. Not a VM or network/filesystem isolation boundary. No production environment variables inherited; reviewed code can still access the host filesystem and network.", isolation: { kind: "process", productionCredentialsInherited: false, network: "host network; not isolated", rootFilesystem: "host-accessible; explicit files staged in temporary directory" } };
@@ -13148,8 +13264,8 @@ async function loadDashboardDiscovery(cwd, inventory, opts = {}) {
13148
13264
  previousHead = JSON.parse(await readFile18(join27(cwd, ".agenttwin/git.json"), "utf8")).head;
13149
13265
  } catch {
13150
13266
  }
13151
- const git2 = await captureGit(cwd, previousHead);
13152
- const base = discoveryTransfer({ ...dashboardInventory(cwd, inventory), ...git2 ? { git: git2 } : {} });
13267
+ const git3 = await captureGit(cwd, previousHead);
13268
+ const base = discoveryTransfer({ ...dashboardInventory(cwd, inventory), ...git3 ? { git: git3 } : {} });
13153
13269
  if (opts.includeAgentDiscovery === false) return projectProducts(cwd, base, base);
13154
13270
  let raw;
13155
13271
  try {
@@ -13279,7 +13395,7 @@ async function runWorld(cwd, opts) {
13279
13395
  const sourceDigests = await stageApplication(dirname5(file), spec.files, join28(stage, "app"));
13280
13396
  await writeFile16(join28(stage, "world.json"), JSON.stringify(spec), { mode: 420 });
13281
13397
  if (runtime === "e2b" && suppliedSeed) await writeFile16(join28(stage, "seed.json"), JSON.stringify({ seed: suppliedSeed }), { mode: 420 });
13282
- const git2 = await captureGit(sourceBuild?.root ?? cwd);
13398
+ const git3 = await captureGit(sourceBuild?.root ?? cwd);
13283
13399
  let project2;
13284
13400
  try {
13285
13401
  project2 = JSON.parse(await readFile19(join28(inventoryRoot, ".agenttwin/inventory.json"), "utf8")).name ?? basename3(cwd);
@@ -13305,7 +13421,7 @@ async function runWorld(cwd, opts) {
13305
13421
  }
13306
13422
  }
13307
13423
  const runId2 = randomUUID6();
13308
- const receipt2 = { ...report2, ...sourceBuildEvidence ? { sourceBuild: sourceBuildEvidence } : {}, ...sourceBuildError ? { executionError: sourceBuildError } : {}, sourceDirectory: relative4(cwd, dirname5(file)).split(sep3).join("/"), runId: runId2, runtime, project: project2, git: git2, createdAt: (/* @__PURE__ */ new Date()).toISOString(), sourceDigests, specDigest: createHash13("sha256").update(JSON.stringify(spec)).digest("hex"), provenance: "CLI-reported execution" };
13424
+ const receipt2 = { ...report2, ...sourceBuildEvidence ? { sourceBuild: sourceBuildEvidence } : {}, ...sourceBuildError ? { executionError: sourceBuildError } : {}, sourceDirectory: relative4(cwd, dirname5(file)).split(sep3).join("/"), runId: runId2, runtime, project: project2, git: git3, createdAt: (/* @__PURE__ */ new Date()).toISOString(), sourceDigests, specDigest: createHash13("sha256").update(JSON.stringify(spec)).digest("hex"), provenance: "CLI-reported execution" };
13309
13425
  const out2 = resolve7(cwd, opts.out ?? `.agenttwin/runs/${runId2}`);
13310
13426
  await mkdir10(out2, { recursive: true });
13311
13427
  const evidencePath = join28(out2, "run.json"), reportPath = join28(out2, "report.md");
@@ -13313,7 +13429,7 @@ async function runWorld(cwd, opts) {
13313
13429
  await writeFile16(join28(out2, "world.json"), JSON.stringify(spec, null, 2) + "\n", { mode: 384 });
13314
13430
  const next = receipt2.status === "passed" ? [`Replay: agenttwin replay .agenttwin/runs/${runId2}/run.json`] : [`See the evidence and a fix task: agenttwin receipt --id ${runId2}`, `After fixing, rerun: agenttwin run --file ${relative4(cwd, file).split(sep3).join("/")}`];
13315
13431
  await writeFile16(reportPath, renderRunSummary({ ...receipt2, runId: runId2 }, { markdown: true, next, costs: await readCostConfig(cwd) }) + `
13316
- Runner: CLI \xB7 Git: ${git2?.head ?? "unavailable"} \xB7 Seed: ${receipt2.seed}
13432
+ Runner: CLI \xB7 Git: ${git3?.head ?? "unavailable"} \xB7 Seed: ${receipt2.seed}
13317
13433
  ${receipt2.reproducibility ?? ""}
13318
13434
  ${sourceBuildError ?? ""}
13319
13435
  Full evidence (activities, fault, initial and final state): run.json
@@ -13322,7 +13438,7 @@ Full evidence (activities, fault, initial and final state): run.json
13322
13438
  }
13323
13439
  await stageWorker(stage, import.meta.url);
13324
13440
  if (runtime === "hosted") {
13325
- const receipt2 = await executeRemote(stage, spec, opts.log, { git: git2, project: project2, seed: suppliedSeed });
13441
+ const receipt2 = await executeRemote(stage, spec, opts.log, { git: git3, project: project2, seed: suppliedSeed });
13326
13442
  if (receipt2.schema !== "agenttwin/run-v1" || typeof receipt2.runId !== "string" || !/^[a-f0-9-]{36}$/.test(receipt2.runId) || !["passed", "failed", "error", "incomplete"].includes(String(receipt2.status))) throw new CliError("Invalid hosted receipt");
13327
13443
  if (suppliedSeed && receipt2.seed !== suppliedSeed) throw new CliError("Hosted receipt does not match the requested seed");
13328
13444
  const expectedSpec = createHash13("sha256").update(JSON.stringify(spec)).digest("hex");
@@ -13354,7 +13470,7 @@ See run.json for assertions, service state, application output and isolation met
13354
13470
  const receipt = {
13355
13471
  ...report,
13356
13472
  project: project2,
13357
- git: git2,
13473
+ git: git3,
13358
13474
  ...spec.workflowId ? { workflowId: spec.workflowId } : {},
13359
13475
  runId,
13360
13476
  runtime,
@@ -13433,13 +13549,15 @@ function titleFor(kind, service, path2, actual, expected, records, fault, seeded
13433
13549
  function findingsFromReceipt(r, world) {
13434
13550
  const adapterOf = (service) => world?.services.find((s) => s.name === service)?.adapter ?? "json-collection";
13435
13551
  const checks = r.evaluation?.checks?.length ? r.evaluation.checks.map((c) => ({ ...c, ...r.assertions.find((a) => a.service === c.service && a.path === c.path && JSON.stringify(a.where) === JSON.stringify(c.where))?.hint ? { hint: r.assertions.find((a) => a.service === c.service && a.path === c.path).hint } : {} })) : r.assertions;
13436
- const fault = r.fault?.type ? { type: r.fault.type, service: r.fault.service, path: r.fault.path, triggered: !!r.fault.triggered } : void 0;
13552
+ const engineFault = r.engineFault;
13553
+ const fault = r.fault?.type ? { type: r.fault.type, service: r.fault.service, path: r.fault.path, triggered: !!r.fault.triggered } : engineFault?.fault?.type === "error" ? { type: "server-error", service: engineFault.twin, path: void 0, triggered: !!engineFault.triggered } : void 0;
13437
13554
  const findings = [], seeded = JSON.stringify(r.initialState ?? {});
13438
13555
  const timeline = (highlight) => r.events.slice(0, 200).map((e) => ({ sequence: e.sequence, service: e.service, operation: e.operation, path: e.path, detail: String(e.detail).slice(0, 160), ...e.source ? { source: sourceText(e.source) } : {}, highlight: highlight(e) }));
13439
13556
  for (const [index, c] of checks.entries()) {
13440
13557
  if (c.passed || !c.path || String(c.id ?? "").startsWith("generic:")) continue;
13441
13558
  const expected = typeof c.expected === "number" ? c.expected : c.count, actual = typeof c.actual === "number" ? c.actual : void 0;
13442
- const kind = c.kind === "forbidden-effect" ? "forbidden-effect" : c.kind === "preserved-state" ? "changed-state" : actual !== void 0 && expected === 0 && actual > 0 ? "forbidden-effect" : actual !== void 0 && expected !== void 0 && actual > expected ? "duplicate-effect" : actual !== void 0 && expected !== void 0 && actual < expected ? "missing-effect" : "changed-state";
13559
+ const removalUndone = c.kind !== "forbidden-effect" && actual !== void 0 && expected !== void 0 && expected < seededCount(r.initialState, c.service, c.path, c.where) && actual > expected && actual <= seededCount(r.initialState, c.service, c.path, c.where);
13560
+ const kind = removalUndone ? "missing-effect" : c.kind === "forbidden-effect" ? "forbidden-effect" : c.kind === "preserved-state" ? "changed-state" : actual !== void 0 && expected === 0 && actual > 0 ? "forbidden-effect" : actual !== void 0 && expected !== void 0 && actual > expected ? "duplicate-effect" : actual !== void 0 && expected !== void 0 && actual < expected ? "missing-effect" : "changed-state";
13443
13561
  const sequences = new Set(c.evidence?.eventSequences ?? []);
13444
13562
  const related = (e) => sequences.has(e.sequence) || e.service === c.service && e.path === c.path && ["write", "fault"].includes(e.operation);
13445
13563
  const writes = r.events.filter((e) => e.service === c.service && e.path === c.path && e.operation === "write");
@@ -13469,7 +13587,12 @@ function findingsFromReceipt(r, world) {
13469
13587
  });
13470
13588
  }
13471
13589
  const failedWrite = fault?.triggered && fault.service && !isNotify(fault.service, fault.path ?? "", adapterOf(fault.service)) && ["server-error", "blackhole"].includes(fault.type) && !r.events.some((e) => e.service === fault.service && e.path === fault.path && e.operation === "write") ? r.events.find((e) => e.service === fault.service && e.operation === "fault") : void 0;
13472
- const announce = failedWrite && r.events.find((e) => e.operation === "write" && e.sequence > failedWrite.sequence && isNotify(e.service, e.path, adapterOf(e.service)));
13590
+ const words = (record5) => typeof record5 === "string" ? record5 : record5 && typeof record5 === "object" ? Object.values(record5).map(words).join(" ") : "";
13591
+ const notices = failedWrite ? r.events.filter((e) => e.operation === "write" && e.sequence > failedWrite.sequence && isNotify(e.service, e.path, adapterOf(e.service))) : [];
13592
+ const messages = notices.filter((e) => /\/(messages|emails|mail|sms)\b/.test(e.path));
13593
+ const idOf = (e) => e.record?.id;
13594
+ const text3 = (e) => (idOf(e) === void 0 ? [e] : notices.filter((n) => idOf(n) === idOf(e))).map((n) => words(n.record)).join(" ").slice(0, 4e3);
13595
+ const announce = failedWrite && (messages.length ? messages : notices).find((e) => polarityOf(text3(e)) !== "failure");
13473
13596
  if (failedWrite && announce && findings.length) {
13474
13597
  const what = `the ${serviceName2(failedWrite.service)} ${(failedWrite.path.split("/").pop() ?? "write").replace(/_/g, " ").replace(/s$/, "")}`;
13475
13598
  const existing = findings.find((f) => f.service === announce.service && f.path === announce.path && f.kind !== "missing-effect");
@@ -13837,7 +13960,7 @@ function storeIn(text3, schema) {
13837
13960
  return { kind: "memory" };
13838
13961
  }
13839
13962
  async function projectStore(root2, file) {
13840
- const { readdir: readdir12, readFile: read2 } = await import("fs/promises");
13963
+ const { readdir: readdir13, readFile: read2 } = await import("fs/promises");
13841
13964
  const { posix: posix8 } = await import("path");
13842
13965
  const found = [];
13843
13966
  let scanned = 0;
@@ -13845,7 +13968,7 @@ async function projectStore(root2, file) {
13845
13968
  if (depth > 7 || scanned > 6e3) return;
13846
13969
  let entries;
13847
13970
  try {
13848
- entries = await readdir12(join29(root2, dir), { withFileTypes: true });
13971
+ entries = await readdir13(join29(root2, dir), { withFileTypes: true });
13849
13972
  } catch {
13850
13973
  return;
13851
13974
  }
@@ -14294,6 +14417,7 @@ var quote4, NOTIFY2, IDEMPOTENT_ADAPTERS, SERVICE2, serviceName2, sha4, plural2,
14294
14417
  var init_repair_proof = __esm({
14295
14418
  "src/runtime/repair-proof.ts"() {
14296
14419
  "use strict";
14420
+ init_generic_calls();
14297
14421
  init_run_summary();
14298
14422
  init_repair_proof_page();
14299
14423
  quote4 = (s) => `'${s.replace(/[\\']/g, "\\$&")}'`;
@@ -14434,11 +14558,11 @@ function portableLocalReceipt(value3) {
14434
14558
  if (r.events.some((e) => e.source !== void 0 && (!e.source || !["application-reported", "static-analysis"].includes(e.source.provenance) || typeof e.source.file !== "string" || !Object.hasOwn(r.sourceDigests, e.source.file) || !Number.isSafeInteger(e.source.line) || e.source.line < 1 || e.source.line > 1e6 || !Number.isSafeInteger(e.source.column) || e.source.column < 1 || e.source.column > 1e6))) throw new Error("Invalid reported source evidence");
14435
14559
  if (r.sourceDirectory !== void 0 && (typeof r.sourceDirectory !== "string" || r.sourceDirectory.length > 1024 || r.sourceDirectory.startsWith("/") || r.sourceDirectory.includes("\\") || r.sourceDirectory.split("/").includes("..") || /[\x00-\x1f]/.test(r.sourceDirectory))) throw new Error("Invalid source directory");
14436
14560
  if (r.proof !== void 0 && !validProof(r.proof, r.runId)) throw new Error("Invalid or contradictory fix proof");
14437
- const git2 = validateGit(r.git);
14561
+ const git3 = validateGit(r.git);
14438
14562
  if (r.twinClock !== void 0 && !validTwinClockEvidence(r.twinClock)) throw new Error("Invalid twin clock evidence");
14439
14563
  const fields = ["proof", "schema", "runId", "name", "workflowId", "project", "createdAt", "durationMs", "status", "application", "applicationClock", "twinClock", "assertions", "infrastructureAssertions", "fault", "initialState", "finalState", "events", "unsupported", "coverage", "sourceDigests", "sourceDirectory", "sourceBuild", "specDigest", "evaluation", "contracts", "scenario", "worldId", "browser", "background", "executionError", "blockedFetches", "bridgeViolations", "image", "database"];
14440
14564
  const result2 = Object.fromEntries(fields.filter((k) => r[k] !== void 0).map((k) => [k, r[k]]));
14441
- Object.assign(result2, { runtime: r.runtime, provenance: "CLI-reported execution; not independently attested", isolation: r.runtime === "docker" ? r.isolation : { kind: "process", network: "host network; not isolated", rootFilesystem: "host-accessible" }, ...git2 ? { git: git2 } : {} });
14565
+ Object.assign(result2, { runtime: r.runtime, provenance: "CLI-reported execution; not independently attested", isolation: r.runtime === "docker" ? r.isolation : { kind: "process", network: "host network; not isolated", rootFilesystem: "host-accessible" }, ...git3 ? { git: git3 } : {} });
14442
14566
  if (Buffer.byteLength(JSON.stringify(result2)) > 2 * 1024 * 1024) throw new Error("CLI receipt exceeds 2 MiB");
14443
14567
  return result2;
14444
14568
  }
@@ -14516,15 +14640,15 @@ async function runSync(cwd, opts = {}) {
14516
14640
  const base = apiBase(process.env.AGENTTWIN_API_URL || saved?.base || "https://api.agenttwin.si");
14517
14641
  const inventory = JSON.parse(await readFile22(join31(cwd, ".agenttwin/inventory.json"), "utf8"));
14518
14642
  const payload = await loadDashboardDiscovery(cwd, inventory);
14519
- const git2 = payload.git;
14643
+ const git3 = payload.git;
14520
14644
  const response = await fetch(base + "/v1/discovery", { method: "POST", headers: { authorization: "Bearer " + token, "content-type": "application/json" }, body: JSON.stringify(payload), redirect: "error", signal: AbortSignal.timeout(2e4) });
14521
14645
  const result2 = await response.json();
14522
14646
  if (!response.ok) throw new Error(result2.error || "Discovery sync failed: " + response.status);
14523
- if (git2) await writeFile18(join31(cwd, ".agenttwin/git.json"), JSON.stringify(git2) + "\n", { mode: 384 });
14647
+ if (git3) await writeFile18(join31(cwd, ".agenttwin/git.json"), JSON.stringify(git3) + "\n", { mode: 384 });
14524
14648
  const receipts = await syncReceipts(cwd, base, token, { includeFixDiffs });
14525
14649
  await recordAudit(cwd, "sync.uploaded", {
14526
14650
  endpoint: new URL(base).host,
14527
- discovery: { tools: payload.tools.length, workflows: payload.workflows.length, git: !!git2 },
14651
+ discovery: { tools: payload.tools.length, workflows: payload.workflows.length, git: !!git3 },
14528
14652
  receipts: typeof receipts === "object" && receipts && "uploaded" in receipts ? receipts.uploaded : void 0,
14529
14653
  fixDiffsIncluded: includeFixDiffs
14530
14654
  });
@@ -15491,9 +15615,9 @@ function isPackageLike(source) {
15491
15615
  }
15492
15616
  function importMatcher(source) {
15493
15617
  if (!isPackageLike(source)) return safeRegex(source);
15494
- const esc2 = source.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
15618
+ const esc3 = source.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
15495
15619
  return safeRegex(
15496
- `(?:from\\s*['"]${esc2}['"]|require\\s*\\(\\s*['"]${esc2}['"]|import\\s+${esc2}\\b|import\\s*\\{[^}]*\\}\\s*from\\s*['"]${esc2}['"])`
15620
+ `(?:from\\s*['"]${esc3}['"]|require\\s*\\(\\s*['"]${esc3}['"]|import\\s+${esc3}\\b|import\\s*\\{[^}]*\\}\\s*from\\s*['"]${esc3}['"])`
15497
15621
  );
15498
15622
  }
15499
15623
  function escapeRegExp(value3) {
@@ -17717,9 +17841,9 @@ function packagesFor(providerId) {
17717
17841
  return [...set2];
17718
17842
  }
17719
17843
  function importPattern(pkg, prefix) {
17720
- const esc2 = pkg.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
17844
+ const esc3 = pkg.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
17721
17845
  const tail2 = prefix ? `[^'"]*` : "";
17722
- return new RegExp(`from\\s*['"]${esc2}${tail2}['"]`);
17846
+ return new RegExp(`from\\s*['"]${esc3}${tail2}['"]`);
17723
17847
  }
17724
17848
  function bindingsFor(text3, packageIndex) {
17725
17849
  const bindings = factoryProviderBindings(text3);
@@ -19482,11 +19606,11 @@ async function runExport(opts) {
19482
19606
  const bundle = { schema: "export/v1", inventory, plan: plan ?? null };
19483
19607
  if (opts.out) {
19484
19608
  const { mkdir: mkdir35, writeFile: writeFile49 } = await import("fs/promises");
19485
- const { join: join81 } = await import("path");
19609
+ const { join: join82 } = await import("path");
19486
19610
  await mkdir35(opts.out, { recursive: true });
19487
- await writeFile49(join81(opts.out, "inventory.json"), `${JSON.stringify(inventory, null, 2)}
19611
+ await writeFile49(join82(opts.out, "inventory.json"), `${JSON.stringify(inventory, null, 2)}
19488
19612
  `, "utf8");
19489
- if (plan) await writeFile49(join81(opts.out, "plan.json"), `${JSON.stringify(plan, null, 2)}
19613
+ if (plan) await writeFile49(join82(opts.out, "plan.json"), `${JSON.stringify(plan, null, 2)}
19490
19614
  `, "utf8");
19491
19615
  return { schema: "export/v1", out: opts.out, wrote: ["inventory.json", ...plan ? ["plan.json"] : []] };
19492
19616
  }
@@ -19750,8 +19874,8 @@ async function runPrepare(cwd, opts) {
19750
19874
  await mkdir12(dirname6(directory2), { recursive: true });
19751
19875
  await mkdir12(directory2, { mode: 448 });
19752
19876
  try {
19753
- const { cp: cp2, readdir: readdir12 } = await import("fs/promises");
19754
- for (const entry of await readdir12(stage)) await cp2(join36(stage, entry), join36(directory2, entry), { recursive: true, force: false, errorOnExist: true });
19877
+ const { cp: cp2, readdir: readdir13 } = await import("fs/promises");
19878
+ for (const entry of await readdir13(stage)) await cp2(join36(stage, entry), join36(directory2, entry), { recursive: true, force: false, errorOnExist: true });
19755
19879
  } catch (error) {
19756
19880
  await rm15(directory2, { recursive: true, force: true });
19757
19881
  throw error;
@@ -20523,19 +20647,19 @@ async function runProtectedCheck(cwd, opts) {
20523
20647
  try {
20524
20648
  if (!opts.baseline) throw new Error("An explicit trusted baseline commit SHA is required; candidate-owned checks cannot approve a patch");
20525
20649
  if (!/^[a-f0-9]{40}$/.test(opts.revision) || opts.baseline && !/^[a-f0-9]{40}$/.test(opts.baseline)) throw new Error("Use full 40-character candidate and trusted baseline commit SHAs");
20526
- const git2 = async (...args) => (await exec8("git", ["-C", cwd, ...args], { maxBuffer: 20 * 1024 * 1024, timeout: 15e3, encoding: "buffer" })).stdout;
20527
- result2.candidateRevision = (await git2("rev-parse", `${opts.revision}^{commit}`)).toString().trim();
20528
- result2.baselineRevision = (await git2("rev-parse", `${opts.baseline ?? "HEAD"}^{commit}`)).toString().trim();
20650
+ const git3 = async (...args) => (await exec8("git", ["-C", cwd, ...args], { maxBuffer: 20 * 1024 * 1024, timeout: 15e3, encoding: "buffer" })).stdout;
20651
+ result2.candidateRevision = (await git3("rev-parse", `${opts.revision}^{commit}`)).toString().trim();
20652
+ result2.baselineRevision = (await git3("rev-parse", `${opts.baseline ?? "HEAD"}^{commit}`)).toString().trim();
20529
20653
  const path2 = opts.regression;
20530
20654
  if (path2.startsWith("/") || path2.includes("\\") || path2.split("/").some((p) => !p || p === ".." || p === ".")) throw new Error("Regression must be a repository-relative committed path");
20531
- const regression = parseRegression(JSON.parse((await git2("show", `${result2.baselineRevision}:${path2}`)).toString()));
20655
+ const regression = parseRegression(JSON.parse((await git3("show", `${result2.baselineRevision}:${path2}`)).toString()));
20532
20656
  if (regression.spec.sourceBuild && !regression.callable) throw new Error("Protected callable builds require baseline-owned source and invocation metadata; precompiled bundle approval is unsupported");
20533
20657
  result2.specDigest = regression.specDigest;
20534
20658
  let totalBytes = 0;
20535
20659
  const stageGitFile = async (file, revision, directory2) => {
20536
- const entry = (await git2("ls-tree", revision, "--", file)).toString();
20660
+ const entry = (await git3("ls-tree", revision, "--", file)).toString();
20537
20661
  if (!/^100(644|755) blob /.test(entry)) throw new Error(`Candidate file must be a regular committed file: ${file}`);
20538
- const bytes2 = await git2("show", `${revision}:${file}`);
20662
+ const bytes2 = await git3("show", `${revision}:${file}`);
20539
20663
  totalBytes += bytes2.length;
20540
20664
  if (totalBytes > 100 * 1024 * 1024) throw new Error("Candidate files exceed 100 MiB");
20541
20665
  if (revision === result2.candidateRevision) result2.sourceDigests[file] = hash4(bytes2);
@@ -20549,12 +20673,12 @@ async function runProtectedCheck(cwd, opts) {
20549
20673
  await mkdir18(source);
20550
20674
  await mkdir18(compiled);
20551
20675
  for (const file of ["package-lock.json", "npm-shrinkwrap.json"]) {
20552
- if (!(await git2("ls-tree", result2.baselineRevision, "--", file)).equals(await git2("ls-tree", result2.candidateRevision, "--", file)))
20676
+ if (!(await git3("ls-tree", result2.baselineRevision, "--", file)).equals(await git3("ls-tree", result2.candidateRevision, "--", file)))
20553
20677
  throw Error("Candidate dependency lock changed: " + file + "; review a new regression before approval");
20554
20678
  }
20555
20679
  for (const file of regression.callable.sources) await stageGitFile(file, result2.candidateRevision, source);
20556
20680
  for (const [file, expected] of Object.entries(regression.callable.trustedFiles)) {
20557
- if (!file.split("/").includes("node_modules") && hash4(await git2("show", `${result2.candidateRevision}:${file}`)) !== expected)
20681
+ if (!file.split("/").includes("node_modules") && hash4(await git3("show", `${result2.candidateRevision}:${file}`)) !== expected)
20558
20682
  throw Error("Candidate resolution metadata changed: " + file + "; review a new regression before approval");
20559
20683
  }
20560
20684
  await stageTrustedBuildFiles(cwd, source, regression.callable.trustedFiles);
@@ -20805,8 +20929,8 @@ async function receivePreparation(cwd, id2) {
20805
20929
  const inventory = await project(cwd), remote = await connection();
20806
20930
  if (!uuid4.test(id2)) throw Error("Invalid delivery ID");
20807
20931
  const delivery = await request(remote, `/v1/preparations/${id2}?project=${encodeURIComponent(inventory.name)}`);
20808
- const workflow = inventory.workflows.find((w) => w.id === delivery.workflowId), git2 = await captureGit(cwd);
20809
- if (delivery.schema !== "agenttwin/preparation-delivery-v1" || delivery.id !== id2 || delivery.project !== inventory.name || !workflow?.entrypoint || workflow.entrypoint !== delivery.entrypoint || !git2 || git2.head !== delivery.gitHead) throw Error("Preparation does not match this project, entrypoint and Git revision; refresh discovery and sync before trying again");
20932
+ const workflow = inventory.workflows.find((w) => w.id === delivery.workflowId), git3 = await captureGit(cwd);
20933
+ if (delivery.schema !== "agenttwin/preparation-delivery-v1" || delivery.id !== id2 || delivery.project !== inventory.name || !workflow?.entrypoint || workflow.entrypoint !== delivery.entrypoint || !git3 || git3.head !== delivery.gitHead) throw Error("Preparation does not match this project, entrypoint and Git revision; refresh discovery and sync before trying again");
20810
20934
  if (!["queued", "claimed"].includes(delivery.status)) throw Error("Preparation is not waiting for local receipt");
20811
20935
  const path2 = await storage2(cwd, id2);
20812
20936
  let binding;
@@ -20823,7 +20947,7 @@ async function receivePreparation(cwd, id2) {
20823
20947
  }
20824
20948
  }
20825
20949
  if (binding.id !== id2 || binding.base !== remote.base || binding.project !== inventory.name) throw Error("Delivery binding belongs to another API origin or project");
20826
- const claimed = await request(remote, `/v1/preparations/${id2}/claim`, { project: inventory.name, gitHead: git2.head, workflowId: workflow.id, entrypoint: workflow.entrypoint, revision: delivery.revision, claimToken: binding.claimToken });
20950
+ const claimed = await request(remote, `/v1/preparations/${id2}/claim`, { project: inventory.name, gitHead: git3.head, workflowId: workflow.id, entrypoint: workflow.entrypoint, revision: delivery.revision, claimToken: binding.claimToken });
20827
20951
  if (binding.localRequestId) return { ...await preparationStatus(cwd, binding.localRequestId), deliveryId: id2, notice: "Existing local context; no application executed" };
20828
20952
  const lock = path2 + ".lock";
20829
20953
  try {
@@ -20847,7 +20971,7 @@ async function receivePreparation(cwd, id2) {
20847
20971
  }
20848
20972
  binding.localRequestId = context2.requestId;
20849
20973
  await writeBinding(path2, binding);
20850
- return { ...context2, deliveryId: id2, checkoutDirty: git2.dirty, notice: "Authenticated metadata delivery received. Source stays local; an agent must propose the test and a separate local review must approve it. No application executed." };
20974
+ return { ...context2, deliveryId: id2, checkoutDirty: git3.dirty, notice: "Authenticated metadata delivery received. Source stays local; an agent must propose the test and a separate local review must approve it. No application executed." };
20851
20975
  } finally {
20852
20976
  const { rm: rm27 } = await import("fs/promises");
20853
20977
  await rm27(lock, { recursive: true, force: true });
@@ -21215,6 +21339,7 @@ function prismaSchemaSql(source) {
21215
21339
  if (!["Int", "BigInt"].includes(type) || list4) fail2("autoincrement type");
21216
21340
  c.type = type === "Int" ? "serial" : "bigserial";
21217
21341
  } else if (v === "now()" && type === "DateTime") c.default = "CURRENT_TIMESTAMP";
21342
+ else if (/^(?:cuid|uuid|nanoid|ulid)\(\d*\)$/.test(v) && type === "String" && !list4) c.default = c.type === "uuid" ? "gen_random_uuid()" : "gen_random_uuid()::text";
21218
21343
  else if (a.args.length === 1) {
21219
21344
  const x = a.args[0];
21220
21345
  c.default = x.startsWith('"') ? lit(str4(x)) : /^-?\d+(\.\d+)?$/.test(x) || ["true", "false"].includes(x) ? x : enumNames.has(type) ? lit(x) : fail2(`default ${x}`);
@@ -21299,18 +21424,29 @@ function drizzleSchemaSql(source) {
21299
21424
  if (n?.type === "TSAsExpression" || n?.type === "TSSatisfiesExpression") return calls(n.expression);
21300
21425
  if (n?.type !== "CallExpression") return fail2("dynamic Drizzle column");
21301
21426
  if (n.callee.type === "Identifier") return [{ name: imports.get(n.callee.name) ?? (enumNames.has(n.callee.name) ? n.callee.name : fail2(`unknown Drizzle builder ${n.callee.name}`)), args: n.arguments }];
21427
+ if (n.callee.type === "MemberExpression" && !n.callee.computed && n.callee.object?.type === "Identifier" && namespaces.has(n.callee.object.name)) return [{ name: n.callee.property.name, args: n.arguments }];
21302
21428
  if (n.callee.type === "MemberExpression" && !n.callee.computed) return [...calls(n.callee.object), { name: n.callee.property.name, args: n.arguments }];
21303
21429
  return fail2("dynamic Drizzle builder");
21304
21430
  };
21305
21431
  const declarations = [];
21432
+ const namespaces = /* @__PURE__ */ new Set(), ormHelpers = /* @__PURE__ */ new Set();
21433
+ const builder = (callee) => callee?.type === "Identifier" ? imports.get(callee.name) : callee?.type === "MemberExpression" && !callee.computed && callee.object?.type === "Identifier" && namespaces.has(callee.object.name) ? callee.property.name : void 0;
21306
21434
  for (const raw of ast.program.body) {
21307
21435
  const n = raw.type === "ExportNamedDeclaration" ? raw.declaration : raw;
21308
21436
  if (!n) fail2("Drizzle re-exports");
21309
21437
  if (n.type === "ImportDeclaration") {
21310
21438
  if (n.importKind === "type") continue;
21439
+ if (n.source.value === "drizzle-orm") {
21440
+ for (const s of n.specifiers) if (s.type === "ImportSpecifier") ormHelpers.add(s.local.name);
21441
+ continue;
21442
+ }
21311
21443
  if (n.source.value !== "drizzle-orm/pg-core") fail2(`Drizzle import ${n.source.value}`);
21312
21444
  for (const s of n.specifiers) {
21313
- if (s.type !== "ImportSpecifier") fail2("Drizzle namespace/default import");
21445
+ if (s.type === "ImportNamespaceSpecifier") {
21446
+ namespaces.add(s.local.name);
21447
+ continue;
21448
+ }
21449
+ if (s.type !== "ImportSpecifier") fail2("Drizzle default import");
21314
21450
  imports.set(s.local.name, s.imported.name ?? s.imported.value);
21315
21451
  }
21316
21452
  continue;
@@ -21322,7 +21458,7 @@ function drizzleSchemaSql(source) {
21322
21458
  for (const d2 of declarations) {
21323
21459
  if (d2.id.type !== "Identifier") fail2("Drizzle destructuring");
21324
21460
  const n = d2.init;
21325
- if (n?.type === "CallExpression" && n.callee.type === "Identifier" && imports.get(n.callee.name) === "pgEnum") {
21461
+ if (n?.type === "CallExpression" && builder(n.callee) === "pgEnum") {
21326
21462
  if (n.arguments.length !== 2) fail2("pgEnum arguments");
21327
21463
  const name = value3(n.arguments[0]), vals = value3(n.arguments[1]);
21328
21464
  if (typeof name !== "string" || !Array.isArray(vals) || !vals.length || vals.some((v) => typeof v !== "string")) fail2("pgEnum literals");
@@ -21330,10 +21466,24 @@ function drizzleSchemaSql(source) {
21330
21466
  enums.push(`CREATE TYPE ${q2(name)} AS ENUM (${vals.map(lit).join(", ")});`);
21331
21467
  }
21332
21468
  }
21469
+ const tableExtras = (t, fn) => {
21470
+ if (fn?.type !== "ArrowFunctionExpression" || fn.params.length !== 1 || fn.params[0].type !== "Identifier") fail2("table-level callback");
21471
+ const param = fn.params[0].name, body = fn.body?.type === "ObjectExpression" ? fn.body.properties.map((p) => p.value) : fn.body?.type === "ArrayExpression" ? fn.body.elements : fail2("table-level callback");
21472
+ for (const e of body) {
21473
+ const chain2 = calls(e), kind = chain2[0]?.name, on = chain2.find((c) => c.name === "on");
21474
+ if (kind === "index") continue;
21475
+ if (kind !== "uniqueIndex" && kind !== "unique" || !on || chain2.some((c) => !["uniqueIndex", "unique", "on", "using", "nullsNotDistinct"].includes(c.name))) fail2(`table-level ${kind ?? "constraint"}`);
21476
+ const cols = on.args.map((a) => a?.type === "MemberExpression" && a.object?.type === "Identifier" && a.object.name === param && !a.computed ? t.columns.get(a.property.name)?.name : void 0);
21477
+ if (!cols.length || cols.some((c) => !c)) fail2("table-level unique columns");
21478
+ t.constraints.push(`UNIQUE (${cols.map((c) => q2(c)).join(", ")})`);
21479
+ }
21480
+ };
21333
21481
  for (const d2 of declarations) {
21334
21482
  if (enumNames.has(d2.id.name)) continue;
21335
21483
  const n = d2.init;
21336
- if (n?.type !== "CallExpression" || n.callee.type !== "Identifier" || imports.get(n.callee.name) !== "pgTable" || n.arguments.length !== 2) fail2("pgTable expression or table-level callback constraints");
21484
+ if (n?.type === "CallExpression" && n.callee.type === "Identifier" && ormHelpers.has(n.callee.name)) continue;
21485
+ if (n?.type === "ObjectExpression" && n.properties.every((p) => p.type === "ObjectProperty" && p.value?.type === "Identifier")) continue;
21486
+ if (n?.type !== "CallExpression" || builder(n.callee) !== "pgTable" || n.arguments.length < 2 || n.arguments.length > 3) fail2(`pgTable expression (${d2.id.name})`);
21337
21487
  const name = value3(n.arguments[0]);
21338
21488
  if (typeof name !== "string") fail2("dynamic table name");
21339
21489
  const t = { name, columns: /* @__PURE__ */ new Map(), constraints: [] };
@@ -21389,6 +21539,7 @@ function drizzleSchemaSql(source) {
21389
21539
  }
21390
21540
  t.columns.set(field2, c);
21391
21541
  }
21542
+ if (n.arguments[2]) tableExtras(t, n.arguments[2]);
21392
21543
  }
21393
21544
  const ddl = refs2.map((r) => {
21394
21545
  const from = tables.get(r.from), to = tables.get(r.target), target = to?.columns.get(r.field);
@@ -21425,9 +21576,9 @@ async function discoverAppPostgresSchema(root2, appDir) {
21425
21576
  async function discoverPostgresSchema(root2) {
21426
21577
  const exists3 = async (p) => {
21427
21578
  try {
21428
- const stat13 = await lstat7(join47(root2, p));
21429
- if (stat13.isSymbolicLink()) throw new Error(`Postgres schema discovery refuses symlink: ${p}`);
21430
- return stat13.isFile();
21579
+ const stat14 = await lstat7(join47(root2, p));
21580
+ if (stat14.isSymbolicLink()) throw new Error(`Postgres schema discovery refuses symlink: ${p}`);
21581
+ return stat14.isFile();
21431
21582
  } catch (e) {
21432
21583
  if (e.code === "ENOENT") return false;
21433
21584
  throw e;
@@ -21530,8 +21681,8 @@ async function loadPostgresSchema(root2, files) {
21530
21681
  const path2 = await realpath16(resolve20(base, file));
21531
21682
  const rel = relative14(base, path2);
21532
21683
  if (rel.startsWith("..") || isAbsolute10(rel)) throw new Error(`Postgres schema escapes project: ${file}`);
21533
- const stat13 = await lstat7(path2);
21534
- if (!stat13.isFile() || stat13.size + size > MAX_SCHEMA_BYTES) throw new Error("Postgres schema must contain regular source files totaling at most 16 MiB.");
21684
+ const stat14 = await lstat7(path2);
21685
+ if (!stat14.isFile() || stat14.size + size > MAX_SCHEMA_BYTES) throw new Error("Postgres schema must contain regular source files totaling at most 16 MiB.");
21535
21686
  const sql2 = await readFile37(path2, "utf8");
21536
21687
  size += Buffer.byteLength(sql2);
21537
21688
  if (size > MAX_SCHEMA_BYTES) throw new Error("Postgres schema exceeds the 16 MiB test setup limit.");
@@ -21680,6 +21831,39 @@ function missingTwinRecords(events, supplied, packOf, operations) {
21680
21831
  }
21681
21832
  return [...found.values()];
21682
21833
  }
21834
+ async function alignInputWithSchema(schemaSql, input, generated) {
21835
+ const fields = Object.entries(input).filter(([, v]) => generated(v));
21836
+ if (!fields.length) return { input, changed: [] };
21837
+ const extensions = schemaExtensions(schemaSql).filter((e) => POSTGRES_EXTENSIONS.includes(e));
21838
+ const db = await startPostgresEngine({ extensions, seed: { sql: schemaSql, tables: {} } });
21839
+ const out = { ...input }, changed = [];
21840
+ try {
21841
+ const cols = await queryReadOnly(db, `SELECT table_name, column_name, data_type FROM information_schema.columns WHERE table_schema = 'public'`);
21842
+ const snake = (k) => k.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
21843
+ const plural3 = (t) => [t, t + "s", t + "es", t.replace(/y$/, "ies")];
21844
+ for (const [key3, value3] of fields) {
21845
+ const name = snake(key3);
21846
+ const stem = /^(\w+?)_?id$/.exec(name)?.[1];
21847
+ const table4 = stem ? [...new Set(cols.map((c) => c.table_name))].find((t) => plural3(stem).includes(t) && cols.some((c) => c.table_name === t && c.column_name === "id")) : void 0;
21848
+ if (table4) {
21849
+ const row = (await queryReadOnly(db, `SELECT id FROM "${table4.replace(/"/g, '""')}" ORDER BY 1 LIMIT 1`))[0];
21850
+ if (row && row.id !== null && row.id !== void 0) {
21851
+ out[key3] = row.id;
21852
+ changed.push(`${key3} = ${table4}.id ${JSON.stringify(row.id)}`);
21853
+ continue;
21854
+ }
21855
+ }
21856
+ const numeric = cols.find((c) => c.column_name === name && /int|numeric|decimal|real|double/i.test(c.data_type));
21857
+ if (numeric && typeof value3 === "string") {
21858
+ out[key3] = 100;
21859
+ changed.push(`${key3} = 100 (${numeric.table_name}.${name} is ${numeric.data_type})`);
21860
+ }
21861
+ }
21862
+ } finally {
21863
+ await db.stop();
21864
+ }
21865
+ return { input: out, changed };
21866
+ }
21683
21867
  var sample;
21684
21868
  var init_state_seeding = __esm({
21685
21869
  "src/flow/state-seeding.ts"() {
@@ -23882,6 +24066,15 @@ async function sourceFiles2(root2) {
23882
24066
  await visit(root2);
23883
24067
  return files;
23884
24068
  }
24069
+ function nextBasePath(root2, appDir) {
24070
+ if (appDir === void 0) return "";
24071
+ for (const ext of ["js", "mjs", "ts", "cjs", "mts"]) try {
24072
+ const m = /\bbasePath\s*:\s*['"`](\/[^'"`$]*)['"`]/.exec(readFileSync9(join55(root2, appDir, `next.config.${ext}`), "utf8"));
24073
+ if (m) return m[1].replace(/\/$/, "");
24074
+ } catch {
24075
+ }
24076
+ return "";
24077
+ }
23885
24078
  function nextAppDir(root2, file) {
23886
24079
  for (let dir = posix4.dirname(file); ; dir = posix4.dirname(dir)) {
23887
24080
  const key3 = root2 + "\0" + dir;
@@ -24036,7 +24229,7 @@ async function analyzeWorkflows(root2, opts = {}) {
24036
24229
  }
24037
24230
  };
24038
24231
  const same2 = starters.filter((f) => pkgDir(f) === pkgDir(file));
24039
- return same2.sort((a, b) => Number(/(main|server|index|app)\.[cm]?[jt]s$/.test(b)) - Number(/(main|server|index|app)\.[cm]?[jt]s$/.test(a)))[0];
24232
+ return same2.sort((a, b) => Number(/(main|server|index|app)\.[cm]?[jt]s$/.test(b)) - Number(/(main|server|index|app)\.[cm]?[jt]s$/.test(a)))[0] ?? (top !== file ? top : void 0);
24040
24233
  };
24041
24234
  const startScript = (entry) => {
24042
24235
  for (let dir = posix4.dirname(entry); ; dir = posix4.dirname(dir)) {
@@ -24047,12 +24240,14 @@ async function analyzeWorkflows(root2, opts = {}) {
24047
24240
  }
24048
24241
  if (pkg) {
24049
24242
  const stem = posix4.basename(entry).replace(/\.[cm]?[jt]sx?$/, "");
24050
- for (const name of ["dev", "start:dev", "dev:server", "server", "serve", "start"]) {
24243
+ for (const name of ["dev", "start:dev", "dev:server", "devserver", "dev:api", "dev:backend", "server", "serve", "start:server", "api", "backend", "start"]) {
24051
24244
  const command = pkg.scripts?.[name];
24052
24245
  if (!command) continue;
24053
24246
  if (/concurrently|npm-run-all|run-p|turbo|docker|\bvite\b(?!-node)|\bnext\b|\bbun\b|\bdeno\b|(^|[^&])&([^&]|$)/.test(command)) continue;
24054
24247
  if (!/\b(node|tsx|ts-node|ts-node-dev|tsnd|nodemon|nest|vite-node|babel-node|ts-node-esm)\b/.test(command)) continue;
24055
- if (!(command.includes(stem) || /\bnest\s+start\b/.test(command))) continue;
24248
+ if (/\bts-node-esm\b|\bts-node\b[^&|;]*--esm\b/.test(command)) continue;
24249
+ const runs = [...command.matchAll(/(?:^|\s)(\.?\/?[\w@./-]+\.[cm]?[jt]sx?)\b/g)].map((m) => posix4.normalize(posix4.join(dir === "." ? "" : dir, m[1]))).filter((f) => byFile.has(f));
24250
+ if (!(command.includes(stem) || /\bnest\s+start\b/.test(command) || runs.some((f) => f === entry || reaches(f, entry)))) continue;
24056
24251
  const dist = /\bdist\/|\bbuild\//.exec(command);
24057
24252
  if (dist && !/\bnest\b/.test(command) && !existsSync8(join55(root2, dir, dist[0]))) continue;
24058
24253
  return { name, command, dir: dir === "." ? "" : dir };
@@ -24094,6 +24289,10 @@ async function analyzeWorkflows(root2, opts = {}) {
24094
24289
  if (node.type === "CallExpression" && node.callee?.type === "MemberExpression" && ["map", "flatMap", "forEach", "reduce"].includes(node.callee.property?.name)) uncertainSql.push(node);
24095
24290
  });
24096
24291
  const before = (a, b) => a.line < b.line || a.line === b.line && a.column <= b.column;
24292
+ const loops = [];
24293
+ walk3(fn.body, (node) => {
24294
+ if (["ForStatement", "ForInStatement", "ForOfStatement", "WhileStatement", "DoWhileStatement"].includes(node.type) || node.type === "CallExpression" && node.callee?.type === "MemberExpression" && (["map", "flatMap", "forEach", "reduce"].includes(node.callee.property?.name) || node.callee.object?.name === "Promise" && ["all", "allSettled"].includes(node.callee.property?.name))) loops.push(node);
24295
+ });
24097
24296
  const inBranch = (line, column = 1) => branches.some((b) => b?.loc && before(b.loc.start, { line, column: column - 1 }) && before({ line, column: column - 1 }, b.loc.end));
24098
24297
  const boltNames = /* @__PURE__ */ new Map();
24099
24298
  if (bolt && fn.params?.[0]?.type === "ObjectPattern") {
@@ -24149,7 +24348,8 @@ async function analyzeWorkflows(root2, opts = {}) {
24149
24348
  if (hit) {
24150
24349
  const parsed = new URL(String(url).replaceAll("{id}", "x"));
24151
24350
  const operation2 = String(url).replace(/^https:\/\/[^/]+\/(?:api\/|v1\/)?/, "").replaceAll("/", ".");
24152
- entry.calls.push({ provider: hit[1], operation: operation2, file, line: node.loc.start.line, column: node.loc.start.column + 1, argKeys: [], literals: {}, method, path: String(url).replace(/^https:\/\/[^/]+/, ""), host: parsed.hostname, ...body !== void 0 ? { body } : {}, write: hit[1] === "slack" ? !READ_OPS.test(operation2) : write4 });
24351
+ const args = body && typeof body === "object" && !Array.isArray(body) ? { ...body } : void 0;
24352
+ entry.calls.push({ provider: hit[1], operation: operation2, file, line: node.loc.start.line, column: node.loc.start.column + 1, argKeys: Object.keys(args ?? {}), literals: args ? Object.fromEntries(Object.entries(args).filter(([, v]) => v !== null && typeof v !== "object")) : {}, ...args ? { args } : {}, method, path: String(url).replace(/^https:\/\/[^/]+/, ""), host: parsed.hostname, ...body !== void 0 ? { body } : {}, write: hit[1] === "slack" ? !READ_OPS.test(operation2) : write4 });
24153
24353
  }
24154
24354
  return;
24155
24355
  }
@@ -24264,6 +24464,7 @@ async function analyzeWorkflows(root2, opts = {}) {
24264
24464
  });
24265
24465
  for (const call2 of entry.calls.slice(firstCall)) {
24266
24466
  const at = { line: call2.line, column: (call2.column ?? 1) - 1 };
24467
+ if (loops.some((node) => node.loc && before(node.loc.start, at) && before(at, node.loc.end))) call2.repeats = true;
24267
24468
  if (inBranch(call2.line, call2.column) || (call2.stripeItem || /^sdk:(mysql2?|kafkajs|amqplib)$/.test(call2.provider)) && (exits.some((e) => e.loc && before(e.loc.end, at)) || !!call2.stripeItem && uncertainSql.some((node) => node.loc && before(node.loc.start, at) && before(at, node.loc.end)))) call2.conditional = true;
24268
24469
  }
24269
24470
  return entry;
@@ -24344,7 +24545,7 @@ async function analyzeWorkflows(root2, opts = {}) {
24344
24545
  }
24345
24546
  return seg;
24346
24547
  }).join("/");
24347
- web = { method: exportName, path: path2.replace(/\/+/g, "/") || "/", params, ...appDir !== void 0 ? { appDir } : {} };
24548
+ web = { method: exportName, path: (nextBasePath(root2, appDir) + path2).replace(/\/+/g, "/") || "/", params, ...appDir !== void 0 ? { appDir } : {} };
24348
24549
  const requestName = fn.params?.[0]?.type === "Identifier" ? fn.params[0].name : "request", fields = /* @__PURE__ */ new Set(), aliases2 = /* @__PURE__ */ new Set();
24349
24550
  const unwrap2 = (n) => n && (n.type === "TSAsExpression" || n.type === "TSNonNullExpression" || n.type === "TSSatisfiesExpression" || n.type === "ParenthesizedExpression") ? unwrap2(n.expression) : n;
24350
24551
  const isJson = (raw) => {
@@ -24376,10 +24577,20 @@ async function analyzeWorkflows(root2, opts = {}) {
24376
24577
  }).join("/");
24377
24578
  const text3 = byFile.get(file).text, named = [...text3.matchAll(/\.method\s*={2,3}\s*['"](GET|POST|PUT|PATCH|DELETE)['"]|case\s*['"](GET|POST|PUT|PATCH|DELETE)['"]/g)].map((m) => m[1] ?? m[2]);
24378
24579
  const method = named.find((m) => m !== "GET") ?? (named.length ? "GET" : /\breq\.body\b|rawBody|getRawBody|signature|buffer\(req\)/.test(text3) ? "POST" : "GET");
24379
- web = { method, path: path2.replace(/\/+/g, "/"), params, appDir };
24580
+ web = { method, path: (nextBasePath(root2, appDir) + path2).replace(/\/+/g, "/"), params, appDir };
24380
24581
  input = { name: "req.body", fields: [] };
24381
24582
  }
24382
24583
  }
24584
+ if (web?.appDir !== void 0) {
24585
+ const base = web.appDir ? web.appDir + "/" : "";
24586
+ const mw = ["middleware", "src/middleware"].flatMap((b) => [".ts", ".js", ".mjs", ".tsx"].map((e) => base + b + e)).find((f2) => byFile.get(f2)?.facts.exports.has("middleware"));
24587
+ if (mw) {
24588
+ const extra = closure(mw, byFile.get(mw).facts.exports.get("middleware"));
24589
+ for (const c of extra.calls) if (!calls.some((x) => x.file === c.file && x.line === c.line && x.operation === c.operation)) calls.push({ ...c, write: false, conditional: true });
24590
+ for (const e of extra.env) if (!env.includes(e)) env.push(e);
24591
+ for (const t of extra.files) if (!touched.includes(t)) touched.push(t);
24592
+ }
24593
+ }
24383
24594
  const tools = touched.flatMap((t) => byFile.get(t).facts.tools);
24384
24595
  const providers = new Set(calls.map((c) => c.provider));
24385
24596
  const inNext = nextAppDir(root2, file) !== void 0;
@@ -24435,7 +24646,7 @@ async function analyzeWorkflows(root2, opts = {}) {
24435
24646
  channelHints: channels,
24436
24647
  score: score + 2,
24437
24648
  files: touched,
24438
- serve: { method: route.method, path: path2.replace(/:([A-Za-z_]\w*)\??/g, "1").replace(/\{[^}]+\}/g, "1"), line: route.line, ...listenPort ? { listenPort: Number(listenPort) } : {}, ...entry ? { entry } : {}, ...script ? { script } : {} }
24649
+ serve: { method: route.method, path: path2.replace(/:([A-Za-z_]\w*)\??/g, "1").replace(/\{[^}]+\}/g, "1").replace(/\/\*{1,2}(?=\/|$)/g, "/file-1"), line: route.line, ...listenPort ? { listenPort: Number(listenPort) } : {}, ...entry ? { entry } : {}, ...script ? { script } : {} }
24439
24650
  });
24440
24651
  }
24441
24652
  if (bolt) for (const [file, { facts: f }] of byFile) for (const listener of f.boltListeners) {
@@ -24520,7 +24731,7 @@ var init_analyze = __esm({
24520
24731
  init_tsconfig_paths();
24521
24732
  WHOLE_INPUT = "$input";
24522
24733
  PROVIDER_MODULES = { "@octokit/rest": "github", octokit: "github", "@octokit/core": "github", "@notionhq/client": "notion", "@linear/sdk": "linear", openai: "openai", "groq-sdk": "openai", "@mistralai/mistralai": "openai", "together-ai": "openai", "@anthropic-ai/sdk": "anthropic", stripe: "stripe", "@slack/web-api": "slack", pg: "postgres", postgres: "postgres", "@neondatabase/serverless": "postgres", googleapis: "gmail", "@googleapis/gmail": "gmail", twilio: "twilio", "@hubspot/api-client": "hubspot", ioredis: "redis", redis: "redis", "@aws-sdk/client-s3": "aws", "@aws-sdk/client-dynamodb": "aws", "@aws-sdk/client-sqs": "aws", "@aws-sdk/client-sns": "aws", "@aws-sdk/lib-dynamodb": "aws" };
24523
- FETCH_HOSTS = [[/^https:\/\/slack\.com\/api\//, "slack"], [/^https:\/\/api\.openai\.com\//, "openai"], [/^https:\/\/api\.anthropic\.com\//, "anthropic"], [/^https:\/\/api\.stripe\.com\//, "stripe"], [/^https:\/\/gmail\.googleapis\.com\//, "gmail"], [/^https:\/\/api\.hubapi\.com\//, "hubspot"], [/^https:\/\/api\.twilio\.com\//, "twilio"]];
24734
+ FETCH_HOSTS = [[/^https:\/\/slack\.com\/api\//, "slack"], [/^https:\/\/api\.openai\.com\//, "openai"], [/^https:\/\/api\.anthropic\.com\//, "anthropic"], [/^https:\/\/api\.stripe\.com\//, "stripe"], [/^https:\/\/gmail\.googleapis\.com\//, "gmail"], [/^https:\/\/api\.hubapi\.com\//, "hubspot"], [/^https:\/\/api\.twilio\.com\//, "twilio"], [/^https:\/\/[a-z0-9-]+\.zendesk\.com\//, "zendesk"], [/^https:\/\/[a-z0-9-]+\.atlassian\.net\//, "jira"], [/^https:\/\/[a-z0-9-]+\.myshopify\.com\//, "shopify"], [/^https:\/\/gitlab\.com\/api\//, "gitlab"], [/^https:\/\/api\.(?:us5\.)?datadoghq\.(?:com|eu)\//, "datadog"]];
24524
24735
  KNOWN_PROVIDERS = /* @__PURE__ */ new Set([...FETCH_HOSTS.map(([, provider]) => provider), ...Object.values(PROVIDER_MODULES)]);
24525
24736
  escapeHost = (h2) => h2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
24526
24737
  fetchHosts = () => [...FETCH_HOSTS, ...packHosts ??= Object.values(packCatalog()?.packs ?? {}).flatMap((p) => p.hosts.filter((h2) => !h2.host || !FETCH_HOSTS.some(([re]) => re.test(`https://${h2.host}/`))).map((h2) => [h2.host ? new RegExp(`^https://${h2.suffix ? "(?:[a-z0-9-]+\\.)*" : ""}${escapeHost(h2.host)}(?:[:/]|$)`, "i") : new RegExp(`^https://(?:${h2.hostPattern.replace(/^\^|\$$/g, "")})(?:[:/]|$)`, "i"), `pack:${p.name}`]))];
@@ -24552,6 +24763,129 @@ var init_analyze = __esm({
24552
24763
  }
24553
24764
  });
24554
24765
 
24766
+ // src/runtime/workers-env.ts
24767
+ var WORKERS_ENV;
24768
+ var init_workers_env = __esm({
24769
+ "src/runtime/workers-env.ts"() {
24770
+ "use strict";
24771
+ WORKERS_ENV = String.raw`
24772
+ import { register } from 'node:module';
24773
+ import { readFileSync } from 'node:fs';
24774
+
24775
+ // cloudflare:workers and friends, as ES modules the Worker can import.
24776
+ const SOURCES = {
24777
+ workers: "export class DurableObject { constructor(ctx, env) { this.ctx = ctx; this.env = env; } }\n" +
24778
+ "export class WorkerEntrypoint { constructor(ctx, env) { this.ctx = ctx; this.env = env; } }\n" +
24779
+ "export class WorkflowEntrypoint { constructor(ctx, env) { this.ctx = ctx; this.env = env; } }\n" +
24780
+ "export class RpcTarget {}\n" +
24781
+ "export const env = new Proxy({}, { get: (_, k) => globalThis.__agenttwinWorkersEnv?.[k], has: (_, k) => k in (globalThis.__agenttwinWorkersEnv ?? {}) });\n" +
24782
+ "export default { DurableObject, WorkerEntrypoint, WorkflowEntrypoint, RpcTarget, env };\n",
24783
+ sockets: "export function connect() { throw new Error('AgentTwin: cloudflare:sockets is not modelled'); }\nexport default { connect };\n",
24784
+ };
24785
+ const hooks = 'const S = ' + JSON.stringify(SOURCES) + ';\n' +
24786
+ "export async function resolve(s, c, n) { if (s.startsWith('cloudflare:')) return { url: 'agenttwin-cf:' + s.slice(11), shortCircuit: true }; return n(s, c); }\n" +
24787
+ "export async function load(u, c, n) { if (u.startsWith('agenttwin-cf:')) { const k = u.slice(13); if (!(k in S)) throw new Error('AgentTwin: cloudflare:' + k + ' is not modelled'); return { format: 'module', source: S[k], shortCircuit: true }; } return n(u, c); }\n";
24788
+ export function install() { register('data:text/javascript,' + encodeURIComponent(hooks)); }
24789
+
24790
+ /** wrangler.toml, the subset Workers projects use: tables, arrays of tables, strings, numbers, booleans, inline tables and arrays. */
24791
+ export function parseToml(text) {
24792
+ const root = {}; let cur = root;
24793
+ const value = (raw) => {
24794
+ raw = raw.trim();
24795
+ if (raw.startsWith('"') || raw.startsWith("'")) return raw.slice(1, raw.lastIndexOf(raw[0]));
24796
+ if (raw === 'true' || raw === 'false') return raw === 'true';
24797
+ if (/^-?\d+(\.\d+)?$/.test(raw)) return Number(raw);
24798
+ if (raw.startsWith('[')) return split(raw.slice(1, raw.lastIndexOf(']'))).map(value);
24799
+ if (raw.startsWith('{')) { const o = {}; for (const part of split(raw.slice(1, raw.lastIndexOf('}')))) { const i = part.indexOf('='); if (i > 0) o[part.slice(0, i).trim().replace(/^["']|["']$/g, '')] = value(part.slice(i + 1)); } return o; }
24800
+ return raw;
24801
+ };
24802
+ function split(s) { const out = []; let depth = 0, q = null, start = 0; for (let i = 0; i < s.length; i++) { const ch = s[i]; if (q) { if (ch === q) q = null; continue; } if (ch === '"' || ch === "'") q = ch; else if ('[{'.includes(ch)) depth++; else if (']}'.includes(ch)) depth--; else if (ch === ',' && !depth) { out.push(s.slice(start, i)); start = i + 1; } } if (s.slice(start).trim()) out.push(s.slice(start)); return out.filter(x => x.trim()); }
24803
+ const walk = (path, arrayTable) => { let o = root; path.forEach((k, i) => { const last = i === path.length - 1; if (last && arrayTable) { (o[k] ??= []).push({}); o = o[k][o[k].length - 1]; } else { if (Array.isArray(o[k])) o = o[k][o[k].length - 1]; else o = (o[k] ??= {}); } }); return o; };
24804
+ for (let line of text.split(/\r?\n/)) {
24805
+ line = line.replace(/^\s+/, ''); if (!line || line.startsWith('#')) continue;
24806
+ const arr = /^\[\[([^\]]+)\]\]/.exec(line), tbl = !arr && /^\[([^\]]+)\]/.exec(line);
24807
+ if (arr || tbl) { cur = walk((arr ?? tbl)[1].split('.').map(s => s.trim().replace(/^["']|["']$/g, '')), !!arr); continue; }
24808
+ const i = line.indexOf('='); if (i < 0) continue;
24809
+ let raw = line.slice(i + 1); const hash = raw.search(/\s#(?=(?:[^"']*["'][^"']*["'])*[^"']*$)/); if (hash >= 0) raw = raw.slice(0, hash);
24810
+ cur[line.slice(0, i).trim().replace(/^["']|["']$/g, '')] = value(raw);
24811
+ }
24812
+ return root;
24813
+ }
24814
+ const stripJsonc = (t) => t.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (m, s) => s ?? '').replace(/,(\s*[}\]])/g, '$1');
24815
+
24816
+ function readConfig(file) {
24817
+ const text = readFileSync(file, 'utf8');
24818
+ const cfg = file.endsWith('.toml') ? parseToml(text) : JSON.parse(stripJsonc(text));
24819
+ // Bindings live at the top level, or only under an environment (elrax keeps them in env.dev): the local one.
24820
+ const named = cfg.env && typeof cfg.env === 'object' ? (cfg.env.dev ?? cfg.env.development ?? cfg.env.local ?? Object.values(cfg.env)[0]) : undefined;
24821
+ const pick = (k) => cfg[k] ?? named?.[k];
24822
+ return { vars: { ...(named?.vars ?? {}), ...(cfg.vars ?? {}) }, kv: pick('kv_namespaces') ?? [], r2: pick('r2_buckets') ?? [], durable: pick('durable_objects')?.bindings ?? [],
24823
+ other: ['d1_databases', 'queues', 'services', 'ai', 'vectorize', 'hyperdrive', 'analytics_engine_datasets', 'browser', 'workflows'].flatMap(k => { const v = pick(k); return v ? (Array.isArray(v) ? v : [v]).map(b => ({ kind: k, name: b.binding ?? b.name ?? k })) : []; }) };
24824
+ }
24825
+
24826
+ function kvNamespace() {
24827
+ const m = new Map();
24828
+ return { async get(k, o) { const v = m.get(k); if (v === undefined) return null; const t = typeof o === 'string' ? o : o?.type; return t === 'json' ? JSON.parse(v) : v; },
24829
+ async put(k, v) { m.set(k, typeof v === 'string' ? v : JSON.stringify(v)); }, async delete(k) { m.delete(k); },
24830
+ async list(o = {}) { const keys = [...m.keys()].filter(k => !o.prefix || k.startsWith(o.prefix)).sort().map(name => ({ name })); return { keys, list_complete: true, cursor: '' }; },
24831
+ async getWithMetadata(k, o) { return { value: await this.get(k, o), metadata: null }; } };
24832
+ }
24833
+ function r2Bucket() {
24834
+ const m = new Map();
24835
+ const object = (key, bytes, meta = {}) => ({ key, size: bytes.length, etag: String(bytes.length), httpEtag: '"' + bytes.length + '"', uploaded: new Date(), httpMetadata: meta.httpMetadata ?? {}, customMetadata: meta.customMetadata ?? {},
24836
+ body: new Response(bytes).body, async arrayBuffer() { return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.length); }, async text() { return new TextDecoder().decode(bytes); }, async json() { return JSON.parse(new TextDecoder().decode(bytes)); }, writeHttpMetadata(h) { for (const [k, v] of Object.entries(meta.httpMetadata ?? {})) h.set(k, String(v)); } });
24837
+ const bytesOf = async (v) => v == null ? new Uint8Array() : typeof v === 'string' ? new TextEncoder().encode(v) : v instanceof Uint8Array ? v : v instanceof ArrayBuffer ? new Uint8Array(v) : new Uint8Array(await new Response(v).arrayBuffer());
24838
+ return { async put(k, v, meta) { const b = await bytesOf(v); m.set(k, { b, meta }); return object(k, b, meta); }, async get(k) { const e = m.get(k); return e ? object(k, e.b, e.meta) : null; },
24839
+ async head(k) { const e = m.get(k); return e ? object(k, e.b, e.meta) : null; }, async delete(k) { for (const key of [].concat(k)) m.delete(key); },
24840
+ async list(o = {}) { return { objects: [...m.entries()].filter(([k]) => !o.prefix || k.startsWith(o.prefix)).map(([k, e]) => object(k, e.b, e.meta)), truncated: false, delimitedPrefixes: [] }; } };
24841
+ }
24842
+ async function sqlStorage() {
24843
+ let db; try { const { DatabaseSync } = await import('node:sqlite'); db = new DatabaseSync(':memory:'); } catch { return undefined; }
24844
+ const cursor = (rows, changes) => ({ toArray: () => rows, one: () => { if (rows.length !== 1) throw new Error('Expected exactly one result from SQL query, got ' + rows.length); return rows[0]; },
24845
+ raw: () => rows.map(r => Object.values(r))[Symbol.iterator](), columnNames: rows[0] ? Object.keys(rows[0]) : [], rowsRead: rows.length, rowsWritten: changes, next: (() => { const it = rows[Symbol.iterator](); return () => it.next(); })(), [Symbol.iterator]: () => rows[Symbol.iterator]() });
24846
+ return { exec(query, ...bindings) {
24847
+ const parts = query.split(';').map(s => s.trim()).filter(Boolean);
24848
+ if (parts.length > 1 && !bindings.length) { db.exec(query); return cursor([], 0); }
24849
+ const stmt = db.prepare(query), reads = /^\s*(select|with|pragma)\b|\breturning\b/i.test(query);
24850
+ const args = bindings.map(v => typeof v === 'boolean' ? Number(v) : v);
24851
+ if (reads) return cursor(stmt.all(...args).map(r => ({ ...r })), 0);
24852
+ const r = stmt.run(...args); return cursor([], Number(r.changes ?? 0));
24853
+ }, get databaseSize() { return 0; } };
24854
+ }
24855
+ async function durableNamespace(Class, env, name) {
24856
+ const instances = new Map();
24857
+ const id = (key) => ({ name: key, toString: () => key, equals: (o) => String(o) === key });
24858
+ const instance = async (key) => {
24859
+ if (instances.has(key)) return instances.get(key);
24860
+ const kv = new Map(), sql = await sqlStorage();
24861
+ const storage = { sql, async get(k) { return Array.isArray(k) ? new Map(k.filter(x => kv.has(x)).map(x => [x, kv.get(x)])) : kv.get(k); }, async put(k, v) { if (typeof k === 'object') for (const [a, b] of Object.entries(k)) kv.set(a, b); else kv.set(k, v); },
24862
+ async delete(k) { return [].concat(k).map(x => kv.delete(x)).some(Boolean); }, async list(o = {}) { return new Map([...kv].filter(([k]) => !o.prefix || k.startsWith(o.prefix)).sort()); },
24863
+ async deleteAll() { kv.clear(); }, async transaction(fn) { return fn(storage); }, transactionSync(fn) { return fn(); }, async getAlarm() { return null; }, async setAlarm() {}, async deleteAlarm() {} };
24864
+ const state = { id: id(key), storage, async blockConcurrencyWhile(fn) { return fn(); }, waitUntil() {}, acceptWebSocket() { throw new Error('AgentTwin: Durable Object WebSockets are not modelled'); }, getWebSockets: () => [] };
24865
+ const obj = new Class(state, env); instances.set(key, obj); return obj;
24866
+ };
24867
+ return { idFromName: (n) => id(String(n)), idFromString: (s) => id(String(s)), newUniqueId: () => id('do-' + (instances.size + 1) + '-' + Math.random().toString(36).slice(2, 8)),
24868
+ get(i) { const key = String(i); return new Proxy({}, { get: (_, prop) => prop === 'then' ? undefined : prop === 'id' ? id(key) : async (...args) => { const o = await instance(key); if (prop === 'fetch' && typeof o.fetch !== 'function') throw new Error('AgentTwin: ' + name + ' has no fetch handler'); return o[prop](...args); } }); },
24869
+ getByName(n) { return this.get(this.idFromName(n)); } };
24870
+ }
24871
+ const unsupported = (kind, name) => new Proxy({}, { get: (_, p) => p === 'then' ? undefined : () => { throw new Error('AgentTwin: the Workers binding ' + name + ' (' + kind + ') is not modelled'); } });
24872
+
24873
+ /** The env a Worker's fetch(request, env, ctx) receives: process settings, wrangler vars, then bindings. */
24874
+ export async function environment(file, module) {
24875
+ const cfg = readConfig(file), env = {};
24876
+ for (const [k, v] of Object.entries(process.env)) if (typeof v === 'string') env[k] = v;
24877
+ for (const [k, v] of Object.entries(cfg.vars)) if (process.env[k] === undefined || process.env[k] === '') env[k] = typeof v === 'string' ? v : JSON.stringify(v);
24878
+ for (const b of cfg.kv) env[b.binding] = kvNamespace();
24879
+ for (const b of cfg.r2) env[b.binding] = r2Bucket();
24880
+ for (const b of cfg.other) env[b.name] = unsupported(b.kind, b.name);
24881
+ for (const b of cfg.durable) { const Class = module[b.class_name]; env[b.name] = typeof Class === 'function' ? await durableNamespace(Class, env, b.name) : unsupported('durable object ' + b.class_name, b.name); }
24882
+ globalThis.__agenttwinWorkersEnv = env;
24883
+ return env;
24884
+ }
24885
+ `;
24886
+ }
24887
+ });
24888
+
24555
24889
  // src/runtime/engines/mysql-sql.ts
24556
24890
  function tokenize(sql) {
24557
24891
  const tokens = [];
@@ -25496,6 +25830,7 @@ function accountPreset(pack, calls, context2 = {}) {
25496
25830
  }
25497
25831
  function sdkCallPath(call2, collections, pack) {
25498
25832
  if (call2.path || !call2.write) return;
25833
+ if (/^(?:create|add|update|delete|del|remove)[A-Z]/.test(call2.operation.split(".").pop() ?? "")) return;
25499
25834
  const named = pack ? packMethodCollection(pack, call2.operation) : void 0;
25500
25835
  if (named) return collections.includes(named) ? named : void 0;
25501
25836
  const parts = call2.operation.split(".").filter(Boolean);
@@ -25579,12 +25914,12 @@ import { spawnSync as spawnSync2 } from "child_process";
25579
25914
  import { dirname as dirname16, join as join57, posix as posix5, relative as relative18 } from "path";
25580
25915
  import { pathToFileURL as pathToFileURL2 } from "url";
25581
25916
  function fieldValue(name, message, channel) {
25582
- const n = name.toLowerCase();
25917
+ const n = name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
25583
25918
  if (/^subscription_?item(_?id)?$/.test(n)) return "si_at_1001";
25584
25919
  if (/payment_?method_?types?$/.test(n)) return /types$/.test(n) ? ["card"] : "card";
25585
25920
  if (/payment_?method(_?id)?$/.test(n)) return "pm_card_visa";
25586
25921
  if (/options$|metadata$|config$|settings$/.test(n)) return null;
25587
- if (/^(is|has|should|can)_?[a-z]|enabled$|confirm$/.test(n)) return true;
25922
+ if (/^(is|has|should|can)_[a-z]|enabled$|confirm$/.test(n)) return true;
25588
25923
  if (/quantity|count$|^qty$|seats/.test(n)) return 1;
25589
25924
  if (/url$|uri$|link$/.test(n)) return "https://example.test/return";
25590
25925
  if (/country/.test(n)) return "US";
@@ -25664,8 +25999,13 @@ function discoverServices(candidate, inventorySteps) {
25664
25999
  return t === "postgresql" ? "postgres" : t === "google oauth" ? "google-oauth" : t === "google calendar" ? "google-calendar" : /^aws\b|amazon/.test(t) ? "aws" : t.replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
25665
26000
  };
25666
26001
  const out = /* @__PURE__ */ new Map();
26002
+ const hostKey = (step) => {
26003
+ const host = step.operations.map((op2) => /^HTTP \w+ ([a-z0-9.-]+\.[a-z]{2,})/i.exec(op2)?.[1]).find(Boolean) ?? (/^[a-z0-9.-]+\.[a-z]{2,}$/i.test(step.title) ? step.title : void 0);
26004
+ const hit = host ? fetchHosts().find(([re]) => re.test(`https://${host}/`)) : void 0;
26005
+ return hit ? String(hit[1]).replace(/^pack:/, "") : void 0;
26006
+ };
25667
26007
  for (const step of inventorySteps) {
25668
- const key3 = keyOf(step.title);
26008
+ const key3 = hostKey(step) ?? keyOf(step.title);
25669
26009
  const s = out.get(key3) ?? { key: key3, title: step.title, kind: step.kind, operations: [], calls: [], hosts: [] };
25670
26010
  for (const op2 of step.operations) {
25671
26011
  if (!s.operations.includes(op2)) s.operations.push(op2);
@@ -25694,7 +26034,7 @@ async function generateScenario(candidate, ask, discovered = discoverServices(ca
25694
26034
  })));
25695
26035
  const twins2 = discovered.map(resolveTwin);
25696
26036
  const plan = (key3) => twins2.find((t, i) => discovered[i].key === key3 && t.service);
25697
- const calls = (p) => candidate.calls.filter((c) => c.provider === p);
26037
+ const calls = (p) => candidate.calls.filter((c) => c.provider === p || c.provider === `pack:${p}`);
25698
26038
  const refunds = calls("stripe").some((c) => /^refunds\.create$/.test(c.operation));
25699
26039
  const message = refunds ? `Hi, I was charged twice for the same item on order #${SYNTHETIC.order} (charge ${SYNTHETIC.charge}, $${(SYNTHETIC.amount / 100).toFixed(2)}). Please refund the duplicate $${(SYNTHETIC.refundAmount / 100).toFixed(2)}.` : calls("hubspot").length || candidate.tools.some((t) => /deal/i.test(t.name)) ? `Hi, we are ready to sign. Please close deal ${SYNTHETIC.deal} and send the contract.` : `Hi, I need help with order #${SYNTHETIC.order}. Can you take care of it?`;
25700
26040
  const slackCall = calls("slack").find((c) => /postMessage/.test(c.operation));
@@ -25849,6 +26189,7 @@ async function generateScenario(candidate, ask, discovered = discoverServices(ca
25849
26189
  const target = service.collections.find((c) => c.path === path2);
25850
26190
  if (!target) continue;
25851
26191
  write3(service.name, "stripe", path2, call2.operation, call2);
26192
+ if (/\.(create|update|delete)[A-Z]/.test(call2.operation)) continue;
25852
26193
  assertions.push(path2 === "/v1/refunds" ? { service: service.name, path: path2, count: 1, where: { charge: SYNTHETIC.charge } } : { service: service.name, path: path2, count: target.seed.length + 1 });
25853
26194
  }
25854
26195
  } else if (adapter === "slack") {
@@ -25862,12 +26203,13 @@ async function generateScenario(candidate, ask, discovered = discoverServices(ca
25862
26203
  const repos = collection(service, "/repos"), seen = /* @__PURE__ */ new Set();
25863
26204
  const GITHUB_PATHS = { "issues.create": "/issues", "pulls.create": "/pulls", "issues.createComment": "/comments", "checks.create": "/check-runs" };
25864
26205
  for (const call2 of calls("github")) {
25865
- const owner = String(call2.args?.owner ?? "acme"), repo = String(call2.args?.repo ?? "app"), full = `${owner}/${repo}`;
26206
+ const inUrl = /^\/repos\/([^/{}]+)\/([^/{}]+)(?:\/(issues|pulls|check-runs)(?:\/\{id\}\/(comments))?)?/.exec(call2.path ?? "");
26207
+ const owner = String(call2.args?.owner ?? inUrl?.[1] ?? "acme"), repo = String(call2.args?.repo ?? inUrl?.[2] ?? "app"), full = `${owner}/${repo}`;
25866
26208
  if (!seen.has(full)) {
25867
26209
  seen.add(full);
25868
26210
  repos.seed.push({ id: 100 + seen.size, name: repo, full_name: full, owner: { login: owner }, private: false, default_branch: "main" });
25869
26211
  }
25870
- const path2 = GITHUB_PATHS[call2.operation.replace(/^rest\./, "")];
26212
+ const path2 = GITHUB_PATHS[call2.operation.replace(/^rest\./, "")] ?? (inUrl && (call2.method ?? "GET") === "POST" ? inUrl[4] ? "/comments" : inUrl[3] ? "/" + inUrl[3] : void 0 : void 0);
25871
26213
  if (call2.write && path2 && service.collections.some((c) => c.path === path2)) {
25872
26214
  write3(service.name, "github", path2, call2.operation, call2);
25873
26215
  assertions.push({ service: service.name, path: path2, count: collection(service, path2).seed.length + 1 });
@@ -25908,6 +26250,16 @@ async function generateScenario(candidate, ask, discovered = discoverServices(ca
25908
26250
  }
25909
26251
  }
25910
26252
  if (service.collections.some((c) => c.seed.length)) assumptions.push(`HubSpot twin seeded with deal ${SYNTHETIC.deal} (stage appointmentscheduled).`);
26253
+ } else if (adapter === "jira") {
26254
+ const projects = collection(service, "/rest/api/3/project"), issues = calls("jira").filter((c) => c.write && (c.path ?? "").replace(/\?.*$/, "") === "/rest/api/3/issue");
26255
+ const keys = new Set(calls("jira").map((c) => c.args?.fields?.project?.key).filter((k) => typeof k === "string" && /^[A-Z][A-Z0-9_]{1,9}$/.test(k)));
26256
+ if (!keys.size) keys.add("OPS");
26257
+ for (const key3 of keys) if (!projects.seed.some((p) => p.key === key3)) projects.seed.push({ id: String(1e4 + projects.seed.length), key: key3, name: `${key3} project` });
26258
+ assumptions.push(`Jira twin holds project${keys.size === 1 ? "" : "s"} ${[...keys].join(", ")}.`);
26259
+ if (issues.length) {
26260
+ if (!issues.some((c) => c.repeats || c.conditional)) assertions.push({ service: service.name, path: "/rest/api/3/issue", count: collection(service, "/rest/api/3/issue").seed.length + issues.length });
26261
+ write3(service.name, "jira", "/rest/api/3/issue", "POST /rest/api/3/issue", ...issues);
26262
+ }
25911
26263
  } else if (adapter === "twilio") {
25912
26264
  const sends = calls("twilio").filter((c) => /messages\.create/.test(c.operation));
25913
26265
  if (sends.length) {
@@ -25985,7 +26337,10 @@ async function generateScenario(candidate, ask, discovered = discoverServices(ca
25985
26337
  for (const call2 of own.filter((c) => c.write && (c.method ?? "POST") === "POST" && (c.path || sdkCallPath(c, paths, pack)))) {
25986
26338
  const path2 = (call2.path ?? sdkCallPath(call2, paths, pack)).split("?")[0].replace(/\/\{[^}]+\}.*$/, "");
25987
26339
  if (!service.collections.some((c) => c.path === path2)) continue;
25988
- if (!assertions.some((a) => a.service === service.name && a.path === path2)) assertions.push({ service: service.name, path: path2, count: collection(service, path2).seed.length + 1 });
26340
+ if (/\/\{[^}]+\}\/[^{]/.test(call2.path ?? "")) continue;
26341
+ const last = (path2.split("/").filter(Boolean).pop() ?? "").toLowerCase().replace(/-/g, "_"), types = packRecord(pack)?.resources ?? [];
26342
+ const stored = !types.length || types.some((t) => [t, t + "s", t + "es", t.replace(/y$/, "ies")].includes(last));
26343
+ if (stored && !call2.repeats && !assertions.some((a) => a.service === service.name && a.path === path2)) assertions.push({ service: service.name, path: path2, count: collection(service, path2).seed.length + 1 });
25989
26344
  write3(service.name, adapter, path2, `POST ${path2}`, call2);
25990
26345
  }
25991
26346
  if (preset.doorRecords && candidate.bolt) {
@@ -26138,12 +26493,15 @@ async function prepareWorkflow(cwd, candidate, ask, log, discovered) {
26138
26493
  } else if (reason) scenario.assumptions.push(`No sign-in before the request: ${reason}. Workflows that need a user will find none.`);
26139
26494
  }
26140
26495
  const restDatabase = scenario.services.some((sv) => typeof sv.adapter === "string" && sv.adapter.startsWith("pack:") && (packRecord(sv.adapter.slice(5))?.hosts ?? []).some((h2) => /rest/.test(h2.pathPattern ?? "")));
26141
- if ((candidate.web?.appDir !== void 0 || restDatabase) && !scenario.twins.some((t) => t.engine?.kind === "postgres") && scenario.postgresSchemaFiles === void 0) {
26142
- const files = await discoverAppPostgresSchema(cwd, candidate.web?.appDir ?? "");
26143
- if (files?.length) {
26496
+ const servedPostgres = !!candidate.serve && usesPostgresDriver(cwd);
26497
+ if ((candidate.web?.appDir !== void 0 || restDatabase || servedPostgres) && !scenario.twins.some((t) => t.engine?.kind === "postgres") && scenario.postgresSchemaFiles === void 0) {
26498
+ const appDir = candidate.web?.appDir ?? (candidate.serve ? posix5.dirname(candidate.serve.entry ?? candidate.file) : "");
26499
+ const found = await discoverAppPostgresSchema(cwd, candidate.web?.appDir ?? "");
26500
+ const files = found?.length ? found : servedPostgres ? await discoverWorkspaceSchema(cwd, appDir) : void 0;
26501
+ if (files?.length || servedPostgres) {
26144
26502
  scenario.twins.push({ tier: "engine", provider: "PostgreSQL engine", name: "postgres", title: "PostgreSQL", note: "Embedded PostgreSQL (PGlite); project schema validation pending", engine: { kind: "postgres" } });
26145
26503
  scenario.postgresSchemaMode = "explicit";
26146
- scenario.postgresSchemaFiles = files;
26504
+ scenario.postgresSchemaFiles = files ?? [];
26147
26505
  }
26148
26506
  }
26149
26507
  if (scenario.twins.some((t) => t.engine?.kind === "postgres")) {
@@ -26166,11 +26524,22 @@ async function prepareWorkflow(cwd, candidate, ask, log, discovered) {
26166
26524
  }
26167
26525
  return [];
26168
26526
  };
26169
- const files = mode === "auto" ? await nearest() : scenario.postgresSchemaFiles ?? [];
26527
+ let files = mode === "auto" ? await nearest() : scenario.postgresSchemaFiles ?? [];
26170
26528
  scenario.postgresSchemaMode = mode;
26171
- await loadPostgresSchema(cwd, files);
26529
+ let unreadable = false;
26530
+ try {
26531
+ await loadPostgresSchema(cwd, files);
26532
+ } catch (error) {
26533
+ const why = error instanceof Error ? error.message : String(error);
26534
+ if (!/Unsupported ORM schema|Unsupported SQL|not supported/i.test(why)) throw error;
26535
+ log(` PostgreSQL: ${why.split(". ")[0]}; the app gets an empty database instead.`);
26536
+ const note = `The project's PostgreSQL schema could not be read (${why.slice(0, 160)}); the database starts empty. Supply SQL migrations to check its writes.`;
26537
+ if (!scenario.assumptions.includes(note)) scenario.assumptions.push(note);
26538
+ files = [];
26539
+ unreadable = true;
26540
+ }
26172
26541
  scenario.postgresSchemaFiles = files;
26173
- if (!files.length) {
26542
+ if (!files.length && !unreadable) {
26174
26543
  log(" PostgreSQL: no schema or migrations found, so the app gets an empty database; writes to tables it does not create itself are not checked.");
26175
26544
  const note = "No PostgreSQL schema or migrations were found: the database starts empty and its writes are not checked.";
26176
26545
  if (!scenario.assumptions.includes(note)) scenario.assumptions.push(note);
@@ -26229,6 +26598,12 @@ try{
26229
26598
  setTimeout(()=>process.exit(),1000).unref();
26230
26599
  `;
26231
26600
  const serveEntry = serve?.entry ?? candidate.file;
26601
+ const workersConfig = (() => {
26602
+ for (let dir = posix5.dirname(serveEntry); ; dir = posix5.dirname(dir)) {
26603
+ for (const f of ["wrangler.jsonc", "wrangler.json", "wrangler.toml"]) if (existsSync9(join57(cwd, dir, f))) return join57(cwd, dir, f);
26604
+ if (dir === "." || dir === "/" || dir === "") return void 0;
26605
+ }
26606
+ })();
26232
26607
  const serveDriver = serve ? `// Generated by AgentTwin: starts ${serve.script ? `the app with its "${serve.script.name}" script (${serve.script.command})` : serveEntry} and sends ${serve.method} ${serve.path} to it on twins.
26233
26608
  import {pathToFileURL} from 'node:url';
26234
26609
  import {spawn} from 'node:child_process';
@@ -26262,6 +26637,11 @@ try{
26262
26637
  while(words.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(words[0])){const [k,...v]=words.shift().split('=');env[k]=v.join('=');}
26263
26638
  const tool=words.shift(),local=bins.split(':').map(d=>d+'/'+tool).find(p=>existsSync(p));
26264
26639
  if(tool==='node'){file=process.execPath;args=words;}else if(local){file=local;args=words;}
26640
+ // ts-node's ESM loader fails on current Node and TypeScript releases: the TypeScript loader this driver runs under
26641
+ // does the same job. --watch restarts are dropped; one run is enough.
26642
+ if(tool==='node'){const tsx=process.execArgv[process.execArgv.indexOf('--import')+1];const out=[];
26643
+ for(let i=0;i<args.length;i++){const a=args[i];if(/^--(?:experimental-)?loader$/.test(a)&&/^ts-node\\/esm/.test(args[i+1]??'')){if(tsx)out.push('--import',tsx);i++;continue;}if(/^--(?:experimental-)?loader=ts-node\\/esm/.test(a)){if(tsx)out.push('--import',tsx);continue;}if(a==='--watch')continue;out.push(a);}
26644
+ args=out;}
26265
26645
  }
26266
26646
  child=spawn(file,args,{cwd:script.dir,env,stdio:['ignore','pipe','pipe'],detached:true});
26267
26647
  const keep=chunk=>{const text=chunk.toString();watch(text);process.stderr.write(text);};
@@ -26269,10 +26649,48 @@ try{
26269
26649
  port=await waitFor([free,listenPort]);
26270
26650
  if(!port)throw new Error(exited!==null?'The app stopped while starting ('+script.command+' exited with code '+exited+').':'The app did not start listening within 90 seconds of '+script.command+'.');
26271
26651
  }else{
26652
+ // Every port the app's own code binds counts, wherever its configuration put it.
26653
+ const bound=[];const listen0=net.Server.prototype.listen;
26654
+ net.Server.prototype.listen=function(...a){this.once('listening',()=>{const ad=this.address();if(ad&&typeof ad==='object'&&!bound.includes(ad.port))bound.push(ad.port);});return listen0.apply(this,a);};
26655
+ const workersConfig=${JSON.stringify(workersConfig ?? null)};
26656
+ let workers;if(workersConfig){const {writeFileSync}=await import('node:fs');const shim=${JSON.stringify(join57(cwd, ".agenttwin", "workers-env.mjs"))};writeFileSync(shim,${JSON.stringify(WORKERS_ENV)});workers=await import(pathToFileURL(shim).href);workers.install();}
26272
26657
  const module=await import(pathToFileURL(${JSON.stringify(join57(cwd, serveEntry))}).href);
26273
- port=await waitFor([free,listenPort]);
26274
- const app=module.app??module.default;
26275
- if(!port&&app&&typeof app.listen==='function'){port=await new Promise(resolve=>{const server=app.listen(0,'127.0.0.1',()=>resolve(server.address().port));});}
26658
+ const workersEnv=workers?await workers.environment(workersConfig,module):undefined;
26659
+ const quick=async ports=>{const end=Date.now()+3000;while(Date.now()<end){for(const p of [...ports,...bound,...printed])if(p&&!taken.has(p)&&await open(p))return p;await new Promise(r=>setTimeout(r,100));}};
26660
+ port=await quick([free,listenPort]);
26661
+ const values=[module.app,module.default,...Object.values(module)].filter((v,i,all)=>v&&all.indexOf(v)===i);
26662
+ // An app object: one that listens (express, koa, fastify) or a fetch handler (Hono, a Workers-style export).
26663
+ const listener=values.find(v=>typeof v.listen==='function'&&(typeof v==='function'||typeof v.use==='function'||typeof v.route==='function'||typeof v.register==='function'));
26664
+ if(!port&&listener){port=await new Promise(resolve=>{const server=listener.listen(0,'127.0.0.1',()=>resolve(server.address().port));});}
26665
+ const handler=!port&&values.find(v=>typeof v.fetch==='function');
26666
+ if(handler){
26667
+ const http=await import('node:http');
26668
+ const server=http.createServer(async(req,res)=>{
26669
+ try{
26670
+ const chunks=[];for await(const c of req)chunks.push(c);
26671
+ const body=chunks.length&&!['GET','HEAD'].includes(req.method)?Buffer.concat(chunks):undefined;
26672
+ const headers=new Headers();for(const [k,v] of Object.entries(req.headers))if(v!==undefined)headers.set(k,Array.isArray(v)?v.join(', '):String(v));
26673
+ const reply=await handler.fetch(new Request('http://'+(req.headers.host??'127.0.0.1')+req.url,{method:req.method,headers,body}),workersEnv??process.env,{waitUntil(){},passThroughOnException(){}});
26674
+ res.writeHead(reply.status,Object.fromEntries(reply.headers));res.end(Buffer.from(await reply.arrayBuffer()));
26675
+ }catch(e){res.writeHead(500,{'content-type':'text/plain'});res.end(String(e&&e.stack||e));}
26676
+ });
26677
+ port=await new Promise(resolve=>server.listen(0,'127.0.0.1',()=>resolve(server.address().port)));
26678
+ }
26679
+ // A start function the module exports (startServer, runserver, createApp().listen inside): call it as main would.
26680
+ if(!port){
26681
+ const starters=Object.entries(module).filter(([name,fn])=>typeof fn==='function'&&/^(?:start|run|launch|boot|serve|listen|main)/i.test(name)&&!/^(?:stop|close|shutdown)/i.test(name));
26682
+ for(const [,fn] of starters){
26683
+ // Options first (startServer({port})); a function whose first parameter is something else (a list of
26684
+ // routes) throws on them, so it is called again with its own defaults, as the app's main does.
26685
+ const note=out=>{const p=out&&(out.port??(typeof out.address==='function'?out.address()?.port:undefined));if(typeof p==='number')printed.add(p);};
26686
+ try{note(await fn(fn.length?{port:free,host:'127.0.0.1'}:undefined));}catch(e){
26687
+ if(fn.length){try{note(await fn());}catch(e2){process.stderr.write('[agenttwin] '+String(e2&&e2.message||e2)+'\\n');}}
26688
+ else process.stderr.write('[agenttwin] '+String(e&&e.message||e)+'\\n');
26689
+ }
26690
+ port=await quick([free,listenPort]);if(port)break;
26691
+ }
26692
+ }
26693
+ if(!port)port=await waitFor([free,listenPort,...bound]);
26276
26694
  if(!port)throw new Error('The app did not start listening on PORT ('+free+')${serve.listenPort ? ` or ${serve.listenPort}` : ""}, and ${serveEntry} exports no app to start.');
26277
26695
  }
26278
26696
  for(const [index,args] of calls.entries()){
@@ -26510,11 +26928,48 @@ function ensurePrismaClient(cwd, appDir) {
26510
26928
  `);
26511
26929
  }
26512
26930
  }
26513
- var FORBIDDEN_ENV, TWIN_ENV, DATABASE_ENV, slugName, SCALAR_PARAM, SYNTHETIC, stripePath, TIER_LABEL, tierLabel2, PRETTY, FN2, SLACK_CLIENT, SAY, packTitle, readFileSyncSafe;
26931
+ function usesPostgresDriver(cwd) {
26932
+ const deps = (dir) => {
26933
+ try {
26934
+ const p = JSON.parse(readFileSync11(join57(cwd, dir, "package.json"), "utf8"));
26935
+ return Object.keys({ ...p.dependencies, ...p.devDependencies });
26936
+ } catch {
26937
+ return [];
26938
+ }
26939
+ };
26940
+ const dirs2 = ["."];
26941
+ for (const base of ["packages", "apps", "services", "server", "backend"]) try {
26942
+ for (const e of readdirSync4(join57(cwd, base), { withFileTypes: true })) if (e.isDirectory()) dirs2.push(join57(base, e.name));
26943
+ dirs2.push(base);
26944
+ } catch {
26945
+ }
26946
+ if (dirs2.some((d2) => deps(d2).some((n) => POSTGRES_DRIVERS.includes(n)))) return true;
26947
+ return dirs2.some((d2) => deps(d2).includes("@prisma/client") && ["prisma/schema.prisma", "schema.prisma"].some((f) => {
26948
+ try {
26949
+ return /provider\s*=\s*"postgres(?:ql)?"/.test(readFileSync11(join57(cwd, d2, f), "utf8"));
26950
+ } catch {
26951
+ return false;
26952
+ }
26953
+ }));
26954
+ }
26955
+ async function discoverWorkspaceSchema(cwd, appDir) {
26956
+ const own = appDir && appDir !== "." ? await discoverAppPostgresSchema(cwd, appDir) : void 0;
26957
+ if (own?.length) return own;
26958
+ for (const base of ["packages", "apps", "services"]) try {
26959
+ for (const e of readdirSync4(join57(cwd, base), { withFileTypes: true })) if (e.isDirectory()) {
26960
+ const found = await discoverAppPostgresSchema(cwd, join57(base, e.name));
26961
+ if (found?.length) return found;
26962
+ }
26963
+ } catch {
26964
+ }
26965
+ return void 0;
26966
+ }
26967
+ var FORBIDDEN_ENV, TWIN_ENV, DATABASE_ENV, slugName, SCALAR_PARAM, SYNTHETIC, stripePath, TIER_LABEL, tierLabel2, PRETTY, FN2, SLACK_CLIENT, SAY, packTitle, readFileSyncSafe, POSTGRES_DRIVERS;
26514
26968
  var init_autoprep = __esm({
26515
26969
  "src/flow/autoprep.ts"() {
26516
26970
  "use strict";
26517
26971
  init_http_world();
26972
+ init_workers_env();
26518
26973
  init_postgres_schema();
26519
26974
  init_rabbitmq_assertions();
26520
26975
  init_kafka_assertions();
@@ -26559,6 +27014,7 @@ var init_autoprep = __esm({
26559
27014
  return "";
26560
27015
  }
26561
27016
  };
27017
+ POSTGRES_DRIVERS = ["pg", "postgres", "@neondatabase/serverless", "@vercel/postgres", "pg-promise", "slonik"];
26562
27018
  }
26563
27019
  });
26564
27020
 
@@ -26582,7 +27038,7 @@ function explainCleanRun(f) {
26582
27038
  const edit = `Change "input" in ${f.scenarioPath}, then run npx agenttwin again.`;
26583
27039
  const pm = f.packageManager ?? "npm", run3 = (script) => pm === "npm" ? `npm run ${script}` : `${pm} ${script}`;
26584
27040
  const environment = `"environment" in ${f.scenarioPath}`;
26585
- const envNames2 = [...new Set([...f.stderr.matchAll(/\b([A-Z][A-Z0-9_]{2,})\b(?=[^\n]{0,80}?(?:is (?:not set|missing|required|undefined)|must be set|not defined|Required|Invalid))|(?:missing|required|invalid|not set)[^\n]{0,40}?(?:env(?:ironment)?(?: variables?)?)[:\s]+['"`]?([A-Z][A-Z0-9_]{2,})/gi)].map((m) => m[1] ?? m[2]).filter((n) => n && /^[A-Z0-9_]+$/.test(n)))];
27041
+ const envNames2 = [...new Set([...f.stderr.matchAll(/\b([A-Z][A-Z0-9_]{2,})\b(?=[^\n]{0,80}?(?:is (?:not set|missing|required|undefined)|must be set|not defined|Required|Invalid))|(?:missing|required|invalid|not set)[^\n]{0,40}?(?:env(?:ironment)?(?: variables?)?)[:\s]+['"`]?([A-Z][A-Z0-9_]{2,})/gi)].map((m) => m[1] ?? m[2]).filter((n) => n && /^[A-Z0-9_]+$/.test(n) && !NOT_SETTINGS.test(n)))];
26586
27042
  if (envNames2.length && /env|environment|config|setting/i.test(f.stderr)) return {
26587
27043
  headline: `The app stopped while starting: it needs ${envNames2.slice(0, 3).join(", ")}${envNames2.length > 3 ? ` and ${envNames2.length - 3} more` : ""}.`,
26588
27044
  cause: `It checks its settings when it starts, and ${envNames2.length === 1 ? "that one is" : "those are"} not set. Twins answer for services, so any placeholder value works for an API key.`,
@@ -26691,7 +27147,7 @@ function explainCleanRun(f) {
26691
27147
  next: `Fix the error or adjust the input. ${edit}`
26692
27148
  };
26693
27149
  }
26694
- var short2;
27150
+ var short2, NOT_SETTINGS;
26695
27151
  var init_first_run_help = __esm({
26696
27152
  "src/flow/first-run-help.ts"() {
26697
27153
  "use strict";
@@ -26699,13 +27155,14 @@ var init_first_run_help = __esm({
26699
27155
  const s = JSON.stringify(v);
26700
27156
  return s.length > 90 ? s.slice(0, 87) + "\u2026" : s;
26701
27157
  };
27158
+ NOT_SETTINGS = /^(?:GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS|URL|URI|HTTPS?|JSON|XML|HTML|API|SQL|TLS|SSL|DNS|TCP|UDP|UTF\d*|ESM|CJS|CORS|JWT|UUID|ERR\w*|EOF|NULL|TRUE|FALSE|NAN)$/;
26702
27159
  }
26703
27160
  });
26704
27161
 
26705
27162
  // src/flow/setup.ts
26706
27163
  import { spawn as spawn11, spawnSync as spawnSync3 } from "child_process";
26707
27164
  import { existsSync as existsSync10, readFileSync as readFileSync12, readdirSync as readdirSync5 } from "fs";
26708
- import { join as join58, posix as posix6 } from "path";
27165
+ import { delimiter as delimiter3, join as join58, posix as posix6 } from "path";
26709
27166
  function packageManager(cwd) {
26710
27167
  const field2 = readJson2(join58(cwd, "package.json"))?.packageManager;
26711
27168
  if (typeof field2 === "string") {
@@ -26795,12 +27252,41 @@ function planSetup(cwd, opts = {}) {
26795
27252
  }
26796
27253
  const unbuilt = steps.length || opts.only === "install" ? [] : unbuiltWorkspacePackages(cwd, opts.appDir);
26797
27254
  if (unbuilt.length) {
26798
- const r = existsSync10(join58(cwd, "turbo.json")) && existsSync10(join58(cwd, "node_modules/.bin/turbo")) ? { command: join58(cwd, "node_modules/.bin/turbo"), args: ["run", "build", ...unbuilt.map((d2) => `--filter=./${d2}`)] } : pm.name === "pnpm" ? runner(["-r", ...unbuilt.flatMap((d2) => ["--filter", `./${d2}`]), "run", "build"]) : pm.name === "yarn" ? runner(["workspaces", "foreach", "-R", "--from", `{${unbuilt.join(",")}}`, "run", "build"]) : pm.name === "bun" ? runner(["run", "--filter", "*", "build"]) : runner(["run", "build", ...unbuilt.flatMap((d2) => ["--workspace", d2]), "--if-present"]);
27255
+ const own = pm.name === "pnpm" ? runner(["-r", ...unbuilt.flatMap((d2) => ["--filter", `./${d2}`]), "run", "build"]) : pm.name === "yarn" ? runner(["workspaces", "foreach", "-R", "--from", `{${unbuilt.join(",")}}`, "run", "build"]) : pm.name === "bun" ? runner(["run", "--filter", "*", "build"]) : runner(["run", "build", ...unbuilt.flatMap((d2) => ["--workspace", d2]), "--if-present"]);
27256
+ const turbo = existsSync10(join58(cwd, "turbo.json")) && existsSync10(join58(cwd, "node_modules/.bin/turbo")) ? { command: join58(cwd, "node_modules/.bin/turbo"), args: ["run", "build", ...unbuilt.map((d2) => `--filter=./${d2}`)] } : void 0;
27257
+ const r = turbo ? { ...turbo, fallback: own } : own;
26799
27258
  steps.push({ id: "build", ...r, why: `${unbuilt.length} workspace package${unbuilt.length === 1 ? " is" : "s are"} not built yet (${unbuilt.slice(0, 3).join(", ")}${unbuilt.length > 3 ? "\u2026" : ""})`, dir: cwd });
26800
27259
  }
26801
27260
  const want = opts.only === "build" ? void 0 : nodeWanted(root2.engines?.node);
26802
27261
  return { packageManager: pm.name, steps, ...want ? { node: { want, have: process.versions.node, command: `nvm install ${want} && nvm use ${want}` } } : {} };
26803
27262
  }
27263
+ function installRetry(step, output) {
27264
+ const pm = step.command === "corepack" || step.command === "npx" ? step.args.find((a) => /^(npm|pnpm|yarn|bun)(@|$)/.test(a))?.split("@")[0] : step.command;
27265
+ const tail2 = step.command === "corepack" ? step.args.slice(1) : step.command === "npx" ? step.args.slice(2) : step.args;
27266
+ const pinned = step.command === "corepack" || step.command === "npx" ? step.args.find((a) => /^(npm|pnpm|yarn|bun)(@|$)/.test(a)) : pm;
27267
+ if (pm === "pnpm" && /ERR_PNPM_(OUTDATED_LOCKFILE|LOCKFILE_CONFIG_MISMATCH|LOCKFILE_MISSING_DEPENDENCY)|frozen.lockfile|specifiers in the lockfile/i.test(output))
27268
+ return { why: "The lockfile is behind package.json, so a frozen install stops", step: { ...step, args: [...step.args, "--no-frozen-lockfile"] } };
27269
+ if (pm === "yarn" && /YN0028|lockfile would have been modified|--frozen-lockfile/i.test(output))
27270
+ return { why: "The lockfile is behind package.json, so a frozen install stops", step: { ...step, args: [...step.args, "--no-immutable"] } };
27271
+ if (pm === "pnpm" && /ERR_PNPM_IGNORED_BUILDS/.test(output) && !step.args.some((a) => a.startsWith("--config.dangerously-allow-all-builds")))
27272
+ return { why: "pnpm skipped the dependencies' build scripts", step: { ...step, args: [...step.args, "--config.dangerously-allow-all-builds=true"] } };
27273
+ if (pm === "bun" && step.command === "corepack")
27274
+ return { why: "corepack cannot fetch bun", step: { ...step, command: "npx", args: ["--yes", pinned, ...tail2] } };
27275
+ if (pm === "npm" && /EBADENGINE|notsup|Unsupported engine/i.test(output) && !step.args.includes("--engine-strict=false"))
27276
+ return { why: "The project's engines field does not allow this Node version", step: { ...step, args: [...step.args, "--engine-strict=false"] } };
27277
+ }
27278
+ async function corepackShims(cwd, steps) {
27279
+ const pm = packageManager(cwd).name;
27280
+ const managers = [.../* @__PURE__ */ new Set([...steps.filter((s) => s.command === "corepack").map((s) => s.args[0]?.split("@")[0]), pm])].filter((m) => (m === "pnpm" || m === "yarn") && !has(m));
27281
+ if (!managers.length || !steps.length || !has("corepack")) return;
27282
+ const dir = join58(cwd, ".agenttwin", "bin");
27283
+ const ok4 = await new Promise((resolve35) => {
27284
+ const c = spawn11("corepack", ["enable", "--install-directory", dir, ...managers], { stdio: "ignore" });
27285
+ c.once("error", () => resolve35(false));
27286
+ c.once("exit", (code) => resolve35(code === 0));
27287
+ });
27288
+ return ok4 ? dir : void 0;
27289
+ }
26804
27290
  async function runSetup2(cwd, opts) {
26805
27291
  const plan = opts.plan ?? planSetup(cwd, { ...opts.appDir !== void 0 ? { appDir: opts.appDir } : {}, ...opts.only ? { only: opts.only } : {} });
26806
27292
  if (plan.node) opts.log(` ! This project asks for Node.js ${plan.node.want}; this machine runs ${plan.node.have}. If the app fails to start, run: ${plan.node.command}`);
@@ -26811,26 +27297,38 @@ async function runSetup2(cwd, opts) {
26811
27297
  opts.log(` Skipped. Run ${plan.steps.map(show).join(" && ")} yourself, then npx agenttwin again.`);
26812
27298
  return false;
26813
27299
  }
27300
+ const shims = await corepackShims(cwd, plan.steps);
27301
+ const exec11 = (step) => new Promise((resolve35) => {
27302
+ const child = spawn11(step.command, step.args, { cwd: step.dir, stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, CI: "1", COREPACK_ENABLE_DOWNLOAD_PROMPT: "0", ...shims ? { PATH: `${shims}${delimiter3}${process.env.PATH ?? ""}` } : {} } });
27303
+ let tail2 = "";
27304
+ const keep = (c) => {
27305
+ tail2 = (tail2 + c.toString()).slice(-4e3);
27306
+ };
27307
+ child.stdout.on("data", keep);
27308
+ child.stderr.on("data", keep);
27309
+ child.once("error", (e) => {
27310
+ tail2 += String(e);
27311
+ resolve35({ code: 1, tail: tail2 });
27312
+ });
27313
+ child.once("exit", (c) => resolve35({ code: c ?? 1, tail: tail2 }));
27314
+ });
26814
27315
  for (const step of plan.steps) {
26815
27316
  opts.log(` Running ${show(step)}\u2026`);
26816
- const code = await new Promise((resolve35) => {
26817
- const child = spawn11(step.command, step.args, { cwd: step.dir, stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, CI: "1", COREPACK_ENABLE_DOWNLOAD_PROMPT: "0" } });
26818
- let tail2 = "";
26819
- const keep = (c) => {
26820
- tail2 = (tail2 + c.toString()).slice(-4e3);
26821
- };
26822
- child.stdout.on("data", keep);
26823
- child.stderr.on("data", keep);
26824
- child.once("error", (e) => {
26825
- tail2 += String(e);
26826
- resolve35(1);
26827
- });
26828
- child.once("exit", (c) => {
26829
- if (c !== 0) opts.log(tail2.split("\n").filter(Boolean).slice(-6).map((l) => " " + l.slice(0, 200)).join("\n"));
26830
- resolve35(c ?? 1);
26831
- });
26832
- });
27317
+ let { code, tail: tail2 } = await exec11(step);
27318
+ for (let current2 = step, tries = 0; code !== 0 && step.id === "install" && tries < 3; tries++) {
27319
+ const retry = installRetry(current2, tail2);
27320
+ if (!retry) break;
27321
+ opts.log(` ${retry.why}; running ${show(retry.step)}\u2026`);
27322
+ current2 = retry.step;
27323
+ ({ code, tail: tail2 } = await exec11(retry.step));
27324
+ }
27325
+ if (code !== 0 && step.fallback) {
27326
+ const next = { ...step, ...step.fallback, fallback: void 0 };
27327
+ opts.log(` ${show(step)} failed; running ${show(next)}\u2026`);
27328
+ ({ code, tail: tail2 } = await exec11(next));
27329
+ }
26833
27330
  if (code !== 0) {
27331
+ opts.log(tail2.split("\n").filter(Boolean).slice(-6).map((l) => " " + l.slice(0, 200)).join("\n"));
26834
27332
  opts.log(` ${show(step)} failed (exit ${code}). The run goes on; if the app cannot start, fix that first.`);
26835
27333
  return false;
26836
27334
  }
@@ -27038,15 +27536,15 @@ async function startS3Engine(options = {}) {
27038
27536
  const objects = ensureBucket(bucket) ?? store.get(bucket);
27039
27537
  if (!objects) return error(res, 404, "NoSuchBucket", "The specified bucket does not exist", bucket);
27040
27538
  if (method === "GET" && !url2.searchParams.has("uploads")) {
27041
- const prefix = url2.searchParams.get("prefix") ?? "", delimiter3 = url2.searchParams.get("delimiter");
27539
+ const prefix = url2.searchParams.get("prefix") ?? "", delimiter4 = url2.searchParams.get("delimiter");
27042
27540
  const max = Math.min(Number(url2.searchParams.get("max-keys") ?? 1e3) || 1e3, 1e3);
27043
27541
  const after = url2.searchParams.get("continuation-token") ? Buffer.from(url2.searchParams.get("continuation-token"), "base64").toString() : url2.searchParams.get("start-after") ?? url2.searchParams.get("marker") ?? "";
27044
27542
  let keys = [...objects.keys()].filter((k) => k.startsWith(prefix) && k > after).sort();
27045
27543
  const prefixes = /* @__PURE__ */ new Set();
27046
- if (delimiter3) keys = keys.filter((k) => {
27047
- const rest = k.slice(prefix.length), i = rest.indexOf(delimiter3);
27544
+ if (delimiter4) keys = keys.filter((k) => {
27545
+ const rest = k.slice(prefix.length), i = rest.indexOf(delimiter4);
27048
27546
  if (i < 0) return true;
27049
- prefixes.add(prefix + rest.slice(0, i + delimiter3.length));
27547
+ prefixes.add(prefix + rest.slice(0, i + delimiter4.length));
27050
27548
  return false;
27051
27549
  });
27052
27550
  const page2 = keys.slice(0, max), truncated = keys.length > max;
@@ -29110,7 +29608,9 @@ function findingsFor(clean, run3, fault, candidate) {
29110
29608
  const cleanChecks = [...clean.receipt.assertions, ...clean.receipt.evaluation?.checks ?? []];
29111
29609
  const findings = [];
29112
29610
  for (const f of findingsFromReceipt(run3.receipt, run3.world)) {
29113
- if (!cleanChecks.some((c) => c.passed && sameCheck(c, f))) continue;
29611
+ if (f.kind !== "unconfirmed-announce" && !cleanChecks.some((c) => c.passed && sameCheck(c, f))) continue;
29612
+ if (f.kind === "missing-effect" && /-down$/.test(fault.id)) continue;
29613
+ if (f.kind === "missing-effect" && f.handled) continue;
29114
29614
  if (findings.some((x) => x.proof && sameCheck(x.proof, f))) continue;
29115
29615
  const money2 = f.service === "stripe" || /refunds|charges|payment_intents|payouts/.test(f.path);
29116
29616
  findings.push({ id: `${fault.id}:${f.id}`, severity: f.handled ? "low" : money2 && f.kind === "duplicate-effect" ? "high" : "medium", faultId: fault.id, title: f.title, detail: `${f.service}${f.path}${f.where ? " " + JSON.stringify(f.where) : ""}: expected ${(f.expected ?? 0) - (f.existing ?? 0)} new, recorded ${(f.actual ?? 0) - (f.existing ?? 0)} new`, impact: impactSummary([f]), evidencePath: run3.evidencePath, proof: { ...f, id: `${fault.id}.${f.id}` } });
@@ -29119,7 +29619,7 @@ function findingsFor(clean, run3, fault, candidate) {
29119
29619
  if (clean.genericViolations?.some((c) => c.violation.check === violation.check && c.violation.resource === violation.resource)) continue;
29120
29620
  if (findings.some((x) => x.title === finding.title)) continue;
29121
29621
  const hint = usefulImpact(violation.impact.summary);
29122
- findings.push({ id: `${fault.id}:${finding.id}`, severity: violation.impact.kind === "money" || finding.kind === "duplicate-effect" ? "high" : "medium", faultId: fault.id, title: finding.title, detail: `${violation.check}: ${violation.resource}`, impact: hint ? [hint] : [], evidencePath: run3.evidencePath, proof: finding });
29622
+ findings.push({ id: `${fault.id}:${finding.id}`, severity: violation.advisory ? "low" : violation.impact.kind === "money" || finding.kind === "duplicate-effect" ? "high" : "medium", faultId: fault.id, title: finding.title, detail: `${violation.check}: ${violation.resource}`, impact: hint ? [hint] : [], evidencePath: run3.evidencePath, proof: finding });
29123
29623
  }
29124
29624
  for (const check of run3.defaultChecks.filter((c) => !c.passed)) {
29125
29625
  if (clean.defaultChecks.some((c) => c.id === check.id && !c.passed)) continue;
@@ -29334,16 +29834,24 @@ async function executeSpec(cwd, prepared, effective, opts) {
29334
29834
  const credentials = await world.start();
29335
29835
  const closers = [];
29336
29836
  const engines2 = [];
29837
+ let pgInitial;
29337
29838
  let routing;
29338
29839
  let live;
29339
29840
  try {
29340
29841
  const pgPlan = prepared.scenario.twins.find((t) => t.engine?.kind === "postgres");
29341
29842
  const schemaFiles = prepared.scenario.postgresSchemaFiles ?? [];
29342
29843
  const schemaSql = pgPlan ? await loadPostgresSchema(cwd, schemaFiles) : void 0;
29343
- const pgEngine = pgPlan ? await startPostgresEngine({ ...schemaSql ? { extensions: schemaExtensions(schemaSql).filter((e) => POSTGRES_EXTENSIONS.includes(e)) } : {}, seed: { ...schemaSql ? { sql: schemaSql } : {}, tables: Object.fromEntries((spec.services.find((s) => s.name === pgPlan.name)?.collections ?? []).map((c) => [c.path.slice(1), c.seed])) } }) : void 0;
29844
+ const pgExtensions = schemaSql ? { extensions: schemaExtensions(schemaSql).filter((e) => POSTGRES_EXTENSIONS.includes(e)) } : {};
29845
+ const pgTables = Object.fromEntries((spec.services.find((s) => s.name === pgPlan?.name)?.collections ?? []).map((c) => [c.path.slice(1), c.seed]));
29846
+ const pgEngine = pgPlan ? await startPostgresEngine({ ...pgExtensions, seed: { ...schemaSql ? { sql: schemaSql } : {}, tables: pgTables } }).catch(async (error) => {
29847
+ if (!schemaSql || !/null value in column/.test(String(error instanceof Error ? error.message : error))) throw error;
29848
+ const completed = await rowsForLookups(schemaSql, Object.entries(pgTables).flatMap(([table4, rows2]) => rows2.map((where) => ({ table: table4, where }))));
29849
+ return startPostgresEngine({ ...pgExtensions, seed: { sql: schemaSql, tables: Object.fromEntries(Object.keys(pgTables).map((t) => [t, completed[t] ?? []])) } });
29850
+ }) : void 0;
29344
29851
  if (pgEngine) {
29345
29852
  closers.push(() => pgEngine.stop());
29346
29853
  const state = await pgEngine.readState();
29854
+ if ("tables" in state) pgInitial = asSnapshot(state.tables);
29347
29855
  if ("tables" in state && world.state[pgPlan.name]) for (const table4 of state.tables) {
29348
29856
  const path2 = "/" + table4.name;
29349
29857
  if (Object.hasOwn(world.state[pgPlan.name], path2)) world.state[pgPlan.name][path2] = structuredClone(table4.rows);
@@ -29470,11 +29978,13 @@ async function executeSpec(cwd, prepared, effective, opts) {
29470
29978
  if ("queues" in state) for (const path2 of Object.keys(world.state[twin.name]))
29471
29979
  world.state[twin.name][path2] = structuredClone(state.queues.find((q3) => "/" + q3.name === path2)?.messages ?? []);
29472
29980
  }
29473
- if (assertedEngines.length) {
29981
+ const pgFinal = pgEngine && pgInitial ? await pgEngine.readState().catch(() => void 0) : void 0;
29982
+ const database = pgEngine && pgInitial ? { initial: pgInitial, ...pgFinal && "tables" in pgFinal ? { final: asSnapshot(pgFinal.tables) } : {}, statements: [...pgEngine.statements ?? []] } : void 0;
29983
+ if (assertedEngines.length || database) {
29474
29984
  report.finalState = world.snapshot();
29475
29985
  report.assertions = world.assertions();
29476
29986
  report.evaluation = evaluateState(spec, report.initialState, report.finalState, world.events);
29477
- report.defaultChecks = runDefaultChecks({ spec, initialState: report.initialState, finalState: report.finalState, events: world.events, fault: report.fault });
29987
+ report.defaultChecks = runDefaultChecks({ spec, initialState: report.initialState, finalState: report.finalState, events: world.events, fault: report.fault, ...database ? { database } : {} });
29478
29988
  report.status = report.blockedFetches.length || report.unsupported.length || report.fault && !report.fault.triggered ? "incomplete" : report.application.timedOut || report.application.exitCode !== 0 ? "error" : report.background?.passed === false || report.browser?.passed === false ? "failed" : report.evaluation.outcome === "passed" && report.defaultChecks.every((c) => c.passed) ? "passed" : "failed";
29479
29989
  }
29480
29990
  attachStaticSources(report.events, prepared);
@@ -29492,7 +30002,7 @@ async function executeSpec(cwd, prepared, effective, opts) {
29492
30002
  report.unsupported.push(...engineUnsupported);
29493
30003
  const engineStates = await Promise.all(engines2.filter((e) => ["postgres", "mysql", "kafka", "rabbitmq"].includes(e.engine.kind)).map(async (e) => ({ service: e.twin.name, ...await e.engine.readState() })));
29494
30004
  const kafkaIssues = kafkaDiagnostics(report.assertions, engineStates, report.application.exitCode, opts.engineFault?.fault.type === "drop-after-commit" && faultTriggered ? opts.engineFault.twin : void 0);
29495
- const defaultChecks = opts.repeat > 1 ? runDefaultChecks({ spec, initialState: report.initialState, finalState: report.finalState, events: report.events, fault: report.fault, duplicateDelivery: true }) : report.defaultChecks;
30005
+ const defaultChecks = opts.repeat > 1 ? runDefaultChecks({ spec, initialState: report.initialState, finalState: report.finalState, events: report.events, fault: report.fault, duplicateDelivery: true, ...database ? { database } : {} }) : report.defaultChecks;
29496
30006
  const status = engineUnsupported.length || receiptFaultEngine && !faultTriggered ? "incomplete" : report.status === "passed" && (violations.length && opts.caseInfo.id !== "clean" || opts.repeat > 1 && defaultChecks.some((c) => !c.passed)) ? "failed" : blockedCalls.length && report.status === "passed" ? "incomplete" : report.status;
29497
30007
  const runId = randomUUID14(), out = join62(cwd, ".agenttwin", "runs", runId);
29498
30008
  await mkdir23(out, { recursive: true });
@@ -29739,6 +30249,8 @@ async function runOneCommand(opts) {
29739
30249
  if (!opts.skipSetup) {
29740
30250
  let appDir = posix7.dirname(candidate.serve?.entry ?? candidate.file);
29741
30251
  while (appDir !== "." && !existsSync11(join62(cwd, appDir, "package.json"))) appDir = posix7.dirname(appDir);
30252
+ const ownLock = ["package-lock.json", "pnpm-lock.yaml", "yarn.lock", "bun.lock", "bun.lockb"].some((f) => existsSync11(join62(cwd, appDir, f)));
30253
+ if (appDir !== "." && !existsSync11(join62(cwd, appDir, "node_modules")) && (ownLock || !existsSync11(join62(cwd, "node_modules")))) await runSetup2(join62(cwd, appDir), { ask, log, interactive, only: "install" });
29742
30254
  await runSetup2(cwd, { ask, log, interactive, only: "build", appDir: appDir === "." ? "" : appDir });
29743
30255
  }
29744
30256
  log(bold("2/7 Twin") + dim(" generating synthetic starting state and inputs\u2026"));
@@ -29753,6 +30265,18 @@ async function runOneCommand(opts) {
29753
30265
  for (const a of prepared.scenario.assumptions) log(dim(` \xB7 ${a}`));
29754
30266
  log(dim(` Scenario: ${relative19(cwd, prepared.scenarioPath)} (edit to change inputs or expectations)`));
29755
30267
  const runOpts = { seed, integrations };
30268
+ const inputObject = prepared.scenario.input && typeof prepared.scenario.input === "object" && !Array.isArray(prepared.scenario.input) ? prepared.scenario.input : void 0;
30269
+ if (inputObject && prepared.scenario.postgresSchemaFiles?.length) {
30270
+ try {
30271
+ const aligned = await alignInputWithSchema(await loadPostgresSchema(cwd, prepared.scenario.postgresSchemaFiles), inputObject, (v) => typeof v === "string" && v.startsWith("synthetic-"));
30272
+ if (aligned.changed.length) {
30273
+ prepared.scenario.input = aligned.input;
30274
+ await writeFile34(prepared.scenarioPath, JSON.stringify(prepared.scenario, null, 2) + "\n", { mode: 384 });
30275
+ log(dim(` Input matched to the database: ${aligned.changed.join("; ")}`));
30276
+ }
30277
+ } catch {
30278
+ }
30279
+ }
29756
30280
  const liveHosts = (await readConnections(cwd)).connections.map((c) => c.host);
29757
30281
  log(bold("3/7 Run") + dim(liveHosts.length ? " real workflow code against twins\u2026" : " real workflow code against twins (no production calls)\u2026"));
29758
30282
  if (liveHosts.length) log(yellow(` Connected for real: ${liveHosts.join(", ")}. Every case, including faults and duplicate runs, calls these with your key; use a sandbox account. agenttwin disconnect <host> returns a host to its twin.`));
@@ -29958,8 +30482,9 @@ async function runOneCommand(opts) {
29958
30482
  for (const e of clean.events) {
29959
30483
  if (e.operation !== "write") continue;
29960
30484
  const adapter = prepared.scenario.services.find((sv) => sv.name === e.service)?.adapter;
29961
- if (typeof adapter !== "string" || !adapter.startsWith("pack:")) continue;
29962
- const m = /^(POST|PUT|PATCH|DELETE) (\/[^\s?]*)/.exec(e.detail ?? "");
30485
+ if (typeof adapter !== "string" || /^(?:pack:)?(?:openai|anthropic|google-oauth|postgres)$/.test(adapter)) continue;
30486
+ const pack = adapter.startsWith("pack:");
30487
+ const m = /^(POST|PUT|PATCH|DELETE) (\/[^\s?]*)/.exec(e.detail ?? "") ?? (!pack && /^\/[^\s?]*$/.test(e.detail ?? "") ? [void 0, "POST", e.detail] : null);
29963
30488
  if (!m) continue;
29964
30489
  if (m[2].startsWith("/_twin/") || prepared.scenario.signIn && e.service.endsWith("_signin")) continue;
29965
30490
  const path2 = m[2].replace(/\/(?=[^/]*\d)[^/]*_[^/]*$/, "");
@@ -29970,7 +30495,9 @@ async function runOneCommand(opts) {
29970
30495
  observedWrites.push(svc);
29971
30496
  }
29972
30497
  if (!/^\/[a-zA-Z0-9_./-]+$/.test(path2) || path2.includes("//")) continue;
29973
- for (const sv of [prepared.scenario.services, prepared.world.services].map((list4) => list4.find((x) => x.name === e.service))) if (sv && !sv.collections.some((c) => c.path === path2)) sv.collections.push({ path: path2, seed: [] });
30498
+ if (pack) {
30499
+ for (const sv of [prepared.scenario.services, prepared.world.services].map((list4) => list4.find((x) => x.name === e.service))) if (sv && !sv.collections.some((c) => c.path === path2)) sv.collections.push({ path: path2, seed: [] });
30500
+ }
29974
30501
  if (!svc.writes.some((w) => w.path === path2)) svc.writes.push({ path: path2, operation: m[1] === "DELETE" ? "delete" : m[1] === "POST" ? "create" : "update" });
29975
30502
  }
29976
30503
  const faults = integrations.defaultFaultMatrix([...prepared.scenario.writes, ...observedWrites]).filter((f) => !(prepared.scenario.twins.some((t) => t.engine?.kind === "postgres") && f.supported === false && f.id.startsWith("postgres-")));
@@ -29985,7 +30512,7 @@ async function runOneCommand(opts) {
29985
30512
  for (const c of genericFaultMatrix(cleanCalls, { timeouts, max: 16 })) faults.push({ id: c.id, title: c.title, generic: c.fault, ...c.supported ? {} : { supported: false, reason: c.reason } });
29986
30513
  }
29987
30514
  for (const c of cleanProblems) findings.push({ id: `clean:${c.id}`, severity: c.impact.kind === "money" || c.impact.kind === "data-integrity" ? "high" : "medium", faultId: "clean", title: c.finding ?? c.title, detail: `${c.check}: ${c.service}${c.path}`, impact: [c.impact.summary], evidencePath: clean.evidencePath });
29988
- for (const { violation, finding } of clean.genericViolations ?? []) findings.push({ id: `clean:${finding.id}`, severity: violation.impact.kind === "money" || finding.kind === "duplicate-effect" ? "high" : "medium", faultId: "clean", title: finding.title, detail: `${violation.check}: ${violation.resource}`, impact: /^\d+ occurrences?:/.test(violation.impact.summary) ? [] : [violation.impact.summary], evidencePath: clean.evidencePath, proof: finding });
30515
+ for (const { violation, finding } of clean.genericViolations ?? []) findings.push({ id: `clean:${finding.id}`, severity: violation.advisory ? "low" : violation.impact.kind === "money" || finding.kind === "duplicate-effect" ? "high" : "medium", faultId: "clean", title: finding.title, detail: `${violation.check}: ${violation.resource}`, impact: /^\d+ occurrences?:/.test(violation.impact.summary) ? [] : [violation.impact.summary], evidencePath: clean.evidencePath, proof: finding });
29989
30516
  const runnable = faults.filter((f) => f.supported !== false);
29990
30517
  const cases = /* @__PURE__ */ new Map();
29991
30518
  if (candidate.web?.appDir !== void 0 && clean.status === "passed") {
@@ -29999,7 +30526,7 @@ async function runOneCommand(opts) {
29999
30526
  }
30000
30527
  }
30001
30528
  const cleanEvents = clean.events;
30002
- const idle = clean.status === "passed" && !cleanEvents.some((e) => e.operation !== "read") && !clean.assertions.some((a) => a.service !== "none");
30529
+ const idle = clean.status === "passed" && !cleanEvents.some((e) => e.operation !== "read") && !cleanCalls.some((c) => c.isWrite) && !clean.assertions.some((a) => a.service !== "none");
30003
30530
  const emptyReads = [...new Set(cleanEvents.filter((e) => e.operation === "read" && /^SELECT 0$/.test(e.detail ?? "")).map((e) => (e.path ?? "").replace(/^\//, "")))].filter(Boolean);
30004
30531
  if (idle) {
30005
30532
  log(yellow(" The request was accepted, but the app did nothing a test can check: no service was called and no row changed."));
@@ -30213,7 +30740,7 @@ async function runOneCommand(opts) {
30213
30740
  }
30214
30741
  return { ...result2, resultPath, dashboard: link ?? null };
30215
30742
  }
30216
- var specDigest, WEBHOOK_PATH, JOB_PATH, WORKFLOW_KINDS, MONEY_OR_SEND, DATABASE, PAYMENT_PROVIDERS, vendors, routeGroup, GROUP_LIST_LIMIT, FLAT_LIST_LIMIT, PROVIDER_TITLES, TOOLCHAIN_HOST, NON_HTTP_PORTS, statusMark, diffLines, TELEMETRY;
30743
+ var specDigest, asSnapshot, WEBHOOK_PATH, JOB_PATH, WORKFLOW_KINDS, MONEY_OR_SEND, DATABASE, PAYMENT_PROVIDERS, vendors, routeGroup, GROUP_LIST_LIMIT, FLAT_LIST_LIMIT, PROVIDER_TITLES, TOOLCHAIN_HOST, NON_HTTP_PORTS, statusMark, diffLines, TELEMETRY;
30217
30744
  var init_one_command = __esm({
30218
30745
  "src/flow/one-command.ts"() {
30219
30746
  "use strict";
@@ -30266,6 +30793,7 @@ var init_one_command = __esm({
30266
30793
  const { sourceBuild: _build, files: _files, ...rest } = spec;
30267
30794
  return createHash31("sha256").update(JSON.stringify(rest)).digest("hex");
30268
30795
  };
30796
+ asSnapshot = (tables) => ({ tables: tables.map((t) => ({ name: t.name, columns: [], rows: structuredClone(t.rows) })) });
30269
30797
  WEBHOOK_PATH = /(^|\/)(webhooks?|callback|events?|inbound|incoming|notifications?|push|hooks?)(\/|$)/i;
30270
30798
  JOB_PATH = /(^|\/)(cron|jobs?|queue|tasks?|scheduled?)(\/|$)/i;
30271
30799
  WORKFLOW_KINDS = ["Events from other services (webhooks)", "Routes that charge or send", "Scheduled and queued jobs", "Other API routes", "Functions that call a service"];
@@ -31030,7 +31558,7 @@ function repairFailureCount(receipt) {
31030
31558
  }
31031
31559
  async function stageRepairPatch(cwd, opts) {
31032
31560
  const { raw, regression } = await repairBaseline(cwd, opts);
31033
- const git2 = repairGit;
31561
+ const git3 = repairGit;
31034
31562
  const patchPath = resolve28(cwd, opts.patch), info2 = await lstat9(patchPath);
31035
31563
  if (!info2.isFile() || info2.size > 2 * 1024 * 1024) throw Error("Repair patch must be a regular file of at most 2 MiB");
31036
31564
  const patch = await readFile49(patchPath);
@@ -31039,28 +31567,28 @@ async function stageRepairPatch(cwd, opts) {
31039
31567
  const stage = await mkdtemp16(join67(tmpdir17(), "agenttwin-repair-index-"));
31040
31568
  const env = { ...gitEnvironment(), GIT_INDEX_FILE: join67(stage, "index") };
31041
31569
  try {
31042
- await git2(cwd, ["read-tree", opts.revision], env);
31570
+ await git3(cwd, ["read-tree", opts.revision], env);
31043
31571
  const snapshot2 = join67(stage, "proposal.patch");
31044
31572
  await writeFile38(snapshot2, patch, { mode: 384, flag: "wx" });
31045
- await git2(cwd, ["apply", "--cached", "--check", "--whitespace=error", "--", snapshot2], env);
31046
- await git2(cwd, ["apply", "--cached", "--whitespace=error", "--", snapshot2], env);
31047
- const changes = (await git2(cwd, ["diff", "--cached", "--no-renames", "--name-status", "-z", opts.revision, "--"], env)).toString().split("\0");
31573
+ await git3(cwd, ["apply", "--cached", "--check", "--whitespace=error", "--", snapshot2], env);
31574
+ await git3(cwd, ["apply", "--cached", "--whitespace=error", "--", snapshot2], env);
31575
+ const changes = (await git3(cwd, ["diff", "--cached", "--no-renames", "--name-status", "-z", opts.revision, "--"], env)).toString().split("\0");
31048
31576
  changes.pop();
31049
31577
  if (!changes.length || changes.length % 2) throw Error("Repair patch has no source changes");
31050
31578
  const files = [];
31051
31579
  for (let index = 0; index < changes.length; index += 2) {
31052
31580
  const [status, file] = changes.slice(index, index + 2);
31053
31581
  if (status !== "M" || !sources.has(file)) throw Error("Repair may only modify existing application source in the trusted regression closure");
31054
- const original = (await git2(cwd, ["ls-tree", opts.revision, "--", file], env)).toString();
31055
- const staged = (await git2(cwd, ["ls-files", "--stage", "--", file], env)).toString();
31582
+ const original = (await git3(cwd, ["ls-tree", opts.revision, "--", file], env)).toString();
31583
+ const staged = (await git3(cwd, ["ls-files", "--stage", "--", file], env)).toString();
31056
31584
  if (!/^100(?:644|755) blob /.test(original) || original.slice(0, 6) !== staged.slice(0, 6)) throw Error("Repair cannot change source file types or permissions");
31057
- const bytes2 = await git2(cwd, ["show", `:${file}`], env);
31585
+ const bytes2 = await git3(cwd, ["show", `:${file}`], env);
31058
31586
  if (bytes2.length > 2 * 1024 * 1024 || bytes2.includes(0)) throw Error("Repair source must be text of at most 2 MiB per file");
31059
31587
  files.push(file);
31060
31588
  }
31061
- const tree = (await git2(cwd, ["write-tree"], env)).toString().trim();
31589
+ const tree = (await git3(cwd, ["write-tree"], env)).toString().trim();
31062
31590
  const identity = { ...env, GIT_AUTHOR_NAME: "AgentTwin repair verifier", GIT_AUTHOR_EMAIL: "repair@agenttwin.invalid", GIT_COMMITTER_NAME: "AgentTwin repair verifier", GIT_COMMITTER_EMAIL: "repair@agenttwin.invalid" };
31063
- const revision = (await git2(cwd, ["-c", "commit.gpgSign=false", "commit-tree", tree, "-p", opts.revision, "-m", "Unreferenced AgentTwin repair candidate"], identity)).toString().trim();
31591
+ const revision = (await git3(cwd, ["-c", "commit.gpgSign=false", "commit-tree", tree, "-p", opts.revision, "-m", "Unreferenced AgentTwin repair candidate"], identity)).toString().trim();
31064
31592
  return { revision, files, patch, regression: raw, specDigest: regression.specDigest };
31065
31593
  } finally {
31066
31594
  await rm22(stage, { recursive: true, force: true });
@@ -31352,6 +31880,25 @@ async function runPrCheck(cwd, opts = {}) {
31352
31880
  const failed = regressions.filter((r) => r.status === "fail");
31353
31881
  const incomplete = regressions.filter((r) => r.status === "incomplete");
31354
31882
  const uncovered = touched.filter((w) => !w.covered && w.operations.some((o) => o.changed));
31883
+ const explored = [];
31884
+ if (opts.explore ?? (runtime === "local" && opts.execute !== false)) {
31885
+ const run3 = opts.runWorkflow ?? (async (workflow) => (await Promise.resolve().then(() => (init_one_command(), one_command_exports))).runOneCommand({ cwd, yes: true, interactive: false, workflow, log: () => {
31886
+ }, integrations: { syncDashboard: async () => void 0 } }));
31887
+ for (const w of uncovered.slice(0, 2)) {
31888
+ log(`Running ${w.title} against twins (no saved check covers it)\u2026`);
31889
+ try {
31890
+ const r = await run3(w.entrypoint ?? w.title);
31891
+ const problems = (r.findings ?? []).filter((f) => f.severity !== "low").map((f) => {
31892
+ const c = r.cost?.find((x) => x.title === f.title)?.estimate;
31893
+ return { title: f.title, severity: f.severity, ...c?.perIncident ? { perIncident: c.perIncident, currency: c.currency ?? "USD" } : {} };
31894
+ });
31895
+ explored.push({ workflow: w.title, status: r.status ?? "incomplete", problems, ...r.fix?.diff && problems.length ? { fix: { title: r.fix.title ?? "Proposed fix", diff: r.fix.diff } } : {} });
31896
+ } catch (error) {
31897
+ explored.push({ workflow: w.title, status: "incomplete", problems: [], reason: error instanceof Error ? error.message.split("\n")[0] : String(error) });
31898
+ }
31899
+ }
31900
+ }
31901
+ const exploredProblems = explored.flatMap((e) => e.problems);
31355
31902
  const money2 = failed.map((r) => r.atRisk).filter((m) => !!m);
31356
31903
  const atRisk = money2.length ? { amount: money2.reduce((s, m) => s + m.amount, 0), currency: money2[0].currency } : void 0;
31357
31904
  const priced = failed.map((r) => r.cost).filter((c) => !!c);
@@ -31378,9 +31925,10 @@ async function runPrCheck(cwd, opts = {}) {
31378
31925
  title: `AgentTwin: calls ${serviceTitle(op2.service)} with no check`,
31379
31926
  message: `This line sends ${serviceTitle(op2.service)} ${op2.operation} (part of "${w.title}"). No AgentTwin check runs it. Run npx agenttwin --workflow ${w.title}, fix what it finds, and commit the saved run in .agenttwin/regressions/.`
31380
31927
  });
31381
- const verdict = failed.length ? "fail" : incomplete.length || notRun.length ? "incomplete" : uncovered.length ? "warn" : "pass";
31928
+ const verdict = failed.length || exploredProblems.length ? "fail" : incomplete.length || notRun.length ? "incomplete" : uncovered.length ? "warn" : "pass";
31382
31929
  const services = [...new Set(touched.flatMap((w) => w.operations.filter((o) => o.changed).map((o) => serviceTitle(o.service))))];
31383
- const headline = verdict === "fail" ? `${failed.length} of ${regressions.length} twin check${regressions.length === 1 ? "" : "s"} failed${atRisk ? ` \xB7 ${formatMoney(atRisk)} at risk` : ""}` : verdict === "incomplete" && notRun.length && !incomplete.length ? `This pull request changes code ${notRun.length === 1 ? "a saved check covers, and the check" : `${notRun.length} saved checks cover, and they`} did not run here` : verdict === "incomplete" ? `${incomplete.length} twin check${incomplete.length === 1 ? "" : "s"} could not run` : verdict === "warn" ? (() => {
31930
+ const worstExplored = exploredProblems.filter((p) => p.perIncident).sort((a, b) => b.perIncident - a.perIncident)[0];
31931
+ const headline = verdict === "fail" && !failed.length ? `${exploredProblems.length} problem${exploredProblems.length === 1 ? "" : "s"} found in ${explored.filter((e) => e.problems.length).map((e) => e.workflow).join(" and ")}${worstExplored ? ` \xB7 up to ${formatMoney({ amount: worstExplored.perIncident, currency: worstExplored.currency })} each time` : ""}` : verdict === "fail" ? `${failed.length} of ${regressions.length} twin check${regressions.length === 1 ? "" : "s"} failed${atRisk ? ` \xB7 ${formatMoney(atRisk)} at risk` : ""}` : verdict === "incomplete" && notRun.length && !incomplete.length ? `This pull request changes code ${notRun.length === 1 ? "a saved check covers, and the check" : `${notRun.length} saved checks cover, and they`} did not run here` : verdict === "incomplete" ? `${incomplete.length} twin check${incomplete.length === 1 ? "" : "s"} could not run` : verdict === "warn" ? (() => {
31384
31932
  const n = new Set(uncovered.flatMap((w) => w.operations.filter((o) => o.changed).map((o) => `${o.file}:${o.line}`))).size;
31385
31933
  return `${n} changed line${n === 1 ? " calls" : "s call"} ${services.length > 1 ? `${services.slice(0, -1).join(", ")} and ${services[services.length - 1]}` : services[0] || "an external service"} with no check`;
31386
31934
  })() : regressions.length === 1 ? "The twin check passed" : regressions.length ? `All ${regressions.length} twin checks passed` : "No agent side effects changed";
@@ -31389,7 +31937,7 @@ async function runPrCheck(cwd, opts = {}) {
31389
31937
  if (opts.execute === false && baseRegressions.length && !notRun.length) notes.push(`${baseRegressions.length} saved check${baseRegressions.length === 1 ? "" : "s"} did not run: this check does not run pull-request code on AgentTwin's servers. To run ${baseRegressions.length === 1 ? "it" : "them"} on every pull request, add AgentTwin to your CI with npx agenttwin check install.`);
31390
31938
  if (runtime === "local" && regressions.length) notes.push("Checks ran directly on the CI machine, not in a container. To isolate them, set AGENTTWIN_RUNNER_IMAGE to a Docker image pinned by digest.");
31391
31939
  if (added.length) notes.push(`This pull request adds ${added.length} check${added.length === 1 ? "" : "s"}. ${added.length === 1 ? "It runs" : "They run"} on later pull requests, after this one is merged: a pull request cannot change the checks that judge it.`);
31392
- return { schema: "agenttwin/pr-check-v1", createdAt: (/* @__PURE__ */ new Date()).toISOString(), base, head, verdict, headline, changedFiles: [...changed], regressions, addedRegressions: added, touched, ...atRisk ? { atRisk } : {}, ...cost ? { cost } : {}, annotations, notes };
31940
+ return { schema: "agenttwin/pr-check-v1", createdAt: (/* @__PURE__ */ new Date()).toISOString(), base, head, verdict, headline, changedFiles: [...changed], regressions, addedRegressions: added, touched, ...explored.length ? { explored } : {}, ...atRisk ? { atRisk } : {}, ...cost ? { cost } : {}, annotations, notes };
31393
31941
  }
31394
31942
  var exec10, SERVICE3, serviceTitle, statusOf;
31395
31943
  var init_pr_check = __esm({
@@ -31434,7 +31982,8 @@ ${r.checks.filter((c) => !c.passed).map((c) => `- ${c.text}`).join("\n")}`,
31434
31982
  }
31435
31983
  function uncoveredLines(report) {
31436
31984
  const byLine = /* @__PURE__ */ new Map();
31437
- for (const w of report.touched.filter((t) => !t.covered)) for (const o of w.operations.filter((op2) => op2.changed)) {
31985
+ const tested = new Set((report.explored ?? []).filter((e) => e.status !== "incomplete").map((e) => e.workflow));
31986
+ for (const w of report.touched.filter((t) => !t.covered && !tested.has(t.title))) for (const o of w.operations.filter((op2) => op2.changed)) {
31438
31987
  const key3 = `${o.file}:${o.line}`, entry = byLine.get(key3) ?? { file: o.file, line: o.line, services: [], sends: [], workflows: [] };
31439
31988
  const service = serviceTitle(o.service), send = `${service} \xB7 \`${o.operation}\``;
31440
31989
  if (!entry.services.includes(service)) entry.services.push(service);
@@ -31456,6 +32005,17 @@ function renderMarkdown(report, opts = {}) {
31456
32005
  if (r.cause) out.push(`> ${r.cause}`);
31457
32006
  out.push("");
31458
32007
  }
32008
+ for (const e of (report.explored ?? []).filter((x) => x.problems.length)) {
32009
+ out.push(`### ${cell(e.workflow)}`, "", "Run on this pull request's code against simulated services, with timeouts, errors, outages and duplicate requests injected.", "", "| Problem | Cost each time |", "|---|---|");
32010
+ for (const p of e.problems.slice(0, 10)) out.push(`| ${cell(p.title)} | ${p.perIncident ? formatMoney({ amount: p.perIncident, currency: p.currency ?? "USD" }) : "\u2014"} |`);
32011
+ out.push("");
32012
+ if (e.fix) out.push("<details><summary><b>Proposed fix:</b> " + cell(e.fix.title) + "</summary>", "", "```diff", e.fix.diff.trim().slice(0, 6e3), "```", "", `Apply and prove it locally: \`npx agenttwin --workflow "${e.workflow}" --fix\``, "</details>", "");
32013
+ else out.push(`Reproduce locally: \`npx agenttwin --workflow "${e.workflow}"\``, "");
32014
+ }
32015
+ const clean = (report.explored ?? []).filter((x) => !x.problems.length && x.status !== "incomplete");
32016
+ if (clean.length) out.push(`<sub>Tested on this pull request with no problems found: ${clean.map((x) => cell(x.workflow)).join(", ")}.</sub>`, "");
32017
+ const couldNot = (report.explored ?? []).filter((x) => x.status === "incomplete");
32018
+ if (couldNot.length) out.push(`<sub>Could not test here: ${couldNot.map((x) => `${cell(x.workflow)}${x.reason ? ` (${cell(x.reason.slice(0, 120))})` : ""}`).join("; ")}.</sub>`, "");
31459
32019
  if (report.regressions.length) {
31460
32020
  out.push("| | Twin check | Touched by this PR | Result |", "|---|---|---|---|");
31461
32021
  for (const r of [...report.regressions].sort((a, b) => Number(b.status === "fail") - Number(a.status === "fail") || Number(b.affected) - Number(a.affected)))
@@ -31557,8 +32117,10 @@ __export(pr_check_github_exports, {
31557
32117
  CHECK_NAME: () => CHECK_NAME,
31558
32118
  actionsTarget: () => actionsTarget,
31559
32119
  checkWorkflow: () => checkWorkflow,
32120
+ postFixSuggestions: () => postFixSuggestions,
31560
32121
  publishCheckRun: () => publishCheckRun,
31561
32122
  startCheckRun: () => startCheckRun,
32123
+ suggestionsFromDiff: () => suggestionsFromDiff,
31562
32124
  upsertComment: () => upsertComment,
31563
32125
  writeActionsOutput: () => writeActionsOutput
31564
32126
  });
@@ -31608,6 +32170,88 @@ async function upsertComment(report, target) {
31608
32170
  }
31609
32171
  return (await api(target, "POST", `/repos/${target.repository}/issues/${target.pullRequest}/comments`, { body })).html_url;
31610
32172
  }
32173
+ function suggestionsFromDiff(diff) {
32174
+ const out = [];
32175
+ let path2, oldLine = 0, prev, block;
32176
+ const flush = () => {
32177
+ if (!block || !path2) {
32178
+ block = void 0;
32179
+ return;
32180
+ }
32181
+ if (block.removed.length) out.push({ path: path2, startLine: block.start, line: block.start + block.removed.length - 1, replacement: block.added.join("\n") });
32182
+ else if (block.start > 1 && prev !== void 0) out.push({ path: path2, startLine: block.start - 1, line: block.start - 1, replacement: [prev, ...block.added].join("\n") });
32183
+ block = void 0;
32184
+ };
32185
+ for (const raw of diff.split("\n")) {
32186
+ if (raw.startsWith("--- ")) {
32187
+ flush();
32188
+ continue;
32189
+ }
32190
+ if (raw.startsWith("+++ ")) {
32191
+ const f = raw.slice(4).trim();
32192
+ path2 = f === "/dev/null" ? void 0 : f.replace(/^b\//, "");
32193
+ continue;
32194
+ }
32195
+ const hunk = /^@@ -(\d+)(?:,\d+)? \+\d+(?:,\d+)? @@/.exec(raw);
32196
+ if (hunk) {
32197
+ flush();
32198
+ oldLine = Number(hunk[1]);
32199
+ prev = void 0;
32200
+ continue;
32201
+ }
32202
+ if (raw.startsWith("-")) {
32203
+ block ??= { start: oldLine, removed: [], added: [] };
32204
+ block.removed.push(raw.slice(1));
32205
+ oldLine++;
32206
+ continue;
32207
+ }
32208
+ if (raw.startsWith("+")) {
32209
+ block ??= { start: oldLine, removed: [], added: [] };
32210
+ block.added.push(raw.slice(1));
32211
+ continue;
32212
+ }
32213
+ if (raw.startsWith(" ") || raw === "") {
32214
+ flush();
32215
+ prev = raw.slice(1);
32216
+ oldLine++;
32217
+ }
32218
+ }
32219
+ flush();
32220
+ return out;
32221
+ }
32222
+ async function postFixSuggestions(report, target) {
32223
+ if (!target.pullRequest) return "none";
32224
+ const fixes = (report.explored ?? []).filter((e) => e.fix?.diff && e.problems.length);
32225
+ const comments = fixes.flatMap((e) => suggestionsFromDiff(e.fix.diff).map((sg) => ({
32226
+ path: sg.path,
32227
+ line: sg.line,
32228
+ side: "RIGHT",
32229
+ ...sg.startLine < sg.line ? { start_line: sg.startLine, start_side: "RIGHT" } : {},
32230
+ body: `**${e.fix.title}** (${e.workflow}: ${e.problems[0].title})
32231
+
32232
+ \`\`\`suggestion
32233
+ ${sg.replacement}
32234
+ \`\`\``
32235
+ }))).slice(0, 30);
32236
+ if (!comments.length) return "none";
32237
+ const { createHash: createHash40 } = await import("crypto");
32238
+ const hash9 = createHash40("sha256").update(fixes.map((e) => e.fix.diff).join("\n")).digest("hex").slice(0, 16);
32239
+ const reviews = await api(target, "GET", `/repos/${target.repository}/pulls/${target.pullRequest}/reviews?per_page=100`);
32240
+ if (reviews.some((r) => r.body?.includes(SUGGESTION_MARKER + hash9))) return "already-posted";
32241
+ try {
32242
+ await api(target, "POST", `/repos/${target.repository}/pulls/${target.pullRequest}/reviews`, {
32243
+ commit_id: target.sha,
32244
+ event: "COMMENT",
32245
+ comments,
32246
+ body: `${SUGGESTION_MARKER}${hash9} -->
32247
+ AgentTwin found ${fixes.length === 1 ? "a problem" : "problems"} in this change and proposes ${comments.length === 1 ? "a fix" : "fixes"}. Each suggestion is the change AgentTwin proposes for the problem shown in its comment; review it, then commit it from here. The next push is checked again.`
32248
+ });
32249
+ return "posted";
32250
+ } catch (error) {
32251
+ if (error.status === 422) return "outside-diff";
32252
+ throw error;
32253
+ }
32254
+ }
31611
32255
  async function writeActionsOutput(report, env = process.env, write3 = (s) => process.stdout.write(s)) {
31612
32256
  if (env.GITHUB_STEP_SUMMARY) await appendFile(env.GITHUB_STEP_SUMMARY, renderMarkdown(report));
31613
32257
  const command = { failure: "error", warning: "warning", notice: "notice" };
@@ -31659,7 +32303,7 @@ jobs:
31659
32303
  GITHUB_TOKEN: \${{ secrets.GITHUB_TOKEN }}
31660
32304
  `;
31661
32305
  }
31662
- var CHECK_NAME, CONCLUSION, MAX_SUMMARY, escapeData, escapeProperty;
32306
+ var CHECK_NAME, CONCLUSION, MAX_SUMMARY, SUGGESTION_MARKER, escapeData, escapeProperty;
31663
32307
  var init_pr_check_github = __esm({
31664
32308
  "src/runtime/pr-check-github.ts"() {
31665
32309
  "use strict";
@@ -31667,6 +32311,7 @@ var init_pr_check_github = __esm({
31667
32311
  CHECK_NAME = "AgentTwin";
31668
32312
  CONCLUSION = { pass: "success", fail: "failure", warn: "neutral", incomplete: "neutral" };
31669
32313
  MAX_SUMMARY = 65e3;
32314
+ SUGGESTION_MARKER = "<!-- agenttwin:fix ";
31670
32315
  escapeData = (s) => s.replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A");
31671
32316
  escapeProperty = (s) => escapeData(s).replace(/:/g, "%3A").replace(/,/g, "%2C");
31672
32317
  }
@@ -31758,7 +32403,7 @@ async function runAutomaticRepair(cwd, opts, runAgent = runCodexRepair) {
31758
32403
  baselineRevision: opts.baseline,
31759
32404
  candidateRevision: opts.revision,
31760
32405
  specDigest: before.specDigest,
31761
- sources: sources.map(({ file, content, sha256: sha2562 }) => ({ file, content, sha256: sha2562 })),
32406
+ sources: sources.map(({ file, content, sha256: sha2563 }) => ({ file, content, sha256: sha2563 })),
31762
32407
  providerContracts: { services: receipt.contracts?.services ?? [], adapters: Object.fromEntries(Object.entries(receipt.contracts?.adapters ?? {}).filter(([name]) => adapters.has(name))) },
31763
32408
  trustedChecks: { assertions: regression.spec.assertions, forbiddenEffects: regression.spec.forbiddenEffects ?? [], preservedState: regression.spec.preservedState ?? [], properties: regression.spec.properties ?? [] },
31764
32409
  failure: { assertions: receipt.assertions, infrastructureAssertions: receipt.infrastructureAssertions ?? [], checks: receipt.evaluation?.checks ?? [], fault: receipt.fault ?? null }
@@ -32001,6 +32646,121 @@ var init_conformance = __esm({
32001
32646
  }
32002
32647
  });
32003
32648
 
32649
+ // src/runtime/release-record.ts
32650
+ var release_record_exports = {};
32651
+ __export(release_record_exports, {
32652
+ buildReleaseRecord: () => buildReleaseRecord,
32653
+ renderReleaseRecord: () => renderReleaseRecord
32654
+ });
32655
+ import { createHash as createHash38 } from "crypto";
32656
+ import { execFileSync } from "child_process";
32657
+ import { readdir as readdir12, readFile as readFile57, stat as stat13 } from "fs/promises";
32658
+ import { join as join78, relative as relative25 } from "path";
32659
+ async function latestResults(cwd) {
32660
+ const auto = join78(cwd, ".agenttwin", "auto"), out = [];
32661
+ for (const wf of await readdir12(auto).catch(() => [])) {
32662
+ const dir = join78(auto, wf, "results");
32663
+ let best;
32664
+ for (const id2 of await readdir12(dir).catch(() => [])) {
32665
+ const file = join78(dir, id2, "result.json"), at = (await stat13(file).catch(() => void 0))?.mtimeMs;
32666
+ if (at && (!best || at > best.at)) best = { file, at };
32667
+ }
32668
+ if (best) out.push(best);
32669
+ }
32670
+ return out.sort((a, b) => a.file.localeCompare(b.file));
32671
+ }
32672
+ async function buildReleaseRecord(cwd, version, now = /* @__PURE__ */ new Date()) {
32673
+ const workflows = [];
32674
+ for (const { file, at } of await latestResults(cwd)) {
32675
+ let r;
32676
+ try {
32677
+ r = JSON.parse(await readFile57(file, "utf8"));
32678
+ } catch {
32679
+ continue;
32680
+ }
32681
+ if (!r || typeof r !== "object" || !Array.isArray(r.runs)) continue;
32682
+ const cases2 = [];
32683
+ for (const run3 of r.runs) {
32684
+ const recorded = typeof run3.evidencePath === "string" ? run3.evidencePath : void 0;
32685
+ const local = recorded ? recorded.includes("/.agenttwin/") ? join78(cwd, recorded.slice(recorded.indexOf("/.agenttwin/") + 1)) : recorded : void 0;
32686
+ const digest6 = local ? await sha2562(local) : void 0;
32687
+ cases2.push({ id: String(run3.id), title: String(run3.title ?? run3.id), status: String(run3.status ?? "unknown"), ...local && digest6 ? { receipt: { path: relative25(cwd, local), sha256: digest6 } } : {} });
32688
+ }
32689
+ workflows.push({
32690
+ title: String(r.workflow?.title ?? r.workflow?.id ?? "workflow"),
32691
+ status: String(r.status ?? "unknown"),
32692
+ testedAt: new Date(at).toISOString(),
32693
+ twins: (r.twins ?? []).map((t) => ({ title: String(t.title ?? t.service), tier: String(t.tier ?? "") })),
32694
+ cases: cases2,
32695
+ findings: (r.findings ?? []).map((f) => ({ title: String(f.title), ...f.severity ? { severity: String(f.severity) } : {}, ...f.faultId ? { fault: String(f.faultId) } : {} })),
32696
+ limitations: (r.limitations ?? []).map(String).slice(0, 10)
32697
+ });
32698
+ }
32699
+ const failed = workflows.filter((w) => w.status === "failed" || w.findings.length).length, passed = workflows.filter((w) => w.status === "passed" && !w.findings.length).length;
32700
+ const incomplete = workflows.length - failed - passed;
32701
+ const cases = workflows.reduce((n, w) => n + w.cases.length, 0);
32702
+ const verdict = !workflows.length ? "nothing-tested" : failed ? "failed" : incomplete ? "incomplete" : "passed";
32703
+ const commit = git2(cwd, ["rev-parse", "HEAD"]), branch = git2(cwd, ["rev-parse", "--abbrev-ref", "HEAD"]), status = git2(cwd, ["status", "--porcelain", "--untracked-files=no"]);
32704
+ return {
32705
+ schema: "agenttwin/release-record-v1",
32706
+ createdAt: now.toISOString(),
32707
+ agenttwinVersion: version,
32708
+ ...commit ? { commit } : {},
32709
+ ...branch ? { branch } : {},
32710
+ ...status !== void 0 ? { dirty: status.length > 0 } : {},
32711
+ project: git2(cwd, ["config", "--get", "remote.origin.url"])?.replace(/^.*[:/]([^/]+\/[^/]+?)(\.git)?$/, "$1") ?? cwd.split("/").pop() ?? "project",
32712
+ verdict,
32713
+ summary: { workflows: workflows.length, passed, failed, incomplete, cases, faults: cases - workflows.length, findings: workflows.reduce((n, w) => n + w.findings.length, 0) },
32714
+ workflows
32715
+ };
32716
+ }
32717
+ function renderReleaseRecord(rec) {
32718
+ const s = rec.summary;
32719
+ const rows2 = rec.workflows.map((w) => `<section><h2>${esc2(w.title)} <span class="st ${esc2(w.findings.length ? "failed" : w.status)}">${esc2(w.findings.length ? "problems found" : w.status)}</span></h2>
32720
+ <p class="meta">Tested ${esc2(w.testedAt.replace("T", " ").slice(0, 16))} UTC \xB7 twins: ${w.twins.map((t) => `${esc2(t.title)} (${esc2(t.tier)})`).join(", ") || "none"}</p>
32721
+ <table><thead><tr><th>Case</th><th>Result</th><th>Receipt (SHA-256)</th></tr></thead><tbody>
32722
+ ${w.cases.map((c) => `<tr><td>${esc2(c.title)}</td><td class="st ${esc2(c.status)}">${esc2(c.status)}</td><td><code>${c.receipt ? esc2(c.receipt.sha256.slice(0, 16)) + "\u2026" : "\u2014"}</code></td></tr>`).join("\n")}
32723
+ </tbody></table>
32724
+ ${w.findings.length ? `<h3>Found</h3><ul>${w.findings.map((f) => `<li>${esc2(f.title)}${f.fault ? ` <span class="meta">(${esc2(f.fault)})</span>` : ""}</li>`).join("")}</ul>` : ""}
32725
+ ${w.limitations.length ? `<details><summary>Limits of this test</summary><ul>${w.limitations.map((l) => `<li>${esc2(l)}</li>`).join("")}</ul></details>` : ""}
32726
+ </section>`).join("\n");
32727
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Release record: ${esc2(rec.project)}</title>
32728
+ <style>:root{--bg:#fff;--fg:#16181d;--mute:#5d6470;--line:#e3e6eb;--ok:#137a3f;--bad:#b3261e;--warn:#8a5a00}@media (prefers-color-scheme:dark){:root{--bg:#121417;--fg:#e8eaee;--mute:#9aa1ad;--line:#2a2e35;--ok:#5fd18e;--bad:#ff8a80;--warn:#f0c060}}
32729
+ body{background:var(--bg);color:var(--fg);font:15px/1.5 system-ui,sans-serif;max-width:860px;margin:0 auto;padding:24px 16px}h1{font-size:22px;margin:0 0 4px}h2{font-size:17px;margin:28px 0 4px}.meta{color:var(--mute);font-size:13px}
32730
+ table{width:100%;border-collapse:collapse;margin:8px 0;font-size:14px}th,td{text-align:left;padding:6px 8px;border-bottom:1px solid var(--line)}th{color:var(--mute);font-weight:500}code{font-size:12px}
32731
+ .st{font-weight:600}.passed{color:var(--ok)}.failed,.error{color:var(--bad)}.incomplete,.nothing-tested{color:var(--warn)}.box{border:1px solid var(--line);border-radius:8px;padding:12px 16px;margin:16px 0}</style></head><body>
32732
+ <h1>Release record \xB7 ${esc2(rec.project)}</h1>
32733
+ <p class="meta">Commit <code>${esc2(rec.commit ?? "unknown")}</code>${rec.branch ? ` on ${esc2(rec.branch)}` : ""}${rec.dirty ? " (with uncommitted changes)" : ""} \xB7 recorded ${esc2(rec.createdAt.replace("T", " ").slice(0, 16))} UTC \xB7 AgentTwin ${esc2(rec.agenttwinVersion)}</p>
32734
+ <div class="box"><p class="st ${esc2(rec.verdict)}" style="font-size:18px;margin:0">${VERDICT2[rec.verdict]}</p>
32735
+ <p style="margin:4px 0 0">${s.workflows} workflow${s.workflows === 1 ? "" : "s"} run against twins of the services they call, with ${s.faults} injected fault${s.faults === 1 ? "" : "s"} (timeouts after a write, server errors, slow replies, a service that stays down, duplicate deliveries). ${s.passed} passed, ${s.failed} with problems, ${s.incomplete} partly tested; ${s.findings} problem${s.findings === 1 ? "" : "s"} found.</p></div>
32736
+ ${rows2 || "<p>No workflow results yet. Run <code>npx agenttwin</code> first.</p>"}
32737
+ <p class="meta" style="margin-top:32px">Built from the run results in <code>.agenttwin/</code>. Each receipt's SHA-256 identifies the exact run file; recompute it with <code>shasum -a 256 &lt;receipt&gt;</code>. Twins are working copies of each service, not the services themselves; the limits of each test are listed with it.</p>
32738
+ </body></html>
32739
+ `;
32740
+ }
32741
+ var git2, sha2562, esc2, VERDICT2;
32742
+ var init_release_record = __esm({
32743
+ "src/runtime/release-record.ts"() {
32744
+ "use strict";
32745
+ git2 = (cwd, args) => {
32746
+ try {
32747
+ return execFileSync("git", ["-C", cwd, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
32748
+ } catch {
32749
+ return void 0;
32750
+ }
32751
+ };
32752
+ sha2562 = async (file) => {
32753
+ try {
32754
+ return createHash38("sha256").update(await readFile57(file)).digest("hex");
32755
+ } catch {
32756
+ return void 0;
32757
+ }
32758
+ };
32759
+ esc2 = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
32760
+ VERDICT2 = { passed: "Passed", failed: "Problems found", incomplete: "Partly tested", "nothing-tested": "Nothing tested" };
32761
+ }
32762
+ });
32763
+
32004
32764
  // src/runtime/exploration.ts
32005
32765
  var exploration_exports = {};
32006
32766
  __export(exploration_exports, {
@@ -32010,9 +32770,9 @@ __export(exploration_exports, {
32010
32770
  runExploration: () => runExploration,
32011
32771
  saveExplorationRegression: () => saveExplorationRegression
32012
32772
  });
32013
- import { createHash as createHash38, randomUUID as randomUUID19 } from "crypto";
32014
- import { mkdir as mkdir34, readFile as readFile57, writeFile as writeFile48, rm as rm26 } from "fs/promises";
32015
- import { dirname as dirname24, join as join78, relative as relative25, resolve as resolve33, sep as sep18 } from "path";
32773
+ import { createHash as createHash39, randomUUID as randomUUID19 } from "crypto";
32774
+ import { mkdir as mkdir34, readFile as readFile58, writeFile as writeFile48, rm as rm26 } from "fs/promises";
32775
+ import { dirname as dirname24, join as join79, relative as relative26, resolve as resolve33, sep as sep18 } from "path";
32016
32776
  function faultCases(spec, seed, trials) {
32017
32777
  if (!seed || seed.length > 128 || !Number.isInteger(trials) || trials < 1 || trials > 32) throw new Error("Choose a seed (1\u2013128 characters) and 1\u201332 trials");
32018
32778
  const targets = spec.fault ? [spec.fault] : spec.services.flatMap((service) => service.collections.map((collection) => ({ service: service.name, path: collection.path, type: "timeout-after-write", delayMs: 1e3 })));
@@ -32024,40 +32784,40 @@ function faultCases(spec, seed, trials) {
32024
32784
  });
32025
32785
  }
32026
32786
  async function captureExploration(cwd, file, seed, trials) {
32027
- const path2 = resolve33(cwd, file), sourceDirectory = relative25(resolve33(cwd), dirname24(path2)).split(sep18).join("/");
32787
+ const path2 = resolve33(cwd, file), sourceDirectory = relative26(resolve33(cwd), dirname24(path2)).split(sep18).join("/");
32028
32788
  if (sourceDirectory === ".." || sourceDirectory.startsWith("../")) throw new Error("World must be inside this repository");
32029
- const spec = parseWorld(JSON.parse(await readFile57(path2, "utf8")));
32789
+ const spec = parseWorld(JSON.parse(await readFile58(path2, "utf8")));
32030
32790
  if (spec.sourceBuild) throw new Error("Callable builds currently support run and replay; captured exploration needs source recompilation against unchanged checks and is unsupported");
32031
32791
  const cases = faultCases(spec, seed, trials), id2 = randomUUID19();
32032
32792
  await ensureStore(cwd);
32033
- const directory2 = join78(cwd, ".agenttwin/explorations", id2);
32793
+ const directory2 = join79(cwd, ".agenttwin/explorations", id2);
32034
32794
  await mkdir34(directory2, { recursive: true, mode: 448 });
32035
- const sourceDigests = await stageApplication(dirname24(path2), spec.files, join78(directory2, "snapshot"));
32795
+ const sourceDigests = await stageApplication(dirname24(path2), spec.files, join79(directory2, "snapshot"));
32036
32796
  const manifest = { schema: "agenttwin/exploration-v1", id: id2, seed, sourceDirectory, spec, specDigest: hash8(JSON.stringify(spec)), sourceDigests, cases };
32037
- await writeFile48(join78(directory2, "manifest.json"), JSON.stringify(manifest, null, 2) + "\n", { flag: "wx", mode: 384 });
32797
+ await writeFile48(join79(directory2, "manifest.json"), JSON.stringify(manifest, null, 2) + "\n", { flag: "wx", mode: 384 });
32038
32798
  return manifest;
32039
32799
  }
32040
32800
  async function loadExploration(cwd, id2) {
32041
32801
  if (!/^[a-f0-9-]{36}$/.test(id2)) throw new Error("Invalid exploration id");
32042
- const manifest = JSON.parse(await readFile57(join78(cwd, ".agenttwin/explorations", id2, "manifest.json"), "utf8"));
32802
+ const manifest = JSON.parse(await readFile58(join79(cwd, ".agenttwin/explorations", id2, "manifest.json"), "utf8"));
32043
32803
  if (manifest.schema !== "agenttwin/exploration-v1" || manifest.id !== id2 || typeof manifest.sourceDirectory !== "string" || manifest.sourceDirectory.includes("\\") || manifest.sourceDirectory.startsWith("/") || manifest.sourceDirectory.split("/").includes("..") || hash8(JSON.stringify(parseWorld(manifest.spec))) !== manifest.specDigest || !Array.isArray(manifest.cases) || JSON.stringify(faultCases(manifest.spec, manifest.seed, manifest.cases.length)) !== JSON.stringify(manifest.cases)) throw new Error("Exploration integrity failed");
32044
32804
  for (const file of manifest.spec.files) {
32045
32805
  if (file.startsWith("/") || file.includes("\\") || file.split("/").includes("..")) throw new Error("Unsafe snapshot path");
32046
- if (hash8(await readFile57(join78(cwd, ".agenttwin/explorations", id2, "snapshot", file))) !== manifest.sourceDigests[file]) throw new Error("Captured application changed; create a new exploration");
32806
+ if (hash8(await readFile58(join79(cwd, ".agenttwin/explorations", id2, "snapshot", file))) !== manifest.sourceDigests[file]) throw new Error("Captured application changed; create a new exploration");
32047
32807
  }
32048
32808
  return manifest;
32049
32809
  }
32050
32810
  async function runExploration(cwd, id2, opts) {
32051
32811
  const manifest = await loadExploration(cwd, id2);
32052
- const root2 = join78(cwd, ".agenttwin/explorations", id2), attempt = randomUUID19();
32053
- const application = join78(root2, "attempts", attempt, "app");
32054
- await stageApplication(opts.patched ? resolve33(cwd, manifest.sourceDirectory) : join78(root2, "snapshot"), manifest.spec.files, application);
32812
+ const root2 = join79(cwd, ".agenttwin/explorations", id2), attempt = randomUUID19();
32813
+ const application = join79(root2, "attempts", attempt, "app");
32814
+ await stageApplication(opts.patched ? resolve33(cwd, manifest.sourceDirectory) : join79(root2, "snapshot"), manifest.spec.files, application);
32055
32815
  const results = [];
32056
32816
  for (const [index, trial] of manifest.cases.entries()) {
32057
32817
  const spec = structuredClone(manifest.spec);
32058
32818
  delete spec.fault;
32059
32819
  if (trial.fault) spec.fault = trial.fault;
32060
- const file = join78(application, `.agenttwin-trial-${attempt}.json`);
32820
+ const file = join79(application, `.agenttwin-trial-${attempt}.json`);
32061
32821
  await writeFile48(file, JSON.stringify(spec), { mode: 384 });
32062
32822
  const result2 = await runWorld(cwd, { file, log: opts.log });
32063
32823
  results.push({ index, seed: trial.seed, fault: trial.fault ?? null, status: result2.status, evidencePath: result2.evidencePath, specDigest: result2.specDigest });
@@ -32065,7 +32825,7 @@ async function runExploration(cwd, id2, opts) {
32065
32825
  }
32066
32826
  const status = results.some((r) => ["failed", "error"].includes(r.status)) ? "failed" : results.some((r) => r.status === "incomplete") ? "incomplete" : "passed";
32067
32827
  const summary2 = { schema: "agenttwin/exploration-result-v1", id: id2, attempt, patched: !!opts.patched, status, checksDigest: manifest.specDigest, results, limitations: ["Seeds reproduce fault selection and delays, not OS scheduling or arbitrary application randomness", "Local application execution is not an OS sandbox", "Hash checks detect accidental changes; protected CI must anchor regression checks in a trusted Git baseline"] };
32068
- await writeFile48(join78(root2, "attempts", attempt, "summary.json"), JSON.stringify(summary2, null, 2) + "\n", { mode: 384 });
32828
+ await writeFile48(join79(root2, "attempts", attempt, "summary.json"), JSON.stringify(summary2, null, 2) + "\n", { mode: 384 });
32069
32829
  return summary2;
32070
32830
  }
32071
32831
  async function saveExplorationRegression(cwd, explorationId, trialIndex, id2) {
@@ -32090,7 +32850,7 @@ var init_exploration = __esm({
32090
32850
  init_spec();
32091
32851
  init_regressions();
32092
32852
  init_store();
32093
- hash8 = (value3) => createHash38("sha256").update(value3).digest("hex");
32853
+ hash8 = (value3) => createHash39("sha256").update(value3).digest("hex");
32094
32854
  }
32095
32855
  });
32096
32856
 
@@ -32100,12 +32860,12 @@ __export(run_outcome_exports, {
32100
32860
  mainRunFailure: () => mainRunFailure
32101
32861
  });
32102
32862
  import { existsSync as existsSync13 } from "fs";
32103
- import { join as join79 } from "path";
32863
+ import { join as join80 } from "path";
32104
32864
  function mainRunFailure(error, cwd) {
32105
32865
  const message = error instanceof Error ? error.message : String(error);
32106
32866
  const firstLine = message.split("\n").map((l) => l.trim()).find(Boolean) ?? "it stopped without a message.";
32107
32867
  if (error instanceof CliError) return { reason: firstLine, ...error.action ? { next: error.action } : {} };
32108
- const packageManager2 = packageManagerOf(cwd, (f) => existsSync13(join79(cwd, f)));
32868
+ const packageManager2 = packageManagerOf(cwd, (f) => existsSync13(join80(cwd, f)));
32109
32869
  const help = explainCleanRun({ status: "failed", exitCode: 1, stderr: message, unsupported: [], assertions: [], input: null, scenarioPath: ".agenttwin/auto/<workflow>/scenario.json", packageManager: packageManager2 });
32110
32870
  if (help && !/^Your code stopped with an error/.test(help.headline)) return { reason: help.headline, next: help.next, ...help.command ? { command: help.command } : {} };
32111
32871
  return { reason: firstLine.length > 240 ? firstLine.slice(0, 237) + "\u2026" : firstLine, next: "This is a problem in AgentTwin, not in your code. Report it with the line above at https://github.com/AgentTwin/AgentTwin/issues." };
@@ -32208,7 +32968,7 @@ init_login();
32208
32968
  init_version();
32209
32969
  init_sync();
32210
32970
  init_prepare();
32211
- import { join as join80, relative as relative26, resolve as resolve34 } from "path";
32971
+ import { join as join81, relative as relative27, resolve as resolve34 } from "path";
32212
32972
  import { parseArgs } from "util";
32213
32973
 
32214
32974
  // src/commands/setup.ts
@@ -32371,7 +33131,12 @@ var HOSTED_TOOLS = [
32371
33131
  hosted("list_org_tokens", "Organization tokens (for CI and SCIM) in the workspace. Secrets are never returned after creation.", {}, [], true),
32372
33132
  hosted("create_org_token", "Create an organization token for CI or SCIM. The secret is shown once. Admins only.", { label: string, role }, ["label"], false),
32373
33133
  hosted("revoke_org_token", "Revoke an organization token. Admins only.", { tokenId: uuid2 }, ["tokenId"], false),
32374
- hosted("audit_log", "The workspace audit log, newest first: who did what and when.", { limit }, [], true)
33134
+ hosted("audit_log", "The workspace audit log, newest first: who did what and when.", { limit }, [], true),
33135
+ hosted("workspace_value", "Problems AgentTwin caught before merge in one month, the pull requests they were on and what they would have cost had each shipped once. Only problems with a known cost are priced.", { month: { type: "string", pattern: "^\\d{4}-\\d{2}$", description: "YYYY-MM; this month when omitted." } }, [], true),
33136
+ hosted("workspace_plan", "The workspace plan (free or Team), trial end date and whether the free trial is still available.", {}, [], true),
33137
+ hosted("start_trial", "Start the 14-day Team trial, which checks private repositories too. No card needed; once per workspace. Admins only.", {}, [], false),
33138
+ hosted("slack_alerts", "Whether failed pull request checks are posted to a Slack channel. The saved URL is never returned.", {}, [], true),
33139
+ hosted("set_slack_alerts", "Post failed pull request checks to a Slack incoming webhook (https://hooks.slack.com/services/\u2026), or turn alerts off with null. Admins only.", { slackWebhookUrl: { type: ["string", "null"], description: "A hooks.slack.com incoming webhook URL, or null to turn off." } }, ["slackWebhookUrl"], false)
32375
33140
  ];
32376
33141
  async function hostedConnection() {
32377
33142
  const saved = await savedConnection();
@@ -32452,6 +33217,16 @@ async function callHostedTool(name, args, deps = {}) {
32452
33217
  const value3 = await api2("GET", "/v1/team/audit");
32453
33218
  return { events: (value3.events ?? []).slice(0, Number(args.limit ?? 100)) };
32454
33219
  }
33220
+ case "workspace_value":
33221
+ return api2("GET", "/v1/workspace/value" + q({ month: args.month }));
33222
+ case "workspace_plan":
33223
+ return api2("GET", "/v1/workspace/plan");
33224
+ case "start_trial":
33225
+ return api2("POST", "/v1/workspace/trial");
33226
+ case "slack_alerts":
33227
+ return api2("GET", "/v1/workspace/alerts");
33228
+ case "set_slack_alerts":
33229
+ return api2("PUT", "/v1/workspace/alerts", { slackWebhookUrl: args.slackWebhookUrl ?? null });
32455
33230
  case "workspace_summary":
32456
33231
  return workspaceSummary(api2, args.project);
32457
33232
  default:
@@ -35148,6 +35923,7 @@ function helpText() {
35148
35923
  ` ${"scenario".padEnd(12)}save --file scenario.json | list | show --scenario id@version`,
35149
35924
  ` ${"world".padEnd(12)}create --file world.json | list | status/reset/extend/run/teardown --id UUID`,
35150
35925
  ` ${"receipt".padEnd(12)}Inspect failures and get a fix task (--id run UUID)`,
35926
+ ` ${"record".padEnd(12)}Write the release record for this commit: what was tested, faults, results, receipt hashes [--out DIR]`,
35151
35927
  ` ${"mcp".padEnd(12)}Serve coding-agent tools over MCP stdio in this workspace`,
35152
35928
  ` ${"incident".padEnd(12)}import --file incident.json [--out redacted-preview.json]`,
35153
35929
  ` ${"check".padEnd(12)}Pull-request check: run twin checks from the base branch against this branch [--base REF] [--head REF] [--runtime docker] [--markdown out.md] [--github] | install (writes the GitHub workflow)`,
@@ -35373,8 +36149,8 @@ async function main() {
35373
36149
  if (positionals[1] === "install") {
35374
36150
  const { checkWorkflow: checkWorkflow2 } = await Promise.resolve().then(() => (init_pr_check_github(), pr_check_github_exports));
35375
36151
  const { mkdir: mkdir35, writeFile: writeFile49 } = await import("fs/promises");
35376
- const path2 = join80(cwd, ".github/workflows/agenttwin.yml");
35377
- await mkdir35(join80(cwd, ".github/workflows"), { recursive: true });
36152
+ const path2 = join81(cwd, ".github/workflows/agenttwin.yml");
36153
+ await mkdir35(join81(cwd, ".github/workflows"), { recursive: true });
35378
36154
  try {
35379
36155
  await writeFile49(path2, checkWorkflow2(readVersion()), { flag: flag("force") ? "w" : "wx" });
35380
36156
  } catch (error) {
@@ -35491,9 +36267,9 @@ ${requirements.blockers.map((blocker) => ` - ${blocker}`).join("\n")}`);
35491
36267
  const { runProbe: runProbe2, PROBES: PROBES2, REAL_TARGETS: REAL_TARGETS2 } = await Promise.resolve().then(() => (init_conformance(), conformance_exports));
35492
36268
  const { HttpWorld: HttpWorld2 } = await Promise.resolve().then(() => (init_http_world(), http_world_exports));
35493
36269
  const { parseWorld: parseWorld2, ADAPTER_COLLECTIONS: ADAPTER_COLLECTIONS2 } = await Promise.resolve().then(() => (init_spec(), spec_exports));
35494
- const { readFile: readFile58, writeFile: writeFile49, mkdir: mkdir35 } = await import("fs/promises");
36270
+ const { readFile: readFile59, writeFile: writeFile49, mkdir: mkdir35 } = await import("fs/promises");
35495
36271
  const adapter = str4("adapter") ?? "stripe";
35496
- const probes = str4("probes") ? JSON.parse(await readFile58(resolve34(cwd, str4("probes")), "utf8")) : PROBES2[adapter];
36272
+ const probes = str4("probes") ? JSON.parse(await readFile59(resolve34(cwd, str4("probes")), "utf8")) : PROBES2[adapter];
35497
36273
  const collections = ADAPTER_COLLECTIONS2[adapter];
35498
36274
  if (!probes?.length || !collections) throw new CliError(`No conformance probes for "${adapter}". Built in: ${Object.keys(PROBES2).join(", ")}. Add your own with --probes probes.json.`, { code: EXIT.USAGE });
35499
36275
  const spec = parseWorld2({ schema: "agenttwin/world-v1", name: "conformance", files: ["conformance.js"], command: ["node", "-e", "0"], timeoutSeconds: 30, services: [{ name: adapter, adapter, collections: collections.map((path2) => ({ path: path2, seed: [] })) }], assertions: [{ service: adapter, path: collections[0], count: 0 }] });
@@ -35513,11 +36289,11 @@ ${requirements.blockers.map((blocker) => ` - ${blocker}`).join("\n")}`);
35513
36289
  (${r.omitted} fields the real service returns are not modelled)` : ""}`);
35514
36290
  }
35515
36291
  const verified = results.filter((r) => r.match === true), summary2 = { schema: "agenttwin/conformance-run-v1", adapter, at: (/* @__PURE__ */ new Date()).toISOString(), against: real ? new URL(real.base).host : null, probes: results.length, verified: verified.length, differs: results.filter((r) => r.failures.length).length, results };
35516
- await mkdir35(join80(cwd, ".agenttwin", "conformance"), { recursive: true });
35517
- const out = join80(cwd, ".agenttwin", "conformance", `${adapter}-${summary2.at.slice(0, 10)}.json`);
36292
+ await mkdir35(join81(cwd, ".agenttwin", "conformance"), { recursive: true });
36293
+ const out = join81(cwd, ".agenttwin", "conformance", `${adapter}-${summary2.at.slice(0, 10)}.json`);
35518
36294
  await writeFile49(out, JSON.stringify(summary2, null, 2) + "\n");
35519
36295
  if (flag("record") && real && verified.length) {
35520
- const file = resolve34(cwd, "conformance/results.json"), existing = JSON.parse(await readFile58(file, "utf8").catch(() => '{"schema":"agenttwin/conformance-results-v1","results":[]}'));
36296
+ const file = resolve34(cwd, "conformance/results.json"), existing = JSON.parse(await readFile59(file, "utf8").catch(() => '{"schema":"agenttwin/conformance-results-v1","results":[]}'));
35521
36297
  for (const r of verified) {
35522
36298
  const probe = probes.find((p) => p.id === r.probe);
35523
36299
  existing.results = existing.results.filter((e) => e.probe !== r.probe);
@@ -35526,7 +36302,7 @@ ${requirements.blockers.map((blocker) => ` - ${blocker}`).join("\n")}`);
35526
36302
  await writeFile49(file, JSON.stringify(existing, null, 2) + "\n");
35527
36303
  log(`Recorded ${verified.length} verified probe(s) in conformance/results.json.`);
35528
36304
  } else if (flag("record")) log("Nothing recorded: --record needs a real target and at least one probe that matched it.");
35529
- printResult(summary2, `${summary2.verified} of ${summary2.probes} probes verified against ${summary2.against ?? "no real service"}. Results: ${relative26(cwd, out)}`);
36305
+ printResult(summary2, `${summary2.verified} of ${summary2.probes} probes verified against ${summary2.against ?? "no real service"}. Results: ${relative27(cwd, out)}`);
35530
36306
  process.exitCode = summary2.differs ? EXIT.ERROR : EXIT.OK;
35531
36307
  } finally {
35532
36308
  await world.close();
@@ -35584,13 +36360,30 @@ ${requirements.blockers.map((blocker) => ` - ${blocker}`).join("\n")}`);
35584
36360
  if (action === "run") process.exitCode = result2.status === "passed" ? EXIT.OK : result2.status === "incomplete" ? EXIT.BLOCKED : EXIT.ERROR;
35585
36361
  return;
35586
36362
  }
36363
+ case "record": {
36364
+ const { buildReleaseRecord: buildReleaseRecord2, renderReleaseRecord: renderReleaseRecord2 } = await Promise.resolve().then(() => (init_release_record(), release_record_exports));
36365
+ const { mkdir: mkdir35, writeFile: writeFile49 } = await import("fs/promises");
36366
+ const record5 = await buildReleaseRecord2(cwd, VERSION);
36367
+ const dir = str4("out") ? resolve34(cwd, str4("out")) : join81(cwd, ".agenttwin");
36368
+ await mkdir35(dir, { recursive: true });
36369
+ const html = join81(dir, "release-record.html"), json4 = join81(dir, "release-record.json");
36370
+ await writeFile49(json4, JSON.stringify(record5, null, 2) + "\n");
36371
+ await writeFile49(html, renderReleaseRecord2(record5));
36372
+ const s = record5.summary;
36373
+ printResult({ ...record5, files: { html, json: json4 } }, record5.workflows.length ? `Release record (${record5.verdict}): ${s.workflows} workflow${s.workflows === 1 ? "" : "s"}, ${s.faults} faults, ${s.findings} problem${s.findings === 1 ? "" : "s"} found.
36374
+ ${html}
36375
+ ${json4}
36376
+ ` : `No workflow results yet: run npx agenttwin first. Wrote an empty record to ${html}
36377
+ `);
36378
+ return;
36379
+ }
35587
36380
  case "receipt": {
35588
36381
  let id2 = str4("id");
35589
36382
  if (!id2) {
35590
- const { readdir: readdir12, stat: stat13 } = await import("fs/promises");
35591
- const dir = join80(cwd, ".agenttwin/runs");
35592
- const runs = await readdir12(dir).catch(() => []);
35593
- const dated = await Promise.all(runs.map(async (run3) => ({ run: run3, at: (await stat13(join80(dir, run3, "run.json")).catch(() => void 0))?.mtimeMs ?? 0 })));
36383
+ const { readdir: readdir13, stat: stat14 } = await import("fs/promises");
36384
+ const dir = join81(cwd, ".agenttwin/runs");
36385
+ const runs = await readdir13(dir).catch(() => []);
36386
+ const dated = await Promise.all(runs.map(async (run3) => ({ run: run3, at: (await stat14(join81(dir, run3, "run.json")).catch(() => void 0))?.mtimeMs ?? 0 })));
35594
36387
  id2 = dated.filter((r) => r.at).sort((a, b) => b.at - a.at)[0]?.run;
35595
36388
  if (!id2) throw new CliError("No runs yet. Run a test first: agenttwin run --file agenttwin.world.json", { code: EXIT.USAGE });
35596
36389
  }
@@ -35727,8 +36520,8 @@ Review with: agenttwin prepare review --id ${id2}`);
35727
36520
  }
35728
36521
  const status = await preparationStatus(cwd, id2);
35729
36522
  if (status.status !== "needs-review" || status.expired || !status.reviewPath || !status.proposalDigest) throw new CliError("No current proposal awaits review", { code: EXIT.BLOCKED });
35730
- const { readFile: readFile58 } = await import("fs/promises");
35731
- const review = await readFile58(status.reviewPath, "utf8");
36523
+ const { readFile: readFile59 } = await import("fs/promises");
36524
+ const review = await readFile59(status.reviewPath, "utf8");
35732
36525
  if (!flag("yes")) {
35733
36526
  if (json3 || !process.stdin.isTTY) {
35734
36527
  printResult({ ...status, review, runnable: false }, review);
@@ -35955,7 +36748,7 @@ ${result2.uploaded}`);
35955
36748
  result2,
35956
36749
  [
35957
36750
  `Discovered ${counts.tools} tools (${counts.classified} classified) \xB7 ${counts.unclassified} unclassified \xB7 ${counts.withTwin} with twins`,
35958
- `Wrote ${join80(".agenttwin", "inventory.json")}`,
36751
+ `Wrote ${join81(".agenttwin", "inventory.json")}`,
35959
36752
  result2.blocked.length > 0 ? `Blocked: ${result2.blocked.join("; ")}` : "",
35960
36753
  result2.opportunities.length > 0 ? `Opportunities: ${result2.opportunities.join("; ")}` : "",
35961
36754
  result2.reconciliation.splits.length > 0 ? `Splits: ${result2.reconciliation.splits.map((s) => s.from).join(", ")}` : ""
@@ -35978,7 +36771,7 @@ ${result2.uploaded}`);
35978
36771
  printResult(
35979
36772
  result2,
35980
36773
  `Plan: ${result2.plan.items.length} tools \xB7 ${Object.entries(byStrategy).map(([k, v]) => `${k} ${v}`).join(", ")}
35981
- Wrote ${join80(".agenttwin", "plan.json")}`
36774
+ Wrote ${join81(".agenttwin", "plan.json")}`
35982
36775
  );
35983
36776
  return;
35984
36777
  }