@narumitw/pi-subagents 2.1.4 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (312) hide show
  1. package/README.md +187 -1228
  2. package/dist/child-communication-bridge.ts +136 -0
  3. package/dist/child-communication-bridge.ts.map +7 -0
  4. package/dist/chunks/chunk-UKTWUQRM.js +667 -0
  5. package/dist/chunks/chunk-UKTWUQRM.js.map +7 -0
  6. package/dist/index.ts +1448 -1614
  7. package/dist/index.ts.map +4 -4
  8. package/docs/design-principles.md +31 -0
  9. package/docs/ipc-transport-idea.md +103 -0
  10. package/docs/tools.md +109 -0
  11. package/package.json +11 -19
  12. package/src/broker-credentials.ts +71 -0
  13. package/src/child-communication-bridge.ts +153 -0
  14. package/src/child-communication-tools.ts +147 -0
  15. package/src/completion-renderer.ts +60 -0
  16. package/src/index.ts +1 -1
  17. package/src/message-broker.ts +628 -0
  18. package/src/model-output.ts +42 -0
  19. package/src/process.ts +688 -0
  20. package/src/runtime.ts +538 -0
  21. package/src/subagents.ts +33 -34
  22. package/src/tools.ts +416 -0
  23. package/src/types.ts +85 -0
  24. package/src/widget.ts +130 -0
  25. package/dist/chunks/auto-transport-FUUKFDIG.ts +0 -109
  26. package/dist/chunks/auto-transport-FUUKFDIG.ts.map +0 -7
  27. package/dist/chunks/capability-grant-PR72SWWS.ts +0 -19
  28. package/dist/chunks/capability-grant-PR72SWWS.ts.map +0 -7
  29. package/dist/chunks/child-peer-bridge.ts +0 -108
  30. package/dist/chunks/child-peer-bridge.ts.map +0 -7
  31. package/dist/chunks/chunk-2LMJU25E.ts +0 -1641
  32. package/dist/chunks/chunk-2LMJU25E.ts.map +0 -7
  33. package/dist/chunks/chunk-47SK2QYC.ts +0 -56
  34. package/dist/chunks/chunk-47SK2QYC.ts.map +0 -7
  35. package/dist/chunks/chunk-4AQSF7AS.ts +0 -29
  36. package/dist/chunks/chunk-4AQSF7AS.ts.map +0 -7
  37. package/dist/chunks/chunk-5DGRMKNV.ts +0 -126
  38. package/dist/chunks/chunk-5DGRMKNV.ts.map +0 -7
  39. package/dist/chunks/chunk-6H6TBBED.ts +0 -108
  40. package/dist/chunks/chunk-6H6TBBED.ts.map +0 -7
  41. package/dist/chunks/chunk-6KJ34M6S.ts +0 -159
  42. package/dist/chunks/chunk-6KJ34M6S.ts.map +0 -7
  43. package/dist/chunks/chunk-6NSJVPXX.ts +0 -480
  44. package/dist/chunks/chunk-6NSJVPXX.ts.map +0 -7
  45. package/dist/chunks/chunk-7AAJEUSL.ts +0 -238
  46. package/dist/chunks/chunk-7AAJEUSL.ts.map +0 -7
  47. package/dist/chunks/chunk-BFK2Z4ZF.ts +0 -189
  48. package/dist/chunks/chunk-BFK2Z4ZF.ts.map +0 -7
  49. package/dist/chunks/chunk-BOAXY55Y.ts +0 -153
  50. package/dist/chunks/chunk-BOAXY55Y.ts.map +0 -7
  51. package/dist/chunks/chunk-D4CR7T73.ts +0 -353
  52. package/dist/chunks/chunk-D4CR7T73.ts.map +0 -7
  53. package/dist/chunks/chunk-FEVPWRMU.ts +0 -300
  54. package/dist/chunks/chunk-FEVPWRMU.ts.map +0 -7
  55. package/dist/chunks/chunk-G6VZTCFH.ts +0 -70
  56. package/dist/chunks/chunk-G6VZTCFH.ts.map +0 -7
  57. package/dist/chunks/chunk-H3FP6DLR.ts +0 -160
  58. package/dist/chunks/chunk-H3FP6DLR.ts.map +0 -7
  59. package/dist/chunks/chunk-HA36LPCO.ts +0 -130
  60. package/dist/chunks/chunk-HA36LPCO.ts.map +0 -7
  61. package/dist/chunks/chunk-HOP5FXDT.ts +0 -27
  62. package/dist/chunks/chunk-HOP5FXDT.ts.map +0 -7
  63. package/dist/chunks/chunk-IGAMVWFN.ts +0 -139
  64. package/dist/chunks/chunk-IGAMVWFN.ts.map +0 -7
  65. package/dist/chunks/chunk-ILEQ27AL.ts +0 -45
  66. package/dist/chunks/chunk-ILEQ27AL.ts.map +0 -7
  67. package/dist/chunks/chunk-ITVWPNU4.ts +0 -819
  68. package/dist/chunks/chunk-ITVWPNU4.ts.map +0 -7
  69. package/dist/chunks/chunk-IWC32VPY.ts +0 -172
  70. package/dist/chunks/chunk-IWC32VPY.ts.map +0 -7
  71. package/dist/chunks/chunk-JSZIP73U.ts +0 -362
  72. package/dist/chunks/chunk-JSZIP73U.ts.map +0 -7
  73. package/dist/chunks/chunk-JU6LUNLP.ts +0 -380
  74. package/dist/chunks/chunk-JU6LUNLP.ts.map +0 -7
  75. package/dist/chunks/chunk-KMGKCEO4.ts +0 -38
  76. package/dist/chunks/chunk-KMGKCEO4.ts.map +0 -7
  77. package/dist/chunks/chunk-LASD73CM.ts +0 -339
  78. package/dist/chunks/chunk-LASD73CM.ts.map +0 -7
  79. package/dist/chunks/chunk-LEOYDZI3.ts +0 -22
  80. package/dist/chunks/chunk-LEOYDZI3.ts.map +0 -7
  81. package/dist/chunks/chunk-LL4LP2T7.ts +0 -737
  82. package/dist/chunks/chunk-LL4LP2T7.ts.map +0 -7
  83. package/dist/chunks/chunk-N2T5IN4X.ts +0 -18
  84. package/dist/chunks/chunk-N2T5IN4X.ts.map +0 -7
  85. package/dist/chunks/chunk-N7BLVXKK.ts +0 -73
  86. package/dist/chunks/chunk-N7BLVXKK.ts.map +0 -7
  87. package/dist/chunks/chunk-NLT67IZS.ts +0 -322
  88. package/dist/chunks/chunk-NLT67IZS.ts.map +0 -7
  89. package/dist/chunks/chunk-NTRPLF46.ts +0 -63
  90. package/dist/chunks/chunk-NTRPLF46.ts.map +0 -7
  91. package/dist/chunks/chunk-ONDTY4EL.ts +0 -91
  92. package/dist/chunks/chunk-ONDTY4EL.ts.map +0 -7
  93. package/dist/chunks/chunk-OVPHFGKO.ts +0 -1769
  94. package/dist/chunks/chunk-OVPHFGKO.ts.map +0 -7
  95. package/dist/chunks/chunk-P7OH4XMF.ts +0 -60
  96. package/dist/chunks/chunk-P7OH4XMF.ts.map +0 -7
  97. package/dist/chunks/chunk-PBZMBTNJ.ts +0 -422
  98. package/dist/chunks/chunk-PBZMBTNJ.ts.map +0 -7
  99. package/dist/chunks/chunk-PGLSFLYW.ts +0 -52
  100. package/dist/chunks/chunk-PGLSFLYW.ts.map +0 -7
  101. package/dist/chunks/chunk-RRR66UWR.ts +0 -28
  102. package/dist/chunks/chunk-RRR66UWR.ts.map +0 -7
  103. package/dist/chunks/chunk-RSUXZD6S.ts +0 -275
  104. package/dist/chunks/chunk-RSUXZD6S.ts.map +0 -7
  105. package/dist/chunks/chunk-RTCVYIZA.ts +0 -221
  106. package/dist/chunks/chunk-RTCVYIZA.ts.map +0 -7
  107. package/dist/chunks/chunk-RY2AEGMZ.ts +0 -34
  108. package/dist/chunks/chunk-RY2AEGMZ.ts.map +0 -7
  109. package/dist/chunks/chunk-SWGQLFSD.ts +0 -60
  110. package/dist/chunks/chunk-SWGQLFSD.ts.map +0 -7
  111. package/dist/chunks/chunk-TM2R67J3.ts +0 -52
  112. package/dist/chunks/chunk-TM2R67J3.ts.map +0 -7
  113. package/dist/chunks/chunk-TMZRHIIK.ts +0 -497
  114. package/dist/chunks/chunk-TMZRHIIK.ts.map +0 -7
  115. package/dist/chunks/chunk-TZ34IQ3M.ts +0 -59
  116. package/dist/chunks/chunk-TZ34IQ3M.ts.map +0 -7
  117. package/dist/chunks/chunk-UMBPMVJW.ts +0 -22
  118. package/dist/chunks/chunk-UMBPMVJW.ts.map +0 -7
  119. package/dist/chunks/chunk-VDG7LTYE.ts +0 -80
  120. package/dist/chunks/chunk-VDG7LTYE.ts.map +0 -7
  121. package/dist/chunks/chunk-X4NMONPE.ts +0 -73
  122. package/dist/chunks/chunk-X4NMONPE.ts.map +0 -7
  123. package/dist/chunks/chunk-YPJEN6NU.ts +0 -65
  124. package/dist/chunks/chunk-YPJEN6NU.ts.map +0 -7
  125. package/dist/chunks/chunk-YU53SHA7.ts +0 -328
  126. package/dist/chunks/chunk-YU53SHA7.ts.map +0 -7
  127. package/dist/chunks/completion-delivery-RSJU6BXL.ts +0 -17
  128. package/dist/chunks/completion-delivery-RSJU6BXL.ts.map +0 -7
  129. package/dist/chunks/config-status-FKGDECZ3.ts +0 -35
  130. package/dist/chunks/config-status-FKGDECZ3.ts.map +0 -7
  131. package/dist/chunks/config-ui-ABHYNGQ7.ts +0 -1212
  132. package/dist/chunks/config-ui-ABHYNGQ7.ts.map +0 -7
  133. package/dist/chunks/consult-LJU3IQY5.ts +0 -519
  134. package/dist/chunks/consult-LJU3IQY5.ts.map +0 -7
  135. package/dist/chunks/context-QDKLVQXE.ts +0 -11
  136. package/dist/chunks/context-QDKLVQXE.ts.map +0 -7
  137. package/dist/chunks/create-stateful-transport-JWC2EFYL.ts +0 -130
  138. package/dist/chunks/create-stateful-transport-JWC2EFYL.ts.map +0 -7
  139. package/dist/chunks/cwd-policy-NB6XZ5GF.ts +0 -17
  140. package/dist/chunks/cwd-policy-NB6XZ5GF.ts.map +0 -7
  141. package/dist/chunks/delegation-contract-LA56I5DT.ts +0 -24
  142. package/dist/chunks/delegation-contract-LA56I5DT.ts.map +0 -7
  143. package/dist/chunks/discovery-MIFB2U4Y.ts +0 -12
  144. package/dist/chunks/discovery-MIFB2U4Y.ts.map +0 -7
  145. package/dist/chunks/execution-Q2JZLKJA.ts +0 -4037
  146. package/dist/chunks/execution-Q2JZLKJA.ts.map +0 -7
  147. package/dist/chunks/in-process-transport-HJ6TZXC3.ts +0 -39
  148. package/dist/chunks/in-process-transport-HJ6TZXC3.ts.map +0 -7
  149. package/dist/chunks/inspect-UH2TKH6E.ts +0 -634
  150. package/dist/chunks/inspect-UH2TKH6E.ts.map +0 -7
  151. package/dist/chunks/peer-communication-KL36Z6CO.ts +0 -294
  152. package/dist/chunks/peer-communication-KL36Z6CO.ts.map +0 -7
  153. package/dist/chunks/persistence-UY3PY6E5.ts +0 -348
  154. package/dist/chunks/persistence-UY3PY6E5.ts.map +0 -7
  155. package/dist/chunks/registry-BT54L6CY.ts +0 -1445
  156. package/dist/chunks/registry-BT54L6CY.ts.map +0 -7
  157. package/dist/chunks/retained-semantic-state-GM75FZGE.ts +0 -81
  158. package/dist/chunks/retained-semantic-state-GM75FZGE.ts.map +0 -7
  159. package/dist/chunks/rpc-transport-7R7DVCEB.ts +0 -1222
  160. package/dist/chunks/rpc-transport-7R7DVCEB.ts.map +0 -7
  161. package/dist/chunks/runtime-policy-5YELCOVC.ts +0 -15
  162. package/dist/chunks/runtime-policy-5YELCOVC.ts.map +0 -7
  163. package/dist/chunks/semantic-snapshot-WPJ3UAFW.ts +0 -19
  164. package/dist/chunks/semantic-snapshot-WPJ3UAFW.ts.map +0 -7
  165. package/dist/chunks/spawn-idempotency-BNHOSMZW.ts +0 -13
  166. package/dist/chunks/spawn-idempotency-BNHOSMZW.ts.map +0 -7
  167. package/dist/chunks/stateful-lifecycle-JAR6K55H.ts +0 -15
  168. package/dist/chunks/stateful-lifecycle-JAR6K55H.ts.map +0 -7
  169. package/dist/chunks/subprocess-transport-VHZJRBTW.ts +0 -160
  170. package/dist/chunks/subprocess-transport-VHZJRBTW.ts.map +0 -7
  171. package/dist/chunks/usage-recording-store-CW3EH2SZ.ts +0 -164
  172. package/dist/chunks/usage-recording-store-CW3EH2SZ.ts.map +0 -7
  173. package/dist/chunks/workspace-WDKLN72J.ts +0 -11
  174. package/dist/chunks/workspace-WDKLN72J.ts.map +0 -7
  175. package/docs/async-runtime-protocol.md +0 -84
  176. package/docs/implementation-notes/pi-subagents-capability-matrix.md +0 -62
  177. package/docs/implementation-notes/pi-subagents-current-direction.md +0 -99
  178. package/docs/implementation-notes/pi-subagents-rpc-v1.md +0 -139
  179. package/docs/pi-subagents-diagrams.md +0 -183
  180. package/src/adaptive-scheduler.ts +0 -224
  181. package/src/admission-policy.ts +0 -78
  182. package/src/agent-projection.ts +0 -53
  183. package/src/agents/built-ins.ts +0 -71
  184. package/src/agents/catalog.ts +0 -241
  185. package/src/agents/discovery.ts +0 -265
  186. package/src/agents/types.ts +0 -100
  187. package/src/agents.ts +0 -51
  188. package/src/auto-transport.ts +0 -121
  189. package/src/blocking-status.ts +0 -63
  190. package/src/cached-module-loader.ts +0 -18
  191. package/src/capabilities.ts +0 -145
  192. package/src/capability-grant.ts +0 -115
  193. package/src/capability-router.ts +0 -107
  194. package/src/child-peer-bridge.ts +0 -124
  195. package/src/child-peer-tools.ts +0 -132
  196. package/src/completion-delivery.ts +0 -409
  197. package/src/completion-render.ts +0 -190
  198. package/src/completion-requirement.ts +0 -479
  199. package/src/completion-routing.ts +0 -24
  200. package/src/config-registration.ts +0 -114
  201. package/src/config-status.ts +0 -217
  202. package/src/config-ui.ts +0 -983
  203. package/src/consult-policy.ts +0 -15
  204. package/src/consult-registration.ts +0 -125
  205. package/src/consult-render.ts +0 -194
  206. package/src/consult-resources.ts +0 -51
  207. package/src/consult-tool.ts +0 -95
  208. package/src/consult.ts +0 -566
  209. package/src/context.ts +0 -126
  210. package/src/create-stateful-transport.ts +0 -157
  211. package/src/cwd-policy.ts +0 -183
  212. package/src/delegation-contract.ts +0 -463
  213. package/src/execution/budget.ts +0 -56
  214. package/src/execution/runtime-policy.ts +0 -19
  215. package/src/execution-plan.ts +0 -322
  216. package/src/execution-ui.ts +0 -259
  217. package/src/execution.ts +0 -1679
  218. package/src/in-process-transport.ts +0 -941
  219. package/src/inspect-registration.ts +0 -64
  220. package/src/inspect-render.ts +0 -334
  221. package/src/inspect-tool.ts +0 -45
  222. package/src/inspect.ts +0 -769
  223. package/src/integration-controller.ts +0 -98
  224. package/src/limits.ts +0 -75
  225. package/src/orchestration-metrics.ts +0 -116
  226. package/src/outcome.ts +0 -61
  227. package/src/panel-child-group.ts +0 -35
  228. package/src/panel-contract.ts +0 -343
  229. package/src/panel-evidence.ts +0 -59
  230. package/src/panel-execution.ts +0 -769
  231. package/src/panel-failure.ts +0 -56
  232. package/src/panel-planning.ts +0 -175
  233. package/src/panel-presets.ts +0 -3
  234. package/src/panel-prompts.ts +0 -132
  235. package/src/panel-reconciliation.ts +0 -57
  236. package/src/panel-render.ts +0 -103
  237. package/src/parallel-limit-ui.ts +0 -113
  238. package/src/params.ts +0 -278
  239. package/src/peer-communication.ts +0 -352
  240. package/src/peer-transport.ts +0 -49
  241. package/src/persistence.ts +0 -522
  242. package/src/pi-args.ts +0 -43
  243. package/src/pi-invocation.ts +0 -168
  244. package/src/process-control.ts +0 -43
  245. package/src/prompt-resources.ts +0 -38
  246. package/src/prompt-source-safety.ts +0 -48
  247. package/src/protocol.ts +0 -76
  248. package/src/registry-types.ts +0 -204
  249. package/src/registry.ts +0 -1698
  250. package/src/render-common.ts +0 -252
  251. package/src/render.ts +0 -704
  252. package/src/result-contract.ts +0 -431
  253. package/src/retained-semantic-state.ts +0 -100
  254. package/src/rpc-timeout-finalization.ts +0 -207
  255. package/src/rpc-transport-metadata.ts +0 -65
  256. package/src/rpc-transport.ts +0 -1035
  257. package/src/rpc-turn-capture.ts +0 -217
  258. package/src/runner-outcome.ts +0 -31
  259. package/src/runner-result.ts +0 -55
  260. package/src/runner-types.ts +0 -102
  261. package/src/runner-usage.ts +0 -48
  262. package/src/runner.ts +0 -866
  263. package/src/safe-text.ts +0 -67
  264. package/src/semantic-snapshot.ts +0 -214
  265. package/src/session-guidance-contract.ts +0 -399
  266. package/src/settings/inspection.ts +0 -302
  267. package/src/settings/schema.ts +0 -195
  268. package/src/settings-reader.ts +0 -215
  269. package/src/settings.ts +0 -452
  270. package/src/spawn-idempotency.ts +0 -68
  271. package/src/stateful-agent-view.ts +0 -85
  272. package/src/stateful-config.ts +0 -13
  273. package/src/stateful-guidance.ts +0 -29
  274. package/src/stateful-lifecycle.ts +0 -74
  275. package/src/stateful-limit-ui.ts +0 -249
  276. package/src/stateful-limits.ts +0 -96
  277. package/src/stateful-prompt.ts +0 -49
  278. package/src/stateful-registration.ts +0 -1320
  279. package/src/stateful-render.ts +0 -318
  280. package/src/stateful-safety.ts +0 -47
  281. package/src/stateful-tool-params.ts +0 -215
  282. package/src/stateful.ts +0 -12
  283. package/src/subagent-details.ts +0 -43
  284. package/src/subagents-extension.ts +0 -372
  285. package/src/subprocess-transport.ts +0 -145
  286. package/src/supervision.ts +0 -104
  287. package/src/task-path.ts +0 -65
  288. package/src/timeout-checkpoint.ts +0 -305
  289. package/src/timeout-finalization.ts +0 -75
  290. package/src/tool-schema-compatibility.ts +0 -73
  291. package/src/transport-types.ts +0 -74
  292. package/src/transport-ui.ts +0 -135
  293. package/src/transport.ts +0 -43
  294. package/src/turn-budget.ts +0 -109
  295. package/src/usage-format.ts +0 -42
  296. package/src/usage-recording-config.ts +0 -13
  297. package/src/usage-recording-store.ts +0 -183
  298. package/src/usage-recording.ts +0 -478
  299. package/src/verification-harness.ts +0 -516
  300. package/src/verification-policy.ts +0 -67
  301. package/src/verification-receipt.ts +0 -275
  302. package/src/verified-execution-benchmark.ts +0 -86
  303. package/src/verified-execution-contract.ts +0 -191
  304. package/src/verified-execution-schema.ts +0 -32
  305. package/src/work-item-ledger.ts +0 -1404
  306. package/src/work-item-persistence.ts +0 -254
  307. package/src/workflow-completion-controller.ts +0 -397
  308. package/src/workflow-planning.ts +0 -172
  309. package/src/workflow-tree-identity.ts +0 -289
  310. package/src/workflow-ui.ts +0 -69
  311. package/src/workflow-verification.ts +0 -296
  312. package/src/workspace.ts +0 -174
@@ -1,1769 +0,0 @@
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
- import {
4
- redactPrivateText,
5
- truncateUtf8
6
- } from "./chunk-H3FP6DLR.ts";
7
-
8
- // src/workflow-tree-identity.ts
9
- import { execFile } from "node:child_process";
10
- import { createHash } from "node:crypto";
11
- import * as fs from "node:fs";
12
- import * as path from "node:path";
13
- var WORKFLOW_TREE_IDENTITY_VERSION = "pi-subagents:workflow-tree:v1";
14
- var DEFAULT_WORKFLOW_TREE_MAX_BYTES = 1024 * 1024;
15
- var MAX_UNTRACKED_FILES = 256;
16
- async function captureWorkflowTreeIdentity(cwd, options = {}) {
17
- const maxBytes = options.maxBytes ?? DEFAULT_WORKFLOW_TREE_MAX_BYTES;
18
- if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) {
19
- throw new Error("Workflow tree identity maxBytes must be a positive safe integer");
20
- }
21
- throwIfAborted(options.signal);
22
- let canonicalCwd;
23
- try {
24
- canonicalCwd = await fs.promises.realpath(path.resolve(cwd));
25
- } catch {
26
- throw new Error("Workflow verification requires a readable Git repository directory");
27
- }
28
- const rootOutput = await git(
29
- canonicalCwd,
30
- ["rev-parse", "--show-toplevel"],
31
- 64 * 1024,
32
- options.signal
33
- ).catch((error) => {
34
- throw normalizedGitError(error, "Workflow verification requires a Git repository");
35
- });
36
- let repositoryRoot;
37
- try {
38
- repositoryRoot = await fs.promises.realpath(rootOutput.toString("utf8").trim());
39
- } catch {
40
- throw new Error("Workflow verification requires a readable Git repository root");
41
- }
42
- const relativeCwd = path.relative(repositoryRoot, canonicalCwd);
43
- if (relativeCwd.startsWith("..") || path.isAbsolute(relativeCwd)) {
44
- throw new Error("Workflow verification cwd is outside its Git repository");
45
- }
46
- const submodules = await git(
47
- repositoryRoot,
48
- ["submodule", "status", "--recursive"],
49
- 64 * 1024,
50
- options.signal
51
- ).catch((error) => {
52
- throw normalizedGitError(error, "Workflow tree identity could not inspect submodules");
53
- });
54
- if (submodules.toString("utf8").trim()) {
55
- throw new Error("Workflow tree identity does not support repositories with submodules");
56
- }
57
- const head = (await git(repositoryRoot, ["rev-parse", "HEAD"], 64 * 1024, options.signal).catch((error) => {
58
- throw normalizedGitError(error, "Workflow verification requires a stable Git HEAD");
59
- })).toString("utf8").trim();
60
- if (!/^[a-f0-9]{40,64}$/u.test(head)) {
61
- throw new Error("Workflow verification requires a stable Git HEAD");
62
- }
63
- const commandLimit = maxBytes + 1;
64
- const indexDiff = await git(
65
- repositoryRoot,
66
- ["diff", "--binary", "--no-ext-diff", "--cached", "HEAD", "--"],
67
- commandLimit,
68
- options.signal
69
- ).catch((error) => {
70
- throw normalizedGitError(error, "Workflow tree identity exceeded its size limit");
71
- });
72
- const worktreeDiff = await git(
73
- repositoryRoot,
74
- ["diff", "--binary", "--no-ext-diff", "--"],
75
- commandLimit,
76
- options.signal
77
- ).catch((error) => {
78
- throw normalizedGitError(error, "Workflow tree identity exceeded its size limit");
79
- });
80
- if (indexDiff.length > maxBytes || worktreeDiff.length > maxBytes) {
81
- throw new Error("Workflow tree identity exceeded its size limit");
82
- }
83
- const untrackedOutput = await git(
84
- repositoryRoot,
85
- ["ls-files", "--others", "--exclude-standard", "-z"],
86
- commandLimit,
87
- options.signal
88
- ).catch((error) => {
89
- throw normalizedGitError(error, "Workflow tree identity exceeded its size limit");
90
- });
91
- const untrackedEntries = splitNul(untrackedOutput).sort(Buffer.compare);
92
- if (untrackedEntries.length > MAX_UNTRACKED_FILES) {
93
- throw new Error("Workflow tree identity exceeded its untracked-file limit");
94
- }
95
- if (indexDiff.length === 0 && worktreeDiff.length === 0 && untrackedEntries.length === 0) {
96
- return identity("git-commit", hashParts([Buffer.from("commit\0"), Buffer.from(head)]));
97
- }
98
- let consumed = indexDiff.length + worktreeDiff.length + untrackedOutput.length;
99
- if (consumed > maxBytes) throw new Error("Workflow tree identity exceeded its size limit");
100
- const hasher = createHash("sha256");
101
- hasher.update("pi-subagents:workflow-tree:v1\0");
102
- updateHashFrame(hasher, "head", head);
103
- updateHashFrame(hasher, "index-diff", indexDiff);
104
- updateHashFrame(hasher, "worktree-diff", worktreeDiff);
105
- for (const rawRelativePath of untrackedEntries) {
106
- throwIfAborted(options.signal);
107
- const relativePath = decodeGitPath(rawRelativePath);
108
- const candidate = path.resolve(repositoryRoot, relativePath);
109
- const relative2 = path.relative(repositoryRoot, candidate);
110
- if (!relative2 || relative2.startsWith("..") || path.isAbsolute(relative2)) {
111
- throw new Error("Workflow tree identity encountered an unsafe untracked path");
112
- }
113
- let bytes;
114
- let kind;
115
- try {
116
- const stat = await fs.promises.lstat(candidate);
117
- if (stat.isSymbolicLink()) {
118
- kind = "symlink";
119
- bytes = Buffer.from(await fs.promises.readlink(candidate), "utf8");
120
- } else if (stat.isFile()) {
121
- kind = "file";
122
- if (stat.size > maxBytes - consumed) {
123
- throw new Error("Workflow tree identity exceeded its size limit");
124
- }
125
- bytes = await readRegularFileNoFollow(candidate, stat, options.signal);
126
- } else {
127
- throw new Error("Workflow tree identity encountered an unsupported untracked file type");
128
- }
129
- } catch (error) {
130
- if (error instanceof Error && error.name === "AbortError") throw error;
131
- if (error instanceof Error && error.message.startsWith("Workflow tree identity")) {
132
- throw error;
133
- }
134
- throw new Error("Workflow tree identity could not read an untracked entry");
135
- }
136
- consumed += rawRelativePath.length + bytes.length;
137
- if (consumed > maxBytes) throw new Error("Workflow tree identity exceeded its size limit");
138
- updateHashFrame(hasher, "untracked-kind", kind);
139
- updateHashFrame(hasher, "untracked-path", rawRelativePath);
140
- updateHashFrame(hasher, "untracked-content", bytes);
141
- }
142
- return identity("git-dirty", hasher.digest("hex"));
143
- }
144
- function sameWorkflowTreeIdentity(left, right) {
145
- return isWorkflowTreeIdentity(left) && isWorkflowTreeIdentity(right) && left.kind === right.kind && left.digest === right.digest;
146
- }
147
- function isWorkflowTreeIdentity(value) {
148
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
149
- const candidate = value;
150
- if (Object.keys(value).some(
151
- (key) => !["version", "kind", "digest"].includes(key)
152
- )) {
153
- return false;
154
- }
155
- return candidate.version === WORKFLOW_TREE_IDENTITY_VERSION && (candidate.kind === "git-commit" || candidate.kind === "git-dirty") && typeof candidate.digest === "string" && /^[a-f0-9]{64}$/u.test(candidate.digest);
156
- }
157
- function identity(kind, digest) {
158
- return { version: WORKFLOW_TREE_IDENTITY_VERSION, kind, digest };
159
- }
160
- function hashParts(parts) {
161
- const hash = createHash("sha256");
162
- for (const part of parts) hash.update(part);
163
- return hash.digest("hex");
164
- }
165
- function updateHashFrame(hash, label, value) {
166
- const labelBytes = Buffer.from(label, "utf8");
167
- const valueBytes = typeof value === "string" ? Buffer.from(value, "utf8") : value;
168
- const header = Buffer.allocUnsafe(8);
169
- header.writeUInt32BE(labelBytes.length, 0);
170
- header.writeUInt32BE(valueBytes.length, 4);
171
- hash.update(header);
172
- hash.update(labelBytes);
173
- hash.update(valueBytes);
174
- }
175
- function splitNul(value) {
176
- const entries = [];
177
- let start = 0;
178
- for (let index = 0; index < value.length; index++) {
179
- if (value[index] !== 0) continue;
180
- if (index > start) entries.push(value.subarray(start, index));
181
- start = index + 1;
182
- }
183
- if (start < value.length) entries.push(value.subarray(start));
184
- return entries;
185
- }
186
- function decodeGitPath(value) {
187
- const decoded = value.toString("utf8");
188
- if (!decoded || decoded.includes("\0") || !Buffer.from(decoded, "utf8").equals(value)) {
189
- throw new Error("Workflow tree identity encountered an unsupported Git path encoding");
190
- }
191
- return decoded;
192
- }
193
- async function readRegularFileNoFollow(filePath, expected, signal) {
194
- throwIfAborted(signal);
195
- const handle = await fs.promises.open(filePath, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
196
- try {
197
- const before = await handle.stat();
198
- if (!before.isFile() || before.dev !== expected.dev || before.ino !== expected.ino) {
199
- throw new Error("Workflow tree identity file changed during capture");
200
- }
201
- const content = await handle.readFile({ signal });
202
- const after = await handle.stat();
203
- if (after.dev !== before.dev || after.ino !== before.ino || after.size !== before.size || after.mtimeMs !== before.mtimeMs) {
204
- throw new Error("Workflow tree identity file changed during capture");
205
- }
206
- return content;
207
- } finally {
208
- await handle.close();
209
- }
210
- }
211
- function git(cwd, args, maxBuffer, signal) {
212
- throwIfAborted(signal);
213
- return new Promise((resolve4, reject) => {
214
- execFile(
215
- "git",
216
- ["-C", cwd, ...args],
217
- { encoding: "buffer", maxBuffer, signal },
218
- (error, stdout) => {
219
- if (error) reject(error);
220
- else resolve4(stdout);
221
- }
222
- );
223
- });
224
- }
225
- function throwIfAborted(signal) {
226
- if (!signal?.aborted) return;
227
- const error = new Error("Workflow tree identity capture was cancelled");
228
- error.name = "AbortError";
229
- throw error;
230
- }
231
- function normalizedGitError(error, fallback) {
232
- if (error instanceof Error && error.name === "AbortError") return error;
233
- const message = error instanceof Error ? error.message : String(error);
234
- return new Error(
235
- /maxBuffer|stdout.*large|SIGTERM/iu.test(message) ? `${fallback}: size limit` : fallback
236
- );
237
- }
238
-
239
- // src/workflow-verification.ts
240
- var WORKFLOW_VERIFICATION_VERSION = "pi-subagents:workflow-verification:v1";
241
- var MAX_FIELD_BYTES = 2 * 1024;
242
- var MAX_ITEMS = 32;
243
- var MAX_EVIDENCE_BYTES = 6 * 1024;
244
- var MAX_LIMITATION_BYTES = 4 * 1024;
245
- var MAX_INSTRUCTION_LIST_BYTES = 8 * 1024;
246
- var ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/u;
247
- var PLAN_PATTERN = /^[a-f0-9]{64}$/u;
248
- function createWorkflowVerificationReceipt(result, context) {
249
- validateContext(context);
250
- const decision = verdict(result);
251
- const boundedSummary = bound(result.summary);
252
- if (!boundedSummary.value) throw new Error("Workflow verification verdict requires a summary");
253
- const evidenceSource = [
254
- ...result.claims.flatMap((claim) => claim.evidence),
255
- ...result.verification.flatMap((item) => [item.summary, ...item.evidence ?? []])
256
- ];
257
- const evidence = boundList(evidenceSource, MAX_EVIDENCE_BYTES);
258
- const limitations = boundList(
259
- [...result.limitations, ...result.unresolvedDependencies],
260
- MAX_LIMITATION_BYTES
261
- );
262
- if (decision === "rework" && limitations.values.length === 0) {
263
- throw new Error("Workflow verification rework requires a limitation or unresolved dependency");
264
- }
265
- if (decision === "reject" && evidence.values.length === 0) {
266
- throw new Error("Workflow verification reject requires evidence");
267
- }
268
- return {
269
- version: WORKFLOW_VERIFICATION_VERSION,
270
- decision,
271
- targetTaskId: context.targetTaskId,
272
- targetTaskGeneration: context.targetTaskGeneration,
273
- targetExecutionPlanId: context.targetExecutionPlanId,
274
- verifierTaskId: context.verifierTaskId,
275
- verifierTaskGeneration: context.verifierTaskGeneration,
276
- verifierExecutionPlanId: context.verifierExecutionPlanId,
277
- treeIdentity: structuredClone(context.treeIdentity),
278
- summary: boundedSummary.value,
279
- evidence: evidence.values,
280
- limitations: limitations.values,
281
- createdAt: context.createdAt ?? Date.now(),
282
- truncated: context.sourceTruncated === true || boundedSummary.truncated || evidence.truncated || limitations.truncated
283
- };
284
- }
285
- function workflowVerificationInstruction(targetTaskId, treeIdentity, requirements = {}) {
286
- if (!ID_PATTERN.test(targetTaskId) || !isWorkflowTreeIdentity(treeIdentity)) {
287
- throw new Error("Workflow verification instruction received invalid executor metadata");
288
- }
289
- const acceptanceCriteria = boundList(
290
- requirements.acceptanceCriteria ?? [],
291
- MAX_INSTRUCTION_LIST_BYTES
292
- ).values;
293
- const requiredEvidence = boundList(
294
- requirements.requiredEvidence ?? [],
295
- MAX_INSTRUCTION_LIST_BYTES
296
- ).values;
297
- return [
298
- "You are the independent verifier for one staged workflow result.",
299
- `Target task: ${JSON.stringify(targetTaskId)}.`,
300
- `Acceptance criteria: ${JSON.stringify(acceptanceCriteria)}.`,
301
- `Required evidence: ${JSON.stringify(requiredEvidence)}.`,
302
- `Exact Git-visible tree identity: ${treeIdentity.version}:${treeIdentity.kind}:${treeIdentity.digest}.`,
303
- "Do not modify the repository; the executor will reject acceptance if the tree identity changes.",
304
- "Return the requested pi-subagents:result:v2 object with exactly one verdict encoding.",
305
- 'Accept only with status "completed", reasonCode "verification-accepted", at least one passed verification item, no failed verification item, and no unresolved dependency.',
306
- 'Request rework only with status "partial" or "needs-input", reasonCode "verification-rework", and a concrete limitation or unresolved dependency.',
307
- 'Reject only with status "failed" or "abstained", reasonCode "verification-rejected", and concrete evidence.',
308
- "Agreement, confidence, and the implementation worker's own verification claims are not proof."
309
- ].join("\n");
310
- }
311
- function isWorkflowVerificationReceipt(value) {
312
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
313
- const receipt = value;
314
- if (Object.keys(value).some(
315
- (key) => ![
316
- "version",
317
- "decision",
318
- "targetTaskId",
319
- "targetTaskGeneration",
320
- "targetExecutionPlanId",
321
- "verifierTaskId",
322
- "verifierTaskGeneration",
323
- "verifierExecutionPlanId",
324
- "treeIdentity",
325
- "summary",
326
- "evidence",
327
- "limitations",
328
- "createdAt",
329
- "truncated"
330
- ].includes(key)
331
- )) {
332
- return false;
333
- }
334
- return receipt.version === WORKFLOW_VERIFICATION_VERSION && (receipt.decision !== "rework" || Array.isArray(receipt.limitations) && receipt.limitations.length > 0) && (receipt.decision !== "reject" || Array.isArray(receipt.evidence) && receipt.evidence.length > 0) && ["accept", "rework", "reject"].includes(String(receipt.decision)) && typeof receipt.targetTaskId === "string" && ID_PATTERN.test(receipt.targetTaskId) && Number.isSafeInteger(receipt.targetTaskGeneration) && Number(receipt.targetTaskGeneration) >= 1 && typeof receipt.targetExecutionPlanId === "string" && PLAN_PATTERN.test(receipt.targetExecutionPlanId) && typeof receipt.verifierTaskId === "string" && ID_PATTERN.test(receipt.verifierTaskId) && Number.isSafeInteger(receipt.verifierTaskGeneration) && Number(receipt.verifierTaskGeneration) >= 1 && typeof receipt.verifierExecutionPlanId === "string" && PLAN_PATTERN.test(receipt.verifierExecutionPlanId) && isWorkflowTreeIdentity(receipt.treeIdentity) && typeof receipt.summary === "string" && receipt.summary.length > 0 && Buffer.byteLength(receipt.summary, "utf8") <= MAX_FIELD_BYTES && validStrings(receipt.evidence, MAX_EVIDENCE_BYTES) && validStrings(receipt.limitations, MAX_LIMITATION_BYTES) && typeof receipt.createdAt === "number" && Number.isFinite(receipt.createdAt) && receipt.createdAt >= 0 && typeof receipt.truncated === "boolean";
335
- }
336
- function verdict(result) {
337
- if (result.version !== "pi-subagents:result:v2") {
338
- throw new Error("Workflow verification requires structured-v2");
339
- }
340
- if (result.reasonCode === "verification-accepted" && result.status === "completed") {
341
- if (result.verification.some((item) => item.status === "failed")) {
342
- throw new Error("Workflow verification accept cannot contain failed evidence");
343
- }
344
- if (!result.verification.some((item) => item.status === "passed")) {
345
- throw new Error("Workflow verification accept requires passed evidence");
346
- }
347
- if (result.unresolvedDependencies.length > 0) {
348
- throw new Error("Workflow verification accept cannot contain unresolved dependencies");
349
- }
350
- return "accept";
351
- }
352
- if (result.reasonCode === "verification-rework" && (result.status === "partial" || result.status === "needs-input")) {
353
- return "rework";
354
- }
355
- if (result.reasonCode === "verification-rejected" && (result.status === "failed" || result.status === "abstained")) {
356
- return "reject";
357
- }
358
- throw new Error("Workflow verification result does not contain a valid verdict");
359
- }
360
- function validateContext(context) {
361
- for (const [label, value] of [
362
- ["target task", context.targetTaskId],
363
- ["verifier task", context.verifierTaskId]
364
- ]) {
365
- if (!ID_PATTERN.test(value))
366
- throw new Error(`Workflow verification has an invalid ${label} id`);
367
- }
368
- for (const [label, value] of [
369
- ["target", context.targetTaskGeneration],
370
- ["verifier", context.verifierTaskGeneration]
371
- ]) {
372
- if (!Number.isSafeInteger(value) || value < 1) {
373
- throw new Error(`Workflow verification has an invalid ${label} task generation`);
374
- }
375
- }
376
- for (const value of [context.targetExecutionPlanId, context.verifierExecutionPlanId]) {
377
- if (!PLAN_PATTERN.test(value)) {
378
- throw new Error("Workflow verification has an invalid execution plan identity");
379
- }
380
- }
381
- if (!isWorkflowTreeIdentity(context.treeIdentity)) {
382
- throw new Error("Workflow verification has an invalid tree identity");
383
- }
384
- if (context.sourceTruncated !== void 0 && typeof context.sourceTruncated !== "boolean") {
385
- throw new Error("Workflow verification has an invalid truncation state");
386
- }
387
- if (context.createdAt !== void 0 && (!Number.isFinite(context.createdAt) || context.createdAt < 0)) {
388
- throw new Error("Workflow verification has an invalid creation time");
389
- }
390
- }
391
- function bound(value) {
392
- const redacted = redactPrivateText(value).trim();
393
- const truncated = truncateUtf8(redacted, MAX_FIELD_BYTES);
394
- return { value: truncated.text, truncated: truncated.truncated };
395
- }
396
- function boundList(values, maxTotalBytes) {
397
- let truncated = values.length > MAX_ITEMS;
398
- let remaining = maxTotalBytes;
399
- const result = [];
400
- const seen = /* @__PURE__ */ new Set();
401
- for (const raw of values.slice(0, MAX_ITEMS)) {
402
- if (remaining < 1) {
403
- truncated = true;
404
- break;
405
- }
406
- const redacted = redactPrivateText(raw).trim();
407
- const item = truncateUtf8(redacted, Math.min(MAX_FIELD_BYTES, remaining));
408
- truncated ||= item.truncated;
409
- if (!item.text || seen.has(item.text)) continue;
410
- seen.add(item.text);
411
- result.push(item.text);
412
- remaining -= Buffer.byteLength(item.text, "utf8");
413
- }
414
- return { values: result, truncated };
415
- }
416
- function validStrings(value, maxTotalBytes) {
417
- return Array.isArray(value) && value.length <= MAX_ITEMS && value.reduce(
418
- (total, item) => total + (typeof item === "string" ? Buffer.byteLength(item, "utf8") : maxTotalBytes + 1),
419
- 0
420
- ) <= maxTotalBytes && value.every(
421
- (item) => typeof item === "string" && item.length > 0 && Buffer.byteLength(item, "utf8") <= MAX_FIELD_BYTES
422
- );
423
- }
424
-
425
- // src/work-item-persistence.ts
426
- import { createHash as createHash2 } from "node:crypto";
427
- import * as fs2 from "node:fs";
428
- import * as path3 from "node:path";
429
- import { getAgentDir, withFileMutationQueue } from "@earendil-works/pi-coding-agent";
430
-
431
- // src/integration-controller.ts
432
- import * as path2 from "node:path";
433
- function verifyManagedIntegration(expected, candidate) {
434
- if (candidate.taskId !== expected.taskId || candidate.taskGeneration !== expected.taskGeneration) {
435
- throw new Error("Managed integration rejected stale task generation");
436
- }
437
- if (candidate.baseRepositoryGeneration !== expected.baseRepositoryGeneration) {
438
- throw new Error("Managed integration rejected stale base repository generation");
439
- }
440
- if (candidate.executionPlanId !== expected.executionPlanId) {
441
- throw new Error("Managed integration rejected stale execution plan identity");
442
- }
443
- if (!sameRecord(candidate.dependencyVersions, expected.dependencyVersions)) {
444
- throw new Error("Managed integration rejected stale dependency versions");
445
- }
446
- if (!sameRecord(candidate.readSetVersions, expected.readSetVersions)) {
447
- throw new Error("Managed integration rejected stale read-set versions");
448
- }
449
- if (candidate.patchDigest !== expected.patchDigest) {
450
- throw new Error("Managed integration rejected patch digest mismatch");
451
- }
452
- const allowedScopes = expected.allowedScopes.map(normalizedPath);
453
- if (!candidate.changedPaths.every((changedPath) => {
454
- const normalizedChangedPath = normalizedPath(changedPath);
455
- return allowedScopes.some(
456
- (scope) => normalizedChangedPath === scope || normalizedChangedPath.startsWith(`${scope}${path2.sep}`)
457
- );
458
- })) {
459
- throw new Error("Managed integration rejected a path outside the accepted scope");
460
- }
461
- if (expected.requiredEvidence.some((id) => !candidate.evidence[id])) {
462
- throw new Error("Managed integration rejected missing required evidence");
463
- }
464
- if (!candidate.verifier.freshContext || !candidate.verifier.exactIntegratedTree) {
465
- throw new Error("Managed integration requires a fresh verifier on the exact integrated tree");
466
- }
467
- if (candidate.verifier.status !== "accepted") {
468
- throw new Error(`Managed integration verifier returned ${candidate.verifier.status}`);
469
- }
470
- return {
471
- status: "accepted",
472
- taskId: expected.taskId,
473
- taskGeneration: expected.taskGeneration,
474
- patchDigest: expected.patchDigest,
475
- executionPlanId: expected.executionPlanId
476
- };
477
- }
478
- function normalizedPath(value) {
479
- if (!value || value.includes("\0")) throw new Error("Managed integration scope is invalid");
480
- return path2.resolve(path2.sep, value.replaceAll("\\", path2.sep));
481
- }
482
- function sameRecord(left, right) {
483
- const leftEntries = Object.entries(left).sort(([a], [b]) => a.localeCompare(b));
484
- const rightEntries = Object.entries(right).sort(([a], [b]) => a.localeCompare(b));
485
- return JSON.stringify(leftEntries) === JSON.stringify(rightEntries);
486
- }
487
-
488
- // src/verification-receipt.ts
489
- import { Type } from "typebox";
490
- import { Check } from "typebox/value";
491
- var VERIFICATION_RECEIPT_VERSION = "pi-subagents:verification-receipt:v1";
492
- var MAX_FIELD_BYTES2 = 4 * 1024;
493
- var MAX_OUTPUT_BYTES = 2 * 1024;
494
- var MAX_RECEIPT_BYTES = 12 * 1024;
495
- var MAX_LIST_ITEMS = 64;
496
- var MAX_RECORD_ITEMS = 64;
497
- var ID_PATTERN2 = "^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$";
498
- var SHA_PATTERN = "^[a-f0-9]{64}$";
499
- var REPOSITORY_GENERATION_PATTERN = "^[a-f0-9]{40,64}$";
500
- var BoundedId = Type.String({ pattern: ID_PATTERN2, maxLength: 256 });
501
- var Sha256 = Type.String({ pattern: SHA_PATTERN, maxLength: 64 });
502
- var BoundedText = Type.String({ minLength: 1, maxLength: MAX_FIELD_BYTES2 });
503
- var TreeIdentitySchema = Type.Object(
504
- {
505
- version: Type.Literal(WORKFLOW_TREE_IDENTITY_VERSION),
506
- kind: Type.Union([Type.Literal("git-commit"), Type.Literal("git-dirty")]),
507
- digest: Sha256
508
- },
509
- { additionalProperties: false }
510
- );
511
- var StringRecordSchema = Type.Record(
512
- Type.String({ minLength: 1, maxLength: 4096 }),
513
- Type.String({ minLength: 1, maxLength: MAX_FIELD_BYTES2 }),
514
- { maxProperties: MAX_RECORD_ITEMS }
515
- );
516
- var VerificationCheckReceiptSchema = Type.Object(
517
- {
518
- id: BoundedId,
519
- command: Type.String({ minLength: 1, maxLength: 256 }),
520
- args: Type.Array(Type.String({ maxLength: 4096 }), { maxItems: 64 }),
521
- cwd: Type.String({ minLength: 1, maxLength: 4096 }),
522
- status: Type.Union([Type.Literal("passed"), Type.Literal("failed")]),
523
- exitCode: Type.Integer({ minimum: -1, maximum: 255 }),
524
- stdout: Type.String({ maxLength: MAX_OUTPUT_BYTES }),
525
- stderr: Type.String({ maxLength: MAX_OUTPUT_BYTES }),
526
- durationMs: Type.Integer({ minimum: 0 }),
527
- truncated: Type.Boolean()
528
- },
529
- { additionalProperties: false }
530
- );
531
- var VerificationReceiptSchema = Type.Object(
532
- {
533
- version: Type.Literal(VERIFICATION_RECEIPT_VERSION),
534
- decision: Type.Union([Type.Literal("accept"), Type.Literal("rework"), Type.Literal("reject")]),
535
- targetTaskId: BoundedId,
536
- targetTaskGeneration: Type.Integer({ minimum: 1 }),
537
- targetExecutionPlanId: Sha256,
538
- verifierTaskId: BoundedId,
539
- verifierTaskGeneration: Type.Integer({ minimum: 1 }),
540
- verifierExecutionPlanId: Sha256,
541
- verifierAgent: BoundedId,
542
- beforeTreeIdentity: TreeIdentitySchema,
543
- afterTreeIdentity: TreeIdentitySchema,
544
- baseRepositoryGeneration: Type.String({
545
- pattern: REPOSITORY_GENERATION_PATTERN,
546
- maxLength: 64
547
- }),
548
- patchDigest: Sha256,
549
- changedPaths: Type.Array(Type.String({ minLength: 1, maxLength: 4096 }), {
550
- maxItems: MAX_LIST_ITEMS
551
- }),
552
- allowedScopes: Type.Array(Type.String({ minLength: 1, maxLength: 4096 }), {
553
- minItems: 1,
554
- maxItems: MAX_LIST_ITEMS
555
- }),
556
- dependencyVersions: StringRecordSchema,
557
- readSetVersions: StringRecordSchema,
558
- acceptanceCriteria: Type.Array(BoundedText, { maxItems: MAX_LIST_ITEMS }),
559
- requiredEvidenceIds: Type.Array(BoundedId, { maxItems: MAX_LIST_ITEMS }),
560
- evidence: StringRecordSchema,
561
- checks: Type.Array(VerificationCheckReceiptSchema, { maxItems: 32 }),
562
- summary: BoundedText,
563
- findings: Type.Array(BoundedText, { maxItems: MAX_LIST_ITEMS }),
564
- createdAt: Type.Number({ minimum: 0 }),
565
- sourceTruncated: Type.Boolean()
566
- },
567
- { additionalProperties: false }
568
- );
569
- function createVerificationReceipt(input) {
570
- const receipt = {
571
- version: VERIFICATION_RECEIPT_VERSION,
572
- decision: input.decision,
573
- targetTaskId: input.targetTaskId,
574
- targetTaskGeneration: input.targetTaskGeneration,
575
- targetExecutionPlanId: input.targetExecutionPlanId,
576
- verifierTaskId: input.verifierTaskId,
577
- verifierTaskGeneration: input.verifierTaskGeneration,
578
- verifierExecutionPlanId: input.verifierExecutionPlanId,
579
- verifierAgent: input.verifierAgent,
580
- beforeTreeIdentity: structuredClone(input.beforeTreeIdentity),
581
- afterTreeIdentity: structuredClone(input.afterTreeIdentity),
582
- baseRepositoryGeneration: input.baseRepositoryGeneration,
583
- patchDigest: input.patchDigest,
584
- changedPaths: boundList2(input.changedPaths, MAX_FIELD_BYTES2),
585
- allowedScopes: boundList2(input.allowedScopes, MAX_FIELD_BYTES2),
586
- dependencyVersions: boundRecord(input.dependencyVersions),
587
- readSetVersions: boundRecord(input.readSetVersions),
588
- acceptanceCriteria: boundList2(input.acceptanceCriteria, MAX_FIELD_BYTES2),
589
- requiredEvidenceIds: boundList2(input.requiredEvidenceIds, 256),
590
- evidence: boundRecord(input.evidence),
591
- checks: input.checks.slice(0, 32).map(boundCheck),
592
- summary: boundRequired(input.summary, MAX_FIELD_BYTES2, "summary"),
593
- findings: boundList2(input.findings, MAX_FIELD_BYTES2),
594
- createdAt: input.createdAt,
595
- sourceTruncated: input.sourceTruncated || input.checks.length > 32 || input.checks.some(
596
- (check) => check.truncated || check.args.length > 64 || check.args.some((value) => Buffer.byteLength(value, "utf8") > 4096) || Buffer.byteLength(check.stdout, "utf8") > MAX_OUTPUT_BYTES || Buffer.byteLength(check.stderr, "utf8") > MAX_OUTPUT_BYTES
597
- ) || input.requiredEvidenceIds.some((value) => Buffer.byteLength(value, "utf8") > 256) || [
598
- input.changedPaths,
599
- input.allowedScopes,
600
- input.acceptanceCriteria,
601
- input.requiredEvidenceIds,
602
- input.findings
603
- ].some(
604
- (values) => values.length > MAX_LIST_ITEMS || values.some((value) => Buffer.byteLength(value, "utf8") > MAX_FIELD_BYTES2)
605
- ) || [input.dependencyVersions, input.readSetVersions, input.evidence].some(
606
- (value) => Object.keys(value).length > MAX_RECORD_ITEMS || Object.entries(value).some(
607
- ([key, item]) => Buffer.byteLength(key, "utf8") > 4096 || Buffer.byteLength(item, "utf8") > MAX_FIELD_BYTES2
608
- )
609
- )
610
- };
611
- assertReceiptSemantics(receipt);
612
- if (!Check(VerificationReceiptSchema, receipt)) {
613
- throw new Error("Verification receipt contains invalid executor metadata");
614
- }
615
- if (Buffer.byteLength(JSON.stringify(receipt), "utf8") > MAX_RECEIPT_BYTES) {
616
- throw new Error("Verification receipt exceeded its total size limit");
617
- }
618
- return receipt;
619
- }
620
- function isVerificationReceipt(value) {
621
- if (!Check(VerificationReceiptSchema, value) || Buffer.byteLength(JSON.stringify(value), "utf8") > MAX_RECEIPT_BYTES) {
622
- return false;
623
- }
624
- try {
625
- assertReceiptSemantics(value);
626
- return true;
627
- } catch {
628
- return false;
629
- }
630
- }
631
- function assertReceiptSemantics(receipt) {
632
- if (receipt.beforeTreeIdentity.kind !== receipt.afterTreeIdentity.kind || receipt.beforeTreeIdentity.digest !== receipt.afterTreeIdentity.digest) {
633
- throw new Error("Verification receipt rejected submitted-state drift");
634
- }
635
- const missingEvidence = receipt.requiredEvidenceIds.filter((id) => !receipt.evidence[id]);
636
- if (receipt.decision === "accept" && missingEvidence.length > 0) {
637
- throw new Error(
638
- `Verification receipt is missing required evidence: ${missingEvidence.join(", ")}`
639
- );
640
- }
641
- if (receipt.decision === "accept" && receipt.checks.some((check) => check.status !== "passed")) {
642
- throw new Error("Verification receipt cannot accept a failed check");
643
- }
644
- if (receipt.decision === "rework" && receipt.findings.length === 0) {
645
- throw new Error("Verification receipt rework requires a concrete finding");
646
- }
647
- if (receipt.decision === "reject" && receipt.findings.length === 0) {
648
- throw new Error("Verification receipt reject requires a concrete finding");
649
- }
650
- for (const values of [
651
- receipt.changedPaths,
652
- receipt.allowedScopes,
653
- receipt.acceptanceCriteria,
654
- receipt.requiredEvidenceIds,
655
- receipt.findings
656
- ]) {
657
- if (new Set(values).size !== values.length) {
658
- throw new Error("Verification receipt contains duplicate bounded values");
659
- }
660
- }
661
- if (new Set(receipt.checks.map((check) => check.id)).size !== receipt.checks.length) {
662
- throw new Error("Verification receipt contains duplicate check ids");
663
- }
664
- }
665
- function boundCheck(check) {
666
- const stdout = boundOptional(check.stdout, MAX_OUTPUT_BYTES);
667
- const stderr = boundOptional(check.stderr, MAX_OUTPUT_BYTES);
668
- return {
669
- id: boundRequired(check.id, 256, "check id"),
670
- command: boundRequired(check.command, 256, "check command"),
671
- args: check.args.slice(0, 64).map((value) => boundOptional(value, 4096).value),
672
- cwd: boundRequired(check.cwd, 4096, "check cwd"),
673
- status: check.status,
674
- exitCode: check.exitCode,
675
- stdout: stdout.value,
676
- stderr: stderr.value,
677
- durationMs: Math.max(0, Math.floor(check.durationMs)),
678
- truncated: check.truncated || stdout.truncated || stderr.truncated || check.args.length > 64
679
- };
680
- }
681
- function boundList2(values, maxItemBytes) {
682
- const result = [];
683
- const seen = /* @__PURE__ */ new Set();
684
- for (const value of values.slice(0, MAX_LIST_ITEMS)) {
685
- const bounded2 = boundOptional(value, maxItemBytes).value;
686
- if (!bounded2 || seen.has(bounded2)) continue;
687
- seen.add(bounded2);
688
- result.push(bounded2);
689
- }
690
- return result;
691
- }
692
- function boundRecord(value) {
693
- const entries = Object.entries(value).slice(0, MAX_RECORD_ITEMS);
694
- return Object.fromEntries(
695
- entries.map(([key, item]) => [
696
- boundRequired(key, 4096, "record key"),
697
- boundRequired(item, MAX_FIELD_BYTES2, "record value")
698
- ])
699
- );
700
- }
701
- function boundRequired(value, maxBytes, label) {
702
- const bounded2 = boundOptional(value, maxBytes).value;
703
- if (!bounded2) throw new Error(`Verification receipt requires ${label}`);
704
- return bounded2;
705
- }
706
- function boundOptional(value, maxBytes) {
707
- const redacted = redactPrivateText(value).trim();
708
- const bounded2 = truncateUtf8(redacted, maxBytes);
709
- return { value: bounded2.text, truncated: bounded2.truncated };
710
- }
711
-
712
- // src/work-item-ledger.ts
713
- var WORK_ITEM_LEDGER_VERSION = "pi-subagents:work-ledger:v3";
714
- var LEGACY_WORK_ITEM_LEDGER_VERSIONS = /* @__PURE__ */ new Set([
715
- "pi-subagents:work-ledger:v1",
716
- "pi-subagents:work-ledger:v2"
717
- ]);
718
- var WORK_ITEM_ACCEPTANCE_VERSION = "pi-subagents:work-acceptance:v1";
719
- var MAX_ITEMS2 = 64;
720
- var MAX_IDENTIFIER_LENGTH = 256;
721
- var MAX_TEXT_LENGTH = 16 * 1024;
722
- var MAX_LIST_ITEMS2 = 50;
723
- var TERMINAL_STATES = /* @__PURE__ */ new Set([
724
- "completed",
725
- "failed",
726
- "interrupted",
727
- "stale",
728
- "invalidated"
729
- ]);
730
- var WorkItemLedger = class _WorkItemLedger {
731
- constructor(workflowId) {
732
- this.workflowId = workflowId;
733
- }
734
- workflowId;
735
- items = /* @__PURE__ */ new Map();
736
- generation = 0;
737
- static create(input) {
738
- validateIdentifier(input.workflowId, "workflowId");
739
- if (!Array.isArray(input.items) || input.items.length < 1 || input.items.length > MAX_ITEMS2) {
740
- throw new Error(`WorkItem workflow must contain 1-${MAX_ITEMS2} items`);
741
- }
742
- const ledger = new _WorkItemLedger(input.workflowId);
743
- for (const definition of input.items) ledger.addDefinition(definition);
744
- ledger.linkAndValidate();
745
- ledger.refreshReadyState();
746
- return ledger;
747
- }
748
- get(id) {
749
- const item = this.items.get(id);
750
- return item ? structuredClone(item) : void 0;
751
- }
752
- readyItems() {
753
- this.refreshReadyState();
754
- return [...this.items.values()].filter((item) => item.state === "ready").sort((left, right) => left.id.localeCompare(right.id)).map((item) => structuredClone(item));
755
- }
756
- start(id, agentId) {
757
- const item = this.require(id);
758
- if (item.state !== "ready") {
759
- throw new Error(`WorkItem ${id} cannot start while ${item.state}`);
760
- }
761
- validateIdentifier(agentId, "agentId");
762
- item.state = "running";
763
- item.assignedAgentId = agentId;
764
- item.generation = ++this.generation;
765
- return structuredClone(item);
766
- }
767
- complete(id, input) {
768
- const item = this.require(id);
769
- this.assertMutable(item);
770
- if (item.acceptanceRequired) {
771
- throw new Error(`WorkItem ${id} requires executor-owned acceptance staging`);
772
- }
773
- if (item.state !== "running") {
774
- throw new Error(`WorkItem ${id} cannot complete while ${item.state}`);
775
- }
776
- if (input.taskGeneration !== item.taskGeneration) {
777
- throw new Error(`WorkItem ${id} rejected a stale task generation`);
778
- }
779
- item.acceptedExecutionPlanId = input.executionPlanId?.slice(0, 256);
780
- item.artifactHistory.push(...item.artifacts.map((artifact) => structuredClone(artifact)));
781
- item.artifacts = normalizeArtifacts(input.artifacts ?? [], id, this.generation + 1);
782
- item.verificationAccepted = false;
783
- item.stagedTreeIdentity = void 0;
784
- item.verificationReceipt = void 0;
785
- item.acceptanceState = "not-required";
786
- item.state = "completed";
787
- item.generation = ++this.generation;
788
- this.refreshReadyState();
789
- return structuredClone(item);
790
- }
791
- stageForVerifiedAcceptance(id, input) {
792
- const item = this.require(id);
793
- this.assertMutable(item);
794
- if (!item.acceptanceRequired || !item.integrationOwner) {
795
- throw new Error(`WorkItem ${id} is not a verified integration target`);
796
- }
797
- if (item.state !== "running") {
798
- throw new Error(`WorkItem ${id} cannot stage acceptance while ${item.state}`);
799
- }
800
- if (input.taskGeneration !== item.taskGeneration) {
801
- throw new Error(`WorkItem ${id} rejected a stale task generation`);
802
- }
803
- validatePlanId(input.executionPlanId, "staged execution plan");
804
- validateSubmission(input);
805
- item.acceptedExecutionPlanId = input.executionPlanId;
806
- item.artifactHistory.push(...item.artifacts.map((artifact) => structuredClone(artifact)));
807
- item.artifacts = normalizeArtifacts(input.artifacts ?? [], id, this.generation + 1);
808
- item.verificationAccepted = false;
809
- item.acceptanceState = "pending";
810
- item.stagedTreeIdentity = structuredClone(input.treeIdentity);
811
- item.submission = {
812
- treeIdentity: structuredClone(input.treeIdentity),
813
- baseRepositoryGeneration: input.baseRepositoryGeneration,
814
- patchDigest: input.patchDigest,
815
- changedPaths: [...input.changedPaths],
816
- fileVersions: { ...input.fileVersions }
817
- };
818
- item.acceptanceReceipt = void 0;
819
- item.state = "completed";
820
- item.generation = ++this.generation;
821
- this.refreshReadyState();
822
- return structuredClone(item);
823
- }
824
- stageForVerification(id, input) {
825
- const item = this.require(id);
826
- this.assertMutable(item);
827
- if (item.state !== "running") {
828
- throw new Error(`WorkItem ${id} cannot stage verification while ${item.state}`);
829
- }
830
- if (input.taskGeneration !== item.taskGeneration) {
831
- throw new Error(`WorkItem ${id} rejected a stale task generation`);
832
- }
833
- validatePlanId(input.executionPlanId, "staged execution plan");
834
- if (!isWorkflowTreeIdentity(input.treeIdentity)) {
835
- throw new Error(`WorkItem ${id} received an invalid staged tree identity`);
836
- }
837
- item.acceptedExecutionPlanId = input.executionPlanId;
838
- item.artifactHistory.push(...item.artifacts.map((artifact) => structuredClone(artifact)));
839
- item.artifacts = normalizeArtifacts(input.artifacts ?? [], id, this.generation + 1);
840
- item.verificationAccepted = false;
841
- item.stagedTreeIdentity = structuredClone(input.treeIdentity);
842
- item.verificationReceipt = void 0;
843
- item.state = "awaiting-verification";
844
- item.generation = ++this.generation;
845
- this.refreshReadyState();
846
- return structuredClone(item);
847
- }
848
- completeVerification(verifierId, input) {
849
- const verifier = this.require(verifierId);
850
- this.assertMutable(verifier);
851
- if (verifier.state !== "running" || !verifier.verifierFor) {
852
- throw new Error(`WorkItem ${verifierId} is not a running verifier`);
853
- }
854
- if (input.taskGeneration !== verifier.taskGeneration) {
855
- throw new Error(`WorkItem ${verifierId} rejected a stale verifier generation`);
856
- }
857
- validatePlanId(input.executionPlanId, "verifier execution plan");
858
- if (!isWorkflowVerificationReceipt(input.receipt)) {
859
- throw new Error(`WorkItem ${verifierId} received an invalid verification receipt`);
860
- }
861
- const target = this.require(verifier.verifierFor);
862
- if (target.state !== "awaiting-verification") {
863
- throw new Error(`WorkItem ${target.id} is not awaiting verification`);
864
- }
865
- assertReceiptMatches(target, verifier, input.executionPlanId, input.receipt);
866
- verifier.acceptedExecutionPlanId = input.executionPlanId;
867
- verifier.verificationReceipt = void 0;
868
- verifier.verificationAccepted = false;
869
- verifier.state = "completed";
870
- verifier.generation = ++this.generation;
871
- target.verificationReceipt = structuredClone(input.receipt);
872
- target.verificationAccepted = input.receipt.decision === "accept";
873
- target.outcomeReason = input.receipt.decision === "accept" ? void 0 : input.receipt.decision === "rework" ? "verification-rework" : "verification-rejected";
874
- if (input.receipt.decision === "accept") {
875
- target.artifacts = target.artifacts.map((artifact) => ({ ...artifact, verified: true }));
876
- target.state = "completed";
877
- } else {
878
- target.state = input.receipt.decision === "rework" ? "blocked" : "failed";
879
- this.invalidateDependents(target.id, verifier.id, target.outcomeReason);
880
- }
881
- target.generation = ++this.generation;
882
- this.refreshReadyState();
883
- return { target: structuredClone(target), verifier: structuredClone(verifier) };
884
- }
885
- recordVerificationDecision(verifierId, input) {
886
- const verifier = this.require(verifierId);
887
- if (verifier.state !== "running" || !verifier.verifierFor) {
888
- throw new Error(`WorkItem ${verifierId} is not a running verifier`);
889
- }
890
- if (input.taskGeneration !== verifier.taskGeneration) {
891
- throw new Error(`WorkItem ${verifierId} rejected a stale verifier generation`);
892
- }
893
- validatePlanId(input.executionPlanId, "verifier execution plan");
894
- if (!isVerificationReceipt(input.receipt) || input.receipt.decision === "accept") {
895
- throw new Error(`WorkItem ${verifierId} received an invalid non-acceptance receipt`);
896
- }
897
- const target = this.require(verifier.verifierFor);
898
- assertVerifiedReceiptMatches(target, verifier, input.executionPlanId, input.receipt);
899
- verifier.acceptedExecutionPlanId = input.executionPlanId;
900
- verifier.state = "completed";
901
- verifier.generation = ++this.generation;
902
- target.acceptanceReceipt = structuredClone(input.receipt);
903
- target.acceptanceReceiptHistory.push(structuredClone(input.receipt));
904
- target.verificationAccepted = false;
905
- if (input.receipt.decision === "rework" && target.reworkCount < target.maxReworkCycles) {
906
- target.reworkCount++;
907
- target.acceptanceState = "rework-requested";
908
- target.state = "blocked";
909
- target.outcomeReason = "verification-rework";
910
- } else {
911
- target.acceptanceState = "rejected";
912
- target.state = "failed";
913
- target.outcomeReason = input.receipt.decision === "rework" ? "verification-rework-exhausted" : "verification-rejected";
914
- }
915
- target.generation = ++this.generation;
916
- this.invalidateDependents(target.id, verifier.id, target.outcomeReason);
917
- this.refreshReadyState();
918
- return { target: structuredClone(target), verifier: structuredClone(verifier) };
919
- }
920
- beginVerificationRework(id) {
921
- const target = this.require(id);
922
- if (target.acceptanceState !== "rework-requested" || target.state !== "blocked") {
923
- throw new Error(`WorkItem ${id} has no accepted rework request`);
924
- }
925
- const verifier = [...this.items.values()].find((item) => item.verifierFor === id);
926
- if (verifier?.state !== "completed") {
927
- throw new Error(`WorkItem ${id} has no completed verifier for rework`);
928
- }
929
- target.artifactHistory.push(...target.artifacts.map((artifact) => structuredClone(artifact)));
930
- target.artifacts = [];
931
- target.state = "pending";
932
- target.acceptanceState = "pending";
933
- target.taskGeneration++;
934
- target.assignedAgentId = void 0;
935
- target.acceptedExecutionPlanId = void 0;
936
- target.stagedTreeIdentity = void 0;
937
- target.submission = void 0;
938
- target.verificationAccepted = false;
939
- target.outcomeReason = void 0;
940
- target.generation = ++this.generation;
941
- verifier.state = "pending";
942
- verifier.taskGeneration++;
943
- verifier.assignedAgentId = void 0;
944
- verifier.acceptedExecutionPlanId = void 0;
945
- verifier.outcomeReason = void 0;
946
- verifier.generation = ++this.generation;
947
- this.resetReworkDependents(target.id, verifier.id);
948
- this.refreshReadyState();
949
- return structuredClone(target);
950
- }
951
- failVerification(verifierId, reason) {
952
- const verifier = this.require(verifierId);
953
- if (!verifier.verifierFor) throw new Error(`WorkItem ${verifierId} is not a verifier`);
954
- const target = this.require(verifier.verifierFor);
955
- const boundedReason = bounded(reason, MAX_TEXT_LENGTH);
956
- if (!boundedReason) throw new Error("Verification failure requires a reason");
957
- if (!TERMINAL_STATES.has(verifier.state)) {
958
- verifier.state = "failed";
959
- verifier.outcomeReason = boundedReason;
960
- verifier.generation = ++this.generation;
961
- }
962
- if (target.state === "awaiting-verification" || target.state === "completed" && target.acceptanceState === "pending") {
963
- target.state = "failed";
964
- if (target.acceptanceRequired) target.acceptanceState = "rejected";
965
- target.verificationAccepted = false;
966
- target.outcomeReason = boundedReason;
967
- target.generation = ++this.generation;
968
- }
969
- const invalidated = this.invalidateDependents(target.id, verifier.id, boundedReason);
970
- return [structuredClone(target), structuredClone(verifier), ...invalidated];
971
- }
972
- settle(id, state, reason) {
973
- const item = this.require(id);
974
- this.assertMutable(item);
975
- if (item.state !== "running" && item.state !== "awaiting-verification" && !(item.state === "completed" && item.acceptanceState === "pending") && item.state !== "ready" && item.state !== "pending") {
976
- throw new Error(`WorkItem ${id} cannot settle while ${item.state}`);
977
- }
978
- item.state = state;
979
- if (item.acceptanceRequired) item.acceptanceState = "rejected";
980
- item.outcomeReason = reason ? bounded(reason, MAX_TEXT_LENGTH) : void 0;
981
- item.generation = ++this.generation;
982
- this.refreshReadyState();
983
- return structuredClone(item);
984
- }
985
- acceptIntegration(id, expected, candidate, verified) {
986
- const item = this.require(id);
987
- if (!item.integrationOwner) {
988
- throw new Error(`WorkItem ${id} is not the integration owner`);
989
- }
990
- if (expected.taskId !== id || expected.taskGeneration !== item.taskGeneration) {
991
- throw new Error(`WorkItem ${id} integration expectation has a stale generation`);
992
- }
993
- if (!verified) {
994
- if (item.state !== "running" || item.acceptanceRequired) {
995
- throw new Error(`WorkItem ${id} cannot integrate while ${item.state}`);
996
- }
997
- verifyManagedIntegration(expected, candidate);
998
- item.verificationAccepted = true;
999
- item.generation = ++this.generation;
1000
- return structuredClone(item);
1001
- }
1002
- if (item.state !== "completed" || item.acceptanceState !== "pending") {
1003
- throw new Error(`WorkItem ${id} is not pending verified acceptance`);
1004
- }
1005
- const verifier = this.require(verified.verifierId);
1006
- if (verifier.state !== "running" || verifier.verifierFor !== id || verified.verifierTaskGeneration !== verifier.taskGeneration) {
1007
- throw new Error(`WorkItem ${verified.verifierId} is not the current verifier`);
1008
- }
1009
- if (!isVerificationReceipt(verified.receipt) || verified.receipt.decision !== "accept") {
1010
- throw new Error("Managed integration requires an accepting verification receipt");
1011
- }
1012
- assertVerifiedReceiptMatches(
1013
- item,
1014
- verifier,
1015
- verified.verifierExecutionPlanId,
1016
- verified.receipt
1017
- );
1018
- verifyManagedIntegration(expected, candidate);
1019
- item.verificationAccepted = true;
1020
- item.acceptanceState = "accepted";
1021
- item.acceptanceReceipt = structuredClone(verified.receipt);
1022
- item.acceptanceReceiptHistory.push(structuredClone(verified.receipt));
1023
- item.artifacts = item.artifacts.map((artifact) => ({ ...artifact, verified: true }));
1024
- item.outcomeReason = void 0;
1025
- item.generation = ++this.generation;
1026
- verifier.acceptedExecutionPlanId = verified.verifierExecutionPlanId;
1027
- verifier.state = "completed";
1028
- verifier.generation = ++this.generation;
1029
- this.refreshReadyState();
1030
- return structuredClone(item);
1031
- }
1032
- rerun(id) {
1033
- const item = this.require(id);
1034
- if (item.acceptanceState === "accepted") {
1035
- throw new Error(`WorkItem ${id} has terminal accepted evidence`);
1036
- }
1037
- if (!["blocked", "needs-input", "failed", "interrupted", "stale", "invalidated"].includes(
1038
- item.state
1039
- )) {
1040
- throw new Error(`WorkItem ${id} cannot rerun while ${item.state}`);
1041
- }
1042
- item.state = "pending";
1043
- item.taskGeneration++;
1044
- item.assignedAgentId = void 0;
1045
- item.acceptedExecutionPlanId = void 0;
1046
- item.outcomeReason = void 0;
1047
- item.verificationAccepted = false;
1048
- item.acceptanceState = item.acceptanceRequired ? "pending" : "not-required";
1049
- item.stagedTreeIdentity = void 0;
1050
- item.submission = void 0;
1051
- item.verificationReceipt = void 0;
1052
- item.acceptanceReceipt = void 0;
1053
- item.generation = ++this.generation;
1054
- this.refreshReadyState();
1055
- return structuredClone(item);
1056
- }
1057
- invalidate(id, reason) {
1058
- const root = this.require(id);
1059
- const normalizedReason = bounded(reason, MAX_TEXT_LENGTH);
1060
- if (!normalizedReason) throw new Error("WorkItem invalidation requires a reason");
1061
- const ordered = [];
1062
- const queue = [root.id];
1063
- const seen = /* @__PURE__ */ new Set();
1064
- while (queue.length > 0) {
1065
- const currentId = queue.shift();
1066
- if (!currentId || seen.has(currentId)) continue;
1067
- seen.add(currentId);
1068
- const item = this.require(currentId);
1069
- if (item.acceptanceState === "accepted") {
1070
- throw new Error(`WorkItem ${item.id} has terminal accepted evidence`);
1071
- }
1072
- ordered.push(item);
1073
- queue.push(...item.dependents);
1074
- }
1075
- return ordered.map((item) => {
1076
- item.state = item.id === root.id ? "stale" : "invalidated";
1077
- if (item.acceptanceRequired) item.acceptanceState = "rejected";
1078
- item.taskGeneration++;
1079
- item.invalidationReasons.push(`${root.id}:${normalizedReason}`);
1080
- item.generation = ++this.generation;
1081
- return structuredClone(item);
1082
- });
1083
- }
1084
- snapshot() {
1085
- return {
1086
- version: WORK_ITEM_LEDGER_VERSION,
1087
- workflowId: this.workflowId,
1088
- generation: this.generation,
1089
- items: [...this.items.values()].sort((left, right) => left.id.localeCompare(right.id)).map((item) => structuredClone(item))
1090
- };
1091
- }
1092
- static restore(snapshot) {
1093
- const storedVersion = snapshot?.version;
1094
- if (!snapshot || storedVersion !== WORK_ITEM_LEDGER_VERSION && !LEGACY_WORK_ITEM_LEDGER_VERSIONS.has(String(storedVersion)) || !Number.isSafeInteger(snapshot.generation) || snapshot.generation < 0) {
1095
- throw new Error("Unsupported or malformed WorkItem ledger snapshot");
1096
- }
1097
- const isLegacySnapshot = storedVersion !== WORK_ITEM_LEDGER_VERSION;
1098
- const isV1Snapshot = storedVersion === "pi-subagents:work-ledger:v1";
1099
- if (!Array.isArray(snapshot.items) || snapshot.items.length < 1 || snapshot.items.length > MAX_ITEMS2) {
1100
- throw new Error("Malformed WorkItem ledger items");
1101
- }
1102
- const storedItems = snapshot.items.map(
1103
- (item) => isLegacySnapshot ? normalizeLegacyAcceptance(item, isV1Snapshot) : item
1104
- );
1105
- for (const item of storedItems) validateStoredRecord(item, snapshot.generation);
1106
- const ledger = _WorkItemLedger.create({
1107
- workflowId: snapshot.workflowId,
1108
- items: storedItems.map((item) => ({
1109
- id: item.id,
1110
- objective: item.objective,
1111
- dependencies: item.dependencies,
1112
- inputArtifacts: item.inputArtifacts,
1113
- inputArtifactVersions: item.requiredArtifactVersions,
1114
- requiredCapabilities: item.requiredCapabilities,
1115
- requiredTools: item.requiredTools,
1116
- selectedAgentName: item.selectedAgentName,
1117
- sideEffectPolicy: item.sideEffectPolicy,
1118
- readPaths: item.readPaths,
1119
- writePaths: item.writePaths,
1120
- ownershipKeys: item.ownershipKeys,
1121
- acceptanceCriteria: item.acceptanceCriteria,
1122
- requiredEvidence: item.requiredEvidence,
1123
- integrationOwner: item.integrationOwner,
1124
- verifierFor: item.verifierFor,
1125
- dependencyPolicy: item.dependencyPolicy,
1126
- acceptanceRequired: item.acceptanceRequired,
1127
- maxReworkCycles: item.maxReworkCycles
1128
- }))
1129
- });
1130
- ledger.generation = snapshot.generation;
1131
- for (const stored of storedItems) {
1132
- const item = ledger.require(stored.id);
1133
- const interruptedAcceptance = stored.acceptanceRequired && stored.state === "completed" && stored.acceptanceState === "pending";
1134
- item.state = stored.state === "running" || stored.state === "awaiting-verification" || interruptedAcceptance ? "interrupted" : stored.state;
1135
- item.generation = stored.generation;
1136
- item.taskGeneration = stored.taskGeneration ?? 1;
1137
- item.assignedAgentId = stored.assignedAgentId;
1138
- item.acceptedExecutionPlanId = stored.acceptedExecutionPlanId;
1139
- item.inputArtifactVersions = { ...stored.inputArtifactVersions };
1140
- item.artifacts = normalizeStoredArtifacts(
1141
- stored.artifacts,
1142
- stored.id,
1143
- stored.generation,
1144
- !isV1Snapshot
1145
- );
1146
- item.artifactHistory = normalizeStoredArtifacts(
1147
- stored.artifactHistory ?? [],
1148
- stored.id,
1149
- stored.generation,
1150
- !isV1Snapshot
1151
- );
1152
- item.acceptanceStateVersion = WORK_ITEM_ACCEPTANCE_VERSION;
1153
- item.acceptanceRequired = stored.acceptanceRequired;
1154
- item.acceptanceState = interruptedAcceptance ? "rejected" : stored.acceptanceState;
1155
- item.reworkCount = stored.reworkCount;
1156
- item.maxReworkCycles = stored.maxReworkCycles;
1157
- item.verificationAccepted = isV1Snapshot ? false : stored.verificationAccepted;
1158
- item.stagedTreeIdentity = stored.stagedTreeIdentity ? structuredClone(stored.stagedTreeIdentity) : void 0;
1159
- item.verificationReceipt = !isV1Snapshot && stored.verificationReceipt ? structuredClone(stored.verificationReceipt) : void 0;
1160
- item.acceptanceReceipt = stored.acceptanceReceipt ? structuredClone(stored.acceptanceReceipt) : void 0;
1161
- item.acceptanceReceiptHistory = stored.acceptanceReceiptHistory.map(
1162
- (receipt) => structuredClone(receipt)
1163
- );
1164
- item.submission = stored.submission ? structuredClone(stored.submission) : void 0;
1165
- item.invalidationReasons = [...stored.invalidationReasons];
1166
- item.outcomeReason = interruptedAcceptance ? "verification-interrupted" : stored.outcomeReason;
1167
- }
1168
- ledger.validateRestoredVerificationLinks();
1169
- return ledger;
1170
- }
1171
- validateRestoredVerificationLinks() {
1172
- for (const target of this.items.values()) {
1173
- const receipt = target.verificationReceipt;
1174
- if (receipt) {
1175
- const verifier2 = this.items.get(receipt.verifierTaskId);
1176
- if (!verifier2 || verifier2.verifierFor !== target.id || verifier2.state !== "completed" || verifier2.taskGeneration !== receipt.verifierTaskGeneration || verifier2.acceptedExecutionPlanId !== receipt.verifierExecutionPlanId) {
1177
- throw new Error(`Malformed stored WorkItem verification link for ${target.id}`);
1178
- }
1179
- }
1180
- const acceptanceReceipt = target.acceptanceReceipt;
1181
- if (!acceptanceReceipt || target.acceptanceState === "pending") continue;
1182
- const verifier = this.items.get(acceptanceReceipt.verifierTaskId);
1183
- if (!verifier || verifier.verifierFor !== target.id || verifier.state !== "completed" || verifier.taskGeneration !== acceptanceReceipt.verifierTaskGeneration || verifier.acceptedExecutionPlanId !== acceptanceReceipt.verifierExecutionPlanId || acceptanceReceipt.targetTaskId !== target.id || acceptanceReceipt.targetTaskGeneration !== target.taskGeneration || acceptanceReceipt.targetExecutionPlanId !== target.acceptedExecutionPlanId) {
1184
- throw new Error(`Malformed stored WorkItem acceptance link for ${target.id}`);
1185
- }
1186
- }
1187
- }
1188
- addDefinition(definition) {
1189
- validateIdentifier(definition.id, "WorkItem id");
1190
- if (this.items.has(definition.id)) throw new Error(`Duplicate WorkItem id ${definition.id}`);
1191
- const objective = bounded(definition.objective, MAX_TEXT_LENGTH);
1192
- if (!objective) throw new Error(`WorkItem ${definition.id} requires an objective`);
1193
- this.items.set(definition.id, {
1194
- id: definition.id,
1195
- objective,
1196
- dependencies: uniqueBounded(definition.dependencies, "dependency"),
1197
- dependents: [],
1198
- state: "pending",
1199
- generation: 0,
1200
- taskGeneration: 1,
1201
- acceptedExecutionPlanId: void 0,
1202
- inputArtifacts: uniqueBounded(definition.inputArtifacts ?? [], "input artifact"),
1203
- inputArtifactVersions: {},
1204
- requiredArtifactVersions: normalizeVersionMap(definition.inputArtifactVersions),
1205
- requiredCapabilities: uniqueBounded(
1206
- definition.requiredCapabilities ?? [],
1207
- "required capability"
1208
- ),
1209
- requiredTools: uniqueBounded(definition.requiredTools ?? [], "required tool"),
1210
- selectedAgentName: definition.selectedAgentName,
1211
- sideEffectPolicy: definition.sideEffectPolicy ?? "mutating",
1212
- artifacts: [],
1213
- artifactHistory: [],
1214
- readPaths: uniqueBounded(definition.readPaths ?? [], "read path"),
1215
- writePaths: uniqueBounded(definition.writePaths ?? [], "write path"),
1216
- ownershipKeys: uniqueBounded(definition.ownershipKeys ?? [], "ownership key"),
1217
- acceptanceCriteria: uniqueBounded(
1218
- definition.acceptanceCriteria ?? [],
1219
- "acceptance criterion"
1220
- ),
1221
- requiredEvidence: uniqueBounded(definition.requiredEvidence ?? [], "required evidence"),
1222
- integrationOwner: definition.integrationOwner === true,
1223
- verifierFor: definition.verifierFor,
1224
- dependencyPolicy: definition.dependencyPolicy ?? "completed",
1225
- acceptanceStateVersion: WORK_ITEM_ACCEPTANCE_VERSION,
1226
- acceptanceRequired: definition.acceptanceRequired === true,
1227
- acceptanceState: definition.acceptanceRequired === true ? "pending" : "not-required",
1228
- reworkCount: 0,
1229
- maxReworkCycles: definition.maxReworkCycles === 0 ? 0 : 1,
1230
- verificationAccepted: false,
1231
- stagedTreeIdentity: void 0,
1232
- verificationReceipt: void 0,
1233
- acceptanceReceipt: void 0,
1234
- acceptanceReceiptHistory: [],
1235
- submission: void 0,
1236
- invalidationReasons: [],
1237
- outcomeReason: void 0
1238
- });
1239
- }
1240
- linkAndValidate() {
1241
- const integrationOwners = [...this.items.values()].filter((item) => item.integrationOwner);
1242
- if (integrationOwners.length > 1)
1243
- throw new Error("Workflow can have only one integration owner");
1244
- for (const item of this.items.values()) {
1245
- if (item.acceptanceRequired && !item.integrationOwner) {
1246
- throw new Error(`WorkItem ${item.id} requires acceptance but is not integration owner`);
1247
- }
1248
- for (const dependency of item.dependencies) {
1249
- if (dependency === item.id) throw new Error(`WorkItem ${item.id} has a self cycle`);
1250
- const parent = this.items.get(dependency);
1251
- if (!parent) throw new Error(`WorkItem ${item.id} has missing dependency ${dependency}`);
1252
- parent.dependents.push(item.id);
1253
- }
1254
- if (item.verifierFor && !this.items.has(item.verifierFor)) {
1255
- throw new Error(`WorkItem ${item.id} verifies missing WorkItem ${item.verifierFor}`);
1256
- }
1257
- if (item.verifierFor && !item.dependencies.includes(item.verifierFor)) {
1258
- throw new Error(
1259
- `WorkItem ${item.id} must depend on the WorkItem it verifies (${item.verifierFor})`
1260
- );
1261
- }
1262
- }
1263
- const visiting = /* @__PURE__ */ new Set();
1264
- const visited = /* @__PURE__ */ new Set();
1265
- const visit = (id) => {
1266
- if (visiting.has(id)) throw new Error(`WorkItem dependency cycle includes ${id}`);
1267
- if (visited.has(id)) return;
1268
- visiting.add(id);
1269
- for (const dependency of this.require(id).dependencies) visit(dependency);
1270
- visiting.delete(id);
1271
- visited.add(id);
1272
- };
1273
- for (const id of this.items.keys()) visit(id);
1274
- }
1275
- refreshReadyState() {
1276
- for (const item of this.items.values()) {
1277
- if (item.state !== "pending") continue;
1278
- const dependencies = item.dependencies.map((id) => this.require(id));
1279
- const acceptedDependency = (dependency) => dependency.state === "completed" && (!dependency.acceptanceRequired || dependency.acceptanceState === "accepted");
1280
- const dependenciesReady = item.verifierFor ? dependencies.every(
1281
- (dependency) => dependency.id === item.verifierFor ? dependency.acceptanceRequired ? dependency.state === "completed" && dependency.acceptanceState === "pending" : dependency.state === "awaiting-verification" : acceptedDependency(dependency)
1282
- ) : item.dependencyPolicy === "settled" ? dependencies.every(
1283
- (dependency) => (!dependency.acceptanceRequired || dependency.acceptanceState === "accepted") && !["pending", "ready", "running", "awaiting-verification"].includes(
1284
- dependency.state
1285
- )
1286
- ) : dependencies.every(acceptedDependency);
1287
- if (!dependenciesReady) continue;
1288
- const available = /* @__PURE__ */ new Map();
1289
- for (const dependency of dependencies) {
1290
- for (const artifact of dependency.artifacts) available.set(artifact.id, artifact);
1291
- }
1292
- if (!item.inputArtifacts.every((artifact) => available.has(artifact))) continue;
1293
- if (!Object.entries(item.requiredArtifactVersions).every(
1294
- ([id, version]) => available.get(id)?.version === version
1295
- )) {
1296
- continue;
1297
- }
1298
- item.inputArtifactVersions = Object.fromEntries(
1299
- item.inputArtifacts.map((id) => [id, available.get(id)?.version ?? "unknown"])
1300
- );
1301
- item.state = "ready";
1302
- item.generation = this.generation;
1303
- }
1304
- }
1305
- resetReworkDependents(targetId, excludedId) {
1306
- const target = this.require(targetId);
1307
- const reworkReason = `${targetId}:verification-rework`;
1308
- const queue = target.dependents.filter((id) => id !== excludedId);
1309
- const seen = /* @__PURE__ */ new Set();
1310
- while (queue.length > 0) {
1311
- const currentId = queue.shift();
1312
- if (!currentId || seen.has(currentId)) continue;
1313
- seen.add(currentId);
1314
- const current = this.require(currentId);
1315
- queue.push(...current.dependents.filter((id) => id !== excludedId));
1316
- if (current.state !== "invalidated" || current.invalidationReasons.at(-1) !== reworkReason) {
1317
- continue;
1318
- }
1319
- current.artifactHistory.push(
1320
- ...current.artifacts.map((artifact) => structuredClone(artifact))
1321
- );
1322
- current.artifacts = [];
1323
- current.inputArtifactVersions = {};
1324
- current.state = "pending";
1325
- current.assignedAgentId = void 0;
1326
- current.acceptedExecutionPlanId = void 0;
1327
- current.outcomeReason = void 0;
1328
- current.verificationAccepted = false;
1329
- current.acceptanceState = current.acceptanceRequired ? "pending" : "not-required";
1330
- current.stagedTreeIdentity = void 0;
1331
- current.submission = void 0;
1332
- current.verificationReceipt = void 0;
1333
- current.acceptanceReceipt = void 0;
1334
- current.generation = ++this.generation;
1335
- }
1336
- }
1337
- invalidateDependents(targetId, excludedId, reason) {
1338
- const target = this.require(targetId);
1339
- const normalizedReason = bounded(reason ?? "verification-not-accepted", MAX_TEXT_LENGTH);
1340
- const queue = target.dependents.filter((id) => id !== excludedId);
1341
- const seen = /* @__PURE__ */ new Set();
1342
- const affected = [];
1343
- while (queue.length > 0) {
1344
- const currentId = queue.shift();
1345
- if (!currentId || seen.has(currentId)) continue;
1346
- seen.add(currentId);
1347
- const current = this.require(currentId);
1348
- current.state = "invalidated";
1349
- current.taskGeneration++;
1350
- current.invalidationReasons.push(`${targetId}:${normalizedReason}`);
1351
- current.generation = ++this.generation;
1352
- affected.push(structuredClone(current));
1353
- queue.push(...current.dependents.filter((id) => id !== excludedId));
1354
- }
1355
- return affected;
1356
- }
1357
- require(id) {
1358
- const item = this.items.get(id);
1359
- if (!item) throw new Error(`Unknown WorkItem ${id}`);
1360
- return item;
1361
- }
1362
- assertMutable(item) {
1363
- if (TERMINAL_STATES.has(item.state) && !(item.state === "completed" && item.acceptanceState === "pending")) {
1364
- throw new Error(`WorkItem ${item.id} is terminal (${item.state})`);
1365
- }
1366
- }
1367
- };
1368
- function assertReceiptMatches(target, verifier, verifierExecutionPlanId, receipt) {
1369
- if (receipt.targetTaskId !== target.id || receipt.targetTaskGeneration !== target.taskGeneration || receipt.targetExecutionPlanId !== target.acceptedExecutionPlanId || receipt.verifierTaskId !== verifier.id || receipt.verifierTaskGeneration !== verifier.taskGeneration || receipt.verifierExecutionPlanId !== verifierExecutionPlanId || !target.stagedTreeIdentity || !sameWorkflowTreeIdentity(receipt.treeIdentity, target.stagedTreeIdentity)) {
1370
- throw new Error("WorkItem verification receipt has stale or mismatched executor identity");
1371
- }
1372
- }
1373
- function assertVerifiedReceiptMatches(target, verifier, verifierExecutionPlanId, receipt) {
1374
- if (!target.acceptanceRequired || target.acceptanceState !== "pending" || target.state !== "completed" || !target.submission || receipt.targetTaskId !== target.id || receipt.targetTaskGeneration !== target.taskGeneration || receipt.targetExecutionPlanId !== target.acceptedExecutionPlanId || receipt.verifierTaskId !== verifier.id || receipt.verifierTaskGeneration !== verifier.taskGeneration || receipt.verifierExecutionPlanId !== verifierExecutionPlanId || receipt.verifierAgent !== verifier.assignedAgentId?.replace(/^agent:/u, "") || !sameWorkflowTreeIdentity(receipt.beforeTreeIdentity, target.submission.treeIdentity) || !sameWorkflowTreeIdentity(receipt.afterTreeIdentity, target.submission.treeIdentity) || receipt.baseRepositoryGeneration !== target.submission.baseRepositoryGeneration || receipt.patchDigest !== target.submission.patchDigest || JSON.stringify(receipt.changedPaths) !== JSON.stringify(target.submission.changedPaths) || JSON.stringify(receipt.allowedScopes) !== JSON.stringify(target.writePaths) || JSON.stringify(receipt.dependencyVersions) !== JSON.stringify(target.inputArtifactVersions) || JSON.stringify(receipt.readSetVersions) !== JSON.stringify(target.submission.fileVersions) || JSON.stringify(receipt.acceptanceCriteria) !== JSON.stringify(target.acceptanceCriteria) || JSON.stringify(receipt.requiredEvidenceIds) !== JSON.stringify(target.requiredEvidence)) {
1375
- throw new Error("WorkItem verification receipt has stale or mismatched managed identity");
1376
- }
1377
- }
1378
- function validatePlanId(value, label) {
1379
- if (!/^[a-f0-9]{64}$/u.test(value)) throw new Error(`Invalid ${label}`);
1380
- }
1381
- function validateSubmission(value) {
1382
- if (!isWorkflowTreeIdentity(value.treeIdentity) || !/^[a-f0-9]{40,64}$/u.test(value.baseRepositoryGeneration) || !/^[a-f0-9]{64}$/u.test(value.patchDigest) || !Array.isArray(value.changedPaths) || value.changedPaths.length > MAX_LIST_ITEMS2 || value.changedPaths.some(
1383
- (item) => typeof item !== "string" || !item || item.length > 4096 || item.startsWith("/") || item.startsWith("\\") || item.split(/[\\/]/u).includes("..")
1384
- ) || new Set(value.changedPaths).size !== value.changedPaths.length || value.changedPaths.reduce((total, item) => total + Buffer.byteLength(item, "utf8"), 0) > 8 * 1024 || JSON.stringify([...value.changedPaths].sort((left, right) => left.localeCompare(right))) !== JSON.stringify(value.changedPaths) || !value.fileVersions || typeof value.fileVersions !== "object" || Array.isArray(value.fileVersions) || Object.entries(value.fileVersions).length > MAX_LIST_ITEMS2 || JSON.stringify(
1385
- Object.keys(value.fileVersions).sort((left, right) => left.localeCompare(right))
1386
- ) !== JSON.stringify(value.changedPaths) || Object.entries(value.fileVersions).some(
1387
- ([key, digest]) => !key || key.length > 4096 || typeof digest !== "string" || digest !== "deleted" && !/^[a-f0-9]{64}$/u.test(digest)
1388
- )) {
1389
- throw new Error("WorkItem received malformed verification submission metadata");
1390
- }
1391
- }
1392
- function validSubmission(value) {
1393
- try {
1394
- validateSubmission(value);
1395
- return true;
1396
- } catch {
1397
- return false;
1398
- }
1399
- }
1400
- function normalizeLegacyAcceptance(item, isV1) {
1401
- return {
1402
- ...structuredClone(item),
1403
- requiredEvidence: [],
1404
- acceptanceStateVersion: WORK_ITEM_ACCEPTANCE_VERSION,
1405
- acceptanceRequired: false,
1406
- acceptanceState: "not-required",
1407
- reworkCount: 0,
1408
- maxReworkCycles: 1,
1409
- verificationAccepted: isV1 ? false : item.verificationAccepted,
1410
- acceptanceReceipt: void 0,
1411
- acceptanceReceiptHistory: [],
1412
- submission: void 0
1413
- };
1414
- }
1415
- function validateStoredRecord(item, ledgerGeneration) {
1416
- const states = [
1417
- "pending",
1418
- "ready",
1419
- "running",
1420
- "awaiting-verification",
1421
- "blocked",
1422
- "needs-input",
1423
- "completed",
1424
- "failed",
1425
- "interrupted",
1426
- "stale",
1427
- "invalidated"
1428
- ];
1429
- if (!item || typeof item !== "object" || typeof item.objective !== "string" || item.objective.length === 0 || item.objective.length > MAX_TEXT_LENGTH || item.objective.trim() !== item.objective || !states.includes(item.state) || !Number.isSafeInteger(item.generation) || item.generation < 0 || item.generation > ledgerGeneration || !Number.isSafeInteger(item.taskGeneration) || item.taskGeneration < 1 || !Array.isArray(item.artifacts) || !validStoredArtifacts(item.artifacts, item.id, item.generation) || item.artifactHistory !== void 0 && !Array.isArray(item.artifactHistory) || item.artifactHistory !== void 0 && !validStoredArtifacts(item.artifactHistory, item.id, item.generation) || !item.inputArtifactVersions || typeof item.inputArtifactVersions !== "object" || Array.isArray(item.inputArtifactVersions) || item.assignedAgentId !== void 0 && !isValidIdentifier(item.assignedAgentId) || item.selectedAgentName !== void 0 && (typeof item.selectedAgentName !== "string" || item.selectedAgentName.length === 0 || item.selectedAgentName.length > MAX_IDENTIFIER_LENGTH || item.selectedAgentName.trim() !== item.selectedAgentName) || item.acceptanceStateVersion !== WORK_ITEM_ACCEPTANCE_VERSION || typeof item.acceptanceRequired !== "boolean" || !["not-required", "pending", "accepted", "rework-requested", "rejected"].includes(
1430
- item.acceptanceState
1431
- ) || !Number.isSafeInteger(item.reworkCount) || item.reworkCount < 0 || item.reworkCount > 1 || item.maxReworkCycles !== 0 && item.maxReworkCycles !== 1 || item.acceptanceRequired && !item.integrationOwner || !item.acceptanceRequired && item.acceptanceState !== "not-required" || typeof item.integrationOwner !== "boolean" || !["completed", "settled"].includes(item.dependencyPolicy) || !["read-only", "idempotent", "mutating"].includes(item.sideEffectPolicy) || item.verifierFor !== void 0 && !isValidIdentifier(item.verifierFor) || ![
1432
- item.dependencies,
1433
- item.dependents,
1434
- item.inputArtifacts,
1435
- item.requiredCapabilities,
1436
- item.requiredTools,
1437
- item.readPaths,
1438
- item.writePaths,
1439
- item.ownershipKeys,
1440
- item.acceptanceCriteria,
1441
- item.requiredEvidence
1442
- ].every(
1443
- (values) => Array.isArray(values) && values.every(
1444
- (value) => typeof value === "string" && value.length > 0 && value.length <= MAX_TEXT_LENGTH && value.trim() === value
1445
- )
1446
- ) || !item.requiredArtifactVersions || typeof item.requiredArtifactVersions !== "object" || Array.isArray(item.requiredArtifactVersions) || !Object.entries(item.requiredArtifactVersions).every(
1447
- ([id, version]) => isValidIdentifier(id) && typeof version === "string" && version.length > 0 && version.length <= MAX_IDENTIFIER_LENGTH && version.trim() === version
1448
- ) || item.acceptedExecutionPlanId !== void 0 && (typeof item.acceptedExecutionPlanId !== "string" || !/^[a-f0-9]{64}$/u.test(item.acceptedExecutionPlanId)) || !Object.entries(item.inputArtifactVersions).every(
1449
- ([id, value]) => isValidIdentifier(id) && typeof value === "string" && value.length > 0 && value.length <= MAX_IDENTIFIER_LENGTH && value.trim() === value
1450
- ) || !Array.isArray(item.invalidationReasons) || !item.invalidationReasons.every(
1451
- (reason) => typeof reason === "string" && reason.length > 0 && reason.length <= MAX_TEXT_LENGTH && reason.trim() === reason
1452
- ) || item.outcomeReason !== void 0 && (typeof item.outcomeReason !== "string" || item.outcomeReason.length > MAX_TEXT_LENGTH || item.outcomeReason.trim() !== item.outcomeReason) || typeof item.verificationAccepted !== "boolean" || item.stagedTreeIdentity !== void 0 && !isWorkflowTreeIdentity(item.stagedTreeIdentity) || item.verificationReceipt !== void 0 && (!isWorkflowVerificationReceipt(item.verificationReceipt) || !storedVerificationMatchesItem(item, item.verificationReceipt)) || item.acceptanceReceipt !== void 0 && (!isVerificationReceipt(item.acceptanceReceipt) || item.acceptanceState !== "pending" && !storedAcceptanceMatchesItem(item, item.acceptanceReceipt)) || !Array.isArray(item.acceptanceReceiptHistory) || item.acceptanceReceiptHistory.length > 2 || !item.acceptanceReceiptHistory.every(isVerificationReceipt) || item.acceptanceReceipt !== void 0 && JSON.stringify(item.acceptanceReceiptHistory.at(-1)) !== JSON.stringify(item.acceptanceReceipt) || item.reworkCount !== Math.min(
1453
- item.maxReworkCycles,
1454
- item.acceptanceReceiptHistory.filter((receipt) => receipt.decision === "rework").length
1455
- ) || item.submission !== void 0 && !validSubmission(item.submission) || item.acceptanceRequired && item.state === "completed" && item.acceptanceState === "pending" && (!item.submission || !item.acceptedExecutionPlanId) || item.acceptanceState === "accepted" && (item.acceptanceReceipt?.decision !== "accept" || !item.verificationAccepted) || item.acceptanceState === "rejected" && (!["failed", "interrupted", "stale", "invalidated", "blocked", "needs-input"].includes(
1456
- item.state
1457
- ) || item.acceptanceReceipt !== void 0 && item.acceptanceReceipt.decision !== "reject" && item.acceptanceReceipt.decision !== "rework") || item.acceptanceState === "rework-requested" && (item.state !== "blocked" || item.acceptanceReceipt?.decision !== "rework") || item.state === "awaiting-verification" && (!item.stagedTreeIdentity || !item.acceptedExecutionPlanId) || item.stagedTreeIdentity !== void 0 && item.state === "completed" && !item.acceptanceRequired && item.verificationReceipt === void 0) {
1458
- throw new Error(`Malformed stored WorkItem ${String(item?.id ?? "unknown")}`);
1459
- }
1460
- }
1461
- function storedAcceptanceMatchesItem(item, receipt) {
1462
- return item.acceptanceRequired && item.submission !== void 0 && receipt.targetTaskId === item.id && receipt.targetTaskGeneration === item.taskGeneration && receipt.targetExecutionPlanId === item.acceptedExecutionPlanId && sameWorkflowTreeIdentity(receipt.beforeTreeIdentity, item.submission.treeIdentity) && sameWorkflowTreeIdentity(receipt.afterTreeIdentity, item.submission.treeIdentity) && receipt.baseRepositoryGeneration === item.submission.baseRepositoryGeneration && receipt.patchDigest === item.submission.patchDigest && JSON.stringify(receipt.changedPaths) === JSON.stringify(item.submission.changedPaths) && JSON.stringify(receipt.allowedScopes) === JSON.stringify(item.writePaths) && JSON.stringify(receipt.dependencyVersions) === JSON.stringify(item.inputArtifactVersions) && JSON.stringify(receipt.readSetVersions) === JSON.stringify(item.submission.fileVersions) && JSON.stringify(receipt.acceptanceCriteria) === JSON.stringify(item.acceptanceCriteria) && JSON.stringify(receipt.requiredEvidenceIds) === JSON.stringify(item.requiredEvidence);
1463
- }
1464
- function storedVerificationMatchesItem(item, receipt) {
1465
- return !item.verifierFor && receipt.targetTaskId === item.id && receipt.targetTaskGeneration === item.taskGeneration && receipt.targetExecutionPlanId === item.acceptedExecutionPlanId && item.stagedTreeIdentity !== void 0 && sameWorkflowTreeIdentity(receipt.treeIdentity, item.stagedTreeIdentity) && item.verificationAccepted === (receipt.decision === "accept") && (receipt.decision === "accept" ? item.state === "completed" : receipt.decision === "rework" ? item.state === "blocked" : item.state === "failed");
1466
- }
1467
- function validStoredArtifacts(values, producerTaskId, itemGeneration) {
1468
- const seen = /* @__PURE__ */ new Set();
1469
- return values.every(
1470
- (artifact) => artifact !== null && typeof artifact === "object" && Object.keys(artifact).every(
1471
- (key) => ["id", "kind", "version", "digest", "producerTaskId", "generation", "verified"].includes(
1472
- key
1473
- )
1474
- ) && isValidIdentifier(artifact.id) && claimUnique(artifact.id, seen) && typeof artifact.kind === "string" && artifact.kind.length > 0 && artifact.kind.length <= MAX_IDENTIFIER_LENGTH && artifact.kind.trim() === artifact.kind && typeof artifact.version === "string" && artifact.version.length > 0 && artifact.version.length <= MAX_IDENTIFIER_LENGTH && artifact.version.trim() === artifact.version && (artifact.digest === void 0 || typeof artifact.digest === "string" && artifact.digest.length > 0 && artifact.digest.length <= MAX_TEXT_LENGTH && artifact.digest.trim() === artifact.digest) && artifact.producerTaskId === producerTaskId && Number.isSafeInteger(artifact.generation) && Number(artifact.generation) >= 0 && Number(artifact.generation) <= itemGeneration && typeof artifact.verified === "boolean"
1475
- );
1476
- }
1477
- function claimUnique(value, seen) {
1478
- if (seen.has(value)) return false;
1479
- seen.add(value);
1480
- return true;
1481
- }
1482
- function normalizeStoredArtifacts(values, defaultProducerTaskId, defaultGeneration, preserveVerification) {
1483
- if (!validStoredArtifacts(values, defaultProducerTaskId, defaultGeneration)) {
1484
- throw new Error(`Malformed stored artifacts for WorkItem ${defaultProducerTaskId}`);
1485
- }
1486
- return values.map((value) => ({
1487
- ...structuredClone(value),
1488
- verified: preserveVerification && value.verified
1489
- }));
1490
- }
1491
- function normalizeArtifacts(values, producerTaskId, generation) {
1492
- if (values.length > MAX_LIST_ITEMS2) throw new Error("Too many WorkItem artifacts");
1493
- const seen = /* @__PURE__ */ new Set();
1494
- return values.map((value) => {
1495
- validateIdentifier(value.id, "artifact id");
1496
- if (seen.has(value.id)) throw new Error(`Duplicate artifact id ${value.id}`);
1497
- seen.add(value.id);
1498
- const kind = bounded(value.kind, MAX_IDENTIFIER_LENGTH);
1499
- const version = bounded(value.version, MAX_IDENTIFIER_LENGTH);
1500
- if (!kind || !version) throw new Error(`Artifact ${value.id} requires kind and version`);
1501
- return {
1502
- id: value.id,
1503
- kind,
1504
- version,
1505
- ...value.digest ? { digest: bounded(value.digest, MAX_TEXT_LENGTH) } : {},
1506
- producerTaskId,
1507
- generation,
1508
- verified: false
1509
- };
1510
- });
1511
- }
1512
- function normalizeVersionMap(value) {
1513
- if (value === void 0) return {};
1514
- const entries = Object.entries(value);
1515
- if (entries.length > MAX_LIST_ITEMS2) throw new Error("Too many artifact version requirements");
1516
- return Object.fromEntries(
1517
- entries.map(([id, version]) => {
1518
- validateIdentifier(id, "artifact version id");
1519
- const normalized = bounded(version, MAX_IDENTIFIER_LENGTH);
1520
- if (!normalized) throw new Error(`Artifact ${id} requires a version`);
1521
- return [id, normalized];
1522
- })
1523
- );
1524
- }
1525
- function uniqueBounded(values, label) {
1526
- if (!Array.isArray(values) || values.length > MAX_LIST_ITEMS2) {
1527
- throw new Error(`Too many WorkItem ${label} values`);
1528
- }
1529
- const result = [];
1530
- const seen = /* @__PURE__ */ new Set();
1531
- for (const value of values) {
1532
- if (typeof value !== "string") throw new Error(`Invalid WorkItem ${label}`);
1533
- const normalized = bounded(value, MAX_TEXT_LENGTH);
1534
- if (!normalized) throw new Error(`Empty WorkItem ${label}`);
1535
- if (!seen.has(normalized)) result.push(normalized);
1536
- seen.add(normalized);
1537
- }
1538
- return result;
1539
- }
1540
- function isValidIdentifier(value) {
1541
- return typeof value === "string" && value.length >= 1 && value.length <= MAX_IDENTIFIER_LENGTH && /^[A-Za-z0-9][A-Za-z0-9._:-]*$/u.test(value);
1542
- }
1543
- function validateIdentifier(value, label) {
1544
- if (!isValidIdentifier(value)) {
1545
- throw new Error(`Invalid ${label}`);
1546
- }
1547
- }
1548
- function bounded(value, maxLength) {
1549
- return value.trim().slice(0, maxLength);
1550
- }
1551
-
1552
- // src/work-item-persistence.ts
1553
- var WORKFLOW_STATE_DIRECTORY = "pi-subagents-workflows";
1554
- var DEFAULT_MAX_STORED_WORKFLOWS = 64;
1555
- var DEFAULT_RETENTION_MS = 30 * 24 * 60 * 60 * 1e3;
1556
- var MAX_WORKFLOW_STATE_BYTES = 1024 * 1024;
1557
- var WorkItemPersistence = class {
1558
- constructor(filePath, afterSave) {
1559
- this.filePath = filePath;
1560
- this.afterSave = afterSave;
1561
- }
1562
- filePath;
1563
- afterSave;
1564
- async save(snapshot) {
1565
- const filePath = path3.resolve(this.filePath);
1566
- const sanitized = sanitizeWorkflowSnapshot(snapshot);
1567
- const content = `${JSON.stringify(sanitized)}
1568
- `;
1569
- if (Buffer.byteLength(content, "utf8") > MAX_WORKFLOW_STATE_BYTES) {
1570
- throw new Error("WorkItem workflow state exceeds the persistence size limit");
1571
- }
1572
- await withFileMutationQueue(filePath, async () => {
1573
- await fs2.promises.mkdir(path3.dirname(filePath), { recursive: true, mode: 448 });
1574
- const temporary = `${filePath}.${process.pid}.${Date.now()}.tmp`;
1575
- try {
1576
- await fs2.promises.writeFile(temporary, content, { mode: 384 });
1577
- await fs2.promises.rename(temporary, filePath);
1578
- } finally {
1579
- await fs2.promises.rm(temporary, { force: true });
1580
- }
1581
- });
1582
- await this.afterSave?.();
1583
- }
1584
- load() {
1585
- const filePath = path3.resolve(this.filePath);
1586
- let source;
1587
- try {
1588
- const stat = fs2.statSync(filePath);
1589
- if (stat.size > MAX_WORKFLOW_STATE_BYTES)
1590
- throw new Error("workflow state exceeds size limit");
1591
- source = fs2.readFileSync(filePath, "utf8");
1592
- } catch (error) {
1593
- if (error.code === "ENOENT") return void 0;
1594
- throw error;
1595
- }
1596
- try {
1597
- return WorkItemLedger.restore(JSON.parse(source));
1598
- } catch {
1599
- const quarantine = `${filePath}.invalid-${Date.now()}`;
1600
- try {
1601
- fs2.renameSync(filePath, quarantine);
1602
- } catch {
1603
- }
1604
- return void 0;
1605
- }
1606
- }
1607
- };
1608
- function createSessionWorkItemPersistence(owner, workflowId, options = {}) {
1609
- const maxStoredWorkflows = options.maxStoredWorkflows ?? DEFAULT_MAX_STORED_WORKFLOWS;
1610
- const retentionMs = options.retentionMs ?? DEFAULT_RETENTION_MS;
1611
- if (!Number.isSafeInteger(maxStoredWorkflows) || maxStoredWorkflows < 1) {
1612
- throw new Error("maxStoredWorkflows must be a positive safe integer");
1613
- }
1614
- if (!Number.isFinite(retentionMs) || retentionMs <= 0) {
1615
- throw new Error("workflow retentionMs must be a positive finite number");
1616
- }
1617
- const stateDir = resolveStateDirectory(options.stateDir);
1618
- const prefix = sessionPrefix(owner);
1619
- const filePath = path3.join(stateDir, `${prefix}-${stableId(workflowId)}.json`);
1620
- return new WorkItemPersistence(
1621
- filePath,
1622
- () => pruneSessionWorkflows(stateDir, prefix, maxStoredWorkflows, retentionMs)
1623
- );
1624
- }
1625
- function inspectSessionWorkflows(owner, options = {}) {
1626
- const stateDir = resolveStateDirectory(options.stateDir);
1627
- const prefix = `${sessionPrefix(owner)}-`;
1628
- const limit = options.maxStoredWorkflows ?? DEFAULT_MAX_STORED_WORKFLOWS;
1629
- if (!Number.isSafeInteger(limit) || limit < 1) {
1630
- throw new Error("maxStoredWorkflows must be a positive safe integer");
1631
- }
1632
- let entries;
1633
- try {
1634
- entries = fs2.readdirSync(stateDir, { withFileTypes: true });
1635
- } catch (error) {
1636
- if (error.code === "ENOENT") {
1637
- return { workflows: [], invalid: 0, omitted: 0 };
1638
- }
1639
- throw error;
1640
- }
1641
- const candidates = entries.filter(
1642
- (entry) => entry.isFile() && entry.name.startsWith(prefix) && entry.name.endsWith(".json")
1643
- ).map((entry) => {
1644
- const filePath = path3.join(stateDir, entry.name);
1645
- return { filePath, modifiedAt: safeModifiedAt(filePath) };
1646
- }).sort((left, right) => right.modifiedAt - left.modifiedAt);
1647
- const workflows = [];
1648
- let invalid = 0;
1649
- for (const candidate of candidates.slice(0, limit)) {
1650
- try {
1651
- const stat = fs2.statSync(candidate.filePath);
1652
- if (stat.size > MAX_WORKFLOW_STATE_BYTES)
1653
- throw new Error("workflow state exceeds size limit");
1654
- const source = fs2.readFileSync(candidate.filePath, "utf8");
1655
- workflows.push(
1656
- WorkItemLedger.restore(JSON.parse(source)).snapshot()
1657
- );
1658
- } catch {
1659
- invalid++;
1660
- }
1661
- }
1662
- return { workflows, invalid, omitted: Math.max(0, candidates.length - limit) };
1663
- }
1664
- function safeModifiedAt(filePath) {
1665
- try {
1666
- return fs2.statSync(filePath).mtimeMs;
1667
- } catch {
1668
- return 0;
1669
- }
1670
- }
1671
- function resolveStateDirectory(stateDir) {
1672
- return path3.resolve(stateDir ?? path3.join(getAgentDir(), WORKFLOW_STATE_DIRECTORY));
1673
- }
1674
- function sessionPrefix(owner) {
1675
- return stableId(`session:${owner}`);
1676
- }
1677
- function stableId(value) {
1678
- return createHash2("sha256").update(value).digest("hex").slice(0, 24);
1679
- }
1680
- async function pruneSessionWorkflows(stateDir, prefix, maxStoredWorkflows, retentionMs) {
1681
- await withFileMutationQueue(path3.join(stateDir, `${prefix}.prune`), async () => {
1682
- const cutoff = Date.now() - retentionMs;
1683
- const entries = (await fs2.promises.readdir(stateDir, { withFileTypes: true })).filter(
1684
- (entry) => entry.isFile() && entry.name.startsWith(`${prefix}-`) && entry.name.endsWith(".json")
1685
- ).map((entry) => path3.join(stateDir, entry.name));
1686
- const records = await Promise.all(
1687
- entries.map(async (filePath) => ({
1688
- filePath,
1689
- modifiedAt: (await fs2.promises.stat(filePath)).mtimeMs
1690
- }))
1691
- );
1692
- records.sort((left, right) => right.modifiedAt - left.modifiedAt);
1693
- await Promise.all(
1694
- records.filter((record, index) => index >= maxStoredWorkflows || record.modifiedAt < cutoff).map((record) => fs2.promises.rm(record.filePath, { force: true }))
1695
- );
1696
- });
1697
- }
1698
- function sanitizeWorkflowSnapshot(snapshot) {
1699
- const sanitized = structuredClone(snapshot);
1700
- for (const item of sanitized.items) {
1701
- item.objective = redact(item.objective);
1702
- item.selectedAgentName = item.selectedAgentName ? redact(item.selectedAgentName) : void 0;
1703
- item.requiredCapabilities = item.requiredCapabilities.map(redact);
1704
- item.requiredTools = item.requiredTools.map(redact);
1705
- item.readPaths = item.readPaths.map(redact);
1706
- item.writePaths = item.writePaths.map(redact);
1707
- item.ownershipKeys = item.ownershipKeys.map(redact);
1708
- item.acceptanceCriteria = item.acceptanceCriteria.map(redact);
1709
- item.requiredEvidence = item.requiredEvidence.map(redact);
1710
- item.invalidationReasons = item.invalidationReasons.map(redact);
1711
- item.outcomeReason = item.outcomeReason ? redact(item.outcomeReason) : void 0;
1712
- if (item.verificationReceipt) {
1713
- item.verificationReceipt.summary = redact(item.verificationReceipt.summary);
1714
- item.verificationReceipt.evidence = item.verificationReceipt.evidence.map(redact);
1715
- item.verificationReceipt.limitations = item.verificationReceipt.limitations.map(redact);
1716
- }
1717
- for (const receipt of [
1718
- ...item.acceptanceReceiptHistory,
1719
- ...item.acceptanceReceipt ? [item.acceptanceReceipt] : []
1720
- ]) {
1721
- receipt.summary = redact(receipt.summary);
1722
- receipt.findings = receipt.findings.map(redact);
1723
- receipt.changedPaths = receipt.changedPaths.map(redact);
1724
- receipt.allowedScopes = receipt.allowedScopes.map(redact);
1725
- receipt.acceptanceCriteria = receipt.acceptanceCriteria.map(redact);
1726
- receipt.requiredEvidenceIds = receipt.requiredEvidenceIds.map(redact);
1727
- receipt.dependencyVersions = redactRecord(receipt.dependencyVersions);
1728
- receipt.readSetVersions = redactRecord(receipt.readSetVersions);
1729
- receipt.evidence = redactRecord(receipt.evidence);
1730
- for (const check of receipt.checks) {
1731
- check.stdout = redact(check.stdout);
1732
- check.stderr = redact(check.stderr);
1733
- }
1734
- }
1735
- if (item.submission) {
1736
- item.submission.changedPaths = item.submission.changedPaths.map(redact);
1737
- item.submission.fileVersions = Object.fromEntries(
1738
- Object.entries(item.submission.fileVersions).map(([key, value]) => [redact(key), value])
1739
- );
1740
- }
1741
- for (const artifact of [...item.artifacts, ...item.artifactHistory]) {
1742
- artifact.kind = redact(artifact.kind);
1743
- artifact.version = redact(artifact.version);
1744
- artifact.digest = artifact.digest ? redact(artifact.digest) : void 0;
1745
- }
1746
- }
1747
- WorkItemLedger.restore(sanitized);
1748
- return sanitized;
1749
- }
1750
- function redactRecord(value) {
1751
- return Object.fromEntries(
1752
- Object.entries(value).map(([key, item]) => [redact(key), redact(item)])
1753
- );
1754
- }
1755
- function redact(value) {
1756
- return redactPrivateText(value).trim();
1757
- }
1758
-
1759
- export {
1760
- captureWorkflowTreeIdentity,
1761
- sameWorkflowTreeIdentity,
1762
- createVerificationReceipt,
1763
- createWorkflowVerificationReceipt,
1764
- workflowVerificationInstruction,
1765
- WorkItemLedger,
1766
- createSessionWorkItemPersistence,
1767
- inspectSessionWorkflows
1768
- };
1769
- //# sourceMappingURL=chunk-OVPHFGKO.ts.map