open-multi-agent-kit 0.98.4 → 0.98.5

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 (252) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +3 -2
  3. package/dist/commands/run-command.d.ts +2 -1
  4. package/dist/commands/run-command.d.ts.map +1 -1
  5. package/dist/commands/run-command.js +9 -1
  6. package/dist/commands/run-command.js.map +1 -1
  7. package/dist/commands/verified-run-cli.d.ts +6 -0
  8. package/dist/commands/verified-run-cli.d.ts.map +1 -0
  9. package/dist/commands/verified-run-cli.js +190 -0
  10. package/dist/commands/verified-run-cli.js.map +1 -0
  11. package/dist/core/agent-session-services.d.ts +8 -1
  12. package/dist/core/agent-session-services.d.ts.map +1 -1
  13. package/dist/core/agent-session-services.js +41 -0
  14. package/dist/core/agent-session-services.js.map +1 -1
  15. package/dist/core/agent-session.d.ts +7 -8
  16. package/dist/core/agent-session.d.ts.map +1 -1
  17. package/dist/core/agent-session.js +61 -41
  18. package/dist/core/agent-session.js.map +1 -1
  19. package/dist/core/prompt-settlement.d.ts +4 -3
  20. package/dist/core/prompt-settlement.d.ts.map +1 -1
  21. package/dist/core/prompt-settlement.js.map +1 -1
  22. package/dist/core/run-budget-policy.d.ts +18 -0
  23. package/dist/core/run-budget-policy.d.ts.map +1 -0
  24. package/dist/core/run-budget-policy.js +52 -0
  25. package/dist/core/run-budget-policy.js.map +1 -0
  26. package/dist/core/run-budget.d.ts +33 -0
  27. package/dist/core/run-budget.d.ts.map +1 -0
  28. package/dist/core/run-budget.js +89 -0
  29. package/dist/core/run-budget.js.map +1 -0
  30. package/dist/core/run-execution-api.d.ts +15 -0
  31. package/dist/core/run-execution-api.d.ts.map +1 -0
  32. package/dist/core/run-execution-api.js +7 -0
  33. package/dist/core/run-execution-api.js.map +1 -0
  34. package/dist/core/run-journal.d.ts.map +1 -1
  35. package/dist/core/run-journal.js +30 -208
  36. package/dist/core/run-journal.js.map +1 -1
  37. package/dist/core/session-bash-service.d.ts +2 -2
  38. package/dist/core/session-bash-service.d.ts.map +1 -1
  39. package/dist/core/session-bash-service.js +21 -9
  40. package/dist/core/session-bash-service.js.map +1 -1
  41. package/dist/core/session-failure-cause.d.ts.map +1 -1
  42. package/dist/core/session-failure-cause.js +5 -0
  43. package/dist/core/session-failure-cause.js.map +1 -1
  44. package/dist/core/session-prompt-lifecycle.d.ts +25 -0
  45. package/dist/core/session-prompt-lifecycle.d.ts.map +1 -0
  46. package/dist/core/session-prompt-lifecycle.js +87 -0
  47. package/dist/core/session-prompt-lifecycle.js.map +1 -0
  48. package/dist/core/session-run-budget.d.ts +28 -0
  49. package/dist/core/session-run-budget.d.ts.map +1 -0
  50. package/dist/core/session-run-budget.js +127 -0
  51. package/dist/core/session-run-budget.js.map +1 -0
  52. package/dist/core/session-run-termination.d.ts.map +1 -1
  53. package/dist/core/session-run-termination.js +14 -3
  54. package/dist/core/session-run-termination.js.map +1 -1
  55. package/dist/core/session-termination-types.d.ts +97 -0
  56. package/dist/core/session-termination-types.d.ts.map +1 -0
  57. package/dist/core/session-termination-types.js +26 -0
  58. package/dist/core/session-termination-types.js.map +1 -0
  59. package/dist/core/session-termination.d.ts +3 -97
  60. package/dist/core/session-termination.d.ts.map +1 -1
  61. package/dist/core/session-termination.js +24 -28
  62. package/dist/core/session-termination.js.map +1 -1
  63. package/dist/core/slash-commands.d.ts.map +1 -1
  64. package/dist/core/slash-commands.js +1 -0
  65. package/dist/core/slash-commands.js.map +1 -1
  66. package/dist/core/subagent-lane-launcher.d.ts +3 -2
  67. package/dist/core/subagent-lane-launcher.d.ts.map +1 -1
  68. package/dist/core/subagent-lane-launcher.js +24 -13
  69. package/dist/core/subagent-lane-launcher.js.map +1 -1
  70. package/dist/core/verified-run/broker.d.ts +26 -0
  71. package/dist/core/verified-run/broker.d.ts.map +1 -0
  72. package/dist/core/verified-run/broker.js +210 -0
  73. package/dist/core/verified-run/broker.js.map +1 -0
  74. package/dist/core/verified-run/candidate.d.ts +24 -0
  75. package/dist/core/verified-run/candidate.d.ts.map +1 -0
  76. package/dist/core/verified-run/candidate.js +167 -0
  77. package/dist/core/verified-run/candidate.js.map +1 -0
  78. package/dist/core/verified-run/check-receipt.d.ts +18 -0
  79. package/dist/core/verified-run/check-receipt.d.ts.map +1 -0
  80. package/dist/core/verified-run/check-receipt.js +92 -0
  81. package/dist/core/verified-run/check-receipt.js.map +1 -0
  82. package/dist/core/verified-run/coordinator.d.ts +39 -0
  83. package/dist/core/verified-run/coordinator.d.ts.map +1 -0
  84. package/dist/core/verified-run/coordinator.js +190 -0
  85. package/dist/core/verified-run/coordinator.js.map +1 -0
  86. package/dist/core/verified-run/dag-candidates.d.ts +8 -0
  87. package/dist/core/verified-run/dag-candidates.d.ts.map +1 -0
  88. package/dist/core/verified-run/dag-candidates.js +65 -0
  89. package/dist/core/verified-run/dag-candidates.js.map +1 -0
  90. package/dist/core/verified-run/dag-phase.d.ts +7 -0
  91. package/dist/core/verified-run/dag-phase.d.ts.map +1 -0
  92. package/dist/core/verified-run/dag-phase.js +92 -0
  93. package/dist/core/verified-run/dag-phase.js.map +1 -0
  94. package/dist/core/verified-run/dag-projection.d.ts +7 -0
  95. package/dist/core/verified-run/dag-projection.d.ts.map +1 -0
  96. package/dist/core/verified-run/dag-projection.js +90 -0
  97. package/dist/core/verified-run/dag-projection.js.map +1 -0
  98. package/dist/core/verified-run/dag-recovery.d.ts +13 -0
  99. package/dist/core/verified-run/dag-recovery.d.ts.map +1 -0
  100. package/dist/core/verified-run/dag-recovery.js +98 -0
  101. package/dist/core/verified-run/dag-recovery.js.map +1 -0
  102. package/dist/core/verified-run/dag-retry-projection.d.ts +9 -0
  103. package/dist/core/verified-run/dag-retry-projection.d.ts.map +1 -0
  104. package/dist/core/verified-run/dag-retry-projection.js +43 -0
  105. package/dist/core/verified-run/dag-retry-projection.js.map +1 -0
  106. package/dist/core/verified-run/dag-types.d.ts +47 -0
  107. package/dist/core/verified-run/dag-types.d.ts.map +1 -0
  108. package/dist/core/verified-run/dag-types.js +2 -0
  109. package/dist/core/verified-run/dag-types.js.map +1 -0
  110. package/dist/core/verified-run/event-parser.d.ts +3 -0
  111. package/dist/core/verified-run/event-parser.d.ts.map +1 -0
  112. package/dist/core/verified-run/event-parser.js +153 -0
  113. package/dist/core/verified-run/event-parser.js.map +1 -0
  114. package/dist/core/verified-run/events.d.ts +4 -0
  115. package/dist/core/verified-run/events.d.ts.map +1 -0
  116. package/dist/core/verified-run/events.js +3 -0
  117. package/dist/core/verified-run/events.js.map +1 -0
  118. package/dist/core/verified-run/evidence-binding.d.ts +18 -0
  119. package/dist/core/verified-run/evidence-binding.d.ts.map +1 -0
  120. package/dist/core/verified-run/evidence-binding.js +81 -0
  121. package/dist/core/verified-run/evidence-binding.js.map +1 -0
  122. package/dist/core/verified-run/evidence.d.ts +27 -0
  123. package/dist/core/verified-run/evidence.d.ts.map +1 -0
  124. package/dist/core/verified-run/evidence.js +100 -0
  125. package/dist/core/verified-run/evidence.js.map +1 -0
  126. package/dist/core/verified-run/journal.d.ts +32 -0
  127. package/dist/core/verified-run/journal.d.ts.map +1 -0
  128. package/dist/core/verified-run/journal.js +103 -0
  129. package/dist/core/verified-run/journal.js.map +1 -0
  130. package/dist/core/verified-run/namespace-identity.d.ts +11 -0
  131. package/dist/core/verified-run/namespace-identity.d.ts.map +1 -0
  132. package/dist/core/verified-run/namespace-identity.js +77 -0
  133. package/dist/core/verified-run/namespace-identity.js.map +1 -0
  134. package/dist/core/verified-run/owned-execution.d.ts +21 -0
  135. package/dist/core/verified-run/owned-execution.d.ts.map +1 -0
  136. package/dist/core/verified-run/owned-execution.js +43 -0
  137. package/dist/core/verified-run/owned-execution.js.map +1 -0
  138. package/dist/core/verified-run/phase-context.d.ts +9 -0
  139. package/dist/core/verified-run/phase-context.d.ts.map +1 -0
  140. package/dist/core/verified-run/phase-context.js +2 -0
  141. package/dist/core/verified-run/phase-context.js.map +1 -0
  142. package/dist/core/verified-run/process-gate.d.ts +5 -0
  143. package/dist/core/verified-run/process-gate.d.ts.map +1 -0
  144. package/dist/core/verified-run/process-gate.js +31 -0
  145. package/dist/core/verified-run/process-gate.js.map +1 -0
  146. package/dist/core/verified-run/projection.d.ts +4 -0
  147. package/dist/core/verified-run/projection.d.ts.map +1 -0
  148. package/dist/core/verified-run/projection.js +219 -0
  149. package/dist/core/verified-run/projection.js.map +1 -0
  150. package/dist/core/verified-run/recovery-clock.d.ts +19 -0
  151. package/dist/core/verified-run/recovery-clock.d.ts.map +1 -0
  152. package/dist/core/verified-run/recovery-clock.js +69 -0
  153. package/dist/core/verified-run/recovery-clock.js.map +1 -0
  154. package/dist/core/verified-run/recovery-command.d.ts +11 -0
  155. package/dist/core/verified-run/recovery-command.d.ts.map +1 -0
  156. package/dist/core/verified-run/recovery-command.js +73 -0
  157. package/dist/core/verified-run/recovery-command.js.map +1 -0
  158. package/dist/core/verified-run/recovery-projection.d.ts +12 -0
  159. package/dist/core/verified-run/recovery-projection.d.ts.map +1 -0
  160. package/dist/core/verified-run/recovery-projection.js +88 -0
  161. package/dist/core/verified-run/recovery-projection.js.map +1 -0
  162. package/dist/core/verified-run/recovery.d.ts +12 -0
  163. package/dist/core/verified-run/recovery.d.ts.map +1 -0
  164. package/dist/core/verified-run/recovery.js +115 -0
  165. package/dist/core/verified-run/recovery.js.map +1 -0
  166. package/dist/core/verified-run/run-types.d.ts +103 -0
  167. package/dist/core/verified-run/run-types.d.ts.map +1 -0
  168. package/dist/core/verified-run/run-types.js +2 -0
  169. package/dist/core/verified-run/run-types.js.map +1 -0
  170. package/dist/core/verified-run/scripted-writer.d.ts +15 -0
  171. package/dist/core/verified-run/scripted-writer.d.ts.map +1 -0
  172. package/dist/core/verified-run/scripted-writer.js +94 -0
  173. package/dist/core/verified-run/scripted-writer.js.map +1 -0
  174. package/dist/core/verified-run/session-port.d.ts +27 -0
  175. package/dist/core/verified-run/session-port.d.ts.map +1 -0
  176. package/dist/core/verified-run/session-port.js +2 -0
  177. package/dist/core/verified-run/session-port.js.map +1 -0
  178. package/dist/core/verified-run/storage.d.ts +15 -0
  179. package/dist/core/verified-run/storage.d.ts.map +1 -0
  180. package/dist/core/verified-run/storage.js +96 -0
  181. package/dist/core/verified-run/storage.js.map +1 -0
  182. package/dist/core/verified-run/verification-phase.d.ts +5 -0
  183. package/dist/core/verified-run/verification-phase.d.ts.map +1 -0
  184. package/dist/core/verified-run/verification-phase.js +56 -0
  185. package/dist/core/verified-run/verification-phase.js.map +1 -0
  186. package/dist/core/verified-run/work-recovery.d.ts +8 -0
  187. package/dist/core/verified-run/work-recovery.d.ts.map +1 -0
  188. package/dist/core/verified-run/work-recovery.js +44 -0
  189. package/dist/core/verified-run/work-recovery.js.map +1 -0
  190. package/dist/core/verified-run/writer-completion.d.ts +4 -0
  191. package/dist/core/verified-run/writer-completion.d.ts.map +1 -0
  192. package/dist/core/verified-run/writer-completion.js +27 -0
  193. package/dist/core/verified-run/writer-completion.js.map +1 -0
  194. package/dist/core/verified-run/writer-phase.d.ts +8 -0
  195. package/dist/core/verified-run/writer-phase.d.ts.map +1 -0
  196. package/dist/core/verified-run/writer-phase.js +76 -0
  197. package/dist/core/verified-run/writer-phase.js.map +1 -0
  198. package/dist/core/verified-run/writer-projection.d.ts +11 -0
  199. package/dist/core/verified-run/writer-projection.d.ts.map +1 -0
  200. package/dist/core/verified-run/writer-projection.js +70 -0
  201. package/dist/core/verified-run/writer-projection.js.map +1 -0
  202. package/dist/core/verified-run/writer-recovery.d.ts +16 -0
  203. package/dist/core/verified-run/writer-recovery.d.ts.map +1 -0
  204. package/dist/core/verified-run/writer-recovery.js +107 -0
  205. package/dist/core/verified-run/writer-recovery.js.map +1 -0
  206. package/dist/core/workload-permit-pool.d.ts +1 -3
  207. package/dist/core/workload-permit-pool.d.ts.map +1 -1
  208. package/dist/core/workload-permit-pool.js +11 -11
  209. package/dist/core/workload-permit-pool.js.map +1 -1
  210. package/dist/index.d.ts +3 -2
  211. package/dist/index.d.ts.map +1 -1
  212. package/dist/index.js +2 -2
  213. package/dist/index.js.map +1 -1
  214. package/dist/main.d.ts.map +1 -1
  215. package/dist/main.js +2 -8
  216. package/dist/main.js.map +1 -1
  217. package/dist/modes/interactive/components/session-failure.d.ts +13 -0
  218. package/dist/modes/interactive/components/session-failure.d.ts.map +1 -0
  219. package/dist/modes/interactive/components/session-failure.js +81 -0
  220. package/dist/modes/interactive/components/session-failure.js.map +1 -0
  221. package/dist/modes/interactive/interactive-mode.d.ts +1 -0
  222. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  223. package/dist/modes/interactive/interactive-mode.js +45 -31
  224. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  225. package/dist/modes/interactive/tui-diagnostics.d.ts +36 -0
  226. package/dist/modes/interactive/tui-diagnostics.d.ts.map +1 -0
  227. package/dist/modes/interactive/tui-diagnostics.js +105 -0
  228. package/dist/modes/interactive/tui-diagnostics.js.map +1 -0
  229. package/dist/modes/interactive/tui-runtime-info.d.ts +20 -0
  230. package/dist/modes/interactive/tui-runtime-info.d.ts.map +1 -0
  231. package/dist/modes/interactive/tui-runtime-info.js +76 -0
  232. package/dist/modes/interactive/tui-runtime-info.js.map +1 -0
  233. package/docs/development.md +10 -0
  234. package/docs/keybindings.md +1 -1
  235. package/docs/release-audit-0.98.5.md +84 -0
  236. package/docs/run-protocol.md +33 -1
  237. package/docs/runtime-algorithms.md +26 -0
  238. package/docs/sdk.md +193 -0
  239. package/docs/usage.md +54 -0
  240. package/docs/verified-run-testing.md +417 -0
  241. package/docs/verified-run.md +388 -0
  242. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  243. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  244. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  245. package/examples/extensions/gondolin/package-lock.json +2 -2
  246. package/examples/extensions/gondolin/package.json +1 -1
  247. package/examples/extensions/sandbox/package-lock.json +2 -2
  248. package/examples/extensions/sandbox/package.json +1 -1
  249. package/examples/extensions/with-deps/package-lock.json +2 -2
  250. package/examples/extensions/with-deps/package.json +1 -1
  251. package/npm-shrinkwrap.json +18 -18
  252. package/package.json +6 -6
@@ -0,0 +1,210 @@
1
+ import { spawn, spawnSync } from "node:child_process";
2
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
3
+ import { release } from "node:os";
4
+ import { performance } from "node:perf_hooks";
5
+ import { identityFromSandboxInfo, PROCESS_GATE_ARGV } from "./process-gate.js";
6
+ import { digestBytes, digestObject, VerifiedRunError } from "./storage.js";
7
+ const BWRAP = "/usr/bin/bwrap";
8
+ const SYSTEM_ARGS = [
9
+ "--unshare-all",
10
+ "--die-with-parent",
11
+ "--new-session",
12
+ "--cap-drop",
13
+ "ALL",
14
+ "--clearenv",
15
+ "--ro-bind",
16
+ "/usr",
17
+ "/usr",
18
+ "--symlink",
19
+ "usr/bin",
20
+ "/bin",
21
+ "--symlink",
22
+ "usr/lib",
23
+ "/lib",
24
+ "--symlink",
25
+ "usr/lib64",
26
+ "/lib64",
27
+ "--proc",
28
+ "/proc",
29
+ "--dev",
30
+ "/dev",
31
+ "--tmpfs",
32
+ "/tmp",
33
+ "--setenv",
34
+ "PATH",
35
+ "/usr/bin:/bin",
36
+ "--setenv",
37
+ "LANG",
38
+ "C.UTF-8",
39
+ ];
40
+ export function commandEnvironmentDigest(contract, driver = "legacy") {
41
+ if (process.platform !== "linux" || !existsSync(BWRAP))
42
+ throw new VerifiedRunError("unsupported");
43
+ let writers;
44
+ switch (contract.profile) {
45
+ case "linux-command-v1":
46
+ writers = [contract.writer];
47
+ break;
48
+ case "linux-scripted-agent-v1":
49
+ writers = contract.writer.steps;
50
+ break;
51
+ case "linux-command-dag-v1":
52
+ writers = contract.writer.tasks.flatMap((task) => task.attempts);
53
+ break;
54
+ default: {
55
+ const exhaustive = contract;
56
+ throw new VerifiedRunError(String(exhaustive));
57
+ }
58
+ }
59
+ const binaries = [
60
+ ...new Set([
61
+ BWRAP,
62
+ ...writers.map((argv) => argv[0]),
63
+ ...contract.checks.map((check) => check.argv[0]),
64
+ ...(driver === "gated-v1" ? [PROCESS_GATE_ARGV[0]] : []),
65
+ ]),
66
+ ];
67
+ const materials = binaries.map((binary) => {
68
+ if (!binary || (!binary.startsWith("/usr/bin/") && !binary.startsWith("/bin/")))
69
+ throw new VerifiedRunError("unsupported_executable");
70
+ const path = realpathSync(binary);
71
+ if (!path.startsWith("/usr/"))
72
+ throw new VerifiedRunError("unsupported_executable");
73
+ return { path, digest: digestBytes(readFileSync(path)) };
74
+ });
75
+ return digestObject({
76
+ profile: contract.profile,
77
+ platform: process.platform,
78
+ architecture: process.arch,
79
+ kernel: release(),
80
+ sandbox: SYSTEM_ARGS,
81
+ ...(driver === "gated-v1" ? { gate: PROCESS_GATE_ARGV, infoFd: 3 } : {}),
82
+ binaries: materials,
83
+ });
84
+ }
85
+ export function probeVerifiedSandbox() {
86
+ if (process.platform !== "linux" || !existsSync(BWRAP))
87
+ throw new VerifiedRunError("unsupported");
88
+ const probe = spawnSync(BWRAP, [...SYSTEM_ARGS, "--", "/bin/true"], {
89
+ env: {},
90
+ timeout: 3000,
91
+ maxBuffer: 4096,
92
+ stdio: ["ignore", "pipe", "pipe"],
93
+ });
94
+ if (probe.error || probe.status !== 0)
95
+ throw new VerifiedRunError("unsupported");
96
+ }
97
+ /** The only process dispatch port; close means the PID namespace and its inherited pipes have drained. */
98
+ export async function executeSandbox(request) {
99
+ if (request.signal?.aborted)
100
+ throw new VerifiedRunError("cancelled");
101
+ if (request.timeoutMs <= 0)
102
+ throw new VerifiedRunError("deadline");
103
+ const started = performance.now();
104
+ const startedAt = new Date().toISOString();
105
+ const argv = [
106
+ ...SYSTEM_ARGS,
107
+ request.writable ? "--bind" : "--ro-bind",
108
+ request.workspace,
109
+ "/workspace",
110
+ "--chdir",
111
+ "/workspace",
112
+ ...(request.onReady ? ["--info-fd", "3", "--", ...PROCESS_GATE_ARGV] : ["--"]),
113
+ ...request.argv,
114
+ ];
115
+ return new Promise((resolve, reject) => {
116
+ const child = request.onReady
117
+ ? spawn(BWRAP, argv, { env: {}, stdio: ["pipe", "pipe", "pipe", "pipe"] })
118
+ : spawn(BWRAP, argv, { env: {}, stdio: ["ignore", "pipe", "pipe"] });
119
+ let gateFailed = false;
120
+ let gateError;
121
+ const stdout = [];
122
+ const stderr = [];
123
+ let size = 0;
124
+ let failure = null;
125
+ let cleanup;
126
+ let finished = false;
127
+ const stop = (reason) => {
128
+ if (finished || failure)
129
+ return;
130
+ failure = reason;
131
+ child.kill("SIGKILL");
132
+ cleanup = setTimeout(() => reject(new VerifiedRunError("unsettled")), request.cleanupMs);
133
+ };
134
+ const deadline = setTimeout(() => stop("deadline"), request.timeoutMs);
135
+ const abort = () => stop("cancelled");
136
+ request.signal?.addEventListener("abort", abort, { once: true });
137
+ if (request.signal?.aborted)
138
+ abort();
139
+ const collect = (target, chunk) => {
140
+ if (failure)
141
+ return;
142
+ size += chunk.length;
143
+ if (size > request.maxOutputBytes) {
144
+ stop("output_limit");
145
+ return;
146
+ }
147
+ target.push(chunk);
148
+ };
149
+ child.stdout?.on("data", (chunk) => collect(stdout, chunk));
150
+ child.stderr?.on("data", (chunk) => collect(stderr, chunk));
151
+ if (request.onReady) {
152
+ const info = child.stdio[3];
153
+ let metadata = "";
154
+ if (!info || !child.stdin) {
155
+ gateFailed = true;
156
+ gateError = new VerifiedRunError("process_identity");
157
+ stop("process_identity");
158
+ }
159
+ else {
160
+ child.stdin.on("error", () => stop("execution_failed"));
161
+ info.on("data", (chunk) => {
162
+ metadata += chunk.toString("utf8");
163
+ if (metadata.length > 4096)
164
+ stop("process_identity");
165
+ });
166
+ info.once("end", async () => {
167
+ if (finished || failure)
168
+ return;
169
+ try {
170
+ await request.onReady?.(identityFromSandboxInfo(metadata));
171
+ if (performance.now() - started >= request.timeoutMs || request.signal?.aborted)
172
+ stop(request.signal?.aborted ? "cancelled" : "deadline");
173
+ if (!finished && !failure)
174
+ child.stdin?.end("go\n");
175
+ }
176
+ catch (error) {
177
+ gateFailed = true;
178
+ gateError = error;
179
+ stop("process_identity");
180
+ }
181
+ });
182
+ }
183
+ }
184
+ child.once("error", () => {
185
+ failure = "execution_failed";
186
+ });
187
+ child.once("close", (exitCode) => {
188
+ finished = true;
189
+ clearTimeout(deadline);
190
+ clearTimeout(cleanup);
191
+ request.signal?.removeEventListener("abort", abort);
192
+ if (gateFailed) {
193
+ reject(gateError);
194
+ return;
195
+ }
196
+ const durationMs = Math.max(0, Math.round(performance.now() - started));
197
+ resolve({
198
+ stdout: Buffer.concat(stdout),
199
+ stderr: Buffer.concat(stderr),
200
+ exitCode,
201
+ failure: failure ?? (exitCode === 0 ? null : "execution_failed"),
202
+ startedAt,
203
+ // Project the finish instant from the start's wall reference and monotonic elapsed time.
204
+ finishedAt: new Date(Date.parse(startedAt) + durationMs).toISOString(),
205
+ durationMs,
206
+ });
207
+ });
208
+ });
209
+ }
210
+ //# sourceMappingURL=broker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"broker.js","sourceRoot":"","sources":["../../../src/core/verified-run/broker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACjE,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAG9C,OAAO,EAAE,uBAAuB,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAC/E,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAE3E,MAAM,KAAK,GAAG,gBAAgB,CAAC;AAC/B,MAAM,WAAW,GAAG;IACnB,eAAe;IACf,mBAAmB;IACnB,eAAe;IACf,YAAY;IACZ,KAAK;IACL,YAAY;IACZ,WAAW;IACX,MAAM;IACN,MAAM;IACN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C,OAAO,CAAC,CAAC;YACtB,OAAO,CAAC,MAAM,EAAE,mBAAmB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;YACpD,IAAI,UAAU,EAAE,CAAC;gBAChB,MAAM,CAAC,SAAS,CAAC,CAAC;gBAClB,OAAO;YACR,CAAC;YACD,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,OAAO,CAAC,CAAC,CAAC;YACxE,OAAO,CAAC;gBACP,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC;gBAC7B,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC;gBAC7B,QAAQ;gBACR,OAAO,EAAE,OAAO,IAAI,CAAC,QAAQ,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,kBAAkB,CAAC;gBAChE,SAAS;gBACT,yFAAyF;gBACzF,UAAU,EAAE,IAAI,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,GAAG,UAAU,CAAC,CAAC,WAAW,EAAE;gBACtE,UAAU;aACV,CAAC,CAAC;QAAA,CACH,CAAC,CAAC;IAAA,CACH,CAAC,CAAC;AAAA,CACH","sourcesContent":["import { spawn, spawnSync } from \"node:child_process\";\nimport { existsSync, readFileSync, realpathSync } from \"node:fs\";\nimport { release } from \"node:os\";\nimport { performance } from \"node:perf_hooks\";\nimport type { RunContract } from \"omk-protocol\";\nimport type { NamespaceIdentity } from \"./namespace-identity.ts\";\nimport { identityFromSandboxInfo, PROCESS_GATE_ARGV } from \"./process-gate.ts\";\nimport { digestBytes, digestObject, VerifiedRunError } from \"./storage.ts\";\n\nconst BWRAP = \"/usr/bin/bwrap\";\nconst SYSTEM_ARGS = [\n\t\"--unshare-all\",\n\t\"--die-with-parent\",\n\t\"--new-session\",\n\t\"--cap-drop\",\n\t\"ALL\",\n\t\"--clearenv\",\n\t\"--ro-bind\",\n\t\"/usr\",\n\t\"/usr\",\n\t\"--symlink\",\n\t\"usr/bin\",\n\t\"/bin\",\n\t\"--symlink\",\n\t\"usr/lib\",\n\t\"/lib\",\n\t\"--symlink\",\n\t\"usr/lib64\",\n\t\"/lib64\",\n\t\"--proc\",\n\t\"/proc\",\n\t\"--dev\",\n\t\"/dev\",\n\t\"--tmpfs\",\n\t\"/tmp\",\n\t\"--setenv\",\n\t\"PATH\",\n\t\"/usr/bin:/bin\",\n\t\"--setenv\",\n\t\"LANG\",\n\t\"C.UTF-8\",\n] as const;\n\nexport interface SandboxExecution {\n\treadonly workspace: string;\n\treadonly argv: readonly string[];\n\treadonly writable: boolean;\n\treadonly timeoutMs: number;\n\treadonly cleanupMs: number;\n\treadonly maxOutputBytes: number;\n\treadonly signal?: AbortSignal;\n\treadonly onReady?: (identity: NamespaceIdentity) => void | Promise<void>;\n}\nexport interface SandboxOutcome {\n\treadonly stdout: Buffer;\n\treadonly stderr: Buffer;\n\treadonly exitCode: number | null;\n\treadonly failure: string | null;\n\treadonly startedAt: string;\n\treadonly finishedAt: string;\n\treadonly durationMs: number;\n}\n\nexport function commandEnvironmentDigest(contract: RunContract, driver: \"legacy\" | \"gated-v1\" = \"legacy\"): string {\n\tif (process.platform !== \"linux\" || !existsSync(BWRAP)) throw new VerifiedRunError(\"unsupported\");\n\tlet writers: readonly (readonly string[])[];\n\tswitch (contract.profile) {\n\t\tcase \"linux-command-v1\":\n\t\t\twriters = [contract.writer];\n\t\t\tbreak;\n\t\tcase \"linux-scripted-agent-v1\":\n\t\t\twriters = contract.writer.steps;\n\t\t\tbreak;\n\t\tcase \"linux-command-dag-v1\":\n\t\t\twriters = contract.writer.tasks.flatMap((task) => task.attempts);\n\t\t\tbreak;\n\t\tdefault: {\n\t\t\tconst exhaustive: never = contract;\n\t\t\tthrow new VerifiedRunError(String(exhaustive));\n\t\t}\n\t}\n\tconst binaries = [\n\t\t...new Set([\n\t\t\tBWRAP,\n\t\t\t...writers.map((argv) => argv[0]),\n\t\t\t...contract.checks.map((check) => check.argv[0]),\n\t\t\t...(driver === \"gated-v1\" ? [PROCESS_GATE_ARGV[0]] : []),\n\t\t]),\n\t];\n\tconst materials = binaries.map((binary) => {\n\t\tif (!binary || (!binary.startsWith(\"/usr/bin/\") && !binary.startsWith(\"/bin/\")))\n\t\t\tthrow new VerifiedRunError(\"unsupported_executable\");\n\t\tconst path = realpathSync(binary);\n\t\tif (!path.startsWith(\"/usr/\")) throw new VerifiedRunError(\"unsupported_executable\");\n\t\treturn { path, digest: digestBytes(readFileSync(path)) };\n\t});\n\treturn digestObject({\n\t\tprofile: contract.profile,\n\t\tplatform: process.platform,\n\t\tarchitecture: process.arch,\n\t\tkernel: release(),\n\t\tsandbox: SYSTEM_ARGS,\n\t\t...(driver === \"gated-v1\" ? { gate: PROCESS_GATE_ARGV, infoFd: 3 } : {}),\n\t\tbinaries: materials,\n\t});\n}\n\nexport function probeVerifiedSandbox(): void {\n\tif (process.platform !== \"linux\" || !existsSync(BWRAP)) throw new VerifiedRunError(\"unsupported\");\n\tconst probe = spawnSync(BWRAP, [...SYSTEM_ARGS, \"--\", \"/bin/true\"], {\n\t\tenv: {},\n\t\ttimeout: 3000,\n\t\tmaxBuffer: 4096,\n\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t});\n\tif (probe.error || probe.status !== 0) throw new VerifiedRunError(\"unsupported\");\n}\n\n/** The only process dispatch port; close means the PID namespace and its inherited pipes have drained. */\nexport async function executeSandbox(request: SandboxExecution): Promise<SandboxOutcome> {\n\tif (request.signal?.aborted) throw new VerifiedRunError(\"cancelled\");\n\tif (request.timeoutMs <= 0) throw new VerifiedRunError(\"deadline\");\n\tconst started = performance.now();\n\tconst startedAt = new Date().toISOString();\n\tconst argv = [\n\t\t...SYSTEM_ARGS,\n\t\trequest.writable ? \"--bind\" : \"--ro-bind\",\n\t\trequest.workspace,\n\t\t\"/workspace\",\n\t\t\"--chdir\",\n\t\t\"/workspace\",\n\t\t...(request.onReady ? [\"--info-fd\", \"3\", \"--\", ...PROCESS_GATE_ARGV] : [\"--\"]),\n\t\t...request.argv,\n\t];\n\treturn new Promise((resolve, reject) => {\n\t\tconst child = request.onReady\n\t\t\t? spawn(BWRAP, argv, { env: {}, stdio: [\"pipe\", \"pipe\", \"pipe\", \"pipe\"] })\n\t\t\t: spawn(BWRAP, argv, { env: {}, stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n\t\tlet gateFailed = false;\n\t\tlet gateError: unknown;\n\t\tconst stdout: Buffer[] = [];\n\t\tconst stderr: Buffer[] = [];\n\t\tlet size = 0;\n\t\tlet failure: string | null = null;\n\t\tlet cleanup: ReturnType<typeof setTimeout> | undefined;\n\t\tlet finished = false;\n\t\tconst stop = (reason: string): void => {\n\t\t\tif (finished || failure) return;\n\t\t\tfailure = reason;\n\t\t\tchild.kill(\"SIGKILL\");\n\t\t\tcleanup = setTimeout(() => reject(new VerifiedRunError(\"unsettled\")), request.cleanupMs);\n\t\t};\n\t\tconst deadline = setTimeout(() => stop(\"deadline\"), request.timeoutMs);\n\t\tconst abort = (): void => stop(\"cancelled\");\n\t\trequest.signal?.addEventListener(\"abort\", abort, { once: true });\n\t\tif (request.signal?.aborted) abort();\n\t\tconst collect = (target: Buffer[], chunk: Buffer): void => {\n\t\t\tif (failure) return;\n\t\t\tsize += chunk.length;\n\t\t\tif (size > request.maxOutputBytes) {\n\t\t\t\tstop(\"output_limit\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\ttarget.push(chunk);\n\t\t};\n\t\tchild.stdout?.on(\"data\", (chunk: Buffer) => collect(stdout, chunk));\n\t\tchild.stderr?.on(\"data\", (chunk: Buffer) => collect(stderr, chunk));\n\t\tif (request.onReady) {\n\t\t\tconst info = child.stdio[3];\n\t\t\tlet metadata = \"\";\n\t\t\tif (!info || !child.stdin) {\n\t\t\t\tgateFailed = true;\n\t\t\t\tgateError = new VerifiedRunError(\"process_identity\");\n\t\t\t\tstop(\"process_identity\");\n\t\t\t} else {\n\t\t\t\tchild.stdin.on(\"error\", () => stop(\"execution_failed\"));\n\t\t\t\tinfo.on(\"data\", (chunk: Buffer) => {\n\t\t\t\t\tmetadata += chunk.toString(\"utf8\");\n\t\t\t\t\tif (metadata.length > 4096) stop(\"process_identity\");\n\t\t\t\t});\n\t\t\t\tinfo.once(\"end\", async () => {\n\t\t\t\t\tif (finished || failure) return;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait request.onReady?.(identityFromSandboxInfo(metadata));\n\t\t\t\t\t\tif (performance.now() - started >= request.timeoutMs || request.signal?.aborted)\n\t\t\t\t\t\t\tstop(request.signal?.aborted ? \"cancelled\" : \"deadline\");\n\t\t\t\t\t\tif (!finished && !failure) child.stdin?.end(\"go\\n\");\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tgateFailed = true;\n\t\t\t\t\t\tgateError = error;\n\t\t\t\t\t\tstop(\"process_identity\");\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tchild.once(\"error\", () => {\n\t\t\tfailure = \"execution_failed\";\n\t\t});\n\t\tchild.once(\"close\", (exitCode) => {\n\t\t\tfinished = true;\n\t\t\tclearTimeout(deadline);\n\t\t\tclearTimeout(cleanup);\n\t\t\trequest.signal?.removeEventListener(\"abort\", abort);\n\t\t\tif (gateFailed) {\n\t\t\t\treject(gateError);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst durationMs = Math.max(0, Math.round(performance.now() - started));\n\t\t\tresolve({\n\t\t\t\tstdout: Buffer.concat(stdout),\n\t\t\t\tstderr: Buffer.concat(stderr),\n\t\t\t\texitCode,\n\t\t\t\tfailure: failure ?? (exitCode === 0 ? null : \"execution_failed\"),\n\t\t\t\tstartedAt,\n\t\t\t\t// Project the finish instant from the start's wall reference and monotonic elapsed time.\n\t\t\t\tfinishedAt: new Date(Date.parse(startedAt) + durationMs).toISOString(),\n\t\t\t\tdurationMs,\n\t\t\t});\n\t\t});\n\t});\n}\n"]}
@@ -0,0 +1,24 @@
1
+ import type { RunPhaseBudget } from "omk-protocol";
2
+ export interface CandidateFile {
3
+ readonly path: string;
4
+ readonly mode: number;
5
+ readonly digest: string;
6
+ readonly size: number;
7
+ }
8
+ export interface CandidateManifest {
9
+ readonly version: 1;
10
+ readonly directories: readonly string[];
11
+ readonly files: readonly CandidateFile[];
12
+ }
13
+ export interface CandidateSnapshot {
14
+ readonly manifest: CandidateManifest;
15
+ readonly digest: string;
16
+ readonly contents: ReadonlyMap<string, Buffer>;
17
+ }
18
+ /** Entire regular-file tree, including dot/untracked files; .git/.omk metadata is excluded by this profile. */
19
+ export declare function captureCandidate(root: string, limits: RunPhaseBudget): CandidateSnapshot;
20
+ export declare function materializeCandidate(snapshot: CandidateSnapshot, target: string): void;
21
+ export declare function assertCandidateScope(base: CandidateManifest, candidate: CandidateManifest, writable: readonly string[]): void;
22
+ export declare function storeCandidate(snapshot: CandidateSnapshot, runPath: string): void;
23
+ export declare function loadCandidate(runPath: string, digest: string, limits: RunPhaseBudget): CandidateSnapshot;
24
+ //# sourceMappingURL=candidate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"candidate.d.ts","sourceRoot":"","sources":["../../../src/core/verified-run/candidate.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAYnD,MAAM,WAAW,aAAa;IAC7B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;CACtB;AACD,MAAM,WAAW,iBAAiB;IACjC,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAC;IACpB,QAAQ,CAAC,WAAW,EAAE,SAAS,MAAM,EAAE,CAAC;IACxC,QAAQ,CAAC,KAAK,EAAE,SAAS,aAAa,EAAE,CAAC;CACzC;AACD,MAAM,WAAW,iBAAiB;IACjC,QAAQ,CAAC,QAAQ,EAAE,iBAAiB,CAAC;IACrC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,QAAQ,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAC/C;AAYD,+GAA+G;AAC/G,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,cAAc,GAAG,iBAAiB,CAsCxF;AAED,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,iBAAiB,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,CAStF;AAED,wBAAgB,oBAAoB,CACnC,IAAI,EAAE,iBAAiB,EACvB,SAAS,EAAE,iBAAiB,EAC5B,QAAQ,EAAE,SAAS,MAAM,EAAE,GACzB,IAAI,CAWN;AAED,wBAAgB,cAAc,CAAC,QAAQ,EAAE,iBAAiB,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI,CAGjF;AAED,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,cAAc,GAAG,iBAAiB,CAyExG","sourcesContent":["import { chmodSync, lstatSync, mkdirSync, readdirSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { RunPhaseBudget } from \"omk-protocol\";\nimport {\n\tassertDirectory,\n\tdigestBytes,\n\tdigestObject,\n\tpublishBytes,\n\tpublishObject,\n\treadJson,\n\treadRegularFile,\n\tVerifiedRunError,\n} from \"./storage.ts\";\n\nexport interface CandidateFile {\n\treadonly path: string;\n\treadonly mode: number;\n\treadonly digest: string;\n\treadonly size: number;\n}\nexport interface CandidateManifest {\n\treadonly version: 1;\n\treadonly directories: readonly string[];\n\treadonly files: readonly CandidateFile[];\n}\nexport interface CandidateSnapshot {\n\treadonly manifest: CandidateManifest;\n\treadonly digest: string;\n\treadonly contents: ReadonlyMap<string, Buffer>;\n}\n\nfunction safePath(path: string): void {\n\tif (\n\t\t!path ||\n\t\t/[\\\\\\u0000-\\u001f\\u007f]/.test(path) ||\n\t\tpath.split(\"/\").some((part) => [\"\", \".\", \"..\", \".git\", \".omk\"].includes(part))\n\t) {\n\t\tthrow new VerifiedRunError(\"file_type\");\n\t}\n}\n\n/** Entire regular-file tree, including dot/untracked files; .git/.omk metadata is excluded by this profile. */\nexport function captureCandidate(root: string, limits: RunPhaseBudget): CandidateSnapshot {\n\tassertDirectory(root);\n\tconst files: CandidateFile[] = [];\n\tconst directories: string[] = [];\n\tconst contents = new Map<string, Buffer>();\n\tlet bytesUsed = 0;\n\tconst visit = (prefix: string): void => {\n\t\tconst names = readdirSync(join(root, prefix), { encoding: \"buffer\" })\n\t\t\t.map((name) => new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(name))\n\t\t\t.sort();\n\t\tfor (const name of names) {\n\t\t\tif (!prefix && (name === \".git\" || name === \".omk\")) continue;\n\t\t\tconst path = prefix ? `${prefix}/${name}` : name;\n\t\t\tsafePath(path);\n\t\t\tif (files.length + directories.length >= limits.maxFiles) throw new VerifiedRunError(\"storage_limit\");\n\t\t\tconst absolute = join(root, path);\n\t\t\tconst stat = lstatSync(absolute);\n\t\t\tif (stat.isDirectory()) {\n\t\t\t\tif ((stat.mode & 0o7777) !== 0o755) throw new VerifiedRunError(\"file_type\");\n\t\t\t\tdirectories.push(path);\n\t\t\t\tvisit(path);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!stat.isFile() || stat.nlink !== 1 || (stat.mode & 0o7000) !== 0) throw new VerifiedRunError(\"file_type\");\n\t\t\tconst bytes = readRegularFile(absolute, limits.maxBytes - bytesUsed);\n\t\t\tbytesUsed += bytes.length;\n\t\t\tconst digest = digestBytes(bytes);\n\t\t\tcontents.set(digest, bytes);\n\t\t\tfiles.push(Object.freeze({ path, mode: stat.mode & 0o777, digest, size: bytes.length }));\n\t\t}\n\t};\n\tvisit(\"\");\n\tconst manifest: CandidateManifest = Object.freeze({\n\t\tversion: 1,\n\t\tdirectories: Object.freeze(directories),\n\t\tfiles: Object.freeze(files),\n\t});\n\treturn { manifest, digest: digestObject(manifest), contents };\n}\n\nexport function materializeCandidate(snapshot: CandidateSnapshot, target: string): void {\n\tmkdirSync(target, { mode: 0o700 });\n\tfor (const directory of snapshot.manifest.directories) mkdirSync(join(target, directory), { mode: 0o755 });\n\tfor (const file of snapshot.manifest.files) {\n\t\tconst bytes = snapshot.contents.get(file.digest);\n\t\tif (!bytes) throw new VerifiedRunError(\"integrity\");\n\t\tpublishBytes(join(target, file.path), bytes);\n\t\tchmodSync(join(target, file.path), file.mode);\n\t}\n}\n\nexport function assertCandidateScope(\n\tbase: CandidateManifest,\n\tcandidate: CandidateManifest,\n\twritable: readonly string[],\n): void {\n\tconst before = new Map(base.files.map((file) => [file.path, digestObject(file)]));\n\tconst after = new Map(candidate.files.map((file) => [file.path, digestObject(file)]));\n\tfor (const directory of base.directories) before.set(`${directory}/`, \"directory\");\n\tfor (const directory of candidate.directories) after.set(`${directory}/`, \"directory\");\n\tfor (const path of new Set([...before.keys(), ...after.keys()])) {\n\t\tif (before.get(path) === after.get(path)) continue;\n\t\tconst normalized = path.endsWith(\"/\") ? path.slice(0, -1) : path;\n\t\tif (!writable.some((scope) => normalized === scope || normalized.startsWith(`${scope}/`)))\n\t\t\tthrow new VerifiedRunError(\"scope_changed\");\n\t}\n}\n\nexport function storeCandidate(snapshot: CandidateSnapshot, runPath: string): void {\n\tfor (const [digest, bytes] of snapshot.contents) publishBytes(join(runPath, \"blobs\", digest), bytes);\n\tpublishObject(join(runPath, \"candidates\", `${snapshot.digest}.json`), snapshot.manifest);\n}\n\nexport function loadCandidate(runPath: string, digest: string, limits: RunPhaseBudget): CandidateSnapshot {\n\tif (!/^[a-f0-9]{64}$/.test(digest)) throw new VerifiedRunError(\"integrity\");\n\tconst raw = readJson(join(runPath, \"candidates\", `${digest}.json`), 4194304);\n\tif (\n\t\tdigestObject(raw) !== digest ||\n\t\ttypeof raw !== \"object\" ||\n\t\traw === null ||\n\t\t!(\"version\" in raw) ||\n\t\traw.version !== 1 ||\n\t\t!(\"files\" in raw) ||\n\t\t!Array.isArray(raw.files) ||\n\t\t!(\"directories\" in raw) ||\n\t\t!Array.isArray(raw.directories)\n\t) {\n\t\tthrow new VerifiedRunError(\"integrity\");\n\t}\n\tif (raw.files.length + raw.directories.length > limits.maxFiles) throw new VerifiedRunError(\"integrity\");\n\tconst files: CandidateFile[] = [];\n\tconst directories: string[] = [];\n\tconst paths = new Set<string>();\n\tlet total = 0;\n\tfor (const directory of raw.directories) {\n\t\tif (typeof directory !== \"string\") throw new VerifiedRunError(\"integrity\");\n\t\tsafePath(directory);\n\t\tif (paths.has(directory)) throw new VerifiedRunError(\"integrity\");\n\t\tpaths.add(directory);\n\t\tdirectories.push(directory);\n\t}\n\tconst contents = new Map<string, Buffer>();\n\tconst rawFiles: readonly unknown[] = raw.files;\n\tfor (const file of rawFiles) {\n\t\tif (\n\t\t\ttypeof file !== \"object\" ||\n\t\t\tfile === null ||\n\t\t\t!(\"path\" in file) ||\n\t\t\ttypeof file.path !== \"string\" ||\n\t\t\t!(\"digest\" in file) ||\n\t\t\ttypeof file.digest !== \"string\" ||\n\t\t\t!/^[a-f0-9]{64}$/.test(file.digest) ||\n\t\t\t!(\"mode\" in file) ||\n\t\t\ttypeof file.mode !== \"number\" ||\n\t\t\t!Number.isSafeInteger(file.mode) ||\n\t\t\tfile.mode < 0 ||\n\t\t\tfile.mode > 0o777 ||\n\t\t\t!(\"size\" in file) ||\n\t\t\ttypeof file.size !== \"number\" ||\n\t\t\t!Number.isSafeInteger(file.size) ||\n\t\t\tfile.size < 0\n\t\t)\n\t\t\tthrow new VerifiedRunError(\"integrity\");\n\t\tsafePath(file.path);\n\t\tif (paths.has(file.path)) throw new VerifiedRunError(\"integrity\");\n\t\tpaths.add(file.path);\n\t\ttotal += file.size;\n\t\tif (total > limits.maxBytes) throw new VerifiedRunError(\"integrity\");\n\t\tlet bytes: Buffer;\n\t\ttry {\n\t\t\tbytes = readRegularFile(join(runPath, \"blobs\", file.digest), file.size);\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error) throw new VerifiedRunError(\"integrity\");\n\t\t\tthrow error;\n\t\t}\n\t\tif (bytes.length !== file.size || digestBytes(bytes) !== file.digest) throw new VerifiedRunError(\"integrity\");\n\t\tcontents.set(file.digest, bytes);\n\t\tfiles.push(Object.freeze({ path: file.path, mode: file.mode, digest: file.digest, size: file.size }));\n\t}\n\tconst manifest: CandidateManifest = Object.freeze({\n\t\tversion: 1,\n\t\tdirectories: Object.freeze(directories),\n\t\tfiles: Object.freeze(files),\n\t});\n\tif (digestObject(manifest) !== digest) throw new VerifiedRunError(\"integrity\");\n\treturn { manifest, digest, contents };\n}\n"]}
@@ -0,0 +1,167 @@
1
+ import { chmodSync, lstatSync, mkdirSync, readdirSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { assertDirectory, digestBytes, digestObject, publishBytes, publishObject, readJson, readRegularFile, VerifiedRunError, } from "./storage.js";
4
+ function safePath(path) {
5
+ if (!path ||
6
+ /[\\\u0000-\u001f\u007f]/.test(path) ||
7
+ path.split("/").some((part) => ["", ".", "..", ".git", ".omk"].includes(part))) {
8
+ throw new VerifiedRunError("file_type");
9
+ }
10
+ }
11
+ /** Entire regular-file tree, including dot/untracked files; .git/.omk metadata is excluded by this profile. */
12
+ export function captureCandidate(root, limits) {
13
+ assertDirectory(root);
14
+ const files = [];
15
+ const directories = [];
16
+ const contents = new Map();
17
+ let bytesUsed = 0;
18
+ const visit = (prefix) => {
19
+ const names = readdirSync(join(root, prefix), { encoding: "buffer" })
20
+ .map((name) => new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(name))
21
+ .sort();
22
+ for (const name of names) {
23
+ if (!prefix && (name === ".git" || name === ".omk"))
24
+ continue;
25
+ const path = prefix ? `${prefix}/${name}` : name;
26
+ safePath(path);
27
+ if (files.length + directories.length >= limits.maxFiles)
28
+ throw new VerifiedRunError("storage_limit");
29
+ const absolute = join(root, path);
30
+ const stat = lstatSync(absolute);
31
+ if (stat.isDirectory()) {
32
+ if ((stat.mode & 0o7777) !== 0o755)
33
+ throw new VerifiedRunError("file_type");
34
+ directories.push(path);
35
+ visit(path);
36
+ continue;
37
+ }
38
+ if (!stat.isFile() || stat.nlink !== 1 || (stat.mode & 0o7000) !== 0)
39
+ throw new VerifiedRunError("file_type");
40
+ const bytes = readRegularFile(absolute, limits.maxBytes - bytesUsed);
41
+ bytesUsed += bytes.length;
42
+ const digest = digestBytes(bytes);
43
+ contents.set(digest, bytes);
44
+ files.push(Object.freeze({ path, mode: stat.mode & 0o777, digest, size: bytes.length }));
45
+ }
46
+ };
47
+ visit("");
48
+ const manifest = Object.freeze({
49
+ version: 1,
50
+ directories: Object.freeze(directories),
51
+ files: Object.freeze(files),
52
+ });
53
+ return { manifest, digest: digestObject(manifest), contents };
54
+ }
55
+ export function materializeCandidate(snapshot, target) {
56
+ mkdirSync(target, { mode: 0o700 });
57
+ for (const directory of snapshot.manifest.directories)
58
+ mkdirSync(join(target, directory), { mode: 0o755 });
59
+ for (const file of snapshot.manifest.files) {
60
+ const bytes = snapshot.contents.get(file.digest);
61
+ if (!bytes)
62
+ throw new VerifiedRunError("integrity");
63
+ publishBytes(join(target, file.path), bytes);
64
+ chmodSync(join(target, file.path), file.mode);
65
+ }
66
+ }
67
+ export function assertCandidateScope(base, candidate, writable) {
68
+ const before = new Map(base.files.map((file) => [file.path, digestObject(file)]));
69
+ const after = new Map(candidate.files.map((file) => [file.path, digestObject(file)]));
70
+ for (const directory of base.directories)
71
+ before.set(`${directory}/`, "directory");
72
+ for (const directory of candidate.directories)
73
+ after.set(`${directory}/`, "directory");
74
+ for (const path of new Set([...before.keys(), ...after.keys()])) {
75
+ if (before.get(path) === after.get(path))
76
+ continue;
77
+ const normalized = path.endsWith("/") ? path.slice(0, -1) : path;
78
+ if (!writable.some((scope) => normalized === scope || normalized.startsWith(`${scope}/`)))
79
+ throw new VerifiedRunError("scope_changed");
80
+ }
81
+ }
82
+ export function storeCandidate(snapshot, runPath) {
83
+ for (const [digest, bytes] of snapshot.contents)
84
+ publishBytes(join(runPath, "blobs", digest), bytes);
85
+ publishObject(join(runPath, "candidates", `${snapshot.digest}.json`), snapshot.manifest);
86
+ }
87
+ export function loadCandidate(runPath, digest, limits) {
88
+ if (!/^[a-f0-9]{64}$/.test(digest))
89
+ throw new VerifiedRunError("integrity");
90
+ const raw = readJson(join(runPath, "candidates", `${digest}.json`), 4194304);
91
+ if (digestObject(raw) !== digest ||
92
+ typeof raw !== "object" ||
93
+ raw === null ||
94
+ !("version" in raw) ||
95
+ raw.version !== 1 ||
96
+ !("files" in raw) ||
97
+ !Array.isArray(raw.files) ||
98
+ !("directories" in raw) ||
99
+ !Array.isArray(raw.directories)) {
100
+ throw new VerifiedRunError("integrity");
101
+ }
102
+ if (raw.files.length + raw.directories.length > limits.maxFiles)
103
+ throw new VerifiedRunError("integrity");
104
+ const files = [];
105
+ const directories = [];
106
+ const paths = new Set();
107
+ let total = 0;
108
+ for (const directory of raw.directories) {
109
+ if (typeof directory !== "string")
110
+ throw new VerifiedRunError("integrity");
111
+ safePath(directory);
112
+ if (paths.has(directory))
113
+ throw new VerifiedRunError("integrity");
114
+ paths.add(directory);
115
+ directories.push(directory);
116
+ }
117
+ const contents = new Map();
118
+ const rawFiles = raw.files;
119
+ for (const file of rawFiles) {
120
+ if (typeof file !== "object" ||
121
+ file === null ||
122
+ !("path" in file) ||
123
+ typeof file.path !== "string" ||
124
+ !("digest" in file) ||
125
+ typeof file.digest !== "string" ||
126
+ !/^[a-f0-9]{64}$/.test(file.digest) ||
127
+ !("mode" in file) ||
128
+ typeof file.mode !== "number" ||
129
+ !Number.isSafeInteger(file.mode) ||
130
+ file.mode < 0 ||
131
+ file.mode > 0o777 ||
132
+ !("size" in file) ||
133
+ typeof file.size !== "number" ||
134
+ !Number.isSafeInteger(file.size) ||
135
+ file.size < 0)
136
+ throw new VerifiedRunError("integrity");
137
+ safePath(file.path);
138
+ if (paths.has(file.path))
139
+ throw new VerifiedRunError("integrity");
140
+ paths.add(file.path);
141
+ total += file.size;
142
+ if (total > limits.maxBytes)
143
+ throw new VerifiedRunError("integrity");
144
+ let bytes;
145
+ try {
146
+ bytes = readRegularFile(join(runPath, "blobs", file.digest), file.size);
147
+ }
148
+ catch (error) {
149
+ if (error instanceof Error)
150
+ throw new VerifiedRunError("integrity");
151
+ throw error;
152
+ }
153
+ if (bytes.length !== file.size || digestBytes(bytes) !== file.digest)
154
+ throw new VerifiedRunError("integrity");
155
+ contents.set(file.digest, bytes);
156
+ files.push(Object.freeze({ path: file.path, mode: file.mode, digest: file.digest, size: file.size }));
157
+ }
158
+ const manifest = Object.freeze({
159
+ version: 1,
160
+ directories: Object.freeze(directories),
161
+ files: Object.freeze(files),
162
+ });
163
+ if (digestObject(manifest) !== digest)
164
+ throw new VerifiedRunError("integrity");
165
+ return { manifest, digest, contents };
166
+ }
167
+ //# sourceMappingURL=candidate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"candidate.js","sourceRoot":"","sources":["../../../src/core/verified-run/candidate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AACvE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,EACN,eAAe,EACf,WAAW,EACX,YAAY,EACZ,YAAY,EACZ,aAAa,EACb,QAAQ,EACR,eAAe,EACf,gBAAgB,GAChB,MAAM,cAAc,CAAC;AAmBtB,SAAS,QAAQ,CAAC,IAAY,EAAQ;IACrC,IACC,CAAC,IAAI;QACL,yBAAyB,CAAC,IAAI,CAAC,IAAI,CAAC;QACpC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,EAAE,EAAE,GAAG,EAAE,IAAI,EAAE,MA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EAAE,CAAC;QACV,WAAW,EAAE,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC;QACvC,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC;KAC3B,CAAC,CAAC;IACH,IAAI,YAAY,CAAC,QAAQ,CAAC,KAAK,MAAM;QAAE,MAAM,IAAI,gBAAgB,CAAC,WAAW,CAAC,CAAC;IAC/E,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC;AAAA,CACtC","sourcesContent":["import { chmodSync, lstatSync, mkdirSync, readdirSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { RunPhaseBudget } from \"omk-protocol\";\nimport {\n\tassertDirectory,\n\tdigestBytes,\n\tdigestObject,\n\tpublishBytes,\n\tpublishObject,\n\treadJson,\n\treadRegularFile,\n\tVerifiedRunError,\n} from \"./storage.ts\";\n\nexport interface CandidateFile {\n\treadonly path: string;\n\treadonly mode: number;\n\treadonly digest: string;\n\treadonly size: number;\n}\nexport interface CandidateManifest {\n\treadonly version: 1;\n\treadonly directories: readonly string[];\n\treadonly files: readonly CandidateFile[];\n}\nexport interface CandidateSnapshot {\n\treadonly manifest: CandidateManifest;\n\treadonly digest: string;\n\treadonly contents: ReadonlyMap<string, Buffer>;\n}\n\nfunction safePath(path: string): void {\n\tif (\n\t\t!path ||\n\t\t/[\\\\\\u0000-\\u001f\\u007f]/.test(path) ||\n\t\tpath.split(\"/\").some((part) => [\"\", \".\", \"..\", \".git\", \".omk\"].includes(part))\n\t) {\n\t\tthrow new VerifiedRunError(\"file_type\");\n\t}\n}\n\n/** Entire regular-file tree, including dot/untracked files; .git/.omk metadata is excluded by this profile. */\nexport function captureCandidate(root: string, limits: RunPhaseBudget): CandidateSnapshot {\n\tassertDirectory(root);\n\tconst files: CandidateFile[] = [];\n\tconst directories: string[] = [];\n\tconst contents = new Map<string, Buffer>();\n\tlet bytesUsed = 0;\n\tconst visit = (prefix: string): void => {\n\t\tconst names = readdirSync(join(root, prefix), { encoding: \"buffer\" })\n\t\t\t.map((name) => new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(name))\n\t\t\t.sort();\n\t\tfor (const name of names) {\n\t\t\tif (!prefix && (name === \".git\" || name === \".omk\")) continue;\n\t\t\tconst path = prefix ? `${prefix}/${name}` : name;\n\t\t\tsafePath(path);\n\t\t\tif (files.length + directories.length >= limits.maxFiles) throw new VerifiedRunError(\"storage_limit\");\n\t\t\tconst absolute = join(root, path);\n\t\t\tconst stat = lstatSync(absolute);\n\t\t\tif (stat.isDirectory()) {\n\t\t\t\tif ((stat.mode & 0o7777) !== 0o755) throw new VerifiedRunError(\"file_type\");\n\t\t\t\tdirectories.push(path);\n\t\t\t\tvisit(path);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!stat.isFile() || stat.nlink !== 1 || (stat.mode & 0o7000) !== 0) throw new VerifiedRunError(\"file_type\");\n\t\t\tconst bytes = readRegularFile(absolute, limits.maxBytes - bytesUsed);\n\t\t\tbytesUsed += bytes.length;\n\t\t\tconst digest = digestBytes(bytes);\n\t\t\tcontents.set(digest, bytes);\n\t\t\tfiles.push(Object.freeze({ path, mode: stat.mode & 0o777, digest, size: bytes.length }));\n\t\t}\n\t};\n\tvisit(\"\");\n\tconst manifest: CandidateManifest = Object.freeze({\n\t\tversion: 1,\n\t\tdirectories: Object.freeze(directories),\n\t\tfiles: Object.freeze(files),\n\t});\n\treturn { manifest, digest: digestObject(manifest), contents };\n}\n\nexport function materializeCandidate(snapshot: CandidateSnapshot, target: string): void {\n\tmkdirSync(target, { mode: 0o700 });\n\tfor (const directory of snapshot.manifest.directories) mkdirSync(join(target, directory), { mode: 0o755 });\n\tfor (const file of snapshot.manifest.files) {\n\t\tconst bytes = snapshot.contents.get(file.digest);\n\t\tif (!bytes) throw new VerifiedRunError(\"integrity\");\n\t\tpublishBytes(join(target, file.path), bytes);\n\t\tchmodSync(join(target, file.path), file.mode);\n\t}\n}\n\nexport function assertCandidateScope(\n\tbase: CandidateManifest,\n\tcandidate: CandidateManifest,\n\twritable: readonly string[],\n): void {\n\tconst before = new Map(base.files.map((file) => [file.path, digestObject(file)]));\n\tconst after = new Map(candidate.files.map((file) => [file.path, digestObject(file)]));\n\tfor (const directory of base.directories) before.set(`${directory}/`, \"directory\");\n\tfor (const directory of candidate.directories) after.set(`${directory}/`, \"directory\");\n\tfor (const path of new Set([...before.keys(), ...after.keys()])) {\n\t\tif (before.get(path) === after.get(path)) continue;\n\t\tconst normalized = path.endsWith(\"/\") ? path.slice(0, -1) : path;\n\t\tif (!writable.some((scope) => normalized === scope || normalized.startsWith(`${scope}/`)))\n\t\t\tthrow new VerifiedRunError(\"scope_changed\");\n\t}\n}\n\nexport function storeCandidate(snapshot: CandidateSnapshot, runPath: string): void {\n\tfor (const [digest, bytes] of snapshot.contents) publishBytes(join(runPath, \"blobs\", digest), bytes);\n\tpublishObject(join(runPath, \"candidates\", `${snapshot.digest}.json`), snapshot.manifest);\n}\n\nexport function loadCandidate(runPath: string, digest: string, limits: RunPhaseBudget): CandidateSnapshot {\n\tif (!/^[a-f0-9]{64}$/.test(digest)) throw new VerifiedRunError(\"integrity\");\n\tconst raw = readJson(join(runPath, \"candidates\", `${digest}.json`), 4194304);\n\tif (\n\t\tdigestObject(raw) !== digest ||\n\t\ttypeof raw !== \"object\" ||\n\t\traw === null ||\n\t\t!(\"version\" in raw) ||\n\t\traw.version !== 1 ||\n\t\t!(\"files\" in raw) ||\n\t\t!Array.isArray(raw.files) ||\n\t\t!(\"directories\" in raw) ||\n\t\t!Array.isArray(raw.directories)\n\t) {\n\t\tthrow new VerifiedRunError(\"integrity\");\n\t}\n\tif (raw.files.length + raw.directories.length > limits.maxFiles) throw new VerifiedRunError(\"integrity\");\n\tconst files: CandidateFile[] = [];\n\tconst directories: string[] = [];\n\tconst paths = new Set<string>();\n\tlet total = 0;\n\tfor (const directory of raw.directories) {\n\t\tif (typeof directory !== \"string\") throw new VerifiedRunError(\"integrity\");\n\t\tsafePath(directory);\n\t\tif (paths.has(directory)) throw new VerifiedRunError(\"integrity\");\n\t\tpaths.add(directory);\n\t\tdirectories.push(directory);\n\t}\n\tconst contents = new Map<string, Buffer>();\n\tconst rawFiles: readonly unknown[] = raw.files;\n\tfor (const file of rawFiles) {\n\t\tif (\n\t\t\ttypeof file !== \"object\" ||\n\t\t\tfile === null ||\n\t\t\t!(\"path\" in file) ||\n\t\t\ttypeof file.path !== \"string\" ||\n\t\t\t!(\"digest\" in file) ||\n\t\t\ttypeof file.digest !== \"string\" ||\n\t\t\t!/^[a-f0-9]{64}$/.test(file.digest) ||\n\t\t\t!(\"mode\" in file) ||\n\t\t\ttypeof file.mode !== \"number\" ||\n\t\t\t!Number.isSafeInteger(file.mode) ||\n\t\t\tfile.mode < 0 ||\n\t\t\tfile.mode > 0o777 ||\n\t\t\t!(\"size\" in file) ||\n\t\t\ttypeof file.size !== \"number\" ||\n\t\t\t!Number.isSafeInteger(file.size) ||\n\t\t\tfile.size < 0\n\t\t)\n\t\t\tthrow new VerifiedRunError(\"integrity\");\n\t\tsafePath(file.path);\n\t\tif (paths.has(file.path)) throw new VerifiedRunError(\"integrity\");\n\t\tpaths.add(file.path);\n\t\ttotal += file.size;\n\t\tif (total > limits.maxBytes) throw new VerifiedRunError(\"integrity\");\n\t\tlet bytes: Buffer;\n\t\ttry {\n\t\t\tbytes = readRegularFile(join(runPath, \"blobs\", file.digest), file.size);\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error) throw new VerifiedRunError(\"integrity\");\n\t\t\tthrow error;\n\t\t}\n\t\tif (bytes.length !== file.size || digestBytes(bytes) !== file.digest) throw new VerifiedRunError(\"integrity\");\n\t\tcontents.set(file.digest, bytes);\n\t\tfiles.push(Object.freeze({ path: file.path, mode: file.mode, digest: file.digest, size: file.size }));\n\t}\n\tconst manifest: CandidateManifest = Object.freeze({\n\t\tversion: 1,\n\t\tdirectories: Object.freeze(directories),\n\t\tfiles: Object.freeze(files),\n\t});\n\tif (digestObject(manifest) !== digest) throw new VerifiedRunError(\"integrity\");\n\treturn { manifest, digest, contents };\n}\n"]}
@@ -0,0 +1,18 @@
1
+ import type { RunCheck, RunContract } from "omk-protocol";
2
+ import type { EvidenceReceipt } from "../../types/evidence.ts";
3
+ import type { SandboxOutcome } from "./broker.ts";
4
+ import type { CandidateManifest } from "./candidate.ts";
5
+ import type { CheckObservation } from "./evidence-binding.ts";
6
+ export declare function preflightCheckReceipts(contract: RunContract): void;
7
+ export declare function storeCheckReceipt(runPath: string, contract: RunContract, execution: {
8
+ readonly check: RunCheck;
9
+ readonly executionId: string;
10
+ readonly result: SandboxOutcome;
11
+ readonly timeoutMs: number;
12
+ readonly manifest: CandidateManifest;
13
+ }): string;
14
+ export declare function readCheckReceipts(runPath: string, contract: RunContract, binding: {
15
+ readonly manifest: CandidateManifest;
16
+ readonly checks: readonly CheckObservation[];
17
+ }): readonly EvidenceReceipt[];
18
+ //# sourceMappingURL=check-receipt.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"check-receipt.d.ts","sourceRoot":"","sources":["../../../src/core/verified-run/check-receipt.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAI1D,OAAO,KAAK,EAEX,eAAe,EAGf,MAAM,yBAAyB,CAAC;AAGjC,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAClD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AACxD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAS9D,wBAAgB,sBAAsB,CAAC,QAAQ,EAAE,WAAW,GAAG,IAAI,CAElE;AAuBD,wBAAgB,iBAAiB,CAChC,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,WAAW,EACrB,SAAS,EAAE;IACV,QAAQ,CAAC,KAAK,EAAE,QAAQ,CAAC;IACzB,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,MAAM,EAAE,cAAc,CAAC;IAChC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,QAAQ,EAAE,iBAAiB,CAAC;CACrC,GACC,MAAM,CA0BR;AAED,wBAAgB,iBAAiB,CAChC,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,WAAW,EACrB,OAAO,EAAE;IACR,QAAQ,CAAC,QAAQ,EAAE,iBAAiB,CAAC;IACrC,QAAQ,CAAC,MAAM,EAAE,SAAS,gBAAgB,EAAE,CAAC;CAC7C,GACC,SAAS,eAAe,EAAE,CA+B5B","sourcesContent":["import { join } from \"node:path\";\nimport type { RunCheck, RunContract } from \"omk-protocol\";\nimport { assertCredentialFreeEvidenceCommand } from \"../../guardrails/command-redaction.ts\";\nimport { createEvidenceReceipt, parseSha256Hex, validateEvidenceReceipt } from \"../../guardrails/evidence-receipt.ts\";\nimport { computeWorkspaceManifestSha256 } from \"../../guardrails/workspace-fingerprint.ts\";\nimport type {\n\tEvidenceCommandDescriptor,\n\tEvidenceReceipt,\n\tEvidenceReceiptDisposition,\n\tWorkspaceFingerprint,\n} from \"../../types/evidence.ts\";\nimport { redactSensitiveTextForced } from \"../redaction.ts\";\nimport { canonicalJson } from \"../run-journal.ts\";\nimport type { SandboxOutcome } from \"./broker.ts\";\nimport type { CandidateManifest } from \"./candidate.ts\";\nimport type { CheckObservation } from \"./evidence-binding.ts\";\nimport { publishObject, readJson, VerifiedRunError } from \"./storage.ts\";\n\nfunction command(check: RunCheck): EvidenceCommandDescriptor {\n\tconst executable = check.argv[0];\n\tif (!executable) throw new VerifiedRunError(\"integrity\");\n\treturn { kind: \"argv\", executable, argv: check.argv.slice(1) };\n}\n\nexport function preflightCheckReceipts(contract: RunContract): void {\n\tfor (const check of contract.checks) assertCredentialFreeEvidenceCommand(command(check));\n}\n\nfunction fingerprint(manifest: CandidateManifest): WorkspaceFingerprint {\n\tconst files = [...manifest.files].sort((left, right) =>\n\t\tleft.path < right.path ? -1 : left.path > right.path ? 1 : 0,\n\t);\n\tconst scope = { root: \"/workspace\", artifactPaths: files.map((file) => file.path) };\n\tconst artifacts = files.map((file) => ({\n\t\tpath: file.path,\n\t\tstate: \"file\" as const,\n\t\tsha256: parseSha256Hex(file.digest),\n\t\tsize: file.size,\n\t}));\n\treturn { kind: \"artifact-set\", scope, artifacts, manifestSha256: computeWorkspaceManifestSha256(scope, artifacts) };\n}\n\nfunction disposition(result: Pick<SandboxOutcome, \"failure\" | \"exitCode\">): EvidenceReceiptDisposition {\n\tif (result.failure === \"deadline\") return { status: \"timeout\", exitCode: null };\n\tif (result.failure === \"cancelled\" || result.failure === \"output_limit\" || result.exitCode === null)\n\t\treturn { status: \"aborted\", exitCode: null };\n\treturn result.exitCode === 0 ? { status: \"passed\", exitCode: 0 } : { status: \"failed\", exitCode: result.exitCode };\n}\n\nexport function storeCheckReceipt(\n\trunPath: string,\n\tcontract: RunContract,\n\texecution: {\n\t\treadonly check: RunCheck;\n\t\treadonly executionId: string;\n\t\treadonly result: SandboxOutcome;\n\t\treadonly timeoutMs: number;\n\t\treadonly manifest: CandidateManifest;\n\t},\n): string {\n\tconst workspace = fingerprint(execution.manifest);\n\tconst result = execution.result;\n\tconst receipt = createEvidenceReceipt({\n\t\treceiptId: execution.executionId,\n\t\tgoalId: contract.runId,\n\t\tclaim: `Exact stdout for ${execution.check.claimId}`,\n\t\tcommand: command(execution.check),\n\t\tcwd: \"/workspace\",\n\t\ttimeoutMs: execution.timeoutMs,\n\t\tstartedAt: result.startedAt,\n\t\tfinishedAt: result.finishedAt,\n\t\tdurationMs: Date.parse(result.finishedAt) - Date.parse(result.startedAt),\n\t\tworkspaceBefore: workspace,\n\t\tworkspaceAfter: workspace,\n\t\texecutor: \"internal\",\n\t\ttoolCallId: execution.executionId,\n\t\talreadyRedactedOutput: {\n\t\t\tredactionPolicyId: \"omk-verified-run-v1+forced-text+prefix-32k-per-stream\",\n\t\t\tstdout: Buffer.from(redactSensitiveTextForced(result.stdout.toString(\"utf8\"))).subarray(0, 32768),\n\t\t\tstderr: Buffer.from(redactSensitiveTextForced(result.stderr.toString(\"utf8\"))).subarray(0, 32768),\n\t\t},\n\t\t...disposition(result),\n\t});\n\tpublishObject(join(runPath, \"receipts\", `${receipt.envelope.coreSha256}.json`), receipt);\n\treturn receipt.envelope.coreSha256;\n}\n\nexport function readCheckReceipts(\n\trunPath: string,\n\tcontract: RunContract,\n\tbinding: {\n\t\treadonly manifest: CandidateManifest;\n\t\treadonly checks: readonly CheckObservation[];\n\t},\n): readonly EvidenceReceipt[] {\n\tconst workspace = fingerprint(binding.manifest);\n\treturn Object.freeze(\n\t\tbinding.checks.map((observation) => {\n\t\t\tconst digest = observation.receiptCoreDigest;\n\t\t\tif (!digest || !/^[a-f0-9]{64}$/.test(digest)) throw new VerifiedRunError(\"integrity\");\n\t\t\tconst receipt = validateEvidenceReceipt(readJson(join(runPath, \"receipts\", `${digest}.json`), 8388608));\n\t\t\tconst core = receipt.core;\n\t\t\tconst check = contract.checks.find((item) => item.claimId === observation.claimId);\n\t\t\tconst expected = disposition(observation);\n\t\t\tif (\n\t\t\t\t!check ||\n\t\t\t\tcanonicalJson(receipt.envelope) !== canonicalJson({ coreSha256: digest }) ||\n\t\t\t\tcore.receiptId !== observation.executionId ||\n\t\t\t\tcore.toolCallId !== observation.executionId ||\n\t\t\t\tcore.goalId !== contract.runId ||\n\t\t\t\tcore.executor !== \"internal\" ||\n\t\t\t\tcore.claim !== `Exact stdout for ${check.claimId}` ||\n\t\t\t\tcore.cwd !== \"/workspace\" ||\n\t\t\t\tcore.status !== expected.status ||\n\t\t\t\tcore.exitCode !== expected.exitCode ||\n\t\t\t\tcore.timeoutMs === null ||\n\t\t\t\tcore.timeoutMs > contract.budget.verifyMs ||\n\t\t\t\tcanonicalJson(core.command) !== canonicalJson(command(check)) ||\n\t\t\t\tcanonicalJson(core.workspaceBefore) !== canonicalJson(workspace) ||\n\t\t\t\tcanonicalJson(core.workspaceAfter) !== canonicalJson(workspace)\n\t\t\t)\n\t\t\t\tthrow new VerifiedRunError(\"integrity\");\n\t\t\treturn receipt;\n\t\t}),\n\t);\n}\n"]}
@@ -0,0 +1,92 @@
1
+ import { join } from "node:path";
2
+ import { assertCredentialFreeEvidenceCommand } from "../../guardrails/command-redaction.js";
3
+ import { createEvidenceReceipt, parseSha256Hex, validateEvidenceReceipt } from "../../guardrails/evidence-receipt.js";
4
+ import { computeWorkspaceManifestSha256 } from "../../guardrails/workspace-fingerprint.js";
5
+ import { redactSensitiveTextForced } from "../redaction.js";
6
+ import { canonicalJson } from "../run-journal.js";
7
+ import { publishObject, readJson, VerifiedRunError } from "./storage.js";
8
+ function command(check) {
9
+ const executable = check.argv[0];
10
+ if (!executable)
11
+ throw new VerifiedRunError("integrity");
12
+ return { kind: "argv", executable, argv: check.argv.slice(1) };
13
+ }
14
+ export function preflightCheckReceipts(contract) {
15
+ for (const check of contract.checks)
16
+ assertCredentialFreeEvidenceCommand(command(check));
17
+ }
18
+ function fingerprint(manifest) {
19
+ const files = [...manifest.files].sort((left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : 0);
20
+ const scope = { root: "/workspace", artifactPaths: files.map((file) => file.path) };
21
+ const artifacts = files.map((file) => ({
22
+ path: file.path,
23
+ state: "file",
24
+ sha256: parseSha256Hex(file.digest),
25
+ size: file.size,
26
+ }));
27
+ return { kind: "artifact-set", scope, artifacts, manifestSha256: computeWorkspaceManifestSha256(scope, artifacts) };
28
+ }
29
+ function disposition(result) {
30
+ if (result.failure === "deadline")
31
+ return { status: "timeout", exitCode: null };
32
+ if (result.failure === "cancelled" || result.failure === "output_limit" || result.exitCode === null)
33
+ return { status: "aborted", exitCode: null };
34
+ return result.exitCode === 0 ? { status: "passed", exitCode: 0 } : { status: "failed", exitCode: result.exitCode };
35
+ }
36
+ export function storeCheckReceipt(runPath, contract, execution) {
37
+ const workspace = fingerprint(execution.manifest);
38
+ const result = execution.result;
39
+ const receipt = createEvidenceReceipt({
40
+ receiptId: execution.executionId,
41
+ goalId: contract.runId,
42
+ claim: `Exact stdout for ${execution.check.claimId}`,
43
+ command: command(execution.check),
44
+ cwd: "/workspace",
45
+ timeoutMs: execution.timeoutMs,
46
+ startedAt: result.startedAt,
47
+ finishedAt: result.finishedAt,
48
+ durationMs: Date.parse(result.finishedAt) - Date.parse(result.startedAt),
49
+ workspaceBefore: workspace,
50
+ workspaceAfter: workspace,
51
+ executor: "internal",
52
+ toolCallId: execution.executionId,
53
+ alreadyRedactedOutput: {
54
+ redactionPolicyId: "omk-verified-run-v1+forced-text+prefix-32k-per-stream",
55
+ stdout: Buffer.from(redactSensitiveTextForced(result.stdout.toString("utf8"))).subarray(0, 32768),
56
+ stderr: Buffer.from(redactSensitiveTextForced(result.stderr.toString("utf8"))).subarray(0, 32768),
57
+ },
58
+ ...disposition(result),
59
+ });
60
+ publishObject(join(runPath, "receipts", `${receipt.envelope.coreSha256}.json`), receipt);
61
+ return receipt.envelope.coreSha256;
62
+ }
63
+ export function readCheckReceipts(runPath, contract, binding) {
64
+ const workspace = fingerprint(binding.manifest);
65
+ return Object.freeze(binding.checks.map((observation) => {
66
+ const digest = observation.receiptCoreDigest;
67
+ if (!digest || !/^[a-f0-9]{64}$/.test(digest))
68
+ throw new VerifiedRunError("integrity");
69
+ const receipt = validateEvidenceReceipt(readJson(join(runPath, "receipts", `${digest}.json`), 8388608));
70
+ const core = receipt.core;
71
+ const check = contract.checks.find((item) => item.claimId === observation.claimId);
72
+ const expected = disposition(observation);
73
+ if (!check ||
74
+ canonicalJson(receipt.envelope) !== canonicalJson({ coreSha256: digest }) ||
75
+ core.receiptId !== observation.executionId ||
76
+ core.toolCallId !== observation.executionId ||
77
+ core.goalId !== contract.runId ||
78
+ core.executor !== "internal" ||
79
+ core.claim !== `Exact stdout for ${check.claimId}` ||
80
+ core.cwd !== "/workspace" ||
81
+ core.status !== expected.status ||
82
+ core.exitCode !== expected.exitCode ||
83
+ core.timeoutMs === null ||
84
+ core.timeoutMs > contract.budget.verifyMs ||
85
+ canonicalJson(core.command) !== canonicalJson(command(check)) ||
86
+ canonicalJson(core.workspaceBefore) !== canonicalJson(workspace) ||
87
+ canonicalJson(core.workspaceAfter) !== canonicalJson(workspace))
88
+ throw new VerifiedRunError("integrity");
89
+ return receipt;
90
+ }));
91
+ }
92
+ //# sourceMappingURL=check-receipt.js.map