agenttwin 0.3.32 → 0.3.33

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 (113) hide show
  1. package/dist/api.js +14134 -2452
  2. package/dist/dashboard/assets/next/static/chunks/app/_not-found/page-1fd9ba71e57294ba.js +1 -0
  3. package/dist/dashboard/assets/next/static/chunks/app/about/{page-b09a2d8452522c20.js → page-81ddde965e6dfa96.js} +1 -1
  4. package/dist/dashboard/assets/next/static/chunks/app/account/password/{page-b9ca284314cace59.js → page-47d3b1ebd057bb1a.js} +1 -1
  5. package/dist/dashboard/assets/next/static/chunks/app/{auth/page-94d508052ae30dcb.js → api-policy/page-137a6dba95d2ef51.js} +1 -1
  6. package/dist/dashboard/assets/next/static/chunks/app/{compare/page-94d508052ae30dcb.js → auth/page-137a6dba95d2ef51.js} +1 -1
  7. package/dist/dashboard/assets/next/static/chunks/app/blog/agenttwin-vs-mockoon/page-46b9ffc514b56c84.js +1 -0
  8. package/dist/dashboard/assets/next/static/chunks/app/blog/agenttwin-vs-pact/page-46b9ffc514b56c84.js +1 -0
  9. package/dist/dashboard/assets/next/static/chunks/app/blog/agenttwin-vs-testcontainers/page-46b9ffc514b56c84.js +1 -0
  10. package/dist/dashboard/assets/next/static/chunks/app/blog/agenttwin-vs-wiremock/page-46b9ffc514b56c84.js +1 -0
  11. package/dist/dashboard/assets/next/static/chunks/app/blog/choose-first-agent-workflow-test/page-46b9ffc514b56c84.js +1 -0
  12. package/dist/dashboard/assets/next/static/chunks/app/blog/clean-baseline-before-fault-injection/page-46b9ffc514b56c84.js +1 -0
  13. package/dist/dashboard/assets/next/static/chunks/app/blog/idempotency-keys-and-safe-retries/page-46b9ffc514b56c84.js +1 -0
  14. package/dist/dashboard/assets/next/static/chunks/app/blog/keep-real-service-tests-with-digital-twins/page-46b9ffc514b56c84.js +1 -0
  15. package/dist/dashboard/assets/next/static/chunks/app/blog/keploy-alternatives-for-database-and-payment-workflows/page-46b9ffc514b56c84.js +1 -0
  16. package/dist/dashboard/assets/next/static/chunks/app/blog/{layout-b095a34d742bd1fd.js → layout-a68ffff4758226cc.js} +1 -1
  17. package/dist/dashboard/assets/next/static/chunks/app/blog/page-46b9ffc514b56c84.js +1 -0
  18. package/dist/dashboard/assets/next/static/chunks/app/blog/read-workflow-test-receipts/page-46b9ffc514b56c84.js +1 -0
  19. package/dist/dashboard/assets/next/static/chunks/app/blog/reset-test-environment-between-runs/page-46b9ffc514b56c84.js +1 -0
  20. package/dist/dashboard/assets/next/static/chunks/app/blog/simulate-timeouts-and-duplicate-events/page-46b9ffc514b56c84.js +1 -0
  21. package/dist/dashboard/assets/next/static/chunks/app/blog/test-boundaries-for-ai-agents/page-46b9ffc514b56c84.js +1 -0
  22. package/dist/dashboard/assets/next/static/chunks/app/blog/timeout-retry-double-charge/page-46b9ffc514b56c84.js +1 -0
  23. package/dist/dashboard/assets/next/static/chunks/app/blog/we-ran-50-real-incidents-through-agenttwin/page-46b9ffc514b56c84.js +1 -0
  24. package/dist/dashboard/assets/next/static/chunks/app/blog/why-ai-agents-delete-production-databases/page-46b9ffc514b56c84.js +1 -0
  25. package/dist/dashboard/assets/next/static/chunks/app/blog/workflow-testing-evaluation-checklist/page-46b9ffc514b56c84.js +1 -0
  26. package/dist/dashboard/assets/next/static/chunks/app/blog/write-better-workflow-assertions/page-46b9ffc514b56c84.js +1 -0
  27. package/dist/dashboard/assets/next/static/chunks/app/{contact/page-94d508052ae30dcb.js → compare/page-137a6dba95d2ef51.js} +1 -1
  28. package/dist/dashboard/assets/next/static/chunks/app/{api-policy/page-94d508052ae30dcb.js → contact/page-137a6dba95d2ef51.js} +1 -1
  29. package/dist/dashboard/assets/next/static/chunks/app/dashboard/{layout-820e83f47c1bfe08.js → layout-b448c11ac382ac4d.js} +1 -1
  30. package/dist/dashboard/assets/next/static/chunks/app/dashboard/page-921966e3dedcd521.js +1 -0
  31. package/dist/dashboard/assets/next/static/chunks/app/demo/{page-ef75632088a6ea0b.js → page-cea8a4e63415fbd3.js} +1 -1
  32. package/dist/dashboard/assets/next/static/chunks/app/developers/page-137a6dba95d2ef51.js +1 -0
  33. package/dist/dashboard/assets/next/static/chunks/app/docs/[[...slug]]/{page-c25a8cab5ab065c4.js → page-8ae8656bb220cf5f.js} +1 -1
  34. package/dist/dashboard/assets/next/static/chunks/app/dpa/page-137a6dba95d2ef51.js +1 -0
  35. package/dist/dashboard/assets/next/static/chunks/app/enterprise/page-e6b3e380979825ee.js +1 -0
  36. package/dist/dashboard/assets/next/static/chunks/app/guides/page-137a6dba95d2ef51.js +1 -0
  37. package/dist/dashboard/assets/next/static/chunks/app/{layout-be64d3e50db4b7a9.js → layout-82c443ae1fa2121f.js} +1 -1
  38. package/dist/dashboard/assets/next/static/chunks/app/login/page-fd67c8f49df437a8.js +1 -0
  39. package/dist/dashboard/assets/next/static/chunks/app/not-found-137a6dba95d2ef51.js +1 -0
  40. package/dist/dashboard/assets/next/static/chunks/app/onboarding/{page-26b963fb1dc02cc7.js → page-5f34951664ab6faa.js} +1 -1
  41. package/dist/dashboard/assets/next/static/chunks/app/{page-ede77810f4904ea5.js → page-75da7f74524cc22b.js} +1 -1
  42. package/dist/dashboard/assets/next/static/chunks/app/{enterprise/page-91c6176f28dfdccd.js → pricing/page-2ba2ef1861af2b9a.js} +1 -1
  43. package/dist/dashboard/assets/next/static/chunks/app/privacy/page-137a6dba95d2ef51.js +1 -0
  44. package/dist/dashboard/assets/next/static/chunks/app/sandbox/page-137a6dba95d2ef51.js +1 -0
  45. package/dist/dashboard/assets/next/static/chunks/app/scoreboard/page-137a6dba95d2ef51.js +1 -0
  46. package/dist/dashboard/assets/next/static/chunks/app/security/page-137a6dba95d2ef51.js +1 -0
  47. package/dist/dashboard/assets/next/static/chunks/app/signup/page-fd67c8f49df437a8.js +1 -0
  48. package/dist/dashboard/assets/next/static/chunks/app/sitemap.xml/route-46b9ffc514b56c84.js +1 -0
  49. package/dist/dashboard/assets/next/static/chunks/app/status/page-0ad713a62e231968.js +1 -0
  50. package/dist/dashboard/assets/next/static/chunks/app/subprocessors/page-137a6dba95d2ef51.js +1 -0
  51. package/dist/dashboard/assets/next/static/chunks/app/terms/page-137a6dba95d2ef51.js +1 -0
  52. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/layout-80e06fdbf1bfc0ab.js +1 -0
  53. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/page-21ed4ad2bb01e324.js +1 -0
  54. package/dist/dashboard/assets/next/static/chunks/app/v2/layout-1565491a06814842.js +1 -0
  55. package/dist/dashboard/assets/next/static/chunks/app/v2/login/page-250c09869871e915.js +1 -0
  56. package/dist/dashboard/assets/next/static/chunks/app/v2/onboarding/page-300bc2cb63084339.js +1 -0
  57. package/dist/dashboard/assets/next/static/chunks/app/v2/page-f76e6c096d562f02.js +1 -0
  58. package/dist/dashboard/assets/next/static/chunks/app/v2/signup/page-250c09869871e915.js +1 -0
  59. package/dist/dashboard/assets/next/static/chunks/app/what-is-agenttwin/page-137a6dba95d2ef51.js +1 -0
  60. package/dist/dashboard/assets/next/static/chunks/{main-app-b4faf61f2e1c2b6d.js → main-app-5cdab67e2bf5802d.js} +1 -1
  61. package/dist/dashboard/assets/next/static/chunks/{webpack-53525dd96c1c1e70.js → webpack-cc6e66684b86a020.js} +1 -1
  62. package/dist/dashboard/assets/next/static/gqlJaiQCOn6PSaPVSG0RS/_buildManifest.js +1 -0
  63. package/dist/dashboard/index.html +2 -2
  64. package/dist/engine.js +1284 -562
  65. package/dist/gateway.js +14152 -2466
  66. package/dist/twins/catalog.json +113 -113
  67. package/dist/twins/packs/stripe/index.mjs +8 -8
  68. package/dist/worker.js +70 -19
  69. package/dist/world-host.js +113 -25
  70. package/package.json +1 -1
  71. package/dist/dashboard/assets/next/static/chunks/app/_not-found/page-5d1ba67144da5868.js +0 -1
  72. package/dist/dashboard/assets/next/static/chunks/app/blog/agenttwin-vs-mockoon/page-11a5fdc2662ff51d.js +0 -1
  73. package/dist/dashboard/assets/next/static/chunks/app/blog/agenttwin-vs-pact/page-11a5fdc2662ff51d.js +0 -1
  74. package/dist/dashboard/assets/next/static/chunks/app/blog/agenttwin-vs-testcontainers/page-11a5fdc2662ff51d.js +0 -1
  75. package/dist/dashboard/assets/next/static/chunks/app/blog/agenttwin-vs-wiremock/page-11a5fdc2662ff51d.js +0 -1
  76. package/dist/dashboard/assets/next/static/chunks/app/blog/choose-first-agent-workflow-test/page-11a5fdc2662ff51d.js +0 -1
  77. package/dist/dashboard/assets/next/static/chunks/app/blog/clean-baseline-before-fault-injection/page-11a5fdc2662ff51d.js +0 -1
  78. package/dist/dashboard/assets/next/static/chunks/app/blog/idempotency-keys-and-safe-retries/page-11a5fdc2662ff51d.js +0 -1
  79. package/dist/dashboard/assets/next/static/chunks/app/blog/keep-real-service-tests-with-digital-twins/page-11a5fdc2662ff51d.js +0 -1
  80. package/dist/dashboard/assets/next/static/chunks/app/blog/keploy-alternatives-for-database-and-payment-workflows/page-11a5fdc2662ff51d.js +0 -1
  81. package/dist/dashboard/assets/next/static/chunks/app/blog/page-11a5fdc2662ff51d.js +0 -1
  82. package/dist/dashboard/assets/next/static/chunks/app/blog/read-workflow-test-receipts/page-11a5fdc2662ff51d.js +0 -1
  83. package/dist/dashboard/assets/next/static/chunks/app/blog/reset-test-environment-between-runs/page-11a5fdc2662ff51d.js +0 -1
  84. package/dist/dashboard/assets/next/static/chunks/app/blog/simulate-timeouts-and-duplicate-events/page-11a5fdc2662ff51d.js +0 -1
  85. package/dist/dashboard/assets/next/static/chunks/app/blog/test-boundaries-for-ai-agents/page-11a5fdc2662ff51d.js +0 -1
  86. package/dist/dashboard/assets/next/static/chunks/app/blog/workflow-testing-evaluation-checklist/page-11a5fdc2662ff51d.js +0 -1
  87. package/dist/dashboard/assets/next/static/chunks/app/blog/write-better-workflow-assertions/page-11a5fdc2662ff51d.js +0 -1
  88. package/dist/dashboard/assets/next/static/chunks/app/dashboard/page-8b436163bc85e182.js +0 -1
  89. package/dist/dashboard/assets/next/static/chunks/app/developers/page-94d508052ae30dcb.js +0 -1
  90. package/dist/dashboard/assets/next/static/chunks/app/dpa/page-94d508052ae30dcb.js +0 -1
  91. package/dist/dashboard/assets/next/static/chunks/app/guides/page-94d508052ae30dcb.js +0 -1
  92. package/dist/dashboard/assets/next/static/chunks/app/login/page-7ee25051f2743d68.js +0 -1
  93. package/dist/dashboard/assets/next/static/chunks/app/not-found-94d508052ae30dcb.js +0 -1
  94. package/dist/dashboard/assets/next/static/chunks/app/pricing/page-535834810dc4bee1.js +0 -1
  95. package/dist/dashboard/assets/next/static/chunks/app/privacy/page-94d508052ae30dcb.js +0 -1
  96. package/dist/dashboard/assets/next/static/chunks/app/sandbox/page-94d508052ae30dcb.js +0 -1
  97. package/dist/dashboard/assets/next/static/chunks/app/scoreboard/page-94d508052ae30dcb.js +0 -1
  98. package/dist/dashboard/assets/next/static/chunks/app/security/page-94d508052ae30dcb.js +0 -1
  99. package/dist/dashboard/assets/next/static/chunks/app/signup/page-7ee25051f2743d68.js +0 -1
  100. package/dist/dashboard/assets/next/static/chunks/app/sitemap.xml/route-11a5fdc2662ff51d.js +0 -1
  101. package/dist/dashboard/assets/next/static/chunks/app/status/page-569ae36bd08d867c.js +0 -1
  102. package/dist/dashboard/assets/next/static/chunks/app/subprocessors/page-94d508052ae30dcb.js +0 -1
  103. package/dist/dashboard/assets/next/static/chunks/app/terms/page-94d508052ae30dcb.js +0 -1
  104. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/layout-b92ad482b0164f93.js +0 -1
  105. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/page-b1341267b2478360.js +0 -1
  106. package/dist/dashboard/assets/next/static/chunks/app/v2/layout-edb84faba63372b4.js +0 -1
  107. package/dist/dashboard/assets/next/static/chunks/app/v2/login/page-bfbe86a28adc6d30.js +0 -1
  108. package/dist/dashboard/assets/next/static/chunks/app/v2/onboarding/page-79cd80f87d39230d.js +0 -1
  109. package/dist/dashboard/assets/next/static/chunks/app/v2/page-1391f1ae01a91dc0.js +0 -1
  110. package/dist/dashboard/assets/next/static/chunks/app/v2/signup/page-bfbe86a28adc6d30.js +0 -1
  111. package/dist/dashboard/assets/next/static/chunks/app/what-is-agenttwin/page-94d508052ae30dcb.js +0 -1
  112. package/dist/dashboard/assets/next/static/dQPcd2gl7ABZiL9lr9ruM/_buildManifest.js +0 -1
  113. /package/dist/dashboard/assets/next/static/{dQPcd2gl7ABZiL9lr9ruM → gqlJaiQCOn6PSaPVSG0RS}/_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.33",
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,367 @@ 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
+ });
3126
+ continue;
3127
+ }
3128
+ if (fault && !keyed && made >= 2 && !covered(first.service, "retry-without-key")) {
3129
+ const retry = group.find((c) => c.sequence > fault.sequence);
3130
+ out.push({
3131
+ check: "retry-without-key",
3132
+ service: first.service,
3133
+ resource: `${first.method} ${first.path}`,
3134
+ calls: group.map((c) => c.sequence),
3135
+ finding: `${label(first)} was sent ${times(group.length)}${when}, ${retry.idempotencyKey ? "with a new idempotency key" : "without an idempotency key"}`,
3136
+ 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` },
3137
+ ...retry.source ? { source: retry.source } : {},
3138
+ writeSites: sites(group),
3139
+ fix: announce ? "check-before-resend" : "idempotency-key"
3140
+ });
3141
+ }
3142
+ }
3143
+ for (const limited of ordered.filter((c) => c.outcome === "rate-limited" && c.retryAfterMs && c.at !== void 0)) {
3144
+ const next = ordered.find((c) => c.sequence > limited.sequence && c.service === limited.service && c.at !== void 0 && sameRequest(limited, c));
3145
+ if (next && next.at - limited.at < limited.retryAfterMs * 0.9 && !covered(limited.service, "retry-after-ignored"))
3146
+ out.push({
3147
+ check: "retry-after-ignored",
3148
+ service: limited.service,
3149
+ resource: `${limited.method} ${limited.path}`,
3150
+ calls: [limited.sequence, next.sequence],
3151
+ 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)`,
3152
+ impact: { kind: "reliability", count: 1, summary: "ignoring Retry-After prolongs rate limiting and can get the credential throttled or banned" },
3153
+ ...next.source ? { source: next.source } : {},
3154
+ fix: "respect-retry-after"
3155
+ });
3156
+ }
3157
+ 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)));
3158
+ for (const claim of claims.filter((c) => c.polarity === "success")) {
3159
+ const via = claim.via !== void 0 ? ordered.find((c) => c.sequence === claim.via) : void 0, failed = unrecoveredBefore(claim.sequence, via)[0];
3160
+ if (!failed || covered(via?.service ?? failed.service, "announce-after-failed-write")) continue;
3161
+ out.push({
3162
+ check: "announce-after-failed-write",
3163
+ service: via?.service ?? failed.service,
3164
+ resource: via ? `${via.method} ${via.path}` : "agent output",
3165
+ calls: [failed.sequence, ...via ? [via.sequence] : []],
3166
+ finding: `Your agent said "${claim.text.slice(0, 80)}"${via ? ` (${label(via)})` : ""} after ${label(failed)} failed (${faultWords(failed)}) and never succeeded`,
3167
+ impact: impactOf(via ? [via] : [], 0, "customer-facing", "the agent reports work that never happened"),
3168
+ ...claim.source ?? via?.source ? { source: claim.source ?? via?.source } : {},
3169
+ fix: "confirm-before-announce"
3170
+ });
3171
+ break;
3172
+ }
3173
+ for (const claim of claims.filter((c) => c.polarity === "failure")) {
3174
+ const later = writes.find((w) => w.sequence > claim.sequence && !announcementSeqs.has(w.sequence) && effects(w) > 0);
3175
+ if (!later || covered(later.service, "write-after-reported-failure")) continue;
3176
+ out.push({
3177
+ check: "write-after-reported-failure",
3178
+ service: later.service,
3179
+ resource: `${later.method} ${later.path}`,
3180
+ calls: [...claim.via ? [claim.via] : [], later.sequence],
3181
+ finding: `Your agent reported "${claim.text.slice(0, 80)}" and then still sent ${label(later)}`,
3182
+ impact: impactOf([later], 0, "data-integrity", "the system changed after the agent told someone it had not"),
3183
+ ...later.source ? { source: later.source } : {}
3184
+ });
3185
+ break;
3186
+ }
3187
+ if (opts.readBack) for (const claim of claims.filter((c) => c.polarity === "success")) {
3188
+ 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))) {
3189
+ const rb = opts.readBack(w);
3190
+ if (!rb || covered(w.service, "claimed-change-unchanged")) continue;
3191
+ const unchanged = w.method === "DELETE" ? rb.after !== void 0 : canonical2(stable(rb.before)) === canonical2(stable(rb.after));
3192
+ if (!unchanged) continue;
3193
+ out.push({
3194
+ check: "claimed-change-unchanged",
3195
+ service: w.service,
3196
+ resource: `${w.method} ${w.path}`,
3197
+ calls: [w.sequence, ...claim.via ? [claim.via] : []],
3198
+ finding: `Your agent said "${claim.text.slice(0, 80)}", but ${w.service} ${w.path} is unchanged at read-back`,
3199
+ impact: { kind: "data-integrity", count: 1, summary: `${w.resourcePath.split("/").filter((s) => s !== "{id}").pop() ?? "record"} ${w.resourceId} was reported changed but is not` },
3200
+ ...claim.source ?? w.source ? { source: claim.source ?? w.source } : {},
3201
+ fix: "confirm-before-announce"
3202
+ });
3203
+ break;
3204
+ }
3205
+ }
3206
+ 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))) {
3207
+ if (writes.some((r) => r.sequence > failed.sequence && sameRequest(failed, r) && succeeded(r))) continue;
3208
+ 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));
3209
+ if (!committed || covered(committed.service, "partial-commit")) continue;
3210
+ out.push({
3211
+ check: "partial-commit",
3212
+ service: committed.service,
3213
+ resource: `${committed.method} ${committed.path}`,
3214
+ calls: [committed.sequence, failed.sequence],
3215
+ finding: `${label(committed)} was saved, then ${label(failed)} failed (${faultWords(failed)}) and nothing undid the first write`,
3216
+ impact: impactOf([committed], 0, "data-integrity", `${committed.service} and ${failed.service} disagree: one recorded the change, the other did not`),
3217
+ ...failed.source ? { source: failed.source } : {}
3218
+ });
3219
+ break;
3220
+ }
3221
+ return out;
3222
+ }
3223
+ function worldReadBack(ctx) {
3224
+ return (c) => {
3225
+ const find = (state) => (state?.[c.service]?.[c.resourcePath.replace(/\/\{id\}$/, "")] ?? []).find((r) => r && typeof r === "object" && String(r.id) === c.resourceId);
3226
+ return { before: find(ctx.initialState), after: find(ctx.finalState) };
3227
+ };
3228
+ }
3229
+ function genericWorldChecks(covers) {
3230
+ const rules = ["retry-without-key", "announce-after-failed-write", "write-after-reported-failure", "claimed-change-unchanged", "partial-commit"];
3231
+ return rules.map((rule) => ({
3232
+ id: `generic.${rule}`,
3233
+ title: GENERIC_TITLES[rule][0],
3234
+ expected: GENERIC_TITLES[rule][1],
3235
+ path: "/",
3236
+ impact: rule === "announce-after-failed-write" ? "customer-facing" : rule === "retry-without-key" ? "reliability" : "data-integrity",
3237
+ impactHint: GENERIC_TITLES[rule][1],
3238
+ run(ctx) {
3239
+ if (["openai", "anthropic", "google-oauth", "postgres"].includes(ctx.service.adapter ?? "")) return [];
3240
+ const adapterOf = (name) => ctx.services.find((s) => s.name === name)?.adapter;
3241
+ const calls = callsFromWorldEvents(ctx.events).filter((c) => !["openai", "anthropic", "google-oauth"].includes(adapterOf(c.service) ?? ""));
3242
+ 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 }));
3243
+ }
3244
+ }));
3245
+ }
3246
+ function proofFindings(violations, calls) {
3247
+ return violations.map((v, i) => {
3248
+ const involved = new Set(v.calls), first = calls.find((c) => c.sequence === v.calls[0]);
3249
+ 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";
3250
+ const failed = calls.find((c) => involved.has(c.sequence) && FAILED.includes(c.outcome));
3251
+ return {
3252
+ id: `generic_${v.check.replace(/-/g, "_")}_${i + 1}`,
3253
+ kind,
3254
+ service: v.service,
3255
+ path: v.resource.split(" ")[1] ?? "/",
3256
+ title: v.finding,
3257
+ records: [],
3258
+ 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) })),
3259
+ ...v.source ? { source: v.source } : {},
3260
+ ...v.writeSites?.length ? { writeSites: v.writeSites } : {},
3261
+ ...failed ? { fault: { type: failed.outcome, service: failed.service, path: failed.path, triggered: true } } : {},
3262
+ ...kind === "duplicate-effect" ? { expected: 1, actual: Math.max(2, v.impact.count !== void 0 ? v.impact.count + 1 : 2) } : {},
3263
+ adapter: first?.tier ?? "generic",
3264
+ ...v.fix ? { hint: v.fix } : {},
3265
+ ...failed?.source && v.check === "announce-after-failed-write" ? { relatedSource: { file: failed.source.file, line: failed.source.line } } : {}
3266
+ };
3267
+ });
3268
+ }
3269
+ 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;
3270
+ var init_generic_calls = __esm({
3271
+ "src/runtime/generic-calls.ts"() {
3272
+ "use strict";
3273
+ init_run_summary();
3274
+ WRITE_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
3275
+ READ_LIKE = /\/(search|query|lookup|count|batch\/read|completions|embeddings|responses|count_tokens|graphql\/query)$/i;
3276
+ MODEL_HOST = /(^|\.)(openai\.com|anthropic\.com|generativelanguage\.googleapis\.com|mistral\.ai|groq\.com|cohere\.ai)$/i;
3277
+ VOLATILE = /^(id|ts|created|created_at|updated_at|createdAt|updatedAt|timestamp|request_id|requestId|nonce|uuid|sequence|object|livemode)$|_at$/;
3278
+ KEY_HEADERS = ["idempotency-key", "x-idempotency-key", "x-request-id", "x-amz-client-token"];
3279
+ KEY_FIELDS = /^(idempotency_?key|ClientToken|ClientRequestToken|MessageDeduplicationId|client_token|request_id)$/i;
3280
+ digest = (value3) => `sha256:${createHash5("sha256").update(typeof value3 === "string" ? value3 : canonical2(value3)).digest("hex").slice(0, 16)}`;
3281
+ 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;
3282
+ 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);
3283
+ outcomeOf = (status) => status === void 0 ? "ok" : status === 401 || status === 403 ? "unauthorized" : status === 429 ? "rate-limited" : status >= 500 ? "server-error" : status >= 400 ? "client-error" : "ok";
3284
+ parseSource = (s) => {
3285
+ if (!s) return;
3286
+ if (typeof s !== "string") return s;
3287
+ try {
3288
+ const v = JSON.parse(s);
3289
+ return typeof v?.file === "string" ? v : void 0;
3290
+ } catch {
3291
+ return;
3292
+ }
3293
+ };
3294
+ 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;
3295
+ 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;
3296
+ TEXT_FIELDS = /^(text|body|message|content|subject|summary|description|Body|Message|html|markdown|note|comment)$/;
3297
+ MESSAGING = /(message|messages|sms|mail|email|emails|notification|notifications|notify|send|postMessage|comments?|reply|replies)(\.json)?$/i;
3298
+ polarityOf = (text3) => FAILURE.test(text3) ? "failure" : SUCCESS.test(text3) ? "success" : "neutral";
3299
+ RECIPIENT = /^(to|recipient|recipients|email|phone|phone_number|channel|cc|bcc|To|chat_id|user_id)$/;
3300
+ isAnnouncement = (c) => c.isWrite && !!textOf(c.body) && (MESSAGING.test(c.path) || recipientsOf(c.body).length > 0);
3301
+ AMOUNT = /^(amount|total|price|unit_amount|amount_total|grand_total|subtotal|value|amount_cents|amount_minor|total_cents|price_cents)$/i;
3302
+ times = (n) => n === 2 ? "twice" : `${n} times`;
3303
+ FAILED = ["server-error", "lost-response", "timeout", "client-error", "unauthorized", "rate-limited"];
3304
+ AMBIGUOUS = ["server-error", "lost-response", "timeout"];
3305
+ label = (c) => `${c.method} ${c.path} on ${c.service}`;
3306
+ 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);
3307
+ succeeded = (c) => c.outcome === "ok" || c.outcome === "replayed";
3308
+ effects = (c) => c.committed === false || c.outcome === "replayed" || c.outcome === "blocked" ? 0 : (c.committed || c.outcome === "ok" ? 1 : 0) * (c.duplicated ? 2 : 1);
3309
+ sites = (calls) => [...new Map(calls.filter((c) => c.source).map((c) => [`${c.source.file}:${c.source.line}`, c.source])).values()];
3310
+ groupsOf = (writes) => {
3311
+ const groups2 = [];
3312
+ for (const c of writes) {
3313
+ const g = groups2.find((g2) => sameRequest(g2[0], c));
3314
+ if (g) g.push(c);
3315
+ else groups2.push([c]);
3316
+ }
3317
+ return groups2;
3318
+ };
3319
+ GENERIC_TITLES = {
3320
+ "duplicate-write": ["World-changing calls take effect once", "each create, charge or send is applied once, even under retries and redelivery"],
3321
+ "retry-without-key": ["Retries after a fault reuse the idempotency key", "a write retried after an ambiguous failure carries the same idempotency key"],
3322
+ "retry-after-ignored": ["Rate-limited calls wait for Retry-After", "a 429 is retried no sooner than its Retry-After"],
3323
+ "announce-after-failed-write": ["Success is announced only after the write succeeded", "the agent claims success only when every write it depends on succeeded"],
3324
+ "write-after-reported-failure": ["No writes after the agent reported failure", "after the agent reports a failure it changes nothing else"],
3325
+ "claimed-change-unchanged": ["Claimed changes are visible at read-back", "every resource the agent says it changed is changed when read back"],
3326
+ "partial-commit": ["Multi-service writes commit together or compensate", "when a later write fails, earlier writes in other services are undone"]
3327
+ };
3328
+ }
3329
+ });
3330
+
2968
3331
  // src/runtime/repair-proof-page.ts
2969
3332
  function diffHtml(diff) {
2970
3333
  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 +4029,9 @@ function esbuildBinary(real){const match=real.match(/^(.*[\/\\]node_modules[\/\\
3666
4029
  // the same name inside a project or earlier on PATH is still reported.
3667
4030
  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
4031
  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;}
4032
+ // 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.
4033
+ 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));}
4034
+ 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
4035
  const reportedSubprocesses=new Set();
3671
4036
  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
4037
  // Never throws: an unclassifiable command is reported, and the application's spawn proceeds unchanged.
@@ -3698,7 +4063,9 @@ if(originalFetch)globalThis.fetch=async function(input,init){
3698
4063
  const target=route?route.endpoint+url.pathname+url.search:url.href;
3699
4064
  // Forward the body as bytes: copying a keepalive Request whose body is a stream throws in Node's fetch.
3700
4065
  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'});
4066
+ const signal=init?.signal??(input instanceof Request?input.signal:undefined),sent=originalFetch(target,{method:request.method,headers,body,signal:request.signal,redirect:'error'});
4067
+ if(!signal)return sent;if(signal.aborted)throw signal.reason;
4068
+ 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
4069
  };
3703
4070
  const plainHttp={request:http.request,get:http.get};
3704
4071
  const loopback=host=>['127.0.0.1','localhost','::1','[::1]'].includes(host);
@@ -4173,7 +4540,7 @@ var init_composio_twin = __esm({
4173
4540
  });
4174
4541
 
4175
4542
  // src/runtime/google-oauth-twin.ts
4176
- import { createHash as createHash5 } from "crypto";
4543
+ import { createHash as createHash6 } from "crypto";
4177
4544
  var googleOAuthOperation;
4178
4545
  var init_google_oauth_twin = __esm({
4179
4546
  "src/runtime/google-oauth-twin.ts"() {
@@ -4190,7 +4557,7 @@ var init_google_oauth_twin = __esm({
4190
4557
  const grant = data["/grants"].find((row) => row.refresh_token === params.refresh_token && row.client_id === params.client_id);
4191
4558
  if (!grant || !synthetic(grant.refresh_token) || grant.active !== true) return error(400, "invalid_grant");
4192
4559
  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);
4560
+ const access_token = "synthetic-access-" + createHash6("sha256").update(JSON.stringify([params.client_id, params.refresh_token, sequence])).digest("hex").slice(0, 24);
4194
4561
  const body = { access_token, token_type: "Bearer", expires_in: grant.expires_in, scope: grant.scope };
4195
4562
  const record5 = { id: "issuance_" + sequence, client_id: params.client_id, ...body };
4196
4563
  data["/tokens"].push(record5);
@@ -4337,7 +4704,7 @@ var init_resp = __esm({
4337
4704
 
4338
4705
  // src/runtime/engines/redis-lua.ts
4339
4706
  import { createRequire } from "module";
4340
- import { createHash as createHash6 } from "crypto";
4707
+ import { createHash as createHash7 } from "crypto";
4341
4708
  var vm, load, toLua, fromLua, RedisScripts, WRITE_HINT;
4342
4709
  var init_redis_lua = __esm({
4343
4710
  "src/runtime/engines/redis-lua.ts"() {
@@ -4376,7 +4743,7 @@ var init_redis_lua = __esm({
4376
4743
  return this.execute(source, args.slice(2, 2 + count), args.slice(2 + count), name.endsWith("_ro"));
4377
4744
  }
4378
4745
  store(source) {
4379
- const sha6 = createHash6("sha1").update(Buffer.from(source, "latin1")).digest("hex");
4746
+ const sha6 = createHash7("sha1").update(Buffer.from(source, "latin1")).digest("hex");
4380
4747
  this.cache.set(sha6, source);
4381
4748
  return sha6;
4382
4749
  }
@@ -5818,7 +6185,7 @@ var init_gmail_mime = __esm({
5818
6185
  });
5819
6186
 
5820
6187
  // src/runtime/rest-adapters.ts
5821
- import { createHash as createHash7 } from "crypto";
6188
+ import { createHash as createHash8 } from "crypto";
5822
6189
  function githubOperation(method, path2, params, _headers, data, sequence) {
5823
6190
  const errors = (status, message, extra) => ({ status, body: { message, documentation_url: "https://docs.github.com/rest", ...extra ?? {} }, collection: "/repos" });
5824
6191
  if (path2 === "/repos") return method === "GET" ? ok("/repos", rows(data, "/repos").map((row) => structuredClone(row))) : void 0;
@@ -6948,7 +7315,7 @@ var init_rest_adapters = __esm({
6948
7315
  init_gmail_mime();
6949
7316
  EPOCH2 = 17e8;
6950
7317
  iso2 = (epoch = EPOCH2) => new Date(twinNowMs(epoch * 1e3)).toISOString();
6951
- sha2 = (value3) => createHash7("sha256").update(value3).digest("hex");
7318
+ sha2 = (value3) => createHash8("sha256").update(value3).digest("hex");
6952
7319
  detUuid = (seed) => {
6953
7320
  const hex = sha2(seed).slice(0, 32).split("");
6954
7321
  hex[12] = "4";
@@ -7324,12 +7691,12 @@ __export(http_world_exports, {
7324
7691
  import { createServer as createServer3 } from "http";
7325
7692
  import { createServer as createNetServer } from "net";
7326
7693
  import { isDeepStrictEqual as isDeepStrictEqual2 } from "util";
7327
- import { createHash as createHash8 } from "crypto";
7694
+ import { createHash as createHash9 } from "crypto";
7328
7695
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
7329
7696
  import { mkdir as mkdir4, mkdtemp as mkdtemp5, rm as rm8, writeFile as writeFile7 } from "fs/promises";
7330
7697
  import { tmpdir as tmpdir5 } from "os";
7331
7698
  import { join as join14 } from "path";
7332
- var slackDirectMessageId, idempotencyKeyDigest, HttpWorld;
7699
+ var KEYED_PACKS, slackDirectMessageId, idempotencyKeyDigest, HttpWorld;
7333
7700
  var init_http_world = __esm({
7334
7701
  "src/runtime/http-world.ts"() {
7335
7702
  "use strict";
@@ -7346,8 +7713,9 @@ var init_http_world = __esm({
7346
7713
  init_pack_log();
7347
7714
  init_pack_aliases();
7348
7715
  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;
7716
+ KEYED_PACKS = /* @__PURE__ */ new Set(["resend"]);
7717
+ slackDirectMessageId = (user) => `D${createHash9("sha256").update(user).digest("hex").slice(0, 16).toUpperCase()}`;
7718
+ idempotencyKeyDigest = (key3) => typeof key3 === "string" && key3 ? `sha256:${createHash9("sha256").update(key3).digest("hex").slice(0, 16)}` : void 0;
7351
7719
  HttpWorld = class {
7352
7720
  /** The one-command flow runs apps that hard-code their own model key: the model twins then accept any credential. */
7353
7721
  constructor(spec, seed, options = {}) {
@@ -7744,7 +8112,7 @@ var init_http_world = __esm({
7744
8112
  return;
7745
8113
  }
7746
8114
  }
7747
- if (!this.fired && result2.operation === "write" && fault?.type === "timeout-after-write" && fault.service === service.name && fault.path === result2.collection) {
8115
+ 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
8116
  this.fired = true;
7749
8117
  this.faultActions++;
7750
8118
  this.record(service.name, "fault", result2.collection, `write committed; response delayed ${fault.delayMs}ms`);
@@ -7906,6 +8274,8 @@ var init_http_world = __esm({
7906
8274
  rawServers = [];
7907
8275
  /** Each pack service's plain-TCP port for clients that open their own TLS sockets (see startPack). */
7908
8276
  packTcp = /* @__PURE__ */ Object.create(null);
8277
+ /** Saved responses by service, path and Idempotency-Key, for packs whose vendor replays keyed requests. */
8278
+ packReplays = /* @__PURE__ */ new Map();
7909
8279
  /**
7910
8280
  * A twin pack served behind this world: the run token is checked and swapped for the credential the pack issued,
7911
8281
  * seeded fault schedules apply around the pack's own handler, and every action the pack logs becomes evidence — writes
@@ -8013,7 +8383,7 @@ var init_http_world = __esm({
8013
8383
  const row = { id: id2, ...a.fields ?? {} };
8014
8384
  if (removed) {
8015
8385
  if (at >= 0) rows2.splice(at, 1);
8016
- } else if (at >= 0) rows2[at] = row;
8386
+ } else if (at >= 0) rows2[at] = { ...rows2[at], ...row };
8017
8387
  else rows2.push(row);
8018
8388
  if (!evidence) continue;
8019
8389
  const byApp = a.actor?.kind === "agent" && !byWorld;
@@ -8086,7 +8456,7 @@ var init_http_world = __esm({
8086
8456
  return;
8087
8457
  }
8088
8458
  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" };
8459
+ 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
8460
  last.send(JSON.stringify(again));
8091
8461
  this.record(service.name, "twin", path2, `redelivered ${String(last.envelope.type ?? "envelope")} (retry_attempt ${attempt}, as after a lost acknowledgment)`);
8092
8462
  json3(200, { ok: true, retry_attempt: attempt });
@@ -8160,6 +8530,13 @@ var init_http_world = __esm({
8160
8530
  return { status: r.status, headers: r.headers, bytes: model.restore(Buffer.from(await r.arrayBuffer())), actions: log.drain() };
8161
8531
  };
8162
8532
  if (workspace && method !== "GET") this.causing[service.name] = 1;
8533
+ const replayKey = !workspace && method === "POST" && typeof requestKey === "string" && requestKey && KEYED_PACKS.has(name) ? `${service.name}:${path2}:${requestKey}` : void 0;
8534
+ const replay = replayKey ? this.packReplays.get(replayKey) : void 0;
8535
+ if (replay) {
8536
+ this.record(service.name, "twin", path2, `replayed the first response for Idempotency-Key ${requestKey}; nothing written`);
8537
+ respond(replay.status, replay.out, replay.bytes);
8538
+ return;
8539
+ }
8163
8540
  const first = await serialized(call2).finally(() => {
8164
8541
  if (workspace) this.causing[service.name] = 0;
8165
8542
  });
@@ -8205,13 +8582,14 @@ var init_http_world = __esm({
8205
8582
  first.headers.forEach((v, k) => {
8206
8583
  if (!/^(content-length|transfer-encoding|connection)$/i.test(k)) out[k] = v;
8207
8584
  });
8208
- if (target && !this.fired && fault?.type === "timeout-after-write" && fault.service === service.name && matchesFault(target)) {
8585
+ if (replayKey && first.status < 500) this.packReplays.set(replayKey, { status: first.status, out, bytes: first.bytes });
8586
+ if (target && !this.fired && fault?.type === "timeout-after-write" && fault.service === service.name && (matchesFault(target) || matchesFault(path2))) {
8209
8587
  this.fired = true;
8210
8588
  this.faultActions++;
8211
8589
  this.record(service.name, "fault", target, `write committed; response delayed ${fault.delayMs}ms`);
8212
8590
  this.keyed(requestKey);
8213
8591
  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))) {
8592
+ } else if (fault?.type === "slow-response" && faultOrdinalsFor && (matchesFault(target ?? path2) || matchesFault(path2)) && faultOrdinalsFor.includes(this.candidateIndex(faultKey))) {
8215
8593
  this.faultActions++;
8216
8594
  this.record(service.name, "fault", target ?? path2, `slow-response: ${target ? "write" : "request"} applied; response delayed ${fault.delayMs}ms`);
8217
8595
  this.keyed(requestKey);
@@ -8413,7 +8791,7 @@ function evaluateProperty(policy, final, events) {
8413
8791
  const keyed = /* @__PURE__ */ new Map();
8414
8792
  for (const row of rows2) {
8415
8793
  if (row[field2] === void 0) continue;
8416
- const key3 = JSON.stringify(canonical2(row[field2]));
8794
+ const key3 = JSON.stringify(canonical3(row[field2]));
8417
8795
  keyed.set(key3, [...keyed.get(key3) ?? [], row.id ?? row]);
8418
8796
  }
8419
8797
  const duplicates = [...keyed.entries()].filter(([, list4]) => list4.length > 1);
@@ -8422,7 +8800,7 @@ function evaluateProperty(policy, final, events) {
8422
8800
  passed: duplicates.length === 0,
8423
8801
  expected: 0,
8424
8802
  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) }
8803
+ 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
8804
  };
8427
8805
  }
8428
8806
  if (policy.kind === "no-loss") {
@@ -8455,12 +8833,12 @@ function evaluateProperty(policy, final, events) {
8455
8833
  evidence: { operation, eventSequences: hits.map((e) => e.sequence), evidenceGap: unknown }
8456
8834
  };
8457
8835
  }
8458
- var matches2, canonical2, short, escape;
8836
+ var matches2, canonical3, short, escape;
8459
8837
  var init_evaluation = __esm({
8460
8838
  "src/runtime/evaluation.ts"() {
8461
8839
  "use strict";
8462
8840
  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;
8841
+ 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
8842
  short = (value3, limit2 = 120) => value3.length <= limit2 ? value3 : `${value3.slice(0, limit2)}\u2026`;
8465
8843
  escape = (value3) => value3.replace(/~/g, "~0").replace(/\//g, "~1");
8466
8844
  }
@@ -8787,367 +9165,6 @@ var init_contracts = __esm({
8787
9165
  }
8788
9166
  });
8789
9167
 
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
9168
  // src/runtime/default-checks.ts
9152
9169
  function addedRows(initial, final) {
9153
9170
  const rows2 = (list4) => list4.filter((r) => !!r && typeof r === "object" && !Array.isArray(r));
@@ -9238,7 +9255,7 @@ function defaultChecksFor(services, opts = {}) {
9238
9255
  }
9239
9256
  function runDefaultChecks(input) {
9240
9257
  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 }) => {
9258
+ return defaultChecksFor(services, { postgres: !!input.database }).map(({ service, check }) => {
9242
9259
  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
9260
  const base = { id: `default.${check.id}.${service.name}`, kind: "default", check: check.id, title: check.title, service: service.name, expected: check.expected };
9244
9261
  if (!violations.length) return { ...base, path: check.path, passed: true, actual: "no violations" };
@@ -9273,7 +9290,9 @@ function defaultFaultMatrix(services, opts = {}) {
9273
9290
  presets.push(
9274
9291
  { 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
9292
  { 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" } }
9293
+ { 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
+ // An outage outlasts the client's own retries (Stripe's SDK retries a 500): the action really fails.
9295
+ { 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
9296
  );
9278
9297
  }
9279
9298
  }
@@ -9285,7 +9304,7 @@ function defaultFaultMatrix(services, opts = {}) {
9285
9304
  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
9305
  return entries;
9287
9306
  }
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;
9307
+ var PROVIDER, displayName, rowsOf, VOLATILE2, volatileKey, canonical4, contentSignature, writeSequences, times2, money, stripeRefundOnce, stripeNoDuplicatePayment, stripeIdempotentRetries, NEGATIVE, gmailText, TARGETED, postgresUpdateApplied, postgresNoDuplicateInsert, UNSCOPED, postgresNoUnscopedDestructive, NOT_EFFECTS, genericRepeat, DEFAULT_CHECKS, VENDOR_COVERS, registryFor, refOf, WRITE_PATHS, slug;
9289
9308
  var init_default_checks = __esm({
9290
9309
  "src/runtime/default-checks.ts"() {
9291
9310
  "use strict";
@@ -9298,9 +9317,14 @@ var init_default_checks = __esm({
9298
9317
  };
9299
9318
  rowsOf = (state, service, path2) => (state?.[service]?.[path2] ?? []).filter((r) => !!r && typeof r === "object" && !Array.isArray(r));
9300
9319
  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);
9320
+ 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
9321
  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))));
9322
+ contentSignature = (row, collection) => {
9323
+ const type = (collection?.split("/").filter(Boolean).pop() ?? "").toLowerCase().replace(/[^a-z]/g, "").replace(/ies$/, "y").replace(/s$/, "");
9324
+ const ownId = (k) => !!type && k.toLowerCase().replace(/[^a-z]/g, "") === type + "id";
9325
+ const own = Object.entries(row).filter(([k, v]) => (volatileKey(k) || ownId(k)) && typeof v === "string" && v.length >= 6).map(([, v]) => v);
9326
+ return canonical4(Object.fromEntries(Object.entries(row).filter(([k, v]) => !volatileKey(k) && !ownId(k) && !own.some((id2) => JSON.stringify(v ?? null).includes(id2)))));
9327
+ };
9304
9328
  writeSequences = (ctx, service, ids) => ctx.events.filter((e) => e.service === service && e.operation === "write" && ids.includes(e.record?.id)).map((e) => e.sequence);
9305
9329
  times2 = (n) => n === 2 ? "twice" : `${n} times`;
9306
9330
  money = (amount, currency) => formatMoney({ amount: amount / 100, currency: currency.toUpperCase() });
@@ -9309,6 +9333,7 @@ var init_default_checks = __esm({
9309
9333
  title: "Each charge refunded at most once per request",
9310
9334
  path: "/v1/refunds",
9311
9335
  coversDuplicates: true,
9336
+ duplicatePaths: ["/v1/refunds"],
9312
9337
  expected: "each charge refunded at most once for the same amount and reason; refund total \u2264 charge amount",
9313
9338
  impact: "money",
9314
9339
  impactHint: "duplicated refund amount is money paid out twice",
@@ -9343,6 +9368,7 @@ var init_default_checks = __esm({
9343
9368
  title: "No duplicate charges, customers or subscriptions for one request",
9344
9369
  path: "/v1/payment_intents",
9345
9370
  coversDuplicates: true,
9371
+ duplicatePaths: ["/v1/payment_intents", "/v1/charges", "/v1/customers", "/v1/subscriptions"],
9346
9372
  expected: "one payment intent per amount/currency/customer/payment method and one customer per email",
9347
9373
  impact: "money",
9348
9374
  impactHint: "a duplicated succeeded payment charges the customer twice",
@@ -9416,6 +9442,7 @@ var init_default_checks = __esm({
9416
9442
  const header3 = (name) => headers.find((h2) => h2.name?.toLowerCase() === name)?.value ?? "";
9417
9443
  return { to: header3("to"), subject: header3("subject"), body: String(r.payload?.body?.data ?? r.snippet ?? "") };
9418
9444
  };
9445
+ TARGETED = /\bwhere\b[\s\S]*=\s*\$\d/i;
9419
9446
  postgresUpdateApplied = {
9420
9447
  id: "postgres.update-applied",
9421
9448
  title: "Updates the agent ran actually changed rows",
@@ -9424,7 +9451,7 @@ var init_default_checks = __esm({
9424
9451
  impact: "data-integrity",
9425
9452
  impactHint: "the agent believes a record changed when it did not",
9426
9453
  run(ctx) {
9427
- return (ctx.database?.statements ?? []).filter((st) => /^(UPDATE|DELETE)$/i.test(st.command ?? "") && st.count === 0).map((st) => {
9454
+ 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
9455
  const table4 = /^\s*(?:update|delete\s+from)\s+(?:only\s+)?"?([\w.]+)"?/i.exec(st.text)?.[1] ?? "a table";
9429
9456
  return {
9430
9457
  path: `/${table4}`,
@@ -9448,7 +9475,7 @@ var init_default_checks = __esm({
9448
9475
  if (!ctx.database?.final) return out;
9449
9476
  for (const table4 of ctx.database.final.tables) {
9450
9477
  const before = ctx.database.initial.tables.find((t) => t.name === table4.name)?.rows ?? [];
9451
- for (const group of groups(addedRows(before, table4.rows), contentSignature))
9478
+ for (const group of groups(addedRows(before, table4.rows), (r) => contentSignature(r, table4.name)))
9452
9479
  out.push({
9453
9480
  path: `/${table4.name}`,
9454
9481
  actual: { table: table4.name, rows: group.length, row: group[0] },
@@ -9459,6 +9486,30 @@ var init_default_checks = __esm({
9459
9486
  return out;
9460
9487
  }
9461
9488
  };
9489
+ 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;
9490
+ postgresNoUnscopedDestructive = {
9491
+ id: "postgres.no-unscoped-destructive",
9492
+ title: "No statement wipes or rewrites a whole table",
9493
+ path: "/",
9494
+ expected: "every DELETE and UPDATE is limited by a WHERE clause; no TRUNCATE or DROP",
9495
+ impact: "data-integrity",
9496
+ impactHint: "every row in the table is deleted or overwritten, not just the ones the action is about",
9497
+ run(ctx) {
9498
+ const out = [];
9499
+ for (const st of ctx.database?.statements ?? []) {
9500
+ const m = UNSCOPED.exec(st.text);
9501
+ if (!m) continue;
9502
+ const verb = (m[1] ?? m[3] ?? m[5]).toUpperCase().replace(/\s+FROM$/, ""), table4 = m[2] ?? m[4] ?? m[6];
9503
+ out.push({
9504
+ path: `/${table4}`,
9505
+ actual: { statement: st.text.slice(0, 200), rowsAffected: st.count ?? null },
9506
+ 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)`,
9507
+ impact: { count: 1 }
9508
+ });
9509
+ }
9510
+ return out;
9511
+ }
9512
+ };
9462
9513
  NOT_EFFECTS = /* @__PURE__ */ new Set(["openai", "anthropic", "google-oauth"]);
9463
9514
  genericRepeat = {
9464
9515
  id: "generic.no-repeat-after-fault",
@@ -9469,11 +9520,13 @@ var init_default_checks = __esm({
9469
9520
  impactHint: "the same record exists twice downstream",
9470
9521
  run(ctx) {
9471
9522
  const s = ctx.service.name, out = [];
9472
- if (NOT_EFFECTS.has(ctx.service.adapter ?? "") || registryFor(ctx.service.adapter).some((c) => c.coversDuplicates)) return out;
9523
+ const covering = registryFor(ctx.service.adapter).filter((c) => c.coversDuplicates);
9524
+ if (NOT_EFFECTS.has(ctx.service.adapter ?? "") || covering.some((c) => !c.duplicatePaths)) return out;
9525
+ const judged = new Set(covering.flatMap((c) => c.duplicatePaths ?? []));
9473
9526
  const faults = ctx.events.filter((e) => e.operation === "fault").map((e) => e.sequence);
9474
9527
  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)) {
9528
+ for (const path2 of Object.keys(ctx.finalState?.[s] ?? {}).filter((p) => !judged.has(p))) {
9529
+ for (const group of groups(addedRows(rowsOf(ctx.initialState, s, path2), rowsOf(ctx.finalState, s, path2)), (r) => contentSignature(r, path2))) {
9477
9530
  const seq = writeSequences(ctx, s, group.map((r) => r.id));
9478
9531
  if (!ctx.duplicateDelivery && seq.length && !faults.some((f) => f < Math.max(...seq))) continue;
9479
9532
  const label2 = path2.split("/").filter(Boolean).pop() ?? "record";
@@ -9493,7 +9546,7 @@ var init_default_checks = __esm({
9493
9546
  stripe: [stripeRefundOnce, stripeNoDuplicatePayment, stripeIdempotentRetries],
9494
9547
  slack: messageChecks("slack", "/messages"),
9495
9548
  gmail: messageChecks("gmail", "/gmail/v1/users/me/messages"),
9496
- postgres: [postgresUpdateApplied, postgresNoDuplicateInsert],
9549
+ postgres: [postgresUpdateApplied, postgresNoDuplicateInsert, postgresNoUnscopedDestructive],
9497
9550
  "*": [genericRepeat]
9498
9551
  };
9499
9552
  VENDOR_COVERS = { "retry-without-key": /\.idempotent-retries$/, "announce-after-failed-write": /\.announce-after-success$/ };
@@ -9720,7 +9773,7 @@ function twinRoutes(services, world, models) {
9720
9773
  continue;
9721
9774
  }
9722
9775
  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 });
9776
+ 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
9777
  }
9725
9778
  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
9779
  return routes2;
@@ -9822,7 +9875,13 @@ var init_twin_routing = __esm({
9822
9875
  linear: [{ hosts: ["api.linear.app"], auth: "bearer" }],
9823
9876
  notion: [{ hosts: ["api.notion.com"], auth: "bearer" }],
9824
9877
  hubspot: [{ hosts: ["api.hubapi.com"], auth: "bearer" }],
9825
- twilio: [{ hosts: ["api.twilio.com"], auth: "bearer" }]
9878
+ twilio: [{ hosts: ["api.twilio.com"], auth: "bearer" }],
9879
+ // Hand-built twins reached on a customer's own subdomain.
9880
+ zendesk: [{ hosts: ["zendesk.com"], suffix: true, auth: "bearer" }],
9881
+ jira: [{ hosts: ["atlassian.net"], suffix: true, auth: "bearer" }],
9882
+ shopify: [{ hosts: ["myshopify.com"], suffix: true, auth: "bearer" }],
9883
+ gitlab: [{ hosts: ["gitlab.com"], auth: "bearer" }],
9884
+ datadog: [{ hosts: ["api.datadoghq.com", "api.datadoghq.eu", "api.us5.datadoghq.com"], auth: "bearer" }]
9826
9885
  };
9827
9886
  KNOWN_PROVIDER_SUFFIXES = {
9828
9887
  "openai.com": "openai",
@@ -9875,11 +9934,16 @@ const SECRET=['authorization','x-api-key','cookie','proxy-authorization','host']
9875
9934
  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
9935
  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
9936
  const removed=r=>r.auth==='passthrough'?['host']:SECRET;
9937
+ // The caller's own timeout or abort ends a routed request exactly when it would against the real service: the app's
9938
+ // AbortSignal.timeout is what makes a lost reply turn into a retry, so it must never be lost on the way to a twin.
9939
+ 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
9940
  const originalFetch=globalThis.fetch;
9879
9941
  if(originalFetch)globalThis.fetch=async function(input,init){
9880
9942
  let url;try{url=new URL(typeof input==='string'||input instanceof URL?String(input):input.url);}catch{return originalFetch(input,init);}
9881
9943
  if((url.protocol!=='http:'&&url.protocol!=='https:')||loopback(url.hostname))return originalFetch(input,init);
9882
9944
  const method=String(init?.method||input?.method||'GET').toUpperCase(),r=match(url.hostname,url.pathname);
9945
+ // Web fonts a framework downloads while it renders (next/font): an empty stylesheet or font, so rendering goes on offline.
9946
+ 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
9947
  if(!r)throw blocked('fetch',url.hostname,url.port||(url.protocol==='https:'?443:80),method);
9884
9948
  if(process.env.AGENTTWIN_DEBUG_ROUTES)console.error('route-match '+url.hostname+' auth='+r.auth+' service='+r.service);
9885
9949
  const request=new Request(input,init),headers=new Headers(request.headers);
@@ -9889,7 +9953,7 @@ if(originalFetch)globalThis.fetch=async function(input,init){
9889
9953
  // Forward the body as bytes: copying a keepalive Request whose body is a stream throws in Node's fetch (Upstash's
9890
9954
  // client sets keepalive on every call).
9891
9955
  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});
9956
+ 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
9957
  };
9894
9958
  const originalHttpRequest=http.request;
9895
9959
  for(const [mod,scheme] of [[http,'http'],[https,'https']]){
@@ -9904,6 +9968,15 @@ for(const [mod,scheme] of [[http,'http'],[https,'https']]){
9904
9968
  if(loopback(host))return original.apply(this,args);
9905
9969
  const method=String(options.method||'GET').toUpperCase(),requestPath=options.path||(url?url.pathname+url.search:'/');
9906
9970
  const r=match(host,String(requestPath).split('?')[0]);
9971
+ // Web fonts (next/font) over http(s): an empty answer from an in-memory socket, so rendering goes on offline.
9972
+ if(!r&&/^fonts\.(googleapis|gstatic)\.com$/.test(bare(host))){
9973
+ const {Duplex}=require('node:stream'),type=/googleapis/.test(host)?'text/css':'font/woff2';let sent=false;
9974
+ 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();}});
9975
+ socket.setTimeout=()=>socket;socket.setNoDelay=()=>socket;socket.setKeepAlive=()=>socket;socket.ref=()=>socket;socket.unref=()=>socket;
9976
+ const {agent:_a,...plain}=options;
9977
+ const req=originalHttpRequest({...plain,method,path:requestPath,host:'127.0.0.1',port:9,createConnection:()=>socket},callback);
9978
+ return req;
9979
+ }
9907
9980
  if(!r)throw blocked(scheme,host,options.port||url?.port||(scheme==='https'?443:80),method);
9908
9981
  const target=new URL(r.target),headers={};
9909
9982
  const given=options.headers||{};
@@ -10041,6 +10114,7 @@ async function startPostgresEngine(options = {}) {
10041
10114
  const createOptions = (extra = {}) => ({ ...extra, ...Object.keys(extensions).length ? { extensions } : {} });
10042
10115
  let db = await PGlite.create(createOptions());
10043
10116
  const version = String((await db.query("show server_version")).rows[0]?.server_version ?? "17");
10117
+ const statements = [];
10044
10118
  const events = [], unsupported3 = [], gate = new FaultGate("postgres", events), listeners = [];
10045
10119
  const lockWaitMs = options.lockWaitMs ?? 5e3;
10046
10120
  const conns = /* @__PURE__ */ new Set();
@@ -10141,6 +10215,19 @@ async function startPostgresEngine(options = {}) {
10141
10215
  const outputs = [];
10142
10216
  for (const m of prepared) outputs.push(await raw(msg(m.type, m.body)));
10143
10217
  const out = Buffer.concat(outputs), { tags, status, failed } = scan(out);
10218
+ const executed = batch.flatMap((m) => {
10219
+ if (m.type === "Q") return [m.body.toString("utf8", 0, m.body.length - 1)];
10220
+ if (m.type !== "B") return [];
10221
+ const pEnd = m.body.indexOf(0), sEnd = m.body.indexOf(0, pEnd + 1), stmt = m.body.toString("utf8", pEnd + 1, sEnd);
10222
+ const q3 = stmt ? conn.names.get(stmt) : conn.unnamed;
10223
+ return q3 ? [q3] : [];
10224
+ });
10225
+ const cmdTags = tags.filter((t) => !/^(BEGIN|COMMIT|ROLLBACK|SET)$/.test(t));
10226
+ executed.forEach((text3, i) => {
10227
+ if (!isWriteSql(text3) || statements.length >= 1e3) return;
10228
+ const tag = executed.length === cmdTags.length ? cmdTags[i] : void 0, m = tag ? /^(\w+)(?:\s+\d+)?\s+(\d+)$/.exec(tag) : null;
10229
+ statements.push({ text: text3.slice(0, 2048), ...tag ? { command: tag.split(" ")[0] } : {}, ...m ? { count: Number(m[2]) } : {} });
10230
+ });
10144
10231
  for (const t of writeTables) conn.txnTables.add(t);
10145
10232
  const binds = batch.filter((m) => m.type === "B").map((m) => {
10146
10233
  const pEnd = m.body.indexOf(0), sEnd = m.body.indexOf(0, pEnd + 1), stmt = m.body.toString("utf8", pEnd + 1, sEnd);
@@ -10377,6 +10464,7 @@ async function startPostgresEngine(options = {}) {
10377
10464
  startupMs: Date.now() - started,
10378
10465
  events,
10379
10466
  unsupported: unsupported3,
10467
+ statements,
10380
10468
  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
10469
  get faultTriggered() {
10382
10470
  return gate.triggered;
@@ -10545,6 +10633,7 @@ async function startLocalEngines(app, spec) {
10545
10633
  const final = await snapshotPublicTables(postgres2).catch(() => void 0);
10546
10634
  return final && { engine: "embedded-postgres", extensions: [...spec.postgres?.extensions ?? []], initial: initialTables, final };
10547
10635
  },
10636
+ statements: () => [...postgres2?.statements ?? []],
10548
10637
  unsupported: () => started.flatMap((e) => e.unsupported.map((u) => `${e.kind}: ${u}`)),
10549
10638
  stop
10550
10639
  };
@@ -10781,9 +10870,10 @@ async function executeLocal(app, spec, signal, existingWorld, seed, extraEnv = {
10781
10870
  }
10782
10871
  const assertions = world.assertions();
10783
10872
  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
10873
  const infrastructureAssertions = await engines2.evaluate();
10786
10874
  const embeddedDatabase = await engines2.databaseEvidence();
10875
+ const database = embeddedDatabase ? { initial: embeddedDatabase.initial, final: embeddedDatabase.final, statements: engines2.statements() } : void 0;
10876
+ const defaultChecks = runDefaultChecks({ spec, initialState, finalState: world.state, events: world.events, fault: spec.fault ? { ...spec.fault, triggered: world.faultTriggered } : null, ...database ? { database } : {} });
10787
10877
  const unsupported3 = [...world.unsupported, ...engines2.unsupported()];
10788
10878
  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
10879
  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 +13238,8 @@ async function loadDashboardDiscovery(cwd, inventory, opts = {}) {
13148
13238
  previousHead = JSON.parse(await readFile18(join27(cwd, ".agenttwin/git.json"), "utf8")).head;
13149
13239
  } catch {
13150
13240
  }
13151
- const git2 = await captureGit(cwd, previousHead);
13152
- const base = discoveryTransfer({ ...dashboardInventory(cwd, inventory), ...git2 ? { git: git2 } : {} });
13241
+ const git3 = await captureGit(cwd, previousHead);
13242
+ const base = discoveryTransfer({ ...dashboardInventory(cwd, inventory), ...git3 ? { git: git3 } : {} });
13153
13243
  if (opts.includeAgentDiscovery === false) return projectProducts(cwd, base, base);
13154
13244
  let raw;
13155
13245
  try {
@@ -13279,7 +13369,7 @@ async function runWorld(cwd, opts) {
13279
13369
  const sourceDigests = await stageApplication(dirname5(file), spec.files, join28(stage, "app"));
13280
13370
  await writeFile16(join28(stage, "world.json"), JSON.stringify(spec), { mode: 420 });
13281
13371
  if (runtime === "e2b" && suppliedSeed) await writeFile16(join28(stage, "seed.json"), JSON.stringify({ seed: suppliedSeed }), { mode: 420 });
13282
- const git2 = await captureGit(sourceBuild?.root ?? cwd);
13372
+ const git3 = await captureGit(sourceBuild?.root ?? cwd);
13283
13373
  let project2;
13284
13374
  try {
13285
13375
  project2 = JSON.parse(await readFile19(join28(inventoryRoot, ".agenttwin/inventory.json"), "utf8")).name ?? basename3(cwd);
@@ -13305,7 +13395,7 @@ async function runWorld(cwd, opts) {
13305
13395
  }
13306
13396
  }
13307
13397
  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" };
13398
+ 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
13399
  const out2 = resolve7(cwd, opts.out ?? `.agenttwin/runs/${runId2}`);
13310
13400
  await mkdir10(out2, { recursive: true });
13311
13401
  const evidencePath = join28(out2, "run.json"), reportPath = join28(out2, "report.md");
@@ -13313,7 +13403,7 @@ async function runWorld(cwd, opts) {
13313
13403
  await writeFile16(join28(out2, "world.json"), JSON.stringify(spec, null, 2) + "\n", { mode: 384 });
13314
13404
  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
13405
  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}
13406
+ Runner: CLI \xB7 Git: ${git3?.head ?? "unavailable"} \xB7 Seed: ${receipt2.seed}
13317
13407
  ${receipt2.reproducibility ?? ""}
13318
13408
  ${sourceBuildError ?? ""}
13319
13409
  Full evidence (activities, fault, initial and final state): run.json
@@ -13322,7 +13412,7 @@ Full evidence (activities, fault, initial and final state): run.json
13322
13412
  }
13323
13413
  await stageWorker(stage, import.meta.url);
13324
13414
  if (runtime === "hosted") {
13325
- const receipt2 = await executeRemote(stage, spec, opts.log, { git: git2, project: project2, seed: suppliedSeed });
13415
+ const receipt2 = await executeRemote(stage, spec, opts.log, { git: git3, project: project2, seed: suppliedSeed });
13326
13416
  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
13417
  if (suppliedSeed && receipt2.seed !== suppliedSeed) throw new CliError("Hosted receipt does not match the requested seed");
13328
13418
  const expectedSpec = createHash13("sha256").update(JSON.stringify(spec)).digest("hex");
@@ -13354,7 +13444,7 @@ See run.json for assertions, service state, application output and isolation met
13354
13444
  const receipt = {
13355
13445
  ...report,
13356
13446
  project: project2,
13357
- git: git2,
13447
+ git: git3,
13358
13448
  ...spec.workflowId ? { workflowId: spec.workflowId } : {},
13359
13449
  runId,
13360
13450
  runtime,
@@ -13433,13 +13523,15 @@ function titleFor(kind, service, path2, actual, expected, records, fault, seeded
13433
13523
  function findingsFromReceipt(r, world) {
13434
13524
  const adapterOf = (service) => world?.services.find((s) => s.name === service)?.adapter ?? "json-collection";
13435
13525
  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;
13526
+ const engineFault = r.engineFault;
13527
+ 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
13528
  const findings = [], seeded = JSON.stringify(r.initialState ?? {});
13438
13529
  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
13530
  for (const [index, c] of checks.entries()) {
13440
13531
  if (c.passed || !c.path || String(c.id ?? "").startsWith("generic:")) continue;
13441
13532
  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";
13533
+ 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);
13534
+ 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
13535
  const sequences = new Set(c.evidence?.eventSequences ?? []);
13444
13536
  const related = (e) => sequences.has(e.sequence) || e.service === c.service && e.path === c.path && ["write", "fault"].includes(e.operation);
13445
13537
  const writes = r.events.filter((e) => e.service === c.service && e.path === c.path && e.operation === "write");
@@ -13469,7 +13561,12 @@ function findingsFromReceipt(r, world) {
13469
13561
  });
13470
13562
  }
13471
13563
  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)));
13564
+ const words = (record5) => typeof record5 === "string" ? record5 : record5 && typeof record5 === "object" ? Object.values(record5).map(words).join(" ") : "";
13565
+ const notices = failedWrite ? r.events.filter((e) => e.operation === "write" && e.sequence > failedWrite.sequence && isNotify(e.service, e.path, adapterOf(e.service))) : [];
13566
+ const messages = notices.filter((e) => /\/(messages|emails|mail|sms)\b/.test(e.path));
13567
+ const idOf = (e) => e.record?.id;
13568
+ const text3 = (e) => (idOf(e) === void 0 ? [e] : notices.filter((n) => idOf(n) === idOf(e))).map((n) => words(n.record)).join(" ").slice(0, 4e3);
13569
+ const announce = failedWrite && (messages.length ? messages : notices).find((e) => polarityOf(text3(e)) !== "failure");
13473
13570
  if (failedWrite && announce && findings.length) {
13474
13571
  const what = `the ${serviceName2(failedWrite.service)} ${(failedWrite.path.split("/").pop() ?? "write").replace(/_/g, " ").replace(/s$/, "")}`;
13475
13572
  const existing = findings.find((f) => f.service === announce.service && f.path === announce.path && f.kind !== "missing-effect");
@@ -13837,7 +13934,7 @@ function storeIn(text3, schema) {
13837
13934
  return { kind: "memory" };
13838
13935
  }
13839
13936
  async function projectStore(root2, file) {
13840
- const { readdir: readdir12, readFile: read2 } = await import("fs/promises");
13937
+ const { readdir: readdir13, readFile: read2 } = await import("fs/promises");
13841
13938
  const { posix: posix8 } = await import("path");
13842
13939
  const found = [];
13843
13940
  let scanned = 0;
@@ -13845,7 +13942,7 @@ async function projectStore(root2, file) {
13845
13942
  if (depth > 7 || scanned > 6e3) return;
13846
13943
  let entries;
13847
13944
  try {
13848
- entries = await readdir12(join29(root2, dir), { withFileTypes: true });
13945
+ entries = await readdir13(join29(root2, dir), { withFileTypes: true });
13849
13946
  } catch {
13850
13947
  return;
13851
13948
  }
@@ -14294,6 +14391,7 @@ var quote4, NOTIFY2, IDEMPOTENT_ADAPTERS, SERVICE2, serviceName2, sha4, plural2,
14294
14391
  var init_repair_proof = __esm({
14295
14392
  "src/runtime/repair-proof.ts"() {
14296
14393
  "use strict";
14394
+ init_generic_calls();
14297
14395
  init_run_summary();
14298
14396
  init_repair_proof_page();
14299
14397
  quote4 = (s) => `'${s.replace(/[\\']/g, "\\$&")}'`;
@@ -14434,11 +14532,11 @@ function portableLocalReceipt(value3) {
14434
14532
  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
14533
  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
14534
  if (r.proof !== void 0 && !validProof(r.proof, r.runId)) throw new Error("Invalid or contradictory fix proof");
14437
- const git2 = validateGit(r.git);
14535
+ const git3 = validateGit(r.git);
14438
14536
  if (r.twinClock !== void 0 && !validTwinClockEvidence(r.twinClock)) throw new Error("Invalid twin clock evidence");
14439
14537
  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
14538
  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 } : {} });
14539
+ 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
14540
  if (Buffer.byteLength(JSON.stringify(result2)) > 2 * 1024 * 1024) throw new Error("CLI receipt exceeds 2 MiB");
14443
14541
  return result2;
14444
14542
  }
@@ -14516,15 +14614,15 @@ async function runSync(cwd, opts = {}) {
14516
14614
  const base = apiBase(process.env.AGENTTWIN_API_URL || saved?.base || "https://api.agenttwin.si");
14517
14615
  const inventory = JSON.parse(await readFile22(join31(cwd, ".agenttwin/inventory.json"), "utf8"));
14518
14616
  const payload = await loadDashboardDiscovery(cwd, inventory);
14519
- const git2 = payload.git;
14617
+ const git3 = payload.git;
14520
14618
  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
14619
  const result2 = await response.json();
14522
14620
  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 });
14621
+ if (git3) await writeFile18(join31(cwd, ".agenttwin/git.json"), JSON.stringify(git3) + "\n", { mode: 384 });
14524
14622
  const receipts = await syncReceipts(cwd, base, token, { includeFixDiffs });
14525
14623
  await recordAudit(cwd, "sync.uploaded", {
14526
14624
  endpoint: new URL(base).host,
14527
- discovery: { tools: payload.tools.length, workflows: payload.workflows.length, git: !!git2 },
14625
+ discovery: { tools: payload.tools.length, workflows: payload.workflows.length, git: !!git3 },
14528
14626
  receipts: typeof receipts === "object" && receipts && "uploaded" in receipts ? receipts.uploaded : void 0,
14529
14627
  fixDiffsIncluded: includeFixDiffs
14530
14628
  });
@@ -15491,9 +15589,9 @@ function isPackageLike(source) {
15491
15589
  }
15492
15590
  function importMatcher(source) {
15493
15591
  if (!isPackageLike(source)) return safeRegex(source);
15494
- const esc2 = source.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
15592
+ const esc3 = source.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
15495
15593
  return safeRegex(
15496
- `(?:from\\s*['"]${esc2}['"]|require\\s*\\(\\s*['"]${esc2}['"]|import\\s+${esc2}\\b|import\\s*\\{[^}]*\\}\\s*from\\s*['"]${esc2}['"])`
15594
+ `(?:from\\s*['"]${esc3}['"]|require\\s*\\(\\s*['"]${esc3}['"]|import\\s+${esc3}\\b|import\\s*\\{[^}]*\\}\\s*from\\s*['"]${esc3}['"])`
15497
15595
  );
15498
15596
  }
15499
15597
  function escapeRegExp(value3) {
@@ -17717,9 +17815,9 @@ function packagesFor(providerId) {
17717
17815
  return [...set2];
17718
17816
  }
17719
17817
  function importPattern(pkg, prefix) {
17720
- const esc2 = pkg.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
17818
+ const esc3 = pkg.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
17721
17819
  const tail2 = prefix ? `[^'"]*` : "";
17722
- return new RegExp(`from\\s*['"]${esc2}${tail2}['"]`);
17820
+ return new RegExp(`from\\s*['"]${esc3}${tail2}['"]`);
17723
17821
  }
17724
17822
  function bindingsFor(text3, packageIndex) {
17725
17823
  const bindings = factoryProviderBindings(text3);
@@ -19482,11 +19580,11 @@ async function runExport(opts) {
19482
19580
  const bundle = { schema: "export/v1", inventory, plan: plan ?? null };
19483
19581
  if (opts.out) {
19484
19582
  const { mkdir: mkdir35, writeFile: writeFile49 } = await import("fs/promises");
19485
- const { join: join81 } = await import("path");
19583
+ const { join: join82 } = await import("path");
19486
19584
  await mkdir35(opts.out, { recursive: true });
19487
- await writeFile49(join81(opts.out, "inventory.json"), `${JSON.stringify(inventory, null, 2)}
19585
+ await writeFile49(join82(opts.out, "inventory.json"), `${JSON.stringify(inventory, null, 2)}
19488
19586
  `, "utf8");
19489
- if (plan) await writeFile49(join81(opts.out, "plan.json"), `${JSON.stringify(plan, null, 2)}
19587
+ if (plan) await writeFile49(join82(opts.out, "plan.json"), `${JSON.stringify(plan, null, 2)}
19490
19588
  `, "utf8");
19491
19589
  return { schema: "export/v1", out: opts.out, wrote: ["inventory.json", ...plan ? ["plan.json"] : []] };
19492
19590
  }
@@ -19750,8 +19848,8 @@ async function runPrepare(cwd, opts) {
19750
19848
  await mkdir12(dirname6(directory2), { recursive: true });
19751
19849
  await mkdir12(directory2, { mode: 448 });
19752
19850
  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 });
19851
+ const { cp: cp2, readdir: readdir13 } = await import("fs/promises");
19852
+ for (const entry of await readdir13(stage)) await cp2(join36(stage, entry), join36(directory2, entry), { recursive: true, force: false, errorOnExist: true });
19755
19853
  } catch (error) {
19756
19854
  await rm15(directory2, { recursive: true, force: true });
19757
19855
  throw error;
@@ -20523,19 +20621,19 @@ async function runProtectedCheck(cwd, opts) {
20523
20621
  try {
20524
20622
  if (!opts.baseline) throw new Error("An explicit trusted baseline commit SHA is required; candidate-owned checks cannot approve a patch");
20525
20623
  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();
20624
+ const git3 = async (...args) => (await exec8("git", ["-C", cwd, ...args], { maxBuffer: 20 * 1024 * 1024, timeout: 15e3, encoding: "buffer" })).stdout;
20625
+ result2.candidateRevision = (await git3("rev-parse", `${opts.revision}^{commit}`)).toString().trim();
20626
+ result2.baselineRevision = (await git3("rev-parse", `${opts.baseline ?? "HEAD"}^{commit}`)).toString().trim();
20529
20627
  const path2 = opts.regression;
20530
20628
  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()));
20629
+ const regression = parseRegression(JSON.parse((await git3("show", `${result2.baselineRevision}:${path2}`)).toString()));
20532
20630
  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
20631
  result2.specDigest = regression.specDigest;
20534
20632
  let totalBytes = 0;
20535
20633
  const stageGitFile = async (file, revision, directory2) => {
20536
- const entry = (await git2("ls-tree", revision, "--", file)).toString();
20634
+ const entry = (await git3("ls-tree", revision, "--", file)).toString();
20537
20635
  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}`);
20636
+ const bytes2 = await git3("show", `${revision}:${file}`);
20539
20637
  totalBytes += bytes2.length;
20540
20638
  if (totalBytes > 100 * 1024 * 1024) throw new Error("Candidate files exceed 100 MiB");
20541
20639
  if (revision === result2.candidateRevision) result2.sourceDigests[file] = hash4(bytes2);
@@ -20549,12 +20647,12 @@ async function runProtectedCheck(cwd, opts) {
20549
20647
  await mkdir18(source);
20550
20648
  await mkdir18(compiled);
20551
20649
  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)))
20650
+ if (!(await git3("ls-tree", result2.baselineRevision, "--", file)).equals(await git3("ls-tree", result2.candidateRevision, "--", file)))
20553
20651
  throw Error("Candidate dependency lock changed: " + file + "; review a new regression before approval");
20554
20652
  }
20555
20653
  for (const file of regression.callable.sources) await stageGitFile(file, result2.candidateRevision, source);
20556
20654
  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)
20655
+ if (!file.split("/").includes("node_modules") && hash4(await git3("show", `${result2.candidateRevision}:${file}`)) !== expected)
20558
20656
  throw Error("Candidate resolution metadata changed: " + file + "; review a new regression before approval");
20559
20657
  }
20560
20658
  await stageTrustedBuildFiles(cwd, source, regression.callable.trustedFiles);
@@ -20805,8 +20903,8 @@ async function receivePreparation(cwd, id2) {
20805
20903
  const inventory = await project(cwd), remote = await connection();
20806
20904
  if (!uuid4.test(id2)) throw Error("Invalid delivery ID");
20807
20905
  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");
20906
+ const workflow = inventory.workflows.find((w) => w.id === delivery.workflowId), git3 = await captureGit(cwd);
20907
+ 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
20908
  if (!["queued", "claimed"].includes(delivery.status)) throw Error("Preparation is not waiting for local receipt");
20811
20909
  const path2 = await storage2(cwd, id2);
20812
20910
  let binding;
@@ -20823,7 +20921,7 @@ async function receivePreparation(cwd, id2) {
20823
20921
  }
20824
20922
  }
20825
20923
  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 });
20924
+ 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
20925
  if (binding.localRequestId) return { ...await preparationStatus(cwd, binding.localRequestId), deliveryId: id2, notice: "Existing local context; no application executed" };
20828
20926
  const lock = path2 + ".lock";
20829
20927
  try {
@@ -20847,7 +20945,7 @@ async function receivePreparation(cwd, id2) {
20847
20945
  }
20848
20946
  binding.localRequestId = context2.requestId;
20849
20947
  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." };
20948
+ 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
20949
  } finally {
20852
20950
  const { rm: rm27 } = await import("fs/promises");
20853
20951
  await rm27(lock, { recursive: true, force: true });
@@ -21215,6 +21313,7 @@ function prismaSchemaSql(source) {
21215
21313
  if (!["Int", "BigInt"].includes(type) || list4) fail2("autoincrement type");
21216
21314
  c.type = type === "Int" ? "serial" : "bigserial";
21217
21315
  } else if (v === "now()" && type === "DateTime") c.default = "CURRENT_TIMESTAMP";
21316
+ 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
21317
  else if (a.args.length === 1) {
21219
21318
  const x = a.args[0];
21220
21319
  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 +21398,29 @@ function drizzleSchemaSql(source) {
21299
21398
  if (n?.type === "TSAsExpression" || n?.type === "TSSatisfiesExpression") return calls(n.expression);
21300
21399
  if (n?.type !== "CallExpression") return fail2("dynamic Drizzle column");
21301
21400
  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 }];
21401
+ 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
21402
  if (n.callee.type === "MemberExpression" && !n.callee.computed) return [...calls(n.callee.object), { name: n.callee.property.name, args: n.arguments }];
21303
21403
  return fail2("dynamic Drizzle builder");
21304
21404
  };
21305
21405
  const declarations = [];
21406
+ const namespaces = /* @__PURE__ */ new Set(), ormHelpers = /* @__PURE__ */ new Set();
21407
+ 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
21408
  for (const raw of ast.program.body) {
21307
21409
  const n = raw.type === "ExportNamedDeclaration" ? raw.declaration : raw;
21308
21410
  if (!n) fail2("Drizzle re-exports");
21309
21411
  if (n.type === "ImportDeclaration") {
21310
21412
  if (n.importKind === "type") continue;
21413
+ if (n.source.value === "drizzle-orm") {
21414
+ for (const s of n.specifiers) if (s.type === "ImportSpecifier") ormHelpers.add(s.local.name);
21415
+ continue;
21416
+ }
21311
21417
  if (n.source.value !== "drizzle-orm/pg-core") fail2(`Drizzle import ${n.source.value}`);
21312
21418
  for (const s of n.specifiers) {
21313
- if (s.type !== "ImportSpecifier") fail2("Drizzle namespace/default import");
21419
+ if (s.type === "ImportNamespaceSpecifier") {
21420
+ namespaces.add(s.local.name);
21421
+ continue;
21422
+ }
21423
+ if (s.type !== "ImportSpecifier") fail2("Drizzle default import");
21314
21424
  imports.set(s.local.name, s.imported.name ?? s.imported.value);
21315
21425
  }
21316
21426
  continue;
@@ -21322,7 +21432,7 @@ function drizzleSchemaSql(source) {
21322
21432
  for (const d2 of declarations) {
21323
21433
  if (d2.id.type !== "Identifier") fail2("Drizzle destructuring");
21324
21434
  const n = d2.init;
21325
- if (n?.type === "CallExpression" && n.callee.type === "Identifier" && imports.get(n.callee.name) === "pgEnum") {
21435
+ if (n?.type === "CallExpression" && builder(n.callee) === "pgEnum") {
21326
21436
  if (n.arguments.length !== 2) fail2("pgEnum arguments");
21327
21437
  const name = value3(n.arguments[0]), vals = value3(n.arguments[1]);
21328
21438
  if (typeof name !== "string" || !Array.isArray(vals) || !vals.length || vals.some((v) => typeof v !== "string")) fail2("pgEnum literals");
@@ -21330,10 +21440,24 @@ function drizzleSchemaSql(source) {
21330
21440
  enums.push(`CREATE TYPE ${q2(name)} AS ENUM (${vals.map(lit).join(", ")});`);
21331
21441
  }
21332
21442
  }
21443
+ const tableExtras = (t, fn) => {
21444
+ if (fn?.type !== "ArrowFunctionExpression" || fn.params.length !== 1 || fn.params[0].type !== "Identifier") fail2("table-level callback");
21445
+ 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");
21446
+ for (const e of body) {
21447
+ const chain2 = calls(e), kind = chain2[0]?.name, on = chain2.find((c) => c.name === "on");
21448
+ if (kind === "index") continue;
21449
+ if (kind !== "uniqueIndex" && kind !== "unique" || !on || chain2.some((c) => !["uniqueIndex", "unique", "on", "using", "nullsNotDistinct"].includes(c.name))) fail2(`table-level ${kind ?? "constraint"}`);
21450
+ 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);
21451
+ if (!cols.length || cols.some((c) => !c)) fail2("table-level unique columns");
21452
+ t.constraints.push(`UNIQUE (${cols.map((c) => q2(c)).join(", ")})`);
21453
+ }
21454
+ };
21333
21455
  for (const d2 of declarations) {
21334
21456
  if (enumNames.has(d2.id.name)) continue;
21335
21457
  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");
21458
+ if (n?.type === "CallExpression" && n.callee.type === "Identifier" && ormHelpers.has(n.callee.name)) continue;
21459
+ if (n?.type === "ObjectExpression" && n.properties.every((p) => p.type === "ObjectProperty" && p.value?.type === "Identifier")) continue;
21460
+ if (n?.type !== "CallExpression" || builder(n.callee) !== "pgTable" || n.arguments.length < 2 || n.arguments.length > 3) fail2(`pgTable expression (${d2.id.name})`);
21337
21461
  const name = value3(n.arguments[0]);
21338
21462
  if (typeof name !== "string") fail2("dynamic table name");
21339
21463
  const t = { name, columns: /* @__PURE__ */ new Map(), constraints: [] };
@@ -21389,6 +21513,7 @@ function drizzleSchemaSql(source) {
21389
21513
  }
21390
21514
  t.columns.set(field2, c);
21391
21515
  }
21516
+ if (n.arguments[2]) tableExtras(t, n.arguments[2]);
21392
21517
  }
21393
21518
  const ddl = refs2.map((r) => {
21394
21519
  const from = tables.get(r.from), to = tables.get(r.target), target = to?.columns.get(r.field);
@@ -21425,9 +21550,9 @@ async function discoverAppPostgresSchema(root2, appDir) {
21425
21550
  async function discoverPostgresSchema(root2) {
21426
21551
  const exists3 = async (p) => {
21427
21552
  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();
21553
+ const stat14 = await lstat7(join47(root2, p));
21554
+ if (stat14.isSymbolicLink()) throw new Error(`Postgres schema discovery refuses symlink: ${p}`);
21555
+ return stat14.isFile();
21431
21556
  } catch (e) {
21432
21557
  if (e.code === "ENOENT") return false;
21433
21558
  throw e;
@@ -21530,8 +21655,8 @@ async function loadPostgresSchema(root2, files) {
21530
21655
  const path2 = await realpath16(resolve20(base, file));
21531
21656
  const rel = relative14(base, path2);
21532
21657
  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.");
21658
+ const stat14 = await lstat7(path2);
21659
+ 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
21660
  const sql2 = await readFile37(path2, "utf8");
21536
21661
  size += Buffer.byteLength(sql2);
21537
21662
  if (size > MAX_SCHEMA_BYTES) throw new Error("Postgres schema exceeds the 16 MiB test setup limit.");
@@ -23882,6 +24007,15 @@ async function sourceFiles2(root2) {
23882
24007
  await visit(root2);
23883
24008
  return files;
23884
24009
  }
24010
+ function nextBasePath(root2, appDir) {
24011
+ if (appDir === void 0) return "";
24012
+ for (const ext of ["js", "mjs", "ts", "cjs", "mts"]) try {
24013
+ const m = /\bbasePath\s*:\s*['"`](\/[^'"`$]*)['"`]/.exec(readFileSync9(join55(root2, appDir, `next.config.${ext}`), "utf8"));
24014
+ if (m) return m[1].replace(/\/$/, "");
24015
+ } catch {
24016
+ }
24017
+ return "";
24018
+ }
23885
24019
  function nextAppDir(root2, file) {
23886
24020
  for (let dir = posix4.dirname(file); ; dir = posix4.dirname(dir)) {
23887
24021
  const key3 = root2 + "\0" + dir;
@@ -24036,7 +24170,7 @@ async function analyzeWorkflows(root2, opts = {}) {
24036
24170
  }
24037
24171
  };
24038
24172
  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];
24173
+ 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
24174
  };
24041
24175
  const startScript = (entry) => {
24042
24176
  for (let dir = posix4.dirname(entry); ; dir = posix4.dirname(dir)) {
@@ -24047,12 +24181,14 @@ async function analyzeWorkflows(root2, opts = {}) {
24047
24181
  }
24048
24182
  if (pkg) {
24049
24183
  const stem = posix4.basename(entry).replace(/\.[cm]?[jt]sx?$/, "");
24050
- for (const name of ["dev", "start:dev", "dev:server", "server", "serve", "start"]) {
24184
+ for (const name of ["dev", "start:dev", "dev:server", "devserver", "dev:api", "dev:backend", "server", "serve", "start:server", "api", "backend", "start"]) {
24051
24185
  const command = pkg.scripts?.[name];
24052
24186
  if (!command) continue;
24053
24187
  if (/concurrently|npm-run-all|run-p|turbo|docker|\bvite\b(?!-node)|\bnext\b|\bbun\b|\bdeno\b|(^|[^&])&([^&]|$)/.test(command)) continue;
24054
24188
  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;
24189
+ if (/\bts-node-esm\b|\bts-node\b[^&|;]*--esm\b/.test(command)) continue;
24190
+ 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));
24191
+ if (!(command.includes(stem) || /\bnest\s+start\b/.test(command) || runs.some((f) => f === entry || reaches(f, entry)))) continue;
24056
24192
  const dist = /\bdist\/|\bbuild\//.exec(command);
24057
24193
  if (dist && !/\bnest\b/.test(command) && !existsSync8(join55(root2, dir, dist[0]))) continue;
24058
24194
  return { name, command, dir: dir === "." ? "" : dir };
@@ -24094,6 +24230,10 @@ async function analyzeWorkflows(root2, opts = {}) {
24094
24230
  if (node.type === "CallExpression" && node.callee?.type === "MemberExpression" && ["map", "flatMap", "forEach", "reduce"].includes(node.callee.property?.name)) uncertainSql.push(node);
24095
24231
  });
24096
24232
  const before = (a, b) => a.line < b.line || a.line === b.line && a.column <= b.column;
24233
+ const loops = [];
24234
+ walk3(fn.body, (node) => {
24235
+ 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);
24236
+ });
24097
24237
  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
24238
  const boltNames = /* @__PURE__ */ new Map();
24099
24239
  if (bolt && fn.params?.[0]?.type === "ObjectPattern") {
@@ -24149,7 +24289,8 @@ async function analyzeWorkflows(root2, opts = {}) {
24149
24289
  if (hit) {
24150
24290
  const parsed = new URL(String(url).replaceAll("{id}", "x"));
24151
24291
  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 });
24292
+ const args = body && typeof body === "object" && !Array.isArray(body) ? { ...body } : void 0;
24293
+ 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
24294
  }
24154
24295
  return;
24155
24296
  }
@@ -24264,6 +24405,7 @@ async function analyzeWorkflows(root2, opts = {}) {
24264
24405
  });
24265
24406
  for (const call2 of entry.calls.slice(firstCall)) {
24266
24407
  const at = { line: call2.line, column: (call2.column ?? 1) - 1 };
24408
+ if (loops.some((node) => node.loc && before(node.loc.start, at) && before(at, node.loc.end))) call2.repeats = true;
24267
24409
  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
24410
  }
24269
24411
  return entry;
@@ -24344,7 +24486,7 @@ async function analyzeWorkflows(root2, opts = {}) {
24344
24486
  }
24345
24487
  return seg;
24346
24488
  }).join("/");
24347
- web = { method: exportName, path: path2.replace(/\/+/g, "/") || "/", params, ...appDir !== void 0 ? { appDir } : {} };
24489
+ web = { method: exportName, path: (nextBasePath(root2, appDir) + path2).replace(/\/+/g, "/") || "/", params, ...appDir !== void 0 ? { appDir } : {} };
24348
24490
  const requestName = fn.params?.[0]?.type === "Identifier" ? fn.params[0].name : "request", fields = /* @__PURE__ */ new Set(), aliases2 = /* @__PURE__ */ new Set();
24349
24491
  const unwrap2 = (n) => n && (n.type === "TSAsExpression" || n.type === "TSNonNullExpression" || n.type === "TSSatisfiesExpression" || n.type === "ParenthesizedExpression") ? unwrap2(n.expression) : n;
24350
24492
  const isJson = (raw) => {
@@ -24376,10 +24518,20 @@ async function analyzeWorkflows(root2, opts = {}) {
24376
24518
  }).join("/");
24377
24519
  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
24520
  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 };
24521
+ web = { method, path: (nextBasePath(root2, appDir) + path2).replace(/\/+/g, "/"), params, appDir };
24380
24522
  input = { name: "req.body", fields: [] };
24381
24523
  }
24382
24524
  }
24525
+ if (web?.appDir !== void 0) {
24526
+ const base = web.appDir ? web.appDir + "/" : "";
24527
+ 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"));
24528
+ if (mw) {
24529
+ const extra = closure(mw, byFile.get(mw).facts.exports.get("middleware"));
24530
+ 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 });
24531
+ for (const e of extra.env) if (!env.includes(e)) env.push(e);
24532
+ for (const t of extra.files) if (!touched.includes(t)) touched.push(t);
24533
+ }
24534
+ }
24383
24535
  const tools = touched.flatMap((t) => byFile.get(t).facts.tools);
24384
24536
  const providers = new Set(calls.map((c) => c.provider));
24385
24537
  const inNext = nextAppDir(root2, file) !== void 0;
@@ -24435,7 +24587,7 @@ async function analyzeWorkflows(root2, opts = {}) {
24435
24587
  channelHints: channels,
24436
24588
  score: score + 2,
24437
24589
  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 } : {} }
24590
+ 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
24591
  });
24440
24592
  }
24441
24593
  if (bolt) for (const [file, { facts: f }] of byFile) for (const listener of f.boltListeners) {
@@ -24520,7 +24672,7 @@ var init_analyze = __esm({
24520
24672
  init_tsconfig_paths();
24521
24673
  WHOLE_INPUT = "$input";
24522
24674
  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"]];
24675
+ 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
24676
  KNOWN_PROVIDERS = /* @__PURE__ */ new Set([...FETCH_HOSTS.map(([, provider]) => provider), ...Object.values(PROVIDER_MODULES)]);
24525
24677
  escapeHost = (h2) => h2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
24526
24678
  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 +24704,129 @@ var init_analyze = __esm({
24552
24704
  }
24553
24705
  });
24554
24706
 
24707
+ // src/runtime/workers-env.ts
24708
+ var WORKERS_ENV;
24709
+ var init_workers_env = __esm({
24710
+ "src/runtime/workers-env.ts"() {
24711
+ "use strict";
24712
+ WORKERS_ENV = String.raw`
24713
+ import { register } from 'node:module';
24714
+ import { readFileSync } from 'node:fs';
24715
+
24716
+ // cloudflare:workers and friends, as ES modules the Worker can import.
24717
+ const SOURCES = {
24718
+ workers: "export class DurableObject { constructor(ctx, env) { this.ctx = ctx; this.env = env; } }\n" +
24719
+ "export class WorkerEntrypoint { constructor(ctx, env) { this.ctx = ctx; this.env = env; } }\n" +
24720
+ "export class WorkflowEntrypoint { constructor(ctx, env) { this.ctx = ctx; this.env = env; } }\n" +
24721
+ "export class RpcTarget {}\n" +
24722
+ "export const env = new Proxy({}, { get: (_, k) => globalThis.__agenttwinWorkersEnv?.[k], has: (_, k) => k in (globalThis.__agenttwinWorkersEnv ?? {}) });\n" +
24723
+ "export default { DurableObject, WorkerEntrypoint, WorkflowEntrypoint, RpcTarget, env };\n",
24724
+ sockets: "export function connect() { throw new Error('AgentTwin: cloudflare:sockets is not modelled'); }\nexport default { connect };\n",
24725
+ };
24726
+ const hooks = 'const S = ' + JSON.stringify(SOURCES) + ';\n' +
24727
+ "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" +
24728
+ "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";
24729
+ export function install() { register('data:text/javascript,' + encodeURIComponent(hooks)); }
24730
+
24731
+ /** wrangler.toml, the subset Workers projects use: tables, arrays of tables, strings, numbers, booleans, inline tables and arrays. */
24732
+ export function parseToml(text) {
24733
+ const root = {}; let cur = root;
24734
+ const value = (raw) => {
24735
+ raw = raw.trim();
24736
+ if (raw.startsWith('"') || raw.startsWith("'")) return raw.slice(1, raw.lastIndexOf(raw[0]));
24737
+ if (raw === 'true' || raw === 'false') return raw === 'true';
24738
+ if (/^-?\d+(\.\d+)?$/.test(raw)) return Number(raw);
24739
+ if (raw.startsWith('[')) return split(raw.slice(1, raw.lastIndexOf(']'))).map(value);
24740
+ 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; }
24741
+ return raw;
24742
+ };
24743
+ 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()); }
24744
+ 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; };
24745
+ for (let line of text.split(/\r?\n/)) {
24746
+ line = line.replace(/^\s+/, ''); if (!line || line.startsWith('#')) continue;
24747
+ const arr = /^\[\[([^\]]+)\]\]/.exec(line), tbl = !arr && /^\[([^\]]+)\]/.exec(line);
24748
+ if (arr || tbl) { cur = walk((arr ?? tbl)[1].split('.').map(s => s.trim().replace(/^["']|["']$/g, '')), !!arr); continue; }
24749
+ const i = line.indexOf('='); if (i < 0) continue;
24750
+ let raw = line.slice(i + 1); const hash = raw.search(/\s#(?=(?:[^"']*["'][^"']*["'])*[^"']*$)/); if (hash >= 0) raw = raw.slice(0, hash);
24751
+ cur[line.slice(0, i).trim().replace(/^["']|["']$/g, '')] = value(raw);
24752
+ }
24753
+ return root;
24754
+ }
24755
+ const stripJsonc = (t) => t.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (m, s) => s ?? '').replace(/,(\s*[}\]])/g, '$1');
24756
+
24757
+ function readConfig(file) {
24758
+ const text = readFileSync(file, 'utf8');
24759
+ const cfg = file.endsWith('.toml') ? parseToml(text) : JSON.parse(stripJsonc(text));
24760
+ // Bindings live at the top level, or only under an environment (elrax keeps them in env.dev): the local one.
24761
+ const named = cfg.env && typeof cfg.env === 'object' ? (cfg.env.dev ?? cfg.env.development ?? cfg.env.local ?? Object.values(cfg.env)[0]) : undefined;
24762
+ const pick = (k) => cfg[k] ?? named?.[k];
24763
+ return { vars: { ...(named?.vars ?? {}), ...(cfg.vars ?? {}) }, kv: pick('kv_namespaces') ?? [], r2: pick('r2_buckets') ?? [], durable: pick('durable_objects')?.bindings ?? [],
24764
+ 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 })) : []; }) };
24765
+ }
24766
+
24767
+ function kvNamespace() {
24768
+ const m = new Map();
24769
+ 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; },
24770
+ async put(k, v) { m.set(k, typeof v === 'string' ? v : JSON.stringify(v)); }, async delete(k) { m.delete(k); },
24771
+ 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: '' }; },
24772
+ async getWithMetadata(k, o) { return { value: await this.get(k, o), metadata: null }; } };
24773
+ }
24774
+ function r2Bucket() {
24775
+ const m = new Map();
24776
+ 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 ?? {},
24777
+ 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)); } });
24778
+ 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());
24779
+ 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; },
24780
+ 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); },
24781
+ 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: [] }; } };
24782
+ }
24783
+ async function sqlStorage() {
24784
+ let db; try { const { DatabaseSync } = await import('node:sqlite'); db = new DatabaseSync(':memory:'); } catch { return undefined; }
24785
+ 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]; },
24786
+ 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]() });
24787
+ return { exec(query, ...bindings) {
24788
+ const parts = query.split(';').map(s => s.trim()).filter(Boolean);
24789
+ if (parts.length > 1 && !bindings.length) { db.exec(query); return cursor([], 0); }
24790
+ const stmt = db.prepare(query), reads = /^\s*(select|with|pragma)\b|\breturning\b/i.test(query);
24791
+ const args = bindings.map(v => typeof v === 'boolean' ? Number(v) : v);
24792
+ if (reads) return cursor(stmt.all(...args).map(r => ({ ...r })), 0);
24793
+ const r = stmt.run(...args); return cursor([], Number(r.changes ?? 0));
24794
+ }, get databaseSize() { return 0; } };
24795
+ }
24796
+ async function durableNamespace(Class, env, name) {
24797
+ const instances = new Map();
24798
+ const id = (key) => ({ name: key, toString: () => key, equals: (o) => String(o) === key });
24799
+ const instance = async (key) => {
24800
+ if (instances.has(key)) return instances.get(key);
24801
+ const kv = new Map(), sql = await sqlStorage();
24802
+ 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); },
24803
+ 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()); },
24804
+ async deleteAll() { kv.clear(); }, async transaction(fn) { return fn(storage); }, transactionSync(fn) { return fn(); }, async getAlarm() { return null; }, async setAlarm() {}, async deleteAlarm() {} };
24805
+ const state = { id: id(key), storage, async blockConcurrencyWhile(fn) { return fn(); }, waitUntil() {}, acceptWebSocket() { throw new Error('AgentTwin: Durable Object WebSockets are not modelled'); }, getWebSockets: () => [] };
24806
+ const obj = new Class(state, env); instances.set(key, obj); return obj;
24807
+ };
24808
+ return { idFromName: (n) => id(String(n)), idFromString: (s) => id(String(s)), newUniqueId: () => id('do-' + (instances.size + 1) + '-' + Math.random().toString(36).slice(2, 8)),
24809
+ 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); } }); },
24810
+ getByName(n) { return this.get(this.idFromName(n)); } };
24811
+ }
24812
+ const unsupported = (kind, name) => new Proxy({}, { get: (_, p) => p === 'then' ? undefined : () => { throw new Error('AgentTwin: the Workers binding ' + name + ' (' + kind + ') is not modelled'); } });
24813
+
24814
+ /** The env a Worker's fetch(request, env, ctx) receives: process settings, wrangler vars, then bindings. */
24815
+ export async function environment(file, module) {
24816
+ const cfg = readConfig(file), env = {};
24817
+ for (const [k, v] of Object.entries(process.env)) if (typeof v === 'string') env[k] = v;
24818
+ 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);
24819
+ for (const b of cfg.kv) env[b.binding] = kvNamespace();
24820
+ for (const b of cfg.r2) env[b.binding] = r2Bucket();
24821
+ for (const b of cfg.other) env[b.name] = unsupported(b.kind, b.name);
24822
+ 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); }
24823
+ globalThis.__agenttwinWorkersEnv = env;
24824
+ return env;
24825
+ }
24826
+ `;
24827
+ }
24828
+ });
24829
+
24555
24830
  // src/runtime/engines/mysql-sql.ts
24556
24831
  function tokenize(sql) {
24557
24832
  const tokens = [];
@@ -25496,6 +25771,7 @@ function accountPreset(pack, calls, context2 = {}) {
25496
25771
  }
25497
25772
  function sdkCallPath(call2, collections, pack) {
25498
25773
  if (call2.path || !call2.write) return;
25774
+ if (/^(?:create|add|update|delete|del|remove)[A-Z]/.test(call2.operation.split(".").pop() ?? "")) return;
25499
25775
  const named = pack ? packMethodCollection(pack, call2.operation) : void 0;
25500
25776
  if (named) return collections.includes(named) ? named : void 0;
25501
25777
  const parts = call2.operation.split(".").filter(Boolean);
@@ -25579,12 +25855,12 @@ import { spawnSync as spawnSync2 } from "child_process";
25579
25855
  import { dirname as dirname16, join as join57, posix as posix5, relative as relative18 } from "path";
25580
25856
  import { pathToFileURL as pathToFileURL2 } from "url";
25581
25857
  function fieldValue(name, message, channel) {
25582
- const n = name.toLowerCase();
25858
+ const n = name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
25583
25859
  if (/^subscription_?item(_?id)?$/.test(n)) return "si_at_1001";
25584
25860
  if (/payment_?method_?types?$/.test(n)) return /types$/.test(n) ? ["card"] : "card";
25585
25861
  if (/payment_?method(_?id)?$/.test(n)) return "pm_card_visa";
25586
25862
  if (/options$|metadata$|config$|settings$/.test(n)) return null;
25587
- if (/^(is|has|should|can)_?[a-z]|enabled$|confirm$/.test(n)) return true;
25863
+ if (/^(is|has|should|can)_[a-z]|enabled$|confirm$/.test(n)) return true;
25588
25864
  if (/quantity|count$|^qty$|seats/.test(n)) return 1;
25589
25865
  if (/url$|uri$|link$/.test(n)) return "https://example.test/return";
25590
25866
  if (/country/.test(n)) return "US";
@@ -25664,8 +25940,13 @@ function discoverServices(candidate, inventorySteps) {
25664
25940
  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
25941
  };
25666
25942
  const out = /* @__PURE__ */ new Map();
25943
+ const hostKey = (step) => {
25944
+ 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);
25945
+ const hit = host ? fetchHosts().find(([re]) => re.test(`https://${host}/`)) : void 0;
25946
+ return hit ? String(hit[1]).replace(/^pack:/, "") : void 0;
25947
+ };
25667
25948
  for (const step of inventorySteps) {
25668
- const key3 = keyOf(step.title);
25949
+ const key3 = hostKey(step) ?? keyOf(step.title);
25669
25950
  const s = out.get(key3) ?? { key: key3, title: step.title, kind: step.kind, operations: [], calls: [], hosts: [] };
25670
25951
  for (const op2 of step.operations) {
25671
25952
  if (!s.operations.includes(op2)) s.operations.push(op2);
@@ -25694,7 +25975,7 @@ async function generateScenario(candidate, ask, discovered = discoverServices(ca
25694
25975
  })));
25695
25976
  const twins2 = discovered.map(resolveTwin);
25696
25977
  const plan = (key3) => twins2.find((t, i) => discovered[i].key === key3 && t.service);
25697
- const calls = (p) => candidate.calls.filter((c) => c.provider === p);
25978
+ const calls = (p) => candidate.calls.filter((c) => c.provider === p || c.provider === `pack:${p}`);
25698
25979
  const refunds = calls("stripe").some((c) => /^refunds\.create$/.test(c.operation));
25699
25980
  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
25981
  const slackCall = calls("slack").find((c) => /postMessage/.test(c.operation));
@@ -25849,6 +26130,7 @@ async function generateScenario(candidate, ask, discovered = discoverServices(ca
25849
26130
  const target = service.collections.find((c) => c.path === path2);
25850
26131
  if (!target) continue;
25851
26132
  write3(service.name, "stripe", path2, call2.operation, call2);
26133
+ if (/\.(create|update|delete)[A-Z]/.test(call2.operation)) continue;
25852
26134
  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
26135
  }
25854
26136
  } else if (adapter === "slack") {
@@ -25862,12 +26144,13 @@ async function generateScenario(candidate, ask, discovered = discoverServices(ca
25862
26144
  const repos = collection(service, "/repos"), seen = /* @__PURE__ */ new Set();
25863
26145
  const GITHUB_PATHS = { "issues.create": "/issues", "pulls.create": "/pulls", "issues.createComment": "/comments", "checks.create": "/check-runs" };
25864
26146
  for (const call2 of calls("github")) {
25865
- const owner = String(call2.args?.owner ?? "acme"), repo = String(call2.args?.repo ?? "app"), full = `${owner}/${repo}`;
26147
+ const inUrl = /^\/repos\/([^/{}]+)\/([^/{}]+)(?:\/(issues|pulls|check-runs)(?:\/\{id\}\/(comments))?)?/.exec(call2.path ?? "");
26148
+ const owner = String(call2.args?.owner ?? inUrl?.[1] ?? "acme"), repo = String(call2.args?.repo ?? inUrl?.[2] ?? "app"), full = `${owner}/${repo}`;
25866
26149
  if (!seen.has(full)) {
25867
26150
  seen.add(full);
25868
26151
  repos.seed.push({ id: 100 + seen.size, name: repo, full_name: full, owner: { login: owner }, private: false, default_branch: "main" });
25869
26152
  }
25870
- const path2 = GITHUB_PATHS[call2.operation.replace(/^rest\./, "")];
26153
+ 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
26154
  if (call2.write && path2 && service.collections.some((c) => c.path === path2)) {
25872
26155
  write3(service.name, "github", path2, call2.operation, call2);
25873
26156
  assertions.push({ service: service.name, path: path2, count: collection(service, path2).seed.length + 1 });
@@ -25908,6 +26191,16 @@ async function generateScenario(candidate, ask, discovered = discoverServices(ca
25908
26191
  }
25909
26192
  }
25910
26193
  if (service.collections.some((c) => c.seed.length)) assumptions.push(`HubSpot twin seeded with deal ${SYNTHETIC.deal} (stage appointmentscheduled).`);
26194
+ } else if (adapter === "jira") {
26195
+ const projects = collection(service, "/rest/api/3/project"), issues = calls("jira").filter((c) => c.write && (c.path ?? "").replace(/\?.*$/, "") === "/rest/api/3/issue");
26196
+ 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)));
26197
+ if (!keys.size) keys.add("OPS");
26198
+ 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` });
26199
+ assumptions.push(`Jira twin holds project${keys.size === 1 ? "" : "s"} ${[...keys].join(", ")}.`);
26200
+ if (issues.length) {
26201
+ 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 });
26202
+ write3(service.name, "jira", "/rest/api/3/issue", "POST /rest/api/3/issue", ...issues);
26203
+ }
25911
26204
  } else if (adapter === "twilio") {
25912
26205
  const sends = calls("twilio").filter((c) => /messages\.create/.test(c.operation));
25913
26206
  if (sends.length) {
@@ -25985,7 +26278,10 @@ async function generateScenario(candidate, ask, discovered = discoverServices(ca
25985
26278
  for (const call2 of own.filter((c) => c.write && (c.method ?? "POST") === "POST" && (c.path || sdkCallPath(c, paths, pack)))) {
25986
26279
  const path2 = (call2.path ?? sdkCallPath(call2, paths, pack)).split("?")[0].replace(/\/\{[^}]+\}.*$/, "");
25987
26280
  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 });
26281
+ if (/\/\{[^}]+\}\/[^{]/.test(call2.path ?? "")) continue;
26282
+ const last = (path2.split("/").filter(Boolean).pop() ?? "").toLowerCase().replace(/-/g, "_"), types = packRecord(pack)?.resources ?? [];
26283
+ const stored = !types.length || types.some((t) => [t, t + "s", t + "es", t.replace(/y$/, "ies")].includes(last));
26284
+ 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
26285
  write3(service.name, adapter, path2, `POST ${path2}`, call2);
25990
26286
  }
25991
26287
  if (preset.doorRecords && candidate.bolt) {
@@ -26138,12 +26434,15 @@ async function prepareWorkflow(cwd, candidate, ask, log, discovered) {
26138
26434
  } else if (reason) scenario.assumptions.push(`No sign-in before the request: ${reason}. Workflows that need a user will find none.`);
26139
26435
  }
26140
26436
  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) {
26437
+ const servedPostgres = !!candidate.serve && usesPostgresDriver(cwd);
26438
+ if ((candidate.web?.appDir !== void 0 || restDatabase || servedPostgres) && !scenario.twins.some((t) => t.engine?.kind === "postgres") && scenario.postgresSchemaFiles === void 0) {
26439
+ const appDir = candidate.web?.appDir ?? (candidate.serve ? posix5.dirname(candidate.serve.entry ?? candidate.file) : "");
26440
+ const found = await discoverAppPostgresSchema(cwd, candidate.web?.appDir ?? "");
26441
+ const files = found?.length ? found : servedPostgres ? await discoverWorkspaceSchema(cwd, appDir) : void 0;
26442
+ if (files?.length || servedPostgres) {
26144
26443
  scenario.twins.push({ tier: "engine", provider: "PostgreSQL engine", name: "postgres", title: "PostgreSQL", note: "Embedded PostgreSQL (PGlite); project schema validation pending", engine: { kind: "postgres" } });
26145
26444
  scenario.postgresSchemaMode = "explicit";
26146
- scenario.postgresSchemaFiles = files;
26445
+ scenario.postgresSchemaFiles = files ?? [];
26147
26446
  }
26148
26447
  }
26149
26448
  if (scenario.twins.some((t) => t.engine?.kind === "postgres")) {
@@ -26166,11 +26465,22 @@ async function prepareWorkflow(cwd, candidate, ask, log, discovered) {
26166
26465
  }
26167
26466
  return [];
26168
26467
  };
26169
- const files = mode === "auto" ? await nearest() : scenario.postgresSchemaFiles ?? [];
26468
+ let files = mode === "auto" ? await nearest() : scenario.postgresSchemaFiles ?? [];
26170
26469
  scenario.postgresSchemaMode = mode;
26171
- await loadPostgresSchema(cwd, files);
26470
+ let unreadable = false;
26471
+ try {
26472
+ await loadPostgresSchema(cwd, files);
26473
+ } catch (error) {
26474
+ const why = error instanceof Error ? error.message : String(error);
26475
+ if (!/Unsupported ORM schema|Unsupported SQL|not supported/i.test(why)) throw error;
26476
+ log(` PostgreSQL: ${why.split(". ")[0]}; the app gets an empty database instead.`);
26477
+ 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.`;
26478
+ if (!scenario.assumptions.includes(note)) scenario.assumptions.push(note);
26479
+ files = [];
26480
+ unreadable = true;
26481
+ }
26172
26482
  scenario.postgresSchemaFiles = files;
26173
- if (!files.length) {
26483
+ if (!files.length && !unreadable) {
26174
26484
  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
26485
  const note = "No PostgreSQL schema or migrations were found: the database starts empty and its writes are not checked.";
26176
26486
  if (!scenario.assumptions.includes(note)) scenario.assumptions.push(note);
@@ -26229,6 +26539,12 @@ try{
26229
26539
  setTimeout(()=>process.exit(),1000).unref();
26230
26540
  `;
26231
26541
  const serveEntry = serve?.entry ?? candidate.file;
26542
+ const workersConfig = (() => {
26543
+ for (let dir = posix5.dirname(serveEntry); ; dir = posix5.dirname(dir)) {
26544
+ for (const f of ["wrangler.jsonc", "wrangler.json", "wrangler.toml"]) if (existsSync9(join57(cwd, dir, f))) return join57(cwd, dir, f);
26545
+ if (dir === "." || dir === "/" || dir === "") return void 0;
26546
+ }
26547
+ })();
26232
26548
  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
26549
  import {pathToFileURL} from 'node:url';
26234
26550
  import {spawn} from 'node:child_process';
@@ -26262,6 +26578,11 @@ try{
26262
26578
  while(words.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(words[0])){const [k,...v]=words.shift().split('=');env[k]=v.join('=');}
26263
26579
  const tool=words.shift(),local=bins.split(':').map(d=>d+'/'+tool).find(p=>existsSync(p));
26264
26580
  if(tool==='node'){file=process.execPath;args=words;}else if(local){file=local;args=words;}
26581
+ // ts-node's ESM loader fails on current Node and TypeScript releases: the TypeScript loader this driver runs under
26582
+ // does the same job. --watch restarts are dropped; one run is enough.
26583
+ if(tool==='node'){const tsx=process.execArgv[process.execArgv.indexOf('--import')+1];const out=[];
26584
+ 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);}
26585
+ args=out;}
26265
26586
  }
26266
26587
  child=spawn(file,args,{cwd:script.dir,env,stdio:['ignore','pipe','pipe'],detached:true});
26267
26588
  const keep=chunk=>{const text=chunk.toString();watch(text);process.stderr.write(text);};
@@ -26269,10 +26590,48 @@ try{
26269
26590
  port=await waitFor([free,listenPort]);
26270
26591
  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
26592
  }else{
26593
+ // Every port the app's own code binds counts, wherever its configuration put it.
26594
+ const bound=[];const listen0=net.Server.prototype.listen;
26595
+ 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);};
26596
+ const workersConfig=${JSON.stringify(workersConfig ?? null)};
26597
+ 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
26598
  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));});}
26599
+ const workersEnv=workers?await workers.environment(workersConfig,module):undefined;
26600
+ 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));}};
26601
+ port=await quick([free,listenPort]);
26602
+ const values=[module.app,module.default,...Object.values(module)].filter((v,i,all)=>v&&all.indexOf(v)===i);
26603
+ // An app object: one that listens (express, koa, fastify) or a fetch handler (Hono, a Workers-style export).
26604
+ const listener=values.find(v=>typeof v.listen==='function'&&(typeof v==='function'||typeof v.use==='function'||typeof v.route==='function'||typeof v.register==='function'));
26605
+ if(!port&&listener){port=await new Promise(resolve=>{const server=listener.listen(0,'127.0.0.1',()=>resolve(server.address().port));});}
26606
+ const handler=!port&&values.find(v=>typeof v.fetch==='function');
26607
+ if(handler){
26608
+ const http=await import('node:http');
26609
+ const server=http.createServer(async(req,res)=>{
26610
+ try{
26611
+ const chunks=[];for await(const c of req)chunks.push(c);
26612
+ const body=chunks.length&&!['GET','HEAD'].includes(req.method)?Buffer.concat(chunks):undefined;
26613
+ 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));
26614
+ 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(){}});
26615
+ res.writeHead(reply.status,Object.fromEntries(reply.headers));res.end(Buffer.from(await reply.arrayBuffer()));
26616
+ }catch(e){res.writeHead(500,{'content-type':'text/plain'});res.end(String(e&&e.stack||e));}
26617
+ });
26618
+ port=await new Promise(resolve=>server.listen(0,'127.0.0.1',()=>resolve(server.address().port)));
26619
+ }
26620
+ // A start function the module exports (startServer, runserver, createApp().listen inside): call it as main would.
26621
+ if(!port){
26622
+ 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));
26623
+ for(const [,fn] of starters){
26624
+ // Options first (startServer({port})); a function whose first parameter is something else (a list of
26625
+ // routes) throws on them, so it is called again with its own defaults, as the app's main does.
26626
+ const note=out=>{const p=out&&(out.port??(typeof out.address==='function'?out.address()?.port:undefined));if(typeof p==='number')printed.add(p);};
26627
+ try{note(await fn(fn.length?{port:free,host:'127.0.0.1'}:undefined));}catch(e){
26628
+ if(fn.length){try{note(await fn());}catch(e2){process.stderr.write('[agenttwin] '+String(e2&&e2.message||e2)+'\\n');}}
26629
+ else process.stderr.write('[agenttwin] '+String(e&&e.message||e)+'\\n');
26630
+ }
26631
+ port=await quick([free,listenPort]);if(port)break;
26632
+ }
26633
+ }
26634
+ if(!port)port=await waitFor([free,listenPort,...bound]);
26276
26635
  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
26636
  }
26278
26637
  for(const [index,args] of calls.entries()){
@@ -26510,11 +26869,48 @@ function ensurePrismaClient(cwd, appDir) {
26510
26869
  `);
26511
26870
  }
26512
26871
  }
26513
- var FORBIDDEN_ENV, TWIN_ENV, DATABASE_ENV, slugName, SCALAR_PARAM, SYNTHETIC, stripePath, TIER_LABEL, tierLabel2, PRETTY, FN2, SLACK_CLIENT, SAY, packTitle, readFileSyncSafe;
26872
+ function usesPostgresDriver(cwd) {
26873
+ const deps = (dir) => {
26874
+ try {
26875
+ const p = JSON.parse(readFileSync11(join57(cwd, dir, "package.json"), "utf8"));
26876
+ return Object.keys({ ...p.dependencies, ...p.devDependencies });
26877
+ } catch {
26878
+ return [];
26879
+ }
26880
+ };
26881
+ const dirs2 = ["."];
26882
+ for (const base of ["packages", "apps", "services", "server", "backend"]) try {
26883
+ for (const e of readdirSync4(join57(cwd, base), { withFileTypes: true })) if (e.isDirectory()) dirs2.push(join57(base, e.name));
26884
+ dirs2.push(base);
26885
+ } catch {
26886
+ }
26887
+ if (dirs2.some((d2) => deps(d2).some((n) => POSTGRES_DRIVERS.includes(n)))) return true;
26888
+ return dirs2.some((d2) => deps(d2).includes("@prisma/client") && ["prisma/schema.prisma", "schema.prisma"].some((f) => {
26889
+ try {
26890
+ return /provider\s*=\s*"postgres(?:ql)?"/.test(readFileSync11(join57(cwd, d2, f), "utf8"));
26891
+ } catch {
26892
+ return false;
26893
+ }
26894
+ }));
26895
+ }
26896
+ async function discoverWorkspaceSchema(cwd, appDir) {
26897
+ const own = appDir && appDir !== "." ? await discoverAppPostgresSchema(cwd, appDir) : void 0;
26898
+ if (own?.length) return own;
26899
+ for (const base of ["packages", "apps", "services"]) try {
26900
+ for (const e of readdirSync4(join57(cwd, base), { withFileTypes: true })) if (e.isDirectory()) {
26901
+ const found = await discoverAppPostgresSchema(cwd, join57(base, e.name));
26902
+ if (found?.length) return found;
26903
+ }
26904
+ } catch {
26905
+ }
26906
+ return void 0;
26907
+ }
26908
+ 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
26909
  var init_autoprep = __esm({
26515
26910
  "src/flow/autoprep.ts"() {
26516
26911
  "use strict";
26517
26912
  init_http_world();
26913
+ init_workers_env();
26518
26914
  init_postgres_schema();
26519
26915
  init_rabbitmq_assertions();
26520
26916
  init_kafka_assertions();
@@ -26559,6 +26955,7 @@ var init_autoprep = __esm({
26559
26955
  return "";
26560
26956
  }
26561
26957
  };
26958
+ POSTGRES_DRIVERS = ["pg", "postgres", "@neondatabase/serverless", "@vercel/postgres", "pg-promise", "slonik"];
26562
26959
  }
26563
26960
  });
26564
26961
 
@@ -26582,7 +26979,7 @@ function explainCleanRun(f) {
26582
26979
  const edit = `Change "input" in ${f.scenarioPath}, then run npx agenttwin again.`;
26583
26980
  const pm = f.packageManager ?? "npm", run3 = (script) => pm === "npm" ? `npm run ${script}` : `${pm} ${script}`;
26584
26981
  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)))];
26982
+ 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
26983
  if (envNames2.length && /env|environment|config|setting/i.test(f.stderr)) return {
26587
26984
  headline: `The app stopped while starting: it needs ${envNames2.slice(0, 3).join(", ")}${envNames2.length > 3 ? ` and ${envNames2.length - 3} more` : ""}.`,
26588
26985
  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 +27088,7 @@ function explainCleanRun(f) {
26691
27088
  next: `Fix the error or adjust the input. ${edit}`
26692
27089
  };
26693
27090
  }
26694
- var short2;
27091
+ var short2, NOT_SETTINGS;
26695
27092
  var init_first_run_help = __esm({
26696
27093
  "src/flow/first-run-help.ts"() {
26697
27094
  "use strict";
@@ -26699,13 +27096,14 @@ var init_first_run_help = __esm({
26699
27096
  const s = JSON.stringify(v);
26700
27097
  return s.length > 90 ? s.slice(0, 87) + "\u2026" : s;
26701
27098
  };
27099
+ 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
27100
  }
26703
27101
  });
26704
27102
 
26705
27103
  // src/flow/setup.ts
26706
27104
  import { spawn as spawn11, spawnSync as spawnSync3 } from "child_process";
26707
27105
  import { existsSync as existsSync10, readFileSync as readFileSync12, readdirSync as readdirSync5 } from "fs";
26708
- import { join as join58, posix as posix6 } from "path";
27106
+ import { delimiter as delimiter3, join as join58, posix as posix6 } from "path";
26709
27107
  function packageManager(cwd) {
26710
27108
  const field2 = readJson2(join58(cwd, "package.json"))?.packageManager;
26711
27109
  if (typeof field2 === "string") {
@@ -26795,12 +27193,41 @@ function planSetup(cwd, opts = {}) {
26795
27193
  }
26796
27194
  const unbuilt = steps.length || opts.only === "install" ? [] : unbuiltWorkspacePackages(cwd, opts.appDir);
26797
27195
  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"]);
27196
+ 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"]);
27197
+ 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;
27198
+ const r = turbo ? { ...turbo, fallback: own } : own;
26799
27199
  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
27200
  }
26801
27201
  const want = opts.only === "build" ? void 0 : nodeWanted(root2.engines?.node);
26802
27202
  return { packageManager: pm.name, steps, ...want ? { node: { want, have: process.versions.node, command: `nvm install ${want} && nvm use ${want}` } } : {} };
26803
27203
  }
27204
+ function installRetry(step, output) {
27205
+ const pm = step.command === "corepack" || step.command === "npx" ? step.args.find((a) => /^(npm|pnpm|yarn|bun)(@|$)/.test(a))?.split("@")[0] : step.command;
27206
+ const tail2 = step.command === "corepack" ? step.args.slice(1) : step.command === "npx" ? step.args.slice(2) : step.args;
27207
+ const pinned = step.command === "corepack" || step.command === "npx" ? step.args.find((a) => /^(npm|pnpm|yarn|bun)(@|$)/.test(a)) : pm;
27208
+ if (pm === "pnpm" && /ERR_PNPM_(OUTDATED_LOCKFILE|LOCKFILE_CONFIG_MISMATCH|LOCKFILE_MISSING_DEPENDENCY)|frozen.lockfile|specifiers in the lockfile/i.test(output))
27209
+ return { why: "The lockfile is behind package.json, so a frozen install stops", step: { ...step, args: [...step.args, "--no-frozen-lockfile"] } };
27210
+ if (pm === "yarn" && /YN0028|lockfile would have been modified|--frozen-lockfile/i.test(output))
27211
+ return { why: "The lockfile is behind package.json, so a frozen install stops", step: { ...step, args: [...step.args, "--no-immutable"] } };
27212
+ if (pm === "pnpm" && /ERR_PNPM_IGNORED_BUILDS/.test(output) && !step.args.some((a) => a.startsWith("--config.dangerously-allow-all-builds")))
27213
+ return { why: "pnpm skipped the dependencies' build scripts", step: { ...step, args: [...step.args, "--config.dangerously-allow-all-builds=true"] } };
27214
+ if (pm === "bun" && step.command === "corepack")
27215
+ return { why: "corepack cannot fetch bun", step: { ...step, command: "npx", args: ["--yes", pinned, ...tail2] } };
27216
+ if (pm === "npm" && /EBADENGINE|notsup|Unsupported engine/i.test(output) && !step.args.includes("--engine-strict=false"))
27217
+ return { why: "The project's engines field does not allow this Node version", step: { ...step, args: [...step.args, "--engine-strict=false"] } };
27218
+ }
27219
+ async function corepackShims(cwd, steps) {
27220
+ const pm = packageManager(cwd).name;
27221
+ 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));
27222
+ if (!managers.length || !steps.length || !has("corepack")) return;
27223
+ const dir = join58(cwd, ".agenttwin", "bin");
27224
+ const ok4 = await new Promise((resolve35) => {
27225
+ const c = spawn11("corepack", ["enable", "--install-directory", dir, ...managers], { stdio: "ignore" });
27226
+ c.once("error", () => resolve35(false));
27227
+ c.once("exit", (code) => resolve35(code === 0));
27228
+ });
27229
+ return ok4 ? dir : void 0;
27230
+ }
26804
27231
  async function runSetup2(cwd, opts) {
26805
27232
  const plan = opts.plan ?? planSetup(cwd, { ...opts.appDir !== void 0 ? { appDir: opts.appDir } : {}, ...opts.only ? { only: opts.only } : {} });
26806
27233
  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 +27238,38 @@ async function runSetup2(cwd, opts) {
26811
27238
  opts.log(` Skipped. Run ${plan.steps.map(show).join(" && ")} yourself, then npx agenttwin again.`);
26812
27239
  return false;
26813
27240
  }
27241
+ const shims = await corepackShims(cwd, plan.steps);
27242
+ const exec11 = (step) => new Promise((resolve35) => {
27243
+ 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 ?? ""}` } : {} } });
27244
+ let tail2 = "";
27245
+ const keep = (c) => {
27246
+ tail2 = (tail2 + c.toString()).slice(-4e3);
27247
+ };
27248
+ child.stdout.on("data", keep);
27249
+ child.stderr.on("data", keep);
27250
+ child.once("error", (e) => {
27251
+ tail2 += String(e);
27252
+ resolve35({ code: 1, tail: tail2 });
27253
+ });
27254
+ child.once("exit", (c) => resolve35({ code: c ?? 1, tail: tail2 }));
27255
+ });
26814
27256
  for (const step of plan.steps) {
26815
27257
  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
- });
27258
+ let { code, tail: tail2 } = await exec11(step);
27259
+ for (let current2 = step, tries = 0; code !== 0 && step.id === "install" && tries < 3; tries++) {
27260
+ const retry = installRetry(current2, tail2);
27261
+ if (!retry) break;
27262
+ opts.log(` ${retry.why}; running ${show(retry.step)}\u2026`);
27263
+ current2 = retry.step;
27264
+ ({ code, tail: tail2 } = await exec11(retry.step));
27265
+ }
27266
+ if (code !== 0 && step.fallback) {
27267
+ const next = { ...step, ...step.fallback, fallback: void 0 };
27268
+ opts.log(` ${show(step)} failed; running ${show(next)}\u2026`);
27269
+ ({ code, tail: tail2 } = await exec11(next));
27270
+ }
26833
27271
  if (code !== 0) {
27272
+ opts.log(tail2.split("\n").filter(Boolean).slice(-6).map((l) => " " + l.slice(0, 200)).join("\n"));
26834
27273
  opts.log(` ${show(step)} failed (exit ${code}). The run goes on; if the app cannot start, fix that first.`);
26835
27274
  return false;
26836
27275
  }
@@ -27038,15 +27477,15 @@ async function startS3Engine(options = {}) {
27038
27477
  const objects = ensureBucket(bucket) ?? store.get(bucket);
27039
27478
  if (!objects) return error(res, 404, "NoSuchBucket", "The specified bucket does not exist", bucket);
27040
27479
  if (method === "GET" && !url2.searchParams.has("uploads")) {
27041
- const prefix = url2.searchParams.get("prefix") ?? "", delimiter3 = url2.searchParams.get("delimiter");
27480
+ const prefix = url2.searchParams.get("prefix") ?? "", delimiter4 = url2.searchParams.get("delimiter");
27042
27481
  const max = Math.min(Number(url2.searchParams.get("max-keys") ?? 1e3) || 1e3, 1e3);
27043
27482
  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
27483
  let keys = [...objects.keys()].filter((k) => k.startsWith(prefix) && k > after).sort();
27045
27484
  const prefixes = /* @__PURE__ */ new Set();
27046
- if (delimiter3) keys = keys.filter((k) => {
27047
- const rest = k.slice(prefix.length), i = rest.indexOf(delimiter3);
27485
+ if (delimiter4) keys = keys.filter((k) => {
27486
+ const rest = k.slice(prefix.length), i = rest.indexOf(delimiter4);
27048
27487
  if (i < 0) return true;
27049
- prefixes.add(prefix + rest.slice(0, i + delimiter3.length));
27488
+ prefixes.add(prefix + rest.slice(0, i + delimiter4.length));
27050
27489
  return false;
27051
27490
  });
27052
27491
  const page2 = keys.slice(0, max), truncated = keys.length > max;
@@ -29110,7 +29549,9 @@ function findingsFor(clean, run3, fault, candidate) {
29110
29549
  const cleanChecks = [...clean.receipt.assertions, ...clean.receipt.evaluation?.checks ?? []];
29111
29550
  const findings = [];
29112
29551
  for (const f of findingsFromReceipt(run3.receipt, run3.world)) {
29113
- if (!cleanChecks.some((c) => c.passed && sameCheck(c, f))) continue;
29552
+ if (f.kind !== "unconfirmed-announce" && !cleanChecks.some((c) => c.passed && sameCheck(c, f))) continue;
29553
+ if (f.kind === "missing-effect" && /-down$/.test(fault.id)) continue;
29554
+ if (f.kind === "missing-effect" && f.handled) continue;
29114
29555
  if (findings.some((x) => x.proof && sameCheck(x.proof, f))) continue;
29115
29556
  const money2 = f.service === "stripe" || /refunds|charges|payment_intents|payouts/.test(f.path);
29116
29557
  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}` } });
@@ -29334,16 +29775,24 @@ async function executeSpec(cwd, prepared, effective, opts) {
29334
29775
  const credentials = await world.start();
29335
29776
  const closers = [];
29336
29777
  const engines2 = [];
29778
+ let pgInitial;
29337
29779
  let routing;
29338
29780
  let live;
29339
29781
  try {
29340
29782
  const pgPlan = prepared.scenario.twins.find((t) => t.engine?.kind === "postgres");
29341
29783
  const schemaFiles = prepared.scenario.postgresSchemaFiles ?? [];
29342
29784
  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;
29785
+ const pgExtensions = schemaSql ? { extensions: schemaExtensions(schemaSql).filter((e) => POSTGRES_EXTENSIONS.includes(e)) } : {};
29786
+ const pgTables = Object.fromEntries((spec.services.find((s) => s.name === pgPlan?.name)?.collections ?? []).map((c) => [c.path.slice(1), c.seed]));
29787
+ const pgEngine = pgPlan ? await startPostgresEngine({ ...pgExtensions, seed: { ...schemaSql ? { sql: schemaSql } : {}, tables: pgTables } }).catch(async (error) => {
29788
+ if (!schemaSql || !/null value in column/.test(String(error instanceof Error ? error.message : error))) throw error;
29789
+ const completed = await rowsForLookups(schemaSql, Object.entries(pgTables).flatMap(([table4, rows2]) => rows2.map((where) => ({ table: table4, where }))));
29790
+ return startPostgresEngine({ ...pgExtensions, seed: { sql: schemaSql, tables: Object.fromEntries(Object.keys(pgTables).map((t) => [t, completed[t] ?? []])) } });
29791
+ }) : void 0;
29344
29792
  if (pgEngine) {
29345
29793
  closers.push(() => pgEngine.stop());
29346
29794
  const state = await pgEngine.readState();
29795
+ if ("tables" in state) pgInitial = asSnapshot(state.tables);
29347
29796
  if ("tables" in state && world.state[pgPlan.name]) for (const table4 of state.tables) {
29348
29797
  const path2 = "/" + table4.name;
29349
29798
  if (Object.hasOwn(world.state[pgPlan.name], path2)) world.state[pgPlan.name][path2] = structuredClone(table4.rows);
@@ -29470,11 +29919,13 @@ async function executeSpec(cwd, prepared, effective, opts) {
29470
29919
  if ("queues" in state) for (const path2 of Object.keys(world.state[twin.name]))
29471
29920
  world.state[twin.name][path2] = structuredClone(state.queues.find((q3) => "/" + q3.name === path2)?.messages ?? []);
29472
29921
  }
29473
- if (assertedEngines.length) {
29922
+ const pgFinal = pgEngine && pgInitial ? await pgEngine.readState().catch(() => void 0) : void 0;
29923
+ const database = pgEngine && pgInitial ? { initial: pgInitial, ...pgFinal && "tables" in pgFinal ? { final: asSnapshot(pgFinal.tables) } : {}, statements: [...pgEngine.statements ?? []] } : void 0;
29924
+ if (assertedEngines.length || database) {
29474
29925
  report.finalState = world.snapshot();
29475
29926
  report.assertions = world.assertions();
29476
29927
  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 });
29928
+ report.defaultChecks = runDefaultChecks({ spec, initialState: report.initialState, finalState: report.finalState, events: world.events, fault: report.fault, ...database ? { database } : {} });
29478
29929
  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
29930
  }
29480
29931
  attachStaticSources(report.events, prepared);
@@ -29492,7 +29943,7 @@ async function executeSpec(cwd, prepared, effective, opts) {
29492
29943
  report.unsupported.push(...engineUnsupported);
29493
29944
  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
29945
  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;
29946
+ 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
29947
  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
29948
  const runId = randomUUID14(), out = join62(cwd, ".agenttwin", "runs", runId);
29498
29949
  await mkdir23(out, { recursive: true });
@@ -29739,6 +30190,8 @@ async function runOneCommand(opts) {
29739
30190
  if (!opts.skipSetup) {
29740
30191
  let appDir = posix7.dirname(candidate.serve?.entry ?? candidate.file);
29741
30192
  while (appDir !== "." && !existsSync11(join62(cwd, appDir, "package.json"))) appDir = posix7.dirname(appDir);
30193
+ const ownLock = ["package-lock.json", "pnpm-lock.yaml", "yarn.lock", "bun.lock", "bun.lockb"].some((f) => existsSync11(join62(cwd, appDir, f)));
30194
+ 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
30195
  await runSetup2(cwd, { ask, log, interactive, only: "build", appDir: appDir === "." ? "" : appDir });
29743
30196
  }
29744
30197
  log(bold("2/7 Twin") + dim(" generating synthetic starting state and inputs\u2026"));
@@ -29958,8 +30411,9 @@ async function runOneCommand(opts) {
29958
30411
  for (const e of clean.events) {
29959
30412
  if (e.operation !== "write") continue;
29960
30413
  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 ?? "");
30414
+ if (typeof adapter !== "string" || /^(?:pack:)?(?:openai|anthropic|google-oauth|postgres)$/.test(adapter)) continue;
30415
+ const pack = adapter.startsWith("pack:");
30416
+ const m = /^(POST|PUT|PATCH|DELETE) (\/[^\s?]*)/.exec(e.detail ?? "") ?? (!pack && /^\/[^\s?]*$/.test(e.detail ?? "") ? [void 0, "POST", e.detail] : null);
29963
30417
  if (!m) continue;
29964
30418
  if (m[2].startsWith("/_twin/") || prepared.scenario.signIn && e.service.endsWith("_signin")) continue;
29965
30419
  const path2 = m[2].replace(/\/(?=[^/]*\d)[^/]*_[^/]*$/, "");
@@ -29970,7 +30424,9 @@ async function runOneCommand(opts) {
29970
30424
  observedWrites.push(svc);
29971
30425
  }
29972
30426
  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: [] });
30427
+ if (pack) {
30428
+ 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: [] });
30429
+ }
29974
30430
  if (!svc.writes.some((w) => w.path === path2)) svc.writes.push({ path: path2, operation: m[1] === "DELETE" ? "delete" : m[1] === "POST" ? "create" : "update" });
29975
30431
  }
29976
30432
  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-")));
@@ -30213,7 +30669,7 @@ async function runOneCommand(opts) {
30213
30669
  }
30214
30670
  return { ...result2, resultPath, dashboard: link ?? null };
30215
30671
  }
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;
30672
+ 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
30673
  var init_one_command = __esm({
30218
30674
  "src/flow/one-command.ts"() {
30219
30675
  "use strict";
@@ -30266,6 +30722,7 @@ var init_one_command = __esm({
30266
30722
  const { sourceBuild: _build, files: _files, ...rest } = spec;
30267
30723
  return createHash31("sha256").update(JSON.stringify(rest)).digest("hex");
30268
30724
  };
30725
+ asSnapshot = (tables) => ({ tables: tables.map((t) => ({ name: t.name, columns: [], rows: structuredClone(t.rows) })) });
30269
30726
  WEBHOOK_PATH = /(^|\/)(webhooks?|callback|events?|inbound|incoming|notifications?|push|hooks?)(\/|$)/i;
30270
30727
  JOB_PATH = /(^|\/)(cron|jobs?|queue|tasks?|scheduled?)(\/|$)/i;
30271
30728
  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 +31487,7 @@ function repairFailureCount(receipt) {
31030
31487
  }
31031
31488
  async function stageRepairPatch(cwd, opts) {
31032
31489
  const { raw, regression } = await repairBaseline(cwd, opts);
31033
- const git2 = repairGit;
31490
+ const git3 = repairGit;
31034
31491
  const patchPath = resolve28(cwd, opts.patch), info2 = await lstat9(patchPath);
31035
31492
  if (!info2.isFile() || info2.size > 2 * 1024 * 1024) throw Error("Repair patch must be a regular file of at most 2 MiB");
31036
31493
  const patch = await readFile49(patchPath);
@@ -31039,28 +31496,28 @@ async function stageRepairPatch(cwd, opts) {
31039
31496
  const stage = await mkdtemp16(join67(tmpdir17(), "agenttwin-repair-index-"));
31040
31497
  const env = { ...gitEnvironment(), GIT_INDEX_FILE: join67(stage, "index") };
31041
31498
  try {
31042
- await git2(cwd, ["read-tree", opts.revision], env);
31499
+ await git3(cwd, ["read-tree", opts.revision], env);
31043
31500
  const snapshot2 = join67(stage, "proposal.patch");
31044
31501
  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");
31502
+ await git3(cwd, ["apply", "--cached", "--check", "--whitespace=error", "--", snapshot2], env);
31503
+ await git3(cwd, ["apply", "--cached", "--whitespace=error", "--", snapshot2], env);
31504
+ const changes = (await git3(cwd, ["diff", "--cached", "--no-renames", "--name-status", "-z", opts.revision, "--"], env)).toString().split("\0");
31048
31505
  changes.pop();
31049
31506
  if (!changes.length || changes.length % 2) throw Error("Repair patch has no source changes");
31050
31507
  const files = [];
31051
31508
  for (let index = 0; index < changes.length; index += 2) {
31052
31509
  const [status, file] = changes.slice(index, index + 2);
31053
31510
  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();
31511
+ const original = (await git3(cwd, ["ls-tree", opts.revision, "--", file], env)).toString();
31512
+ const staged = (await git3(cwd, ["ls-files", "--stage", "--", file], env)).toString();
31056
31513
  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);
31514
+ const bytes2 = await git3(cwd, ["show", `:${file}`], env);
31058
31515
  if (bytes2.length > 2 * 1024 * 1024 || bytes2.includes(0)) throw Error("Repair source must be text of at most 2 MiB per file");
31059
31516
  files.push(file);
31060
31517
  }
31061
- const tree = (await git2(cwd, ["write-tree"], env)).toString().trim();
31518
+ const tree = (await git3(cwd, ["write-tree"], env)).toString().trim();
31062
31519
  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();
31520
+ const revision = (await git3(cwd, ["-c", "commit.gpgSign=false", "commit-tree", tree, "-p", opts.revision, "-m", "Unreferenced AgentTwin repair candidate"], identity)).toString().trim();
31064
31521
  return { revision, files, patch, regression: raw, specDigest: regression.specDigest };
31065
31522
  } finally {
31066
31523
  await rm22(stage, { recursive: true, force: true });
@@ -31352,6 +31809,25 @@ async function runPrCheck(cwd, opts = {}) {
31352
31809
  const failed = regressions.filter((r) => r.status === "fail");
31353
31810
  const incomplete = regressions.filter((r) => r.status === "incomplete");
31354
31811
  const uncovered = touched.filter((w) => !w.covered && w.operations.some((o) => o.changed));
31812
+ const explored = [];
31813
+ if (opts.explore ?? (runtime === "local" && opts.execute !== false)) {
31814
+ const run3 = opts.runWorkflow ?? (async (workflow) => (await Promise.resolve().then(() => (init_one_command(), one_command_exports))).runOneCommand({ cwd, yes: true, interactive: false, workflow, log: () => {
31815
+ }, integrations: { syncDashboard: async () => void 0 } }));
31816
+ for (const w of uncovered.slice(0, 2)) {
31817
+ log(`Running ${w.title} against twins (no saved check covers it)\u2026`);
31818
+ try {
31819
+ const r = await run3(w.entrypoint ?? w.title);
31820
+ const problems = (r.findings ?? []).filter((f) => f.severity !== "low").map((f) => {
31821
+ const c = r.cost?.find((x) => x.title === f.title)?.estimate;
31822
+ return { title: f.title, severity: f.severity, ...c?.perIncident ? { perIncident: c.perIncident, currency: c.currency ?? "USD" } : {} };
31823
+ });
31824
+ 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 } } : {} });
31825
+ } catch (error) {
31826
+ explored.push({ workflow: w.title, status: "incomplete", problems: [], reason: error instanceof Error ? error.message.split("\n")[0] : String(error) });
31827
+ }
31828
+ }
31829
+ }
31830
+ const exploredProblems = explored.flatMap((e) => e.problems);
31355
31831
  const money2 = failed.map((r) => r.atRisk).filter((m) => !!m);
31356
31832
  const atRisk = money2.length ? { amount: money2.reduce((s, m) => s + m.amount, 0), currency: money2[0].currency } : void 0;
31357
31833
  const priced = failed.map((r) => r.cost).filter((c) => !!c);
@@ -31378,9 +31854,10 @@ async function runPrCheck(cwd, opts = {}) {
31378
31854
  title: `AgentTwin: calls ${serviceTitle(op2.service)} with no check`,
31379
31855
  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
31856
  });
31381
- const verdict = failed.length ? "fail" : incomplete.length || notRun.length ? "incomplete" : uncovered.length ? "warn" : "pass";
31857
+ const verdict = failed.length || exploredProblems.length ? "fail" : incomplete.length || notRun.length ? "incomplete" : uncovered.length ? "warn" : "pass";
31382
31858
  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" ? (() => {
31859
+ const worstExplored = exploredProblems.filter((p) => p.perIncident).sort((a, b) => b.perIncident - a.perIncident)[0];
31860
+ 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
31861
  const n = new Set(uncovered.flatMap((w) => w.operations.filter((o) => o.changed).map((o) => `${o.file}:${o.line}`))).size;
31385
31862
  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
31863
  })() : regressions.length === 1 ? "The twin check passed" : regressions.length ? `All ${regressions.length} twin checks passed` : "No agent side effects changed";
@@ -31389,7 +31866,7 @@ async function runPrCheck(cwd, opts = {}) {
31389
31866
  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
31867
  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
31868
  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 };
31869
+ 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
31870
  }
31394
31871
  var exec10, SERVICE3, serviceTitle, statusOf;
31395
31872
  var init_pr_check = __esm({
@@ -31434,7 +31911,8 @@ ${r.checks.filter((c) => !c.passed).map((c) => `- ${c.text}`).join("\n")}`,
31434
31911
  }
31435
31912
  function uncoveredLines(report) {
31436
31913
  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)) {
31914
+ const tested = new Set((report.explored ?? []).filter((e) => e.status !== "incomplete").map((e) => e.workflow));
31915
+ 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
31916
  const key3 = `${o.file}:${o.line}`, entry = byLine.get(key3) ?? { file: o.file, line: o.line, services: [], sends: [], workflows: [] };
31439
31917
  const service = serviceTitle(o.service), send = `${service} \xB7 \`${o.operation}\``;
31440
31918
  if (!entry.services.includes(service)) entry.services.push(service);
@@ -31456,6 +31934,17 @@ function renderMarkdown(report, opts = {}) {
31456
31934
  if (r.cause) out.push(`> ${r.cause}`);
31457
31935
  out.push("");
31458
31936
  }
31937
+ for (const e of (report.explored ?? []).filter((x) => x.problems.length)) {
31938
+ 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 |", "|---|---|");
31939
+ 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"} |`);
31940
+ out.push("");
31941
+ 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>", "");
31942
+ else out.push(`Reproduce locally: \`npx agenttwin --workflow "${e.workflow}"\``, "");
31943
+ }
31944
+ const clean = (report.explored ?? []).filter((x) => !x.problems.length && x.status !== "incomplete");
31945
+ if (clean.length) out.push(`<sub>Tested on this pull request with no problems found: ${clean.map((x) => cell(x.workflow)).join(", ")}.</sub>`, "");
31946
+ const couldNot = (report.explored ?? []).filter((x) => x.status === "incomplete");
31947
+ 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
31948
  if (report.regressions.length) {
31460
31949
  out.push("| | Twin check | Touched by this PR | Result |", "|---|---|---|---|");
31461
31950
  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 +32046,10 @@ __export(pr_check_github_exports, {
31557
32046
  CHECK_NAME: () => CHECK_NAME,
31558
32047
  actionsTarget: () => actionsTarget,
31559
32048
  checkWorkflow: () => checkWorkflow,
32049
+ postFixSuggestions: () => postFixSuggestions,
31560
32050
  publishCheckRun: () => publishCheckRun,
31561
32051
  startCheckRun: () => startCheckRun,
32052
+ suggestionsFromDiff: () => suggestionsFromDiff,
31562
32053
  upsertComment: () => upsertComment,
31563
32054
  writeActionsOutput: () => writeActionsOutput
31564
32055
  });
@@ -31608,6 +32099,88 @@ async function upsertComment(report, target) {
31608
32099
  }
31609
32100
  return (await api(target, "POST", `/repos/${target.repository}/issues/${target.pullRequest}/comments`, { body })).html_url;
31610
32101
  }
32102
+ function suggestionsFromDiff(diff) {
32103
+ const out = [];
32104
+ let path2, oldLine = 0, prev, block;
32105
+ const flush = () => {
32106
+ if (!block || !path2) {
32107
+ block = void 0;
32108
+ return;
32109
+ }
32110
+ if (block.removed.length) out.push({ path: path2, startLine: block.start, line: block.start + block.removed.length - 1, replacement: block.added.join("\n") });
32111
+ 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") });
32112
+ block = void 0;
32113
+ };
32114
+ for (const raw of diff.split("\n")) {
32115
+ if (raw.startsWith("--- ")) {
32116
+ flush();
32117
+ continue;
32118
+ }
32119
+ if (raw.startsWith("+++ ")) {
32120
+ const f = raw.slice(4).trim();
32121
+ path2 = f === "/dev/null" ? void 0 : f.replace(/^b\//, "");
32122
+ continue;
32123
+ }
32124
+ const hunk = /^@@ -(\d+)(?:,\d+)? \+\d+(?:,\d+)? @@/.exec(raw);
32125
+ if (hunk) {
32126
+ flush();
32127
+ oldLine = Number(hunk[1]);
32128
+ prev = void 0;
32129
+ continue;
32130
+ }
32131
+ if (raw.startsWith("-")) {
32132
+ block ??= { start: oldLine, removed: [], added: [] };
32133
+ block.removed.push(raw.slice(1));
32134
+ oldLine++;
32135
+ continue;
32136
+ }
32137
+ if (raw.startsWith("+")) {
32138
+ block ??= { start: oldLine, removed: [], added: [] };
32139
+ block.added.push(raw.slice(1));
32140
+ continue;
32141
+ }
32142
+ if (raw.startsWith(" ") || raw === "") {
32143
+ flush();
32144
+ prev = raw.slice(1);
32145
+ oldLine++;
32146
+ }
32147
+ }
32148
+ flush();
32149
+ return out;
32150
+ }
32151
+ async function postFixSuggestions(report, target) {
32152
+ if (!target.pullRequest) return "none";
32153
+ const fixes = (report.explored ?? []).filter((e) => e.fix?.diff && e.problems.length);
32154
+ const comments = fixes.flatMap((e) => suggestionsFromDiff(e.fix.diff).map((sg) => ({
32155
+ path: sg.path,
32156
+ line: sg.line,
32157
+ side: "RIGHT",
32158
+ ...sg.startLine < sg.line ? { start_line: sg.startLine, start_side: "RIGHT" } : {},
32159
+ body: `**${e.fix.title}** (${e.workflow}: ${e.problems[0].title})
32160
+
32161
+ \`\`\`suggestion
32162
+ ${sg.replacement}
32163
+ \`\`\``
32164
+ }))).slice(0, 30);
32165
+ if (!comments.length) return "none";
32166
+ const { createHash: createHash40 } = await import("crypto");
32167
+ const hash9 = createHash40("sha256").update(fixes.map((e) => e.fix.diff).join("\n")).digest("hex").slice(0, 16);
32168
+ const reviews = await api(target, "GET", `/repos/${target.repository}/pulls/${target.pullRequest}/reviews?per_page=100`);
32169
+ if (reviews.some((r) => r.body?.includes(SUGGESTION_MARKER + hash9))) return "already-posted";
32170
+ try {
32171
+ await api(target, "POST", `/repos/${target.repository}/pulls/${target.pullRequest}/reviews`, {
32172
+ commit_id: target.sha,
32173
+ event: "COMMENT",
32174
+ comments,
32175
+ body: `${SUGGESTION_MARKER}${hash9} -->
32176
+ 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.`
32177
+ });
32178
+ return "posted";
32179
+ } catch (error) {
32180
+ if (error.status === 422) return "outside-diff";
32181
+ throw error;
32182
+ }
32183
+ }
31611
32184
  async function writeActionsOutput(report, env = process.env, write3 = (s) => process.stdout.write(s)) {
31612
32185
  if (env.GITHUB_STEP_SUMMARY) await appendFile(env.GITHUB_STEP_SUMMARY, renderMarkdown(report));
31613
32186
  const command = { failure: "error", warning: "warning", notice: "notice" };
@@ -31659,7 +32232,7 @@ jobs:
31659
32232
  GITHUB_TOKEN: \${{ secrets.GITHUB_TOKEN }}
31660
32233
  `;
31661
32234
  }
31662
- var CHECK_NAME, CONCLUSION, MAX_SUMMARY, escapeData, escapeProperty;
32235
+ var CHECK_NAME, CONCLUSION, MAX_SUMMARY, SUGGESTION_MARKER, escapeData, escapeProperty;
31663
32236
  var init_pr_check_github = __esm({
31664
32237
  "src/runtime/pr-check-github.ts"() {
31665
32238
  "use strict";
@@ -31667,6 +32240,7 @@ var init_pr_check_github = __esm({
31667
32240
  CHECK_NAME = "AgentTwin";
31668
32241
  CONCLUSION = { pass: "success", fail: "failure", warn: "neutral", incomplete: "neutral" };
31669
32242
  MAX_SUMMARY = 65e3;
32243
+ SUGGESTION_MARKER = "<!-- agenttwin:fix ";
31670
32244
  escapeData = (s) => s.replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A");
31671
32245
  escapeProperty = (s) => escapeData(s).replace(/:/g, "%3A").replace(/,/g, "%2C");
31672
32246
  }
@@ -31758,7 +32332,7 @@ async function runAutomaticRepair(cwd, opts, runAgent = runCodexRepair) {
31758
32332
  baselineRevision: opts.baseline,
31759
32333
  candidateRevision: opts.revision,
31760
32334
  specDigest: before.specDigest,
31761
- sources: sources.map(({ file, content, sha256: sha2562 }) => ({ file, content, sha256: sha2562 })),
32335
+ sources: sources.map(({ file, content, sha256: sha2563 }) => ({ file, content, sha256: sha2563 })),
31762
32336
  providerContracts: { services: receipt.contracts?.services ?? [], adapters: Object.fromEntries(Object.entries(receipt.contracts?.adapters ?? {}).filter(([name]) => adapters.has(name))) },
31763
32337
  trustedChecks: { assertions: regression.spec.assertions, forbiddenEffects: regression.spec.forbiddenEffects ?? [], preservedState: regression.spec.preservedState ?? [], properties: regression.spec.properties ?? [] },
31764
32338
  failure: { assertions: receipt.assertions, infrastructureAssertions: receipt.infrastructureAssertions ?? [], checks: receipt.evaluation?.checks ?? [], fault: receipt.fault ?? null }
@@ -32001,6 +32575,121 @@ var init_conformance = __esm({
32001
32575
  }
32002
32576
  });
32003
32577
 
32578
+ // src/runtime/release-record.ts
32579
+ var release_record_exports = {};
32580
+ __export(release_record_exports, {
32581
+ buildReleaseRecord: () => buildReleaseRecord,
32582
+ renderReleaseRecord: () => renderReleaseRecord
32583
+ });
32584
+ import { createHash as createHash38 } from "crypto";
32585
+ import { execFileSync } from "child_process";
32586
+ import { readdir as readdir12, readFile as readFile57, stat as stat13 } from "fs/promises";
32587
+ import { join as join78, relative as relative25 } from "path";
32588
+ async function latestResults(cwd) {
32589
+ const auto = join78(cwd, ".agenttwin", "auto"), out = [];
32590
+ for (const wf of await readdir12(auto).catch(() => [])) {
32591
+ const dir = join78(auto, wf, "results");
32592
+ let best;
32593
+ for (const id2 of await readdir12(dir).catch(() => [])) {
32594
+ const file = join78(dir, id2, "result.json"), at = (await stat13(file).catch(() => void 0))?.mtimeMs;
32595
+ if (at && (!best || at > best.at)) best = { file, at };
32596
+ }
32597
+ if (best) out.push(best);
32598
+ }
32599
+ return out.sort((a, b) => a.file.localeCompare(b.file));
32600
+ }
32601
+ async function buildReleaseRecord(cwd, version, now = /* @__PURE__ */ new Date()) {
32602
+ const workflows = [];
32603
+ for (const { file, at } of await latestResults(cwd)) {
32604
+ let r;
32605
+ try {
32606
+ r = JSON.parse(await readFile57(file, "utf8"));
32607
+ } catch {
32608
+ continue;
32609
+ }
32610
+ if (!r || typeof r !== "object" || !Array.isArray(r.runs)) continue;
32611
+ const cases2 = [];
32612
+ for (const run3 of r.runs) {
32613
+ const recorded = typeof run3.evidencePath === "string" ? run3.evidencePath : void 0;
32614
+ const local = recorded ? recorded.includes("/.agenttwin/") ? join78(cwd, recorded.slice(recorded.indexOf("/.agenttwin/") + 1)) : recorded : void 0;
32615
+ const digest6 = local ? await sha2562(local) : void 0;
32616
+ 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 } } : {} });
32617
+ }
32618
+ workflows.push({
32619
+ title: String(r.workflow?.title ?? r.workflow?.id ?? "workflow"),
32620
+ status: String(r.status ?? "unknown"),
32621
+ testedAt: new Date(at).toISOString(),
32622
+ twins: (r.twins ?? []).map((t) => ({ title: String(t.title ?? t.service), tier: String(t.tier ?? "") })),
32623
+ cases: cases2,
32624
+ findings: (r.findings ?? []).map((f) => ({ title: String(f.title), ...f.severity ? { severity: String(f.severity) } : {}, ...f.faultId ? { fault: String(f.faultId) } : {} })),
32625
+ limitations: (r.limitations ?? []).map(String).slice(0, 10)
32626
+ });
32627
+ }
32628
+ const failed = workflows.filter((w) => w.status === "failed" || w.findings.length).length, passed = workflows.filter((w) => w.status === "passed" && !w.findings.length).length;
32629
+ const incomplete = workflows.length - failed - passed;
32630
+ const cases = workflows.reduce((n, w) => n + w.cases.length, 0);
32631
+ const verdict = !workflows.length ? "nothing-tested" : failed ? "failed" : incomplete ? "incomplete" : "passed";
32632
+ const commit = git2(cwd, ["rev-parse", "HEAD"]), branch = git2(cwd, ["rev-parse", "--abbrev-ref", "HEAD"]), status = git2(cwd, ["status", "--porcelain", "--untracked-files=no"]);
32633
+ return {
32634
+ schema: "agenttwin/release-record-v1",
32635
+ createdAt: now.toISOString(),
32636
+ agenttwinVersion: version,
32637
+ ...commit ? { commit } : {},
32638
+ ...branch ? { branch } : {},
32639
+ ...status !== void 0 ? { dirty: status.length > 0 } : {},
32640
+ project: git2(cwd, ["config", "--get", "remote.origin.url"])?.replace(/^.*[:/]([^/]+\/[^/]+?)(\.git)?$/, "$1") ?? cwd.split("/").pop() ?? "project",
32641
+ verdict,
32642
+ summary: { workflows: workflows.length, passed, failed, incomplete, cases, faults: cases - workflows.length, findings: workflows.reduce((n, w) => n + w.findings.length, 0) },
32643
+ workflows
32644
+ };
32645
+ }
32646
+ function renderReleaseRecord(rec) {
32647
+ const s = rec.summary;
32648
+ 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>
32649
+ <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>
32650
+ <table><thead><tr><th>Case</th><th>Result</th><th>Receipt (SHA-256)</th></tr></thead><tbody>
32651
+ ${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")}
32652
+ </tbody></table>
32653
+ ${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>` : ""}
32654
+ ${w.limitations.length ? `<details><summary>Limits of this test</summary><ul>${w.limitations.map((l) => `<li>${esc2(l)}</li>`).join("")}</ul></details>` : ""}
32655
+ </section>`).join("\n");
32656
+ 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>
32657
+ <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}}
32658
+ 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}
32659
+ 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}
32660
+ .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>
32661
+ <h1>Release record \xB7 ${esc2(rec.project)}</h1>
32662
+ <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>
32663
+ <div class="box"><p class="st ${esc2(rec.verdict)}" style="font-size:18px;margin:0">${VERDICT2[rec.verdict]}</p>
32664
+ <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>
32665
+ ${rows2 || "<p>No workflow results yet. Run <code>npx agenttwin</code> first.</p>"}
32666
+ <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>
32667
+ </body></html>
32668
+ `;
32669
+ }
32670
+ var git2, sha2562, esc2, VERDICT2;
32671
+ var init_release_record = __esm({
32672
+ "src/runtime/release-record.ts"() {
32673
+ "use strict";
32674
+ git2 = (cwd, args) => {
32675
+ try {
32676
+ return execFileSync("git", ["-C", cwd, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
32677
+ } catch {
32678
+ return void 0;
32679
+ }
32680
+ };
32681
+ sha2562 = async (file) => {
32682
+ try {
32683
+ return createHash38("sha256").update(await readFile57(file)).digest("hex");
32684
+ } catch {
32685
+ return void 0;
32686
+ }
32687
+ };
32688
+ esc2 = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
32689
+ VERDICT2 = { passed: "Passed", failed: "Problems found", incomplete: "Partly tested", "nothing-tested": "Nothing tested" };
32690
+ }
32691
+ });
32692
+
32004
32693
  // src/runtime/exploration.ts
32005
32694
  var exploration_exports = {};
32006
32695
  __export(exploration_exports, {
@@ -32010,9 +32699,9 @@ __export(exploration_exports, {
32010
32699
  runExploration: () => runExploration,
32011
32700
  saveExplorationRegression: () => saveExplorationRegression
32012
32701
  });
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";
32702
+ import { createHash as createHash39, randomUUID as randomUUID19 } from "crypto";
32703
+ import { mkdir as mkdir34, readFile as readFile58, writeFile as writeFile48, rm as rm26 } from "fs/promises";
32704
+ import { dirname as dirname24, join as join79, relative as relative26, resolve as resolve33, sep as sep18 } from "path";
32016
32705
  function faultCases(spec, seed, trials) {
32017
32706
  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
32707
  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 +32713,40 @@ function faultCases(spec, seed, trials) {
32024
32713
  });
32025
32714
  }
32026
32715
  async function captureExploration(cwd, file, seed, trials) {
32027
- const path2 = resolve33(cwd, file), sourceDirectory = relative25(resolve33(cwd), dirname24(path2)).split(sep18).join("/");
32716
+ const path2 = resolve33(cwd, file), sourceDirectory = relative26(resolve33(cwd), dirname24(path2)).split(sep18).join("/");
32028
32717
  if (sourceDirectory === ".." || sourceDirectory.startsWith("../")) throw new Error("World must be inside this repository");
32029
- const spec = parseWorld(JSON.parse(await readFile57(path2, "utf8")));
32718
+ const spec = parseWorld(JSON.parse(await readFile58(path2, "utf8")));
32030
32719
  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
32720
  const cases = faultCases(spec, seed, trials), id2 = randomUUID19();
32032
32721
  await ensureStore(cwd);
32033
- const directory2 = join78(cwd, ".agenttwin/explorations", id2);
32722
+ const directory2 = join79(cwd, ".agenttwin/explorations", id2);
32034
32723
  await mkdir34(directory2, { recursive: true, mode: 448 });
32035
- const sourceDigests = await stageApplication(dirname24(path2), spec.files, join78(directory2, "snapshot"));
32724
+ const sourceDigests = await stageApplication(dirname24(path2), spec.files, join79(directory2, "snapshot"));
32036
32725
  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 });
32726
+ await writeFile48(join79(directory2, "manifest.json"), JSON.stringify(manifest, null, 2) + "\n", { flag: "wx", mode: 384 });
32038
32727
  return manifest;
32039
32728
  }
32040
32729
  async function loadExploration(cwd, id2) {
32041
32730
  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"));
32731
+ const manifest = JSON.parse(await readFile58(join79(cwd, ".agenttwin/explorations", id2, "manifest.json"), "utf8"));
32043
32732
  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
32733
  for (const file of manifest.spec.files) {
32045
32734
  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");
32735
+ 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
32736
  }
32048
32737
  return manifest;
32049
32738
  }
32050
32739
  async function runExploration(cwd, id2, opts) {
32051
32740
  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);
32741
+ const root2 = join79(cwd, ".agenttwin/explorations", id2), attempt = randomUUID19();
32742
+ const application = join79(root2, "attempts", attempt, "app");
32743
+ await stageApplication(opts.patched ? resolve33(cwd, manifest.sourceDirectory) : join79(root2, "snapshot"), manifest.spec.files, application);
32055
32744
  const results = [];
32056
32745
  for (const [index, trial] of manifest.cases.entries()) {
32057
32746
  const spec = structuredClone(manifest.spec);
32058
32747
  delete spec.fault;
32059
32748
  if (trial.fault) spec.fault = trial.fault;
32060
- const file = join78(application, `.agenttwin-trial-${attempt}.json`);
32749
+ const file = join79(application, `.agenttwin-trial-${attempt}.json`);
32061
32750
  await writeFile48(file, JSON.stringify(spec), { mode: 384 });
32062
32751
  const result2 = await runWorld(cwd, { file, log: opts.log });
32063
32752
  results.push({ index, seed: trial.seed, fault: trial.fault ?? null, status: result2.status, evidencePath: result2.evidencePath, specDigest: result2.specDigest });
@@ -32065,7 +32754,7 @@ async function runExploration(cwd, id2, opts) {
32065
32754
  }
32066
32755
  const status = results.some((r) => ["failed", "error"].includes(r.status)) ? "failed" : results.some((r) => r.status === "incomplete") ? "incomplete" : "passed";
32067
32756
  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 });
32757
+ await writeFile48(join79(root2, "attempts", attempt, "summary.json"), JSON.stringify(summary2, null, 2) + "\n", { mode: 384 });
32069
32758
  return summary2;
32070
32759
  }
32071
32760
  async function saveExplorationRegression(cwd, explorationId, trialIndex, id2) {
@@ -32090,7 +32779,7 @@ var init_exploration = __esm({
32090
32779
  init_spec();
32091
32780
  init_regressions();
32092
32781
  init_store();
32093
- hash8 = (value3) => createHash38("sha256").update(value3).digest("hex");
32782
+ hash8 = (value3) => createHash39("sha256").update(value3).digest("hex");
32094
32783
  }
32095
32784
  });
32096
32785
 
@@ -32100,12 +32789,12 @@ __export(run_outcome_exports, {
32100
32789
  mainRunFailure: () => mainRunFailure
32101
32790
  });
32102
32791
  import { existsSync as existsSync13 } from "fs";
32103
- import { join as join79 } from "path";
32792
+ import { join as join80 } from "path";
32104
32793
  function mainRunFailure(error, cwd) {
32105
32794
  const message = error instanceof Error ? error.message : String(error);
32106
32795
  const firstLine = message.split("\n").map((l) => l.trim()).find(Boolean) ?? "it stopped without a message.";
32107
32796
  if (error instanceof CliError) return { reason: firstLine, ...error.action ? { next: error.action } : {} };
32108
- const packageManager2 = packageManagerOf(cwd, (f) => existsSync13(join79(cwd, f)));
32797
+ const packageManager2 = packageManagerOf(cwd, (f) => existsSync13(join80(cwd, f)));
32109
32798
  const help = explainCleanRun({ status: "failed", exitCode: 1, stderr: message, unsupported: [], assertions: [], input: null, scenarioPath: ".agenttwin/auto/<workflow>/scenario.json", packageManager: packageManager2 });
32110
32799
  if (help && !/^Your code stopped with an error/.test(help.headline)) return { reason: help.headline, next: help.next, ...help.command ? { command: help.command } : {} };
32111
32800
  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 +32897,7 @@ init_login();
32208
32897
  init_version();
32209
32898
  init_sync();
32210
32899
  init_prepare();
32211
- import { join as join80, relative as relative26, resolve as resolve34 } from "path";
32900
+ import { join as join81, relative as relative27, resolve as resolve34 } from "path";
32212
32901
  import { parseArgs } from "util";
32213
32902
 
32214
32903
  // src/commands/setup.ts
@@ -32371,7 +33060,12 @@ var HOSTED_TOOLS = [
32371
33060
  hosted("list_org_tokens", "Organization tokens (for CI and SCIM) in the workspace. Secrets are never returned after creation.", {}, [], true),
32372
33061
  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
33062
  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)
33063
+ hosted("audit_log", "The workspace audit log, newest first: who did what and when.", { limit }, [], true),
33064
+ 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),
33065
+ hosted("workspace_plan", "The workspace plan (free or Team), trial end date and whether the free trial is still available.", {}, [], true),
33066
+ hosted("start_trial", "Start the 14-day Team trial, which checks private repositories too. No card needed; once per workspace. Admins only.", {}, [], false),
33067
+ hosted("slack_alerts", "Whether failed pull request checks are posted to a Slack channel. The saved URL is never returned.", {}, [], true),
33068
+ 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
33069
  ];
32376
33070
  async function hostedConnection() {
32377
33071
  const saved = await savedConnection();
@@ -32452,6 +33146,16 @@ async function callHostedTool(name, args, deps = {}) {
32452
33146
  const value3 = await api2("GET", "/v1/team/audit");
32453
33147
  return { events: (value3.events ?? []).slice(0, Number(args.limit ?? 100)) };
32454
33148
  }
33149
+ case "workspace_value":
33150
+ return api2("GET", "/v1/workspace/value" + q({ month: args.month }));
33151
+ case "workspace_plan":
33152
+ return api2("GET", "/v1/workspace/plan");
33153
+ case "start_trial":
33154
+ return api2("POST", "/v1/workspace/trial");
33155
+ case "slack_alerts":
33156
+ return api2("GET", "/v1/workspace/alerts");
33157
+ case "set_slack_alerts":
33158
+ return api2("PUT", "/v1/workspace/alerts", { slackWebhookUrl: args.slackWebhookUrl ?? null });
32455
33159
  case "workspace_summary":
32456
33160
  return workspaceSummary(api2, args.project);
32457
33161
  default:
@@ -35148,6 +35852,7 @@ function helpText() {
35148
35852
  ` ${"scenario".padEnd(12)}save --file scenario.json | list | show --scenario id@version`,
35149
35853
  ` ${"world".padEnd(12)}create --file world.json | list | status/reset/extend/run/teardown --id UUID`,
35150
35854
  ` ${"receipt".padEnd(12)}Inspect failures and get a fix task (--id run UUID)`,
35855
+ ` ${"record".padEnd(12)}Write the release record for this commit: what was tested, faults, results, receipt hashes [--out DIR]`,
35151
35856
  ` ${"mcp".padEnd(12)}Serve coding-agent tools over MCP stdio in this workspace`,
35152
35857
  ` ${"incident".padEnd(12)}import --file incident.json [--out redacted-preview.json]`,
35153
35858
  ` ${"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 +36078,8 @@ async function main() {
35373
36078
  if (positionals[1] === "install") {
35374
36079
  const { checkWorkflow: checkWorkflow2 } = await Promise.resolve().then(() => (init_pr_check_github(), pr_check_github_exports));
35375
36080
  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 });
36081
+ const path2 = join81(cwd, ".github/workflows/agenttwin.yml");
36082
+ await mkdir35(join81(cwd, ".github/workflows"), { recursive: true });
35378
36083
  try {
35379
36084
  await writeFile49(path2, checkWorkflow2(readVersion()), { flag: flag("force") ? "w" : "wx" });
35380
36085
  } catch (error) {
@@ -35491,9 +36196,9 @@ ${requirements.blockers.map((blocker) => ` - ${blocker}`).join("\n")}`);
35491
36196
  const { runProbe: runProbe2, PROBES: PROBES2, REAL_TARGETS: REAL_TARGETS2 } = await Promise.resolve().then(() => (init_conformance(), conformance_exports));
35492
36197
  const { HttpWorld: HttpWorld2 } = await Promise.resolve().then(() => (init_http_world(), http_world_exports));
35493
36198
  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");
36199
+ const { readFile: readFile59, writeFile: writeFile49, mkdir: mkdir35 } = await import("fs/promises");
35495
36200
  const adapter = str4("adapter") ?? "stripe";
35496
- const probes = str4("probes") ? JSON.parse(await readFile58(resolve34(cwd, str4("probes")), "utf8")) : PROBES2[adapter];
36201
+ const probes = str4("probes") ? JSON.parse(await readFile59(resolve34(cwd, str4("probes")), "utf8")) : PROBES2[adapter];
35497
36202
  const collections = ADAPTER_COLLECTIONS2[adapter];
35498
36203
  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
36204
  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 +36218,11 @@ ${requirements.blockers.map((blocker) => ` - ${blocker}`).join("\n")}`);
35513
36218
  (${r.omitted} fields the real service returns are not modelled)` : ""}`);
35514
36219
  }
35515
36220
  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`);
36221
+ await mkdir35(join81(cwd, ".agenttwin", "conformance"), { recursive: true });
36222
+ const out = join81(cwd, ".agenttwin", "conformance", `${adapter}-${summary2.at.slice(0, 10)}.json`);
35518
36223
  await writeFile49(out, JSON.stringify(summary2, null, 2) + "\n");
35519
36224
  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":[]}'));
36225
+ const file = resolve34(cwd, "conformance/results.json"), existing = JSON.parse(await readFile59(file, "utf8").catch(() => '{"schema":"agenttwin/conformance-results-v1","results":[]}'));
35521
36226
  for (const r of verified) {
35522
36227
  const probe = probes.find((p) => p.id === r.probe);
35523
36228
  existing.results = existing.results.filter((e) => e.probe !== r.probe);
@@ -35526,7 +36231,7 @@ ${requirements.blockers.map((blocker) => ` - ${blocker}`).join("\n")}`);
35526
36231
  await writeFile49(file, JSON.stringify(existing, null, 2) + "\n");
35527
36232
  log(`Recorded ${verified.length} verified probe(s) in conformance/results.json.`);
35528
36233
  } 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)}`);
36234
+ printResult(summary2, `${summary2.verified} of ${summary2.probes} probes verified against ${summary2.against ?? "no real service"}. Results: ${relative27(cwd, out)}`);
35530
36235
  process.exitCode = summary2.differs ? EXIT.ERROR : EXIT.OK;
35531
36236
  } finally {
35532
36237
  await world.close();
@@ -35584,13 +36289,30 @@ ${requirements.blockers.map((blocker) => ` - ${blocker}`).join("\n")}`);
35584
36289
  if (action === "run") process.exitCode = result2.status === "passed" ? EXIT.OK : result2.status === "incomplete" ? EXIT.BLOCKED : EXIT.ERROR;
35585
36290
  return;
35586
36291
  }
36292
+ case "record": {
36293
+ const { buildReleaseRecord: buildReleaseRecord2, renderReleaseRecord: renderReleaseRecord2 } = await Promise.resolve().then(() => (init_release_record(), release_record_exports));
36294
+ const { mkdir: mkdir35, writeFile: writeFile49 } = await import("fs/promises");
36295
+ const record5 = await buildReleaseRecord2(cwd, VERSION);
36296
+ const dir = str4("out") ? resolve34(cwd, str4("out")) : join81(cwd, ".agenttwin");
36297
+ await mkdir35(dir, { recursive: true });
36298
+ const html = join81(dir, "release-record.html"), json4 = join81(dir, "release-record.json");
36299
+ await writeFile49(json4, JSON.stringify(record5, null, 2) + "\n");
36300
+ await writeFile49(html, renderReleaseRecord2(record5));
36301
+ const s = record5.summary;
36302
+ 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.
36303
+ ${html}
36304
+ ${json4}
36305
+ ` : `No workflow results yet: run npx agenttwin first. Wrote an empty record to ${html}
36306
+ `);
36307
+ return;
36308
+ }
35587
36309
  case "receipt": {
35588
36310
  let id2 = str4("id");
35589
36311
  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 })));
36312
+ const { readdir: readdir13, stat: stat14 } = await import("fs/promises");
36313
+ const dir = join81(cwd, ".agenttwin/runs");
36314
+ const runs = await readdir13(dir).catch(() => []);
36315
+ 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
36316
  id2 = dated.filter((r) => r.at).sort((a, b) => b.at - a.at)[0]?.run;
35595
36317
  if (!id2) throw new CliError("No runs yet. Run a test first: agenttwin run --file agenttwin.world.json", { code: EXIT.USAGE });
35596
36318
  }
@@ -35727,8 +36449,8 @@ Review with: agenttwin prepare review --id ${id2}`);
35727
36449
  }
35728
36450
  const status = await preparationStatus(cwd, id2);
35729
36451
  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");
36452
+ const { readFile: readFile59 } = await import("fs/promises");
36453
+ const review = await readFile59(status.reviewPath, "utf8");
35732
36454
  if (!flag("yes")) {
35733
36455
  if (json3 || !process.stdin.isTTY) {
35734
36456
  printResult({ ...status, review, runnable: false }, review);
@@ -35955,7 +36677,7 @@ ${result2.uploaded}`);
35955
36677
  result2,
35956
36678
  [
35957
36679
  `Discovered ${counts.tools} tools (${counts.classified} classified) \xB7 ${counts.unclassified} unclassified \xB7 ${counts.withTwin} with twins`,
35958
- `Wrote ${join80(".agenttwin", "inventory.json")}`,
36680
+ `Wrote ${join81(".agenttwin", "inventory.json")}`,
35959
36681
  result2.blocked.length > 0 ? `Blocked: ${result2.blocked.join("; ")}` : "",
35960
36682
  result2.opportunities.length > 0 ? `Opportunities: ${result2.opportunities.join("; ")}` : "",
35961
36683
  result2.reconciliation.splits.length > 0 ? `Splits: ${result2.reconciliation.splits.map((s) => s.from).join(", ")}` : ""
@@ -35978,7 +36700,7 @@ ${result2.uploaded}`);
35978
36700
  printResult(
35979
36701
  result2,
35980
36702
  `Plan: ${result2.plan.items.length} tools \xB7 ${Object.entries(byStrategy).map(([k, v]) => `${k} ${v}`).join(", ")}
35981
- Wrote ${join80(".agenttwin", "plan.json")}`
36703
+ Wrote ${join81(".agenttwin", "plan.json")}`
35982
36704
  );
35983
36705
  return;
35984
36706
  }