@narumitw/pi-subagents 2.0.1 → 2.0.3

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 (148) hide show
  1. package/README.md +20 -7
  2. package/dist/chunks/auto-transport-SY2VHUFH.ts +109 -0
  3. package/dist/chunks/auto-transport-SY2VHUFH.ts.map +7 -0
  4. package/dist/chunks/capability-grant-CGEWOEKE.ts +19 -0
  5. package/dist/chunks/capability-grant-CGEWOEKE.ts.map +7 -0
  6. package/dist/chunks/chunk-434NII74.ts +282 -0
  7. package/dist/chunks/chunk-434NII74.ts.map +7 -0
  8. package/dist/chunks/chunk-47SK2QYC.ts +56 -0
  9. package/dist/chunks/chunk-47SK2QYC.ts.map +7 -0
  10. package/dist/chunks/chunk-6KJ34M6S.ts +159 -0
  11. package/dist/chunks/chunk-6KJ34M6S.ts.map +7 -0
  12. package/dist/chunks/chunk-7OBINKFM.ts +80 -0
  13. package/dist/chunks/chunk-7OBINKFM.ts.map +7 -0
  14. package/dist/chunks/chunk-7QPPBBXZ.ts +335 -0
  15. package/dist/chunks/chunk-7QPPBBXZ.ts.map +7 -0
  16. package/dist/chunks/chunk-AEUYS7JC.ts +73 -0
  17. package/dist/chunks/chunk-AEUYS7JC.ts.map +7 -0
  18. package/dist/chunks/chunk-BFK2Z4ZF.ts +189 -0
  19. package/dist/chunks/chunk-BFK2Z4ZF.ts.map +7 -0
  20. package/dist/chunks/chunk-BOAXY55Y.ts +153 -0
  21. package/dist/chunks/chunk-BOAXY55Y.ts.map +7 -0
  22. package/dist/chunks/chunk-C4L6P266.ts +22 -0
  23. package/dist/chunks/chunk-C4L6P266.ts.map +7 -0
  24. package/dist/chunks/chunk-DPPVEQAM.ts +29 -0
  25. package/dist/chunks/chunk-DPPVEQAM.ts.map +7 -0
  26. package/dist/chunks/chunk-DQMN4OYM.ts +913 -0
  27. package/dist/chunks/chunk-DQMN4OYM.ts.map +7 -0
  28. package/dist/chunks/chunk-DSOOH73Y.ts +238 -0
  29. package/dist/chunks/chunk-DSOOH73Y.ts.map +7 -0
  30. package/dist/chunks/chunk-EFBPISNT.ts +421 -0
  31. package/dist/chunks/chunk-EFBPISNT.ts.map +7 -0
  32. package/dist/chunks/chunk-EWWXFU7N.ts +150 -0
  33. package/dist/chunks/chunk-EWWXFU7N.ts.map +7 -0
  34. package/dist/chunks/chunk-F4L2UVSK.ts +380 -0
  35. package/dist/chunks/chunk-F4L2UVSK.ts.map +7 -0
  36. package/dist/chunks/chunk-F5YWVHQX.ts +1543 -0
  37. package/dist/chunks/chunk-F5YWVHQX.ts.map +7 -0
  38. package/dist/chunks/chunk-G3RSMSXJ.ts +63 -0
  39. package/dist/chunks/chunk-G3RSMSXJ.ts.map +7 -0
  40. package/dist/chunks/chunk-G6VZTCFH.ts +70 -0
  41. package/dist/chunks/chunk-G6VZTCFH.ts.map +7 -0
  42. package/dist/chunks/chunk-H3FP6DLR.ts +160 -0
  43. package/dist/chunks/chunk-H3FP6DLR.ts.map +7 -0
  44. package/dist/chunks/chunk-HA36LPCO.ts +130 -0
  45. package/dist/chunks/chunk-HA36LPCO.ts.map +7 -0
  46. package/dist/chunks/chunk-HKC4ES4B.ts +65 -0
  47. package/dist/chunks/chunk-HKC4ES4B.ts.map +7 -0
  48. package/dist/chunks/chunk-HOP5FXDT.ts +27 -0
  49. package/dist/chunks/chunk-HOP5FXDT.ts.map +7 -0
  50. package/dist/chunks/chunk-I2FAK44T.ts +324 -0
  51. package/dist/chunks/chunk-I2FAK44T.ts.map +7 -0
  52. package/dist/chunks/chunk-IGAMVWFN.ts +139 -0
  53. package/dist/chunks/chunk-IGAMVWFN.ts.map +7 -0
  54. package/dist/chunks/chunk-KMGKCEO4.ts +38 -0
  55. package/dist/chunks/chunk-KMGKCEO4.ts.map +7 -0
  56. package/dist/chunks/chunk-N7BLVXKK.ts +73 -0
  57. package/dist/chunks/chunk-N7BLVXKK.ts.map +7 -0
  58. package/dist/chunks/chunk-NIF42QMF.ts +297 -0
  59. package/dist/chunks/chunk-NIF42QMF.ts.map +7 -0
  60. package/dist/chunks/chunk-O4VO6JUJ.ts +52 -0
  61. package/dist/chunks/chunk-O4VO6JUJ.ts.map +7 -0
  62. package/dist/chunks/chunk-ONDTY4EL.ts +91 -0
  63. package/dist/chunks/chunk-ONDTY4EL.ts.map +7 -0
  64. package/dist/chunks/chunk-OVPHFGKO.ts +1769 -0
  65. package/dist/chunks/chunk-OVPHFGKO.ts.map +7 -0
  66. package/dist/chunks/chunk-P7OH4XMF.ts +60 -0
  67. package/dist/chunks/chunk-P7OH4XMF.ts.map +7 -0
  68. package/dist/chunks/chunk-PSK43Y6A.ts +339 -0
  69. package/dist/chunks/chunk-PSK43Y6A.ts.map +7 -0
  70. package/dist/chunks/chunk-QBORTI4W.ts +468 -0
  71. package/dist/chunks/chunk-QBORTI4W.ts.map +7 -0
  72. package/dist/chunks/chunk-QDVGH2X7.ts +171 -0
  73. package/dist/chunks/chunk-QDVGH2X7.ts.map +7 -0
  74. package/dist/chunks/chunk-RHRQMT7Q.ts +490 -0
  75. package/dist/chunks/chunk-RHRQMT7Q.ts.map +7 -0
  76. package/dist/chunks/chunk-RRR66UWR.ts +28 -0
  77. package/dist/chunks/chunk-RRR66UWR.ts.map +7 -0
  78. package/dist/chunks/chunk-RSUXZD6S.ts +275 -0
  79. package/dist/chunks/chunk-RSUXZD6S.ts.map +7 -0
  80. package/dist/chunks/chunk-RTCVYIZA.ts +221 -0
  81. package/dist/chunks/chunk-RTCVYIZA.ts.map +7 -0
  82. package/dist/chunks/chunk-S2IWVK3J.ts +44 -0
  83. package/dist/chunks/chunk-S2IWVK3J.ts.map +7 -0
  84. package/dist/chunks/chunk-SCZ33MYW.ts +52 -0
  85. package/dist/chunks/chunk-SCZ33MYW.ts.map +7 -0
  86. package/dist/chunks/chunk-SWGQLFSD.ts +60 -0
  87. package/dist/chunks/chunk-SWGQLFSD.ts.map +7 -0
  88. package/dist/chunks/chunk-UMBPMVJW.ts +22 -0
  89. package/dist/chunks/chunk-UMBPMVJW.ts.map +7 -0
  90. package/dist/chunks/chunk-UVFVHIOP.ts +735 -0
  91. package/dist/chunks/chunk-UVFVHIOP.ts.map +7 -0
  92. package/dist/chunks/completion-delivery-YPOWSSV3.ts +16 -0
  93. package/dist/chunks/completion-delivery-YPOWSSV3.ts.map +7 -0
  94. package/dist/chunks/config-status-J4GPWP46.ts +34 -0
  95. package/dist/chunks/config-status-J4GPWP46.ts.map +7 -0
  96. package/dist/chunks/config-ui-3IBMHTQB.ts +1146 -0
  97. package/dist/chunks/config-ui-3IBMHTQB.ts.map +7 -0
  98. package/dist/chunks/consult-NYXVDN5G.ts +518 -0
  99. package/dist/chunks/consult-NYXVDN5G.ts.map +7 -0
  100. package/dist/chunks/context-QDKLVQXE.ts +11 -0
  101. package/dist/chunks/context-QDKLVQXE.ts.map +7 -0
  102. package/dist/chunks/create-stateful-transport-4WKZHRSI.ts +130 -0
  103. package/dist/chunks/create-stateful-transport-4WKZHRSI.ts.map +7 -0
  104. package/dist/chunks/cwd-policy-NB6XZ5GF.ts +17 -0
  105. package/dist/chunks/cwd-policy-NB6XZ5GF.ts.map +7 -0
  106. package/dist/chunks/delegation-contract-WJPT4FVS.ts +24 -0
  107. package/dist/chunks/delegation-contract-WJPT4FVS.ts.map +7 -0
  108. package/dist/chunks/discovery-K25T3SH4.ts +12 -0
  109. package/dist/chunks/discovery-K25T3SH4.ts.map +7 -0
  110. package/dist/chunks/execution-DS2DEIQZ.ts +4034 -0
  111. package/dist/chunks/execution-DS2DEIQZ.ts.map +7 -0
  112. package/dist/chunks/in-process-transport-TEYAWSEC.ts +38 -0
  113. package/dist/chunks/in-process-transport-TEYAWSEC.ts.map +7 -0
  114. package/dist/chunks/inspect-UOQQ3KNL.ts +619 -0
  115. package/dist/chunks/inspect-UOQQ3KNL.ts.map +7 -0
  116. package/dist/chunks/peer-communication-KL36Z6CO.ts +294 -0
  117. package/dist/chunks/peer-communication-KL36Z6CO.ts.map +7 -0
  118. package/dist/chunks/persistence-VSGXAW4P.ts +344 -0
  119. package/dist/chunks/persistence-VSGXAW4P.ts.map +7 -0
  120. package/dist/chunks/registry-E6XPJB7L.ts +1324 -0
  121. package/dist/chunks/registry-E6XPJB7L.ts.map +7 -0
  122. package/dist/chunks/retained-semantic-state-7WXSGRJU.ts +81 -0
  123. package/dist/chunks/retained-semantic-state-7WXSGRJU.ts.map +7 -0
  124. package/dist/chunks/rpc-transport-Y6LA5BOP.ts +1154 -0
  125. package/dist/chunks/rpc-transport-Y6LA5BOP.ts.map +7 -0
  126. package/dist/chunks/runtime-policy-5YELCOVC.ts +15 -0
  127. package/dist/chunks/runtime-policy-5YELCOVC.ts.map +7 -0
  128. package/dist/chunks/semantic-snapshot-WPJ3UAFW.ts +19 -0
  129. package/dist/chunks/semantic-snapshot-WPJ3UAFW.ts.map +7 -0
  130. package/dist/chunks/spawn-idempotency-QGHO2WKC.ts +13 -0
  131. package/dist/chunks/spawn-idempotency-QGHO2WKC.ts.map +7 -0
  132. package/dist/chunks/stateful-lifecycle-JAR6K55H.ts +15 -0
  133. package/dist/chunks/stateful-lifecycle-JAR6K55H.ts.map +7 -0
  134. package/dist/chunks/subprocess-transport-C2XVR25R.ts +158 -0
  135. package/dist/chunks/subprocess-transport-C2XVR25R.ts.map +7 -0
  136. package/dist/chunks/workspace-WDKLN72J.ts +11 -0
  137. package/dist/chunks/workspace-WDKLN72J.ts.map +7 -0
  138. package/dist/index.ts +1057 -0
  139. package/dist/index.ts.map +7 -0
  140. package/package.json +9 -5
  141. package/src/index.ts +1 -1
  142. package/src/settings-reader.ts +208 -0
  143. package/src/settings.ts +22 -187
  144. package/src/stateful-registration.ts +1230 -0
  145. package/src/stateful-safety.ts +1 -1
  146. package/src/stateful.ts +2 -1234
  147. package/src/subagents-extension.ts +307 -0
  148. package/src/subagents.ts +1 -308
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/workflow-tree-identity.ts", "../../src/workflow-verification.ts", "../../src/work-item-persistence.ts", "../../src/integration-controller.ts", "../../src/verification-receipt.ts", "../../src/work-item-ledger.ts"],
4
+ "sourcesContent": ["import { execFile } from \"node:child_process\";\nimport { createHash, type Hash } from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nexport const WORKFLOW_TREE_IDENTITY_VERSION = \"pi-subagents:workflow-tree:v1\" as const;\nexport const DEFAULT_WORKFLOW_TREE_MAX_BYTES = 1024 * 1024;\nconst MAX_UNTRACKED_FILES = 256;\n\nexport interface WorkflowTreeIdentity {\n\tversion: typeof WORKFLOW_TREE_IDENTITY_VERSION;\n\tkind: \"git-commit\" | \"git-dirty\";\n\tdigest: string;\n}\n\nexport interface CaptureWorkflowTreeIdentityOptions {\n\tmaxBytes?: number;\n\tsignal?: AbortSignal;\n}\n\nexport async function captureWorkflowTreeIdentity(\n\tcwd: string,\n\toptions: CaptureWorkflowTreeIdentityOptions = {},\n): Promise<WorkflowTreeIdentity> {\n\tconst maxBytes = options.maxBytes ?? DEFAULT_WORKFLOW_TREE_MAX_BYTES;\n\tif (!Number.isSafeInteger(maxBytes) || maxBytes < 1) {\n\t\tthrow new Error(\"Workflow tree identity maxBytes must be a positive safe integer\");\n\t}\n\tthrowIfAborted(options.signal);\n\tlet canonicalCwd: string;\n\ttry {\n\t\tcanonicalCwd = await fs.promises.realpath(path.resolve(cwd));\n\t} catch {\n\t\tthrow new Error(\"Workflow verification requires a readable Git repository directory\");\n\t}\n\tconst rootOutput = await git(\n\t\tcanonicalCwd,\n\t\t[\"rev-parse\", \"--show-toplevel\"],\n\t\t64 * 1024,\n\t\toptions.signal,\n\t).catch((error) => {\n\t\tthrow normalizedGitError(error, \"Workflow verification requires a Git repository\");\n\t});\n\tlet repositoryRoot: string;\n\ttry {\n\t\trepositoryRoot = await fs.promises.realpath(rootOutput.toString(\"utf8\").trim());\n\t} catch {\n\t\tthrow new Error(\"Workflow verification requires a readable Git repository root\");\n\t}\n\tconst relativeCwd = path.relative(repositoryRoot, canonicalCwd);\n\tif (relativeCwd.startsWith(\"..\") || path.isAbsolute(relativeCwd)) {\n\t\tthrow new Error(\"Workflow verification cwd is outside its Git repository\");\n\t}\n\tconst submodules = await git(\n\t\trepositoryRoot,\n\t\t[\"submodule\", \"status\", \"--recursive\"],\n\t\t64 * 1024,\n\t\toptions.signal,\n\t).catch((error) => {\n\t\tthrow normalizedGitError(error, \"Workflow tree identity could not inspect submodules\");\n\t});\n\tif (submodules.toString(\"utf8\").trim()) {\n\t\tthrow new Error(\"Workflow tree identity does not support repositories with submodules\");\n\t}\n\tconst head = (\n\t\tawait git(repositoryRoot, [\"rev-parse\", \"HEAD\"], 64 * 1024, options.signal).catch((error) => {\n\t\t\tthrow normalizedGitError(error, \"Workflow verification requires a stable Git HEAD\");\n\t\t})\n\t)\n\t\t.toString(\"utf8\")\n\t\t.trim();\n\tif (!/^[a-f0-9]{40,64}$/u.test(head)) {\n\t\tthrow new Error(\"Workflow verification requires a stable Git HEAD\");\n\t}\n\tconst commandLimit = maxBytes + 1;\n\tconst indexDiff = await git(\n\t\trepositoryRoot,\n\t\t[\"diff\", \"--binary\", \"--no-ext-diff\", \"--cached\", \"HEAD\", \"--\"],\n\t\tcommandLimit,\n\t\toptions.signal,\n\t).catch((error) => {\n\t\tthrow normalizedGitError(error, \"Workflow tree identity exceeded its size limit\");\n\t});\n\tconst worktreeDiff = await git(\n\t\trepositoryRoot,\n\t\t[\"diff\", \"--binary\", \"--no-ext-diff\", \"--\"],\n\t\tcommandLimit,\n\t\toptions.signal,\n\t).catch((error) => {\n\t\tthrow normalizedGitError(error, \"Workflow tree identity exceeded its size limit\");\n\t});\n\tif (indexDiff.length > maxBytes || worktreeDiff.length > maxBytes) {\n\t\tthrow new Error(\"Workflow tree identity exceeded its size limit\");\n\t}\n\tconst untrackedOutput = await git(\n\t\trepositoryRoot,\n\t\t[\"ls-files\", \"--others\", \"--exclude-standard\", \"-z\"],\n\t\tcommandLimit,\n\t\toptions.signal,\n\t).catch((error) => {\n\t\tthrow normalizedGitError(error, \"Workflow tree identity exceeded its size limit\");\n\t});\n\tconst untrackedEntries = splitNul(untrackedOutput).sort(Buffer.compare);\n\tif (untrackedEntries.length > MAX_UNTRACKED_FILES) {\n\t\tthrow new Error(\"Workflow tree identity exceeded its untracked-file limit\");\n\t}\n\tif (indexDiff.length === 0 && worktreeDiff.length === 0 && untrackedEntries.length === 0) {\n\t\treturn identity(\"git-commit\", hashParts([Buffer.from(\"commit\\0\"), Buffer.from(head)]));\n\t}\n\tlet consumed = indexDiff.length + worktreeDiff.length + untrackedOutput.length;\n\tif (consumed > maxBytes) throw new Error(\"Workflow tree identity exceeded its size limit\");\n\tconst hasher = createHash(\"sha256\");\n\thasher.update(\"pi-subagents:workflow-tree:v1\\0\");\n\tupdateHashFrame(hasher, \"head\", head);\n\tupdateHashFrame(hasher, \"index-diff\", indexDiff);\n\tupdateHashFrame(hasher, \"worktree-diff\", worktreeDiff);\n\tfor (const rawRelativePath of untrackedEntries) {\n\t\tthrowIfAborted(options.signal);\n\t\tconst relativePath = decodeGitPath(rawRelativePath);\n\t\tconst candidate = path.resolve(repositoryRoot, relativePath);\n\t\tconst relative = path.relative(repositoryRoot, candidate);\n\t\tif (!relative || relative.startsWith(\"..\") || path.isAbsolute(relative)) {\n\t\t\tthrow new Error(\"Workflow tree identity encountered an unsafe untracked path\");\n\t\t}\n\t\tlet bytes: Buffer;\n\t\tlet kind: string;\n\t\ttry {\n\t\t\tconst stat = await fs.promises.lstat(candidate);\n\t\t\tif (stat.isSymbolicLink()) {\n\t\t\t\tkind = \"symlink\";\n\t\t\t\tbytes = Buffer.from(await fs.promises.readlink(candidate), \"utf8\");\n\t\t\t} else if (stat.isFile()) {\n\t\t\t\tkind = \"file\";\n\t\t\t\tif (stat.size > maxBytes - consumed) {\n\t\t\t\t\tthrow new Error(\"Workflow tree identity exceeded its size limit\");\n\t\t\t\t}\n\t\t\t\tbytes = await readRegularFileNoFollow(candidate, stat, options.signal);\n\t\t\t} else {\n\t\t\t\tthrow new Error(\"Workflow tree identity encountered an unsupported untracked file type\");\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && error.name === \"AbortError\") throw error;\n\t\t\tif (error instanceof Error && error.message.startsWith(\"Workflow tree identity\")) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tthrow new Error(\"Workflow tree identity could not read an untracked entry\");\n\t\t}\n\t\tconsumed += rawRelativePath.length + bytes.length;\n\t\tif (consumed > maxBytes) throw new Error(\"Workflow tree identity exceeded its size limit\");\n\t\tupdateHashFrame(hasher, \"untracked-kind\", kind);\n\t\tupdateHashFrame(hasher, \"untracked-path\", rawRelativePath);\n\t\tupdateHashFrame(hasher, \"untracked-content\", bytes);\n\t}\n\treturn identity(\"git-dirty\", hasher.digest(\"hex\"));\n}\n\nexport function sameWorkflowTreeIdentity(\n\tleft: WorkflowTreeIdentity,\n\tright: WorkflowTreeIdentity,\n): boolean {\n\treturn (\n\t\tisWorkflowTreeIdentity(left) &&\n\t\tisWorkflowTreeIdentity(right) &&\n\t\tleft.kind === right.kind &&\n\t\tleft.digest === right.digest\n\t);\n}\n\nexport function isWorkflowTreeIdentity(value: unknown): value is WorkflowTreeIdentity {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst candidate = value as Partial<WorkflowTreeIdentity>;\n\tif (\n\t\tObject.keys(value as Record<string, unknown>).some(\n\t\t\t(key) => ![\"version\", \"kind\", \"digest\"].includes(key),\n\t\t)\n\t) {\n\t\treturn false;\n\t}\n\treturn (\n\t\tcandidate.version === WORKFLOW_TREE_IDENTITY_VERSION &&\n\t\t(candidate.kind === \"git-commit\" || candidate.kind === \"git-dirty\") &&\n\t\ttypeof candidate.digest === \"string\" &&\n\t\t/^[a-f0-9]{64}$/u.test(candidate.digest)\n\t);\n}\n\nfunction identity(kind: WorkflowTreeIdentity[\"kind\"], digest: string): WorkflowTreeIdentity {\n\treturn { version: WORKFLOW_TREE_IDENTITY_VERSION, kind, digest };\n}\n\nfunction hashParts(parts: Buffer[]): string {\n\tconst hash = createHash(\"sha256\");\n\tfor (const part of parts) hash.update(part);\n\treturn hash.digest(\"hex\");\n}\n\nfunction updateHashFrame(hash: Hash, label: string, value: string | Buffer): void {\n\tconst labelBytes = Buffer.from(label, \"utf8\");\n\tconst valueBytes = typeof value === \"string\" ? Buffer.from(value, \"utf8\") : value;\n\tconst header = Buffer.allocUnsafe(8);\n\theader.writeUInt32BE(labelBytes.length, 0);\n\theader.writeUInt32BE(valueBytes.length, 4);\n\thash.update(header);\n\thash.update(labelBytes);\n\thash.update(valueBytes);\n}\n\nfunction splitNul(value: Buffer): Buffer[] {\n\tconst entries: Buffer[] = [];\n\tlet start = 0;\n\tfor (let index = 0; index < value.length; index++) {\n\t\tif (value[index] !== 0) continue;\n\t\tif (index > start) entries.push(value.subarray(start, index));\n\t\tstart = index + 1;\n\t}\n\tif (start < value.length) entries.push(value.subarray(start));\n\treturn entries;\n}\n\nfunction decodeGitPath(value: Buffer): string {\n\tconst decoded = value.toString(\"utf8\");\n\tif (!decoded || decoded.includes(\"\\0\") || !Buffer.from(decoded, \"utf8\").equals(value)) {\n\t\tthrow new Error(\"Workflow tree identity encountered an unsupported Git path encoding\");\n\t}\n\treturn decoded;\n}\n\nasync function readRegularFileNoFollow(\n\tfilePath: string,\n\texpected: fs.Stats,\n\tsignal: AbortSignal | undefined,\n): Promise<Buffer> {\n\tthrowIfAborted(signal);\n\tconst handle = await fs.promises.open(filePath, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);\n\ttry {\n\t\tconst before = await handle.stat();\n\t\tif (!before.isFile() || before.dev !== expected.dev || before.ino !== expected.ino) {\n\t\t\tthrow new Error(\"Workflow tree identity file changed during capture\");\n\t\t}\n\t\tconst content = await handle.readFile({ signal });\n\t\tconst after = await handle.stat();\n\t\tif (\n\t\t\tafter.dev !== before.dev ||\n\t\t\tafter.ino !== before.ino ||\n\t\t\tafter.size !== before.size ||\n\t\t\tafter.mtimeMs !== before.mtimeMs\n\t\t) {\n\t\t\tthrow new Error(\"Workflow tree identity file changed during capture\");\n\t\t}\n\t\treturn content;\n\t} finally {\n\t\tawait handle.close();\n\t}\n}\n\nfunction git(\n\tcwd: string,\n\targs: string[],\n\tmaxBuffer: number,\n\tsignal?: AbortSignal,\n): Promise<Buffer> {\n\tthrowIfAborted(signal);\n\treturn new Promise((resolve, reject) => {\n\t\texecFile(\n\t\t\t\"git\",\n\t\t\t[\"-C\", cwd, ...args],\n\t\t\t{ encoding: \"buffer\", maxBuffer, signal },\n\t\t\t(error, stdout) => {\n\t\t\t\tif (error) reject(error);\n\t\t\t\telse resolve(stdout);\n\t\t\t},\n\t\t);\n\t});\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n\tif (!signal?.aborted) return;\n\tconst error = new Error(\"Workflow tree identity capture was cancelled\");\n\terror.name = \"AbortError\";\n\tthrow error;\n}\n\nfunction normalizedGitError(error: unknown, fallback: string): Error {\n\tif (error instanceof Error && error.name === \"AbortError\") return error;\n\tconst message = error instanceof Error ? error.message : String(error);\n\treturn new Error(\n\t\t/maxBuffer|stdout.*large|SIGTERM/iu.test(message) ? `${fallback}: size limit` : fallback,\n\t);\n}\n", "import { redactPrivateText } from \"./context.js\";\nimport { truncateUtf8 } from \"./limits.js\";\nimport type { StructuredSubagentResultV2 } from \"./result-contract.js\";\nimport { isWorkflowTreeIdentity, type WorkflowTreeIdentity } from \"./workflow-tree-identity.js\";\n\nexport const WORKFLOW_VERIFICATION_VERSION = \"pi-subagents:workflow-verification:v1\" as const;\nexport type WorkflowVerificationDecision = \"accept\" | \"rework\" | \"reject\";\nconst MAX_FIELD_BYTES = 2 * 1024;\nconst MAX_ITEMS = 32;\nconst MAX_EVIDENCE_BYTES = 6 * 1024;\nconst MAX_LIMITATION_BYTES = 4 * 1024;\nconst MAX_INSTRUCTION_LIST_BYTES = 8 * 1024;\nconst ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/u;\nconst PLAN_PATTERN = /^[a-f0-9]{64}$/u;\n\nexport interface WorkflowVerificationReceipt {\n\tversion: typeof WORKFLOW_VERIFICATION_VERSION;\n\tdecision: WorkflowVerificationDecision;\n\ttargetTaskId: string;\n\ttargetTaskGeneration: number;\n\ttargetExecutionPlanId: string;\n\tverifierTaskId: string;\n\tverifierTaskGeneration: number;\n\tverifierExecutionPlanId: string;\n\ttreeIdentity: WorkflowTreeIdentity;\n\tsummary: string;\n\tevidence: string[];\n\tlimitations: string[];\n\tcreatedAt: number;\n\ttruncated: boolean;\n}\n\nexport interface WorkflowVerificationContext {\n\ttargetTaskId: string;\n\ttargetTaskGeneration: number;\n\ttargetExecutionPlanId: string;\n\tverifierTaskId: string;\n\tverifierTaskGeneration: number;\n\tverifierExecutionPlanId: string;\n\ttreeIdentity: WorkflowTreeIdentity;\n\tcreatedAt?: number;\n\tsourceTruncated?: boolean;\n}\n\nexport function createWorkflowVerificationReceipt(\n\tresult: StructuredSubagentResultV2,\n\tcontext: WorkflowVerificationContext,\n): WorkflowVerificationReceipt {\n\tvalidateContext(context);\n\tconst decision = verdict(result);\n\tconst boundedSummary = bound(result.summary);\n\tif (!boundedSummary.value) throw new Error(\"Workflow verification verdict requires a summary\");\n\tconst evidenceSource = [\n\t\t...result.claims.flatMap((claim) => claim.evidence),\n\t\t...result.verification.flatMap((item) => [item.summary, ...(item.evidence ?? [])]),\n\t];\n\tconst evidence = boundList(evidenceSource, MAX_EVIDENCE_BYTES);\n\tconst limitations = boundList(\n\t\t[...result.limitations, ...result.unresolvedDependencies],\n\t\tMAX_LIMITATION_BYTES,\n\t);\n\tif (decision === \"rework\" && limitations.values.length === 0) {\n\t\tthrow new Error(\"Workflow verification rework requires a limitation or unresolved dependency\");\n\t}\n\tif (decision === \"reject\" && evidence.values.length === 0) {\n\t\tthrow new Error(\"Workflow verification reject requires evidence\");\n\t}\n\treturn {\n\t\tversion: WORKFLOW_VERIFICATION_VERSION,\n\t\tdecision,\n\t\ttargetTaskId: context.targetTaskId,\n\t\ttargetTaskGeneration: context.targetTaskGeneration,\n\t\ttargetExecutionPlanId: context.targetExecutionPlanId,\n\t\tverifierTaskId: context.verifierTaskId,\n\t\tverifierTaskGeneration: context.verifierTaskGeneration,\n\t\tverifierExecutionPlanId: context.verifierExecutionPlanId,\n\t\ttreeIdentity: structuredClone(context.treeIdentity),\n\t\tsummary: boundedSummary.value,\n\t\tevidence: evidence.values,\n\t\tlimitations: limitations.values,\n\t\tcreatedAt: context.createdAt ?? Date.now(),\n\t\ttruncated:\n\t\t\tcontext.sourceTruncated === true ||\n\t\t\tboundedSummary.truncated ||\n\t\t\tevidence.truncated ||\n\t\t\tlimitations.truncated,\n\t};\n}\n\nexport function workflowVerificationInstruction(\n\ttargetTaskId: string,\n\ttreeIdentity: WorkflowTreeIdentity,\n\trequirements: {\n\t\tacceptanceCriteria?: readonly string[];\n\t\trequiredEvidence?: readonly string[];\n\t} = {},\n): string {\n\tif (!ID_PATTERN.test(targetTaskId) || !isWorkflowTreeIdentity(treeIdentity)) {\n\t\tthrow new Error(\"Workflow verification instruction received invalid executor metadata\");\n\t}\n\tconst acceptanceCriteria = boundList(\n\t\trequirements.acceptanceCriteria ?? [],\n\t\tMAX_INSTRUCTION_LIST_BYTES,\n\t).values;\n\tconst requiredEvidence = boundList(\n\t\trequirements.requiredEvidence ?? [],\n\t\tMAX_INSTRUCTION_LIST_BYTES,\n\t).values;\n\treturn [\n\t\t\"You are the independent verifier for one staged workflow result.\",\n\t\t`Target task: ${JSON.stringify(targetTaskId)}.`,\n\t\t`Acceptance criteria: ${JSON.stringify(acceptanceCriteria)}.`,\n\t\t`Required evidence: ${JSON.stringify(requiredEvidence)}.`,\n\t\t`Exact Git-visible tree identity: ${treeIdentity.version}:${treeIdentity.kind}:${treeIdentity.digest}.`,\n\t\t\"Do not modify the repository; the executor will reject acceptance if the tree identity changes.\",\n\t\t\"Return the requested pi-subagents:result:v2 object with exactly one verdict encoding.\",\n\t\t'Accept only with status \"completed\", reasonCode \"verification-accepted\", at least one passed verification item, no failed verification item, and no unresolved dependency.',\n\t\t'Request rework only with status \"partial\" or \"needs-input\", reasonCode \"verification-rework\", and a concrete limitation or unresolved dependency.',\n\t\t'Reject only with status \"failed\" or \"abstained\", reasonCode \"verification-rejected\", and concrete evidence.',\n\t\t\"Agreement, confidence, and the implementation worker's own verification claims are not proof.\",\n\t].join(\"\\n\");\n}\n\nexport function isWorkflowVerificationReceipt(\n\tvalue: unknown,\n): value is WorkflowVerificationReceipt {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst receipt = value as Partial<WorkflowVerificationReceipt>;\n\tif (\n\t\tObject.keys(value as Record<string, unknown>).some(\n\t\t\t(key) =>\n\t\t\t\t![\n\t\t\t\t\t\"version\",\n\t\t\t\t\t\"decision\",\n\t\t\t\t\t\"targetTaskId\",\n\t\t\t\t\t\"targetTaskGeneration\",\n\t\t\t\t\t\"targetExecutionPlanId\",\n\t\t\t\t\t\"verifierTaskId\",\n\t\t\t\t\t\"verifierTaskGeneration\",\n\t\t\t\t\t\"verifierExecutionPlanId\",\n\t\t\t\t\t\"treeIdentity\",\n\t\t\t\t\t\"summary\",\n\t\t\t\t\t\"evidence\",\n\t\t\t\t\t\"limitations\",\n\t\t\t\t\t\"createdAt\",\n\t\t\t\t\t\"truncated\",\n\t\t\t\t].includes(key),\n\t\t)\n\t) {\n\t\treturn false;\n\t}\n\treturn (\n\t\treceipt.version === WORKFLOW_VERIFICATION_VERSION &&\n\t\t(receipt.decision !== \"rework\" ||\n\t\t\t(Array.isArray(receipt.limitations) && receipt.limitations.length > 0)) &&\n\t\t(receipt.decision !== \"reject\" ||\n\t\t\t(Array.isArray(receipt.evidence) && receipt.evidence.length > 0)) &&\n\t\t[\"accept\", \"rework\", \"reject\"].includes(String(receipt.decision)) &&\n\t\ttypeof receipt.targetTaskId === \"string\" &&\n\t\tID_PATTERN.test(receipt.targetTaskId) &&\n\t\tNumber.isSafeInteger(receipt.targetTaskGeneration) &&\n\t\tNumber(receipt.targetTaskGeneration) >= 1 &&\n\t\ttypeof receipt.targetExecutionPlanId === \"string\" &&\n\t\tPLAN_PATTERN.test(receipt.targetExecutionPlanId) &&\n\t\ttypeof receipt.verifierTaskId === \"string\" &&\n\t\tID_PATTERN.test(receipt.verifierTaskId) &&\n\t\tNumber.isSafeInteger(receipt.verifierTaskGeneration) &&\n\t\tNumber(receipt.verifierTaskGeneration) >= 1 &&\n\t\ttypeof receipt.verifierExecutionPlanId === \"string\" &&\n\t\tPLAN_PATTERN.test(receipt.verifierExecutionPlanId) &&\n\t\tisWorkflowTreeIdentity(receipt.treeIdentity) &&\n\t\ttypeof receipt.summary === \"string\" &&\n\t\treceipt.summary.length > 0 &&\n\t\tBuffer.byteLength(receipt.summary, \"utf8\") <= MAX_FIELD_BYTES &&\n\t\tvalidStrings(receipt.evidence, MAX_EVIDENCE_BYTES) &&\n\t\tvalidStrings(receipt.limitations, MAX_LIMITATION_BYTES) &&\n\t\ttypeof receipt.createdAt === \"number\" &&\n\t\tNumber.isFinite(receipt.createdAt) &&\n\t\treceipt.createdAt >= 0 &&\n\t\ttypeof receipt.truncated === \"boolean\"\n\t);\n}\n\nfunction verdict(result: StructuredSubagentResultV2): WorkflowVerificationDecision {\n\tif (result.version !== \"pi-subagents:result:v2\") {\n\t\tthrow new Error(\"Workflow verification requires structured-v2\");\n\t}\n\tif (result.reasonCode === \"verification-accepted\" && result.status === \"completed\") {\n\t\tif (result.verification.some((item) => item.status === \"failed\")) {\n\t\t\tthrow new Error(\"Workflow verification accept cannot contain failed evidence\");\n\t\t}\n\t\tif (!result.verification.some((item) => item.status === \"passed\")) {\n\t\t\tthrow new Error(\"Workflow verification accept requires passed evidence\");\n\t\t}\n\t\tif (result.unresolvedDependencies.length > 0) {\n\t\t\tthrow new Error(\"Workflow verification accept cannot contain unresolved dependencies\");\n\t\t}\n\t\treturn \"accept\";\n\t}\n\tif (\n\t\tresult.reasonCode === \"verification-rework\" &&\n\t\t(result.status === \"partial\" || result.status === \"needs-input\")\n\t) {\n\t\treturn \"rework\";\n\t}\n\tif (\n\t\tresult.reasonCode === \"verification-rejected\" &&\n\t\t(result.status === \"failed\" || result.status === \"abstained\")\n\t) {\n\t\treturn \"reject\";\n\t}\n\tthrow new Error(\"Workflow verification result does not contain a valid verdict\");\n}\n\nfunction validateContext(context: WorkflowVerificationContext): void {\n\tfor (const [label, value] of [\n\t\t[\"target task\", context.targetTaskId],\n\t\t[\"verifier task\", context.verifierTaskId],\n\t] as const) {\n\t\tif (!ID_PATTERN.test(value))\n\t\t\tthrow new Error(`Workflow verification has an invalid ${label} id`);\n\t}\n\tfor (const [label, value] of [\n\t\t[\"target\", context.targetTaskGeneration],\n\t\t[\"verifier\", context.verifierTaskGeneration],\n\t] as const) {\n\t\tif (!Number.isSafeInteger(value) || value < 1) {\n\t\t\tthrow new Error(`Workflow verification has an invalid ${label} task generation`);\n\t\t}\n\t}\n\tfor (const value of [context.targetExecutionPlanId, context.verifierExecutionPlanId]) {\n\t\tif (!PLAN_PATTERN.test(value)) {\n\t\t\tthrow new Error(\"Workflow verification has an invalid execution plan identity\");\n\t\t}\n\t}\n\tif (!isWorkflowTreeIdentity(context.treeIdentity)) {\n\t\tthrow new Error(\"Workflow verification has an invalid tree identity\");\n\t}\n\tif (context.sourceTruncated !== undefined && typeof context.sourceTruncated !== \"boolean\") {\n\t\tthrow new Error(\"Workflow verification has an invalid truncation state\");\n\t}\n\tif (\n\t\tcontext.createdAt !== undefined &&\n\t\t(!Number.isFinite(context.createdAt) || context.createdAt < 0)\n\t) {\n\t\tthrow new Error(\"Workflow verification has an invalid creation time\");\n\t}\n}\n\nfunction bound(value: string): { value: string; truncated: boolean } {\n\tconst redacted = redactPrivateText(value).trim();\n\tconst truncated = truncateUtf8(redacted, MAX_FIELD_BYTES);\n\treturn { value: truncated.text, truncated: truncated.truncated };\n}\n\nfunction boundList(\n\tvalues: readonly string[],\n\tmaxTotalBytes: number,\n): { values: string[]; truncated: boolean } {\n\tlet truncated = values.length > MAX_ITEMS;\n\tlet remaining = maxTotalBytes;\n\tconst result: string[] = [];\n\tconst seen = new Set<string>();\n\tfor (const raw of values.slice(0, MAX_ITEMS)) {\n\t\tif (remaining < 1) {\n\t\t\ttruncated = true;\n\t\t\tbreak;\n\t\t}\n\t\tconst redacted = redactPrivateText(raw).trim();\n\t\tconst item = truncateUtf8(redacted, Math.min(MAX_FIELD_BYTES, remaining));\n\t\ttruncated ||= item.truncated;\n\t\tif (!item.text || seen.has(item.text)) continue;\n\t\tseen.add(item.text);\n\t\tresult.push(item.text);\n\t\tremaining -= Buffer.byteLength(item.text, \"utf8\");\n\t}\n\treturn { values: result, truncated };\n}\n\nfunction validStrings(value: unknown, maxTotalBytes: number): value is string[] {\n\treturn (\n\t\tArray.isArray(value) &&\n\t\tvalue.length <= MAX_ITEMS &&\n\t\tvalue.reduce(\n\t\t\t(total, item) =>\n\t\t\t\ttotal + (typeof item === \"string\" ? Buffer.byteLength(item, \"utf8\") : maxTotalBytes + 1),\n\t\t\t0,\n\t\t) <= maxTotalBytes &&\n\t\tvalue.every(\n\t\t\t(item) =>\n\t\t\t\ttypeof item === \"string\" &&\n\t\t\t\titem.length > 0 &&\n\t\t\t\tBuffer.byteLength(item, \"utf8\") <= MAX_FIELD_BYTES,\n\t\t)\n\t);\n}\n", "import { createHash } from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { getAgentDir, withFileMutationQueue } from \"@earendil-works/pi-coding-agent\";\nimport { redactPrivateText } from \"./context.js\";\nimport { WorkItemLedger, type WorkItemLedgerSnapshot } from \"./work-item-ledger.js\";\n\nconst WORKFLOW_STATE_DIRECTORY = \"pi-subagents-workflows\";\nconst DEFAULT_MAX_STORED_WORKFLOWS = 64;\nconst DEFAULT_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;\nconst MAX_WORKFLOW_STATE_BYTES = 1024 * 1024;\n\nexport interface SessionWorkflowPersistenceOptions {\n\tstateDir?: string;\n\tmaxStoredWorkflows?: number;\n\tretentionMs?: number;\n}\n\nexport interface SessionWorkflowInspection {\n\tworkflows: WorkItemLedgerSnapshot[];\n\tinvalid: number;\n\tomitted: number;\n}\n\nexport class WorkItemPersistence {\n\tconstructor(\n\t\treadonly filePath: string,\n\t\tprivate readonly afterSave?: () => Promise<void>,\n\t) {}\n\n\tasync save(snapshot: WorkItemLedgerSnapshot): Promise<void> {\n\t\tconst filePath = path.resolve(this.filePath);\n\t\tconst sanitized = sanitizeWorkflowSnapshot(snapshot);\n\t\tconst content = `${JSON.stringify(sanitized)}\\n`;\n\t\tif (Buffer.byteLength(content, \"utf8\") > MAX_WORKFLOW_STATE_BYTES) {\n\t\t\tthrow new Error(\"WorkItem workflow state exceeds the persistence size limit\");\n\t\t}\n\t\tawait withFileMutationQueue(filePath, async () => {\n\t\t\tawait fs.promises.mkdir(path.dirname(filePath), { recursive: true, mode: 0o700 });\n\t\t\tconst temporary = `${filePath}.${process.pid}.${Date.now()}.tmp`;\n\t\t\ttry {\n\t\t\t\tawait fs.promises.writeFile(temporary, content, { mode: 0o600 });\n\t\t\t\tawait fs.promises.rename(temporary, filePath);\n\t\t\t} finally {\n\t\t\t\tawait fs.promises.rm(temporary, { force: true });\n\t\t\t}\n\t\t});\n\t\tawait this.afterSave?.();\n\t}\n\n\tload(): WorkItemLedger | undefined {\n\t\tconst filePath = path.resolve(this.filePath);\n\t\tlet source: string;\n\t\ttry {\n\t\t\tconst stat = fs.statSync(filePath);\n\t\t\tif (stat.size > MAX_WORKFLOW_STATE_BYTES)\n\t\t\t\tthrow new Error(\"workflow state exceeds size limit\");\n\t\t\tsource = fs.readFileSync(filePath, \"utf8\");\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return undefined;\n\t\t\tthrow error;\n\t\t}\n\t\ttry {\n\t\t\treturn WorkItemLedger.restore(JSON.parse(source) as WorkItemLedgerSnapshot);\n\t\t} catch {\n\t\t\tconst quarantine = `${filePath}.invalid-${Date.now()}`;\n\t\t\ttry {\n\t\t\t\tfs.renameSync(filePath, quarantine);\n\t\t\t} catch {\n\t\t\t\t// A concurrent owner may already have handled the invalid file.\n\t\t\t}\n\t\t\treturn undefined;\n\t\t}\n\t}\n}\n\nexport function createSessionWorkItemPersistence(\n\towner: string,\n\tworkflowId: string,\n\toptions: SessionWorkflowPersistenceOptions = {},\n): WorkItemPersistence {\n\tconst maxStoredWorkflows = options.maxStoredWorkflows ?? DEFAULT_MAX_STORED_WORKFLOWS;\n\tconst retentionMs = options.retentionMs ?? DEFAULT_RETENTION_MS;\n\tif (!Number.isSafeInteger(maxStoredWorkflows) || maxStoredWorkflows < 1) {\n\t\tthrow new Error(\"maxStoredWorkflows must be a positive safe integer\");\n\t}\n\tif (!Number.isFinite(retentionMs) || retentionMs <= 0) {\n\t\tthrow new Error(\"workflow retentionMs must be a positive finite number\");\n\t}\n\tconst stateDir = resolveStateDirectory(options.stateDir);\n\tconst prefix = sessionPrefix(owner);\n\tconst filePath = path.join(stateDir, `${prefix}-${stableId(workflowId)}.json`);\n\treturn new WorkItemPersistence(filePath, () =>\n\t\tpruneSessionWorkflows(stateDir, prefix, maxStoredWorkflows, retentionMs),\n\t);\n}\n\nexport function inspectSessionWorkflows(\n\towner: string,\n\toptions: SessionWorkflowPersistenceOptions = {},\n): SessionWorkflowInspection {\n\tconst stateDir = resolveStateDirectory(options.stateDir);\n\tconst prefix = `${sessionPrefix(owner)}-`;\n\tconst limit = options.maxStoredWorkflows ?? DEFAULT_MAX_STORED_WORKFLOWS;\n\tif (!Number.isSafeInteger(limit) || limit < 1) {\n\t\tthrow new Error(\"maxStoredWorkflows must be a positive safe integer\");\n\t}\n\tlet entries: fs.Dirent[];\n\ttry {\n\t\tentries = fs.readdirSync(stateDir, { withFileTypes: true });\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n\t\t\treturn { workflows: [], invalid: 0, omitted: 0 };\n\t\t}\n\t\tthrow error;\n\t}\n\tconst candidates = entries\n\t\t.filter(\n\t\t\t(entry) => entry.isFile() && entry.name.startsWith(prefix) && entry.name.endsWith(\".json\"),\n\t\t)\n\t\t.map((entry) => {\n\t\t\tconst filePath = path.join(stateDir, entry.name);\n\t\t\treturn { filePath, modifiedAt: safeModifiedAt(filePath) };\n\t\t})\n\t\t.sort((left, right) => right.modifiedAt - left.modifiedAt);\n\tconst workflows: WorkItemLedgerSnapshot[] = [];\n\tlet invalid = 0;\n\tfor (const candidate of candidates.slice(0, limit)) {\n\t\ttry {\n\t\t\tconst stat = fs.statSync(candidate.filePath);\n\t\t\tif (stat.size > MAX_WORKFLOW_STATE_BYTES)\n\t\t\t\tthrow new Error(\"workflow state exceeds size limit\");\n\t\t\tconst source = fs.readFileSync(candidate.filePath, \"utf8\");\n\t\t\tworkflows.push(\n\t\t\t\tWorkItemLedger.restore(JSON.parse(source) as WorkItemLedgerSnapshot).snapshot(),\n\t\t\t);\n\t\t} catch {\n\t\t\tinvalid++;\n\t\t}\n\t}\n\treturn { workflows, invalid, omitted: Math.max(0, candidates.length - limit) };\n}\n\nfunction safeModifiedAt(filePath: string): number {\n\ttry {\n\t\treturn fs.statSync(filePath).mtimeMs;\n\t} catch {\n\t\treturn 0;\n\t}\n}\n\nfunction resolveStateDirectory(stateDir: string | undefined): string {\n\treturn path.resolve(stateDir ?? path.join(getAgentDir(), WORKFLOW_STATE_DIRECTORY));\n}\n\nfunction sessionPrefix(owner: string): string {\n\treturn stableId(`session:${owner}`);\n}\n\nfunction stableId(value: string): string {\n\treturn createHash(\"sha256\").update(value).digest(\"hex\").slice(0, 24);\n}\n\nasync function pruneSessionWorkflows(\n\tstateDir: string,\n\tprefix: string,\n\tmaxStoredWorkflows: number,\n\tretentionMs: number,\n): Promise<void> {\n\tawait withFileMutationQueue(path.join(stateDir, `${prefix}.prune`), async () => {\n\t\tconst cutoff = Date.now() - retentionMs;\n\t\tconst entries = (await fs.promises.readdir(stateDir, { withFileTypes: true }))\n\t\t\t.filter(\n\t\t\t\t(entry) =>\n\t\t\t\t\tentry.isFile() && entry.name.startsWith(`${prefix}-`) && entry.name.endsWith(\".json\"),\n\t\t\t)\n\t\t\t.map((entry) => path.join(stateDir, entry.name));\n\t\tconst records = await Promise.all(\n\t\t\tentries.map(async (filePath) => ({\n\t\t\t\tfilePath,\n\t\t\t\tmodifiedAt: (await fs.promises.stat(filePath)).mtimeMs,\n\t\t\t})),\n\t\t);\n\t\trecords.sort((left, right) => right.modifiedAt - left.modifiedAt);\n\t\tawait Promise.all(\n\t\t\trecords\n\t\t\t\t.filter((record, index) => index >= maxStoredWorkflows || record.modifiedAt < cutoff)\n\t\t\t\t.map((record) => fs.promises.rm(record.filePath, { force: true })),\n\t\t);\n\t});\n}\n\nfunction sanitizeWorkflowSnapshot(snapshot: WorkItemLedgerSnapshot): WorkItemLedgerSnapshot {\n\tconst sanitized = structuredClone(snapshot);\n\tfor (const item of sanitized.items) {\n\t\titem.objective = redact(item.objective);\n\t\titem.selectedAgentName = item.selectedAgentName ? redact(item.selectedAgentName) : undefined;\n\t\titem.requiredCapabilities = item.requiredCapabilities.map(redact);\n\t\titem.requiredTools = item.requiredTools.map(redact);\n\t\titem.readPaths = item.readPaths.map(redact);\n\t\titem.writePaths = item.writePaths.map(redact);\n\t\titem.ownershipKeys = item.ownershipKeys.map(redact);\n\t\titem.acceptanceCriteria = item.acceptanceCriteria.map(redact);\n\t\titem.requiredEvidence = item.requiredEvidence.map(redact);\n\t\titem.invalidationReasons = item.invalidationReasons.map(redact);\n\t\titem.outcomeReason = item.outcomeReason ? redact(item.outcomeReason) : undefined;\n\t\tif (item.verificationReceipt) {\n\t\t\titem.verificationReceipt.summary = redact(item.verificationReceipt.summary);\n\t\t\titem.verificationReceipt.evidence = item.verificationReceipt.evidence.map(redact);\n\t\t\titem.verificationReceipt.limitations = item.verificationReceipt.limitations.map(redact);\n\t\t}\n\t\tfor (const receipt of [\n\t\t\t...item.acceptanceReceiptHistory,\n\t\t\t...(item.acceptanceReceipt ? [item.acceptanceReceipt] : []),\n\t\t]) {\n\t\t\treceipt.summary = redact(receipt.summary);\n\t\t\treceipt.findings = receipt.findings.map(redact);\n\t\t\treceipt.changedPaths = receipt.changedPaths.map(redact);\n\t\t\treceipt.allowedScopes = receipt.allowedScopes.map(redact);\n\t\t\treceipt.acceptanceCriteria = receipt.acceptanceCriteria.map(redact);\n\t\t\treceipt.requiredEvidenceIds = receipt.requiredEvidenceIds.map(redact);\n\t\t\treceipt.dependencyVersions = redactRecord(receipt.dependencyVersions);\n\t\t\treceipt.readSetVersions = redactRecord(receipt.readSetVersions);\n\t\t\treceipt.evidence = redactRecord(receipt.evidence);\n\t\t\tfor (const check of receipt.checks) {\n\t\t\t\tcheck.stdout = redact(check.stdout);\n\t\t\t\tcheck.stderr = redact(check.stderr);\n\t\t\t}\n\t\t}\n\t\tif (item.submission) {\n\t\t\titem.submission.changedPaths = item.submission.changedPaths.map(redact);\n\t\t\titem.submission.fileVersions = Object.fromEntries(\n\t\t\t\tObject.entries(item.submission.fileVersions).map(([key, value]) => [redact(key), value]),\n\t\t\t);\n\t\t}\n\t\tfor (const artifact of [...item.artifacts, ...item.artifactHistory]) {\n\t\t\tartifact.kind = redact(artifact.kind);\n\t\t\tartifact.version = redact(artifact.version);\n\t\t\tartifact.digest = artifact.digest ? redact(artifact.digest) : undefined;\n\t\t}\n\t}\n\tWorkItemLedger.restore(sanitized);\n\treturn sanitized;\n}\n\nfunction redactRecord(value: Record<string, string>): Record<string, string> {\n\treturn Object.fromEntries(\n\t\tObject.entries(value).map(([key, item]) => [redact(key), redact(item)]),\n\t);\n}\n\nfunction redact(value: string): string {\n\treturn redactPrivateText(value).trim();\n}\n", "import * as path from \"node:path\";\n\nexport interface ManagedIntegrationExpectation {\n\ttaskId: string;\n\ttaskGeneration: number;\n\tbaseRepositoryGeneration: string;\n\tdependencyVersions: Record<string, string>;\n\treadSetVersions: Record<string, string>;\n\texecutionPlanId: string;\n\tallowedScopes: string[];\n\tpatchDigest: string;\n\trequiredEvidence: string[];\n}\n\nexport interface ManagedIntegrationCandidate extends ManagedIntegrationExpectation {\n\tchangedPaths: string[];\n\tevidence: Record<string, string>;\n\tverifier: {\n\t\tfreshContext: boolean;\n\t\texactIntegratedTree: boolean;\n\t\tstatus: \"accepted\" | \"rework\" | \"rejected\";\n\t};\n}\n\nexport interface ManagedIntegrationAcceptance {\n\tstatus: \"accepted\";\n\ttaskId: string;\n\ttaskGeneration: number;\n\tpatchDigest: string;\n\texecutionPlanId: string;\n}\n\nexport function verifyManagedIntegration(\n\texpected: ManagedIntegrationExpectation,\n\tcandidate: ManagedIntegrationCandidate,\n): ManagedIntegrationAcceptance {\n\tif (\n\t\tcandidate.taskId !== expected.taskId ||\n\t\tcandidate.taskGeneration !== expected.taskGeneration\n\t) {\n\t\tthrow new Error(\"Managed integration rejected stale task generation\");\n\t}\n\tif (candidate.baseRepositoryGeneration !== expected.baseRepositoryGeneration) {\n\t\tthrow new Error(\"Managed integration rejected stale base repository generation\");\n\t}\n\tif (candidate.executionPlanId !== expected.executionPlanId) {\n\t\tthrow new Error(\"Managed integration rejected stale execution plan identity\");\n\t}\n\tif (!sameRecord(candidate.dependencyVersions, expected.dependencyVersions)) {\n\t\tthrow new Error(\"Managed integration rejected stale dependency versions\");\n\t}\n\tif (!sameRecord(candidate.readSetVersions, expected.readSetVersions)) {\n\t\tthrow new Error(\"Managed integration rejected stale read-set versions\");\n\t}\n\tif (candidate.patchDigest !== expected.patchDigest) {\n\t\tthrow new Error(\"Managed integration rejected patch digest mismatch\");\n\t}\n\tconst allowedScopes = expected.allowedScopes.map(normalizedPath);\n\tif (\n\t\t!candidate.changedPaths.every((changedPath) => {\n\t\t\tconst normalizedChangedPath = normalizedPath(changedPath);\n\t\t\treturn allowedScopes.some(\n\t\t\t\t(scope) =>\n\t\t\t\t\tnormalizedChangedPath === scope ||\n\t\t\t\t\tnormalizedChangedPath.startsWith(`${scope}${path.sep}`),\n\t\t\t);\n\t\t})\n\t) {\n\t\tthrow new Error(\"Managed integration rejected a path outside the accepted scope\");\n\t}\n\tif (expected.requiredEvidence.some((id) => !candidate.evidence[id])) {\n\t\tthrow new Error(\"Managed integration rejected missing required evidence\");\n\t}\n\tif (!candidate.verifier.freshContext || !candidate.verifier.exactIntegratedTree) {\n\t\tthrow new Error(\"Managed integration requires a fresh verifier on the exact integrated tree\");\n\t}\n\tif (candidate.verifier.status !== \"accepted\") {\n\t\tthrow new Error(`Managed integration verifier returned ${candidate.verifier.status}`);\n\t}\n\treturn {\n\t\tstatus: \"accepted\",\n\t\ttaskId: expected.taskId,\n\t\ttaskGeneration: expected.taskGeneration,\n\t\tpatchDigest: expected.patchDigest,\n\t\texecutionPlanId: expected.executionPlanId,\n\t};\n}\n\nfunction normalizedPath(value: string): string {\n\tif (!value || value.includes(\"\\0\")) throw new Error(\"Managed integration scope is invalid\");\n\treturn path.resolve(path.sep, value.replaceAll(\"\\\\\", path.sep));\n}\n\nfunction sameRecord(left: Record<string, string>, right: Record<string, string>): boolean {\n\tconst leftEntries = Object.entries(left).sort(([a], [b]) => a.localeCompare(b));\n\tconst rightEntries = Object.entries(right).sort(([a], [b]) => a.localeCompare(b));\n\treturn JSON.stringify(leftEntries) === JSON.stringify(rightEntries);\n}\n", "import { type Static, Type } from \"typebox\";\nimport { Check } from \"typebox/value\";\nimport { redactPrivateText } from \"./context.js\";\nimport { truncateUtf8 } from \"./limits.js\";\nimport {\n\tWORKFLOW_TREE_IDENTITY_VERSION,\n\ttype WorkflowTreeIdentity,\n} from \"./workflow-tree-identity.js\";\n\nexport const VERIFICATION_RECEIPT_VERSION = \"pi-subagents:verification-receipt:v1\" as const;\nexport type VerificationReceiptDecision = \"accept\" | \"rework\" | \"reject\";\n\nconst MAX_FIELD_BYTES = 4 * 1024;\nconst MAX_OUTPUT_BYTES = 2 * 1024;\nconst MAX_RECEIPT_BYTES = 12 * 1024;\nconst MAX_LIST_ITEMS = 64;\nconst MAX_RECORD_ITEMS = 64;\nconst ID_PATTERN = \"^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$\";\nconst SHA_PATTERN = \"^[a-f0-9]{64}$\";\nconst REPOSITORY_GENERATION_PATTERN = \"^[a-f0-9]{40,64}$\";\n\nconst BoundedId = Type.String({ pattern: ID_PATTERN, maxLength: 256 });\nconst Sha256 = Type.String({ pattern: SHA_PATTERN, maxLength: 64 });\nconst BoundedText = Type.String({ minLength: 1, maxLength: MAX_FIELD_BYTES });\nconst TreeIdentitySchema = Type.Object(\n\t{\n\t\tversion: Type.Literal(WORKFLOW_TREE_IDENTITY_VERSION),\n\t\tkind: Type.Union([Type.Literal(\"git-commit\"), Type.Literal(\"git-dirty\")]),\n\t\tdigest: Sha256,\n\t},\n\t{ additionalProperties: false },\n);\nconst StringRecordSchema = Type.Record(\n\tType.String({ minLength: 1, maxLength: 4096 }),\n\tType.String({ minLength: 1, maxLength: MAX_FIELD_BYTES }),\n\t{ maxProperties: MAX_RECORD_ITEMS },\n);\n\nexport const VerificationCheckReceiptSchema = Type.Object(\n\t{\n\t\tid: BoundedId,\n\t\tcommand: Type.String({ minLength: 1, maxLength: 256 }),\n\t\targs: Type.Array(Type.String({ maxLength: 4096 }), { maxItems: 64 }),\n\t\tcwd: Type.String({ minLength: 1, maxLength: 4096 }),\n\t\tstatus: Type.Union([Type.Literal(\"passed\"), Type.Literal(\"failed\")]),\n\t\texitCode: Type.Integer({ minimum: -1, maximum: 255 }),\n\t\tstdout: Type.String({ maxLength: MAX_OUTPUT_BYTES }),\n\t\tstderr: Type.String({ maxLength: MAX_OUTPUT_BYTES }),\n\t\tdurationMs: Type.Integer({ minimum: 0 }),\n\t\ttruncated: Type.Boolean(),\n\t},\n\t{ additionalProperties: false },\n);\n\nexport const VerificationReceiptSchema = Type.Object(\n\t{\n\t\tversion: Type.Literal(VERIFICATION_RECEIPT_VERSION),\n\t\tdecision: Type.Union([Type.Literal(\"accept\"), Type.Literal(\"rework\"), Type.Literal(\"reject\")]),\n\t\ttargetTaskId: BoundedId,\n\t\ttargetTaskGeneration: Type.Integer({ minimum: 1 }),\n\t\ttargetExecutionPlanId: Sha256,\n\t\tverifierTaskId: BoundedId,\n\t\tverifierTaskGeneration: Type.Integer({ minimum: 1 }),\n\t\tverifierExecutionPlanId: Sha256,\n\t\tverifierAgent: BoundedId,\n\t\tbeforeTreeIdentity: TreeIdentitySchema,\n\t\tafterTreeIdentity: TreeIdentitySchema,\n\t\tbaseRepositoryGeneration: Type.String({\n\t\t\tpattern: REPOSITORY_GENERATION_PATTERN,\n\t\t\tmaxLength: 64,\n\t\t}),\n\t\tpatchDigest: Sha256,\n\t\tchangedPaths: Type.Array(Type.String({ minLength: 1, maxLength: 4096 }), {\n\t\t\tmaxItems: MAX_LIST_ITEMS,\n\t\t}),\n\t\tallowedScopes: Type.Array(Type.String({ minLength: 1, maxLength: 4096 }), {\n\t\t\tminItems: 1,\n\t\t\tmaxItems: MAX_LIST_ITEMS,\n\t\t}),\n\t\tdependencyVersions: StringRecordSchema,\n\t\treadSetVersions: StringRecordSchema,\n\t\tacceptanceCriteria: Type.Array(BoundedText, { maxItems: MAX_LIST_ITEMS }),\n\t\trequiredEvidenceIds: Type.Array(BoundedId, { maxItems: MAX_LIST_ITEMS }),\n\t\tevidence: StringRecordSchema,\n\t\tchecks: Type.Array(VerificationCheckReceiptSchema, { maxItems: 32 }),\n\t\tsummary: BoundedText,\n\t\tfindings: Type.Array(BoundedText, { maxItems: MAX_LIST_ITEMS }),\n\t\tcreatedAt: Type.Number({ minimum: 0 }),\n\t\tsourceTruncated: Type.Boolean(),\n\t},\n\t{ additionalProperties: false },\n);\n\nexport type VerificationCheckReceipt = Static<typeof VerificationCheckReceiptSchema>;\nexport type VerificationReceipt = Static<typeof VerificationReceiptSchema>;\nexport type CreateVerificationReceiptInput = Omit<VerificationReceipt, \"version\">;\n\nexport function createVerificationReceipt(\n\tinput: CreateVerificationReceiptInput,\n): VerificationReceipt {\n\tconst receipt: VerificationReceipt = {\n\t\tversion: VERIFICATION_RECEIPT_VERSION,\n\t\tdecision: input.decision,\n\t\ttargetTaskId: input.targetTaskId,\n\t\ttargetTaskGeneration: input.targetTaskGeneration,\n\t\ttargetExecutionPlanId: input.targetExecutionPlanId,\n\t\tverifierTaskId: input.verifierTaskId,\n\t\tverifierTaskGeneration: input.verifierTaskGeneration,\n\t\tverifierExecutionPlanId: input.verifierExecutionPlanId,\n\t\tverifierAgent: input.verifierAgent,\n\t\tbeforeTreeIdentity: structuredClone(input.beforeTreeIdentity),\n\t\tafterTreeIdentity: structuredClone(input.afterTreeIdentity),\n\t\tbaseRepositoryGeneration: input.baseRepositoryGeneration,\n\t\tpatchDigest: input.patchDigest,\n\t\tchangedPaths: boundList(input.changedPaths, MAX_FIELD_BYTES),\n\t\tallowedScopes: boundList(input.allowedScopes, MAX_FIELD_BYTES),\n\t\tdependencyVersions: boundRecord(input.dependencyVersions),\n\t\treadSetVersions: boundRecord(input.readSetVersions),\n\t\tacceptanceCriteria: boundList(input.acceptanceCriteria, MAX_FIELD_BYTES),\n\t\trequiredEvidenceIds: boundList(input.requiredEvidenceIds, 256),\n\t\tevidence: boundRecord(input.evidence),\n\t\tchecks: input.checks.slice(0, 32).map(boundCheck),\n\t\tsummary: boundRequired(input.summary, MAX_FIELD_BYTES, \"summary\"),\n\t\tfindings: boundList(input.findings, MAX_FIELD_BYTES),\n\t\tcreatedAt: input.createdAt,\n\t\tsourceTruncated:\n\t\t\tinput.sourceTruncated ||\n\t\t\tinput.checks.length > 32 ||\n\t\t\tinput.checks.some(\n\t\t\t\t(check) =>\n\t\t\t\t\tcheck.truncated ||\n\t\t\t\t\tcheck.args.length > 64 ||\n\t\t\t\t\tcheck.args.some((value) => Buffer.byteLength(value, \"utf8\") > 4096) ||\n\t\t\t\t\tBuffer.byteLength(check.stdout, \"utf8\") > MAX_OUTPUT_BYTES ||\n\t\t\t\t\tBuffer.byteLength(check.stderr, \"utf8\") > MAX_OUTPUT_BYTES,\n\t\t\t) ||\n\t\t\tinput.requiredEvidenceIds.some((value) => Buffer.byteLength(value, \"utf8\") > 256) ||\n\t\t\t[\n\t\t\t\tinput.changedPaths,\n\t\t\t\tinput.allowedScopes,\n\t\t\t\tinput.acceptanceCriteria,\n\t\t\t\tinput.requiredEvidenceIds,\n\t\t\t\tinput.findings,\n\t\t\t].some(\n\t\t\t\t(values) =>\n\t\t\t\t\tvalues.length > MAX_LIST_ITEMS ||\n\t\t\t\t\tvalues.some((value) => Buffer.byteLength(value, \"utf8\") > MAX_FIELD_BYTES),\n\t\t\t) ||\n\t\t\t[input.dependencyVersions, input.readSetVersions, input.evidence].some(\n\t\t\t\t(value) =>\n\t\t\t\t\tObject.keys(value).length > MAX_RECORD_ITEMS ||\n\t\t\t\t\tObject.entries(value).some(\n\t\t\t\t\t\t([key, item]) =>\n\t\t\t\t\t\t\tBuffer.byteLength(key, \"utf8\") > 4096 ||\n\t\t\t\t\t\t\tBuffer.byteLength(item, \"utf8\") > MAX_FIELD_BYTES,\n\t\t\t\t\t),\n\t\t\t),\n\t};\n\tassertReceiptSemantics(receipt);\n\tif (!Check(VerificationReceiptSchema, receipt)) {\n\t\tthrow new Error(\"Verification receipt contains invalid executor metadata\");\n\t}\n\tif (Buffer.byteLength(JSON.stringify(receipt), \"utf8\") > MAX_RECEIPT_BYTES) {\n\t\tthrow new Error(\"Verification receipt exceeded its total size limit\");\n\t}\n\treturn receipt;\n}\n\nexport function isVerificationReceipt(value: unknown): value is VerificationReceipt {\n\tif (\n\t\t!Check(VerificationReceiptSchema, value) ||\n\t\tBuffer.byteLength(JSON.stringify(value), \"utf8\") > MAX_RECEIPT_BYTES\n\t) {\n\t\treturn false;\n\t}\n\ttry {\n\t\tassertReceiptSemantics(value as VerificationReceipt);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction assertReceiptSemantics(receipt: VerificationReceipt): void {\n\tif (\n\t\treceipt.beforeTreeIdentity.kind !== receipt.afterTreeIdentity.kind ||\n\t\treceipt.beforeTreeIdentity.digest !== receipt.afterTreeIdentity.digest\n\t) {\n\t\tthrow new Error(\"Verification receipt rejected submitted-state drift\");\n\t}\n\tconst missingEvidence = receipt.requiredEvidenceIds.filter((id) => !receipt.evidence[id]);\n\tif (receipt.decision === \"accept\" && missingEvidence.length > 0) {\n\t\tthrow new Error(\n\t\t\t`Verification receipt is missing required evidence: ${missingEvidence.join(\", \")}`,\n\t\t);\n\t}\n\tif (receipt.decision === \"accept\" && receipt.checks.some((check) => check.status !== \"passed\")) {\n\t\tthrow new Error(\"Verification receipt cannot accept a failed check\");\n\t}\n\tif (receipt.decision === \"rework\" && receipt.findings.length === 0) {\n\t\tthrow new Error(\"Verification receipt rework requires a concrete finding\");\n\t}\n\tif (receipt.decision === \"reject\" && receipt.findings.length === 0) {\n\t\tthrow new Error(\"Verification receipt reject requires a concrete finding\");\n\t}\n\tfor (const values of [\n\t\treceipt.changedPaths,\n\t\treceipt.allowedScopes,\n\t\treceipt.acceptanceCriteria,\n\t\treceipt.requiredEvidenceIds,\n\t\treceipt.findings,\n\t]) {\n\t\tif (new Set(values).size !== values.length) {\n\t\t\tthrow new Error(\"Verification receipt contains duplicate bounded values\");\n\t\t}\n\t}\n\tif (new Set(receipt.checks.map((check) => check.id)).size !== receipt.checks.length) {\n\t\tthrow new Error(\"Verification receipt contains duplicate check ids\");\n\t}\n}\n\nfunction boundCheck(check: VerificationCheckReceipt): VerificationCheckReceipt {\n\tconst stdout = boundOptional(check.stdout, MAX_OUTPUT_BYTES);\n\tconst stderr = boundOptional(check.stderr, MAX_OUTPUT_BYTES);\n\treturn {\n\t\tid: boundRequired(check.id, 256, \"check id\"),\n\t\tcommand: boundRequired(check.command, 256, \"check command\"),\n\t\targs: check.args.slice(0, 64).map((value) => boundOptional(value, 4096).value),\n\t\tcwd: boundRequired(check.cwd, 4096, \"check cwd\"),\n\t\tstatus: check.status,\n\t\texitCode: check.exitCode,\n\t\tstdout: stdout.value,\n\t\tstderr: stderr.value,\n\t\tdurationMs: Math.max(0, Math.floor(check.durationMs)),\n\t\ttruncated: check.truncated || stdout.truncated || stderr.truncated || check.args.length > 64,\n\t};\n}\n\nfunction boundList(values: readonly string[], maxItemBytes: number): string[] {\n\tconst result: string[] = [];\n\tconst seen = new Set<string>();\n\tfor (const value of values.slice(0, MAX_LIST_ITEMS)) {\n\t\tconst bounded = boundOptional(value, maxItemBytes).value;\n\t\tif (!bounded || seen.has(bounded)) continue;\n\t\tseen.add(bounded);\n\t\tresult.push(bounded);\n\t}\n\treturn result;\n}\n\nfunction boundRecord(value: Record<string, string>): Record<string, string> {\n\tconst entries = Object.entries(value).slice(0, MAX_RECORD_ITEMS);\n\treturn Object.fromEntries(\n\t\tentries.map(([key, item]) => [\n\t\t\tboundRequired(key, 4096, \"record key\"),\n\t\t\tboundRequired(item, MAX_FIELD_BYTES, \"record value\"),\n\t\t]),\n\t);\n}\n\nfunction boundRequired(value: string, maxBytes: number, label: string): string {\n\tconst bounded = boundOptional(value, maxBytes).value;\n\tif (!bounded) throw new Error(`Verification receipt requires ${label}`);\n\treturn bounded;\n}\n\nfunction boundOptional(value: string, maxBytes: number): { value: string; truncated: boolean } {\n\tconst redacted = redactPrivateText(value).trim();\n\tconst bounded = truncateUtf8(redacted, maxBytes);\n\treturn { value: bounded.text, truncated: bounded.truncated };\n}\n\nexport function sameReceiptTree(left: WorkflowTreeIdentity, right: WorkflowTreeIdentity): boolean {\n\treturn left.kind === right.kind && left.digest === right.digest;\n}\n", "/**\n * Ledger transitions and restore validators stay together so every persisted acceptance invariant\n * is audited against the same atomic state machine rather than duplicated across modules.\n */\nimport {\n\ttype ManagedIntegrationCandidate,\n\ttype ManagedIntegrationExpectation,\n\tverifyManagedIntegration,\n} from \"./integration-controller.js\";\nimport type { VerificationSubmission } from \"./verification-harness.js\";\nimport { isVerificationReceipt, type VerificationReceipt } from \"./verification-receipt.js\";\nimport {\n\tisWorkflowTreeIdentity,\n\tsameWorkflowTreeIdentity,\n\ttype WorkflowTreeIdentity,\n} from \"./workflow-tree-identity.js\";\nimport {\n\tisWorkflowVerificationReceipt,\n\ttype WorkflowVerificationReceipt,\n} from \"./workflow-verification.js\";\n\nexport const WORK_ITEM_LEDGER_VERSION = \"pi-subagents:work-ledger:v3\" as const;\nconst LEGACY_WORK_ITEM_LEDGER_VERSIONS = new Set([\n\t\"pi-subagents:work-ledger:v1\",\n\t\"pi-subagents:work-ledger:v2\",\n]);\nexport const WORK_ITEM_ACCEPTANCE_VERSION = \"pi-subagents:work-acceptance:v1\" as const;\nexport type WorkItemAcceptanceState =\n\t| \"not-required\"\n\t| \"pending\"\n\t| \"accepted\"\n\t| \"rework-requested\"\n\t| \"rejected\";\n\nexport type WorkItemState =\n\t| \"pending\"\n\t| \"ready\"\n\t| \"running\"\n\t| \"awaiting-verification\"\n\t| \"blocked\"\n\t| \"needs-input\"\n\t| \"completed\"\n\t| \"failed\"\n\t| \"interrupted\"\n\t| \"stale\"\n\t| \"invalidated\";\n\nexport interface WorkArtifactReference {\n\tid: string;\n\tkind: string;\n\tversion: string;\n\tdigest?: string;\n\tproducerTaskId?: string;\n\tgeneration?: number;\n\tverified?: boolean;\n}\n\nexport interface WorkItemDefinition {\n\tid: string;\n\tobjective: string;\n\tdependencies: string[];\n\tinputArtifacts?: string[];\n\tinputArtifactVersions?: Record<string, string>;\n\trequiredCapabilities?: string[];\n\trequiredTools?: string[];\n\tselectedAgentName?: string;\n\tsideEffectPolicy?: \"read-only\" | \"idempotent\" | \"mutating\";\n\treadPaths?: string[];\n\twritePaths?: string[];\n\townershipKeys?: string[];\n\tacceptanceCriteria?: string[];\n\trequiredEvidence?: string[];\n\tintegrationOwner?: boolean;\n\tverifierFor?: string;\n\tdependencyPolicy?: \"completed\" | \"settled\";\n\tacceptanceRequired?: boolean;\n\tmaxReworkCycles?: 0 | 1;\n}\n\nexport interface WorkItemRecord {\n\tid: string;\n\tobjective: string;\n\tdependencies: string[];\n\tdependents: string[];\n\tstate: WorkItemState;\n\tgeneration: number;\n\ttaskGeneration: number;\n\tassignedAgentId?: string;\n\tacceptedExecutionPlanId?: string;\n\tinputArtifacts: string[];\n\tinputArtifactVersions: Record<string, string>;\n\trequiredArtifactVersions: Record<string, string>;\n\trequiredCapabilities: string[];\n\trequiredTools: string[];\n\tselectedAgentName?: string;\n\tsideEffectPolicy: \"read-only\" | \"idempotent\" | \"mutating\";\n\tartifacts: WorkArtifactReference[];\n\tartifactHistory: WorkArtifactReference[];\n\treadPaths: string[];\n\twritePaths: string[];\n\townershipKeys: string[];\n\tacceptanceCriteria: string[];\n\trequiredEvidence: string[];\n\tintegrationOwner: boolean;\n\tverifierFor?: string;\n\tdependencyPolicy: \"completed\" | \"settled\";\n\tacceptanceStateVersion: typeof WORK_ITEM_ACCEPTANCE_VERSION;\n\tacceptanceRequired: boolean;\n\tacceptanceState: WorkItemAcceptanceState;\n\treworkCount: number;\n\tmaxReworkCycles: 0 | 1;\n\tverificationAccepted: boolean;\n\tstagedTreeIdentity?: WorkflowTreeIdentity;\n\tverificationReceipt?: WorkflowVerificationReceipt;\n\tacceptanceReceipt?: VerificationReceipt;\n\tacceptanceReceiptHistory: VerificationReceipt[];\n\tsubmission?: VerificationSubmission;\n\tinvalidationReasons: string[];\n\toutcomeReason?: string;\n}\n\nexport interface WorkItemLedgerSnapshot {\n\tversion: typeof WORK_ITEM_LEDGER_VERSION;\n\tworkflowId: string;\n\tgeneration: number;\n\titems: WorkItemRecord[];\n}\n\nexport interface CreateWorkItemLedgerInput {\n\tworkflowId: string;\n\titems: WorkItemDefinition[];\n}\n\nexport interface CompleteWorkItemInput {\n\ttaskGeneration: number;\n\texecutionPlanId?: string;\n\tartifacts?: Array<Omit<WorkArtifactReference, \"producerTaskId\" | \"generation\">>;\n}\n\nexport interface StageWorkItemVerificationInput extends CompleteWorkItemInput {\n\texecutionPlanId: string;\n\ttreeIdentity: WorkflowTreeIdentity;\n}\n\nexport interface StageVerifiedAcceptanceInput\n\textends CompleteWorkItemInput,\n\t\tVerificationSubmission {\n\texecutionPlanId: string;\n}\n\nexport interface CompleteWorkItemVerificationInput {\n\ttaskGeneration: number;\n\texecutionPlanId: string;\n\treceipt: WorkflowVerificationReceipt;\n}\n\nexport interface RecordVerificationDecisionInput {\n\ttaskGeneration: number;\n\texecutionPlanId: string;\n\treceipt: VerificationReceipt;\n}\n\nexport interface VerifiedIntegrationInput {\n\tverifierId: string;\n\tverifierTaskGeneration: number;\n\tverifierExecutionPlanId: string;\n\treceipt: VerificationReceipt;\n}\n\nconst MAX_ITEMS = 64;\nconst MAX_IDENTIFIER_LENGTH = 256;\nconst MAX_TEXT_LENGTH = 16 * 1024;\nconst MAX_LIST_ITEMS = 50;\n\nconst TERMINAL_STATES = new Set<WorkItemState>([\n\t\"completed\",\n\t\"failed\",\n\t\"interrupted\",\n\t\"stale\",\n\t\"invalidated\",\n]);\n\nexport class WorkItemLedger {\n\tprivate readonly items = new Map<string, WorkItemRecord>();\n\tprivate generation = 0;\n\n\tprivate constructor(readonly workflowId: string) {}\n\n\tstatic create(input: CreateWorkItemLedgerInput): WorkItemLedger {\n\t\tvalidateIdentifier(input.workflowId, \"workflowId\");\n\t\tif (!Array.isArray(input.items) || input.items.length < 1 || input.items.length > MAX_ITEMS) {\n\t\t\tthrow new Error(`WorkItem workflow must contain 1-${MAX_ITEMS} items`);\n\t\t}\n\t\tconst ledger = new WorkItemLedger(input.workflowId);\n\t\tfor (const definition of input.items) ledger.addDefinition(definition);\n\t\tledger.linkAndValidate();\n\t\tledger.refreshReadyState();\n\t\treturn ledger;\n\t}\n\n\tget(id: string): WorkItemRecord | undefined {\n\t\tconst item = this.items.get(id);\n\t\treturn item ? structuredClone(item) : undefined;\n\t}\n\n\treadyItems(): WorkItemRecord[] {\n\t\tthis.refreshReadyState();\n\t\treturn [...this.items.values()]\n\t\t\t.filter((item) => item.state === \"ready\")\n\t\t\t.sort((left, right) => left.id.localeCompare(right.id))\n\t\t\t.map((item) => structuredClone(item));\n\t}\n\n\tstart(id: string, agentId: string): WorkItemRecord {\n\t\tconst item = this.require(id);\n\t\tif (item.state !== \"ready\") {\n\t\t\tthrow new Error(`WorkItem ${id} cannot start while ${item.state}`);\n\t\t}\n\t\tvalidateIdentifier(agentId, \"agentId\");\n\t\titem.state = \"running\";\n\t\titem.assignedAgentId = agentId;\n\t\titem.generation = ++this.generation;\n\t\treturn structuredClone(item);\n\t}\n\n\tcomplete(id: string, input: CompleteWorkItemInput): WorkItemRecord {\n\t\tconst item = this.require(id);\n\t\tthis.assertMutable(item);\n\t\tif (item.acceptanceRequired) {\n\t\t\tthrow new Error(`WorkItem ${id} requires executor-owned acceptance staging`);\n\t\t}\n\t\tif (item.state !== \"running\") {\n\t\t\tthrow new Error(`WorkItem ${id} cannot complete while ${item.state}`);\n\t\t}\n\t\tif (input.taskGeneration !== item.taskGeneration) {\n\t\t\tthrow new Error(`WorkItem ${id} rejected a stale task generation`);\n\t\t}\n\t\titem.acceptedExecutionPlanId = input.executionPlanId?.slice(0, 256);\n\t\titem.artifactHistory.push(...item.artifacts.map((artifact) => structuredClone(artifact)));\n\t\titem.artifacts = normalizeArtifacts(input.artifacts ?? [], id, this.generation + 1);\n\t\titem.verificationAccepted = false;\n\t\titem.stagedTreeIdentity = undefined;\n\t\titem.verificationReceipt = undefined;\n\t\titem.acceptanceState = \"not-required\";\n\t\titem.state = \"completed\";\n\t\titem.generation = ++this.generation;\n\t\tthis.refreshReadyState();\n\t\treturn structuredClone(item);\n\t}\n\n\tstageForVerifiedAcceptance(id: string, input: StageVerifiedAcceptanceInput): WorkItemRecord {\n\t\tconst item = this.require(id);\n\t\tthis.assertMutable(item);\n\t\tif (!item.acceptanceRequired || !item.integrationOwner) {\n\t\t\tthrow new Error(`WorkItem ${id} is not a verified integration target`);\n\t\t}\n\t\tif (item.state !== \"running\") {\n\t\t\tthrow new Error(`WorkItem ${id} cannot stage acceptance while ${item.state}`);\n\t\t}\n\t\tif (input.taskGeneration !== item.taskGeneration) {\n\t\t\tthrow new Error(`WorkItem ${id} rejected a stale task generation`);\n\t\t}\n\t\tvalidatePlanId(input.executionPlanId, \"staged execution plan\");\n\t\tvalidateSubmission(input);\n\t\titem.acceptedExecutionPlanId = input.executionPlanId;\n\t\titem.artifactHistory.push(...item.artifacts.map((artifact) => structuredClone(artifact)));\n\t\titem.artifacts = normalizeArtifacts(input.artifacts ?? [], id, this.generation + 1);\n\t\titem.verificationAccepted = false;\n\t\titem.acceptanceState = \"pending\";\n\t\titem.stagedTreeIdentity = structuredClone(input.treeIdentity);\n\t\titem.submission = {\n\t\t\ttreeIdentity: structuredClone(input.treeIdentity),\n\t\t\tbaseRepositoryGeneration: input.baseRepositoryGeneration,\n\t\t\tpatchDigest: input.patchDigest,\n\t\t\tchangedPaths: [...input.changedPaths],\n\t\t\tfileVersions: { ...input.fileVersions },\n\t\t};\n\t\titem.acceptanceReceipt = undefined;\n\t\titem.state = \"completed\";\n\t\titem.generation = ++this.generation;\n\t\tthis.refreshReadyState();\n\t\treturn structuredClone(item);\n\t}\n\n\tstageForVerification(id: string, input: StageWorkItemVerificationInput): WorkItemRecord {\n\t\tconst item = this.require(id);\n\t\tthis.assertMutable(item);\n\t\tif (item.state !== \"running\") {\n\t\t\tthrow new Error(`WorkItem ${id} cannot stage verification while ${item.state}`);\n\t\t}\n\t\tif (input.taskGeneration !== item.taskGeneration) {\n\t\t\tthrow new Error(`WorkItem ${id} rejected a stale task generation`);\n\t\t}\n\t\tvalidatePlanId(input.executionPlanId, \"staged execution plan\");\n\t\tif (!isWorkflowTreeIdentity(input.treeIdentity)) {\n\t\t\tthrow new Error(`WorkItem ${id} received an invalid staged tree identity`);\n\t\t}\n\t\titem.acceptedExecutionPlanId = input.executionPlanId;\n\t\titem.artifactHistory.push(...item.artifacts.map((artifact) => structuredClone(artifact)));\n\t\titem.artifacts = normalizeArtifacts(input.artifacts ?? [], id, this.generation + 1);\n\t\titem.verificationAccepted = false;\n\t\titem.stagedTreeIdentity = structuredClone(input.treeIdentity);\n\t\titem.verificationReceipt = undefined;\n\t\titem.state = \"awaiting-verification\";\n\t\titem.generation = ++this.generation;\n\t\tthis.refreshReadyState();\n\t\treturn structuredClone(item);\n\t}\n\n\tcompleteVerification(\n\t\tverifierId: string,\n\t\tinput: CompleteWorkItemVerificationInput,\n\t): { target: WorkItemRecord; verifier: WorkItemRecord } {\n\t\tconst verifier = this.require(verifierId);\n\t\tthis.assertMutable(verifier);\n\t\tif (verifier.state !== \"running\" || !verifier.verifierFor) {\n\t\t\tthrow new Error(`WorkItem ${verifierId} is not a running verifier`);\n\t\t}\n\t\tif (input.taskGeneration !== verifier.taskGeneration) {\n\t\t\tthrow new Error(`WorkItem ${verifierId} rejected a stale verifier generation`);\n\t\t}\n\t\tvalidatePlanId(input.executionPlanId, \"verifier execution plan\");\n\t\tif (!isWorkflowVerificationReceipt(input.receipt)) {\n\t\t\tthrow new Error(`WorkItem ${verifierId} received an invalid verification receipt`);\n\t\t}\n\t\tconst target = this.require(verifier.verifierFor);\n\t\tif (target.state !== \"awaiting-verification\") {\n\t\t\tthrow new Error(`WorkItem ${target.id} is not awaiting verification`);\n\t\t}\n\t\tassertReceiptMatches(target, verifier, input.executionPlanId, input.receipt);\n\t\tverifier.acceptedExecutionPlanId = input.executionPlanId;\n\t\tverifier.verificationReceipt = undefined;\n\t\tverifier.verificationAccepted = false;\n\t\tverifier.state = \"completed\";\n\t\tverifier.generation = ++this.generation;\n\t\ttarget.verificationReceipt = structuredClone(input.receipt);\n\t\ttarget.verificationAccepted = input.receipt.decision === \"accept\";\n\t\ttarget.outcomeReason =\n\t\t\tinput.receipt.decision === \"accept\"\n\t\t\t\t? undefined\n\t\t\t\t: input.receipt.decision === \"rework\"\n\t\t\t\t\t? \"verification-rework\"\n\t\t\t\t\t: \"verification-rejected\";\n\t\tif (input.receipt.decision === \"accept\") {\n\t\t\ttarget.artifacts = target.artifacts.map((artifact) => ({ ...artifact, verified: true }));\n\t\t\ttarget.state = \"completed\";\n\t\t} else {\n\t\t\ttarget.state = input.receipt.decision === \"rework\" ? \"blocked\" : \"failed\";\n\t\t\tthis.invalidateDependents(target.id, verifier.id, target.outcomeReason);\n\t\t}\n\t\ttarget.generation = ++this.generation;\n\t\tthis.refreshReadyState();\n\t\treturn { target: structuredClone(target), verifier: structuredClone(verifier) };\n\t}\n\n\trecordVerificationDecision(\n\t\tverifierId: string,\n\t\tinput: RecordVerificationDecisionInput,\n\t): { target: WorkItemRecord; verifier: WorkItemRecord } {\n\t\tconst verifier = this.require(verifierId);\n\t\tif (verifier.state !== \"running\" || !verifier.verifierFor) {\n\t\t\tthrow new Error(`WorkItem ${verifierId} is not a running verifier`);\n\t\t}\n\t\tif (input.taskGeneration !== verifier.taskGeneration) {\n\t\t\tthrow new Error(`WorkItem ${verifierId} rejected a stale verifier generation`);\n\t\t}\n\t\tvalidatePlanId(input.executionPlanId, \"verifier execution plan\");\n\t\tif (!isVerificationReceipt(input.receipt) || input.receipt.decision === \"accept\") {\n\t\t\tthrow new Error(`WorkItem ${verifierId} received an invalid non-acceptance receipt`);\n\t\t}\n\t\tconst target = this.require(verifier.verifierFor);\n\t\tassertVerifiedReceiptMatches(target, verifier, input.executionPlanId, input.receipt);\n\t\tverifier.acceptedExecutionPlanId = input.executionPlanId;\n\t\tverifier.state = \"completed\";\n\t\tverifier.generation = ++this.generation;\n\t\ttarget.acceptanceReceipt = structuredClone(input.receipt);\n\t\ttarget.acceptanceReceiptHistory.push(structuredClone(input.receipt));\n\t\ttarget.verificationAccepted = false;\n\t\tif (input.receipt.decision === \"rework\" && target.reworkCount < target.maxReworkCycles) {\n\t\t\ttarget.reworkCount++;\n\t\t\ttarget.acceptanceState = \"rework-requested\";\n\t\t\ttarget.state = \"blocked\";\n\t\t\ttarget.outcomeReason = \"verification-rework\";\n\t\t} else {\n\t\t\ttarget.acceptanceState = \"rejected\";\n\t\t\ttarget.state = \"failed\";\n\t\t\ttarget.outcomeReason =\n\t\t\t\tinput.receipt.decision === \"rework\"\n\t\t\t\t\t? \"verification-rework-exhausted\"\n\t\t\t\t\t: \"verification-rejected\";\n\t\t}\n\t\ttarget.generation = ++this.generation;\n\t\tthis.invalidateDependents(target.id, verifier.id, target.outcomeReason);\n\t\tthis.refreshReadyState();\n\t\treturn { target: structuredClone(target), verifier: structuredClone(verifier) };\n\t}\n\n\tbeginVerificationRework(id: string): WorkItemRecord {\n\t\tconst target = this.require(id);\n\t\tif (target.acceptanceState !== \"rework-requested\" || target.state !== \"blocked\") {\n\t\t\tthrow new Error(`WorkItem ${id} has no accepted rework request`);\n\t\t}\n\t\tconst verifier = [...this.items.values()].find((item) => item.verifierFor === id);\n\t\tif (verifier?.state !== \"completed\") {\n\t\t\tthrow new Error(`WorkItem ${id} has no completed verifier for rework`);\n\t\t}\n\t\ttarget.artifactHistory.push(...target.artifacts.map((artifact) => structuredClone(artifact)));\n\t\ttarget.artifacts = [];\n\t\ttarget.state = \"pending\";\n\t\ttarget.acceptanceState = \"pending\";\n\t\ttarget.taskGeneration++;\n\t\ttarget.assignedAgentId = undefined;\n\t\ttarget.acceptedExecutionPlanId = undefined;\n\t\ttarget.stagedTreeIdentity = undefined;\n\t\ttarget.submission = undefined;\n\t\ttarget.verificationAccepted = false;\n\t\ttarget.outcomeReason = undefined;\n\t\ttarget.generation = ++this.generation;\n\t\tverifier.state = \"pending\";\n\t\tverifier.taskGeneration++;\n\t\tverifier.assignedAgentId = undefined;\n\t\tverifier.acceptedExecutionPlanId = undefined;\n\t\tverifier.outcomeReason = undefined;\n\t\tverifier.generation = ++this.generation;\n\t\tthis.resetReworkDependents(target.id, verifier.id);\n\t\tthis.refreshReadyState();\n\t\treturn structuredClone(target);\n\t}\n\n\tfailVerification(verifierId: string, reason: string): WorkItemRecord[] {\n\t\tconst verifier = this.require(verifierId);\n\t\tif (!verifier.verifierFor) throw new Error(`WorkItem ${verifierId} is not a verifier`);\n\t\tconst target = this.require(verifier.verifierFor);\n\t\tconst boundedReason = bounded(reason, MAX_TEXT_LENGTH);\n\t\tif (!boundedReason) throw new Error(\"Verification failure requires a reason\");\n\t\tif (!TERMINAL_STATES.has(verifier.state)) {\n\t\t\tverifier.state = \"failed\";\n\t\t\tverifier.outcomeReason = boundedReason;\n\t\t\tverifier.generation = ++this.generation;\n\t\t}\n\t\tif (\n\t\t\ttarget.state === \"awaiting-verification\" ||\n\t\t\t(target.state === \"completed\" && target.acceptanceState === \"pending\")\n\t\t) {\n\t\t\ttarget.state = \"failed\";\n\t\t\tif (target.acceptanceRequired) target.acceptanceState = \"rejected\";\n\t\t\ttarget.verificationAccepted = false;\n\t\t\ttarget.outcomeReason = boundedReason;\n\t\t\ttarget.generation = ++this.generation;\n\t\t}\n\t\tconst invalidated = this.invalidateDependents(target.id, verifier.id, boundedReason);\n\t\treturn [structuredClone(target), structuredClone(verifier), ...invalidated];\n\t}\n\n\tsettle(\n\t\tid: string,\n\t\tstate: \"blocked\" | \"needs-input\" | \"failed\" | \"interrupted\",\n\t\treason?: string,\n\t): WorkItemRecord {\n\t\tconst item = this.require(id);\n\t\tthis.assertMutable(item);\n\t\tif (\n\t\t\titem.state !== \"running\" &&\n\t\t\titem.state !== \"awaiting-verification\" &&\n\t\t\t!(item.state === \"completed\" && item.acceptanceState === \"pending\") &&\n\t\t\titem.state !== \"ready\" &&\n\t\t\titem.state !== \"pending\"\n\t\t) {\n\t\t\tthrow new Error(`WorkItem ${id} cannot settle while ${item.state}`);\n\t\t}\n\t\titem.state = state;\n\t\tif (item.acceptanceRequired) item.acceptanceState = \"rejected\";\n\t\titem.outcomeReason = reason ? bounded(reason, MAX_TEXT_LENGTH) : undefined;\n\t\titem.generation = ++this.generation;\n\t\tthis.refreshReadyState();\n\t\treturn structuredClone(item);\n\t}\n\n\tacceptIntegration(\n\t\tid: string,\n\t\texpected: ManagedIntegrationExpectation,\n\t\tcandidate: ManagedIntegrationCandidate,\n\t\tverified?: VerifiedIntegrationInput,\n\t): WorkItemRecord {\n\t\tconst item = this.require(id);\n\t\tif (!item.integrationOwner) {\n\t\t\tthrow new Error(`WorkItem ${id} is not the integration owner`);\n\t\t}\n\t\tif (expected.taskId !== id || expected.taskGeneration !== item.taskGeneration) {\n\t\t\tthrow new Error(`WorkItem ${id} integration expectation has a stale generation`);\n\t\t}\n\t\tif (!verified) {\n\t\t\tif (item.state !== \"running\" || item.acceptanceRequired) {\n\t\t\t\tthrow new Error(`WorkItem ${id} cannot integrate while ${item.state}`);\n\t\t\t}\n\t\t\tverifyManagedIntegration(expected, candidate);\n\t\t\titem.verificationAccepted = true;\n\t\t\titem.generation = ++this.generation;\n\t\t\treturn structuredClone(item);\n\t\t}\n\t\tif (item.state !== \"completed\" || item.acceptanceState !== \"pending\") {\n\t\t\tthrow new Error(`WorkItem ${id} is not pending verified acceptance`);\n\t\t}\n\t\tconst verifier = this.require(verified.verifierId);\n\t\tif (\n\t\t\tverifier.state !== \"running\" ||\n\t\t\tverifier.verifierFor !== id ||\n\t\t\tverified.verifierTaskGeneration !== verifier.taskGeneration\n\t\t) {\n\t\t\tthrow new Error(`WorkItem ${verified.verifierId} is not the current verifier`);\n\t\t}\n\t\tif (!isVerificationReceipt(verified.receipt) || verified.receipt.decision !== \"accept\") {\n\t\t\tthrow new Error(\"Managed integration requires an accepting verification receipt\");\n\t\t}\n\t\tassertVerifiedReceiptMatches(\n\t\t\titem,\n\t\t\tverifier,\n\t\t\tverified.verifierExecutionPlanId,\n\t\t\tverified.receipt,\n\t\t);\n\t\tverifyManagedIntegration(expected, candidate);\n\t\titem.verificationAccepted = true;\n\t\titem.acceptanceState = \"accepted\";\n\t\titem.acceptanceReceipt = structuredClone(verified.receipt);\n\t\titem.acceptanceReceiptHistory.push(structuredClone(verified.receipt));\n\t\titem.artifacts = item.artifacts.map((artifact) => ({ ...artifact, verified: true }));\n\t\titem.outcomeReason = undefined;\n\t\titem.generation = ++this.generation;\n\t\tverifier.acceptedExecutionPlanId = verified.verifierExecutionPlanId;\n\t\tverifier.state = \"completed\";\n\t\tverifier.generation = ++this.generation;\n\t\tthis.refreshReadyState();\n\t\treturn structuredClone(item);\n\t}\n\n\trerun(id: string): WorkItemRecord {\n\t\tconst item = this.require(id);\n\t\tif (item.acceptanceState === \"accepted\") {\n\t\t\tthrow new Error(`WorkItem ${id} has terminal accepted evidence`);\n\t\t}\n\t\tif (\n\t\t\t![\"blocked\", \"needs-input\", \"failed\", \"interrupted\", \"stale\", \"invalidated\"].includes(\n\t\t\t\titem.state,\n\t\t\t)\n\t\t) {\n\t\t\tthrow new Error(`WorkItem ${id} cannot rerun while ${item.state}`);\n\t\t}\n\t\titem.state = \"pending\";\n\t\titem.taskGeneration++;\n\t\titem.assignedAgentId = undefined;\n\t\titem.acceptedExecutionPlanId = undefined;\n\t\titem.outcomeReason = undefined;\n\t\titem.verificationAccepted = false;\n\t\titem.acceptanceState = item.acceptanceRequired ? \"pending\" : \"not-required\";\n\t\titem.stagedTreeIdentity = undefined;\n\t\titem.submission = undefined;\n\t\titem.verificationReceipt = undefined;\n\t\titem.acceptanceReceipt = undefined;\n\t\titem.generation = ++this.generation;\n\t\tthis.refreshReadyState();\n\t\treturn structuredClone(item);\n\t}\n\n\tinvalidate(id: string, reason: string): WorkItemRecord[] {\n\t\tconst root = this.require(id);\n\t\tconst normalizedReason = bounded(reason, MAX_TEXT_LENGTH);\n\t\tif (!normalizedReason) throw new Error(\"WorkItem invalidation requires a reason\");\n\t\tconst ordered: WorkItemRecord[] = [];\n\t\tconst queue = [root.id];\n\t\tconst seen = new Set<string>();\n\t\twhile (queue.length > 0) {\n\t\t\tconst currentId = queue.shift();\n\t\t\tif (!currentId || seen.has(currentId)) continue;\n\t\t\tseen.add(currentId);\n\t\t\tconst item = this.require(currentId);\n\t\t\tif (item.acceptanceState === \"accepted\") {\n\t\t\t\tthrow new Error(`WorkItem ${item.id} has terminal accepted evidence`);\n\t\t\t}\n\t\t\tordered.push(item);\n\t\t\tqueue.push(...item.dependents);\n\t\t}\n\t\treturn ordered.map((item) => {\n\t\t\titem.state = item.id === root.id ? \"stale\" : \"invalidated\";\n\t\t\tif (item.acceptanceRequired) item.acceptanceState = \"rejected\";\n\t\t\titem.taskGeneration++;\n\t\t\titem.invalidationReasons.push(`${root.id}:${normalizedReason}`);\n\t\t\titem.generation = ++this.generation;\n\t\t\treturn structuredClone(item);\n\t\t});\n\t}\n\n\tsnapshot(): WorkItemLedgerSnapshot {\n\t\treturn {\n\t\t\tversion: WORK_ITEM_LEDGER_VERSION,\n\t\t\tworkflowId: this.workflowId,\n\t\t\tgeneration: this.generation,\n\t\t\titems: [...this.items.values()]\n\t\t\t\t.sort((left, right) => left.id.localeCompare(right.id))\n\t\t\t\t.map((item) => structuredClone(item)),\n\t\t};\n\t}\n\n\tstatic restore(snapshot: WorkItemLedgerSnapshot): WorkItemLedger {\n\t\tconst storedVersion = (snapshot as { version?: unknown } | undefined)?.version;\n\t\tif (\n\t\t\t!snapshot ||\n\t\t\t(storedVersion !== WORK_ITEM_LEDGER_VERSION &&\n\t\t\t\t!LEGACY_WORK_ITEM_LEDGER_VERSIONS.has(String(storedVersion))) ||\n\t\t\t!Number.isSafeInteger(snapshot.generation) ||\n\t\t\tsnapshot.generation < 0\n\t\t) {\n\t\t\tthrow new Error(\"Unsupported or malformed WorkItem ledger snapshot\");\n\t\t}\n\t\tconst isLegacySnapshot = storedVersion !== WORK_ITEM_LEDGER_VERSION;\n\t\tconst isV1Snapshot = storedVersion === \"pi-subagents:work-ledger:v1\";\n\t\tif (\n\t\t\t!Array.isArray(snapshot.items) ||\n\t\t\tsnapshot.items.length < 1 ||\n\t\t\tsnapshot.items.length > MAX_ITEMS\n\t\t) {\n\t\t\tthrow new Error(\"Malformed WorkItem ledger items\");\n\t\t}\n\t\tconst storedItems = snapshot.items.map((item) =>\n\t\t\tisLegacySnapshot ? normalizeLegacyAcceptance(item, isV1Snapshot) : item,\n\t\t);\n\t\tfor (const item of storedItems) validateStoredRecord(item, snapshot.generation);\n\t\tconst ledger = WorkItemLedger.create({\n\t\t\tworkflowId: snapshot.workflowId,\n\t\t\titems: storedItems.map((item) => ({\n\t\t\t\tid: item.id,\n\t\t\t\tobjective: item.objective,\n\t\t\t\tdependencies: item.dependencies,\n\t\t\t\tinputArtifacts: item.inputArtifacts,\n\t\t\t\tinputArtifactVersions: item.requiredArtifactVersions,\n\t\t\t\trequiredCapabilities: item.requiredCapabilities,\n\t\t\t\trequiredTools: item.requiredTools,\n\t\t\t\tselectedAgentName: item.selectedAgentName,\n\t\t\t\tsideEffectPolicy: item.sideEffectPolicy,\n\t\t\t\treadPaths: item.readPaths,\n\t\t\t\twritePaths: item.writePaths,\n\t\t\t\townershipKeys: item.ownershipKeys,\n\t\t\t\tacceptanceCriteria: item.acceptanceCriteria,\n\t\t\t\trequiredEvidence: item.requiredEvidence,\n\t\t\t\tintegrationOwner: item.integrationOwner,\n\t\t\t\tverifierFor: item.verifierFor,\n\t\t\t\tdependencyPolicy: item.dependencyPolicy,\n\t\t\t\tacceptanceRequired: item.acceptanceRequired,\n\t\t\t\tmaxReworkCycles: item.maxReworkCycles,\n\t\t\t})),\n\t\t});\n\t\tledger.generation = snapshot.generation;\n\t\tfor (const stored of storedItems) {\n\t\t\tconst item = ledger.require(stored.id);\n\t\t\tconst interruptedAcceptance =\n\t\t\t\tstored.acceptanceRequired &&\n\t\t\t\tstored.state === \"completed\" &&\n\t\t\t\tstored.acceptanceState === \"pending\";\n\t\t\titem.state =\n\t\t\t\tstored.state === \"running\" ||\n\t\t\t\tstored.state === \"awaiting-verification\" ||\n\t\t\t\tinterruptedAcceptance\n\t\t\t\t\t? \"interrupted\"\n\t\t\t\t\t: stored.state;\n\t\t\titem.generation = stored.generation;\n\t\t\titem.taskGeneration = stored.taskGeneration ?? 1;\n\t\t\titem.assignedAgentId = stored.assignedAgentId;\n\t\t\titem.acceptedExecutionPlanId = stored.acceptedExecutionPlanId;\n\t\t\titem.inputArtifactVersions = { ...stored.inputArtifactVersions };\n\t\t\titem.artifacts = normalizeStoredArtifacts(\n\t\t\t\tstored.artifacts,\n\t\t\t\tstored.id,\n\t\t\t\tstored.generation,\n\t\t\t\t!isV1Snapshot,\n\t\t\t);\n\t\t\titem.artifactHistory = normalizeStoredArtifacts(\n\t\t\t\tstored.artifactHistory ?? [],\n\t\t\t\tstored.id,\n\t\t\t\tstored.generation,\n\t\t\t\t!isV1Snapshot,\n\t\t\t);\n\t\t\titem.acceptanceStateVersion = WORK_ITEM_ACCEPTANCE_VERSION;\n\t\t\titem.acceptanceRequired = stored.acceptanceRequired;\n\t\t\titem.acceptanceState = interruptedAcceptance ? \"rejected\" : stored.acceptanceState;\n\t\t\titem.reworkCount = stored.reworkCount;\n\t\t\titem.maxReworkCycles = stored.maxReworkCycles;\n\t\t\titem.verificationAccepted = isV1Snapshot ? false : stored.verificationAccepted;\n\t\t\titem.stagedTreeIdentity = stored.stagedTreeIdentity\n\t\t\t\t? structuredClone(stored.stagedTreeIdentity)\n\t\t\t\t: undefined;\n\t\t\titem.verificationReceipt =\n\t\t\t\t!isV1Snapshot && stored.verificationReceipt\n\t\t\t\t\t? structuredClone(stored.verificationReceipt)\n\t\t\t\t\t: undefined;\n\t\t\titem.acceptanceReceipt = stored.acceptanceReceipt\n\t\t\t\t? structuredClone(stored.acceptanceReceipt)\n\t\t\t\t: undefined;\n\t\t\titem.acceptanceReceiptHistory = stored.acceptanceReceiptHistory.map((receipt) =>\n\t\t\t\tstructuredClone(receipt),\n\t\t\t);\n\t\t\titem.submission = stored.submission ? structuredClone(stored.submission) : undefined;\n\t\t\titem.invalidationReasons = [...stored.invalidationReasons];\n\t\t\titem.outcomeReason = interruptedAcceptance\n\t\t\t\t? \"verification-interrupted\"\n\t\t\t\t: stored.outcomeReason;\n\t\t}\n\t\tledger.validateRestoredVerificationLinks();\n\t\treturn ledger;\n\t}\n\n\tprivate validateRestoredVerificationLinks(): void {\n\t\tfor (const target of this.items.values()) {\n\t\t\tconst receipt = target.verificationReceipt;\n\t\t\tif (receipt) {\n\t\t\t\tconst verifier = this.items.get(receipt.verifierTaskId);\n\t\t\t\tif (\n\t\t\t\t\t!verifier ||\n\t\t\t\t\tverifier.verifierFor !== target.id ||\n\t\t\t\t\tverifier.state !== \"completed\" ||\n\t\t\t\t\tverifier.taskGeneration !== receipt.verifierTaskGeneration ||\n\t\t\t\t\tverifier.acceptedExecutionPlanId !== receipt.verifierExecutionPlanId\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(`Malformed stored WorkItem verification link for ${target.id}`);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst acceptanceReceipt = target.acceptanceReceipt;\n\t\t\tif (!acceptanceReceipt || target.acceptanceState === \"pending\") continue;\n\t\t\tconst verifier = this.items.get(acceptanceReceipt.verifierTaskId);\n\t\t\tif (\n\t\t\t\t!verifier ||\n\t\t\t\tverifier.verifierFor !== target.id ||\n\t\t\t\tverifier.state !== \"completed\" ||\n\t\t\t\tverifier.taskGeneration !== acceptanceReceipt.verifierTaskGeneration ||\n\t\t\t\tverifier.acceptedExecutionPlanId !== acceptanceReceipt.verifierExecutionPlanId ||\n\t\t\t\tacceptanceReceipt.targetTaskId !== target.id ||\n\t\t\t\tacceptanceReceipt.targetTaskGeneration !== target.taskGeneration ||\n\t\t\t\tacceptanceReceipt.targetExecutionPlanId !== target.acceptedExecutionPlanId\n\t\t\t) {\n\t\t\t\tthrow new Error(`Malformed stored WorkItem acceptance link for ${target.id}`);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate addDefinition(definition: WorkItemDefinition): void {\n\t\tvalidateIdentifier(definition.id, \"WorkItem id\");\n\t\tif (this.items.has(definition.id)) throw new Error(`Duplicate WorkItem id ${definition.id}`);\n\t\tconst objective = bounded(definition.objective, MAX_TEXT_LENGTH);\n\t\tif (!objective) throw new Error(`WorkItem ${definition.id} requires an objective`);\n\t\tthis.items.set(definition.id, {\n\t\t\tid: definition.id,\n\t\t\tobjective,\n\t\t\tdependencies: uniqueBounded(definition.dependencies, \"dependency\"),\n\t\t\tdependents: [],\n\t\t\tstate: \"pending\",\n\t\t\tgeneration: 0,\n\t\t\ttaskGeneration: 1,\n\t\t\tacceptedExecutionPlanId: undefined,\n\t\t\tinputArtifacts: uniqueBounded(definition.inputArtifacts ?? [], \"input artifact\"),\n\t\t\tinputArtifactVersions: {},\n\t\t\trequiredArtifactVersions: normalizeVersionMap(definition.inputArtifactVersions),\n\t\t\trequiredCapabilities: uniqueBounded(\n\t\t\t\tdefinition.requiredCapabilities ?? [],\n\t\t\t\t\"required capability\",\n\t\t\t),\n\t\t\trequiredTools: uniqueBounded(definition.requiredTools ?? [], \"required tool\"),\n\t\t\tselectedAgentName: definition.selectedAgentName,\n\t\t\tsideEffectPolicy: definition.sideEffectPolicy ?? \"mutating\",\n\t\t\tartifacts: [],\n\t\t\tartifactHistory: [],\n\t\t\treadPaths: uniqueBounded(definition.readPaths ?? [], \"read path\"),\n\t\t\twritePaths: uniqueBounded(definition.writePaths ?? [], \"write path\"),\n\t\t\townershipKeys: uniqueBounded(definition.ownershipKeys ?? [], \"ownership key\"),\n\t\t\tacceptanceCriteria: uniqueBounded(\n\t\t\t\tdefinition.acceptanceCriteria ?? [],\n\t\t\t\t\"acceptance criterion\",\n\t\t\t),\n\t\t\trequiredEvidence: uniqueBounded(definition.requiredEvidence ?? [], \"required evidence\"),\n\t\t\tintegrationOwner: definition.integrationOwner === true,\n\t\t\tverifierFor: definition.verifierFor,\n\t\t\tdependencyPolicy: definition.dependencyPolicy ?? \"completed\",\n\t\t\tacceptanceStateVersion: WORK_ITEM_ACCEPTANCE_VERSION,\n\t\t\tacceptanceRequired: definition.acceptanceRequired === true,\n\t\t\tacceptanceState: definition.acceptanceRequired === true ? \"pending\" : \"not-required\",\n\t\t\treworkCount: 0,\n\t\t\tmaxReworkCycles: definition.maxReworkCycles === 0 ? 0 : 1,\n\t\t\tverificationAccepted: false,\n\t\t\tstagedTreeIdentity: undefined,\n\t\t\tverificationReceipt: undefined,\n\t\t\tacceptanceReceipt: undefined,\n\t\t\tacceptanceReceiptHistory: [],\n\t\t\tsubmission: undefined,\n\t\t\tinvalidationReasons: [],\n\t\t\toutcomeReason: undefined,\n\t\t});\n\t}\n\n\tprivate linkAndValidate(): void {\n\t\tconst integrationOwners = [...this.items.values()].filter((item) => item.integrationOwner);\n\t\tif (integrationOwners.length > 1)\n\t\t\tthrow new Error(\"Workflow can have only one integration owner\");\n\t\tfor (const item of this.items.values()) {\n\t\t\tif (item.acceptanceRequired && !item.integrationOwner) {\n\t\t\t\tthrow new Error(`WorkItem ${item.id} requires acceptance but is not integration owner`);\n\t\t\t}\n\t\t\tfor (const dependency of item.dependencies) {\n\t\t\t\tif (dependency === item.id) throw new Error(`WorkItem ${item.id} has a self cycle`);\n\t\t\t\tconst parent = this.items.get(dependency);\n\t\t\t\tif (!parent) throw new Error(`WorkItem ${item.id} has missing dependency ${dependency}`);\n\t\t\t\tparent.dependents.push(item.id);\n\t\t\t}\n\t\t\tif (item.verifierFor && !this.items.has(item.verifierFor)) {\n\t\t\t\tthrow new Error(`WorkItem ${item.id} verifies missing WorkItem ${item.verifierFor}`);\n\t\t\t}\n\t\t\tif (item.verifierFor && !item.dependencies.includes(item.verifierFor)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`WorkItem ${item.id} must depend on the WorkItem it verifies (${item.verifierFor})`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tconst visiting = new Set<string>();\n\t\tconst visited = new Set<string>();\n\t\tconst visit = (id: string) => {\n\t\t\tif (visiting.has(id)) throw new Error(`WorkItem dependency cycle includes ${id}`);\n\t\t\tif (visited.has(id)) return;\n\t\t\tvisiting.add(id);\n\t\t\tfor (const dependency of this.require(id).dependencies) visit(dependency);\n\t\t\tvisiting.delete(id);\n\t\t\tvisited.add(id);\n\t\t};\n\t\tfor (const id of this.items.keys()) visit(id);\n\t}\n\n\tprivate refreshReadyState(): void {\n\t\tfor (const item of this.items.values()) {\n\t\t\tif (item.state !== \"pending\") continue;\n\t\t\tconst dependencies = item.dependencies.map((id) => this.require(id));\n\t\t\tconst acceptedDependency = (dependency: WorkItemRecord) =>\n\t\t\t\tdependency.state === \"completed\" &&\n\t\t\t\t(!dependency.acceptanceRequired || dependency.acceptanceState === \"accepted\");\n\t\t\tconst dependenciesReady = item.verifierFor\n\t\t\t\t? dependencies.every((dependency) =>\n\t\t\t\t\t\tdependency.id === item.verifierFor\n\t\t\t\t\t\t\t? dependency.acceptanceRequired\n\t\t\t\t\t\t\t\t? dependency.state === \"completed\" && dependency.acceptanceState === \"pending\"\n\t\t\t\t\t\t\t\t: dependency.state === \"awaiting-verification\"\n\t\t\t\t\t\t\t: acceptedDependency(dependency),\n\t\t\t\t\t)\n\t\t\t\t: item.dependencyPolicy === \"settled\"\n\t\t\t\t\t? dependencies.every(\n\t\t\t\t\t\t\t(dependency) =>\n\t\t\t\t\t\t\t\t(!dependency.acceptanceRequired || dependency.acceptanceState === \"accepted\") &&\n\t\t\t\t\t\t\t\t![\"pending\", \"ready\", \"running\", \"awaiting-verification\"].includes(\n\t\t\t\t\t\t\t\t\tdependency.state,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t)\n\t\t\t\t\t: dependencies.every(acceptedDependency);\n\t\t\tif (!dependenciesReady) continue;\n\t\t\tconst available = new Map<string, WorkArtifactReference>();\n\t\t\tfor (const dependency of dependencies) {\n\t\t\t\tfor (const artifact of dependency.artifacts) available.set(artifact.id, artifact);\n\t\t\t}\n\t\t\tif (!item.inputArtifacts.every((artifact) => available.has(artifact))) continue;\n\t\t\tif (\n\t\t\t\t!Object.entries(item.requiredArtifactVersions).every(\n\t\t\t\t\t([id, version]) => available.get(id)?.version === version,\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\titem.inputArtifactVersions = Object.fromEntries(\n\t\t\t\titem.inputArtifacts.map((id) => [id, available.get(id)?.version ?? \"unknown\"]),\n\t\t\t);\n\t\t\titem.state = \"ready\";\n\t\t\titem.generation = this.generation;\n\t\t}\n\t}\n\n\tprivate resetReworkDependents(targetId: string, excludedId: string): void {\n\t\tconst target = this.require(targetId);\n\t\tconst reworkReason = `${targetId}:verification-rework`;\n\t\tconst queue = target.dependents.filter((id) => id !== excludedId);\n\t\tconst seen = new Set<string>();\n\t\twhile (queue.length > 0) {\n\t\t\tconst currentId = queue.shift();\n\t\t\tif (!currentId || seen.has(currentId)) continue;\n\t\t\tseen.add(currentId);\n\t\t\tconst current = this.require(currentId);\n\t\t\tqueue.push(...current.dependents.filter((id) => id !== excludedId));\n\t\t\tif (current.state !== \"invalidated\" || current.invalidationReasons.at(-1) !== reworkReason) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcurrent.artifactHistory.push(\n\t\t\t\t...current.artifacts.map((artifact) => structuredClone(artifact)),\n\t\t\t);\n\t\t\tcurrent.artifacts = [];\n\t\t\tcurrent.inputArtifactVersions = {};\n\t\t\tcurrent.state = \"pending\";\n\t\t\tcurrent.assignedAgentId = undefined;\n\t\t\tcurrent.acceptedExecutionPlanId = undefined;\n\t\t\tcurrent.outcomeReason = undefined;\n\t\t\tcurrent.verificationAccepted = false;\n\t\t\tcurrent.acceptanceState = current.acceptanceRequired ? \"pending\" : \"not-required\";\n\t\t\tcurrent.stagedTreeIdentity = undefined;\n\t\t\tcurrent.submission = undefined;\n\t\t\tcurrent.verificationReceipt = undefined;\n\t\t\tcurrent.acceptanceReceipt = undefined;\n\t\t\tcurrent.generation = ++this.generation;\n\t\t}\n\t}\n\n\tprivate invalidateDependents(\n\t\ttargetId: string,\n\t\texcludedId: string,\n\t\treason: string | undefined,\n\t): WorkItemRecord[] {\n\t\tconst target = this.require(targetId);\n\t\tconst normalizedReason = bounded(reason ?? \"verification-not-accepted\", MAX_TEXT_LENGTH);\n\t\tconst queue = target.dependents.filter((id) => id !== excludedId);\n\t\tconst seen = new Set<string>();\n\t\tconst affected: WorkItemRecord[] = [];\n\t\twhile (queue.length > 0) {\n\t\t\tconst currentId = queue.shift();\n\t\t\tif (!currentId || seen.has(currentId)) continue;\n\t\t\tseen.add(currentId);\n\t\t\tconst current = this.require(currentId);\n\t\t\tcurrent.state = \"invalidated\";\n\t\t\tcurrent.taskGeneration++;\n\t\t\tcurrent.invalidationReasons.push(`${targetId}:${normalizedReason}`);\n\t\t\tcurrent.generation = ++this.generation;\n\t\t\taffected.push(structuredClone(current));\n\t\t\tqueue.push(...current.dependents.filter((id) => id !== excludedId));\n\t\t}\n\t\treturn affected;\n\t}\n\n\tprivate require(id: string): WorkItemRecord {\n\t\tconst item = this.items.get(id);\n\t\tif (!item) throw new Error(`Unknown WorkItem ${id}`);\n\t\treturn item;\n\t}\n\n\tprivate assertMutable(item: WorkItemRecord): void {\n\t\tif (\n\t\t\tTERMINAL_STATES.has(item.state) &&\n\t\t\t!(item.state === \"completed\" && item.acceptanceState === \"pending\")\n\t\t) {\n\t\t\tthrow new Error(`WorkItem ${item.id} is terminal (${item.state})`);\n\t\t}\n\t}\n}\n\nfunction assertReceiptMatches(\n\ttarget: WorkItemRecord,\n\tverifier: WorkItemRecord,\n\tverifierExecutionPlanId: string,\n\treceipt: WorkflowVerificationReceipt,\n): void {\n\tif (\n\t\treceipt.targetTaskId !== target.id ||\n\t\treceipt.targetTaskGeneration !== target.taskGeneration ||\n\t\treceipt.targetExecutionPlanId !== target.acceptedExecutionPlanId ||\n\t\treceipt.verifierTaskId !== verifier.id ||\n\t\treceipt.verifierTaskGeneration !== verifier.taskGeneration ||\n\t\treceipt.verifierExecutionPlanId !== verifierExecutionPlanId ||\n\t\t!target.stagedTreeIdentity ||\n\t\t!sameWorkflowTreeIdentity(receipt.treeIdentity, target.stagedTreeIdentity)\n\t) {\n\t\tthrow new Error(\"WorkItem verification receipt has stale or mismatched executor identity\");\n\t}\n}\n\nfunction assertVerifiedReceiptMatches(\n\ttarget: WorkItemRecord,\n\tverifier: WorkItemRecord,\n\tverifierExecutionPlanId: string,\n\treceipt: VerificationReceipt,\n): void {\n\tif (\n\t\t!target.acceptanceRequired ||\n\t\ttarget.acceptanceState !== \"pending\" ||\n\t\ttarget.state !== \"completed\" ||\n\t\t!target.submission ||\n\t\treceipt.targetTaskId !== target.id ||\n\t\treceipt.targetTaskGeneration !== target.taskGeneration ||\n\t\treceipt.targetExecutionPlanId !== target.acceptedExecutionPlanId ||\n\t\treceipt.verifierTaskId !== verifier.id ||\n\t\treceipt.verifierTaskGeneration !== verifier.taskGeneration ||\n\t\treceipt.verifierExecutionPlanId !== verifierExecutionPlanId ||\n\t\treceipt.verifierAgent !== verifier.assignedAgentId?.replace(/^agent:/u, \"\") ||\n\t\t!sameWorkflowTreeIdentity(receipt.beforeTreeIdentity, target.submission.treeIdentity) ||\n\t\t!sameWorkflowTreeIdentity(receipt.afterTreeIdentity, target.submission.treeIdentity) ||\n\t\treceipt.baseRepositoryGeneration !== target.submission.baseRepositoryGeneration ||\n\t\treceipt.patchDigest !== target.submission.patchDigest ||\n\t\tJSON.stringify(receipt.changedPaths) !== JSON.stringify(target.submission.changedPaths) ||\n\t\tJSON.stringify(receipt.allowedScopes) !== JSON.stringify(target.writePaths) ||\n\t\tJSON.stringify(receipt.dependencyVersions) !== JSON.stringify(target.inputArtifactVersions) ||\n\t\tJSON.stringify(receipt.readSetVersions) !== JSON.stringify(target.submission.fileVersions) ||\n\t\tJSON.stringify(receipt.acceptanceCriteria) !== JSON.stringify(target.acceptanceCriteria) ||\n\t\tJSON.stringify(receipt.requiredEvidenceIds) !== JSON.stringify(target.requiredEvidence)\n\t) {\n\t\tthrow new Error(\"WorkItem verification receipt has stale or mismatched managed identity\");\n\t}\n}\n\nfunction validatePlanId(value: string, label: string): void {\n\tif (!/^[a-f0-9]{64}$/u.test(value)) throw new Error(`Invalid ${label}`);\n}\n\nfunction validateSubmission(value: VerificationSubmission): void {\n\tif (\n\t\t!isWorkflowTreeIdentity(value.treeIdentity) ||\n\t\t!/^[a-f0-9]{40,64}$/u.test(value.baseRepositoryGeneration) ||\n\t\t!/^[a-f0-9]{64}$/u.test(value.patchDigest) ||\n\t\t!Array.isArray(value.changedPaths) ||\n\t\tvalue.changedPaths.length > MAX_LIST_ITEMS ||\n\t\tvalue.changedPaths.some(\n\t\t\t(item) =>\n\t\t\t\ttypeof item !== \"string\" ||\n\t\t\t\t!item ||\n\t\t\t\titem.length > 4096 ||\n\t\t\t\titem.startsWith(\"/\") ||\n\t\t\t\titem.startsWith(\"\\\\\") ||\n\t\t\t\titem.split(/[\\\\/]/u).includes(\"..\"),\n\t\t) ||\n\t\tnew Set(value.changedPaths).size !== value.changedPaths.length ||\n\t\tvalue.changedPaths.reduce((total, item) => total + Buffer.byteLength(item, \"utf8\"), 0) >\n\t\t\t8 * 1024 ||\n\t\tJSON.stringify([...value.changedPaths].sort((left, right) => left.localeCompare(right))) !==\n\t\t\tJSON.stringify(value.changedPaths) ||\n\t\t!value.fileVersions ||\n\t\ttypeof value.fileVersions !== \"object\" ||\n\t\tArray.isArray(value.fileVersions) ||\n\t\tObject.entries(value.fileVersions).length > MAX_LIST_ITEMS ||\n\t\tJSON.stringify(\n\t\t\tObject.keys(value.fileVersions).sort((left, right) => left.localeCompare(right)),\n\t\t) !== JSON.stringify(value.changedPaths) ||\n\t\tObject.entries(value.fileVersions).some(\n\t\t\t([key, digest]) =>\n\t\t\t\t!key ||\n\t\t\t\tkey.length > 4096 ||\n\t\t\t\ttypeof digest !== \"string\" ||\n\t\t\t\t(digest !== \"deleted\" && !/^[a-f0-9]{64}$/u.test(digest)),\n\t\t)\n\t) {\n\t\tthrow new Error(\"WorkItem received malformed verification submission metadata\");\n\t}\n}\n\nfunction validSubmission(value: VerificationSubmission): boolean {\n\ttry {\n\t\tvalidateSubmission(value);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction normalizeLegacyAcceptance(item: WorkItemRecord, isV1: boolean): WorkItemRecord {\n\treturn {\n\t\t...structuredClone(item),\n\t\trequiredEvidence: [],\n\t\tacceptanceStateVersion: WORK_ITEM_ACCEPTANCE_VERSION,\n\t\tacceptanceRequired: false,\n\t\tacceptanceState: \"not-required\",\n\t\treworkCount: 0,\n\t\tmaxReworkCycles: 1,\n\t\tverificationAccepted: isV1 ? false : item.verificationAccepted,\n\t\tacceptanceReceipt: undefined,\n\t\tacceptanceReceiptHistory: [],\n\t\tsubmission: undefined,\n\t};\n}\n\nfunction validateStoredRecord(item: WorkItemRecord, ledgerGeneration: number): void {\n\tconst states: WorkItemState[] = [\n\t\t\"pending\",\n\t\t\"ready\",\n\t\t\"running\",\n\t\t\"awaiting-verification\",\n\t\t\"blocked\",\n\t\t\"needs-input\",\n\t\t\"completed\",\n\t\t\"failed\",\n\t\t\"interrupted\",\n\t\t\"stale\",\n\t\t\"invalidated\",\n\t];\n\tif (\n\t\t!item ||\n\t\ttypeof item !== \"object\" ||\n\t\ttypeof item.objective !== \"string\" ||\n\t\titem.objective.length === 0 ||\n\t\titem.objective.length > MAX_TEXT_LENGTH ||\n\t\titem.objective.trim() !== item.objective ||\n\t\t!states.includes(item.state) ||\n\t\t!Number.isSafeInteger(item.generation) ||\n\t\titem.generation < 0 ||\n\t\titem.generation > ledgerGeneration ||\n\t\t!Number.isSafeInteger(item.taskGeneration) ||\n\t\titem.taskGeneration < 1 ||\n\t\t!Array.isArray(item.artifacts) ||\n\t\t!validStoredArtifacts(item.artifacts, item.id, item.generation) ||\n\t\t(item.artifactHistory !== undefined && !Array.isArray(item.artifactHistory)) ||\n\t\t(item.artifactHistory !== undefined &&\n\t\t\t!validStoredArtifacts(item.artifactHistory, item.id, item.generation)) ||\n\t\t!item.inputArtifactVersions ||\n\t\ttypeof item.inputArtifactVersions !== \"object\" ||\n\t\tArray.isArray(item.inputArtifactVersions) ||\n\t\t(item.assignedAgentId !== undefined && !isValidIdentifier(item.assignedAgentId)) ||\n\t\t(item.selectedAgentName !== undefined &&\n\t\t\t(typeof item.selectedAgentName !== \"string\" ||\n\t\t\t\titem.selectedAgentName.length === 0 ||\n\t\t\t\titem.selectedAgentName.length > MAX_IDENTIFIER_LENGTH ||\n\t\t\t\titem.selectedAgentName.trim() !== item.selectedAgentName)) ||\n\t\titem.acceptanceStateVersion !== WORK_ITEM_ACCEPTANCE_VERSION ||\n\t\ttypeof item.acceptanceRequired !== \"boolean\" ||\n\t\t![\"not-required\", \"pending\", \"accepted\", \"rework-requested\", \"rejected\"].includes(\n\t\t\titem.acceptanceState,\n\t\t) ||\n\t\t!Number.isSafeInteger(item.reworkCount) ||\n\t\titem.reworkCount < 0 ||\n\t\titem.reworkCount > 1 ||\n\t\t(item.maxReworkCycles !== 0 && item.maxReworkCycles !== 1) ||\n\t\t(item.acceptanceRequired && !item.integrationOwner) ||\n\t\t(!item.acceptanceRequired && item.acceptanceState !== \"not-required\") ||\n\t\ttypeof item.integrationOwner !== \"boolean\" ||\n\t\t!([\"completed\", \"settled\"] as const).includes(item.dependencyPolicy) ||\n\t\t!([\"read-only\", \"idempotent\", \"mutating\"] as const).includes(item.sideEffectPolicy) ||\n\t\t(item.verifierFor !== undefined && !isValidIdentifier(item.verifierFor)) ||\n\t\t![\n\t\t\titem.dependencies,\n\t\t\titem.dependents,\n\t\t\titem.inputArtifacts,\n\t\t\titem.requiredCapabilities,\n\t\t\titem.requiredTools,\n\t\t\titem.readPaths,\n\t\t\titem.writePaths,\n\t\t\titem.ownershipKeys,\n\t\t\titem.acceptanceCriteria,\n\t\t\titem.requiredEvidence,\n\t\t].every(\n\t\t\t(values) =>\n\t\t\t\tArray.isArray(values) &&\n\t\t\t\tvalues.every(\n\t\t\t\t\t(value) =>\n\t\t\t\t\t\ttypeof value === \"string\" &&\n\t\t\t\t\t\tvalue.length > 0 &&\n\t\t\t\t\t\tvalue.length <= MAX_TEXT_LENGTH &&\n\t\t\t\t\t\tvalue.trim() === value,\n\t\t\t\t),\n\t\t) ||\n\t\t!item.requiredArtifactVersions ||\n\t\ttypeof item.requiredArtifactVersions !== \"object\" ||\n\t\tArray.isArray(item.requiredArtifactVersions) ||\n\t\t!Object.entries(item.requiredArtifactVersions).every(\n\t\t\t([id, version]) =>\n\t\t\t\tisValidIdentifier(id) &&\n\t\t\t\ttypeof version === \"string\" &&\n\t\t\t\tversion.length > 0 &&\n\t\t\t\tversion.length <= MAX_IDENTIFIER_LENGTH &&\n\t\t\t\tversion.trim() === version,\n\t\t) ||\n\t\t(item.acceptedExecutionPlanId !== undefined &&\n\t\t\t(typeof item.acceptedExecutionPlanId !== \"string\" ||\n\t\t\t\t!/^[a-f0-9]{64}$/u.test(item.acceptedExecutionPlanId))) ||\n\t\t!Object.entries(item.inputArtifactVersions).every(\n\t\t\t([id, value]) =>\n\t\t\t\tisValidIdentifier(id) &&\n\t\t\t\ttypeof value === \"string\" &&\n\t\t\t\tvalue.length > 0 &&\n\t\t\t\tvalue.length <= MAX_IDENTIFIER_LENGTH &&\n\t\t\t\tvalue.trim() === value,\n\t\t) ||\n\t\t!Array.isArray(item.invalidationReasons) ||\n\t\t!item.invalidationReasons.every(\n\t\t\t(reason) =>\n\t\t\t\ttypeof reason === \"string\" &&\n\t\t\t\treason.length > 0 &&\n\t\t\t\treason.length <= MAX_TEXT_LENGTH &&\n\t\t\t\treason.trim() === reason,\n\t\t) ||\n\t\t(item.outcomeReason !== undefined &&\n\t\t\t(typeof item.outcomeReason !== \"string\" ||\n\t\t\t\titem.outcomeReason.length > MAX_TEXT_LENGTH ||\n\t\t\t\titem.outcomeReason.trim() !== item.outcomeReason)) ||\n\t\ttypeof item.verificationAccepted !== \"boolean\" ||\n\t\t(item.stagedTreeIdentity !== undefined && !isWorkflowTreeIdentity(item.stagedTreeIdentity)) ||\n\t\t(item.verificationReceipt !== undefined &&\n\t\t\t(!isWorkflowVerificationReceipt(item.verificationReceipt) ||\n\t\t\t\t!storedVerificationMatchesItem(item, item.verificationReceipt))) ||\n\t\t(item.acceptanceReceipt !== undefined &&\n\t\t\t(!isVerificationReceipt(item.acceptanceReceipt) ||\n\t\t\t\t(item.acceptanceState !== \"pending\" &&\n\t\t\t\t\t!storedAcceptanceMatchesItem(item, item.acceptanceReceipt)))) ||\n\t\t!Array.isArray(item.acceptanceReceiptHistory) ||\n\t\titem.acceptanceReceiptHistory.length > 2 ||\n\t\t!item.acceptanceReceiptHistory.every(isVerificationReceipt) ||\n\t\t(item.acceptanceReceipt !== undefined &&\n\t\t\tJSON.stringify(item.acceptanceReceiptHistory.at(-1)) !==\n\t\t\t\tJSON.stringify(item.acceptanceReceipt)) ||\n\t\titem.reworkCount !==\n\t\t\tMath.min(\n\t\t\t\titem.maxReworkCycles,\n\t\t\t\titem.acceptanceReceiptHistory.filter((receipt) => receipt.decision === \"rework\").length,\n\t\t\t) ||\n\t\t(item.submission !== undefined && !validSubmission(item.submission)) ||\n\t\t(item.acceptanceRequired &&\n\t\t\titem.state === \"completed\" &&\n\t\t\titem.acceptanceState === \"pending\" &&\n\t\t\t(!item.submission || !item.acceptedExecutionPlanId)) ||\n\t\t(item.acceptanceState === \"accepted\" &&\n\t\t\t(item.acceptanceReceipt?.decision !== \"accept\" || !item.verificationAccepted)) ||\n\t\t(item.acceptanceState === \"rejected\" &&\n\t\t\t(![\"failed\", \"interrupted\", \"stale\", \"invalidated\", \"blocked\", \"needs-input\"].includes(\n\t\t\t\titem.state,\n\t\t\t) ||\n\t\t\t\t(item.acceptanceReceipt !== undefined &&\n\t\t\t\t\titem.acceptanceReceipt.decision !== \"reject\" &&\n\t\t\t\t\titem.acceptanceReceipt.decision !== \"rework\"))) ||\n\t\t(item.acceptanceState === \"rework-requested\" &&\n\t\t\t(item.state !== \"blocked\" || item.acceptanceReceipt?.decision !== \"rework\")) ||\n\t\t(item.state === \"awaiting-verification\" &&\n\t\t\t(!item.stagedTreeIdentity || !item.acceptedExecutionPlanId)) ||\n\t\t(item.stagedTreeIdentity !== undefined &&\n\t\t\titem.state === \"completed\" &&\n\t\t\t!item.acceptanceRequired &&\n\t\t\titem.verificationReceipt === undefined)\n\t) {\n\t\tthrow new Error(`Malformed stored WorkItem ${String(item?.id ?? \"unknown\")}`);\n\t}\n}\n\nfunction storedAcceptanceMatchesItem(item: WorkItemRecord, receipt: VerificationReceipt): boolean {\n\treturn (\n\t\titem.acceptanceRequired &&\n\t\titem.submission !== undefined &&\n\t\treceipt.targetTaskId === item.id &&\n\t\treceipt.targetTaskGeneration === item.taskGeneration &&\n\t\treceipt.targetExecutionPlanId === item.acceptedExecutionPlanId &&\n\t\tsameWorkflowTreeIdentity(receipt.beforeTreeIdentity, item.submission.treeIdentity) &&\n\t\tsameWorkflowTreeIdentity(receipt.afterTreeIdentity, item.submission.treeIdentity) &&\n\t\treceipt.baseRepositoryGeneration === item.submission.baseRepositoryGeneration &&\n\t\treceipt.patchDigest === item.submission.patchDigest &&\n\t\tJSON.stringify(receipt.changedPaths) === JSON.stringify(item.submission.changedPaths) &&\n\t\tJSON.stringify(receipt.allowedScopes) === JSON.stringify(item.writePaths) &&\n\t\tJSON.stringify(receipt.dependencyVersions) === JSON.stringify(item.inputArtifactVersions) &&\n\t\tJSON.stringify(receipt.readSetVersions) === JSON.stringify(item.submission.fileVersions) &&\n\t\tJSON.stringify(receipt.acceptanceCriteria) === JSON.stringify(item.acceptanceCriteria) &&\n\t\tJSON.stringify(receipt.requiredEvidenceIds) === JSON.stringify(item.requiredEvidence)\n\t);\n}\n\nfunction storedVerificationMatchesItem(\n\titem: WorkItemRecord,\n\treceipt: WorkflowVerificationReceipt,\n): boolean {\n\treturn (\n\t\t!item.verifierFor &&\n\t\treceipt.targetTaskId === item.id &&\n\t\treceipt.targetTaskGeneration === item.taskGeneration &&\n\t\treceipt.targetExecutionPlanId === item.acceptedExecutionPlanId &&\n\t\titem.stagedTreeIdentity !== undefined &&\n\t\tsameWorkflowTreeIdentity(receipt.treeIdentity, item.stagedTreeIdentity) &&\n\t\titem.verificationAccepted === (receipt.decision === \"accept\") &&\n\t\t(receipt.decision === \"accept\"\n\t\t\t? item.state === \"completed\"\n\t\t\t: receipt.decision === \"rework\"\n\t\t\t\t? item.state === \"blocked\"\n\t\t\t\t: item.state === \"failed\")\n\t);\n}\n\nfunction validStoredArtifacts(\n\tvalues: WorkArtifactReference[],\n\tproducerTaskId: string,\n\titemGeneration: number,\n): boolean {\n\tconst seen = new Set<string>();\n\treturn values.every(\n\t\t(artifact) =>\n\t\t\tartifact !== null &&\n\t\t\ttypeof artifact === \"object\" &&\n\t\t\tObject.keys(artifact).every((key) =>\n\t\t\t\t[\"id\", \"kind\", \"version\", \"digest\", \"producerTaskId\", \"generation\", \"verified\"].includes(\n\t\t\t\t\tkey,\n\t\t\t\t),\n\t\t\t) &&\n\t\t\tisValidIdentifier(artifact.id) &&\n\t\t\tclaimUnique(artifact.id, seen) &&\n\t\t\ttypeof artifact.kind === \"string\" &&\n\t\t\tartifact.kind.length > 0 &&\n\t\t\tartifact.kind.length <= MAX_IDENTIFIER_LENGTH &&\n\t\t\tartifact.kind.trim() === artifact.kind &&\n\t\t\ttypeof artifact.version === \"string\" &&\n\t\t\tartifact.version.length > 0 &&\n\t\t\tartifact.version.length <= MAX_IDENTIFIER_LENGTH &&\n\t\t\tartifact.version.trim() === artifact.version &&\n\t\t\t(artifact.digest === undefined ||\n\t\t\t\t(typeof artifact.digest === \"string\" &&\n\t\t\t\t\tartifact.digest.length > 0 &&\n\t\t\t\t\tartifact.digest.length <= MAX_TEXT_LENGTH &&\n\t\t\t\t\tartifact.digest.trim() === artifact.digest)) &&\n\t\t\tartifact.producerTaskId === producerTaskId &&\n\t\t\tNumber.isSafeInteger(artifact.generation) &&\n\t\t\tNumber(artifact.generation) >= 0 &&\n\t\t\tNumber(artifact.generation) <= itemGeneration &&\n\t\t\ttypeof artifact.verified === \"boolean\",\n\t);\n}\n\nfunction claimUnique(value: string, seen: Set<string>): boolean {\n\tif (seen.has(value)) return false;\n\tseen.add(value);\n\treturn true;\n}\n\nfunction normalizeStoredArtifacts(\n\tvalues: WorkArtifactReference[],\n\tdefaultProducerTaskId: string,\n\tdefaultGeneration: number,\n\tpreserveVerification: boolean,\n): WorkArtifactReference[] {\n\tif (!validStoredArtifacts(values, defaultProducerTaskId, defaultGeneration)) {\n\t\tthrow new Error(`Malformed stored artifacts for WorkItem ${defaultProducerTaskId}`);\n\t}\n\treturn values.map((value) => ({\n\t\t...structuredClone(value),\n\t\tverified: preserveVerification && value.verified,\n\t}));\n}\n\nfunction normalizeArtifacts(\n\tvalues: Array<Omit<WorkArtifactReference, \"producerTaskId\" | \"generation\">>,\n\tproducerTaskId: string,\n\tgeneration: number,\n): WorkArtifactReference[] {\n\tif (values.length > MAX_LIST_ITEMS) throw new Error(\"Too many WorkItem artifacts\");\n\tconst seen = new Set<string>();\n\treturn values.map((value) => {\n\t\tvalidateIdentifier(value.id, \"artifact id\");\n\t\tif (seen.has(value.id)) throw new Error(`Duplicate artifact id ${value.id}`);\n\t\tseen.add(value.id);\n\t\tconst kind = bounded(value.kind, MAX_IDENTIFIER_LENGTH);\n\t\tconst version = bounded(value.version, MAX_IDENTIFIER_LENGTH);\n\t\tif (!kind || !version) throw new Error(`Artifact ${value.id} requires kind and version`);\n\t\treturn {\n\t\t\tid: value.id,\n\t\t\tkind,\n\t\t\tversion,\n\t\t\t...(value.digest ? { digest: bounded(value.digest, MAX_TEXT_LENGTH) } : {}),\n\t\t\tproducerTaskId,\n\t\t\tgeneration,\n\t\t\tverified: false,\n\t\t};\n\t});\n}\n\nfunction normalizeVersionMap(value: Record<string, string> | undefined): Record<string, string> {\n\tif (value === undefined) return {};\n\tconst entries = Object.entries(value);\n\tif (entries.length > MAX_LIST_ITEMS) throw new Error(\"Too many artifact version requirements\");\n\treturn Object.fromEntries(\n\t\tentries.map(([id, version]) => {\n\t\t\tvalidateIdentifier(id, \"artifact version id\");\n\t\t\tconst normalized = bounded(version, MAX_IDENTIFIER_LENGTH);\n\t\t\tif (!normalized) throw new Error(`Artifact ${id} requires a version`);\n\t\t\treturn [id, normalized];\n\t\t}),\n\t);\n}\n\nfunction uniqueBounded(values: readonly string[], label: string): string[] {\n\tif (!Array.isArray(values) || values.length > MAX_LIST_ITEMS) {\n\t\tthrow new Error(`Too many WorkItem ${label} values`);\n\t}\n\tconst result: string[] = [];\n\tconst seen = new Set<string>();\n\tfor (const value of values) {\n\t\tif (typeof value !== \"string\") throw new Error(`Invalid WorkItem ${label}`);\n\t\tconst normalized = bounded(value, MAX_TEXT_LENGTH);\n\t\tif (!normalized) throw new Error(`Empty WorkItem ${label}`);\n\t\tif (!seen.has(normalized)) result.push(normalized);\n\t\tseen.add(normalized);\n\t}\n\treturn result;\n}\n\nfunction isValidIdentifier(value: unknown): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.length >= 1 &&\n\t\tvalue.length <= MAX_IDENTIFIER_LENGTH &&\n\t\t/^[A-Za-z0-9][A-Za-z0-9._:-]*$/u.test(value)\n\t);\n}\n\nfunction validateIdentifier(value: string, label: string): void {\n\tif (!isValidIdentifier(value)) {\n\t\tthrow new Error(`Invalid ${label}`);\n\t}\n}\n\nfunction bounded(value: string, maxLength: number): string {\n\treturn value.trim().slice(0, maxLength);\n}\n"],
5
+ "mappings": ";;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,kBAA6B;AACtC,YAAY,QAAQ;AACpB,YAAY,UAAU;AAEf,IAAM,iCAAiC;AACvC,IAAM,kCAAkC,OAAO;AACtD,IAAM,sBAAsB;AAa5B,eAAsB,4BACrB,KACA,UAA8C,CAAC,GACf;AAChC,QAAM,WAAW,QAAQ,YAAY;AACrC,MAAI,CAAC,OAAO,cAAc,QAAQ,KAAK,WAAW,GAAG;AACpD,UAAM,IAAI,MAAM,iEAAiE;AAAA,EAClF;AACA,iBAAe,QAAQ,MAAM;AAC7B,MAAI;AACJ,MAAI;AACH,mBAAe,MAAS,YAAS,SAAc,aAAQ,GAAG,CAAC;AAAA,EAC5D,QAAQ;AACP,UAAM,IAAI,MAAM,oEAAoE;AAAA,EACrF;AACA,QAAM,aAAa,MAAM;AAAA,IACxB;AAAA,IACA,CAAC,aAAa,iBAAiB;AAAA,IAC/B,KAAK;AAAA,IACL,QAAQ;AAAA,EACT,EAAE,MAAM,CAAC,UAAU;AAClB,UAAM,mBAAmB,OAAO,iDAAiD;AAAA,EAClF,CAAC;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,SAAS,OAAO,SAAS,MAAM,IAAI;AAAA,IAC/D;AAAA,EACD;AACA,iBAAe,QAAQ,SAAS;AAChC,SAAO;AACR;AAEA,SAAS,aAAa,OAAuD;AAC5E,SAAO,OAAO;AAAA,IACb,OAAO,QAAQ,KAAK,EAAE,IAAI,CAAC,CAAC,KAAK,IAAI,MAAM,CAAC,OAAO,GAAG,GAAG,OAAO,IAAI,CAAC,CAAC;AAAA,EACvE;AACD;AAEA,SAAS,OAAO,OAAuB;AACtC,SAAO,kBAAkB,KAAK,EAAE,KAAK;AACtC;",
6
+ "names": ["relative", "resolve", "createHash", "fs", "path", "path", "MAX_FIELD_BYTES", "ID_PATTERN", "boundList", "bounded", "MAX_ITEMS", "MAX_LIST_ITEMS", "verifier", "createHash"]
7
+ }
@@ -0,0 +1,60 @@
1
+ // @generated by scripts/build-runtime.mjs; do not edit.
2
+ // @ts-nocheck -- generated JavaScript uses a .ts extension for Pi's Jiti loader.
3
+
4
+ // src/stateful-lifecycle.ts
5
+ async function cleanupPersistedWorkspaces(agents, workspaceManager) {
6
+ const cleanup = workspaceManager.cleanupPersisted?.bind(workspaceManager);
7
+ if (!cleanup) return 0;
8
+ const results = await Promise.allSettled(
9
+ agents.filter((agent) => agent.workspaceMode === "worktree").map((agent) => cleanup(agent.id, agent.cwd))
10
+ );
11
+ return results.filter((result) => result.status === "rejected").length;
12
+ }
13
+ async function disposeStatefulRuntime(registry, workspaceManager) {
14
+ const errors = [];
15
+ try {
16
+ await registry?.shutdown();
17
+ } catch (error) {
18
+ errors.push(error);
19
+ }
20
+ try {
21
+ await workspaceManager.cleanupAll();
22
+ } catch (error) {
23
+ errors.push(error);
24
+ }
25
+ return errors;
26
+ }
27
+ async function waitForOwnedSpawn(promise, signal) {
28
+ if (!signal) return promise;
29
+ if (signal.aborted) throw ownedSpawnAbortError();
30
+ let abortHandler;
31
+ try {
32
+ return await Promise.race([
33
+ promise,
34
+ new Promise((_resolve, reject) => {
35
+ abortHandler = () => reject(ownedSpawnAbortError());
36
+ signal.addEventListener("abort", abortHandler, { once: true });
37
+ if (signal.aborted) abortHandler();
38
+ })
39
+ ]);
40
+ } finally {
41
+ if (abortHandler) signal.removeEventListener("abort", abortHandler);
42
+ }
43
+ }
44
+ function assertCurrentSpawn(signal, generation, currentGeneration) {
45
+ if (!signal?.aborted && generation === currentGeneration) return;
46
+ throw ownedSpawnAbortError();
47
+ }
48
+ function ownedSpawnAbortError() {
49
+ const error = new Error("Subagent spawn owner was replaced or aborted");
50
+ error.name = "AbortError";
51
+ return error;
52
+ }
53
+
54
+ export {
55
+ cleanupPersistedWorkspaces,
56
+ disposeStatefulRuntime,
57
+ waitForOwnedSpawn,
58
+ assertCurrentSpawn
59
+ };
60
+ //# sourceMappingURL=chunk-P7OH4XMF.ts.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/stateful-lifecycle.ts"],
4
+ "sourcesContent": ["import type { AgentRegistry, ManagedAgent } from \"./registry.js\";\nimport type { WorkspaceManager } from \"./workspace.js\";\n\nexport async function cleanupPersistedWorkspaces(\n\tagents: readonly ManagedAgent[],\n\tworkspaceManager: WorkspaceManager,\n): Promise<number> {\n\tconst cleanup = (\n\t\tworkspaceManager as WorkspaceManager & {\n\t\t\tcleanupPersisted?: (ownerId: string, cwd: string) => Promise<void>;\n\t\t}\n\t).cleanupPersisted?.bind(workspaceManager);\n\tif (!cleanup) return 0;\n\tconst results = await Promise.allSettled(\n\t\tagents\n\t\t\t.filter((agent) => agent.workspaceMode === \"worktree\")\n\t\t\t.map((agent) => cleanup(agent.id, agent.cwd)),\n\t);\n\treturn results.filter((result) => result.status === \"rejected\").length;\n}\n\nexport async function disposeStatefulRuntime(\n\tregistry: AgentRegistry | undefined,\n\tworkspaceManager: WorkspaceManager,\n): Promise<unknown[]> {\n\tconst errors: unknown[] = [];\n\ttry {\n\t\tawait registry?.shutdown();\n\t} catch (error) {\n\t\terrors.push(error);\n\t}\n\ttry {\n\t\tawait workspaceManager.cleanupAll();\n\t} catch (error) {\n\t\terrors.push(error);\n\t}\n\treturn errors;\n}\n\nexport async function waitForOwnedSpawn<T>(\n\tpromise: Promise<T>,\n\tsignal: AbortSignal | undefined,\n): Promise<T> {\n\tif (!signal) return promise;\n\tif (signal.aborted) throw ownedSpawnAbortError();\n\tlet abortHandler: (() => void) | undefined;\n\ttry {\n\t\treturn await Promise.race([\n\t\t\tpromise,\n\t\t\tnew Promise<T>((_resolve, reject) => {\n\t\t\t\tabortHandler = () => reject(ownedSpawnAbortError());\n\t\t\t\tsignal.addEventListener(\"abort\", abortHandler, { once: true });\n\t\t\t\tif (signal.aborted) abortHandler();\n\t\t\t}),\n\t\t]);\n\t} finally {\n\t\tif (abortHandler) signal.removeEventListener(\"abort\", abortHandler);\n\t}\n}\n\nexport function assertCurrentSpawn(\n\tsignal: AbortSignal | undefined,\n\tgeneration: number,\n\tcurrentGeneration: number,\n): void {\n\tif (!signal?.aborted && generation === currentGeneration) return;\n\tthrow ownedSpawnAbortError();\n}\n\nfunction ownedSpawnAbortError(): Error {\n\tconst error = new Error(\"Subagent spawn owner was replaced or aborted\");\n\terror.name = \"AbortError\";\n\treturn error;\n}\n"],
5
+ "mappings": ";;;;AAGA,eAAsB,2BACrB,QACA,kBACkB;AAClB,QAAM,UACL,iBAGC,kBAAkB,KAAK,gBAAgB;AACzC,MAAI,CAAC,QAAS,QAAO;AACrB,QAAM,UAAU,MAAM,QAAQ;AAAA,IAC7B,OACE,OAAO,CAAC,UAAU,MAAM,kBAAkB,UAAU,EACpD,IAAI,CAAC,UAAU,QAAQ,MAAM,IAAI,MAAM,GAAG,CAAC;AAAA,EAC9C;AACA,SAAO,QAAQ,OAAO,CAAC,WAAW,OAAO,WAAW,UAAU,EAAE;AACjE;AAEA,eAAsB,uBACrB,UACA,kBACqB;AACrB,QAAM,SAAoB,CAAC;AAC3B,MAAI;AACH,UAAM,UAAU,SAAS;AAAA,EAC1B,SAAS,OAAO;AACf,WAAO,KAAK,KAAK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