devcontour-harness 0.0.0-stage → 0.1.0-alpha.12

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 (466) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +268 -2
  3. package/docs/architecture.md +496 -0
  4. package/docs/compatibility-versions.md +60 -0
  5. package/docs/compatibility.md +192 -0
  6. package/docs/connectors.md +323 -0
  7. package/docs/contracts.md +630 -0
  8. package/docs/integrations/hindsight.md +148 -0
  9. package/docs/quickstart.md +185 -0
  10. package/docs/release-notes/0.1.0-alpha.10.md +50 -0
  11. package/docs/release-notes/0.1.0-alpha.11.md +44 -0
  12. package/docs/release-notes/0.1.0-alpha.12.md +66 -0
  13. package/docs/release-notes/0.1.0-alpha.6.md +238 -0
  14. package/docs/release-notes/0.1.0-alpha.7.md +71 -0
  15. package/docs/release-notes/0.1.0-alpha.8.md +73 -0
  16. package/docs/release-notes/0.1.0-alpha.9.md +55 -0
  17. package/docs/review-probes.md +199 -0
  18. package/docs/review-protocol.md +251 -0
  19. package/docs/standalone.md +271 -0
  20. package/docs/toolchains.md +167 -0
  21. package/docs/turbo-starter.md +269 -0
  22. package/docs/upgrade.md +219 -0
  23. package/examples/README.md +27 -0
  24. package/examples/external-connector/README.md +19 -0
  25. package/examples/external-connector/connector.mjs +55 -0
  26. package/examples/files-only/README.md +28 -0
  27. package/examples/files-only/context/norms/rules.md +4 -0
  28. package/examples/files-only/graph.json +23 -0
  29. package/examples/files-only/policy.json +30 -0
  30. package/examples/one-vendor/README.md +19 -0
  31. package/examples/one-vendor/policy.json +27 -0
  32. package/examples/single-task/README.md +18 -0
  33. package/examples/single-task/graph.json +27 -0
  34. package/examples/single-task/policy-same-vendor.json +55 -0
  35. package/examples/single-task/policy.json +52 -0
  36. package/examples/single-task/src/.gitkeep +0 -0
  37. package/examples/single-task/test/run.js +19 -0
  38. package/examples/toolchains/README.md +32 -0
  39. package/examples/toolchains/go/bad/label/label.go +9 -0
  40. package/examples/toolchains/go/good/label/label.go +9 -0
  41. package/examples/toolchains/go/policy.json +79 -0
  42. package/examples/toolchains/go/repo/REQUIREMENTS.md +9 -0
  43. package/examples/toolchains/go/repo/_gitignore +1 -0
  44. package/examples/toolchains/go/repo/go.mod +5 -0
  45. package/examples/toolchains/go/repo/go.sum +2 -0
  46. package/examples/toolchains/go/repo/label/label.go +9 -0
  47. package/examples/toolchains/go/repo/label/label_test.go +27 -0
  48. package/examples/toolchains/go/repo/label/version.go +9 -0
  49. package/examples/toolchains/go/task.json +25 -0
  50. package/examples/toolchains/mixed-go/bad/backend/label/label.go +9 -0
  51. package/examples/toolchains/mixed-go/bad/frontend/src/label.js +4 -0
  52. package/examples/toolchains/mixed-go/good/backend/label/label.go +9 -0
  53. package/examples/toolchains/mixed-go/good/frontend/src/label.js +4 -0
  54. package/examples/toolchains/mixed-go/policy.json +126 -0
  55. package/examples/toolchains/mixed-go/repo/REQUIREMENTS.md +9 -0
  56. package/examples/toolchains/mixed-go/repo/_gitignore +6 -0
  57. package/examples/toolchains/mixed-go/repo/backend/go.mod +3 -0
  58. package/examples/toolchains/mixed-go/repo/backend/label/label.go +9 -0
  59. package/examples/toolchains/mixed-go/repo/backend/label/label_test.go +30 -0
  60. package/examples/toolchains/mixed-go/repo/contract/check.mjs +17 -0
  61. package/examples/toolchains/mixed-go/repo/contract/label.json +9 -0
  62. package/examples/toolchains/mixed-go/repo/frontend/package.json +15 -0
  63. package/examples/toolchains/mixed-go/repo/frontend/pnpm-lock.yaml +22 -0
  64. package/examples/toolchains/mixed-go/repo/frontend/src/label.js +4 -0
  65. package/examples/toolchains/mixed-go/repo/frontend/test/label.test.js +11 -0
  66. package/examples/toolchains/mixed-go/task.json +25 -0
  67. package/examples/toolchains/mixed-python/bad/backend/src/fx_backend/__init__.py +6 -0
  68. package/examples/toolchains/mixed-python/bad/frontend/src/label.js +4 -0
  69. package/examples/toolchains/mixed-python/good/backend/src/fx_backend/__init__.py +6 -0
  70. package/examples/toolchains/mixed-python/good/frontend/src/label.js +4 -0
  71. package/examples/toolchains/mixed-python/policy.json +121 -0
  72. package/examples/toolchains/mixed-python/repo/REQUIREMENTS.md +9 -0
  73. package/examples/toolchains/mixed-python/repo/_gitignore +6 -0
  74. package/examples/toolchains/mixed-python/repo/backend/.python-version +1 -0
  75. package/examples/toolchains/mixed-python/repo/backend/pyproject.toml +19 -0
  76. package/examples/toolchains/mixed-python/repo/backend/src/fx_backend/__init__.py +6 -0
  77. package/examples/toolchains/mixed-python/repo/backend/tests/test_label.py +11 -0
  78. package/examples/toolchains/mixed-python/repo/backend/uv.lock +108 -0
  79. package/examples/toolchains/mixed-python/repo/contract/check.mjs +17 -0
  80. package/examples/toolchains/mixed-python/repo/contract/label.json +9 -0
  81. package/examples/toolchains/mixed-python/repo/frontend/package.json +15 -0
  82. package/examples/toolchains/mixed-python/repo/frontend/pnpm-lock.yaml +22 -0
  83. package/examples/toolchains/mixed-python/repo/frontend/src/label.js +4 -0
  84. package/examples/toolchains/mixed-python/repo/frontend/test/label.test.js +11 -0
  85. package/examples/toolchains/mixed-python/task.json +25 -0
  86. package/examples/toolchains/npm/bad/src/label.js +4 -0
  87. package/examples/toolchains/npm/good/src/label.js +4 -0
  88. package/examples/toolchains/npm/policy.json +82 -0
  89. package/examples/toolchains/npm/repo/REQUIREMENTS.md +9 -0
  90. package/examples/toolchains/npm/repo/_gitignore +4 -0
  91. package/examples/toolchains/npm/repo/package-lock.json +22 -0
  92. package/examples/toolchains/npm/repo/package.json +13 -0
  93. package/examples/toolchains/npm/repo/src/label.js +4 -0
  94. package/examples/toolchains/npm/repo/test/label.test.js +13 -0
  95. package/examples/toolchains/npm/task.json +25 -0
  96. package/examples/toolchains/pnpm/bad/packages/label/src/label.js +4 -0
  97. package/examples/toolchains/pnpm/good/packages/label/src/label.js +4 -0
  98. package/examples/toolchains/pnpm/policy.json +85 -0
  99. package/examples/toolchains/pnpm/repo/REQUIREMENTS.md +9 -0
  100. package/examples/toolchains/pnpm/repo/_gitignore +4 -0
  101. package/examples/toolchains/pnpm/repo/package.json +10 -0
  102. package/examples/toolchains/pnpm/repo/packages/checker/check.mjs +5 -0
  103. package/examples/toolchains/pnpm/repo/packages/checker/package.json +9 -0
  104. package/examples/toolchains/pnpm/repo/packages/label/package.json +14 -0
  105. package/examples/toolchains/pnpm/repo/packages/label/src/label.js +4 -0
  106. package/examples/toolchains/pnpm/repo/packages/label/test/label.test.js +13 -0
  107. package/examples/toolchains/pnpm/repo/pnpm-lock.yaml +29 -0
  108. package/examples/toolchains/pnpm/repo/pnpm-workspace.yaml +2 -0
  109. package/examples/toolchains/pnpm/task.json +25 -0
  110. package/examples/toolchains/python/bad/src/fx_label/__init__.py +6 -0
  111. package/examples/toolchains/python/good/src/fx_label/__init__.py +6 -0
  112. package/examples/toolchains/python/policy.json +80 -0
  113. package/examples/toolchains/python/repo/.python-version +1 -0
  114. package/examples/toolchains/python/repo/REQUIREMENTS.md +9 -0
  115. package/examples/toolchains/python/repo/_gitignore +5 -0
  116. package/examples/toolchains/python/repo/pyproject.toml +19 -0
  117. package/examples/toolchains/python/repo/src/fx_label/__init__.py +6 -0
  118. package/examples/toolchains/python/repo/tests/test_label.py +13 -0
  119. package/examples/toolchains/python/repo/uv.lock +108 -0
  120. package/examples/toolchains/python/task.json +25 -0
  121. package/examples/toolchains/turbo/bad/packages/label/src/label.js +4 -0
  122. package/examples/toolchains/turbo/good/packages/label/src/label.js +4 -0
  123. package/examples/toolchains/turbo/policy.json +110 -0
  124. package/examples/toolchains/turbo/repo/REQUIREMENTS.md +9 -0
  125. package/examples/toolchains/turbo/repo/_gitignore +4 -0
  126. package/examples/toolchains/turbo/repo/package.json +13 -0
  127. package/examples/toolchains/turbo/repo/packages/checker/check.mjs +5 -0
  128. package/examples/toolchains/turbo/repo/packages/checker/package.json +9 -0
  129. package/examples/toolchains/turbo/repo/packages/label/package.json +14 -0
  130. package/examples/toolchains/turbo/repo/packages/label/src/label.js +4 -0
  131. package/examples/toolchains/turbo/repo/packages/label/test/label.test.js +13 -0
  132. package/examples/toolchains/turbo/repo/pnpm-lock.yaml +94 -0
  133. package/examples/toolchains/turbo/repo/pnpm-workspace.yaml +2 -0
  134. package/examples/toolchains/turbo/repo/turbo.json +7 -0
  135. package/examples/toolchains/turbo/task.json +25 -0
  136. package/examples/turbo-starter/README.md +16 -0
  137. package/examples/turbo-starter/changes/issued-at-consumer-only.patch +12 -0
  138. package/examples/turbo-starter/changes/issued-at.patch +130 -0
  139. package/examples/turbo-starter/cleanup.mjs +58 -0
  140. package/examples/turbo-starter/graph.json +32 -0
  141. package/examples/turbo-starter/harness/acceptance/db-isolation.test.mjs +97 -0
  142. package/examples/turbo-starter/harness/acceptance/env-probe.test.mjs +75 -0
  143. package/examples/turbo-starter/harness/acceptance/generation.test.mjs +54 -0
  144. package/examples/turbo-starter/harness/acceptance/issued-at.test.mjs +43 -0
  145. package/examples/turbo-starter/harness/acceptance/lifecycle-probe.test.mjs +47 -0
  146. package/examples/turbo-starter/harness/compose-bridge.mjs +593 -0
  147. package/examples/turbo-starter/harness/compose.acceptance.yml +23 -0
  148. package/examples/turbo-starter/harness/env/backend.env.template +7 -0
  149. package/examples/turbo-starter/harness/env/compose.env.template +6 -0
  150. package/examples/turbo-starter/policy.json +109 -0
  151. package/examples/turbo-starter/policy.lifecycle.json +114 -0
  152. package/examples/turbo-starter/setup.mjs +352 -0
  153. package/examples/two-vendors/policy.json +30 -0
  154. package/lib/agents/cli-adapter.d.ts +48 -0
  155. package/lib/agents/cli-adapter.js +393 -0
  156. package/lib/agents/inspect.d.ts +60 -0
  157. package/lib/agents/inspect.js +296 -0
  158. package/lib/agents/probe-server.d.ts +2 -0
  159. package/lib/agents/probe-server.js +13 -0
  160. package/lib/agents/review-probe.d.ts +345 -0
  161. package/lib/agents/review-probe.js +1037 -0
  162. package/lib/agents/runtime-events.d.ts +11 -0
  163. package/lib/agents/runtime-events.js +21 -0
  164. package/lib/agents/schemas.d.ts +217 -0
  165. package/lib/agents/schemas.js +124 -0
  166. package/lib/agents/usage.d.ts +8 -0
  167. package/lib/agents/usage.js +83 -0
  168. package/lib/catalog/bytes.d.ts +9 -0
  169. package/lib/catalog/bytes.js +14 -0
  170. package/lib/catalog/harness.d.ts +3 -0
  171. package/lib/catalog/harness.js +11 -0
  172. package/lib/catalog/index.d.ts +5 -0
  173. package/lib/catalog/index.js +5 -0
  174. package/lib/catalog/operations.d.ts +24 -0
  175. package/lib/catalog/operations.js +74 -0
  176. package/lib/catalog/page.d.ts +46 -0
  177. package/lib/catalog/page.js +128 -0
  178. package/lib/catalog/shared.d.ts +37 -0
  179. package/lib/catalog/shared.js +67 -0
  180. package/lib/cli.d.ts +2 -0
  181. package/lib/cli.js +673 -0
  182. package/lib/connectors/files.d.ts +108 -0
  183. package/lib/connectors/files.js +133 -0
  184. package/lib/contracts/catalog.d.ts +31 -0
  185. package/lib/contracts/catalog.js +18 -0
  186. package/lib/contracts/checks.d.ts +307 -0
  187. package/lib/contracts/checks.js +181 -0
  188. package/lib/contracts/cli.d.ts +4665 -0
  189. package/lib/contracts/cli.js +840 -0
  190. package/lib/contracts/context.d.ts +135 -0
  191. package/lib/contracts/context.js +129 -0
  192. package/lib/contracts/diagnosis.d.ts +108 -0
  193. package/lib/contracts/diagnosis.js +69 -0
  194. package/lib/contracts/digest.d.ts +9 -0
  195. package/lib/contracts/digest.js +22 -0
  196. package/lib/contracts/errors.d.ts +89 -0
  197. package/lib/contracts/errors.js +74 -0
  198. package/lib/contracts/events.d.ts +827 -0
  199. package/lib/contracts/events.js +258 -0
  200. package/lib/contracts/execution.d.ts +3423 -0
  201. package/lib/contracts/execution.js +936 -0
  202. package/lib/contracts/failure.d.ts +38 -0
  203. package/lib/contracts/failure.js +53 -0
  204. package/lib/contracts/index.d.ts +22 -0
  205. package/lib/contracts/index.js +22 -0
  206. package/lib/contracts/planning.d.ts +433 -0
  207. package/lib/contracts/planning.js +159 -0
  208. package/lib/contracts/policy.d.ts +1075 -0
  209. package/lib/contracts/policy.js +544 -0
  210. package/lib/contracts/ports.d.ts +417 -0
  211. package/lib/contracts/ports.js +1 -0
  212. package/lib/contracts/primitives.d.ts +63 -0
  213. package/lib/contracts/primitives.js +73 -0
  214. package/lib/contracts/profiles.d.ts +340 -0
  215. package/lib/contracts/profiles.js +109 -0
  216. package/lib/contracts/project.d.ts +69 -0
  217. package/lib/contracts/project.js +47 -0
  218. package/lib/contracts/published.d.ts +3467 -0
  219. package/lib/contracts/published.js +40 -0
  220. package/lib/contracts/repair-policy.d.ts +31 -0
  221. package/lib/contracts/repair-policy.js +77 -0
  222. package/lib/contracts/result.d.ts +1284 -0
  223. package/lib/contracts/result.js +311 -0
  224. package/lib/contracts/review.d.ts +441 -0
  225. package/lib/contracts/review.js +477 -0
  226. package/lib/contracts/toolchain.d.ts +96 -0
  227. package/lib/contracts/toolchain.js +89 -0
  228. package/lib/contracts/version.d.ts +17 -0
  229. package/lib/contracts/version.js +17 -0
  230. package/lib/contracts/work.d.ts +171 -0
  231. package/lib/contracts/work.js +178 -0
  232. package/lib/control/base-move.d.ts +44 -0
  233. package/lib/control/base-move.js +90 -0
  234. package/lib/control/doctor.d.ts +50 -0
  235. package/lib/control/doctor.js +113 -0
  236. package/lib/control/harness.d.ts +1125 -0
  237. package/lib/control/harness.js +741 -0
  238. package/lib/control/provenance.d.ts +17 -0
  239. package/lib/control/provenance.js +25 -0
  240. package/lib/control/recovery.d.ts +237 -0
  241. package/lib/control/recovery.js +236 -0
  242. package/lib/control/review.d.ts +62 -0
  243. package/lib/control/review.js +182 -0
  244. package/lib/control/workflow.d.ts +256 -0
  245. package/lib/control/workflow.js +277 -0
  246. package/lib/engine/budget.d.ts +345 -0
  247. package/lib/engine/budget.js +278 -0
  248. package/lib/engine/classify.d.ts +8 -0
  249. package/lib/engine/classify.js +41 -0
  250. package/lib/engine/engine.d.ts +1564 -0
  251. package/lib/engine/engine.js +2283 -0
  252. package/lib/engine/failure.d.ts +1 -0
  253. package/lib/engine/failure.js +3 -0
  254. package/lib/engine/joint-runner.d.ts +257 -0
  255. package/lib/engine/joint-runner.js +254 -0
  256. package/lib/engine/measured.d.ts +15 -0
  257. package/lib/engine/measured.js +82 -0
  258. package/lib/engine/prompt.d.ts +66 -0
  259. package/lib/engine/prompt.js +131 -0
  260. package/lib/engine/property-recovery.d.ts +50 -0
  261. package/lib/engine/property-recovery.js +171 -0
  262. package/lib/engine/repair.d.ts +33 -0
  263. package/lib/engine/repair.js +82 -0
  264. package/lib/engine/result.d.ts +9 -0
  265. package/lib/engine/result.js +194 -0
  266. package/lib/engine/reuse.d.ts +80 -0
  267. package/lib/engine/reuse.js +102 -0
  268. package/lib/engine/runner.d.ts +360 -0
  269. package/lib/engine/runner.js +1844 -0
  270. package/lib/engine/standalone.d.ts +6 -0
  271. package/lib/engine/standalone.js +48 -0
  272. package/lib/engine/usage.d.ts +87 -0
  273. package/lib/engine/usage.js +165 -0
  274. package/lib/environment/isolation.d.ts +110 -0
  275. package/lib/environment/isolation.js +238 -0
  276. package/lib/environment/lifecycle.d.ts +40 -0
  277. package/lib/environment/lifecycle.js +197 -0
  278. package/lib/environment/live-calls.d.ts +14 -0
  279. package/lib/environment/live-calls.js +73 -0
  280. package/lib/environment/os-tools.d.ts +16 -0
  281. package/lib/environment/os-tools.js +35 -0
  282. package/lib/environment/process.d.ts +40 -0
  283. package/lib/environment/process.js +375 -0
  284. package/lib/environment/redaction.d.ts +22 -0
  285. package/lib/environment/redaction.js +102 -0
  286. package/lib/environment/resources.d.ts +31 -0
  287. package/lib/environment/resources.js +120 -0
  288. package/lib/explain/diagnose.d.ts +25 -0
  289. package/lib/explain/diagnose.js +60 -0
  290. package/lib/explain/state.d.ts +18 -0
  291. package/lib/explain/state.js +305 -0
  292. package/lib/index.d.ts +72 -0
  293. package/lib/index.js +74 -0
  294. package/lib/init/policy.d.ts +40 -0
  295. package/lib/init/policy.js +73 -0
  296. package/lib/init/project.d.ts +52 -0
  297. package/lib/init/project.js +412 -0
  298. package/lib/integrations/connector/commands.d.ts +358 -0
  299. package/lib/integrations/connector/commands.js +428 -0
  300. package/lib/integrations/connector/config.d.ts +215 -0
  301. package/lib/integrations/connector/config.js +214 -0
  302. package/lib/integrations/connector/delivery.d.ts +107 -0
  303. package/lib/integrations/connector/delivery.js +591 -0
  304. package/lib/integrations/connector/fake.d.ts +291 -0
  305. package/lib/integrations/connector/fake.js +786 -0
  306. package/lib/integrations/connector/history.d.ts +124 -0
  307. package/lib/integrations/connector/history.js +497 -0
  308. package/lib/integrations/connector/index.d.ts +16 -0
  309. package/lib/integrations/connector/index.js +16 -0
  310. package/lib/integrations/connector/redact.d.ts +19 -0
  311. package/lib/integrations/connector/redact.js +91 -0
  312. package/lib/integrations/connector/registry.d.ts +15 -0
  313. package/lib/integrations/connector/registry.js +43 -0
  314. package/lib/integrations/connector/snapshot.d.ts +131 -0
  315. package/lib/integrations/connector/snapshot.js +422 -0
  316. package/lib/integrations/connector/source.d.ts +37 -0
  317. package/lib/integrations/connector/source.js +73 -0
  318. package/lib/integrations/connector/steps.d.ts +71 -0
  319. package/lib/integrations/connector/steps.js +188 -0
  320. package/lib/integrations/connector/store.d.ts +140 -0
  321. package/lib/integrations/connector/store.js +277 -0
  322. package/lib/integrations/connector/summary.d.ts +38 -0
  323. package/lib/integrations/connector/summary.js +59 -0
  324. package/lib/integrations/connector/testing-worker.d.ts +1 -0
  325. package/lib/integrations/connector/testing-worker.js +81 -0
  326. package/lib/integrations/connector/testing.d.ts +205 -0
  327. package/lib/integrations/connector/testing.js +1615 -0
  328. package/lib/integrations/connector/transport.d.ts +240 -0
  329. package/lib/integrations/connector/transport.js +28 -0
  330. package/lib/integrations/memory/context.d.ts +120 -0
  331. package/lib/integrations/memory/context.js +239 -0
  332. package/lib/integrations/memory/index.d.ts +8 -0
  333. package/lib/integrations/memory/index.js +8 -0
  334. package/lib/integrations/memory/provider.d.ts +79 -0
  335. package/lib/integrations/memory/provider.js +22 -0
  336. package/lib/integrations/memory/sink.d.ts +56 -0
  337. package/lib/integrations/memory/sink.js +116 -0
  338. package/lib/integrations/memory/testing.d.ts +44 -0
  339. package/lib/integrations/memory/testing.js +61 -0
  340. package/lib/integrations/relay-v1/index.d.ts +122 -0
  341. package/lib/integrations/relay-v1/index.js +860 -0
  342. package/lib/integrations/relay-v2/index.d.ts +145 -0
  343. package/lib/integrations/relay-v2/index.js +752 -0
  344. package/lib/integrations/relay-v2/process.d.ts +32 -0
  345. package/lib/integrations/relay-v2/process.js +112 -0
  346. package/lib/integrations/relay-v2/protocol.d.ts +172 -0
  347. package/lib/integrations/relay-v2/protocol.js +142 -0
  348. package/lib/package.d.ts +2 -0
  349. package/lib/package.js +3 -0
  350. package/lib/planning/check.d.ts +26 -0
  351. package/lib/planning/check.js +174 -0
  352. package/lib/planning/facts.d.ts +13 -0
  353. package/lib/planning/facts.js +47 -0
  354. package/lib/planning/graph.d.ts +20 -0
  355. package/lib/planning/graph.js +114 -0
  356. package/lib/planning/index.d.ts +6 -0
  357. package/lib/planning/index.js +6 -0
  358. package/lib/planning/issues.d.ts +19 -0
  359. package/lib/planning/issues.js +210 -0
  360. package/lib/planning/request.d.ts +19 -0
  361. package/lib/planning/request.js +57 -0
  362. package/lib/planning/standalone.d.ts +16 -0
  363. package/lib/planning/standalone.js +19 -0
  364. package/lib/planning/stub.d.ts +2 -0
  365. package/lib/planning/stub.js +5 -0
  366. package/lib/profiles/resolve.d.ts +266 -0
  367. package/lib/profiles/resolve.js +322 -0
  368. package/lib/projections/chain.d.ts +35 -0
  369. package/lib/projections/chain.js +72 -0
  370. package/lib/projections/clip.d.ts +6 -0
  371. package/lib/projections/clip.js +23 -0
  372. package/lib/projections/enums.d.ts +7 -0
  373. package/lib/projections/enums.js +19 -0
  374. package/lib/projections/index.d.ts +8 -0
  375. package/lib/projections/index.js +9 -0
  376. package/lib/projections/next.d.ts +28 -0
  377. package/lib/projections/next.js +75 -0
  378. package/lib/projections/progress.d.ts +27 -0
  379. package/lib/projections/progress.js +37 -0
  380. package/lib/projections/queue.d.ts +21 -0
  381. package/lib/projections/queue.js +18 -0
  382. package/lib/projections/stop.d.ts +98 -0
  383. package/lib/projections/stop.js +532 -0
  384. package/lib/setup/files.d.ts +45 -0
  385. package/lib/setup/files.js +280 -0
  386. package/lib/storage/document.d.ts +1286 -0
  387. package/lib/storage/document.js +80 -0
  388. package/lib/storage/sqlite.d.ts +35 -0
  389. package/lib/storage/sqlite.js +260 -0
  390. package/lib/testing/index.d.ts +5 -0
  391. package/lib/testing/index.js +5 -0
  392. package/lib/testing/store-contract.d.ts +8 -0
  393. package/lib/testing/store-contract.js +167 -0
  394. package/lib/toolchains/index.d.ts +9 -0
  395. package/lib/toolchains/index.js +9 -0
  396. package/lib/toolchains/inspect.d.ts +105 -0
  397. package/lib/toolchains/inspect.js +831 -0
  398. package/lib/toolchains/manifests.d.ts +67 -0
  399. package/lib/toolchains/manifests.js +238 -0
  400. package/lib/toolchains/probe.d.ts +28 -0
  401. package/lib/toolchains/probe.js +54 -0
  402. package/lib/toolchains/recipes.d.ts +33 -0
  403. package/lib/toolchains/recipes.js +51 -0
  404. package/lib/validate.d.ts +37 -0
  405. package/lib/validate.js +182 -0
  406. package/lib/verification/acceptance.d.ts +284 -0
  407. package/lib/verification/acceptance.js +670 -0
  408. package/lib/verification/checks.d.ts +72 -0
  409. package/lib/verification/checks.js +190 -0
  410. package/lib/verification/confirm.d.ts +125 -0
  411. package/lib/verification/confirm.js +411 -0
  412. package/lib/verification/corpus.d.ts +1303 -0
  413. package/lib/verification/corpus.js +744 -0
  414. package/lib/verification/dependencies.d.ts +66 -0
  415. package/lib/verification/dependencies.js +144 -0
  416. package/lib/verification/gates.d.ts +182 -0
  417. package/lib/verification/gates.js +641 -0
  418. package/lib/verification/joint.d.ts +63 -0
  419. package/lib/verification/joint.js +121 -0
  420. package/lib/verification/proof.d.ts +54 -0
  421. package/lib/verification/proof.js +96 -0
  422. package/lib/verification/property.d.ts +86 -0
  423. package/lib/verification/property.js +214 -0
  424. package/lib/verification/requirements.d.ts +25 -0
  425. package/lib/verification/requirements.js +69 -0
  426. package/lib/verification/self-check.d.ts +29 -0
  427. package/lib/verification/self-check.js +99 -0
  428. package/lib/verification/spike.d.ts +79 -0
  429. package/lib/verification/spike.js +124 -0
  430. package/package.json +104 -4
  431. package/profiles/expo-mobile.json +15 -0
  432. package/profiles/go-api.json +15 -0
  433. package/profiles/go-gotestsum.json +21 -0
  434. package/profiles/mobile-maestro.json +29 -0
  435. package/profiles/nest-api.json +26 -0
  436. package/profiles/next-product.json +72 -0
  437. package/profiles/node-checks.json +77 -0
  438. package/profiles/npm-ci.json +22 -0
  439. package/profiles/pnpm-frozen.json +24 -0
  440. package/profiles/python-api.json +32 -0
  441. package/profiles/python-uv.json +26 -0
  442. package/profiles/react-native.json +50 -0
  443. package/profiles/react-vite-admin.json +71 -0
  444. package/schemas/context-snapshot.schema.json +231 -0
  445. package/schemas/contract-document.schema.json +385 -0
  446. package/schemas/execution-document.schema.json +3881 -0
  447. package/schemas/execution-policy.schema.json +2196 -0
  448. package/schemas/joint-verification.schema.json +617 -0
  449. package/schemas/plan-draft.schema.json +217 -0
  450. package/schemas/project-manifest.schema.json +167 -0
  451. package/schemas/result-envelope.schema.json +1654 -0
  452. package/schemas/review-record.schema.json +177 -0
  453. package/schemas/run-event.schema.json +2458 -0
  454. package/schemas/run-result.schema.json +1572 -0
  455. package/schemas/stack-profile.schema.json +535 -0
  456. package/schemas/stop-diagnosis.schema.json +169 -0
  457. package/schemas/work-graph.schema.json +381 -0
  458. package/schemas/work-order.schema.json +256 -0
  459. package/skills/harness/SKILL.md +247 -0
  460. package/skills/harness-setup/SKILL.md +356 -0
  461. package/templates/AGENTS.md +13 -0
  462. package/templates/controller-mode/AGENTS.controller.md +58 -0
  463. package/templates/controller-mode/README.md +44 -0
  464. package/templates/graph.json +22 -0
  465. package/templates/plan-draft.json +35 -0
  466. package/templates/policy.json +28 -0
@@ -0,0 +1,2283 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { roleBinding, executionDigest, HarnessError, WORKSPACE_OWNER, MAX_REPRODUCTIONS, sha256, digestOf, expandGateRefs, policyDigest, graphIssues, selectReviewer, vendorOf, workGraphDigest, } from "../contracts/index.js";
3
+ import { HARNESS_VERSION } from "../package.js";
4
+ import { assertBudget, blockingBudget, budgetOverview, callAttribution, callBudgets, legacyGroupCall, workBudgets, } from "./budget.js";
5
+ import { callDurationMs, callOwner, callRecords, ownerGone } from "./usage.js";
6
+ import { failureFingerprint, repairPolicy } from "./failure.js";
7
+ import { reusableImplementation } from "./reuse.js";
8
+ import { uncoveredGates, unprovenReason } from "../verification/proof.js";
9
+ import { contractDocuments, corpusBindingHolds, effectiveChecks, episodeBasis, orderPropertyProblems, } from "../verification/checks.js";
10
+ import { afterFailure, afterSuccess, blocksClaim, closeIfBasisChanged, } from "./property-recovery.js";
11
+ import { REQUIREMENT_GATE } from "../verification/requirements.js";
12
+ import { pinnedCorpus, propertyProofProblem } from "../verification/acceptance.js";
13
+ import { jointImpact, jointPolicyDigest, jointSpecDigest, publicJoint, sameWorks, } from "../verification/joint.js";
14
+ /** Префикс причины неудавшегося продления: первая причина не затирается следствиями. */
15
+ export const HEARTBEAT_FAILED = 'Продление владения не удалось';
16
+ const iso = (ms) => new Date(ms).toISOString();
17
+ /** Содержание поручения без номера редакции источника: одинаковое содержание — та же работа. */
18
+ const contentDigest = (order) => digestOf({ ...order, source: { connector: order.source.connector, ref: order.source.ref } });
19
+ /**
20
+ * Правила исполнения и технической приёмки. Все решения — внутри одной
21
+ * транзакции хранилища: состояние, на котором решение принято, и запись
22
+ * решения неразделимы. Хост может только добавить запрет (`HostGuards`) и
23
+ * дать основания (`BasisProvider`); снять отказ движка он не может.
24
+ */
25
+ export class Engine {
26
+ host;
27
+ policy;
28
+ version;
29
+ now;
30
+ id;
31
+ /** Digest политики процесса на момент создания движка. */
32
+ loadedPolicy;
33
+ /** Содержимое политики при создании движка: изменение в памяти — отказ применения. */
34
+ loadedContent;
35
+ /** Поколение применённой политики, которое процесс застал при запуске. */
36
+ observedGeneration;
37
+ provenance;
38
+ /** Владелец роли controller, под которым этот процесс её получил. */
39
+ ownLeader;
40
+ recordOnLead;
41
+ constructor(options) {
42
+ this.host = options.host;
43
+ this.policy = options.policy;
44
+ this.version = options.version ?? HARNESS_VERSION;
45
+ this.now = options.now ?? Date.now;
46
+ this.id = options.id ?? randomUUID;
47
+ this.provenance = options.provenance ?? (() => undefined);
48
+ this.recordOnLead = options.recordPolicyOnLead !== false;
49
+ this.loadedContent = policyDigest(this.policy);
50
+ this.loadedPolicy = options.policyIdentity ?? this.loadedContent;
51
+ this.observedGeneration = this.host.store.read((v) => v.control().appliedPolicy?.generation ?? 0);
52
+ }
53
+ /** Часы движка: по ним считаются сроки владения. */
54
+ clock() {
55
+ return this.now();
56
+ }
57
+ /** Версия проверок поручения: формула хоста, если он её задал, иначе harness. */
58
+ checksOf(work, view) {
59
+ const policy = this.host.basis.policyDigest(work, view);
60
+ return this.host.basis.checksDigest?.(work, policy, view) ?? effectiveChecks(work, policy);
61
+ }
62
+ /**
63
+ * Основание эпизода разбора по свойству: формула хоста, если он её задал,
64
+ * иначе harness. Хост с принятой историей держит свою — ею подписаны его
65
+ * прежние эпизоды и попытки, и они не закрываются как «новое основание».
66
+ */
67
+ episodeOf(work, view) {
68
+ return this.host.basis.episodeBasis?.(work, view) ?? episodeBasis(work);
69
+ }
70
+ tx(kind, fn) {
71
+ return this.host.store.transact(kind, fn);
72
+ }
73
+ repository(id) {
74
+ const repo = this.policy.repositories.find((r) => r.id === id);
75
+ if (!repo)
76
+ throw new HarnessError('INVALID_INPUT', 'Репозиторий не объявлен: ' + id);
77
+ return repo;
78
+ }
79
+ read(fn) {
80
+ return this.host.store.read(fn);
81
+ }
82
+ /* ---------------------------------------------------------------- */
83
+ /* Граф и согласование */
84
+ /* ---------------------------------------------------------------- */
85
+ /**
86
+ * Регистрация графа. Повтор той же редакции источника с тем же digest —
87
+ * продолжение прежней работы; другой digest той же редакции или того же
88
+ * ID графа — `REVISION_CONFLICT`. Предпосылки должны быть подтверждены:
89
+ * `engine` — успешной попыткой этого хранилища с тем же result SHA,
90
+ * `trusted` — решением источника (`trusted`), переданным вызывающим вместе
91
+ * с проверкой доступности SHA в target ref (`reachable`).
92
+ */
93
+ register(graph, prerequisites) {
94
+ const issues = graphIssues(graph);
95
+ if (issues.length)
96
+ throw new HarnessError(issues[0].code, `Граф отклонён: ${issues.length} нарушений`, issues.map(({ path, message }) => ({ path: ['graph', ...path], message })));
97
+ const digest = workGraphDigest(graph);
98
+ const key = digestOf([graph.source.connector, graph.source.ref, graph.source.revision]);
99
+ return this.tx('graph.registered', (tx) => {
100
+ const known = tx.local('run-keys', WORKSPACE_OWNER, key);
101
+ const existing = tx.graph(graph.id);
102
+ if (known && known.digest !== digest)
103
+ throw new HarnessError('REVISION_CONFLICT', `Редакция ${graph.source.revision} источника ${graph.source.ref} уже зарегистрирована с другим содержанием`);
104
+ if (existing?.digest === digest)
105
+ return { graph: existing, resumed: true };
106
+ // Новая редакция графа заменяет прежнюю, только пока у него нет активных
107
+ // попыток. Принятые поручения с неизменной постановкой остаются принятыми;
108
+ // изменённые и новые — черновики до нового согласования; история попыток
109
+ // не переписывается.
110
+ if (existing && tx.works(graph.id).some((w) => w.activeRunId))
111
+ throw new HarnessError('REVISION_CONFLICT', `У графа ${graph.id} есть активные попытки; новая редакция подождёт их`);
112
+ for (const p of graph.prerequisites) {
113
+ const ok = p.receipt.kind === 'engine'
114
+ ? tx
115
+ .attempts()
116
+ .some((a) => a.id === p.receipt.runId &&
117
+ a.status === 'succeeded' &&
118
+ a.integrationSha === p.resultSha)
119
+ : prerequisites.trusted(p);
120
+ if (!ok || !prerequisites.reachable(p))
121
+ throw new HarnessError('NOT_READY', `Предпосылка ${p.id} не подтверждена: нужен результат движка или доверенный receipt с доступным SHA`);
122
+ }
123
+ const at = iso(this.now());
124
+ const state = {
125
+ id: graph.id,
126
+ digest,
127
+ graph,
128
+ policyDigest: executionDigest(this.policy),
129
+ registeredAt: at,
130
+ };
131
+ tx.putGraph(state);
132
+ for (const order of graph.orders) {
133
+ const prior = tx.work(order.id);
134
+ if (prior && prior.graphId !== graph.id)
135
+ throw new HarnessError('REVISION_CONFLICT', `Поручение ${order.id} уже принадлежит другому графу`);
136
+ if (prior?.status === 'done' && contentDigest(prior.order) === contentDigest(order))
137
+ continue;
138
+ // Принятая версия корпуса остаётся за поручением, пока среди его
139
+ // договоров есть договор этого корпуса с тем же нормативным основанием; эпизод восстановления и его история — тоже: закрывает их
140
+ // согласование нового основания, а не новая редакция источника.
141
+ const corpus = prior?.checkVersion &&
142
+ corpusBindingHolds(tx
143
+ .locals('check-suites')
144
+ .map((x) => x.value)
145
+ .find((x) => x.id === prior.checkVersion.suite), contractDocuments(order, tx), this.host.basis.suiteBasis && ((c) => this.host.basis.suiteBasis(c)))
146
+ ? prior.checkVersion
147
+ : undefined;
148
+ tx.putWork({
149
+ id: order.id,
150
+ graphId: graph.id,
151
+ order,
152
+ status: 'draft',
153
+ attempt: prior?.attempt ?? 0,
154
+ ...(corpus ? { checkVersion: corpus } : {}),
155
+ ...(prior?.recovery ? { recovery: prior.recovery } : {}),
156
+ ...(prior?.recoveryHistory ? { recoveryHistory: prior.recoveryHistory } : {}),
157
+ // Удержание операции принадлежит ей: новая редакция источника его не
158
+ // снимает — только release или передача владельцем.
159
+ ...(prior?.hold ? { hold: prior.hold } : {}),
160
+ });
161
+ }
162
+ for (const prior of existing ? tx.works(graph.id) : [])
163
+ if (!graph.orders.some((o) => o.id === prior.id) && prior.status !== 'done')
164
+ tx.putWork({ ...prior, status: 'cancelled', activeRunId: undefined });
165
+ tx.putLocal('run-keys', WORKSPACE_OWNER, key, { graphId: graph.id, digest, at });
166
+ tx.emit({
167
+ type: 'graph.registered',
168
+ graphId: graph.id,
169
+ payload: { digest, orders: graph.orders.length, source: graph.source },
170
+ });
171
+ return { graph: state, resumed: false, replaced: Boolean(existing) };
172
+ });
173
+ }
174
+ /** Раунд технического ревью плана или контракта сохраняется в истории предмета. */
175
+ /**
176
+ * `document` — документ контракта, который ревью рассматривало: он
177
+ * сохраняется по своему digest, и из него движок берёт договор проверки.
178
+ */
179
+ /**
180
+ * `historyRounds` — раунды предмета, проведённые хостом до harness
181
+ * (`TechnicalReviewInput.history`): первый раунд движка следует за ними, и
182
+ * дальше нумерация идёт подряд от него.
183
+ */
184
+ recordReview(record, document, historyRounds = 0) {
185
+ if (document && (record.kind !== 'contract' || digestOf(document) !== record.digest))
186
+ throw new HarnessError('INVALID_INPUT', 'Документ не соответствует ревью контракта');
187
+ return this.tx('graph.reviewed', (tx) => {
188
+ if (document)
189
+ tx.putLocal('contract-documents', WORKSPACE_OWNER, record.digest, document);
190
+ const previous = tx
191
+ .locals('reviews', WORKSPACE_OWNER)
192
+ .map((r) => r.value)
193
+ .filter((r) => r.kind === record.kind && r.subject === record.subject);
194
+ const offset = previous.length
195
+ ? Math.min(...previous.map((r) => r.round)) - 1
196
+ : historyRounds;
197
+ if (record.round !== offset + previous.length + 1)
198
+ throw new HarnessError('INVALID_INPUT', `Раунд ${record.round} не следует за ${offset + previous.length}`);
199
+ tx.putLocal('reviews', WORKSPACE_OWNER, record.id, record);
200
+ tx.emit({
201
+ type: 'graph.reviewed',
202
+ graphId: record.kind === 'plan' ? record.subject : undefined,
203
+ payload: {
204
+ kind: record.kind,
205
+ subject: record.subject,
206
+ digest: record.digest,
207
+ round: record.round,
208
+ approved: record.approved,
209
+ open: record.findings.filter((f) => f.status === 'open').length,
210
+ },
211
+ });
212
+ return record;
213
+ });
214
+ }
215
+ reviews(kind, subject) {
216
+ return this.read((v) => v
217
+ .locals('reviews', WORKSPACE_OWNER)
218
+ .map((r) => r.value)
219
+ .filter((r) => r.kind === kind && r.subject === subject)
220
+ .sort((a, b) => a.round - b.round));
221
+ }
222
+ /**
223
+ * Digest назначения reviewer вида `kind` для автора по текущей политике:
224
+ * runtime, модель, effort, содержимое профиля и правило вендора. Раунд ревью
225
+ * подтверждает предмет только при том же назначении.
226
+ */
227
+ reviewerBinding(kind, author) {
228
+ const choice = selectReviewer(this.policy, kind, { runtime: author });
229
+ if (!choice.ok)
230
+ return undefined;
231
+ // Содержимое профиля, а не только его имя: другой набор инструментов —
232
+ // другое назначение.
233
+ const profile = choice.reviewer.toolProfile;
234
+ return digestOf({
235
+ reviewer: choice.reviewer,
236
+ vendor: this.policy.review[kind].vendor,
237
+ ...(profile ? { tools: this.policy.toolProfiles[profile] ?? null } : {}),
238
+ });
239
+ }
240
+ /**
241
+ * Контракты поручения: последний раунд ревью каждого контракта — его digest,
242
+ * одобрен, при текущем назначении reviewer; у хоста с портом `contracts` —
243
+ * редакция этого digest согласована хостом. Иначе поручение не выдаётся и не
244
+ * принимается.
245
+ */
246
+ contractBlocker(work, view) {
247
+ for (const ref of work.order.contracts) {
248
+ // Хост, ведущий согласование контрактов сам, подтверждает редакцию по digest.
249
+ if (this.host.contracts) {
250
+ const refusal = this.host.contracts.approved(ref, view);
251
+ if (refusal)
252
+ return refusal.message;
253
+ continue;
254
+ }
255
+ const last = view
256
+ .locals('reviews', WORKSPACE_OWNER)
257
+ .map((r) => r.value)
258
+ .filter((r) => r.kind === 'contract' && r.subject === ref.id)
259
+ .sort((a, b) => a.round - b.round)
260
+ .at(-1);
261
+ if (!last)
262
+ return `Контракт ${ref.id} не проходил технического ревью`;
263
+ if (last.digest !== ref.digest)
264
+ return `Контракт ${ref.id}: последнее ревью относится к другому digest`;
265
+ if (!last.approved)
266
+ return `Контракт ${ref.id}: последний раунд ревью не одобрил его`;
267
+ if (last.reviewerBinding !== this.reviewerBinding('contract', last.authorRuntime))
268
+ return `Контракт ${ref.id}: ревью проведено при другом назначении reviewer`;
269
+ }
270
+ return undefined;
271
+ }
272
+ /**
273
+ * Согласование графа. Привязано к digest проверенного предложения: в
274
+ * режиме `agent` нужен одобренный последний раунд ревью этого digest, в
275
+ * режиме `operator` — проведённое ревью этого digest и решение оператора.
276
+ * Другого способа сделать поручения готовыми к выдаче нет.
277
+ */
278
+ approve(graphId, actor, options = {}) {
279
+ return this.tx('graph.approved', (tx) => {
280
+ this.assertCurrentPolicy(tx);
281
+ const graph = tx.graph(graphId);
282
+ if (!graph)
283
+ throw new HarnessError('NOT_FOUND', 'Граф не найден: ' + graphId);
284
+ if (actor !== this.policy.approvalMode)
285
+ throw new HarnessError('APPROVAL_REQUIRED', `Политика требует согласования ${this.policy.approvalMode === 'operator' ? 'оператором' : 'агентом-ревьюером'}`);
286
+ const rounds = tx
287
+ .locals('reviews', WORKSPACE_OWNER)
288
+ .map((r) => r.value)
289
+ .filter((r) => r.kind === 'plan' && r.subject === graphId)
290
+ .sort((a, b) => a.round - b.round);
291
+ const last = rounds.at(-1);
292
+ if (!last || last.digest !== graph.digest)
293
+ throw new HarnessError('APPROVAL_REQUIRED', 'Нет ревью плана для текущего digest графа');
294
+ if (actor === 'agent' && !last.approved)
295
+ throw new HarnessError('REVIEW_REJECTED', 'Последний раунд ревью плана не одобрил граф');
296
+ if (last.reviewerBinding !== this.reviewerBinding('plan', last.authorRuntime))
297
+ throw new HarnessError('APPROVAL_REQUIRED', 'Ревью плана проведено при другом назначении reviewer; нужен новый раунд');
298
+ // Свойства поручений существуют в их договорах проверки и исполняются
299
+ // их генеративными gates: иначе ожидаемая проверка не определена.
300
+ const problems = tx.works(graphId).flatMap((w) => {
301
+ const repo = this.repository(w.order.repositoryId);
302
+ return orderPropertyProblems(w.order, contractDocuments(w.order, tx), {
303
+ configured: repo.gates,
304
+ ...(w.order.gates ? { scope: expandGateRefs(repo, w.order.gates) } : {}),
305
+ });
306
+ });
307
+ if (problems.length)
308
+ throw new HarnessError('INVALID_INPUT', 'Договор проверки поручений не согласован: ' + problems.join('; '));
309
+ const policy = executionDigest(this.policy);
310
+ const context = options.bindContext ? { digest: last.contextDigest ?? null } : undefined;
311
+ if (graph.approval?.digest === graph.digest &&
312
+ graph.policyDigest === policy &&
313
+ graph.approval.context?.digest === context?.digest)
314
+ return { graph, changed: false };
315
+ const at = iso(this.now());
316
+ const approval = {
317
+ actor,
318
+ digest: graph.digest,
319
+ authorRuntime: last.authorRuntime === 'external' ? undefined : last.authorRuntime,
320
+ reviewerRuntime: last.reviewerRuntime,
321
+ artifact: last.artifact,
322
+ ...(context ? { context } : {}),
323
+ };
324
+ tx.putGraph({ ...graph, policyDigest: policy, approval: { ...approval, at } });
325
+ tx.emit({ type: 'graph.approved', graphId, payload: { digest: graph.digest, actor } });
326
+ for (const work of tx.works(graphId)) {
327
+ if (work.status !== 'draft')
328
+ continue;
329
+ const ready = structuredClone({
330
+ ...work,
331
+ status: 'ready',
332
+ approvedAt: at,
333
+ approvedDigest: this.host.basis.orderDigest(work, tx),
334
+ approvedScope: this.host.basis.scopeDigest(work, tx),
335
+ approval,
336
+ });
337
+ if (closeIfBasisChanged(ready, at, this.episodeOf(ready, tx)))
338
+ this.recoveryEvent(tx, ready, ready.recoveryHistory.at(-1));
339
+ tx.putWork(ready);
340
+ tx.emit({
341
+ type: 'work.ready',
342
+ graphId,
343
+ workId: work.id,
344
+ payload: { orderDigest: ready.approvedDigest },
345
+ });
346
+ }
347
+ return { graph: tx.graph(graphId), changed: true };
348
+ });
349
+ }
350
+ /* ---------------------------------------------------------------- */
351
+ /* Controller и очередь */
352
+ /* ---------------------------------------------------------------- */
353
+ /**
354
+ * Роль принадлежит этому процессу: тот же владелец и та же версия движка
355
+ * (роль прежней версии под тем же именем держит другой процесс); живая,
356
+ * если не `expired`.
357
+ */
358
+ mine(lease, owner, expired = false) {
359
+ return (!!lease &&
360
+ lease.owner === owner &&
361
+ lease.engineVersion === this.version &&
362
+ (expired || lease.leaseUntil > this.now()));
363
+ }
364
+ /** Захват или продление роли единственного controller. */
365
+ lead(owner) {
366
+ let acquired = false;
367
+ const result = this.tx('heartbeat', (tx) => {
368
+ const lease = tx.controller();
369
+ const live = !!lease && lease.leaseUntil > this.now();
370
+ if (live && lease.owner !== owner)
371
+ return false;
372
+ // Живая роль другой версии движка — другой процесс, даже под тем же
373
+ // именем владельца: роль переходит только после истечения срока.
374
+ if (live && lease.engineVersion !== this.version)
375
+ return false;
376
+ acquired = !live || lease.owner !== owner;
377
+ tx.setController({
378
+ owner,
379
+ leaseUntil: this.now() + this.policy.leaseMs,
380
+ engineVersion: this.version,
381
+ });
382
+ return true;
383
+ });
384
+ if (result)
385
+ this.ownLeader = owner;
386
+ if (result && acquired) {
387
+ this.tx('scheduler.started', (tx) => tx.emit({ type: 'controller.acquired', payload: { owner } }));
388
+ if (this.recordOnLead)
389
+ this.recordPolicy(owner);
390
+ }
391
+ return result;
392
+ }
393
+ release(owner) {
394
+ return this.tx('scheduler.released', (tx) => {
395
+ // Роль прежней версии под тем же именем держит другой процесс.
396
+ if (!this.mine(tx.controller(), owner, true))
397
+ return false;
398
+ tx.setController(undefined);
399
+ tx.emit({ type: 'controller.released', payload: { owner } });
400
+ return true;
401
+ });
402
+ }
403
+ /**
404
+ * Пауза оператора или штатной остановки: новые claims запрещены (семантика
405
+ * DevContour `pause`). Штатная остановка поверх существующей паузы её не
406
+ * подменяет, кроме паузы операции reconfigure. Пауза оператора — решение
407
+ * человека: она заменяет любую паузу, и классы отказов прежней паузы с ней
408
+ * не переживают.
409
+ */
410
+ pause(reason) {
411
+ return this.tx('scheduler.paused', (tx) => {
412
+ const control = tx.control();
413
+ if (control.paused && reason === 'shutdown' && control.pauseReason !== 'reconfigure')
414
+ return { control, changed: false };
415
+ // Повторная пауза человека — его новое решение: время паузы обновляется.
416
+ // Хост сравнивает его с началом своей работы (пауза до старта снимается
417
+ // циклом, после — нет), и сохранённое прежнее время выдало бы свежее
418
+ // решение за давнее.
419
+ const next = {
420
+ ...control,
421
+ paused: true,
422
+ pauseReason: reason,
423
+ pausedAt: iso(this.now()),
424
+ pauseOperation: undefined,
425
+ pauseFailures: undefined,
426
+ };
427
+ tx.setControl(next);
428
+ tx.emit({ type: 'control.paused', payload: { reason } });
429
+ return { control: next, changed: true };
430
+ });
431
+ }
432
+ /**
433
+ * Снять паузу — решение человека (семантика DevContour `pause(false)`):
434
+ * снимает паузу оператора, штатной остановки и отказа runtime вместе с её
435
+ * классами отказов. Паузу операции reconfigure снимает только сама
436
+ * операция: `PAUSED`.
437
+ */
438
+ resume() {
439
+ return this.tx('scheduler.started', (tx) => {
440
+ const control = tx.control();
441
+ if (!control.paused)
442
+ return { control, changed: false };
443
+ if (control.pauseReason === 'reconfigure')
444
+ throw new HarnessError('PAUSED', 'Выдачу держит операция применения политики; её снимает сама операция');
445
+ const reason = control.pauseReason ?? 'operator';
446
+ const next = {
447
+ ...control,
448
+ paused: false,
449
+ pauseReason: undefined,
450
+ pausedAt: undefined,
451
+ pauseOperation: undefined,
452
+ pauseFailures: undefined,
453
+ waits: control.waits?.filter((w) => w.kind !== 'base-check'),
454
+ };
455
+ if (!next.waits?.length)
456
+ delete next.waits;
457
+ tx.setControl(next);
458
+ tx.emit({ type: 'control.resumed', payload: { reason } });
459
+ return { control: next, changed: true };
460
+ });
461
+ }
462
+ /** Снять паузу отказа после устранения причины: только названные классы. */
463
+ clearFailure(kinds) {
464
+ return this.tx('scheduler.started', (tx) => {
465
+ const control = tx.control();
466
+ const left = (control.pauseFailures ?? []).filter((k) => !kinds.includes(k));
467
+ if (left.length === (control.pauseFailures ?? []).length)
468
+ return control;
469
+ const unpause = !left.length && control.pauseReason === 'runtime';
470
+ const next = {
471
+ ...control,
472
+ pauseFailures: left.length ? left : undefined,
473
+ ...(unpause ? { paused: false, pauseReason: undefined, pausedAt: undefined } : {}),
474
+ };
475
+ tx.setControl(next);
476
+ if (unpause)
477
+ tx.emit({ type: 'control.resumed', payload: { reason: 'runtime' } });
478
+ return next;
479
+ });
480
+ }
481
+ /* ---------------------------------------------------------------- */
482
+ /* Бюджеты и учёт вызовов */
483
+ /* ---------------------------------------------------------------- */
484
+ /** Правила и области бюджетов: политика движка и группы хоста. */
485
+ budgetContext() {
486
+ return { policy: this.policy, scopes: this.host.budgets };
487
+ }
488
+ /**
489
+ * Бюджетное удержание готовых поручений. Бюджеты считаются по сохранённым
490
+ * записям вызовов: сброс попыток и перезапуск их не уменьшают. Удержанное
491
+ * поручение несёт причину, пока бюджет не позволит снова; выключенные
492
+ * бюджеты удержание снимают.
493
+ */
494
+ budgetBlocks(tx) {
495
+ const ready = tx.works().filter((w) => w.status === 'ready');
496
+ if (!this.policy.budgets) {
497
+ for (const w of ready)
498
+ if (w.budgetBlock)
499
+ tx.putWork({ ...w, budgetBlock: undefined });
500
+ return;
501
+ }
502
+ const c = this.budgetContext();
503
+ const records = callRecords(tx);
504
+ for (const w of ready) {
505
+ const blocking = blockingBudget(c, workBudgets(c, tx, w.id, records));
506
+ if (!blocking) {
507
+ if (w.budgetBlock)
508
+ tx.putWork({ ...w, budgetBlock: undefined });
509
+ continue;
510
+ }
511
+ if (w.budgetBlock?.reason === blocking.reason)
512
+ continue;
513
+ tx.putWork({ ...w, budgetBlock: { reason: blocking.reason, at: iso(this.now()) } });
514
+ tx.emit({
515
+ type: 'budget.blocked',
516
+ graphId: w.graphId,
517
+ workId: w.id,
518
+ payload: {
519
+ scope: blocking.scope.kind,
520
+ ...(blocking.scope.id ? { scopeId: blocking.scope.id } : {}),
521
+ state: blocking.state,
522
+ reason: blocking.reason.slice(0, 4000),
523
+ },
524
+ });
525
+ }
526
+ }
527
+ /**
528
+ * Начало вызова модели: атрибуция на момент вызова и проверка бюджетов — в
529
+ * одной транзакции с регистрацией идущего вызова. Превышенный или
530
+ * неопределённый бюджет — отказ `budget` до вызова, без записи; два процесса
531
+ * не проходят проверку оба, не видя друг друга. Процесс не с применённой
532
+ * политикой — отказ `APPROVAL_STALE` до вызова.
533
+ */
534
+ beginCall(record, meta) {
535
+ return this.tx('usage.recorded', (tx) => {
536
+ // Барьер применённой политики — на границе каждого нового вызова, в той
537
+ // же транзакции: процесс, чью политику сменили (например, понизили
538
+ // бюджет), не начинает вызовов по прежним пределам. Идущий вызов
539
+ // завершается, но разрешением нового он не служит.
540
+ const stale = this.staleReason(tx);
541
+ if (stale)
542
+ throw new HarnessError('APPROVAL_STALE', stale);
543
+ const c = this.budgetContext();
544
+ const started = { ...record, ...callAttribution(c, tx, meta) };
545
+ if (this.policy.budgets)
546
+ assertBudget(c, callBudgets(c, tx, meta, callRecords(tx)));
547
+ tx.putLocal('usage', callOwner(started), started.id, started);
548
+ return started;
549
+ });
550
+ }
551
+ /** Ход или итог вызова: запись заменяется целиком. */
552
+ saveCall(record) {
553
+ this.tx('usage.recorded', (tx) => tx.putLocal('usage', callOwner(record), record.id, record));
554
+ }
555
+ /**
556
+ * Закрывает записи вызовов, чей процесс умер, исходом `abandoned`. Запись
557
+ * без процесса закрывается, когда её попытка уже не активна, а без попытки —
558
+ * спустя два предела времени вызова. Под транзакцией запись перечитывается:
559
+ * вызов мог завершиться между сканированием и закрытием, и его исход и
560
+ * стоимость не затираются устаревшим снимком.
561
+ */
562
+ abandonCalls(at = Date.now()) {
563
+ const dead = (r, view) => r.outcome === 'active' &&
564
+ (r.process
565
+ ? ownerGone(r)
566
+ : r.runId
567
+ ? view.attempt(r.runId)?.status !== 'active'
568
+ : at - Date.parse(r.startedAt) > 2 * this.policy.runTimeoutMs);
569
+ const candidates = this.read((v) => callRecords(v).filter((r) => dead(r, v)));
570
+ if (!candidates.length)
571
+ return [];
572
+ return this.tx('usage.recorded', (tx) => {
573
+ const closedIds = [];
574
+ for (const seen of candidates) {
575
+ const r = tx.local('usage', callOwner(seen), seen.id);
576
+ if (!r || !dead(r, tx))
577
+ continue;
578
+ // Время прерванного вызова фиксируется монотонно (часы ОС, сохранённый
579
+ // замер), пока запись ещё идущая; измерить нельзя — время неизвестно,
580
+ // а не берётся по системным часам, которые могли откатиться.
581
+ const elapsed = callDurationMs(r, at);
582
+ tx.putLocal('usage', callOwner(r), r.id, {
583
+ ...r,
584
+ ...(elapsed !== null ? { durationMs: elapsed } : { durationUnknown: true }),
585
+ outcome: 'abandoned',
586
+ abandonedAt: iso(at),
587
+ });
588
+ closedIds.push(r.id);
589
+ }
590
+ return closedIds;
591
+ });
592
+ }
593
+ /**
594
+ * Закрепляет атрибуцию прежних записей вызовов (без закреплённых поручения и
595
+ * группы) по текущему составу — до того, как новая редакция графа его
596
+ * изменит: иначе перенос поручения снял бы или разделил учтённый расход
597
+ * группы. Уже закреплённое не меняется; запись перечитывается под
598
+ * транзакцией.
599
+ */
600
+ pinLegacyCalls() {
601
+ const unpinned = (r) => !r.workIds && (!r.workId || !r.groupId);
602
+ const legacy = this.read((v) => callRecords(v).filter(unpinned));
603
+ if (!legacy.length)
604
+ return 0;
605
+ return this.tx('usage.recorded', (tx) => {
606
+ let pinned = 0;
607
+ for (const seen of legacy) {
608
+ const r = tx.local('usage', callOwner(seen), seen.id);
609
+ if (!r || !unpinned(r))
610
+ continue;
611
+ const found = this.host.budgets.legacy(r, tx);
612
+ if (!(r.groupId ?? found.groupId))
613
+ continue;
614
+ const next = { ...r, groupId: r.groupId ?? found.groupId };
615
+ // Прежний вызов о группе остаётся расходом её участников, даже если
616
+ // хост по совпавшему ID назвал его вызовом поручения.
617
+ const workId = r.workId ?? (legacyGroupCall(r) ? undefined : found.workId);
618
+ if (workId)
619
+ next.workId = workId;
620
+ if (!next.workId && found.workIds)
621
+ next.workIds = found.workIds;
622
+ if (!next.workId && !next.workIds)
623
+ continue;
624
+ tx.putLocal('usage', callOwner(next), next.id, next);
625
+ pinned++;
626
+ }
627
+ return pinned;
628
+ });
629
+ }
630
+ /** Обзор бюджетов для статуса; `undefined` — бюджеты не заданы. */
631
+ budgets() {
632
+ return this.read((v) => budgetOverview(this.budgetContext(), v));
633
+ }
634
+ /**
635
+ * Причина, по которой бюджет не даст выдать поручение при следующем claim, —
636
+ * тот же расчёт, которым claim ставит `budgetBlock` (и до того, как поле
637
+ * записано). Только чтение; бюджеты выключены — `undefined`.
638
+ */
639
+ budgetBlockOf(workId, view) {
640
+ if (!this.policy.budgets)
641
+ return undefined;
642
+ const c = this.budgetContext();
643
+ return blockingBudget(c, workBudgets(c, view, workId, callRecords(view)))?.reason;
644
+ }
645
+ /** Почему поручение сейчас не выдаётся; пусто — может быть выдано. */
646
+ blockers(work, view) {
647
+ const out = [];
648
+ if (view.control().paused)
649
+ out.push({
650
+ code: 'PAUSED',
651
+ message: 'Очередь на паузе: ' + (view.control().pauseReason ?? 'operator'),
652
+ });
653
+ const reconfigure = this.reconfiguring(view);
654
+ if (reconfigure)
655
+ out.push({
656
+ code: 'PAUSED',
657
+ message: `Операция ${reconfigure.operation} применяет политику`,
658
+ });
659
+ const stale = this.staleReason(view);
660
+ if (stale)
661
+ out.push({ code: 'APPROVAL_STALE', message: stale });
662
+ if (this.liveJoint(view))
663
+ out.push({ code: 'NOT_READY', message: 'Идёт совместная проверка репозиториев' });
664
+ if (work.status === 'draft')
665
+ out.push({ code: 'APPROVAL_REQUIRED', message: 'Граф не согласован' });
666
+ const graph = view.graph(work.graphId);
667
+ if (graph?.approval && graph.policyDigest !== executionDigest(this.policy))
668
+ out.push({
669
+ code: 'APPROVAL_STALE',
670
+ message: 'Политика изменилась после согласования; согласуйте заново',
671
+ });
672
+ else if (work.status !== 'ready')
673
+ out.push({ code: 'NOT_READY', message: 'Статус ' + work.status });
674
+ for (const dep of work.order.dependsOn) {
675
+ const d = view.work(dep);
676
+ const external = view.graph(work.graphId)?.graph.prerequisites.some((p) => p.id === dep);
677
+ if (!external && d?.status !== 'done')
678
+ out.push({ code: 'NOT_READY', message: 'Ждёт ' + dep });
679
+ }
680
+ if (work.attempt >= this.policy.maxAttempts)
681
+ out.push({
682
+ code: 'ATTEMPTS_EXHAUSTED',
683
+ message: `Исчерпано ${work.attempt} из ${this.policy.maxAttempts} попыток`,
684
+ });
685
+ if (work.hold)
686
+ out.push({ code: 'NOT_READY', message: 'Удержано операцией ' + work.hold.operation });
687
+ // Записанный budgetBlock — кэш расчёта claim: готовую работу держит текущий расчёт.
688
+ const budget = work.status === 'ready' ? this.budgetBlockOf(work.id, view) : undefined;
689
+ if (budget)
690
+ out.push({ code: 'BUDGET_EXHAUSTED', message: budget });
691
+ if (blocksClaim(work))
692
+ out.push({
693
+ code: 'NOT_READY',
694
+ message: `Разбор свойства ${work.recovery.property}: ${work.recovery.reason ?? work.recovery.status}`,
695
+ });
696
+ if (this.awaitsOperator(work, view))
697
+ out.push({
698
+ code: 'APPROVAL_REQUIRED',
699
+ message: 'Принятие версии корпуса ждёт подтверждения оператора',
700
+ });
701
+ if (work.status === 'ready' && work.approvedDigest !== this.host.basis.orderDigest(work, view))
702
+ out.push({ code: 'APPROVAL_STALE', message: 'Постановка изменилась после согласования' });
703
+ const contract = this.contractBlocker(work, view);
704
+ if (contract)
705
+ out.push({ code: 'APPROVAL_REQUIRED', message: contract });
706
+ const reviewer = this.reviewerBlocker(work);
707
+ if (reviewer)
708
+ out.push(reviewer);
709
+ const refusal = this.host.guards.claimable(work, view);
710
+ if (refusal)
711
+ out.push(refusal);
712
+ return out;
713
+ }
714
+ /**
715
+ * Назначение ревью кода для роли поручения недопустимо политикой (reviewer
716
+ * того же вендора без явного разрешения, нет reviewer или роли). Такое
717
+ * поручение не выдаётся и видно блокером; остальная очередь идёт дальше.
718
+ */
719
+ reviewerBlocker(work) {
720
+ const role = roleBinding(this.policy, work.order.role, work.order.repositoryId);
721
+ if (!role)
722
+ return { code: 'INVALID_INPUT', message: 'Роль не объявлена: ' + work.order.role };
723
+ const reviewer = selectReviewer(this.policy, 'code', role.writer, work.order.role, work.order.repositoryId);
724
+ return reviewer.ok ? undefined : { code: reviewer.code, message: reviewer.message };
725
+ }
726
+ /**
727
+ * Выдать следующую готовую работу. Только действующий controller; не на
728
+ * паузе; не сверх `concurrency`; первое готовое поручение в порядке
729
+ * регистрации. Поручение с согласованием, не совпадающим с текущим
730
+ * основанием, — отказ `APPROVAL_STALE`, а не выдача.
731
+ */
732
+ claim(owner) {
733
+ return this.tx('run.claimed', (tx) => {
734
+ const lease = tx.controller();
735
+ if (!this.mine(lease, owner))
736
+ throw new HarnessError('CONTROLLER_BUSY', 'Выдавать попытки может только действующий controller');
737
+ if (tx.control().paused || this.host.guards.claimBarrier(tx))
738
+ return undefined;
739
+ // Пока операция применяет политику, попытки не выдаются, даже если
740
+ // человек снял паузу: попытка под прежней политикой не нужна.
741
+ if (this.reconfiguring(tx))
742
+ return undefined;
743
+ // Процесс с не применённой политикой не выдаёт: условия попытки
744
+ // разошлись бы с применёнными.
745
+ if (this.policyStale(tx))
746
+ return undefined;
747
+ // Идущая совместная проверка закрепила комбинацию SHA: новые попытки
748
+ // сдвинули бы target ref под ней.
749
+ if (this.liveJoint(tx))
750
+ return undefined;
751
+ const active = tx.attempts().filter((a) => a.status === 'active');
752
+ if (active.length >= this.policy.concurrency)
753
+ return undefined;
754
+ this.budgetBlocks(tx);
755
+ for (const ready of tx.works().filter((w) => w.status === 'ready' && w.recovery)) {
756
+ const next = structuredClone(ready);
757
+ if (closeIfBasisChanged(next, iso(this.now()), this.episodeOf(next, tx))) {
758
+ tx.putWork(next);
759
+ this.recoveryEvent(tx, next, next.recoveryHistory.at(-1));
760
+ }
761
+ }
762
+ const eligible = tx.works().filter((w) => {
763
+ if (w.status !== 'ready' || w.hold || w.budgetBlock)
764
+ return false;
765
+ // Два содержательных отказа по одному свойству: третья выдача — только
766
+ // после разбора. Принятие корпуса, ждущее оператора, удерживает выдачу.
767
+ if (blocksClaim(w) || this.awaitsOperator(w, tx))
768
+ return false;
769
+ if (w.attempt >= this.policy.maxAttempts)
770
+ return false;
771
+ const graph = tx.graph(w.graphId);
772
+ // Согласование привязано к graph digest и к политике, под которой оно дано.
773
+ if (!graph?.approval || graph.approval.digest !== graph.digest)
774
+ return false;
775
+ if (graph.policyDigest !== executionDigest(this.policy))
776
+ return false;
777
+ const external = new Set(graph.graph.prerequisites.map((p) => p.id));
778
+ if (!w.order.dependsOn.every((d) => external.has(d) || tx.work(d)?.status === 'done'))
779
+ return false;
780
+ // Контракты поручения согласованы ревью своего digest при текущем назначении reviewer.
781
+ if (this.contractBlocker(w, tx))
782
+ return false;
783
+ // Недопустимое назначение reviewer держит только это поручение.
784
+ if (this.reviewerBlocker(w))
785
+ return false;
786
+ return !this.host.guards.claimable(w, tx);
787
+ });
788
+ const work = eligible[0];
789
+ if (!work)
790
+ return undefined;
791
+ if (work.approvedDigest !== this.host.basis.orderDigest(work, tx))
792
+ throw new HarnessError('APPROVAL_STALE', `Постановка ${work.id} изменилась после согласования`);
793
+ if (work.approvedScope && work.approvedScope !== this.host.basis.scopeDigest(work, tx))
794
+ throw new HarnessError('APPROVAL_STALE', `Область проверок ${work.id} изменилась после согласования`);
795
+ const current = this.host.guards.current(work, undefined, tx);
796
+ if (current)
797
+ throw new HarnessError(current.code, current.message);
798
+ const role = roleBinding(this.policy, work.order.role, work.order.repositoryId);
799
+ if (!role)
800
+ throw new HarnessError('INVALID_INPUT', 'Роль не объявлена: ' + work.order.role);
801
+ const reviewer = selectReviewer(this.policy, 'code', role.writer, work.order.role, work.order.repositoryId);
802
+ if (!reviewer.ok)
803
+ throw new HarnessError(reviewer.code, reviewer.message);
804
+ const repo = this.policy.repositories.find((r) => r.id === work.order.repositoryId);
805
+ if (!repo)
806
+ throw new HarnessError('INVALID_INPUT', 'Репозиторий не объявлен: ' + work.order.repositoryId);
807
+ const candidates = eligible.map((w) => ({
808
+ taskId: w.id,
809
+ repositoryId: w.order.repositoryId,
810
+ attempt: w.attempt,
811
+ }));
812
+ const at = this.now();
813
+ const ready = work.approvedAt ? this.host.readyAt?.(work, tx) : undefined;
814
+ const attempt = {
815
+ id: this.id(),
816
+ workId: work.id,
817
+ repositoryId: work.order.repositoryId,
818
+ attempt: work.attempt + 1,
819
+ token: this.id() + this.id(),
820
+ owner,
821
+ runtime: role.writer.runtime,
822
+ reviewer: reviewer.reviewer.runtime,
823
+ ...(role.writer.model ? { model: role.writer.model } : {}),
824
+ ...(reviewer.reviewer.model ? { reviewerModel: reviewer.reviewer.model } : {}),
825
+ ...(role.writer.effort ? { effort: role.writer.effort } : {}),
826
+ ...(reviewer.reviewer.effort ? { reviewerEffort: reviewer.reviewer.effort } : {}),
827
+ policyDigest: this.host.basis.policyDigest(work, tx),
828
+ status: 'active',
829
+ phase: 'running',
830
+ startedAt: iso(at),
831
+ leaseUntil: at + this.policy.leaseMs,
832
+ requiredGates: [
833
+ ...expandGateRefs(repo, work.order.gates),
834
+ ...(work.order.requirements.length ? [REQUIREMENT_GATE] : []),
835
+ ],
836
+ // Проверки потребителей закрепляются раскрытыми: смена групп
837
+ // потребителя после выдачи не меняет состав, который доказывает попытка.
838
+ ...(work.order.consumers?.length
839
+ ? {
840
+ consumers: work.order.consumers.map((c) => ({
841
+ repositoryId: c.repositoryId,
842
+ gates: expandGateRefs(this.repository(c.repositoryId), c.gates),
843
+ })),
844
+ }
845
+ : {}),
846
+ pinned: {
847
+ graphId: work.graphId,
848
+ graphDigest: tx.graph(work.graphId).digest,
849
+ orderDigest: digestOf(work.order),
850
+ targetRef: repo.targetRef,
851
+ source: work.order.source,
852
+ },
853
+ dispatch: {
854
+ policy: 'fifo-ready-v1',
855
+ at: iso(at),
856
+ eligible: candidates,
857
+ activeCount: active.length,
858
+ concurrency: this.policy.concurrency,
859
+ inputDigest: digestOf(candidates),
860
+ },
861
+ ...(work.approvedAt
862
+ ? {
863
+ wait: {
864
+ approvedAt: work.approvedAt,
865
+ ...(ready ? { readyAt: ready } : {}),
866
+ },
867
+ }
868
+ : {}),
869
+ engineVersion: this.version,
870
+ ...(this.host.consumerVersion ? { consumerVersion: this.host.consumerVersion } : {}),
871
+ // Версия проверок закрепляется при выдаче: принятие нового корпуса
872
+ // посередине попытки ждёт её окончания, и evidence этой попытки
873
+ // относится к этой версии.
874
+ checks: {
875
+ effective: this.checksOf(work, tx),
876
+ ...(work.checkVersion ? { corpus: work.checkVersion } : {}),
877
+ },
878
+ episodeBasis: this.episodeOf(work, tx),
879
+ callsRecorded: true,
880
+ evidence: [],
881
+ };
882
+ tx.putAttempt(attempt);
883
+ const recovery = work.recovery?.status === 'retry'
884
+ ? {
885
+ ...structuredClone(work.recovery),
886
+ // Разрешённый разбором повтор выдан: второй раз он не выдаётся.
887
+ status: 'retrying',
888
+ retryRun: attempt.id,
889
+ version: work.recovery.version + 1,
890
+ history: [
891
+ ...work.recovery.history,
892
+ { at: iso(at), event: 'retry-claimed', detail: attempt.id },
893
+ ],
894
+ }
895
+ : work.recovery;
896
+ tx.putWork({
897
+ ...work,
898
+ status: 'running',
899
+ attempt: attempt.attempt,
900
+ activeRunId: attempt.id,
901
+ failure: undefined,
902
+ ...(recovery ? { recovery } : {}),
903
+ });
904
+ if (recovery && recovery !== work.recovery)
905
+ this.recoveryEvent(tx, work, recovery);
906
+ tx.emit({
907
+ type: 'attempt.claimed',
908
+ graphId: work.graphId,
909
+ workId: work.id,
910
+ runId: attempt.id,
911
+ attempt: attempt.attempt,
912
+ payload: {
913
+ owner,
914
+ runtime: attempt.runtime,
915
+ reviewer: attempt.reviewer,
916
+ policyDigest: attempt.policyDigest,
917
+ engineVersion: this.version,
918
+ },
919
+ });
920
+ return attempt;
921
+ });
922
+ }
923
+ /**
924
+ * Единственная точка fencing: операция попытки выполняется, только если
925
+ * попытка активна, токен её, срок владения не истёк, она — текущая попытка
926
+ * поручения, политика не сменилась и хост не возражает.
927
+ */
928
+ withAttempt(id, token, kind, fn) {
929
+ return this.tx(kind, (tx) => {
930
+ const attempt = tx.attempt(id);
931
+ if (!attempt)
932
+ throw new HarnessError('NOT_FOUND', 'Попытка не найдена: ' + id);
933
+ const work = tx.work(attempt.workId);
934
+ if (attempt.status !== 'active' ||
935
+ attempt.token !== token ||
936
+ attempt.leaseUntil <= this.now() ||
937
+ work.activeRunId !== attempt.id)
938
+ throw new HarnessError('LEASE_STALE', 'Устаревшая попытка: владение утрачено');
939
+ // Попытку ведёт только движок той версии, что её выдал. Прежняя (или
940
+ // без версии, записанная до неё) не продолжается новой прежним token:
941
+ // только истечение и recovery с новым владением.
942
+ if (attempt.engineVersion !== this.version)
943
+ throw new HarnessError('LEASE_STALE', `Попытку выдал движок ${attempt.engineVersion ?? 'прежней версии'}, а работает ${this.version}: продолжение прежним token запрещено, нужна новая попытка`);
944
+ if (attempt.policyDigest !== this.host.basis.policyDigest(work, tx))
945
+ throw new HarnessError('APPROVAL_STALE', 'Политика изменилась; нужна новая попытка');
946
+ const refusal = this.host.guards.current(work, attempt, tx);
947
+ if (refusal)
948
+ throw new HarnessError(refusal.code, refusal.message);
949
+ return fn(attempt, work, tx);
950
+ });
951
+ }
952
+ heartbeat(id, token) {
953
+ this.withAttempt(id, token, 'heartbeat', (a, _w, tx) => {
954
+ tx.putAttempt({ ...a, leaseUntil: this.now() + this.policy.leaseMs });
955
+ });
956
+ }
957
+ /** Причина неудавшегося продления: записывается первой и не затирается. Истёкший срок допустим, чужой токен — нет. */
958
+ heartbeatFailed(id, token, reason) {
959
+ return this.tx('run.heartbeat-failed', (tx) => {
960
+ const a = tx.attempt(id);
961
+ if (a?.status !== 'active' ||
962
+ a.token !== token ||
963
+ a.engineVersion !== this.version ||
964
+ a.error?.startsWith(HEARTBEAT_FAILED))
965
+ return false;
966
+ tx.putAttempt({ ...a, error: `${HEARTBEAT_FAILED}: ${reason.slice(0, 500)}` });
967
+ return true;
968
+ });
969
+ }
970
+ phase(id, token, phase, data = {}) {
971
+ this.withAttempt(id, token, 'run.phase', (a, w, tx) => {
972
+ tx.putAttempt({ ...a, ...data, phase });
973
+ tx.putWork({ ...w, status: phase });
974
+ tx.emit({
975
+ type: 'attempt.phase',
976
+ workId: w.id,
977
+ runId: id,
978
+ attempt: a.attempt,
979
+ payload: {
980
+ phase,
981
+ ...((data.integrationSha ?? data.candidateSha ?? data.baseSha)
982
+ ? { sha: (data.integrationSha ?? data.candidateSha ?? data.baseSha) }
983
+ : {}),
984
+ },
985
+ });
986
+ });
987
+ }
988
+ /** Дополнить попытку сведениями её хода (контекст, ресурсы, замеры) под тем же fencing. */
989
+ update(id, token, kind, patch) {
990
+ this.withAttempt(id, token, kind, (a, _w, tx) => tx.putAttempt({ ...a, ...patch }));
991
+ }
992
+ /** Снимок зависимостей, против которого идёт попытка; закрепляется до реализации. */
993
+ dependencies(id, token, snapshots) {
994
+ this.withAttempt(id, token, 'run.dependencies', (a, _w, tx) => tx.putAttempt({ ...a, dependencies: snapshots }));
995
+ }
996
+ /** Свежесть снимка зависимостей на момент окончания: записывается, не отклоняет. */
997
+ dependencyFreshness(id, token, freshness) {
998
+ this.withAttempt(id, token, 'run.dependency-freshness', (a, _w, tx) => tx.putAttempt({ ...a, dependencyFreshness: freshness }));
999
+ }
1000
+ /** Что проверено у потребителя: его голова и снимок всех его зависимостей. */
1001
+ consumerChecked(id, token, repositoryId, checked) {
1002
+ this.withAttempt(id, token, 'run.consumer-checked', (a, _w, tx) => {
1003
+ if (!a.consumers?.some((c) => c.repositoryId === repositoryId))
1004
+ throw new HarnessError('INVALID_INPUT', 'Потребитель не объявлен попыткой: ' + repositoryId);
1005
+ tx.putAttempt({
1006
+ ...a,
1007
+ consumers: a.consumers.map((c) => c.repositoryId === repositoryId ? { ...c, checked } : c),
1008
+ });
1009
+ });
1010
+ }
1011
+ /**
1012
+ * Gates репозиториев, не пройденные на integration ни одним из принятых
1013
+ * поручений: покрытие — по фактическому собственному evidence на принятом
1014
+ * SHA попытки под текущим основанием политики, для любой области. Evidence потребителя — проверка другого
1015
+ * компонента и не в счёт; запись ревью не закрывает одноимённый test gate.
1016
+ * Решение о приёмке набора поручений — за хостом.
1017
+ */
1018
+ uncoveredGates(workIds) {
1019
+ return this.read((v) => {
1020
+ const works = workIds.map((id) => v.work(id)).filter((w) => !!w);
1021
+ const repositories = [...new Set(works.map((w) => w.order.repositoryId))].map((id) => this.repository(id));
1022
+ return uncoveredGates(repositories, works.map((w) => ({
1023
+ repositoryId: w.order.repositoryId,
1024
+ resultSha: w.resultSha,
1025
+ // Покрытие — только evidence попытки под текущим основанием
1026
+ // политики: тот же ID gate с другой командой или профилем —
1027
+ // другая проверка.
1028
+ evidence: v
1029
+ .attempts(w.id)
1030
+ .filter((a) => a.policyDigest === this.host.basis.policyDigest(w, v))
1031
+ .flatMap((a) => a.evidence),
1032
+ })));
1033
+ });
1034
+ }
1035
+ /**
1036
+ * Основания реализации записываются до неё: по ним следующая попытка решит,
1037
+ * можно ли взять этого кандидата. В той же транзакции решается, берётся ли
1038
+ * кандидат предыдущей попытки вместо новой реализации.
1039
+ */
1040
+ implementationBasis(id, token, basis) {
1041
+ return this.withAttempt(id, token, 'run.implementation-basis', (a, w, tx) => {
1042
+ const decision = this.policy.reuseImplementation
1043
+ ? reusableImplementation(tx, w, id, basis)
1044
+ : { reuse: false, reason: 'переиспользование выключено политикой' };
1045
+ const reusedFrom = decision.reuse
1046
+ ? { runId: decision.from.id, candidateSha: decision.candidateSha }
1047
+ : undefined;
1048
+ tx.putAttempt({ ...a, implementationBasis: basis, ...(reusedFrom ? { reusedFrom } : {}) });
1049
+ return reusedFrom ? { reusedFrom } : { reason: decision.reason };
1050
+ });
1051
+ }
1052
+ /** Черновик реализации, оборванной до кандидата (см. `AttemptState.partial`). */
1053
+ recordPartial(id, token, partial) {
1054
+ this.withAttempt(id, token, 'run.partial', (a, _w, tx) => tx.putAttempt({ ...a, partial }));
1055
+ }
1056
+ /** Попытка начала с черновика предыдущей (см. `AttemptState.continuedFrom`). */
1057
+ continuation(id, token, from) {
1058
+ this.withAttempt(id, token, 'run.continuation', (a, _w, tx) => tx.putAttempt({ ...a, continuedFrom: from }));
1059
+ }
1060
+ /** Начало стадии попытки; `timingFinished` закрывает её исходом. */
1061
+ timingStarted(id, token, stage) {
1062
+ const timing = { id: this.id(), stage, startedAt: iso(this.now()) };
1063
+ this.withAttempt(id, token, 'run.timing.started', (a, _w, tx) => tx.putAttempt({ ...a, timings: [...(a.timings ?? []), timing] }));
1064
+ return timing.id;
1065
+ }
1066
+ timingFinished(id, token, timingId, outcome) {
1067
+ this.withAttempt(id, token, 'run.timing.finished', (a, _w, tx) => tx.putAttempt({
1068
+ ...a,
1069
+ timings: (a.timings ?? []).map((t) => t.id === timingId ? { ...t, finishedAt: iso(this.now()), outcome } : t),
1070
+ }));
1071
+ }
1072
+ /**
1073
+ * Записать воспроизведения из находок ревью попытки. Одно свойство на одном
1074
+ * входе — одна запись поручения: повтор добавляет прогон, а не запись;
1075
+ * подтверждение запуском не отменяется последующим неподтверждённым.
1076
+ * Реестр ограничен: старые записи вытесняются, а не копятся без предела.
1077
+ */
1078
+ recordReproductions(id, token, sha, items) {
1079
+ return this.withAttempt(id, token, 'reproduction.recorded', (a, w, tx) => {
1080
+ const registry = tx.local('reproductions', WORKSPACE_OWNER, w.id) ?? {
1081
+ workId: w.id,
1082
+ items: [],
1083
+ };
1084
+ const list = registry.items.map((x) => structuredClone(x));
1085
+ const at = iso(this.now());
1086
+ for (const item of items) {
1087
+ const inputHash = sha256(item.input);
1088
+ const key = digestOf({ workId: w.id, property: item.property, inputHash });
1089
+ const run = { runId: a.id, sha, at };
1090
+ const existing = list.find((x) => x.key === key);
1091
+ if (existing) {
1092
+ if (!existing.runs.some((r) => r.runId === a.id))
1093
+ existing.runs.push(run);
1094
+ existing.runs = existing.runs.slice(-200);
1095
+ // Подтверждённый запуском — с командой и id этого запуска вместе.
1096
+ if (item.observed && !existing.observed) {
1097
+ existing.observed = true;
1098
+ existing.run = item.run;
1099
+ existing.command = item.command;
1100
+ }
1101
+ existing.claimed ||= item.claimed;
1102
+ continue;
1103
+ }
1104
+ list.push({ ...item, key, inputHash, runs: [run] });
1105
+ }
1106
+ tx.putLocal('reproductions', WORKSPACE_OWNER, w.id, {
1107
+ workId: w.id,
1108
+ items: list.slice(-MAX_REPRODUCTIONS),
1109
+ });
1110
+ return list.length;
1111
+ });
1112
+ }
1113
+ /** Воспроизведения поручения, от старых к новым. */
1114
+ reproductions(workId) {
1115
+ return this.read((v) => v.local('reproductions', WORKSPACE_OWNER, workId)?.items ?? []);
1116
+ }
1117
+ evidence(id, token, evidence) {
1118
+ return this.withAttempt(id, token, 'evidence.recorded', (a, w, tx) => {
1119
+ if (evidence.checks !== undefined && evidence.checks !== a.checks?.effective)
1120
+ throw new HarnessError('APPROVAL_STALE', 'Evidence другой версии проверок, чем у попытки');
1121
+ // Вид записи согласован с gate: ревью — только `independent-review`, и
1122
+ // это имя не принадлежит проверке. Иначе запись ревью под именем gate
1123
+ // доказывала бы его (и названный testcase).
1124
+ if ((evidence.kind === 'review') !== (evidence.gate === 'independent-review'))
1125
+ throw new HarnessError('INVALID_INPUT', `Evidence вида ${evidence.kind} не может относиться к gate ${evidence.gate}`);
1126
+ const record = {
1127
+ ...evidence,
1128
+ ...(a.checks ? { checks: a.checks.effective } : {}),
1129
+ id: this.id(),
1130
+ runId: id,
1131
+ createdAt: iso(this.now()),
1132
+ };
1133
+ tx.putAttempt({ ...a, evidence: [...a.evidence, record] });
1134
+ const common = { workId: w.id, runId: id, attempt: a.attempt };
1135
+ if (record.kind === 'review')
1136
+ tx.emit({
1137
+ type: 'attempt.review',
1138
+ ...common,
1139
+ payload: {
1140
+ phase: record.phase,
1141
+ sha: record.sha,
1142
+ passed: record.passed,
1143
+ evidenceId: record.id,
1144
+ reviewer: a.reviewer,
1145
+ sameVendor: vendorOf(a.reviewer) === vendorOf(a.runtime),
1146
+ blocking: (record.findings ?? []).filter((f) => f.severity === 'blocking').length,
1147
+ },
1148
+ });
1149
+ else
1150
+ tx.emit({
1151
+ type: 'attempt.gate',
1152
+ ...common,
1153
+ payload: {
1154
+ phase: record.phase,
1155
+ gate: record.gate,
1156
+ sha: record.sha,
1157
+ passed: record.passed,
1158
+ evidenceId: record.id,
1159
+ ...(record.consumer ? { consumer: record.consumer } : {}),
1160
+ },
1161
+ });
1162
+ return record;
1163
+ });
1164
+ }
1165
+ /**
1166
+ * Техническая приёмка. Требует фазу интеграции и integration SHA, PASS
1167
+ * каждого обязательного gate в обеих фазах на точных SHA, PASS
1168
+ * независимого ревью в обеих фазах; затем условие хоста `beforeAccept`.
1169
+ * `publish` — CAS продвижения target ref — выполняется внутри той же
1170
+ * транзакции до фиксации: его отказ откатывает приёмку целиком.
1171
+ */
1172
+ finish(id, token, sha, publish) {
1173
+ return this.withAttempt(id, token, 'task.done', (a, w, tx) => {
1174
+ // Процесс с не применённой политикой не принимает: сравнение двух его
1175
+ // же старых digest актуальности не доказывает.
1176
+ this.assertCurrentPolicy(tx);
1177
+ if (a.phase !== 'integrating' || !a.candidateSha || a.integrationSha !== sha)
1178
+ throw new HarnessError('NOT_READY', 'Нет интеграционного коммита');
1179
+ // Принять можно только под той версией проверок, под которой шла
1180
+ // попытка: новый корпус, принятый поручением, требует новой попытки.
1181
+ if (a.checks && this.checksOf(w, tx) !== a.checks.effective)
1182
+ throw new HarnessError('APPROVAL_STALE', 'Версия проверок поручения изменилась; нужна новая попытка');
1183
+ const last = (kind, phase, at, gate) => a.evidence.findLast((e) => e.kind === kind &&
1184
+ e.phase === phase &&
1185
+ e.sha === at &&
1186
+ e.gate === gate &&
1187
+ e.consumer === undefined &&
1188
+ (!a.checks || e.checks === a.checks.effective))?.passed === true;
1189
+ for (const gate of a.requiredGates ?? [])
1190
+ for (const phase of ['candidate', 'integration'])
1191
+ if (!last('test', phase, phase === 'candidate' ? a.candidateSha : sha, gate))
1192
+ throw new HarnessError('GATE_FAILED', `Нет PASS: ${phase}/${gate}`);
1193
+ for (const phase of ['candidate', 'integration'])
1194
+ if (!last('review', phase, phase === 'candidate' ? a.candidateSha : sha, 'independent-review'))
1195
+ throw new HarnessError('REVIEW_REJECTED', `Нет независимого ревью: ${phase}`);
1196
+ // Проверки потребителей — на integration, против интегрированного
1197
+ // результата: evidence потребителя закрывает только его проверку.
1198
+ for (const consumer of a.consumers ?? []) {
1199
+ for (const gate of consumer.gates)
1200
+ if (a.evidence.findLast((e) => e.kind === 'test' &&
1201
+ e.phase === 'integration' &&
1202
+ e.sha === sha &&
1203
+ e.gate === gate &&
1204
+ e.consumer === consumer.repositoryId &&
1205
+ (!a.checks || e.checks === a.checks.effective))?.passed !== true)
1206
+ throw new HarnessError('GATE_FAILED', `Нет PASS проверки потребителя: ${consumer.repositoryId}/${gate}`);
1207
+ // Что проверено, обязано быть записано: иначе проверку потребителя не с
1208
+ // чем сверить, и результат нельзя перенести.
1209
+ const provider = consumer.checked?.dependencies.find((d) => d.repositoryId === a.repositoryId);
1210
+ if (provider?.sha !== sha)
1211
+ throw new HarnessError('GATE_FAILED', `Проверка потребителя ${consumer.repositoryId} не записала снимок с интегрированным результатом`);
1212
+ }
1213
+ const unproven = unprovenReason(w.order.requirements, a.evidence, sha, a.checks?.effective);
1214
+ if (unproven)
1215
+ throw new HarnessError('GATE_FAILED', unproven);
1216
+ // Договор проверки доказан манифестом и корпусом закреплённой версии на
1217
+ // обеих фазах, а не только битом PASS: сохранённое evidence без них
1218
+ // (в том числе при recovery) не принимается.
1219
+ const proof = propertyProofProblem({
1220
+ order: w.order,
1221
+ contracts: contractDocuments(w.order, tx),
1222
+ candidateSha: a.candidateSha,
1223
+ resultSha: sha,
1224
+ effective: a.checks?.effective,
1225
+ corpus: a.checks?.corpus ? pinnedCorpus(tx, a.checks.corpus) : undefined,
1226
+ evidence: a.evidence,
1227
+ });
1228
+ if (proof)
1229
+ throw new HarnessError('GATE_FAILED', proof);
1230
+ const contract = this.contractBlocker(w, tx);
1231
+ if (contract)
1232
+ throw new HarnessError('APPROVAL_STALE', contract);
1233
+ // Согласование, связанное с контекстом, принимает только попытку на
1234
+ // том же снимке: новый одобренный контекст требует новой попытки.
1235
+ const bound = tx.graph(w.graphId)?.approval?.context;
1236
+ if (bound && (a.contextSnapshot ?? null) !== bound.digest)
1237
+ throw new HarnessError('APPROVAL_STALE', 'Согласованный контекст изменился после выдачи; нужна новая попытка');
1238
+ const refusal = this.host.guards.beforeAccept(w, a, tx);
1239
+ if (refusal)
1240
+ throw new HarnessError(refusal.code, refusal.message);
1241
+ const at = iso(this.now());
1242
+ tx.putAttempt({ ...a, status: 'succeeded', finishedAt: at });
1243
+ const accepted = structuredClone(w);
1244
+ const open = accepted.recovery;
1245
+ afterSuccess(accepted, at);
1246
+ if (open)
1247
+ this.recoveryEvent(tx, w, accepted.recoveryHistory.at(-1));
1248
+ tx.putWork({
1249
+ ...accepted,
1250
+ status: 'done',
1251
+ resultSha: sha,
1252
+ activeRunId: undefined,
1253
+ failure: undefined,
1254
+ failureKind: undefined,
1255
+ failureFingerprint: undefined,
1256
+ });
1257
+ tx.emit({
1258
+ type: 'work.accepted',
1259
+ graphId: w.graphId,
1260
+ workId: w.id,
1261
+ runId: id,
1262
+ attempt: a.attempt,
1263
+ payload: { resultSha: sha, integrationSha: sha },
1264
+ });
1265
+ publish?.();
1266
+ return { workId: w.id, runId: id, sha };
1267
+ });
1268
+ }
1269
+ /**
1270
+ * Отказ попытки. Класс и отпечаток записываются вместе с отказом. Отказ
1271
+ * окружения до кандидата (`blocked`) попытку не засчитывает. Отказ,
1272
+ * который повторится на любой работе (`repairPolicy.blocksQueue`), ставит
1273
+ * паузу `runtime` с классом отказа — снимает её устранение причины.
1274
+ */
1275
+ fail(id, token, error, options = {}) {
1276
+ const kind = options.kind ?? 'unknown';
1277
+ return this.withAttempt(id, token, 'run.failed', (a, w, tx) => {
1278
+ const fingerprint = failureFingerprint(kind, error);
1279
+ const prefix = a.error?.startsWith(HEARTBEAT_FAILED)
1280
+ ? a.error
1281
+ : options.heartbeatCause
1282
+ ? `${HEARTBEAT_FAILED}: ${options.heartbeatCause.slice(0, 500)}`
1283
+ : undefined;
1284
+ const shown = prefix ? `${prefix}. ${error}` : error;
1285
+ const blocked = Boolean(options.blocked);
1286
+ // Свойство отказа — только объявленное поручением: неизвестное
1287
+ // сохраняется для разбора, но счётчик эпизода не выбирает.
1288
+ const declared = new Set(w.order.properties ?? []);
1289
+ const bound = [...new Set((options.properties?.bound ?? []).filter((p) => declared.has(p)))];
1290
+ const unbound = [
1291
+ ...new Set([
1292
+ ...(options.properties?.unbound ?? []),
1293
+ ...(options.properties?.bound ?? []).filter((p) => !declared.has(p)),
1294
+ ]),
1295
+ ];
1296
+ const failed = {
1297
+ ...a,
1298
+ status: 'failed',
1299
+ error: shown,
1300
+ ...(blocked ? { blocked: true } : {}),
1301
+ failureKind: kind,
1302
+ failureFingerprint: fingerprint,
1303
+ finishedAt: iso(this.now()),
1304
+ ...(bound.length ? { properties: bound } : {}),
1305
+ ...(unbound.length ? { unboundProperties: unbound } : {}),
1306
+ };
1307
+ tx.putAttempt(failed);
1308
+ const next = structuredClone(w);
1309
+ const before = next.recovery?.status;
1310
+ const episode = afterFailure(next, tx.attempts(w.id).map((x) => (x.id === id ? failed : x)), failed, iso(this.now()), this.episodeOf(next, tx));
1311
+ if (episode && (episode.status !== before || !w.recovery || w.recovery.id !== episode.id))
1312
+ this.recoveryEvent(tx, w, episode);
1313
+ tx.putWork({
1314
+ ...next,
1315
+ status: 'failed',
1316
+ failure: shown,
1317
+ failureKind: kind,
1318
+ failureFingerprint: fingerprint,
1319
+ activeRunId: undefined,
1320
+ attempt: blocked && w.attempt > 0 ? w.attempt - 1 : w.attempt,
1321
+ });
1322
+ tx.emit({
1323
+ type: 'attempt.failed',
1324
+ graphId: w.graphId,
1325
+ workId: w.id,
1326
+ runId: id,
1327
+ attempt: a.attempt,
1328
+ payload: { failureKind: kind, message: shown.slice(0, 4000), blocked },
1329
+ });
1330
+ if (repairPolicy[kind].blocksQueue) {
1331
+ const control = tx.control();
1332
+ const failures = [...new Set([...(control.pauseFailures ?? []), kind])];
1333
+ tx.setControl({
1334
+ ...control,
1335
+ paused: true,
1336
+ pauseReason: control.paused ? control.pauseReason : 'runtime',
1337
+ pausedAt: control.pausedAt ?? iso(this.now()),
1338
+ pauseFailures: failures,
1339
+ });
1340
+ tx.emit({
1341
+ type: 'control.paused',
1342
+ payload: {
1343
+ reason: control.paused ? (control.pauseReason ?? 'runtime') : 'runtime',
1344
+ failures,
1345
+ },
1346
+ });
1347
+ }
1348
+ return {
1349
+ workId: w.id,
1350
+ runId: id,
1351
+ kind,
1352
+ blocked,
1353
+ ...(bound.length ? { properties: bound } : {}),
1354
+ ...(episode ? { recovery: { id: episode.id, status: episode.status } } : {}),
1355
+ };
1356
+ });
1357
+ }
1358
+ /* ---------------------------------------------------------------- */
1359
+ /* Эпизоды восстановления по свойству */
1360
+ /* ---------------------------------------------------------------- */
1361
+ recoveryEvent(tx, work, r) {
1362
+ tx.emit({
1363
+ type: 'work.recovery',
1364
+ graphId: work.graphId,
1365
+ workId: work.id,
1366
+ payload: {
1367
+ recoveryId: r.id,
1368
+ property: r.property,
1369
+ status: r.status,
1370
+ ...(r.reason ? { reason: r.reason.slice(0, 4000) } : {}),
1371
+ },
1372
+ });
1373
+ }
1374
+ /** Принятие корпуса, ждущее оператора, удерживает выдачу поручения. */
1375
+ awaitsOperator(work, view) {
1376
+ return view
1377
+ .locals('check-suites', work.order.repositoryId)
1378
+ .some((x) => x.value.pending.some((p) => p.status === 'waiting' && p.awaitingOperator && p.tasks.includes(work.id)));
1379
+ }
1380
+ episode(kind, workId, recoveryId, fn) {
1381
+ return this.tx(kind, (tx) => {
1382
+ const w = tx.work(workId);
1383
+ if (!w)
1384
+ throw new HarnessError('NOT_FOUND', 'Поручение не найдено: ' + workId);
1385
+ if (!w.recovery || w.recovery.id !== recoveryId)
1386
+ throw new HarnessError('NOT_FOUND', 'Эпизод восстановления не найден');
1387
+ const r = structuredClone(w.recovery);
1388
+ const event = fn(r, w);
1389
+ if (event === undefined)
1390
+ return r;
1391
+ r.version++;
1392
+ r.history.push({
1393
+ at: iso(this.now()),
1394
+ event,
1395
+ ...(r.reason ? { detail: r.reason.slice(0, 1000) } : {}),
1396
+ });
1397
+ tx.putWork({ ...w, recovery: r });
1398
+ this.recoveryEvent(tx, w, r);
1399
+ return r;
1400
+ });
1401
+ }
1402
+ /**
1403
+ * Учесть разбор ведущего до вызова модели. Один автоматический разбор на
1404
+ * эпизод: повторная регистрация, рестарт или дубликат бесплатного вызова
1405
+ * не получают. Исчерпанные попытки — решение человека.
1406
+ */
1407
+ recoveryReserve(workId, recoveryId) {
1408
+ return this.episode('recovery.reserved', workId, recoveryId, (r, w) => {
1409
+ if (r.status !== 'awaiting-lead')
1410
+ throw new HarnessError('NOT_READY', `Эпизод ${r.id} не ждёт разбора: ${r.status}`);
1411
+ if (r.calls >= 1) {
1412
+ r.status = 'awaiting-user';
1413
+ r.reason = 'Автоматический разбор эпизода уже использован; повторный вызов не выполняется.';
1414
+ }
1415
+ else if (w.attempt >= this.policy.maxAttempts) {
1416
+ r.status = 'awaiting-user';
1417
+ r.reason =
1418
+ 'Попытки поручения исчерпаны: разрешённого повтора не осталось, сброс — решение человека.';
1419
+ }
1420
+ else {
1421
+ r.calls++;
1422
+ r.status = 'analyzing';
1423
+ }
1424
+ return r.status === 'analyzing' ? 'analysis-reserved' : 'refused';
1425
+ });
1426
+ }
1427
+ /**
1428
+ * Записать решение разбора — ведущего или ручное — и перевести эпизод в
1429
+ * состояние разрешённого действия. Ручное решение сверяет версию записи:
1430
+ * устаревшее не применяется.
1431
+ */
1432
+ recoveryDecide(workId, recoveryId, decision, expectedVersion) {
1433
+ if (decision.reason.trim().length < 10)
1434
+ throw new HarnessError('INVALID_INPUT', 'Решение требует причины не короче 10 символов');
1435
+ return this.episode('recovery.decided', workId, recoveryId, (r, w) => {
1436
+ if (expectedVersion !== undefined && r.version !== expectedVersion)
1437
+ throw new HarnessError('APPROVAL_STALE', 'Эпизод изменился; прочитайте его заново');
1438
+ const manual = decision.source.kind === 'operator';
1439
+ if (!manual && r.status !== 'analyzing')
1440
+ throw new HarnessError('NOT_READY', `Эпизод ${r.id} не в разборе: ${r.status}`);
1441
+ if (manual && !['awaiting-lead', 'awaiting-user', 'stopped', 'analyzing'].includes(r.status))
1442
+ throw new HarnessError('NOT_READY', `Эпизод ${r.id} уже исполняет решение: ${r.status}`);
1443
+ if (w.status === 'cancelled')
1444
+ throw new HarnessError('NOT_READY', 'Поручение отменено');
1445
+ r.decision = decision;
1446
+ const retryable = w.attempt < this.policy.maxAttempts;
1447
+ switch (decision.action) {
1448
+ case 'add-cases':
1449
+ if (!decision.cases?.length)
1450
+ throw new HarnessError('INVALID_INPUT', 'add-cases без случаев');
1451
+ r.status = 'applying';
1452
+ break;
1453
+ case 'new-approach':
1454
+ if (!decision.hypothesis?.trim() || !decision.plan?.trim())
1455
+ throw new HarnessError('INVALID_INPUT', 'Новый подход требует гипотезы и плана проверки');
1456
+ r.status = retryable ? 'retry' : 'awaiting-user';
1457
+ if (!retryable)
1458
+ r.reason = 'Попытки исчерпаны: повтор с новой гипотезой невозможен.';
1459
+ break;
1460
+ case 'strengthen-checker':
1461
+ case 'split-task':
1462
+ if (!decision.proposal?.trim())
1463
+ throw new HarnessError('INVALID_INPUT', 'Предложение для обычного ревью обязательно');
1464
+ r.status = 'stopped';
1465
+ r.reason = `Подготовлено предложение (${decision.action}); оно проходит обычное ревью или перепланирование и автоматически не применяется.`;
1466
+ break;
1467
+ case 'clarify-obligation':
1468
+ r.status = 'awaiting-user';
1469
+ r.reason = `Нужно решение человека: ${decision.conflict ?? decision.reason}`;
1470
+ break;
1471
+ case 'environment':
1472
+ r.status = 'stopped';
1473
+ r.reason = `Причина в среде или не установлена: ${decision.reason}`;
1474
+ break;
1475
+ }
1476
+ return 'decided';
1477
+ });
1478
+ }
1479
+ /** Итог добавления случаев: подтверждённый случай разрешает один повтор. */
1480
+ recoveryApplied(workId, recoveryId, outcomes) {
1481
+ return this.episode('recovery.applied', workId, recoveryId, (r, w) => {
1482
+ if (r.status !== 'applying')
1483
+ throw new HarnessError('NOT_READY', 'Эпизод не исполняет добавление случаев');
1484
+ const confirmed = outcomes.filter((o) => o.outcome === 'confirmed').length;
1485
+ if (confirmed && w.attempt < this.policy.maxAttempts) {
1486
+ r.status = 'retry';
1487
+ r.reason = `${confirmed} из ${outcomes.length} случаев подтверждено`;
1488
+ }
1489
+ else {
1490
+ r.status = 'stopped';
1491
+ r.reason = confirmed
1492
+ ? 'Случаи подтверждены, но попытки поручения исчерпаны.'
1493
+ : 'Ни один предложенный случай не подтверждён эталоном: ' +
1494
+ outcomes
1495
+ .map((o) => o.reason)
1496
+ .join('; ')
1497
+ .slice(0, 800);
1498
+ }
1499
+ return 'applied';
1500
+ });
1501
+ }
1502
+ /** Разбор прервался без решения: вызов учтён, повтор не бесплатен. */
1503
+ recoveryInterrupted(workId, recoveryId, reason) {
1504
+ return this.episode('recovery.interrupted', workId, recoveryId, (r) => {
1505
+ if (!['analyzing', 'applying'].includes(r.status))
1506
+ return undefined;
1507
+ r.status = 'awaiting-user';
1508
+ r.reason = reason.slice(0, 1000);
1509
+ return 'interrupted';
1510
+ });
1511
+ }
1512
+ /* ---------------------------------------------------------------- */
1513
+ /* Применённая политика и операция reconfigure */
1514
+ /* ---------------------------------------------------------------- */
1515
+ /**
1516
+ * Применённая политика в хранилище — единственный источник правды; у
1517
+ * процесса нет своего «поколения», которое мог бы рассинхронизировать
1518
+ * откат транзакции. Процесс текущий, только если его политика совпадает с
1519
+ * применённой. Записать свою вместо применённой (перезапуск с другой
1520
+ * политикой) он может, только если нет живого чужого controller, политика
1521
+ * не менялась в памяти после создания движка, её источник не менялся с
1522
+ * загрузки и после запуска процесса никто не применил другую: поколение
1523
+ * считается по записям, а не по часам.
1524
+ */
1525
+ mayAdopt(view) {
1526
+ const lease = view.controller();
1527
+ if (lease && lease.leaseUntil > this.now() && !this.mine(lease, this.ownLeader))
1528
+ return `работает controller ${lease.owner} с другой политикой`;
1529
+ if (policyDigest(this.policy) !== this.loadedContent)
1530
+ return 'политика изменена в памяти после загрузки';
1531
+ const applied = view.control().appliedPolicy;
1532
+ if (applied && (applied.generation ?? 0) !== this.observedGeneration)
1533
+ return `после запуска процесса применена политика поколения ${applied.generation ?? 0}`;
1534
+ return this.provenance();
1535
+ }
1536
+ adoptPolicy(tx, by, operation) {
1537
+ const control = tx.control();
1538
+ const generation = (control.appliedPolicy?.generation ?? 0) + 1;
1539
+ tx.setControl({
1540
+ ...control,
1541
+ appliedPolicy: { digest: this.loadedPolicy, generation, at: iso(this.now()), by },
1542
+ });
1543
+ tx.emit({
1544
+ type: 'policy.applied',
1545
+ payload: {
1546
+ digest: this.loadedPolicy,
1547
+ generation,
1548
+ by,
1549
+ ...(operation ? { operation } : {}),
1550
+ },
1551
+ });
1552
+ }
1553
+ /** Почему процесс не вправе действовать под своей политикой; `undefined` — вправе. */
1554
+ staleReason(view) {
1555
+ const applied = view.control().appliedPolicy;
1556
+ if (!applied || applied.digest === this.loadedPolicy)
1557
+ return undefined;
1558
+ const refusal = this.mayAdopt(view);
1559
+ return refusal
1560
+ ? `Процесс работает не с применённой политикой (${refusal}); перезапустите его`
1561
+ : undefined;
1562
+ }
1563
+ policyStale(tx) {
1564
+ try {
1565
+ this.assertCurrentPolicy(tx);
1566
+ return false;
1567
+ }
1568
+ catch {
1569
+ return true;
1570
+ }
1571
+ }
1572
+ /**
1573
+ * Общий барьер: в транзакциях выдачи, согласования, приёмки и совместной
1574
+ * проверки процесс сверяет свою политику с применённой. Первый процесс,
1575
+ * действующий после законной смены политики без живого controller,
1576
+ * записывает свою как применённую в той же транзакции — откат отменит и её.
1577
+ */
1578
+ assertCurrentPolicy(tx) {
1579
+ const applied = tx.control().appliedPolicy;
1580
+ if (!applied || applied.digest === this.loadedPolicy)
1581
+ return;
1582
+ const stale = this.staleReason(tx);
1583
+ if (stale)
1584
+ throw new HarnessError('APPROVAL_STALE', stale);
1585
+ this.adoptPolicy(tx, 'process');
1586
+ }
1587
+ /**
1588
+ * Запуск controller записывает его политику применённой, если её ещё нет
1589
+ * или процесс вправе её сменить. Неприменённый запрос операции остаётся.
1590
+ * Хост с `recordPolicyOnLead: false` вызывает это сам при запуске controller.
1591
+ */
1592
+ recordPolicy(owner) {
1593
+ this.tx('config.started', (tx) => {
1594
+ const lease = tx.controller();
1595
+ if (!this.mine(lease, owner))
1596
+ return;
1597
+ const applied = tx.control().appliedPolicy;
1598
+ if (applied?.digest === this.loadedPolicy)
1599
+ return;
1600
+ if (applied && this.mayAdopt(tx))
1601
+ return;
1602
+ this.adoptPolicy(tx, owner);
1603
+ });
1604
+ }
1605
+ reconfiguring(view) {
1606
+ const request = view.control().reconfigure;
1607
+ return request && !request.appliedAt ? request : undefined;
1608
+ }
1609
+ /** Сведения о политике процесса и применённой. */
1610
+ policyState() {
1611
+ return this.read((v) => ({
1612
+ loaded: this.loadedPolicy,
1613
+ ...(v.control().appliedPolicy ? { applied: v.control().appliedPolicy } : {}),
1614
+ ...(v.control().reconfigure ? { reconfigure: v.control().reconfigure } : {}),
1615
+ ...(this.staleReason(v) ? { stale: this.staleReason(v) } : {}),
1616
+ }));
1617
+ }
1618
+ /**
1619
+ * Пауза операции: ставится, только если очередь не остановлена, и
1620
+ * помечается операцией. Пауза человека не перезаписывается.
1621
+ */
1622
+ operationPause(operation) {
1623
+ return this.tx('scheduler.paused', (tx) => {
1624
+ const control = tx.control();
1625
+ if (control.paused)
1626
+ return false;
1627
+ tx.setControl({
1628
+ ...control,
1629
+ paused: true,
1630
+ pauseReason: 'reconfigure',
1631
+ pauseOperation: operation,
1632
+ pausedAt: iso(this.now()),
1633
+ });
1634
+ tx.emit({ type: 'control.paused', payload: { reason: 'reconfigure' } });
1635
+ return true;
1636
+ });
1637
+ }
1638
+ /** Снять паузу операции — только свою; паузу человека она не трогает. */
1639
+ operationResume(operation) {
1640
+ return this.tx('scheduler.started', (tx) => {
1641
+ const control = tx.control();
1642
+ if (!control.paused ||
1643
+ control.pauseReason !== 'reconfigure' ||
1644
+ control.pauseOperation !== operation)
1645
+ return false;
1646
+ tx.setControl({
1647
+ ...control,
1648
+ paused: false,
1649
+ pauseReason: undefined,
1650
+ pauseOperation: undefined,
1651
+ pausedAt: undefined,
1652
+ });
1653
+ tx.emit({ type: 'control.resumed', payload: { reason: 'reconfigure' } });
1654
+ return true;
1655
+ });
1656
+ }
1657
+ /**
1658
+ * Запросить применение политики с ожидаемым digest (`policyDigest`
1659
+ * загруженной политики). Идемпотентно; повтор той же операцией сбрасывает
1660
+ * прежний отказ — политику могли исправить. Пока запрос не применён, новые
1661
+ * попытки не выдаются.
1662
+ */
1663
+ requestReconfigure(operation, digest) {
1664
+ return this.tx('config.reconfigure-requested', (tx) => {
1665
+ const control = tx.control();
1666
+ const current = control.reconfigure;
1667
+ if (current && current.operation === operation && current.digest === digest) {
1668
+ if (!current.error)
1669
+ return { operation, digest, changed: false };
1670
+ tx.setControl({ ...control, reconfigure: { ...current, error: undefined } });
1671
+ tx.emit({
1672
+ type: 'policy.reconfigure',
1673
+ payload: { operation, digest, status: 'requested' },
1674
+ });
1675
+ return { operation, digest, changed: true, retried: true };
1676
+ }
1677
+ if (current && current.operation !== operation && !current.appliedAt)
1678
+ throw new HarnessError('NOT_READY', `Политику уже применяет операция ${current.operation}; дождитесь её`);
1679
+ tx.setControl({
1680
+ ...control,
1681
+ reconfigure: { operation, digest, requestedAt: iso(this.now()) },
1682
+ });
1683
+ tx.emit({ type: 'policy.reconfigure', payload: { operation, digest, status: 'requested' } });
1684
+ return { operation, digest, changed: true };
1685
+ });
1686
+ }
1687
+ /**
1688
+ * Работы, идущие под действующей политикой. Запись с истёкшим сроком не
1689
+ * держит применение: её результат и так не будет принят (владение
1690
+ * проверяется при каждой записи), а держать применение из-за неё значило
1691
+ * бы ждать вечно.
1692
+ */
1693
+ busyWork(view) {
1694
+ const now = this.now();
1695
+ return [
1696
+ ...view
1697
+ .attempts()
1698
+ .filter((a) => a.status === 'active' && a.leaseUntil > now)
1699
+ .map((a) => a.id),
1700
+ ...view
1701
+ .verifications()
1702
+ .filter((v) => v.status === 'active' && v.leaseUntil > now)
1703
+ .map((v) => v.id),
1704
+ ...view
1705
+ .locals('workflow-jobs')
1706
+ .filter((j) => j.value.status === 'running' && (j.value.leaseUntil ?? 0) > now)
1707
+ .map((j) => j.key),
1708
+ ...view.locals('check-suites').flatMap(({ value }) => Object.values(value.operations)
1709
+ .filter((op) => op.status === 'running' && (op.leaseUntil ?? 0) > now)
1710
+ .map((op) => `${value.id}:${op.key}`)),
1711
+ ...(this.host.guards.busy?.(view) ?? []),
1712
+ ];
1713
+ }
1714
+ /**
1715
+ * Применить запрос этим процессом: только если его политика — ровно
1716
+ * ожидаемая и работ под прежней не осталось. Политика другого digest —
1717
+ * отказ с обоими digest (повтор операции его сбросит). Применение и снятие
1718
+ * паузы операции — одна транзакция.
1719
+ */
1720
+ applyReconfigure(by) {
1721
+ return this.tx('config.reconfigured', (tx) => {
1722
+ const control = tx.control();
1723
+ const request = control.reconfigure;
1724
+ if (!request || request.appliedAt || request.error)
1725
+ return { status: 'none' };
1726
+ const busy = this.busyWork(tx);
1727
+ if (busy.length)
1728
+ return { status: 'busy', busy };
1729
+ if (request.digest !== this.loadedPolicy) {
1730
+ const error = `Политика не совпадает с ожидаемой операцией: ожидался digest ${request.digest.slice(0, 16)}, загружен ${this.loadedPolicy.slice(0, 16)}`;
1731
+ tx.setControl({ ...control, reconfigure: { ...request, error } });
1732
+ tx.emit({
1733
+ type: 'policy.reconfigure',
1734
+ payload: {
1735
+ operation: request.operation,
1736
+ digest: request.digest,
1737
+ status: 'failed',
1738
+ error,
1739
+ },
1740
+ });
1741
+ return { status: 'failed', error };
1742
+ }
1743
+ const generation = (control.appliedPolicy?.generation ?? 0) + 1;
1744
+ const at = iso(this.now());
1745
+ const resume = control.paused &&
1746
+ control.pauseReason === 'reconfigure' &&
1747
+ control.pauseOperation === request.operation;
1748
+ tx.setControl({
1749
+ ...control,
1750
+ reconfigure: { ...request, appliedAt: at, appliedBy: by, error: undefined },
1751
+ appliedPolicy: { digest: request.digest, generation, at, by },
1752
+ ...(resume
1753
+ ? {
1754
+ paused: false,
1755
+ pauseReason: undefined,
1756
+ pauseOperation: undefined,
1757
+ pausedAt: undefined,
1758
+ }
1759
+ : {}),
1760
+ });
1761
+ tx.emit({
1762
+ type: 'policy.applied',
1763
+ payload: { digest: request.digest, generation, by, operation: request.operation },
1764
+ });
1765
+ if (resume)
1766
+ tx.emit({ type: 'control.resumed', payload: { reason: 'reconfigure' } });
1767
+ return { status: 'applied', generation };
1768
+ });
1769
+ }
1770
+ /**
1771
+ * Процесс, работающий с прежней политикой, применить запрос не может: он
1772
+ * ждёт перезапуска с ожидаемой. Такой процесс применение не отклоняет.
1773
+ */
1774
+ /**
1775
+ * Применит ли этот процесс ожидающий запрос политики при следующем шаге —
1776
+ * те же условия, что у `serveReconfigure`/`applyReconfigure`. Только чтение.
1777
+ */
1778
+ reconfigureApplies(view) {
1779
+ const request = this.reconfiguring(view);
1780
+ return Boolean(request &&
1781
+ !request.error &&
1782
+ request.digest === this.loadedPolicy &&
1783
+ this.busyWork(view).length === 0);
1784
+ }
1785
+ serveReconfigure(by) {
1786
+ const request = this.read((v) => this.reconfiguring(v));
1787
+ if (!request || request.error || request.digest !== this.loadedPolicy)
1788
+ return { status: 'none' };
1789
+ return this.applyReconfigure(by);
1790
+ }
1791
+ /**
1792
+ * Записать отказ применения с причиной хоста (например, файл политики не
1793
+ * читается или не совпадает с ожидаемым). Только для неприменённого запроса
1794
+ * той же операции и digest; повтор операции сбрасывает отказ.
1795
+ */
1796
+ rejectReconfigure(operation, digest, error) {
1797
+ return this.tx('config.reconfigured', (tx) => {
1798
+ const control = tx.control();
1799
+ const request = control.reconfigure;
1800
+ if (!request || request.operation !== operation || request.digest !== digest)
1801
+ return false;
1802
+ if (request.appliedAt)
1803
+ return false;
1804
+ const message = error.slice(0, 4000) || 'Политика не применена';
1805
+ tx.setControl({ ...control, reconfigure: { ...request, error: message } });
1806
+ tx.emit({
1807
+ type: 'policy.reconfigure',
1808
+ payload: { operation, digest, status: 'failed', error: message },
1809
+ });
1810
+ return true;
1811
+ });
1812
+ }
1813
+ /** Снять завершённый или отменённый запрос операции. */
1814
+ clearReconfigure(operation) {
1815
+ return this.tx('config.reconfigure-cleared', (tx) => {
1816
+ const control = tx.control();
1817
+ if (control.reconfigure?.operation !== operation)
1818
+ return false;
1819
+ tx.setControl({ ...control, reconfigure: undefined });
1820
+ tx.emit({
1821
+ type: 'policy.reconfigure',
1822
+ payload: { operation, digest: control.reconfigure.digest, status: 'cleared' },
1823
+ });
1824
+ return true;
1825
+ });
1826
+ }
1827
+ /* ---------------------------------------------------------------- */
1828
+ /* Удержания операций */
1829
+ /* ---------------------------------------------------------------- */
1830
+ /**
1831
+ * Удержать поручения от выдачи на время операции. Поручение, удерживаемое
1832
+ * другой операцией, — конфликт: две операции не меняют одно поручение
1833
+ * одновременно. Повтор той же операции ничего не меняет. `fence` —
1834
+ * проверка владения операцией в той же транзакции: утративший владение
1835
+ * ничего не пишет.
1836
+ */
1837
+ hold(ids, operation, reason, fence) {
1838
+ return this.tx('task.held', (tx) => {
1839
+ fence?.(tx);
1840
+ const works = ids.map((id) => {
1841
+ const w = tx.work(id);
1842
+ if (!w)
1843
+ throw new HarnessError('NOT_FOUND', 'Поручение не найдено: ' + id);
1844
+ return w;
1845
+ });
1846
+ const busy = works.filter((w) => w.hold && w.hold.operation !== operation);
1847
+ if (busy.length)
1848
+ throw new HarnessError('NOT_READY', 'Поручения удерживает другая операция: ' +
1849
+ busy.map((w) => `${w.id} (${w.hold.operation})`).join(', '));
1850
+ for (const w of works) {
1851
+ if (w.hold?.operation === operation && w.hold.reason === reason)
1852
+ continue;
1853
+ tx.putWork({ ...w, hold: { operation, reason } });
1854
+ tx.emit({
1855
+ type: 'work.held',
1856
+ graphId: w.graphId,
1857
+ workId: w.id,
1858
+ payload: { operation, reason, released: false },
1859
+ });
1860
+ }
1861
+ return works.map((w) => w.id);
1862
+ });
1863
+ }
1864
+ /** Снять удержание операции — со всех или с перечисленных поручений; чужие не трогаются. */
1865
+ releaseHold(operation, ids, fence) {
1866
+ return this.tx('task.released', (tx) => {
1867
+ fence?.(tx);
1868
+ const released = tx
1869
+ .works()
1870
+ .filter((w) => w.hold?.operation === operation && (!ids || ids.includes(w.id)));
1871
+ for (const w of released) {
1872
+ tx.putWork({ ...w, hold: undefined });
1873
+ tx.emit({
1874
+ type: 'work.held',
1875
+ graphId: w.graphId,
1876
+ workId: w.id,
1877
+ payload: { operation, reason: w.hold.reason, released: true },
1878
+ });
1879
+ }
1880
+ return released.map((w) => w.id);
1881
+ });
1882
+ }
1883
+ /** Передать удержание от одной операции другой без окна выдачи. */
1884
+ transferHold(from, to, reason, fence) {
1885
+ return this.tx('task.hold-transferred', (tx) => {
1886
+ fence?.(tx);
1887
+ const moved = tx.works().filter((w) => w.hold?.operation === from);
1888
+ for (const w of moved) {
1889
+ tx.putWork({ ...w, hold: { operation: to, reason } });
1890
+ tx.emit({
1891
+ type: 'work.held',
1892
+ graphId: w.graphId,
1893
+ workId: w.id,
1894
+ payload: { operation: to, reason, released: false },
1895
+ });
1896
+ }
1897
+ return moved.map((w) => w.id);
1898
+ });
1899
+ }
1900
+ /** Попытки, ещё владеющие поручениями (живой срок): операция ждёт их окончания. */
1901
+ activeAttempts(workIds) {
1902
+ return this.read((v) => v
1903
+ .attempts()
1904
+ .filter((a) => a.status === 'active' &&
1905
+ a.leaseUntil > this.now() &&
1906
+ (!workIds || workIds.includes(a.workId)))
1907
+ .map((a) => ({ id: a.id, workId: a.workId, leaseUntil: a.leaseUntil })));
1908
+ }
1909
+ /* ---------------------------------------------------------------- */
1910
+ /* Совместная проверка комбинации репозиториев */
1911
+ /* ---------------------------------------------------------------- */
1912
+ /** Digest политики совместной проверки: формула хоста, если он её задаёт. */
1913
+ jointPolicy(view) {
1914
+ return this.host.basis.jointPolicyDigest?.(view) ?? jointPolicyDigest(this.policy);
1915
+ }
1916
+ /** Основание совместной проверки набора: формула хоста, если он её задаёт. */
1917
+ jointSpec(view, workIds, verificationId) {
1918
+ return (this.host.basis.jointSpecDigest?.(workIds, view, verificationId) ??
1919
+ jointSpecDigest(view, workIds));
1920
+ }
1921
+ liveJoint(view) {
1922
+ return view.verifications().some((v) => v.status === 'active' && v.leaseUntil > this.now());
1923
+ }
1924
+ /**
1925
+ * Начать совместную проверку набора принятых поручений. Нужны gates уровня
1926
+ * workspace с JUnit, у каждого продуктового репозитория — свой; идущих
1927
+ * попыток и другой живой проверки быть не должно; истёкшая проверка
1928
+ * закрывается отказом. `baseline` — успешная проверка, которую хост принял
1929
+ * (для режима `affected`).
1930
+ */
1931
+ jointStart(input) {
1932
+ const gates = this.policy.workspaceGates;
1933
+ if (!gates.some((g) => g.kind === 'test' && g.report))
1934
+ throw new HarnessError('INVALID_INPUT', 'Настройте обязательные gates совместной проверки (workspaceGates) с JUnit');
1935
+ for (const repo of this.policy.repositories.filter((r) => r.kind === 'product'))
1936
+ if (!gates.some((g) => g.repositoryId === repo.id && g.kind === 'test' && g.report))
1937
+ throw new HarnessError('INVALID_INPUT', `Нужна совместная проверка продукта ${repo.id}`);
1938
+ if (!input.workIds.length || new Set(input.workIds).size !== input.workIds.length)
1939
+ throw new HarnessError('INVALID_INPUT', 'Нужен непустой набор разных поручений');
1940
+ return this.tx('workspace.verification.started', (tx) => {
1941
+ this.assertCurrentPolicy(tx);
1942
+ const reconfigure = this.reconfiguring(tx);
1943
+ if (reconfigure)
1944
+ throw new HarnessError('NOT_READY', `Операция ${reconfigure.operation} применяет политику; дождитесь её`);
1945
+ if (tx.attempts().some((a) => a.status === 'active' && a.leaseUntil > this.now()))
1946
+ throw new HarnessError('NOT_READY', 'Дождитесь текущих попыток перед совместной проверкой');
1947
+ for (const v of tx.verifications()) {
1948
+ if (v.status !== 'active')
1949
+ continue;
1950
+ if (v.leaseUntil > this.now())
1951
+ throw new HarnessError('NOT_READY', 'Совместная проверка уже выполняется');
1952
+ const error = 'Истёк срок владения проверкой';
1953
+ tx.putVerification({ ...v, status: 'failed', error, finishedAt: iso(this.now()) });
1954
+ tx.emit({
1955
+ type: 'joint.finished',
1956
+ payload: { verificationId: v.id, status: 'failed', error },
1957
+ });
1958
+ }
1959
+ const previous = tx.verifications().filter((v) => sameWorks(v.workIds, input.workIds));
1960
+ if (previous.length >= this.policy.maxAttempts)
1961
+ throw new HarnessError('ATTEMPTS_EXHAUSTED', 'Исчерпан предел совместных проверок этого набора');
1962
+ const works = input.workIds.map((id) => tx.work(id));
1963
+ if (works.some((w) => !w || w.status !== 'done' || !w.resultSha))
1964
+ throw new HarnessError('NOT_READY', 'Сначала завершите все поручения набора');
1965
+ if (input.baseline && tx.verification(input.baseline)?.status !== 'passed')
1966
+ throw new HarnessError('INVALID_INPUT', 'Базовая проверка не найдена или не успешна');
1967
+ const at = this.now();
1968
+ const v = {
1969
+ apiVersion: 'devcontour-harness/v1alpha1',
1970
+ id: this.id(),
1971
+ token: this.id() + this.id(),
1972
+ engineVersion: this.version,
1973
+ startedAt: iso(at),
1974
+ leaseUntil: at + this.policy.leaseMs,
1975
+ status: 'active',
1976
+ policyDigest: this.jointPolicy(tx),
1977
+ specDigest: this.jointSpec(tx, input.workIds),
1978
+ workIds: [...input.workIds],
1979
+ ...(input.baseline
1980
+ ? {
1981
+ impact: {
1982
+ changed: [],
1983
+ affected: [],
1984
+ gateIds: [],
1985
+ mode: 'all',
1986
+ reason: 'manifest ещё не закреплён',
1987
+ baseline: input.baseline,
1988
+ },
1989
+ }
1990
+ : {}),
1991
+ evidence: [],
1992
+ };
1993
+ tx.putVerification(v);
1994
+ tx.emit({
1995
+ type: 'joint.started',
1996
+ payload: { verificationId: v.id, workIds: v.workIds, policyDigest: v.policyDigest },
1997
+ });
1998
+ return v;
1999
+ });
2000
+ }
2001
+ /**
2002
+ * Fencing совместной проверки: активна, токен её, срок не истёк, политика
2003
+ * и основание (поручения, их постановки и результаты) не изменились.
2004
+ */
2005
+ jointUpdate(id, token, kind, fn) {
2006
+ return this.tx(kind, (tx) => {
2007
+ if (kind !== 'heartbeat')
2008
+ this.assertCurrentPolicy(tx);
2009
+ const v = tx.verification(id);
2010
+ if (!v || v.status !== 'active' || v.token !== token || v.leaseUntil <= this.now())
2011
+ throw new HarnessError('LEASE_STALE', 'Устаревшая попытка совместной проверки');
2012
+ if (v.engineVersion !== this.version)
2013
+ throw new HarnessError('LEASE_STALE', `Совместную проверку начал движок ${v.engineVersion ?? 'прежней версии'}, а работает ${this.version}: нужна новая проверка`);
2014
+ if (v.policyDigest !== this.jointPolicy(tx) ||
2015
+ v.specDigest !== this.jointSpec(tx, v.workIds, v.id))
2016
+ throw new HarnessError('APPROVAL_STALE', 'Состав набора или политика изменились; нужна новая проверка');
2017
+ const out = fn(v, tx);
2018
+ // Продуктовые условия хоста — на состоянии после записи (закреплённый
2019
+ // manifest, итог): отказ откатывает всю запись.
2020
+ if (kind !== 'heartbeat') {
2021
+ const after = tx.verification(id);
2022
+ const refusal = this.host.guards.joint?.(after, tx, kind);
2023
+ if (refusal)
2024
+ throw new HarnessError(refusal.code, refusal.message);
2025
+ }
2026
+ return out;
2027
+ });
2028
+ }
2029
+ jointHeartbeat(id, token) {
2030
+ this.jointUpdate(id, token, 'heartbeat', (v, tx) => tx.putVerification({ ...v, leaseUntil: this.now() + this.policy.leaseMs }));
2031
+ }
2032
+ /**
2033
+ * Закрепить manifest: SHA и tree каждого репозитория политики. Закрепляется
2034
+ * один раз; по нему же выбирается область проверки.
2035
+ */
2036
+ jointManifest(id, token, manifest) {
2037
+ return this.jointUpdate(id, token, 'workspace.manifest', (v, tx) => {
2038
+ if (v.manifest)
2039
+ throw new HarnessError('INVALID_INPUT', 'Manifest уже закреплён');
2040
+ const ids = this.policy.repositories.map((r) => r.id).sort();
2041
+ const sha = /^[a-f0-9]{40,64}$/;
2042
+ if (JSON.stringify(Object.keys(manifest).sort()) !== JSON.stringify(ids) ||
2043
+ Object.values(manifest).some((m) => !sha.test(m.sha) || !sha.test(m.tree)))
2044
+ throw new HarnessError('INVALID_INPUT', 'Manifest должен фиксировать SHA и tree каждого репозитория');
2045
+ const baseline = v.impact?.baseline ? tx.verification(v.impact.baseline) : undefined;
2046
+ const impact = jointImpact(this.policy, manifest, v.policyDigest, baseline);
2047
+ const next = { ...v, manifest, manifestDigest: digestOf(manifest), impact };
2048
+ tx.putVerification(next);
2049
+ return next;
2050
+ });
2051
+ }
2052
+ jointEvidence(id, token, evidence) {
2053
+ this.jointUpdate(id, token, 'workspace.evidence', (v, tx) => {
2054
+ if (!v.manifest)
2055
+ throw new HarnessError('NOT_READY', 'Нет закреплённого manifest');
2056
+ tx.putVerification({ ...v, evidence: [...v.evidence, evidence] });
2057
+ });
2058
+ }
2059
+ jointMissing(v) {
2060
+ if (!v.manifest || digestOf(v.manifest) !== v.manifestDigest)
2061
+ return 'Нет закреплённого manifest';
2062
+ for (const gate of this.policy.workspaceGates.filter((g) => !v.impact || v.impact.gateIds.includes(g.id)))
2063
+ if (!v.evidence.findLast((e) => e.gate === gate.id)?.passed)
2064
+ return `Нет PASS: ${gate.id}`;
2065
+ return undefined;
2066
+ }
2067
+ jointFinish(id, token) {
2068
+ return this.jointUpdate(id, token, 'workspace.verified', (v, tx) => {
2069
+ const missing = this.jointMissing(v);
2070
+ if (missing)
2071
+ throw new HarnessError('GATE_FAILED', missing);
2072
+ const next = {
2073
+ ...v,
2074
+ status: 'passed',
2075
+ manifest: v.manifest,
2076
+ manifestDigest: v.manifestDigest,
2077
+ finishedAt: iso(this.now()),
2078
+ };
2079
+ tx.putVerification(next);
2080
+ tx.emit({
2081
+ type: 'joint.finished',
2082
+ payload: { verificationId: id, status: 'passed', manifestDigest: v.manifestDigest },
2083
+ });
2084
+ return publicJoint(next);
2085
+ });
2086
+ }
2087
+ /** Отказ проверки её владельцем; истёкший срок допустим, чужой токен — нет. */
2088
+ jointFail(id, token, error) {
2089
+ return this.tx('workspace.failed', (tx) => {
2090
+ const v = tx.verification(id);
2091
+ if (!v || v.status !== 'active' || v.token !== token || v.engineVersion !== this.version)
2092
+ return false;
2093
+ const message = error.slice(0, 4000) || 'Совместная проверка не прошла';
2094
+ tx.putVerification({ ...v, status: 'failed', error: message, finishedAt: iso(this.now()) });
2095
+ tx.emit({
2096
+ type: 'joint.finished',
2097
+ payload: { verificationId: id, status: 'failed', error: message },
2098
+ });
2099
+ return true;
2100
+ });
2101
+ }
2102
+ /**
2103
+ * Актуальный результат совместной проверки набора: последняя проверка этого
2104
+ * набора, успешная, с целым manifest, под текущей политикой, на неизменном
2105
+ * основании, с PASS каждого gate своей области. Иначе — причина; прежний
2106
+ * результат как актуальный не выдаётся.
2107
+ */
2108
+ jointResult(workIds,
2109
+ /** Оценить эту проверку набора, а не последнюю (хост выбирает её сам). */
2110
+ verificationId) {
2111
+ return this.read((v) => {
2112
+ const last = verificationId
2113
+ ? v.verification(verificationId)
2114
+ : v
2115
+ .verifications()
2116
+ .filter((x) => sameWorks(x.workIds, workIds))
2117
+ .at(-1);
2118
+ if (last && !sameWorks(last.workIds, workIds))
2119
+ return { current: false, reason: 'Проверка относится к другому набору' };
2120
+ if (!last)
2121
+ return { current: false, reason: 'Совместной проверки этого набора нет' };
2122
+ const verification = publicJoint(last);
2123
+ const reason = last.status !== 'passed'
2124
+ ? `Последняя проверка: ${last.status}${last.status === 'failed' ? ' — ' + last.error : ''}`
2125
+ : last.policyDigest !== this.jointPolicy(v)
2126
+ ? 'Политика совместной проверки изменилась'
2127
+ : last.specDigest !== this.jointSpec(v, last.workIds, last.id)
2128
+ ? 'Поручения набора или их результаты изменились'
2129
+ : this.jointMissing(last);
2130
+ return reason ? { verification, current: false, reason } : { verification, current: true };
2131
+ });
2132
+ }
2133
+ /** Истёкшие попытки: отказ окружения, работа ждёт явного повтора. */
2134
+ /**
2135
+ * Истечение владения на момент `at` (по умолчанию — сейчас). Хост передаёт
2136
+ * момент в будущем, когда снимает всё владение восстановленной копии.
2137
+ */
2138
+ expire(at = this.now()) {
2139
+ return this.tx('runs.expired', (tx) => {
2140
+ const ids = [];
2141
+ for (const a of tx.attempts())
2142
+ if (a.status === 'active' && a.leaseUntil <= at) {
2143
+ const error = (a.error?.startsWith(HEARTBEAT_FAILED) ? a.error + '. ' : '') +
2144
+ 'Истёк срок владения. Повторите явно.';
2145
+ const fingerprint = failureFingerprint('environment', error);
2146
+ tx.putAttempt({
2147
+ ...a,
2148
+ status: 'expired',
2149
+ finishedAt: iso(this.now()),
2150
+ error,
2151
+ failureKind: 'environment',
2152
+ failureFingerprint: fingerprint,
2153
+ });
2154
+ const w = tx.work(a.workId);
2155
+ if (w.activeRunId === a.id)
2156
+ tx.putWork({
2157
+ ...w,
2158
+ status: 'failed',
2159
+ failure: error,
2160
+ failureKind: 'environment',
2161
+ failureFingerprint: fingerprint,
2162
+ activeRunId: undefined,
2163
+ });
2164
+ tx.emit({
2165
+ type: 'attempt.expired',
2166
+ workId: a.workId,
2167
+ runId: a.id,
2168
+ attempt: a.attempt,
2169
+ payload: { leaseUntil: a.leaseUntil },
2170
+ });
2171
+ ids.push(a.id);
2172
+ }
2173
+ return ids;
2174
+ });
2175
+ }
2176
+ /** Восстановление: новый владелец истёкшей активной попытки получает новый токен. Старый токен недействителен. */
2177
+ adopt(id, owner) {
2178
+ return this.tx('run.recovered', (tx) => {
2179
+ const a = tx.attempt(id);
2180
+ if (!a)
2181
+ throw new HarnessError('NOT_FOUND', 'Попытка не найдена: ' + id);
2182
+ if (a.status !== 'active' || a.leaseUntil > this.now())
2183
+ throw new HarnessError('LEASE_STALE', 'Попытка ещё принадлежит владельцу');
2184
+ // Новое владение — под этим движком: дальше попытку ведёт он (и только он).
2185
+ const adopted = {
2186
+ ...a,
2187
+ token: this.id() + this.id(),
2188
+ owner,
2189
+ engineVersion: this.version,
2190
+ leaseUntil: this.now() + this.policy.leaseMs,
2191
+ };
2192
+ tx.putAttempt(adopted);
2193
+ return adopted;
2194
+ });
2195
+ }
2196
+ /** Recovery отклонил продолжение: попытка истечёт на следующем `expire`. */
2197
+ rejectRecovery(id, reason) {
2198
+ return this.tx('recovery.rejected', (tx) => {
2199
+ const a = tx.attempt(id);
2200
+ if (a?.status !== 'active')
2201
+ return false;
2202
+ tx.putAttempt({ ...a, leaseUntil: 0 });
2203
+ if (a.integrationSha)
2204
+ tx.emit({
2205
+ type: 'attempt.recovered',
2206
+ workId: a.workId,
2207
+ runId: a.id,
2208
+ attempt: a.attempt,
2209
+ payload: {
2210
+ integrationSha: a.integrationSha,
2211
+ accepted: false,
2212
+ reason: reason.slice(0, 4000),
2213
+ },
2214
+ });
2215
+ return true;
2216
+ });
2217
+ }
2218
+ /** Отмена: активная попытка теряет владение, поручение — cancelled. Принятое не отменяется. */
2219
+ cancel(workId, reason = 'отменено оператором') {
2220
+ return this.tx('task.cancelled', (tx) => {
2221
+ const w = tx.work(workId);
2222
+ if (!w)
2223
+ throw new HarnessError('NOT_FOUND', 'Поручение не найдено: ' + workId);
2224
+ if (w.status === 'done')
2225
+ throw new HarnessError('NOT_READY', 'Принятый результат не отменяется');
2226
+ if (w.status === 'cancelled')
2227
+ return { work: w, changed: false };
2228
+ const a = w.activeRunId ? tx.attempt(w.activeRunId) : undefined;
2229
+ if (a) {
2230
+ tx.putAttempt({
2231
+ ...a,
2232
+ status: 'cancelled',
2233
+ finishedAt: iso(this.now()),
2234
+ failureKind: 'cancelled',
2235
+ });
2236
+ tx.emit({
2237
+ type: 'attempt.cancelled',
2238
+ workId,
2239
+ runId: a.id,
2240
+ attempt: a.attempt,
2241
+ payload: { reason: reason.slice(0, 4000) },
2242
+ });
2243
+ }
2244
+ const next = {
2245
+ ...w,
2246
+ status: 'cancelled',
2247
+ activeRunId: undefined,
2248
+ failureKind: 'cancelled',
2249
+ };
2250
+ tx.putWork(next);
2251
+ return { work: next, changed: true };
2252
+ });
2253
+ }
2254
+ /**
2255
+ * Повтор неуспешного или отменённого поручения. Пока попытки не
2256
+ * исчерпаны — без сброса; исчерпаны — только явный сброс с причиной.
2257
+ * Класс и отпечаток прошлого отказа снимаются.
2258
+ */
2259
+ retry(workId, reset) {
2260
+ return this.tx('task.retry', (tx) => {
2261
+ const w = tx.work(workId);
2262
+ if (!w)
2263
+ throw new HarnessError('NOT_FOUND', 'Поручение не найдено: ' + workId);
2264
+ const exhausted = w.attempt >= this.policy.maxAttempts;
2265
+ if (w.status === 'ready' && !exhausted)
2266
+ return { work: w, changed: false };
2267
+ if (!['failed', 'cancelled'].includes(w.status) && !(exhausted && !w.activeRunId))
2268
+ throw new HarnessError('NOT_READY', 'Повтор доступен после отказа или отмены');
2269
+ if (exhausted && !reset?.reason.trim())
2270
+ throw new HarnessError('ATTEMPTS_EXHAUSTED', 'Исчерпан лимит попыток; повторите со сбросом и причиной');
2271
+ const next = {
2272
+ ...w,
2273
+ status: w.approvedDigest ? 'ready' : 'draft',
2274
+ attempt: exhausted ? 0 : w.attempt,
2275
+ failure: undefined,
2276
+ failureKind: undefined,
2277
+ failureFingerprint: undefined,
2278
+ };
2279
+ tx.putWork(next);
2280
+ return { work: next, changed: true };
2281
+ });
2282
+ }
2283
+ }