@tangle-network/agent-app 0.60.250 → 0.60.251

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 (222) hide show
  1. package/dist/DesignCanvas-L6J72JQ2.js +15 -0
  2. package/dist/DesignCanvasEditor-QFQD63MR.js +18 -0
  3. package/dist/agent-enrollment/drizzle.js +3 -3
  4. package/dist/agent-enrollment/index.js +3 -3
  5. package/dist/app-auth/drizzle.d.ts +561 -0
  6. package/dist/app-auth/drizzle.js +72 -0
  7. package/dist/app-auth/drizzle.js.map +1 -0
  8. package/dist/app-auth/index.js +5 -3
  9. package/dist/app-auth/index.js.map +1 -1
  10. package/dist/app-oauth/drizzle.d.ts +2080 -0
  11. package/dist/app-oauth/drizzle.js +161 -0
  12. package/dist/app-oauth/drizzle.js.map +1 -0
  13. package/dist/app-oauth/index.d.ts +4 -0
  14. package/dist/app-oauth/index.js +8 -222
  15. package/dist/app-oauth/index.js.map +1 -1
  16. package/dist/app-oauth/issuer.d.ts +133 -0
  17. package/dist/app-oauth/issuer.js +247 -0
  18. package/dist/app-oauth/issuer.js.map +1 -0
  19. package/dist/assistant/index.js +13 -13
  20. package/dist/chat-react/index.js +4 -4
  21. package/dist/chat-routes/index.js +37 -67
  22. package/dist/chat-routes/index.js.map +1 -1
  23. package/dist/chat-routes/promote-file-part.d.ts +2 -3
  24. package/dist/chat-store/index.js +4 -4
  25. package/dist/{chunk-MY3EJJ6Y.js → chunk-4FEH6266.js} +2 -2
  26. package/dist/{chunk-5Y7Z5G3Y.js → chunk-4GCPADYG.js} +20 -336
  27. package/dist/chunk-4GCPADYG.js.map +1 -0
  28. package/dist/{chunk-X556WVBG.js → chunk-4ZSLX3LY.js} +2 -2
  29. package/dist/chunk-57XPEL7X.js +26 -0
  30. package/dist/chunk-57XPEL7X.js.map +1 -0
  31. package/dist/chunk-6Z7TZVKZ.js +26 -0
  32. package/dist/chunk-6Z7TZVKZ.js.map +1 -0
  33. package/dist/{chunk-7KKOFMLD.js → chunk-AWIQQEFP.js} +1 -1
  34. package/dist/chunk-AWIQQEFP.js.map +1 -0
  35. package/dist/{chunk-VBKP2NLI.js → chunk-BTKI4XMM.js} +2 -2
  36. package/dist/{chunk-63QAQP7I.js → chunk-CNBVWPQC.js} +7 -7
  37. package/dist/{chunk-FENBDSIW.js → chunk-CQGEGPY7.js} +75 -3
  38. package/dist/chunk-CQGEGPY7.js.map +1 -0
  39. package/dist/chunk-CTREXL3O.js +335 -0
  40. package/dist/chunk-CTREXL3O.js.map +1 -0
  41. package/dist/chunk-DLWO3J7D.js +238 -0
  42. package/dist/chunk-DLWO3J7D.js.map +1 -0
  43. package/dist/{chunk-LWSJK546.js → chunk-DSMGS4IV.js} +5 -5
  44. package/dist/{chunk-LWSJK546.js.map → chunk-DSMGS4IV.js.map} +1 -1
  45. package/dist/{chunk-A3KPDLSF.js → chunk-EFPIHR6F.js} +18 -18
  46. package/dist/chunk-FRAICFTZ.js +191 -0
  47. package/dist/chunk-FRAICFTZ.js.map +1 -0
  48. package/dist/chunk-GS7VWV26.js +61 -0
  49. package/dist/chunk-GS7VWV26.js.map +1 -0
  50. package/dist/{chunk-NMSAZFRL.js → chunk-H5GQMLHA.js} +2 -2
  51. package/dist/{chunk-OQE6WMDP.js → chunk-HN6MZ2XL.js} +5 -5
  52. package/dist/chunk-HY57QRRW.js +11 -0
  53. package/dist/chunk-HY57QRRW.js.map +1 -0
  54. package/dist/{chunk-TCGZFSN5.js → chunk-KH4QSBNI.js} +2 -2
  55. package/dist/{chunk-JH3CKHF4.js → chunk-KJODHPWM.js} +8 -8
  56. package/dist/chunk-LSBI5MWS.js +66 -0
  57. package/dist/chunk-LSBI5MWS.js.map +1 -0
  58. package/dist/chunk-MDRH3SDA.js +106 -0
  59. package/dist/chunk-MDRH3SDA.js.map +1 -0
  60. package/dist/{chunk-VBWYH7UZ.js → chunk-NHYRIM4I.js} +3 -3
  61. package/dist/{chunk-BYP54FMI.js → chunk-O2RCDK5D.js} +30 -15
  62. package/dist/{chunk-BYP54FMI.js.map → chunk-O2RCDK5D.js.map} +1 -1
  63. package/dist/{chunk-EWOJATDS.js → chunk-PDD5A43Y.js} +3 -3
  64. package/dist/{chunk-23JUSUUB.js → chunk-RZLCBWGG.js} +2 -2
  65. package/dist/chunk-SFZELD6V.js +52 -0
  66. package/dist/chunk-SFZELD6V.js.map +1 -0
  67. package/dist/{chunk-Y4W6GK5X.js → chunk-UGFCLD32.js} +2 -2
  68. package/dist/{chunk-ZGUXI5SI.js → chunk-VUBJZEZB.js} +2 -2
  69. package/dist/{chunk-LQYIBL3G.js → chunk-WL7PZK7Q.js} +71 -1
  70. package/dist/chunk-WL7PZK7Q.js.map +1 -0
  71. package/dist/{chunk-7HZCFG2A.js → chunk-WP2GYFZ4.js} +38 -1
  72. package/dist/chunk-WP2GYFZ4.js.map +1 -0
  73. package/dist/{chunk-JK7R7BZQ.js → chunk-ZWJ3SZ2G.js} +2 -2
  74. package/dist/crypto/digest.d.ts +2 -0
  75. package/dist/crypto/index.d.ts +1 -0
  76. package/dist/crypto/index.js +6 -2
  77. package/dist/design-canvas/index.js +5 -3
  78. package/dist/design-canvas/index.js.map +1 -1
  79. package/dist/design-canvas-react/engine.js +7 -5
  80. package/dist/design-canvas-react/index.js +14 -12
  81. package/dist/design-canvas-react/index.js.map +1 -1
  82. package/dist/design-canvas-react/lazy.js +1 -1
  83. package/dist/eval/index.d.ts +4 -0
  84. package/dist/eval/index.js +125 -0
  85. package/dist/eval/index.js.map +1 -1
  86. package/dist/eval/persona-driver.d.ts +37 -0
  87. package/dist/eval/research-plan.d.ts +25 -0
  88. package/dist/eval/research-plan.js +55 -0
  89. package/dist/eval/research-plan.js.map +1 -0
  90. package/dist/eval/scorecard.d.ts +38 -0
  91. package/dist/forms/blank.d.ts +2 -2
  92. package/dist/forms/index.js +4 -5
  93. package/dist/forms/index.js.map +1 -1
  94. package/dist/hosted-agent/application.js +2 -2
  95. package/dist/interactions/index.js +3 -3
  96. package/dist/knowledge/prelaunch-audit.d.ts +17 -0
  97. package/dist/knowledge/prelaunch-audit.js +67 -0
  98. package/dist/knowledge/prelaunch-audit.js.map +1 -0
  99. package/dist/media/drizzle.d.ts +207 -0
  100. package/dist/media/drizzle.js +26 -0
  101. package/dist/media/drizzle.js.map +1 -0
  102. package/dist/media/generate-request.d.ts +53 -0
  103. package/dist/media/generation-record.d.ts +68 -0
  104. package/dist/media/index.d.ts +13 -0
  105. package/dist/media/index.js +653 -0
  106. package/dist/media/index.js.map +1 -0
  107. package/dist/media/model-catalog.d.ts +109 -0
  108. package/dist/media/router-client.d.ts +40 -0
  109. package/dist/media/router-generation.d.ts +44 -0
  110. package/dist/media/speech-script.d.ts +20 -0
  111. package/dist/openui/index.js +1 -1
  112. package/dist/operator/index.js +4 -5
  113. package/dist/operator/index.js.map +1 -1
  114. package/dist/plans/decision.d.ts +48 -0
  115. package/dist/plans/drizzle.d.ts +25 -0
  116. package/dist/plans/drizzle.js +97 -0
  117. package/dist/plans/drizzle.js.map +1 -0
  118. package/dist/plans/index.d.ts +1 -1
  119. package/dist/plans/index.js +11 -3
  120. package/dist/platform/billing-config.d.ts +22 -0
  121. package/dist/platform/billing-config.js +36 -0
  122. package/dist/platform/billing-config.js.map +1 -0
  123. package/dist/platform/index.js +13 -11
  124. package/dist/platform/index.js.map +1 -1
  125. package/dist/preset-cloudflare/index.js +2 -1
  126. package/dist/preset-cloudflare/index.js.map +1 -1
  127. package/dist/profile/index.js +4 -5
  128. package/dist/profile/index.js.map +1 -1
  129. package/dist/public-consultation/index.d.ts +1 -1
  130. package/dist/public-consultation/index.js +13 -11
  131. package/dist/public-consultation/index.js.map +1 -1
  132. package/dist/runtime/telemetry-cap.d.ts +24 -0
  133. package/dist/runtime/telemetry-cap.js +36 -0
  134. package/dist/runtime/telemetry-cap.js.map +1 -0
  135. package/dist/sandbox/index.js +12 -9
  136. package/dist/sequences/index.js +4 -2
  137. package/dist/sequences/index.js.map +1 -1
  138. package/dist/skills-placement/box.d.ts +50 -0
  139. package/dist/skills-placement/box.js +204 -0
  140. package/dist/skills-placement/box.js.map +1 -0
  141. package/dist/skills-placement/index.js +8 -96
  142. package/dist/skills-placement/index.js.map +1 -1
  143. package/dist/spend/budget.d.ts +13 -0
  144. package/dist/spend/drizzle.d.ts +55 -0
  145. package/dist/spend/drizzle.js +131 -0
  146. package/dist/spend/drizzle.js.map +1 -0
  147. package/dist/spend/index.d.ts +2 -1
  148. package/dist/spend/index.js +77 -58
  149. package/dist/spend/index.js.map +1 -1
  150. package/dist/spend/platform-settlements.d.ts +46 -0
  151. package/dist/stream/index.js +19 -19
  152. package/dist/studio/generated-media/index.d.ts +6 -0
  153. package/dist/studio/generated-media/index.js +590 -0
  154. package/dist/studio/generated-media/index.js.map +1 -0
  155. package/dist/studio/generated-media/output.d.ts +27 -0
  156. package/dist/studio/generated-media/store.d.ts +175 -0
  157. package/dist/studio-react/download-generations.d.ts +7 -0
  158. package/dist/studio-react/index.d.ts +1 -0
  159. package/dist/studio-react/index.js +85 -0
  160. package/dist/studio-react/index.js.map +1 -1
  161. package/dist/studio-react/use-studio-route.d.ts +44 -0
  162. package/dist/teams/invitations-api.d.ts +4 -0
  163. package/dist/teams/invitations-api.js +44 -32
  164. package/dist/teams/invitations-api.js.map +1 -1
  165. package/dist/theme/dom.d.ts +22 -0
  166. package/dist/theme/dom.js +18 -0
  167. package/dist/theme/dom.js.map +1 -0
  168. package/dist/vault/collaboration.d.ts +83 -0
  169. package/dist/vault/collaboration.js +215 -0
  170. package/dist/vault/collaboration.js.map +1 -0
  171. package/dist/vault/server.js +6 -53
  172. package/dist/vault/server.js.map +1 -1
  173. package/dist/vault/store/coordinator.d.ts +64 -0
  174. package/dist/vault/store/index.d.ts +12 -0
  175. package/dist/vault/store/index.js +1202 -0
  176. package/dist/vault/store/index.js.map +1 -0
  177. package/dist/vault/store/paths.d.ts +65 -0
  178. package/dist/vault/store/revisions.d.ts +211 -0
  179. package/dist/vault/store/sandbox-sync.d.ts +74 -0
  180. package/dist/vault/store/store.d.ts +161 -0
  181. package/dist/vault/store/tree.d.ts +11 -0
  182. package/dist/web/entry-server.d.ts +7 -0
  183. package/dist/web/entry-server.js +29 -0
  184. package/dist/web/entry-server.js.map +1 -0
  185. package/dist/web/fetch-guard.d.ts +6 -0
  186. package/dist/web/index.d.ts +3 -0
  187. package/dist/web/index.js +20 -4
  188. package/dist/web/mime.d.ts +16 -0
  189. package/dist/web/rate-limit.d.ts +25 -0
  190. package/dist/web/timeout.d.ts +9 -0
  191. package/dist/web-react/agent-profile-editor.js +3 -3
  192. package/dist/web-react/api-access-panel.d.ts +4 -2
  193. package/dist/web-react/document.d.ts +41 -0
  194. package/dist/web-react/document.js +103 -0
  195. package/dist/web-react/document.js.map +1 -0
  196. package/dist/web-react/index.js +31 -31
  197. package/dist/workspace-react/index.js +5 -5
  198. package/package.json +95 -4
  199. package/dist/DesignCanvas-OW3W2QXW.js +0 -13
  200. package/dist/DesignCanvasEditor-TCHZF25W.js +0 -16
  201. package/dist/chunk-5Y7Z5G3Y.js.map +0 -1
  202. package/dist/chunk-7HZCFG2A.js.map +0 -1
  203. package/dist/chunk-7KKOFMLD.js.map +0 -1
  204. package/dist/chunk-FENBDSIW.js.map +0 -1
  205. package/dist/chunk-LQYIBL3G.js.map +0 -1
  206. /package/dist/{DesignCanvas-OW3W2QXW.js.map → DesignCanvas-L6J72JQ2.js.map} +0 -0
  207. /package/dist/{DesignCanvasEditor-TCHZF25W.js.map → DesignCanvasEditor-QFQD63MR.js.map} +0 -0
  208. /package/dist/{chunk-MY3EJJ6Y.js.map → chunk-4FEH6266.js.map} +0 -0
  209. /package/dist/{chunk-X556WVBG.js.map → chunk-4ZSLX3LY.js.map} +0 -0
  210. /package/dist/{chunk-VBKP2NLI.js.map → chunk-BTKI4XMM.js.map} +0 -0
  211. /package/dist/{chunk-63QAQP7I.js.map → chunk-CNBVWPQC.js.map} +0 -0
  212. /package/dist/{chunk-A3KPDLSF.js.map → chunk-EFPIHR6F.js.map} +0 -0
  213. /package/dist/{chunk-NMSAZFRL.js.map → chunk-H5GQMLHA.js.map} +0 -0
  214. /package/dist/{chunk-OQE6WMDP.js.map → chunk-HN6MZ2XL.js.map} +0 -0
  215. /package/dist/{chunk-TCGZFSN5.js.map → chunk-KH4QSBNI.js.map} +0 -0
  216. /package/dist/{chunk-JH3CKHF4.js.map → chunk-KJODHPWM.js.map} +0 -0
  217. /package/dist/{chunk-VBWYH7UZ.js.map → chunk-NHYRIM4I.js.map} +0 -0
  218. /package/dist/{chunk-EWOJATDS.js.map → chunk-PDD5A43Y.js.map} +0 -0
  219. /package/dist/{chunk-23JUSUUB.js.map → chunk-RZLCBWGG.js.map} +0 -0
  220. /package/dist/{chunk-Y4W6GK5X.js.map → chunk-UGFCLD32.js.map} +0 -0
  221. /package/dist/{chunk-ZGUXI5SI.js.map → chunk-VUBJZEZB.js.map} +0 -0
  222. /package/dist/{chunk-JK7R7BZQ.js.map → chunk-ZWJ3SZ2G.js.map} +0 -0
@@ -0,0 +1,55 @@
1
+ // src/eval/research-plan.ts
2
+ import { mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "fs";
3
+ import { join, resolve } from "path";
4
+ import { productBenchmarkRepoIdentity } from "@tangle-network/agent-eval";
5
+ function researchCliArg(argv, name) {
6
+ const idx = argv.indexOf(`--${name}`);
7
+ if (idx >= 0 && idx + 1 < argv.length) return argv[idx + 1];
8
+ const flat = argv.find((entry) => entry.startsWith(`--${name}=`));
9
+ return flat ? flat.split("=").slice(1).join("=") : void 0;
10
+ }
11
+ function latestRunDir(root) {
12
+ const entries = readdirSync(root, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => join(root, entry.name)).sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs);
13
+ const latest = entries[0];
14
+ if (!latest) throw new Error(`no run directories under ${root}`);
15
+ return latest;
16
+ }
17
+ function packageVersion(name) {
18
+ const pkg = JSON.parse(readFileSync(resolve("package.json"), "utf8"));
19
+ return pkg.dependencies?.[name] ?? pkg.devDependencies?.[name] ?? "unknown";
20
+ }
21
+ function writeResearchPlan(outDir, config) {
22
+ const plan = {
23
+ schemaVersion: 1,
24
+ projectId: config.projectId,
25
+ benchmarkId: config.benchmarkId,
26
+ repo: productBenchmarkRepoIdentity(),
27
+ substrate: {
28
+ agentEval: packageVersion("@tangle-network/agent-eval"),
29
+ agentRuntime: packageVersion("@tangle-network/agent-runtime"),
30
+ agentInterface: packageVersion("@tangle-network/agent-interface"),
31
+ sandbox: packageVersion("@tangle-network/sandbox")
32
+ },
33
+ profiles: [{ id: config.profileId, profileHash: "planned", agentProfilePath: config.agentProfilePath }],
34
+ arms: ["baseline-generic", "production-profile", "policy-resource-long", "policy-resource-short"].map((id) => ({
35
+ id,
36
+ profileId: config.profileId,
37
+ mutableSurfaces: id.startsWith("policy-resource") ? ["resources.files"] : ["prompt"],
38
+ policyAxes: { carrier: id.startsWith("policy-resource") ? "resource-file" : "profile" }
39
+ })),
40
+ scenarios: config.scenarios,
41
+ budgets: { maxUsd: 0, maxCells: 0, maxWallMs: 0 },
42
+ expectedArtifactDir: resolve(outDir)
43
+ };
44
+ mkdirSync(outDir, { recursive: true });
45
+ const path = join(outDir, "product-benchmark-manifest.json");
46
+ writeFileSync(path, `${JSON.stringify(plan, null, 2)}
47
+ `);
48
+ return path;
49
+ }
50
+ export {
51
+ latestRunDir,
52
+ researchCliArg,
53
+ writeResearchPlan
54
+ };
55
+ //# sourceMappingURL=research-plan.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/eval/research-plan.ts"],"sourcesContent":["/**\n * No-spend research plan: the product-benchmark manifest an app writes before\n * any paid cell runs (zero budget, the standard four arms), plus the small CLI\n * helpers its `eval/research-package.ts` wrapper shares.\n *\n * Server-side only (node:fs). The app owns the project and benchmark ids, the\n * profile path and the scenario list; agent-eval owns the manifest shape and\n * the repo identity.\n */\n\nimport { mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport { productBenchmarkRepoIdentity, type ProductBenchmarkManifest } from '@tangle-network/agent-eval'\n\n/** Value of `--name value` or `--name=value`, or undefined when absent. */\nexport function researchCliArg(argv: readonly string[], name: string): string | undefined {\n const idx = argv.indexOf(`--${name}`)\n if (idx >= 0 && idx + 1 < argv.length) return argv[idx + 1]\n const flat = argv.find((entry) => entry.startsWith(`--${name}=`))\n return flat ? flat.split('=').slice(1).join('=') : undefined\n}\n\n/** The most recently modified directory under `root`; throws when there is none. */\nexport function latestRunDir(root: string): string {\n const entries = readdirSync(root, { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry) => join(root, entry.name))\n .sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs)\n const latest = entries[0]\n if (!latest) throw new Error(`no run directories under ${root}`)\n return latest\n}\n\nfunction packageVersion(name: string): string {\n const pkg = JSON.parse(readFileSync(resolve('package.json'), 'utf8')) as {\n dependencies?: Record<string, string>\n devDependencies?: Record<string, string>\n }\n return pkg.dependencies?.[name] ?? pkg.devDependencies?.[name] ?? 'unknown'\n}\n\nexport interface ResearchPlanConfig {\n projectId: string\n benchmarkId: string\n /** Profile id the arms attach to. */\n profileId: string\n /** Repo-relative path of the product's agent profile source. */\n agentProfilePath: string\n scenarios: ProductBenchmarkManifest['scenarios']\n}\n\n/** Write `<outDir>/product-benchmark-manifest.json` with zero budget; returns its path. */\nexport function writeResearchPlan(outDir: string, config: ResearchPlanConfig): string {\n const plan: ProductBenchmarkManifest = {\n schemaVersion: 1,\n projectId: config.projectId,\n benchmarkId: config.benchmarkId,\n repo: productBenchmarkRepoIdentity(),\n substrate: {\n agentEval: packageVersion('@tangle-network/agent-eval'),\n agentRuntime: packageVersion('@tangle-network/agent-runtime'),\n agentInterface: packageVersion('@tangle-network/agent-interface'),\n sandbox: packageVersion('@tangle-network/sandbox'),\n },\n profiles: [{ id: config.profileId, profileHash: 'planned', agentProfilePath: config.agentProfilePath }],\n arms: ['baseline-generic', 'production-profile', 'policy-resource-long', 'policy-resource-short'].map((id) => ({\n id,\n profileId: config.profileId,\n mutableSurfaces: id.startsWith('policy-resource') ? ['resources.files'] : ['prompt'],\n policyAxes: { carrier: id.startsWith('policy-resource') ? 'resource-file' : 'profile' },\n })),\n scenarios: config.scenarios,\n budgets: { maxUsd: 0, maxCells: 0, maxWallMs: 0 },\n expectedArtifactDir: resolve(outDir),\n }\n mkdirSync(outDir, { recursive: true })\n const path = join(outDir, 'product-benchmark-manifest.json')\n writeFileSync(path, `${JSON.stringify(plan, null, 2)}\\n`)\n return path\n}\n"],"mappings":";AAUA,SAAS,WAAW,cAAc,aAAa,UAAU,qBAAqB;AAC9E,SAAS,MAAM,eAAe;AAC9B,SAAS,oCAAmE;AAGrE,SAAS,eAAe,MAAyB,MAAkC;AACxF,QAAM,MAAM,KAAK,QAAQ,KAAK,IAAI,EAAE;AACpC,MAAI,OAAO,KAAK,MAAM,IAAI,KAAK,OAAQ,QAAO,KAAK,MAAM,CAAC;AAC1D,QAAM,OAAO,KAAK,KAAK,CAAC,UAAU,MAAM,WAAW,KAAK,IAAI,GAAG,CAAC;AAChE,SAAO,OAAO,KAAK,MAAM,GAAG,EAAE,MAAM,CAAC,EAAE,KAAK,GAAG,IAAI;AACrD;AAGO,SAAS,aAAa,MAAsB;AACjD,QAAM,UAAU,YAAY,MAAM,EAAE,eAAe,KAAK,CAAC,EACtD,OAAO,CAAC,UAAU,MAAM,YAAY,CAAC,EACrC,IAAI,CAAC,UAAU,KAAK,MAAM,MAAM,IAAI,CAAC,EACrC,KAAK,CAAC,GAAG,MAAM,SAAS,CAAC,EAAE,UAAU,SAAS,CAAC,EAAE,OAAO;AAC3D,QAAM,SAAS,QAAQ,CAAC;AACxB,MAAI,CAAC,OAAQ,OAAM,IAAI,MAAM,4BAA4B,IAAI,EAAE;AAC/D,SAAO;AACT;AAEA,SAAS,eAAe,MAAsB;AAC5C,QAAM,MAAM,KAAK,MAAM,aAAa,QAAQ,cAAc,GAAG,MAAM,CAAC;AAIpE,SAAO,IAAI,eAAe,IAAI,KAAK,IAAI,kBAAkB,IAAI,KAAK;AACpE;AAaO,SAAS,kBAAkB,QAAgB,QAAoC;AACpF,QAAM,OAAiC;AAAA,IACrC,eAAe;AAAA,IACf,WAAW,OAAO;AAAA,IAClB,aAAa,OAAO;AAAA,IACpB,MAAM,6BAA6B;AAAA,IACnC,WAAW;AAAA,MACT,WAAW,eAAe,4BAA4B;AAAA,MACtD,cAAc,eAAe,+BAA+B;AAAA,MAC5D,gBAAgB,eAAe,iCAAiC;AAAA,MAChE,SAAS,eAAe,yBAAyB;AAAA,IACnD;AAAA,IACA,UAAU,CAAC,EAAE,IAAI,OAAO,WAAW,aAAa,WAAW,kBAAkB,OAAO,iBAAiB,CAAC;AAAA,IACtG,MAAM,CAAC,oBAAoB,sBAAsB,wBAAwB,uBAAuB,EAAE,IAAI,CAAC,QAAQ;AAAA,MAC7G;AAAA,MACA,WAAW,OAAO;AAAA,MAClB,iBAAiB,GAAG,WAAW,iBAAiB,IAAI,CAAC,iBAAiB,IAAI,CAAC,QAAQ;AAAA,MACnF,YAAY,EAAE,SAAS,GAAG,WAAW,iBAAiB,IAAI,kBAAkB,UAAU;AAAA,IACxF,EAAE;AAAA,IACF,WAAW,OAAO;AAAA,IAClB,SAAS,EAAE,QAAQ,GAAG,UAAU,GAAG,WAAW,EAAE;AAAA,IAChD,qBAAqB,QAAQ,MAAM;AAAA,EACrC;AACA,YAAU,QAAQ,EAAE,WAAW,KAAK,CAAC;AACrC,QAAM,OAAO,KAAK,QAAQ,iCAAiC;AAC3D,gBAAc,MAAM,GAAG,KAAK,UAAU,MAAM,MAAM,CAAC,CAAC;AAAA,CAAI;AACxD,SAAO;AACT;","names":[]}
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Scorecard wiring: fold a benchmark's `RunRecord[]` into agent-eval's
3
+ * `(scenarioId x profileHash)` scorecard timeline.
4
+ *
5
+ * The scorecard is an append-only JSONL log, one line per (cell, commit).
6
+ * {@link recordScorecardAndDiff} appends a run and diffs the latest entries
7
+ * against their predecessors, answering "did this commit regress any persona on
8
+ * the same profile?", which a single run's pass/fail gate cannot. The app owns
9
+ * the behaviour-only `AgentProfile` it keys the scorecard on.
10
+ */
11
+ import { type AgentProfile, type RunRecord, type ScorecardDiff } from '@tangle-network/agent-eval';
12
+ export interface ScorecardWiringInput {
13
+ scorecardPath: string;
14
+ runs: RunRecord[];
15
+ profile: AgentProfile;
16
+ commitSha: string;
17
+ /** Defaults to `new Date().toISOString()`. */
18
+ timestamp?: string;
19
+ }
20
+ export interface ScorecardWiringResult {
21
+ /** Number of cell entries appended to the log this run (one per scenario). */
22
+ appendedCells: number;
23
+ /** Profile hash this run keyed into. */
24
+ profileHash: string;
25
+ /** Diff of the latest entries against their predecessors. */
26
+ diff: ScorecardDiff;
27
+ /** Human-readable diff block, what a PR or CI run prints. */
28
+ formatted: string;
29
+ /** True when any cell's verdict is `regressed`. */
30
+ regressed: boolean;
31
+ }
32
+ /**
33
+ * Append the run to the scorecard, fold the log, diff, and surface a
34
+ * regression flag. Pure I/O over the JSONL log, no LLM calls. Concurrent eval
35
+ * campaigns are safe: appends are line-atomic and `loadScorecard` skips
36
+ * malformed lines rather than failing closed.
37
+ */
38
+ export declare function recordScorecardAndDiff(input: ScorecardWiringInput): ScorecardWiringResult;
@@ -36,8 +36,8 @@ export interface FormBlank {
36
36
  * and no error at all.
37
37
  */
38
38
  export declare function decodeFormBlank(blank: FormBlank): Uint8Array;
39
- /** Lowercase-hex SHA-256 of a byte range. */
40
- export declare function sha256Hex(bytes: Uint8Array): Promise<string>;
39
+ import { sha256Hex } from '../crypto/digest';
40
+ export { sha256Hex };
41
41
  /**
42
42
  * Prove the embedded bytes are the file the registry was derived from.
43
43
  *
@@ -1,3 +1,7 @@
1
+ import {
2
+ sha256Hex
3
+ } from "../chunk-HY57QRRW.js";
4
+
1
5
  // src/forms/blank.ts
2
6
  var decoded = /* @__PURE__ */ new WeakMap();
3
7
  function decodeFormBlank(blank) {
@@ -14,11 +18,6 @@ function decodeFormBlank(blank) {
14
18
  decoded.set(blank, bytes);
15
19
  return bytes;
16
20
  }
17
- async function sha256Hex(bytes) {
18
- const view = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
19
- const digest = await crypto.subtle.digest("SHA-256", view);
20
- return Array.from(new Uint8Array(digest)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
21
- }
22
21
  async function assertFormBlankIntegrity(blank) {
23
22
  const bytes = decodeFormBlank(blank);
24
23
  const digest = await sha256Hex(bytes);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/forms/blank.ts","../../src/forms/registry.ts","../../src/forms/fill.ts","../../src/forms/verify.ts"],"sourcesContent":["/**\n * The blank a form is filled from — embedded, pinned, and never fetched at\n * fill time.\n *\n * A renderer that downloads its own blank works on a developer laptop and\n * fails in both places these products actually run: a Cloudflare Worker has no\n * business making an outbound call mid-request, and a sandbox container's\n * egress proxy refuses the agencies' own hosts (measured on tax-agent:\n * `www.irs.gov` CONNECT tunnel 403 while pypi and npm returned 200). A\n * form-filler that cannot reach its blank does not fail loudly — it degrades\n * into an agent describing the form in prose, which is the exact behaviour\n * this module exists to end.\n *\n * Pinning the bytes by digest also pins the artifact: a filing made against\n * the 2025 revision is reproducible from the committed bytes, and an agency\n * revision shows up as a diff of the recorded checksum instead of silently\n * changing under a live URL.\n */\n\n/** A blank form's bytes, base64-encoded, with the provenance to check them. */\nexport interface FormBlank {\n /** Base64 of the PDF exactly as the agency published it. */\n base64: string\n /** SHA-256 of the decoded bytes, lowercase hex. */\n sha256: string\n /** Where the bytes came from. Provenance for a reviewer, not a fetch target. */\n sourceUrl: string\n /** Decoded length in bytes. A cheap first check that the base64 is intact. */\n byteLength: number\n}\n\nconst decoded = new WeakMap<FormBlank, Uint8Array>()\n\n/**\n * Decode a blank once per isolate.\n *\n * Keyed on the blank OBJECT rather than a module-level singleton, because a\n * product carries several forms and a single cached slot would serve one\n * form's bytes for another's fill — a failure that produces a plausible PDF\n * and no error at all.\n */\nexport function decodeFormBlank(blank: FormBlank): Uint8Array {\n const cached = decoded.get(blank)\n if (cached) return cached\n const binary = atob(blank.base64)\n const bytes = new Uint8Array(binary.length)\n for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index)\n if (bytes.length !== blank.byteLength) {\n throw new Error(\n `blank form is ${bytes.length} bytes but declares ${blank.byteLength} — the embedded base64 is truncated`,\n )\n }\n decoded.set(blank, bytes)\n return bytes\n}\n\n/** Lowercase-hex SHA-256 of a byte range. */\nexport async function sha256Hex(bytes: Uint8Array): Promise<string> {\n const view = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength)\n const digest = await crypto.subtle.digest('SHA-256', view as ArrayBuffer)\n return Array.from(new Uint8Array(digest))\n .map((byte) => byte.toString(16).padStart(2, '0'))\n .join('')\n}\n\n/**\n * Prove the embedded bytes are the file the registry was derived from.\n *\n * Run this in a test, not on the fill path: a registry is only meaningful\n * against the exact revision it was derived from, and a blank swapped for a\n * newer revision moves every widget without changing a single field name.\n */\nexport async function assertFormBlankIntegrity(blank: FormBlank): Promise<void> {\n const bytes = decodeFormBlank(blank)\n const digest = await sha256Hex(bytes)\n if (digest !== blank.sha256) {\n throw new Error(\n `blank form digest is ${digest} but the registry was derived against ${blank.sha256} (${blank.sourceUrl})`,\n )\n }\n}\n","/**\n * The slot → widget registry: the one place a form filler can be wrong\n * invisibly, and the one place a language model is never allowed to write.\n *\n * WHY THE MODEL NEVER NAMES A WIDGET\n *\n * An agency PDF's widget names carry no meaning a reader can check —\n * `topmostSubform[0].Page2[0].f2_06[0]` on an IRS form, `registered2` on a\n * Texas SOS form. A model asked for one produces a plausible string, and the\n * natural audit — read the field back by the name you just wrote — PASSES\n * REGARDLESS, because it re-reads the invention rather than checking it.\n * Measured on tax-agent: three values written to model-chosen widgets landed\n * in \"Combat zone\" and the date boxes, and the audit reported 3 passed /\n * 0 failed.\n *\n * So the model supplies SEMANTIC SLOTS — a form line, a named box — and the\n * platform owns the slot → widget mapping. A misplaced figure stops being an\n * invention that survives review and becomes something that cannot be\n * expressed at all.\n *\n * WHY A SLOT CARRIES A LABEL, AND WHY THE LABEL DECLARES ITS BASIS\n *\n * A registry is still just a table, and a hand-typed table drifts (tax-agent's\n * form catalog carried wrong page counts for 7 of 17 forms). So every slot\n * states the label it believes it is aiming at, and states where that belief\n * came from:\n *\n * - `labelBasis: 'widget'` — the label must match the widget's OWN `/TU`\n * accessibility text inside the PDF. `checkRegistryAgainstBlank` re-checks\n * it against the bytes, so a mis-aimed slot fails a test rather than\n * quietly printing in the wrong box. Every one of Texas Form 205's 64\n * widgets carries `/TU`, so its whole registry can be checked this way.\n * - `labelBasis: 'derived'` — the label came from somewhere else (an XFA\n * template, a published instruction sheet, a human reading the form) and\n * CANNOT be re-checked against the widget. It is evidence for a reviewer,\n * never proof. Measured on IRS f1040: 0 of 199 widgets carry `/TU` or\n * `/Alt`, so its labels can only ever be derived.\n *\n * Declaring the basis is the point. A guess presented as truth is how a second\n * self-confirming artifact gets built on top of the first one.\n */\n\nimport type { PDFDocument, PDFForm } from 'pdf-lib'\n\n/** What kind of widget a slot writes to. */\nexport type FormSlotKind = 'text' | 'checkbox'\n\n/** How a slot's text value is rendered into the box. */\nexport type FormSlotFormat = 'text' | 'currency'\n\n/** Where a slot's `label` came from, and therefore what it can prove. */\nexport type FormLabelBasis = 'widget' | 'derived'\n\n/** One semantic slot: what a caller supplies, and where the platform puts it. */\nexport interface FormSlot {\n /** The name a caller (and a model) uses: `15`, `entity_name`, `agent_is_org`. */\n slot: string\n /**\n * The AcroForm widget path(s) this slot writes.\n *\n * A LIST because one semantic value legitimately occupies several boxes: IRS\n * Form 1040 states adjusted gross income twice, at the foot of page 1 and\n * the head of page 2, so page 2's arithmetic stands alone. Writing only one\n * of them leaves \"subtract line 14 from line 11b\" pointing at an empty box.\n */\n fields: readonly string[]\n kind: FormSlotKind\n /** How the value is rendered. Ignored for `checkbox`. Default `'text'`. */\n format?: FormSlotFormat\n /** What this slot is, in the form's own words. */\n label: string\n /** Whether `label` is checkable against the PDF, or merely recorded. */\n labelBasis: FormLabelBasis\n}\n\n/** A form's complete slot table, pinned to the revision it was derived from. */\nexport interface FormRegistry {\n /** Stable id for the form: `us-irs-1040`, `us-tx-sos-205`. */\n form: string\n /** The agency's own revision marker: `2025`, `Rev. 12-21`. */\n revision: string\n slots: readonly FormSlot[]\n}\n\n/** Why a registry does not match the blank it claims to describe. */\nexport type RegistryProblemCode =\n | 'no_slots'\n | 'no_fields'\n | 'missing_field'\n | 'wrong_kind'\n | 'label_mismatch'\n | 'duplicate_field'\n | 'duplicate_slot'\n\nexport interface RegistryProblem {\n slot: string\n field?: string\n code: RegistryProblemCode\n detail: string\n}\n\nexport interface RegistryCheckResult {\n ok: boolean\n /** Widgets actually compared against the PDF. Zero means nothing was proven. */\n checked: number\n /** Slots whose label was compared against the widget's own `/TU`. */\n labelsChecked: number\n problems: RegistryProblem[]\n}\n\n/** The `/TU` accessibility text a widget carries, if any. */\nexport async function widgetLabel(form: PDFForm, field: string): Promise<string | undefined> {\n const { PDFName, PDFHexString, PDFString } = await import('pdf-lib')\n const target = form.getFieldMaybe(field)\n if (!target) return undefined\n const tooltip = target.acroField.dict.get(PDFName.of('TU'))\n if (tooltip instanceof PDFString || tooltip instanceof PDFHexString) return tooltip.decodeText()\n return undefined\n}\n\n/** Normalize whitespace so a label comparison survives the agency's own typing. */\nfunction normalizeLabel(value: string): string {\n return value.replace(/\\s+/gu, ' ').trim().toLowerCase()\n}\n\n/**\n * Check a registry against the blank it claims to describe.\n *\n * This is the placement check. It runs in a test or in CI, never on the fill\n * path, and it is the ONLY thing that can catch a slot aimed at the wrong box\n * — reading a value back after writing it cannot, because it re-reads the same\n * name it wrote.\n *\n * It fails on ABSENCE, deliberately. tax-agent shipped an audit that silently\n * skipped an expected field the PDF did not expose, so a fill against entirely\n * wrong paths reported `passed=0 failed=0`. Here an empty registry, a slot\n * with no fields, and a field the PDF does not expose are each a problem with\n * a name, and `checked` is reported so a caller can see how much was actually\n * proven rather than trusting a bare `ok: true`.\n */\nexport async function checkRegistryAgainstBlank(args: {\n /** The blank's bytes. Decode a `FormBlank` with `decodeFormBlank` first. */\n pdf: Uint8Array\n registry: FormRegistry\n}): Promise<RegistryCheckResult> {\n const { PDFDocument } = await import('pdf-lib')\n const document: PDFDocument = await PDFDocument.load(args.pdf, { updateMetadata: false })\n const form = document.getForm()\n\n // The PDF's OWN field list, enumerated independently of anything the\n // registry claims. Every lookup below resolves against this, so a registry\n // naming a field that does not exist cannot pass by being skipped.\n const exposed = new Map<string, string>()\n for (const field of form.getFields()) exposed.set(field.getName(), field.constructor.name)\n\n const problems: RegistryProblem[] = []\n const claimedBy = new Map<string, string>()\n const seenSlots = new Set<string>()\n let checked = 0\n let labelsChecked = 0\n\n if (args.registry.slots.length === 0) {\n problems.push({\n slot: '(registry)',\n code: 'no_slots',\n detail: `registry ${args.registry.form} declares no slots — it can prove nothing and fill nothing`,\n })\n }\n\n for (const slot of args.registry.slots) {\n if (seenSlots.has(slot.slot)) {\n problems.push({\n slot: slot.slot,\n code: 'duplicate_slot',\n detail: `slot ${slot.slot} is declared twice; the later entry silently wins at fill time`,\n })\n }\n seenSlots.add(slot.slot)\n\n if (slot.fields.length === 0) {\n problems.push({\n slot: slot.slot,\n code: 'no_fields',\n detail: `slot ${slot.slot} names no widget, so a value supplied for it goes nowhere`,\n })\n continue\n }\n\n for (const field of slot.fields) {\n const previous = claimedBy.get(field)\n if (previous !== undefined && previous !== slot.slot) {\n problems.push({\n slot: slot.slot,\n field,\n code: 'duplicate_field',\n detail: `${field} is claimed by both slot ${previous} and slot ${slot.slot}`,\n })\n }\n claimedBy.set(field, slot.slot)\n\n const actualKind = exposed.get(field)\n if (actualKind === undefined) {\n problems.push({\n slot: slot.slot,\n field,\n code: 'missing_field',\n detail: `${args.registry.form} has no widget named ${field}`,\n })\n continue\n }\n checked += 1\n\n const expectedKind = slot.kind === 'checkbox' ? 'PDFCheckBox' : 'PDFTextField'\n if (actualKind !== expectedKind) {\n problems.push({\n slot: slot.slot,\n field,\n code: 'wrong_kind',\n detail: `${field} is a ${actualKind}, but slot ${slot.slot} declares ${slot.kind}`,\n })\n continue\n }\n\n if (slot.labelBasis !== 'widget') continue\n const onWidget = await widgetLabel(form, field)\n if (onWidget === undefined) {\n problems.push({\n slot: slot.slot,\n field,\n code: 'label_mismatch',\n detail: `slot ${slot.slot} claims labelBasis 'widget' but ${field} carries no /TU text to check it against — the label is derived, not checked`,\n })\n continue\n }\n labelsChecked += 1\n if (normalizeLabel(onWidget) !== normalizeLabel(slot.label)) {\n problems.push({\n slot: slot.slot,\n field,\n code: 'label_mismatch',\n detail: `${field} is labelled ${JSON.stringify(onWidget)} but slot ${slot.slot} claims ${JSON.stringify(slot.label)}`,\n })\n }\n }\n }\n\n return { ok: problems.length === 0, checked, labelsChecked, problems }\n}\n","/**\n * Fill a real agency PDF from a slot → value map.\n *\n * Mechanically this is `pdf-lib` writing an AcroForm: TypeScript, no\n * container, no Python, no network. That matters because it is the only shape\n * that runs everywhere these products run — a Cloudflare Worker (where 100% of\n * tax-agent's production work products were produced, with no sandbox at all)\n * and a sandbox container whose egress proxy refuses the agency's own host.\n *\n * The invariant it enforces is in `registry.ts`: the caller supplies SEMANTIC\n * SLOTS and never a widget name. Two consequences show up here.\n *\n * NOTHING IS SILENT. Every slot ends in `filled` or in `unfilled` with a code\n * and a reason. A value the caller supplied that never reached the page means\n * the document and the data disagree, which is the one thing a reviewer must\n * not have to discover by eye. That includes a registry naming a widget the\n * PDF does not expose: it is reported per-slot rather than crashing the render\n * or — worse — being skipped, which is how tax-agent once audited a fill\n * against entirely wrong paths as `passed=0 failed=0`.\n *\n * NO ON-STATE IS EVER AUTHORED. A checkbox's \"on\" name is a property of the\n * PDF and frequently a hex-escaped sentence: Texas Form 205's seven boxes are\n * `is#20an#20organization`, `initially#20has#20#20managers` (note the double\n * space), and four more like them. A caller that types one of those strings is\n * authoring something it cannot check, so a checkbox slot takes a BOOLEAN and\n * the widget's own on-value is read out of the file. The escaped spelling is\n * not handled — it is unrepresentable.\n */\n\nimport type { PDFCheckBox, PDFDocument, PDFTextField } from 'pdf-lib'\n\nimport type { FormRegistry, FormSlot } from './registry'\n\n/** One widget the fill actually wrote. */\nexport interface FilledWidget {\n slot: string\n field: string\n kind: FormSlot['kind']\n /** The value as the caller supplied it, before formatting. */\n value: unknown\n /** Exactly the text placed in the box. Absent for a checkbox. */\n text?: string\n /** Whether a checkbox was ticked. Absent for a text field. */\n checked?: boolean\n /** The widget's OWN on-state, decoded — read from the PDF, never authored. */\n onState?: string\n}\n\n/** Why a supplied value did not reach the page. */\nexport type UnfilledCode =\n | 'unknown_slot'\n | 'missing_field'\n | 'wrong_kind'\n | 'not_a_number'\n | 'not_a_boolean'\n | 'unformattable'\n\nexport interface UnfilledSlot {\n slot: string\n field?: string\n value: unknown\n code: UnfilledCode\n reason: string\n}\n\nexport interface FillFormResult {\n bytes: Uint8Array\n filled: FilledWidget[]\n unfilled: UnfilledSlot[]\n form: string\n revision: string\n}\n\nexport interface FillFormOptions {\n /** The blank's bytes. Decode a `FormBlank` with `decodeFormBlank` first. */\n pdf: Uint8Array\n registry: FormRegistry\n /** slot name → value. Keys the registry does not know are reported, not dropped. */\n values: Record<string, unknown>\n /**\n * Override how a text value becomes box text. Return `undefined` to fall\n * through to the built-in formatting for the slot's `format`.\n */\n formatText?: (value: unknown, slot: FormSlot) => string | undefined\n}\n\n/**\n * Format a figure the way a US agency form prints it: grouped thousands, two\n * decimals, negatives in parentheses.\n *\n * Two decimals rather than whole dollars because the caller's data carries\n * cents and a reviewer compares the document against that data — rounding here\n * would manufacture a disagreement between the two on every line with cents.\n */\nexport function formatFormCurrency(value: number): string {\n const magnitude = Math.abs(value).toLocaleString('en-US', {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })\n return value < 0 ? `(${magnitude})` : magnitude\n}\n\n/** A number, or a number written the way a form prints one (`$141,318.74`). */\nexport function parseFormAmount(value: unknown): number | undefined {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (typeof value !== 'string') return undefined\n const normalized = value.replace(/[$,\\s]/gu, '')\n if (!/^-?\\d+(?:\\.\\d+)?$/u.test(normalized)) return undefined\n const parsed = Number(normalized)\n return Number.isFinite(parsed) ? parsed : undefined\n}\n\n/**\n * A checkbox takes a boolean and nothing else.\n *\n * Strict on purpose. Accepting a truthy string would accept the widget's own\n * escaped on-state (`'is#20an#20organization'`) as \"true\", which is exactly\n * the authored-on-state this module refuses — and it would accept `'no'` as\n * true, silently ticking a box the caller meant to leave clear.\n */\nexport function parseFormBoolean(value: unknown): boolean | undefined {\n if (typeof value === 'boolean') return value\n if (typeof value !== 'string') return undefined\n const normalized = value.trim().toLowerCase()\n if (normalized === 'true' || normalized === 'yes') return true\n if (normalized === 'false' || normalized === 'no') return false\n return undefined\n}\n\nfunction textFor(\n value: unknown,\n slot: FormSlot,\n override: FillFormOptions['formatText'],\n): { text: string } | { code: UnfilledCode; reason: string } {\n const custom = override?.(value, slot)\n if (custom !== undefined) return { text: custom }\n if ((slot.format ?? 'text') === 'currency') {\n const amount = parseFormAmount(value)\n if (amount === undefined) return { code: 'not_a_number', reason: 'not a numeric amount' }\n return { text: formatFormCurrency(amount) }\n }\n if (typeof value === 'string') return { text: value }\n if (typeof value === 'number' && Number.isFinite(value)) return { text: String(value) }\n return { code: 'unformattable', reason: `cannot render a ${typeof value} into a text box` }\n}\n\n/**\n * Write a value map onto a blank, returning the bytes plus the exact\n * widget-by-widget account of what was and was not placed.\n */\nexport async function fillPdfForm(options: FillFormOptions): Promise<FillFormResult> {\n const { PDFCheckBox: CheckBox, PDFDocument, PDFName, PDFTextField: TextField } = await import('pdf-lib')\n\n // `updateMetadata: false` keeps the render deterministic — pdf-lib otherwise\n // stamps a ModDate, which would give the same values a different checksum on\n // every call and defeat content-addressed storage. It also keeps our\n // timestamps off the agency's document.\n const document: PDFDocument = await PDFDocument.load(options.pdf, { updateMetadata: false })\n const form = document.getForm()\n\n // Agency forms ship as AcroForm/XFA hybrids, and a reader that prefers the\n // XFA layer would draw the ORIGINAL empty form and show none of these\n // values. `getForm()` drops the XFA packet (pdf-lib does not support it), so\n // this asserts the property rather than trusting it to stay incidental.\n if (document.catalog.getOrCreateAcroForm().dict.has(PDFName.of('XFA'))) {\n throw new Error('filled form still carries an XFA layer — a viewer would draw the blank instead')\n }\n\n const bySlot = new Map(options.registry.slots.map((slot) => [slot.slot, slot]))\n const filled: FilledWidget[] = []\n const unfilled: UnfilledSlot[] = []\n\n for (const [name, value] of Object.entries(options.values)) {\n const slot = bySlot.get(name)\n if (!slot) {\n unfilled.push({\n slot: name,\n value,\n code: 'unknown_slot',\n reason: `${options.registry.form} has no slot named ${name}`,\n })\n continue\n }\n\n if (slot.kind === 'checkbox') {\n const checked = parseFormBoolean(value)\n if (checked === undefined) {\n unfilled.push({\n slot: name,\n value,\n code: 'not_a_boolean',\n reason: 'a checkbox takes true or false; a checkbox on-state is read from the PDF and is never supplied',\n })\n continue\n }\n for (const field of slot.fields) {\n const widget = form.getFieldMaybe(field)\n if (!widget) {\n unfilled.push({ slot: name, field, value, code: 'missing_field', reason: `${options.registry.form} has no widget named ${field}` })\n continue\n }\n if (!(widget instanceof CheckBox)) {\n unfilled.push({ slot: name, field, value, code: 'wrong_kind', reason: `${field} is a ${widget.constructor.name}, not a checkbox` })\n continue\n }\n const box = widget as PDFCheckBox\n // The widget's OWN on-state. Read, never authored: Texas Form 205's\n // are hex-escaped sentences, and a caller that typed one would be\n // asserting a fact about the file it cannot check.\n const onState = box.acroField.getOnValue()?.decodeText()\n if (checked) box.check()\n else box.uncheck()\n filled.push({ slot: name, field, kind: 'checkbox', value, checked, onState })\n }\n continue\n }\n\n const rendered = textFor(value, slot, options.formatText)\n if ('code' in rendered) {\n unfilled.push({ slot: name, value, code: rendered.code, reason: rendered.reason })\n continue\n }\n for (const field of slot.fields) {\n const widget = form.getFieldMaybe(field)\n if (!widget) {\n unfilled.push({ slot: name, field, value, code: 'missing_field', reason: `${options.registry.form} has no widget named ${field}` })\n continue\n }\n if (!(widget instanceof TextField)) {\n unfilled.push({ slot: name, field, value, code: 'wrong_kind', reason: `${field} is a ${widget.constructor.name}, not a text field` })\n continue\n }\n ;(widget as PDFTextField).setText(rendered.text)\n filled.push({ slot: name, field, kind: 'text', value, text: rendered.text })\n }\n }\n\n return {\n bytes: await document.save(),\n filled,\n unfilled,\n form: options.registry.form,\n revision: options.registry.revision,\n }\n}\n\n/**\n * What to tell the agent after a fill.\n *\n * Names the values that did NOT reach the page. Those are exactly the cases\n * where the document and the data disagree, and the agent is the only party\n * that can resolve it — returning a bare \"done\" hands a reviewer a form\n * missing values the data claims are on it.\n */\nexport function describeFormFill(result: FillFormResult): string {\n const count = result.filled.length\n const base = `Filled ${result.form} (${result.revision}) with ${count} ${count === 1 ? 'value' : 'values'}.`\n if (result.unfilled.length === 0) return base\n const detail = result.unfilled.map((entry) => `${entry.slot} (${entry.reason})`).join('; ')\n return `${base} NOT placed on the form: ${detail}. Those values are in the data but not on the document a reviewer opens.`\n}\n","/**\n * Read a filled form back and say, slot by slot, whether the document agrees\n * with the data it was built from.\n *\n * WHAT THIS PROVES, AND WHAT IT CANNOT\n *\n * This proves the WRITE LANDED: the value reached a real widget, that widget\n * exists in the produced file, and it holds the text or tick the data claims.\n * It does NOT prove PLACEMENT — that the widget is the right box on the page —\n * because it resolves the same field names the fill used. Reading a value back\n * by the name you just wrote passes even when the name was invented; measured\n * on tax-agent, an audit of that shape reported 3 passed / 0 failed for three\n * figures sitting in \"Combat zone\" and the date boxes.\n *\n * Placement is proven by `checkRegistryAgainstBlank`, which compares each\n * slot's claimed label against the widget's own `/TU` text inside the PDF.\n * The two checks are complements, and a product that runs only this one has\n * the audit that already failed once. That is stated here rather than in a\n * commit message because a future caller will otherwise reach for the\n * convenient half.\n *\n * FAILS ON ABSENCE. A registry field the produced PDF does not expose is\n * `missing_field`, and an empty `expected` map is `ok: false` — the\n * `passed=0 failed=0` verdict is the exact shape of the bug this replaces.\n */\n\nimport type { PDFCheckBox, PDFDocument, PDFTextField } from 'pdf-lib'\n\nimport { parseFormBoolean, formatFormCurrency, parseFormAmount } from './fill'\nimport { widgetLabel, type FormRegistry } from './registry'\n\nexport type SlotVerdict = 'ok' | 'unknown_slot' | 'missing_field' | 'wrong_kind' | 'not_written' | 'mismatch'\n\n/** What the slot's `label` is worth, checked against the produced file. */\nexport type LabelVerdict = 'matches_widget' | 'label_mismatch' | 'derived_unchecked' | 'no_widget_label'\n\nexport interface SlotVerification {\n slot: string\n field?: string\n verdict: SlotVerdict\n /** What the data says the box should hold. */\n expected?: string\n /** What the box actually holds, read out of the produced bytes. */\n actual?: string\n labelVerdict?: LabelVerdict\n label?: string\n}\n\nexport interface VerifyFormResult {\n ok: boolean\n /** Widgets actually read back. Zero means nothing was proven. */\n verified: number\n slots: SlotVerification[]\n}\n\nfunction expectedText(value: unknown, format: string | undefined): string {\n if (format === 'currency') {\n const amount = parseFormAmount(value)\n return amount === undefined ? String(value) : formatFormCurrency(amount)\n }\n return typeof value === 'number' ? String(value) : String(value)\n}\n\n/**\n * Verify a filled form against the value map it was filled from.\n *\n * `expected` is the SAME shape passed to `fillPdfForm` — deliberately, so a\n * caller cannot verify against a convenient restatement of what it wrote.\n */\nexport async function verifyFilledForm(args: {\n /** The PRODUCED bytes, not the blank. */\n pdf: Uint8Array\n registry: FormRegistry\n expected: Record<string, unknown>\n /** Slots the caller knowingly left out of `expected`; anything else is checked. */\n}): Promise<VerifyFormResult> {\n const { PDFCheckBox: CheckBox, PDFDocument, PDFTextField: TextField } = await import('pdf-lib')\n const document: PDFDocument = await PDFDocument.load(args.pdf, { updateMetadata: false })\n const form = document.getForm()\n\n // The produced file's OWN field list, enumerated before anything the\n // registry claims is consulted. A registry field absent from this set is a\n // failure, never a skip.\n const exposed = new Set(form.getFields().map((field) => field.getName()))\n\n const bySlot = new Map(args.registry.slots.map((slot) => [slot.slot, slot]))\n const slots: SlotVerification[] = []\n let verified = 0\n let ok = true\n\n for (const [name, value] of Object.entries(args.expected)) {\n const slot = bySlot.get(name)\n if (!slot) {\n slots.push({ slot: name, verdict: 'unknown_slot' })\n ok = false\n continue\n }\n for (const field of slot.fields) {\n if (!exposed.has(field)) {\n slots.push({ slot: name, field, verdict: 'missing_field' })\n ok = false\n continue\n }\n const widget = form.getField(field)\n const label = await widgetLabel(form, field)\n const labelVerdict: LabelVerdict =\n slot.labelBasis === 'derived'\n ? 'derived_unchecked'\n : label === undefined\n ? 'no_widget_label'\n : label.replace(/\\s+/gu, ' ').trim().toLowerCase() ===\n slot.label.replace(/\\s+/gu, ' ').trim().toLowerCase()\n ? 'matches_widget'\n : 'label_mismatch'\n if (labelVerdict === 'label_mismatch' || labelVerdict === 'no_widget_label') ok = false\n\n if (slot.kind === 'checkbox') {\n if (!(widget instanceof CheckBox)) {\n slots.push({ slot: name, field, verdict: 'wrong_kind', label, labelVerdict })\n ok = false\n continue\n }\n const want = parseFormBoolean(value)\n const got = (widget as PDFCheckBox).isChecked()\n const verdict: SlotVerdict = want === undefined ? 'mismatch' : got === want ? 'ok' : 'mismatch'\n if (verdict !== 'ok') ok = false\n else verified += 1\n slots.push({\n slot: name,\n field,\n verdict,\n expected: String(want),\n actual: String(got),\n label,\n labelVerdict,\n })\n continue\n }\n\n if (!(widget instanceof TextField)) {\n slots.push({ slot: name, field, verdict: 'wrong_kind', label, labelVerdict })\n ok = false\n continue\n }\n const want = expectedText(value, slot.format)\n const got = (widget as PDFTextField).getText() ?? ''\n const verdict: SlotVerdict = got === '' && want !== '' ? 'not_written' : got === want ? 'ok' : 'mismatch'\n if (verdict !== 'ok') ok = false\n else verified += 1\n slots.push({ slot: name, field, verdict, expected: want, actual: got, label, labelVerdict })\n }\n }\n\n // An audit that checked nothing must never report success. This is the\n // `passed=0 failed=0` verdict, refused by name.\n if (verified === 0) ok = false\n\n return { ok, verified, slots }\n}\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;AAAA,UACA;AAAA,QACF,CAAC;AACD;AAAA,MACF;AAEA,UAAI,EAAE,kBAAkB,YAAY;AAClC,cAAM,KAAK,EAAE,MAAM,MAAM,OAAO,SAAS,cAAc,OAAO,aAAa,CAAC;AAC5E,aAAK;AACL;AAAA,MACF;AACA,YAAM,OAAO,aAAa,OAAO,KAAK,MAAM;AAC5C,YAAM,MAAO,OAAwB,QAAQ,KAAK;AAClD,YAAM,UAAuB,QAAQ,MAAM,SAAS,KAAK,gBAAgB,QAAQ,OAAO,OAAO;AAC/F,UAAI,YAAY,KAAM,MAAK;AAAA,UACtB,aAAY;AACjB,YAAM,KAAK,EAAE,MAAM,MAAM,OAAO,SAAS,UAAU,MAAM,QAAQ,KAAK,OAAO,aAAa,CAAC;AAAA,IAC7F;AAAA,EACF;AAIA,MAAI,aAAa,EAAG,MAAK;AAEzB,SAAO,EAAE,IAAI,UAAU,MAAM;AAC/B;","names":["want","got","verdict"]}
1
+ {"version":3,"sources":["../../src/forms/blank.ts","../../src/forms/registry.ts","../../src/forms/fill.ts","../../src/forms/verify.ts"],"sourcesContent":["/**\n * The blank a form is filled from — embedded, pinned, and never fetched at\n * fill time.\n *\n * A renderer that downloads its own blank works on a developer laptop and\n * fails in both places these products actually run: a Cloudflare Worker has no\n * business making an outbound call mid-request, and a sandbox container's\n * egress proxy refuses the agencies' own hosts (measured on tax-agent:\n * `www.irs.gov` CONNECT tunnel 403 while pypi and npm returned 200). A\n * form-filler that cannot reach its blank does not fail loudly — it degrades\n * into an agent describing the form in prose, which is the exact behaviour\n * this module exists to end.\n *\n * Pinning the bytes by digest also pins the artifact: a filing made against\n * the 2025 revision is reproducible from the committed bytes, and an agency\n * revision shows up as a diff of the recorded checksum instead of silently\n * changing under a live URL.\n */\n\n/** A blank form's bytes, base64-encoded, with the provenance to check them. */\nexport interface FormBlank {\n /** Base64 of the PDF exactly as the agency published it. */\n base64: string\n /** SHA-256 of the decoded bytes, lowercase hex. */\n sha256: string\n /** Where the bytes came from. Provenance for a reviewer, not a fetch target. */\n sourceUrl: string\n /** Decoded length in bytes. A cheap first check that the base64 is intact. */\n byteLength: number\n}\n\nconst decoded = new WeakMap<FormBlank, Uint8Array>()\n\n/**\n * Decode a blank once per isolate.\n *\n * Keyed on the blank OBJECT rather than a module-level singleton, because a\n * product carries several forms and a single cached slot would serve one\n * form's bytes for another's fill — a failure that produces a plausible PDF\n * and no error at all.\n */\nexport function decodeFormBlank(blank: FormBlank): Uint8Array {\n const cached = decoded.get(blank)\n if (cached) return cached\n const binary = atob(blank.base64)\n const bytes = new Uint8Array(binary.length)\n for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index)\n if (bytes.length !== blank.byteLength) {\n throw new Error(\n `blank form is ${bytes.length} bytes but declares ${blank.byteLength} — the embedded base64 is truncated`,\n )\n }\n decoded.set(blank, bytes)\n return bytes\n}\n\nimport { sha256Hex } from '../crypto/digest'\n\nexport { sha256Hex }\n\n/**\n * Prove the embedded bytes are the file the registry was derived from.\n *\n * Run this in a test, not on the fill path: a registry is only meaningful\n * against the exact revision it was derived from, and a blank swapped for a\n * newer revision moves every widget without changing a single field name.\n */\nexport async function assertFormBlankIntegrity(blank: FormBlank): Promise<void> {\n const bytes = decodeFormBlank(blank)\n const digest = await sha256Hex(bytes)\n if (digest !== blank.sha256) {\n throw new Error(\n `blank form digest is ${digest} but the registry was derived against ${blank.sha256} (${blank.sourceUrl})`,\n )\n }\n}\n","/**\n * The slot → widget registry: the one place a form filler can be wrong\n * invisibly, and the one place a language model is never allowed to write.\n *\n * WHY THE MODEL NEVER NAMES A WIDGET\n *\n * An agency PDF's widget names carry no meaning a reader can check —\n * `topmostSubform[0].Page2[0].f2_06[0]` on an IRS form, `registered2` on a\n * Texas SOS form. A model asked for one produces a plausible string, and the\n * natural audit — read the field back by the name you just wrote — PASSES\n * REGARDLESS, because it re-reads the invention rather than checking it.\n * Measured on tax-agent: three values written to model-chosen widgets landed\n * in \"Combat zone\" and the date boxes, and the audit reported 3 passed /\n * 0 failed.\n *\n * So the model supplies SEMANTIC SLOTS — a form line, a named box — and the\n * platform owns the slot → widget mapping. A misplaced figure stops being an\n * invention that survives review and becomes something that cannot be\n * expressed at all.\n *\n * WHY A SLOT CARRIES A LABEL, AND WHY THE LABEL DECLARES ITS BASIS\n *\n * A registry is still just a table, and a hand-typed table drifts (tax-agent's\n * form catalog carried wrong page counts for 7 of 17 forms). So every slot\n * states the label it believes it is aiming at, and states where that belief\n * came from:\n *\n * - `labelBasis: 'widget'` — the label must match the widget's OWN `/TU`\n * accessibility text inside the PDF. `checkRegistryAgainstBlank` re-checks\n * it against the bytes, so a mis-aimed slot fails a test rather than\n * quietly printing in the wrong box. Every one of Texas Form 205's 64\n * widgets carries `/TU`, so its whole registry can be checked this way.\n * - `labelBasis: 'derived'` — the label came from somewhere else (an XFA\n * template, a published instruction sheet, a human reading the form) and\n * CANNOT be re-checked against the widget. It is evidence for a reviewer,\n * never proof. Measured on IRS f1040: 0 of 199 widgets carry `/TU` or\n * `/Alt`, so its labels can only ever be derived.\n *\n * Declaring the basis is the point. A guess presented as truth is how a second\n * self-confirming artifact gets built on top of the first one.\n */\n\nimport type { PDFDocument, PDFForm } from 'pdf-lib'\n\n/** What kind of widget a slot writes to. */\nexport type FormSlotKind = 'text' | 'checkbox'\n\n/** How a slot's text value is rendered into the box. */\nexport type FormSlotFormat = 'text' | 'currency'\n\n/** Where a slot's `label` came from, and therefore what it can prove. */\nexport type FormLabelBasis = 'widget' | 'derived'\n\n/** One semantic slot: what a caller supplies, and where the platform puts it. */\nexport interface FormSlot {\n /** The name a caller (and a model) uses: `15`, `entity_name`, `agent_is_org`. */\n slot: string\n /**\n * The AcroForm widget path(s) this slot writes.\n *\n * A LIST because one semantic value legitimately occupies several boxes: IRS\n * Form 1040 states adjusted gross income twice, at the foot of page 1 and\n * the head of page 2, so page 2's arithmetic stands alone. Writing only one\n * of them leaves \"subtract line 14 from line 11b\" pointing at an empty box.\n */\n fields: readonly string[]\n kind: FormSlotKind\n /** How the value is rendered. Ignored for `checkbox`. Default `'text'`. */\n format?: FormSlotFormat\n /** What this slot is, in the form's own words. */\n label: string\n /** Whether `label` is checkable against the PDF, or merely recorded. */\n labelBasis: FormLabelBasis\n}\n\n/** A form's complete slot table, pinned to the revision it was derived from. */\nexport interface FormRegistry {\n /** Stable id for the form: `us-irs-1040`, `us-tx-sos-205`. */\n form: string\n /** The agency's own revision marker: `2025`, `Rev. 12-21`. */\n revision: string\n slots: readonly FormSlot[]\n}\n\n/** Why a registry does not match the blank it claims to describe. */\nexport type RegistryProblemCode =\n | 'no_slots'\n | 'no_fields'\n | 'missing_field'\n | 'wrong_kind'\n | 'label_mismatch'\n | 'duplicate_field'\n | 'duplicate_slot'\n\nexport interface RegistryProblem {\n slot: string\n field?: string\n code: RegistryProblemCode\n detail: string\n}\n\nexport interface RegistryCheckResult {\n ok: boolean\n /** Widgets actually compared against the PDF. Zero means nothing was proven. */\n checked: number\n /** Slots whose label was compared against the widget's own `/TU`. */\n labelsChecked: number\n problems: RegistryProblem[]\n}\n\n/** The `/TU` accessibility text a widget carries, if any. */\nexport async function widgetLabel(form: PDFForm, field: string): Promise<string | undefined> {\n const { PDFName, PDFHexString, PDFString } = await import('pdf-lib')\n const target = form.getFieldMaybe(field)\n if (!target) return undefined\n const tooltip = target.acroField.dict.get(PDFName.of('TU'))\n if (tooltip instanceof PDFString || tooltip instanceof PDFHexString) return tooltip.decodeText()\n return undefined\n}\n\n/** Normalize whitespace so a label comparison survives the agency's own typing. */\nfunction normalizeLabel(value: string): string {\n return value.replace(/\\s+/gu, ' ').trim().toLowerCase()\n}\n\n/**\n * Check a registry against the blank it claims to describe.\n *\n * This is the placement check. It runs in a test or in CI, never on the fill\n * path, and it is the ONLY thing that can catch a slot aimed at the wrong box\n * — reading a value back after writing it cannot, because it re-reads the same\n * name it wrote.\n *\n * It fails on ABSENCE, deliberately. tax-agent shipped an audit that silently\n * skipped an expected field the PDF did not expose, so a fill against entirely\n * wrong paths reported `passed=0 failed=0`. Here an empty registry, a slot\n * with no fields, and a field the PDF does not expose are each a problem with\n * a name, and `checked` is reported so a caller can see how much was actually\n * proven rather than trusting a bare `ok: true`.\n */\nexport async function checkRegistryAgainstBlank(args: {\n /** The blank's bytes. Decode a `FormBlank` with `decodeFormBlank` first. */\n pdf: Uint8Array\n registry: FormRegistry\n}): Promise<RegistryCheckResult> {\n const { PDFDocument } = await import('pdf-lib')\n const document: PDFDocument = await PDFDocument.load(args.pdf, { updateMetadata: false })\n const form = document.getForm()\n\n // The PDF's OWN field list, enumerated independently of anything the\n // registry claims. Every lookup below resolves against this, so a registry\n // naming a field that does not exist cannot pass by being skipped.\n const exposed = new Map<string, string>()\n for (const field of form.getFields()) exposed.set(field.getName(), field.constructor.name)\n\n const problems: RegistryProblem[] = []\n const claimedBy = new Map<string, string>()\n const seenSlots = new Set<string>()\n let checked = 0\n let labelsChecked = 0\n\n if (args.registry.slots.length === 0) {\n problems.push({\n slot: '(registry)',\n code: 'no_slots',\n detail: `registry ${args.registry.form} declares no slots — it can prove nothing and fill nothing`,\n })\n }\n\n for (const slot of args.registry.slots) {\n if (seenSlots.has(slot.slot)) {\n problems.push({\n slot: slot.slot,\n code: 'duplicate_slot',\n detail: `slot ${slot.slot} is declared twice; the later entry silently wins at fill time`,\n })\n }\n seenSlots.add(slot.slot)\n\n if (slot.fields.length === 0) {\n problems.push({\n slot: slot.slot,\n code: 'no_fields',\n detail: `slot ${slot.slot} names no widget, so a value supplied for it goes nowhere`,\n })\n continue\n }\n\n for (const field of slot.fields) {\n const previous = claimedBy.get(field)\n if (previous !== undefined && previous !== slot.slot) {\n problems.push({\n slot: slot.slot,\n field,\n code: 'duplicate_field',\n detail: `${field} is claimed by both slot ${previous} and slot ${slot.slot}`,\n })\n }\n claimedBy.set(field, slot.slot)\n\n const actualKind = exposed.get(field)\n if (actualKind === undefined) {\n problems.push({\n slot: slot.slot,\n field,\n code: 'missing_field',\n detail: `${args.registry.form} has no widget named ${field}`,\n })\n continue\n }\n checked += 1\n\n const expectedKind = slot.kind === 'checkbox' ? 'PDFCheckBox' : 'PDFTextField'\n if (actualKind !== expectedKind) {\n problems.push({\n slot: slot.slot,\n field,\n code: 'wrong_kind',\n detail: `${field} is a ${actualKind}, but slot ${slot.slot} declares ${slot.kind}`,\n })\n continue\n }\n\n if (slot.labelBasis !== 'widget') continue\n const onWidget = await widgetLabel(form, field)\n if (onWidget === undefined) {\n problems.push({\n slot: slot.slot,\n field,\n code: 'label_mismatch',\n detail: `slot ${slot.slot} claims labelBasis 'widget' but ${field} carries no /TU text to check it against — the label is derived, not checked`,\n })\n continue\n }\n labelsChecked += 1\n if (normalizeLabel(onWidget) !== normalizeLabel(slot.label)) {\n problems.push({\n slot: slot.slot,\n field,\n code: 'label_mismatch',\n detail: `${field} is labelled ${JSON.stringify(onWidget)} but slot ${slot.slot} claims ${JSON.stringify(slot.label)}`,\n })\n }\n }\n }\n\n return { ok: problems.length === 0, checked, labelsChecked, problems }\n}\n","/**\n * Fill a real agency PDF from a slot → value map.\n *\n * Mechanically this is `pdf-lib` writing an AcroForm: TypeScript, no\n * container, no Python, no network. That matters because it is the only shape\n * that runs everywhere these products run — a Cloudflare Worker (where 100% of\n * tax-agent's production work products were produced, with no sandbox at all)\n * and a sandbox container whose egress proxy refuses the agency's own host.\n *\n * The invariant it enforces is in `registry.ts`: the caller supplies SEMANTIC\n * SLOTS and never a widget name. Two consequences show up here.\n *\n * NOTHING IS SILENT. Every slot ends in `filled` or in `unfilled` with a code\n * and a reason. A value the caller supplied that never reached the page means\n * the document and the data disagree, which is the one thing a reviewer must\n * not have to discover by eye. That includes a registry naming a widget the\n * PDF does not expose: it is reported per-slot rather than crashing the render\n * or — worse — being skipped, which is how tax-agent once audited a fill\n * against entirely wrong paths as `passed=0 failed=0`.\n *\n * NO ON-STATE IS EVER AUTHORED. A checkbox's \"on\" name is a property of the\n * PDF and frequently a hex-escaped sentence: Texas Form 205's seven boxes are\n * `is#20an#20organization`, `initially#20has#20#20managers` (note the double\n * space), and four more like them. A caller that types one of those strings is\n * authoring something it cannot check, so a checkbox slot takes a BOOLEAN and\n * the widget's own on-value is read out of the file. The escaped spelling is\n * not handled — it is unrepresentable.\n */\n\nimport type { PDFCheckBox, PDFDocument, PDFTextField } from 'pdf-lib'\n\nimport type { FormRegistry, FormSlot } from './registry'\n\n/** One widget the fill actually wrote. */\nexport interface FilledWidget {\n slot: string\n field: string\n kind: FormSlot['kind']\n /** The value as the caller supplied it, before formatting. */\n value: unknown\n /** Exactly the text placed in the box. Absent for a checkbox. */\n text?: string\n /** Whether a checkbox was ticked. Absent for a text field. */\n checked?: boolean\n /** The widget's OWN on-state, decoded — read from the PDF, never authored. */\n onState?: string\n}\n\n/** Why a supplied value did not reach the page. */\nexport type UnfilledCode =\n | 'unknown_slot'\n | 'missing_field'\n | 'wrong_kind'\n | 'not_a_number'\n | 'not_a_boolean'\n | 'unformattable'\n\nexport interface UnfilledSlot {\n slot: string\n field?: string\n value: unknown\n code: UnfilledCode\n reason: string\n}\n\nexport interface FillFormResult {\n bytes: Uint8Array\n filled: FilledWidget[]\n unfilled: UnfilledSlot[]\n form: string\n revision: string\n}\n\nexport interface FillFormOptions {\n /** The blank's bytes. Decode a `FormBlank` with `decodeFormBlank` first. */\n pdf: Uint8Array\n registry: FormRegistry\n /** slot name → value. Keys the registry does not know are reported, not dropped. */\n values: Record<string, unknown>\n /**\n * Override how a text value becomes box text. Return `undefined` to fall\n * through to the built-in formatting for the slot's `format`.\n */\n formatText?: (value: unknown, slot: FormSlot) => string | undefined\n}\n\n/**\n * Format a figure the way a US agency form prints it: grouped thousands, two\n * decimals, negatives in parentheses.\n *\n * Two decimals rather than whole dollars because the caller's data carries\n * cents and a reviewer compares the document against that data — rounding here\n * would manufacture a disagreement between the two on every line with cents.\n */\nexport function formatFormCurrency(value: number): string {\n const magnitude = Math.abs(value).toLocaleString('en-US', {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })\n return value < 0 ? `(${magnitude})` : magnitude\n}\n\n/** A number, or a number written the way a form prints one (`$141,318.74`). */\nexport function parseFormAmount(value: unknown): number | undefined {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (typeof value !== 'string') return undefined\n const normalized = value.replace(/[$,\\s]/gu, '')\n if (!/^-?\\d+(?:\\.\\d+)?$/u.test(normalized)) return undefined\n const parsed = Number(normalized)\n return Number.isFinite(parsed) ? parsed : undefined\n}\n\n/**\n * A checkbox takes a boolean and nothing else.\n *\n * Strict on purpose. Accepting a truthy string would accept the widget's own\n * escaped on-state (`'is#20an#20organization'`) as \"true\", which is exactly\n * the authored-on-state this module refuses — and it would accept `'no'` as\n * true, silently ticking a box the caller meant to leave clear.\n */\nexport function parseFormBoolean(value: unknown): boolean | undefined {\n if (typeof value === 'boolean') return value\n if (typeof value !== 'string') return undefined\n const normalized = value.trim().toLowerCase()\n if (normalized === 'true' || normalized === 'yes') return true\n if (normalized === 'false' || normalized === 'no') return false\n return undefined\n}\n\nfunction textFor(\n value: unknown,\n slot: FormSlot,\n override: FillFormOptions['formatText'],\n): { text: string } | { code: UnfilledCode; reason: string } {\n const custom = override?.(value, slot)\n if (custom !== undefined) return { text: custom }\n if ((slot.format ?? 'text') === 'currency') {\n const amount = parseFormAmount(value)\n if (amount === undefined) return { code: 'not_a_number', reason: 'not a numeric amount' }\n return { text: formatFormCurrency(amount) }\n }\n if (typeof value === 'string') return { text: value }\n if (typeof value === 'number' && Number.isFinite(value)) return { text: String(value) }\n return { code: 'unformattable', reason: `cannot render a ${typeof value} into a text box` }\n}\n\n/**\n * Write a value map onto a blank, returning the bytes plus the exact\n * widget-by-widget account of what was and was not placed.\n */\nexport async function fillPdfForm(options: FillFormOptions): Promise<FillFormResult> {\n const { PDFCheckBox: CheckBox, PDFDocument, PDFName, PDFTextField: TextField } = await import('pdf-lib')\n\n // `updateMetadata: false` keeps the render deterministic — pdf-lib otherwise\n // stamps a ModDate, which would give the same values a different checksum on\n // every call and defeat content-addressed storage. It also keeps our\n // timestamps off the agency's document.\n const document: PDFDocument = await PDFDocument.load(options.pdf, { updateMetadata: false })\n const form = document.getForm()\n\n // Agency forms ship as AcroForm/XFA hybrids, and a reader that prefers the\n // XFA layer would draw the ORIGINAL empty form and show none of these\n // values. `getForm()` drops the XFA packet (pdf-lib does not support it), so\n // this asserts the property rather than trusting it to stay incidental.\n if (document.catalog.getOrCreateAcroForm().dict.has(PDFName.of('XFA'))) {\n throw new Error('filled form still carries an XFA layer — a viewer would draw the blank instead')\n }\n\n const bySlot = new Map(options.registry.slots.map((slot) => [slot.slot, slot]))\n const filled: FilledWidget[] = []\n const unfilled: UnfilledSlot[] = []\n\n for (const [name, value] of Object.entries(options.values)) {\n const slot = bySlot.get(name)\n if (!slot) {\n unfilled.push({\n slot: name,\n value,\n code: 'unknown_slot',\n reason: `${options.registry.form} has no slot named ${name}`,\n })\n continue\n }\n\n if (slot.kind === 'checkbox') {\n const checked = parseFormBoolean(value)\n if (checked === undefined) {\n unfilled.push({\n slot: name,\n value,\n code: 'not_a_boolean',\n reason: 'a checkbox takes true or false; a checkbox on-state is read from the PDF and is never supplied',\n })\n continue\n }\n for (const field of slot.fields) {\n const widget = form.getFieldMaybe(field)\n if (!widget) {\n unfilled.push({ slot: name, field, value, code: 'missing_field', reason: `${options.registry.form} has no widget named ${field}` })\n continue\n }\n if (!(widget instanceof CheckBox)) {\n unfilled.push({ slot: name, field, value, code: 'wrong_kind', reason: `${field} is a ${widget.constructor.name}, not a checkbox` })\n continue\n }\n const box = widget as PDFCheckBox\n // The widget's OWN on-state. Read, never authored: Texas Form 205's\n // are hex-escaped sentences, and a caller that typed one would be\n // asserting a fact about the file it cannot check.\n const onState = box.acroField.getOnValue()?.decodeText()\n if (checked) box.check()\n else box.uncheck()\n filled.push({ slot: name, field, kind: 'checkbox', value, checked, onState })\n }\n continue\n }\n\n const rendered = textFor(value, slot, options.formatText)\n if ('code' in rendered) {\n unfilled.push({ slot: name, value, code: rendered.code, reason: rendered.reason })\n continue\n }\n for (const field of slot.fields) {\n const widget = form.getFieldMaybe(field)\n if (!widget) {\n unfilled.push({ slot: name, field, value, code: 'missing_field', reason: `${options.registry.form} has no widget named ${field}` })\n continue\n }\n if (!(widget instanceof TextField)) {\n unfilled.push({ slot: name, field, value, code: 'wrong_kind', reason: `${field} is a ${widget.constructor.name}, not a text field` })\n continue\n }\n ;(widget as PDFTextField).setText(rendered.text)\n filled.push({ slot: name, field, kind: 'text', value, text: rendered.text })\n }\n }\n\n return {\n bytes: await document.save(),\n filled,\n unfilled,\n form: options.registry.form,\n revision: options.registry.revision,\n }\n}\n\n/**\n * What to tell the agent after a fill.\n *\n * Names the values that did NOT reach the page. Those are exactly the cases\n * where the document and the data disagree, and the agent is the only party\n * that can resolve it — returning a bare \"done\" hands a reviewer a form\n * missing values the data claims are on it.\n */\nexport function describeFormFill(result: FillFormResult): string {\n const count = result.filled.length\n const base = `Filled ${result.form} (${result.revision}) with ${count} ${count === 1 ? 'value' : 'values'}.`\n if (result.unfilled.length === 0) return base\n const detail = result.unfilled.map((entry) => `${entry.slot} (${entry.reason})`).join('; ')\n return `${base} NOT placed on the form: ${detail}. Those values are in the data but not on the document a reviewer opens.`\n}\n","/**\n * Read a filled form back and say, slot by slot, whether the document agrees\n * with the data it was built from.\n *\n * WHAT THIS PROVES, AND WHAT IT CANNOT\n *\n * This proves the WRITE LANDED: the value reached a real widget, that widget\n * exists in the produced file, and it holds the text or tick the data claims.\n * It does NOT prove PLACEMENT — that the widget is the right box on the page —\n * because it resolves the same field names the fill used. Reading a value back\n * by the name you just wrote passes even when the name was invented; measured\n * on tax-agent, an audit of that shape reported 3 passed / 0 failed for three\n * figures sitting in \"Combat zone\" and the date boxes.\n *\n * Placement is proven by `checkRegistryAgainstBlank`, which compares each\n * slot's claimed label against the widget's own `/TU` text inside the PDF.\n * The two checks are complements, and a product that runs only this one has\n * the audit that already failed once. That is stated here rather than in a\n * commit message because a future caller will otherwise reach for the\n * convenient half.\n *\n * FAILS ON ABSENCE. A registry field the produced PDF does not expose is\n * `missing_field`, and an empty `expected` map is `ok: false` — the\n * `passed=0 failed=0` verdict is the exact shape of the bug this replaces.\n */\n\nimport type { PDFCheckBox, PDFDocument, PDFTextField } from 'pdf-lib'\n\nimport { parseFormBoolean, formatFormCurrency, parseFormAmount } from './fill'\nimport { widgetLabel, type FormRegistry } from './registry'\n\nexport type SlotVerdict = 'ok' | 'unknown_slot' | 'missing_field' | 'wrong_kind' | 'not_written' | 'mismatch'\n\n/** What the slot's `label` is worth, checked against the produced file. */\nexport type LabelVerdict = 'matches_widget' | 'label_mismatch' | 'derived_unchecked' | 'no_widget_label'\n\nexport interface SlotVerification {\n slot: string\n field?: string\n verdict: SlotVerdict\n /** What the data says the box should hold. */\n expected?: string\n /** What the box actually holds, read out of the produced bytes. */\n actual?: string\n labelVerdict?: LabelVerdict\n label?: string\n}\n\nexport interface VerifyFormResult {\n ok: boolean\n /** Widgets actually read back. Zero means nothing was proven. */\n verified: number\n slots: SlotVerification[]\n}\n\nfunction expectedText(value: unknown, format: string | undefined): string {\n if (format === 'currency') {\n const amount = parseFormAmount(value)\n return amount === undefined ? String(value) : formatFormCurrency(amount)\n }\n return typeof value === 'number' ? String(value) : String(value)\n}\n\n/**\n * Verify a filled form against the value map it was filled from.\n *\n * `expected` is the SAME shape passed to `fillPdfForm` — deliberately, so a\n * caller cannot verify against a convenient restatement of what it wrote.\n */\nexport async function verifyFilledForm(args: {\n /** The PRODUCED bytes, not the blank. */\n pdf: Uint8Array\n registry: FormRegistry\n expected: Record<string, unknown>\n /** Slots the caller knowingly left out of `expected`; anything else is checked. */\n}): Promise<VerifyFormResult> {\n const { PDFCheckBox: CheckBox, PDFDocument, PDFTextField: TextField } = await import('pdf-lib')\n const document: PDFDocument = await PDFDocument.load(args.pdf, { updateMetadata: false })\n const form = document.getForm()\n\n // The produced file's OWN field list, enumerated before anything the\n // registry claims is consulted. A registry field absent from this set is a\n // failure, never a skip.\n const exposed = new Set(form.getFields().map((field) => field.getName()))\n\n const bySlot = new Map(args.registry.slots.map((slot) => [slot.slot, slot]))\n const slots: SlotVerification[] = []\n let verified = 0\n let ok = true\n\n for (const [name, value] of Object.entries(args.expected)) {\n const slot = bySlot.get(name)\n if (!slot) {\n slots.push({ slot: name, verdict: 'unknown_slot' })\n ok = false\n continue\n }\n for (const field of slot.fields) {\n if (!exposed.has(field)) {\n slots.push({ slot: name, field, verdict: 'missing_field' })\n ok = false\n continue\n }\n const widget = form.getField(field)\n const label = await widgetLabel(form, field)\n const labelVerdict: LabelVerdict =\n slot.labelBasis === 'derived'\n ? 'derived_unchecked'\n : label === undefined\n ? 'no_widget_label'\n : label.replace(/\\s+/gu, ' ').trim().toLowerCase() ===\n slot.label.replace(/\\s+/gu, ' ').trim().toLowerCase()\n ? 'matches_widget'\n : 'label_mismatch'\n if (labelVerdict === 'label_mismatch' || labelVerdict === 'no_widget_label') ok = false\n\n if (slot.kind === 'checkbox') {\n if (!(widget instanceof CheckBox)) {\n slots.push({ slot: name, field, verdict: 'wrong_kind', label, labelVerdict })\n ok = false\n continue\n }\n const want = parseFormBoolean(value)\n const got = (widget as PDFCheckBox).isChecked()\n const verdict: SlotVerdict = want === undefined ? 'mismatch' : got === want ? 'ok' : 'mismatch'\n if (verdict !== 'ok') ok = false\n else verified += 1\n slots.push({\n slot: name,\n field,\n verdict,\n expected: String(want),\n actual: String(got),\n label,\n labelVerdict,\n })\n continue\n }\n\n if (!(widget instanceof TextField)) {\n slots.push({ slot: name, field, verdict: 'wrong_kind', label, labelVerdict })\n ok = false\n continue\n }\n const want = expectedText(value, slot.format)\n const got = (widget as PDFTextField).getText() ?? ''\n const verdict: SlotVerdict = got === '' && want !== '' ? 'not_written' : got === want ? 'ok' : 'mismatch'\n if (verdict !== 'ok') ok = false\n else verified += 1\n slots.push({ slot: name, field, verdict, expected: want, actual: got, label, labelVerdict })\n }\n }\n\n // An audit that checked nothing must never report success. This is the\n // `passed=0 failed=0` verdict, refused by name.\n if (verified === 0) ok = false\n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AAuB,QAAQ,MAAM,SAAS,KAAK,gBAAgB,QAAQ,OAAO,OAAO;AAC/F,UAAI,YAAY,KAAM,MAAK;AAAA,UACtB,aAAY;AACjB,YAAM,KAAK,EAAE,MAAM,MAAM,OAAO,SAAS,UAAU,MAAM,QAAQ,KAAK,OAAO,aAAa,CAAC;AAAA,IAC7F;AAAA,EACF;AAIA,MAAI,aAAa,EAAG,MAAK;AAEzB,SAAO,EAAE,IAAI,UAAU,MAAM;AAC/B;","names":["want","got","verdict"]}
@@ -2,8 +2,8 @@ import {
2
2
  attachWorkspaceLine,
3
3
  createApplicationLineHandler,
4
4
  publicApplicationSenderVerification
5
- } from "../chunk-MY3EJJ6Y.js";
6
- import "../chunk-7HZCFG2A.js";
5
+ } from "../chunk-4FEH6266.js";
6
+ import "../chunk-WP2GYFZ4.js";
7
7
  import "../chunk-TXD5HXLE.js";
8
8
  export {
9
9
  attachWorkspaceLine,
@@ -7,9 +7,8 @@ import {
7
7
  mapInteractionRespondFailure,
8
8
  respondToSessionInteraction,
9
9
  validateInteractionAnswerBody
10
- } from "../chunk-TCGZFSN5.js";
11
- import "../chunk-7HZCFG2A.js";
12
- import "../chunk-TXD5HXLE.js";
10
+ } from "../chunk-KH4QSBNI.js";
11
+ import "../chunk-WP2GYFZ4.js";
13
12
  import {
14
13
  INTERACTION_CANCEL_EVENT,
15
14
  INTERACTION_EVENT,
@@ -35,6 +34,7 @@ import {
35
34
  questionInteractionContentSignature,
36
35
  stampInteractionAnswers
37
36
  } from "../chunk-6VQCFJWP.js";
37
+ import "../chunk-TXD5HXLE.js";
38
38
  export {
39
39
  INTERACTION_CANCEL_EVENT,
40
40
  INTERACTION_EVENT,
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Prelaunch knowledge audit: build the workspace knowledge index, validate it,
3
+ * score it against the product's readiness specs, and write one JSON report.
4
+ *
5
+ * Server-side only (node:fs plus `@tangle-network/agent-knowledge`). A product's
6
+ * `scripts/prelaunch-knowledge-audit.ts` supplies its id and policy and calls
7
+ * {@link runPrelaunchKnowledgeAudit}; with `--strict` the process exits 1 when
8
+ * validation fails or a blocking requirement is missing.
9
+ */
10
+ export interface PrelaunchKnowledgeAuditConfig {
11
+ /** Product id, used in the task id, the report and the failure message. */
12
+ product: string;
13
+ /** Readiness policy recorded in the bundle metadata. */
14
+ policy: string;
15
+ }
16
+ /** Run the audit, write the report, and exit 1 under `--strict` when it fails. */
17
+ export declare function runPrelaunchKnowledgeAudit(config: PrelaunchKnowledgeAuditConfig): Promise<void>;
@@ -0,0 +1,67 @@
1
+ // src/knowledge/prelaunch-audit.ts
2
+ import { mkdir, readFile, writeFile } from "fs/promises";
3
+ import { dirname, join } from "path";
4
+ import {
5
+ buildEvalKnowledgeBundle,
6
+ buildKnowledgeIndex,
7
+ initKnowledgeBase,
8
+ inspectKnowledgeIndex,
9
+ validateKnowledgeIndex
10
+ } from "@tangle-network/agent-knowledge";
11
+ async function runPrelaunchKnowledgeAudit(config) {
12
+ const { product, policy } = config;
13
+ const strict = process.argv.includes("--strict");
14
+ const knowledgeRoot = process.env.KNOWLEDGE_ROOT ?? ".";
15
+ const reportPath = process.env.KNOWLEDGE_AUDIT_REPORT ?? join(".knowledge-readiness", `${product}-report.json`);
16
+ try {
17
+ await initKnowledgeBase(knowledgeRoot);
18
+ const specs = JSON.parse(
19
+ await readFile(join(knowledgeRoot, "knowledge", "readiness-specs.json"), "utf8")
20
+ );
21
+ const index = await buildKnowledgeIndex(knowledgeRoot);
22
+ const validation = validateKnowledgeIndex(index, { strict: true });
23
+ const inspection = inspectKnowledgeIndex(index);
24
+ const readiness = buildEvalKnowledgeBundle({
25
+ taskId: `${product}:prelaunch-knowledge`,
26
+ index,
27
+ specs,
28
+ searchLimit: 8,
29
+ metadata: { product, policy }
30
+ });
31
+ const missing = readiness.report.blockingMissingRequirements;
32
+ const ok = validation.ok && missing.length === 0;
33
+ const output = {
34
+ product,
35
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
36
+ knowledgeRoot,
37
+ ok,
38
+ strict,
39
+ summary: {
40
+ readinessScore: readiness.report.readinessScore,
41
+ sourceCount: inspection.sourceCount,
42
+ pageCount: inspection.pageCount,
43
+ findingCount: inspection.findingCount,
44
+ blockingFindingCount: inspection.blockingFindingCount,
45
+ blockingMissingRequirements: missing.length
46
+ },
47
+ report: readiness.report,
48
+ findings: validation.findings,
49
+ missingRequirementIds: missing.map((requirement) => requirement.id)
50
+ };
51
+ await mkdir(dirname(reportPath), { recursive: true });
52
+ await writeFile(reportPath, `${JSON.stringify(output, null, 2)}
53
+ `);
54
+ console.log(JSON.stringify(output.summary, null, 2));
55
+ if (strict && !ok) {
56
+ console.error(`${product} knowledge readiness failed; see ${reportPath}`);
57
+ process.exit(1);
58
+ }
59
+ } catch (error) {
60
+ console.error(error);
61
+ process.exit(1);
62
+ }
63
+ }
64
+ export {
65
+ runPrelaunchKnowledgeAudit
66
+ };
67
+ //# sourceMappingURL=prelaunch-audit.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/knowledge/prelaunch-audit.ts"],"sourcesContent":["/**\n * Prelaunch knowledge audit: build the workspace knowledge index, validate it,\n * score it against the product's readiness specs, and write one JSON report.\n *\n * Server-side only (node:fs plus `@tangle-network/agent-knowledge`). A product's\n * `scripts/prelaunch-knowledge-audit.ts` supplies its id and policy and calls\n * {@link runPrelaunchKnowledgeAudit}; with `--strict` the process exits 1 when\n * validation fails or a blocking requirement is missing.\n */\n\nimport { mkdir, readFile, writeFile } from 'node:fs/promises'\nimport { dirname, join } from 'node:path'\nimport {\n buildEvalKnowledgeBundle,\n buildKnowledgeIndex,\n initKnowledgeBase,\n inspectKnowledgeIndex,\n validateKnowledgeIndex,\n type KnowledgeReadinessSpec,\n} from '@tangle-network/agent-knowledge'\n\nexport interface PrelaunchKnowledgeAuditConfig {\n /** Product id, used in the task id, the report and the failure message. */\n product: string\n /** Readiness policy recorded in the bundle metadata. */\n policy: string\n}\n\n/** Run the audit, write the report, and exit 1 under `--strict` when it fails. */\nexport async function runPrelaunchKnowledgeAudit(config: PrelaunchKnowledgeAuditConfig): Promise<void> {\n const { product, policy } = config\n const strict = process.argv.includes('--strict')\n const knowledgeRoot = process.env.KNOWLEDGE_ROOT ?? '.'\n const reportPath = process.env.KNOWLEDGE_AUDIT_REPORT ?? join('.knowledge-readiness', `${product}-report.json`)\n try {\n await initKnowledgeBase(knowledgeRoot)\n const specs = JSON.parse(\n await readFile(join(knowledgeRoot, 'knowledge', 'readiness-specs.json'), 'utf8'),\n ) as KnowledgeReadinessSpec[]\n const index = await buildKnowledgeIndex(knowledgeRoot)\n const validation = validateKnowledgeIndex(index, { strict: true })\n const inspection = inspectKnowledgeIndex(index)\n const readiness = buildEvalKnowledgeBundle({\n taskId: `${product}:prelaunch-knowledge`,\n index,\n specs,\n searchLimit: 8,\n metadata: { product, policy },\n })\n\n const missing = readiness.report.blockingMissingRequirements\n const ok = validation.ok && missing.length === 0\n const output = {\n product,\n generatedAt: new Date().toISOString(),\n knowledgeRoot,\n ok,\n strict,\n summary: {\n readinessScore: readiness.report.readinessScore,\n sourceCount: inspection.sourceCount,\n pageCount: inspection.pageCount,\n findingCount: inspection.findingCount,\n blockingFindingCount: inspection.blockingFindingCount,\n blockingMissingRequirements: missing.length,\n },\n report: readiness.report,\n findings: validation.findings,\n missingRequirementIds: missing.map((requirement) => requirement.id),\n }\n\n await mkdir(dirname(reportPath), { recursive: true })\n await writeFile(reportPath, `${JSON.stringify(output, null, 2)}\\n`)\n console.log(JSON.stringify(output.summary, null, 2))\n if (strict && !ok) {\n console.error(`${product} knowledge readiness failed; see ${reportPath}`)\n process.exit(1)\n }\n } catch (error) {\n console.error(error)\n process.exit(1)\n }\n}\n"],"mappings":";AAUA,SAAS,OAAO,UAAU,iBAAiB;AAC3C,SAAS,SAAS,YAAY;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAUP,eAAsB,2BAA2B,QAAsD;AACrG,Q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