peaks-loop 4.1.4 → 4.1.6

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 (294) hide show
  1. package/.claude-plugin/marketplace.json +7 -2
  2. package/CHANGELOG.md +148 -0
  3. package/README-en.md +47 -183
  4. package/README.md +24 -188
  5. package/dist/cli/cli-helpers.d.ts +20 -0
  6. package/dist/cli/cli-helpers.js +34 -0
  7. package/dist/cli/commands/_register.js +2 -0
  8. package/dist/cli/commands/best-practice-scan-command.d.ts +11 -6
  9. package/dist/cli/commands/best-practice-scan-command.js +35 -20
  10. package/dist/cli/commands/best-practice-scan-helpers.d.ts +47 -0
  11. package/dist/cli/commands/best-practice-scan-helpers.js +88 -5
  12. package/dist/cli/commands/best-practice-scan-lookup-results.d.ts +13 -0
  13. package/dist/cli/commands/best-practice-scan-lookup-results.js +237 -0
  14. package/dist/cli/commands/code-commands.d.ts +6 -4
  15. package/dist/cli/commands/code-commands.js +6 -4
  16. package/dist/cli/commands/code-gate-command.d.ts +5 -5
  17. package/dist/cli/commands/code-gate-command.js +49 -9
  18. package/dist/cli/commands/code-mode-gate-plan-command.d.ts +1 -1
  19. package/dist/cli/commands/code-mode-gate-plan-command.js +2 -2
  20. package/dist/cli/commands/core/memory-extract-command.js +10 -5
  21. package/dist/cli/commands/dispatch-cli-invocation-check.d.ts +108 -0
  22. package/dist/cli/commands/dispatch-cli-invocation-check.js +87 -0
  23. package/dist/cli/commands/dispatch-cli-invocation-scan.d.ts +66 -0
  24. package/dist/cli/commands/dispatch-cli-invocation-scan.js +162 -0
  25. package/dist/cli/commands/dispatch-command-spec.js +1 -1
  26. package/dist/cli/commands/dispatch-commands.js +12 -5
  27. package/dist/cli/commands/dispatch-isolation-lease.d.ts +1 -1
  28. package/dist/cli/commands/dispatch-isolation-lease.js +6 -53
  29. package/dist/cli/commands/dispatch-preflight.js +46 -0
  30. package/dist/cli/commands/dispatch-prompt-blocks.d.ts +1 -1
  31. package/dist/cli/commands/dispatch-prompt-composition.d.ts +7 -1
  32. package/dist/cli/commands/dispatch-prompt-composition.js +29 -7
  33. package/dist/cli/commands/dispatch-record-write.d.ts +1 -1
  34. package/dist/cli/commands/dispatch-tool-call.d.ts +1 -1
  35. package/dist/cli/commands/doc-commands.js +1 -1
  36. package/dist/cli/commands/feedback-commands-helpers.js +1 -1
  37. package/dist/cli/commands/final-review-prepare-command.js +22 -1
  38. package/dist/cli/commands/gate-commands-enforce.js +3 -3
  39. package/dist/cli/commands/hook-handle.js +41 -20
  40. package/dist/cli/commands/lint-commands.js +3 -1
  41. package/dist/cli/commands/loop-eval-capture-index.js +2 -4
  42. package/dist/cli/commands/openspec-command-shared.js +2 -2
  43. package/dist/cli/commands/perf-audit-commands.js +15 -5
  44. package/dist/cli/commands/project-commands.js +9 -6
  45. package/dist/cli/commands/race-commands.d.ts +15 -0
  46. package/dist/cli/commands/race-commands.js +65 -0
  47. package/dist/cli/commands/race-pilot-gate-record-command.d.ts +3 -0
  48. package/dist/cli/commands/race-pilot-gate-record-command.js +81 -0
  49. package/dist/cli/commands/request-command-options.d.ts +8 -0
  50. package/dist/cli/commands/request-commands.js +2 -0
  51. package/dist/cli/commands/request-init-command.js +67 -12
  52. package/dist/cli/commands/{vm-status-command.d.ts → request-retag-command.d.ts} +1 -1
  53. package/dist/cli/commands/request-retag-command.js +50 -0
  54. package/dist/cli/commands/request-show-command.d.ts +8 -0
  55. package/dist/cli/commands/request-show-command.js +14 -1
  56. package/dist/cli/commands/request-transition-command.js +12 -4
  57. package/dist/cli/commands/request-transition-failures.d.ts +14 -0
  58. package/dist/cli/commands/request-transition-failures.js +76 -7
  59. package/dist/cli/commands/request-transition-preflight.js +1 -1
  60. package/dist/cli/commands/scan-scope-commands.js +2 -2
  61. package/dist/cli/commands/security-audit-commands.js +26 -6
  62. package/dist/cli/commands/slice-decompose-artifacts.js +2 -1
  63. package/dist/cli/commands/verdict-aggregate-command.js +2 -1
  64. package/dist/cli/commands/workflow-gate-commands.js +4 -4
  65. package/dist/cli/commands/worktree-lease-gc-command.js +1 -1
  66. package/dist/cli/program.js +0 -2
  67. package/dist/services/artifacts/artifact-contract-block.d.ts +53 -0
  68. package/dist/services/artifacts/artifact-contract-block.js +231 -0
  69. package/dist/services/artifacts/artifact-prerequisites.d.ts +27 -19
  70. package/dist/services/artifacts/artifact-prerequisites.js +65 -135
  71. package/dist/services/artifacts/artifact-templates.d.ts +1 -1
  72. package/dist/services/artifacts/artifact-templates.js +17 -10
  73. package/dist/services/artifacts/prerequisite-checks.d.ts +87 -0
  74. package/dist/services/artifacts/prerequisite-checks.js +198 -0
  75. package/dist/services/artifacts/prerequisite-transition-event.d.ts +20 -0
  76. package/dist/services/artifacts/prerequisite-transition-event.js +27 -0
  77. package/dist/services/artifacts/rd-transition-gates.d.ts +33 -0
  78. package/dist/services/artifacts/rd-transition-gates.js +71 -0
  79. package/dist/services/artifacts/request-artifact-metadata.d.ts +31 -0
  80. package/dist/services/artifacts/request-artifact-metadata.js +44 -0
  81. package/dist/services/artifacts/request-artifact-service.d.ts +5 -0
  82. package/dist/services/artifacts/request-artifact-service.js +43 -69
  83. package/dist/services/artifacts/request-artifact-state-helpers.d.ts +21 -1
  84. package/dist/services/artifacts/request-artifact-state-helpers.js +34 -8
  85. package/dist/services/artifacts/request-retag-service.d.ts +68 -0
  86. package/dist/services/artifacts/request-retag-service.js +125 -0
  87. package/dist/services/artifacts/request-state-order.d.ts +38 -0
  88. package/dist/services/artifacts/request-state-order.js +99 -0
  89. package/dist/services/artifacts/request-type-demand.d.ts +44 -0
  90. package/dist/services/artifacts/request-type-demand.js +71 -0
  91. package/dist/services/audit/audit-goal-service.d.ts +7 -0
  92. package/dist/services/audit/enforcers/active-skill-resolver.d.ts +18 -0
  93. package/dist/services/audit/enforcers/active-skill-resolver.js +48 -1
  94. package/dist/services/audit/enforcers/code-ban.d.ts +11 -2
  95. package/dist/services/audit/enforcers/code-ban.js +21 -1
  96. package/dist/services/audit/red-line-catalog-p2-a-bee-runtime.d.ts +17 -0
  97. package/dist/services/audit/red-line-catalog-p2-a-bee-runtime.js +24 -7
  98. package/dist/services/audit-independent/handoff-missing-refusal.d.ts +26 -0
  99. package/dist/services/audit-independent/handoff-missing-refusal.js +109 -0
  100. package/dist/services/audit-independent/handoff-readers.d.ts +37 -0
  101. package/dist/services/audit-independent/handoff-readers.js +81 -0
  102. package/dist/services/audit-independent/index.d.ts +6 -1
  103. package/dist/services/audit-independent/index.js +6 -1
  104. package/dist/services/audit-independent/judged-declaration-build.d.ts +48 -0
  105. package/dist/services/audit-independent/judged-declaration-build.js +73 -0
  106. package/dist/services/audit-independent/judged-declaration-check.d.ts +80 -0
  107. package/dist/services/audit-independent/judged-declaration-check.js +216 -0
  108. package/dist/services/audit-independent/judged-declaration.d.ts +94 -0
  109. package/dist/services/audit-independent/judged-declaration.js +218 -0
  110. package/dist/services/audit-independent/perf-audit-service.js +12 -14
  111. package/dist/services/audit-independent/security-audit-artifact.d.ts +28 -0
  112. package/dist/services/audit-independent/security-audit-artifact.js +90 -0
  113. package/dist/services/audit-independent/security-audit-service.d.ts +6 -53
  114. package/dist/services/audit-independent/security-audit-service.js +34 -178
  115. package/dist/services/capability-guard-runner/contracts/J05.js +60 -14
  116. package/dist/services/codegraph/codegraph-index-integrity.js +2 -0
  117. package/dist/services/context/build-dispatch-system-prompt.d.ts +8 -12
  118. package/dist/services/context/build-dispatch-system-prompt.js +18 -18
  119. package/dist/services/context/collector.js +5 -1
  120. package/dist/services/context/post-compact-reinjection.js +1 -1
  121. package/dist/services/dispatch/active-dispatch-index.d.ts +36 -0
  122. package/dist/services/dispatch/active-dispatch-index.js +118 -0
  123. package/dist/services/dispatch/batch-counter.js +1 -2
  124. package/dist/services/dispatch/dispatch-record-writer.d.ts +29 -16
  125. package/dist/services/dispatch/dispatch-record-writer.js +58 -100
  126. package/dist/services/dispatch/dispatch-sub-agent.js +1 -1
  127. package/dist/services/dispatch/karpathy-block.d.ts +55 -0
  128. package/dist/services/dispatch/karpathy-block.js +101 -0
  129. package/dist/services/dispatch/ledger-reaper.d.ts +80 -0
  130. package/dist/services/dispatch/ledger-reaper.js +131 -0
  131. package/dist/services/dispatch/test-tool-detection.d.ts +17 -1
  132. package/dist/services/dispatch/test-tool-detection.js +12 -1
  133. package/dist/services/evidence/evidence-generator.js +23 -12
  134. package/dist/services/feedback/feedback-promotion-service.d.ts +8 -11
  135. package/dist/services/feedback/feedback-promotion-service.js +30 -35
  136. package/dist/services/feedback/promotion-artifact-json-evidence.d.ts +18 -0
  137. package/dist/services/feedback/promotion-artifact-missing.d.ts +22 -0
  138. package/dist/services/feedback/promotion-artifact-missing.js +63 -0
  139. package/dist/services/final-review/final-review-contract.d.ts +95 -4
  140. package/dist/services/final-review/final-review-contract.js +64 -0
  141. package/dist/services/final-review/final-review-delivery.d.ts +13 -0
  142. package/dist/services/final-review/final-review-delivery.js +26 -12
  143. package/dist/services/final-review/final-review-evidence-collect.js +8 -53
  144. package/dist/services/final-review/final-review-evidence-records.d.ts +21 -0
  145. package/dist/services/final-review/final-review-evidence-records.js +67 -0
  146. package/dist/services/final-review/final-review-evidence-sources.d.ts +22 -0
  147. package/dist/services/final-review/final-review-evidence-sources.js +28 -4
  148. package/dist/services/final-review/final-review-prompt.js +19 -6
  149. package/dist/services/final-review/final-review-runner.js +5 -0
  150. package/dist/services/final-review/final-review-service.d.ts +2 -2
  151. package/dist/services/final-review/index.d.ts +1 -1
  152. package/dist/services/final-review/pre-post-diff.d.ts +2 -75
  153. package/dist/services/final-review/pre-post-diff.js +60 -59
  154. package/dist/services/hooks/pre-tool-code-gate.d.ts +7 -1
  155. package/dist/services/hooks/pre-tool-code-gate.js +21 -2
  156. package/dist/services/hooks/worktree-authorization-gate.js +6 -31
  157. package/dist/services/hooks/worktree-refusal-messages.d.ts +74 -0
  158. package/dist/services/hooks/worktree-refusal-messages.js +102 -0
  159. package/dist/services/lint/eslint-runner-support.d.ts +1 -1
  160. package/dist/services/lint/eslint-runner-support.js +2 -1
  161. package/dist/services/lint/eslint-runner-types.d.ts +8 -0
  162. package/dist/services/lint/eslint-runner.js +17 -4
  163. package/dist/services/llm/anthropic-runner.js +24 -7
  164. package/dist/services/loop/loop-observability.d.ts +39 -0
  165. package/dist/services/loop/loop-observability.js +55 -0
  166. package/dist/services/loop/monotonic-guard.js +6 -9
  167. package/dist/services/loop/monotonic-runner.js +8 -7
  168. package/dist/services/loop/run-driver.js +18 -22
  169. package/dist/services/memory/project-memory-service/index/kind-dispatch.js +14 -1
  170. package/dist/services/memory/project-memory-service/index/project-memory-plan-exec.js +13 -2
  171. package/dist/services/memory/project-memory-service/index.d.ts +2 -2
  172. package/dist/services/memory/project-memory-service/index.js +1 -1
  173. package/dist/services/memory/project-memory-service/parsers/frontmatter-parse.d.ts +36 -0
  174. package/dist/services/memory/project-memory-service/parsers/frontmatter-parse.js +48 -2
  175. package/dist/services/memory/project-memory-service/parsers/markdown-pure.d.ts +23 -1
  176. package/dist/services/memory/project-memory-service/parsers/markdown-pure.js +37 -0
  177. package/dist/services/memory/project-memory-service/types.d.ts +32 -0
  178. package/dist/services/observability/observability-service.d.ts +7 -0
  179. package/dist/services/observability/observability-service.js +2 -1
  180. package/dist/services/openspec/coverage-evidence-reader.d.ts +9 -9
  181. package/dist/services/openspec/coverage-evidence-reader.js +8 -8
  182. package/dist/services/openspec/openspec-archive-service.d.ts +1 -1
  183. package/dist/services/openspec/openspec-archive-service.js +6 -6
  184. package/dist/services/prd/gate-evidence-derivation.d.ts +4 -3
  185. package/dist/services/prd/gate-evidence-derivation.js +4 -3
  186. package/dist/services/qa/bdd-test-style-verifier.js +22 -8
  187. package/dist/services/race/gate2-evaluator.d.ts +58 -0
  188. package/dist/services/race/gate2-evaluator.js +111 -0
  189. package/dist/services/race/gate2-policy.d.ts +17 -0
  190. package/dist/services/race/gate2-policy.js +31 -0
  191. package/dist/services/race/lane-phase.d.ts +19 -0
  192. package/dist/services/race/lane-phase.js +113 -0
  193. package/dist/services/race/pilot-gate-store.d.ts +67 -0
  194. package/dist/services/race/pilot-gate-store.js +227 -0
  195. package/dist/services/scan/file-size-baseline.d.ts +33 -0
  196. package/dist/services/scan/file-size-baseline.js +173 -0
  197. package/dist/services/scan/file-size-scan.d.ts +35 -3
  198. package/dist/services/scan/file-size-scan.js +63 -42
  199. package/dist/services/scan/type-corroboration.d.ts +32 -0
  200. package/dist/services/scan/type-corroboration.js +51 -0
  201. package/dist/services/scan/type-sanity-service.d.ts +14 -0
  202. package/dist/services/scan/type-sanity-service.js +23 -22
  203. package/dist/services/security/safe-settings-path.d.ts +5 -0
  204. package/dist/services/security/safe-settings-path.js +64 -8
  205. package/dist/services/skill/resume-detector.js +11 -11
  206. package/dist/services/skills/hooks-codegate-superpowers.d.ts +5 -6
  207. package/dist/services/skills/hooks-codegate-superpowers.js +7 -8
  208. package/dist/services/skills/hooks-settings-service.d.ts +1 -1
  209. package/dist/services/skills/hooks-settings-service.js +1 -1
  210. package/dist/services/skills/presence-lease-order.d.ts +13 -0
  211. package/dist/services/skills/presence-lease-order.js +24 -0
  212. package/dist/services/skills/skill-conformance-service.js +1 -0
  213. package/dist/services/skills/skill-statusline-service.js +4 -7
  214. package/dist/services/slice/slice-check-service.js +8 -8
  215. package/dist/services/workflow/pipeline-verify-gate-support.d.ts +24 -8
  216. package/dist/services/workflow/pipeline-verify-gate-support.js +34 -39
  217. package/dist/services/workflow/pipeline-verify-qa-phase.d.ts +102 -0
  218. package/dist/services/workflow/pipeline-verify-qa-phase.js +176 -0
  219. package/dist/services/workflow/pipeline-verify-service.js +27 -28
  220. package/dist/services/workflow/request-type-resolution.d.ts +99 -0
  221. package/dist/services/workflow/request-type-resolution.js +130 -0
  222. package/dist/services/workflow/workflow-skip-service.d.ts +1 -20
  223. package/dist/services/workflow/workflow-skip-service.js +22 -25
  224. package/dist/services/workflow/workflow-state-store.d.ts +9 -0
  225. package/dist/services/workflow/workflow-state-store.js +26 -1
  226. package/dist/services/workspace/claude-settings-retirements.d.ts +54 -0
  227. package/dist/services/workspace/claude-settings-retirements.js +112 -0
  228. package/dist/services/workspace/claude-settings-template-merge.d.ts +35 -15
  229. package/dist/services/workspace/claude-settings-template-merge.js +33 -53
  230. package/dist/services/workspace/claude-settings-template.d.ts +62 -12
  231. package/dist/services/workspace/claude-settings-template.js +58 -58
  232. package/dist/services/workspace/migrate-1-4-1-service.js +3 -0
  233. package/dist/services/workspace/reconcile-service.js +0 -1
  234. package/dist/shared/incrementing-number.d.ts +33 -2
  235. package/dist/shared/incrementing-number.js +72 -3
  236. package/package.json +5 -7
  237. package/skills/bee/peaks-perf-audit/SKILL.md +1 -1
  238. package/skills/bee/peaks-prd/SKILL.md +4 -3
  239. package/skills/bee/peaks-qa/SKILL.md +1 -1
  240. package/skills/bee/peaks-qa/references/qa-sub-agent-dispatch.md +2 -2
  241. package/skills/bee/peaks-qa/references/qa-transition-gates.md +1 -1
  242. package/skills/bee/peaks-rd/SKILL.md +2 -2
  243. package/skills/bee/peaks-rd/references/rd-fanout-contracts.md +1 -1
  244. package/skills/bee/peaks-rd/references/rd-sub-agent-dispatch.md +8 -4
  245. package/skills/bee/peaks-rd/references/rd-transition-gates.md +3 -3
  246. package/skills/bee/peaks-rd/references/v2-12-fanout-collapse.md +2 -2
  247. package/skills/bee/peaks-rd/references/writing-handoff-frontmatter.md +1 -1
  248. package/skills/bee/peaks-reviewer/SKILL.md +1 -1
  249. package/skills/bee/peaks-sc/SKILL.md +1 -1
  250. package/skills/bee/peaks-security-audit/SKILL.md +10 -2
  251. package/skills/bee/peaks-txt/SKILL.md +4 -3
  252. package/skills/bee/peaks-ui/SKILL.md +3 -3
  253. package/skills/peaks-audit/SKILL.md +29 -1
  254. package/skills/peaks-code/SKILL.md +37 -17
  255. package/skills/peaks-code/references/fast-lane-norm.md +42 -0
  256. package/skills/peaks-code/references/fast-mode.md +3 -2
  257. package/skills/peaks-code/references/local-artifact-workspace.md +3 -3
  258. package/skills/peaks-code/references/micro-cycle.md +3 -3
  259. package/skills/peaks-code/references/resume-detection.md +1 -1
  260. package/skills/peaks-code/references/runbook.md +12 -6
  261. package/skills/peaks-code/references/step-11-memory-sediment.md +4 -0
  262. package/skills/peaks-code/references/sub-agent-dispatch.md +1 -1
  263. package/skills/peaks-code/references/swarm-dispatch-contract.md +40 -16
  264. package/skills/peaks-code/references/workflow-gates-and-types.md +6 -6
  265. package/skills/peaks-code/references/worktree-governance.md +4 -4
  266. package/skills/peaks-content/SKILL.md +1 -1
  267. package/skills/peaks-doctor/SKILL.md +1 -1
  268. package/skills/peaks-final-review/SKILL.md +31 -11
  269. package/skills/peaks-ide/SKILL.md +1 -1
  270. package/skills/peaks-issue-fix-orchestrator/SKILL.md +1 -1
  271. package/skills/peaks-race-code/SKILL.md +185 -0
  272. package/skills/peaks-resume/SKILL.md +1 -1
  273. package/skills/peaks-slice-decompose/SKILL.md +1 -1
  274. package/skills/peaks-solo/SKILL.md +1 -1
  275. package/skills/peaks-sop/SKILL.md +1 -1
  276. package/skills/peaks-status/SKILL.md +1 -1
  277. package/skills/peaks-test/SKILL.md +7 -4
  278. package/dist/cli/commands/vm-command-shared.d.ts +0 -23
  279. package/dist/cli/commands/vm-command-shared.js +0 -23
  280. package/dist/cli/commands/vm-commands.d.ts +0 -3
  281. package/dist/cli/commands/vm-commands.js +0 -45
  282. package/dist/cli/commands/vm-hypervisor-probe.d.ts +0 -27
  283. package/dist/cli/commands/vm-hypervisor-probe.js +0 -78
  284. package/dist/cli/commands/vm-hypervisor-runtime.d.ts +0 -15
  285. package/dist/cli/commands/vm-hypervisor-runtime.js +0 -64
  286. package/dist/cli/commands/vm-release-command.d.ts +0 -5
  287. package/dist/cli/commands/vm-release-command.js +0 -101
  288. package/dist/cli/commands/vm-spawn-command.d.ts +0 -5
  289. package/dist/cli/commands/vm-spawn-command.js +0 -177
  290. package/dist/cli/commands/vm-status-command.js +0 -50
  291. package/dist/services/audit/enforcers/lint-peaks-skill-runtime.d.ts +0 -23
  292. package/dist/services/audit/enforcers/lint-peaks-skill-runtime.js +0 -64
  293. package/dist/services/vm/vm-lease.d.ts +0 -40
  294. package/dist/services/vm/vm-lease.js +0 -160
@@ -1,101 +0,0 @@
1
- // src/cli/commands/vm-release-command.ts
2
- //
3
- // `peaks vm release` — transition a VM lease to released and run the
4
- // hypervisor destroy command. Split out of `vm-commands.ts`; every refusal
5
- // code, message, `data` field, warning and next-action string is unchanged.
6
- import { existsSync, readFileSync } from 'node:fs';
7
- import { fail, getErrorMessage, ok } from 'peaks-loop-shared/result';
8
- import { addJsonOption, printResult } from '../cli-helpers.js';
9
- import { findProjectRoot } from '../../services/config/config-safety.js';
10
- import { atomicWriteJson } from '../../services/ide/shared/atomic-json.js';
11
- import { deserializeVmLease, markVmReleased, vmLeaseFilePath } from '../../services/vm/vm-lease.js';
12
- import { destroyVmWithHypervisor } from './vm-hypervisor-runtime.js';
13
- import { joinPathSession, resolveVmSessionId } from './vm-command-shared.js';
14
- /** Print a `vm.release` refusal; the caller stops. */
15
- function emitReleaseRefusal(io, options, refusal) {
16
- printResult(io, fail('vm.release', refusal.code, refusal.message, refusal.data, refusal.nextActions), options.json ?? false);
17
- process.exitCode = 1;
18
- }
19
- /** The lease on disk, or null after the matching refusal envelope was printed. */
20
- function readLeaseOrRefuse(io, options, file) {
21
- if (!existsSync(file)) {
22
- emitReleaseRefusal(io, options, {
23
- code: 'LEASE_NOT_FOUND',
24
- message: `no VM lease on disk at ${file}`,
25
- data: { leaseId: options.leaseId, file },
26
- nextActions: [
27
- 'Run `peaks vm list` (follow-up) to inspect active leases.',
28
- 'For a never-spawned lease, this is a no-op.'
29
- ]
30
- });
31
- return null;
32
- }
33
- try {
34
- return deserializeVmLease(readFileSync(file, 'utf8'));
35
- }
36
- catch (err) {
37
- emitReleaseRefusal(io, options, {
38
- code: 'LEASE_FILE_INVALID',
39
- message: getErrorMessage(err),
40
- data: { leaseId: options.leaseId, file },
41
- nextActions: ['Delete the malformed lease file manually and re-spawn.']
42
- });
43
- return null;
44
- }
45
- }
46
- function emitAlreadyReleased(io, options, target, lease) {
47
- printResult(io, ok('vm.release', {
48
- lease,
49
- sessionId: target.sessionId,
50
- projectRoot: target.projectRoot,
51
- alreadyReleased: true
52
- }, [], [`Lease ${lease.leaseId} already released; nothing to do.`]), options.json ?? false);
53
- }
54
- function emitReleaseSuccess(io, options, target, lease) {
55
- const destroyed = destroyVmWithHypervisor({ hypervisor: lease.hypervisor, vmId: lease.vmId });
56
- const released = markVmReleased(lease);
57
- atomicWriteJson(target.file, released);
58
- printResult(io, ok('vm.release', {
59
- lease: released,
60
- sessionId: target.sessionId,
61
- projectRoot: target.projectRoot,
62
- vmDestroyed: destroyed
63
- }, destroyed
64
- ? []
65
- : [`${lease.hypervisor} destroy command failed; the lease was marked released anyway.`], [
66
- `Lease ${lease.leaseId} marked released.`,
67
- destroyed
68
- ? `${lease.hypervisor} domain ${lease.vmId} stopped.`
69
- : `Manual \`${lease.hypervisor} stop ${lease.vmId}\` may be needed.`
70
- ]), options.json ?? false);
71
- }
72
- export function runVmRelease(io, options) {
73
- try {
74
- const projectRoot = options.project ?? findProjectRoot(process.cwd()) ?? process.cwd();
75
- const sessionId = resolveVmSessionId(projectRoot, options.session);
76
- const file = vmLeaseFilePath(joinPathSession(projectRoot, sessionId), options.leaseId);
77
- const lease = readLeaseOrRefuse(io, options, file);
78
- if (lease === null)
79
- return;
80
- if (lease.status === 'released') {
81
- emitAlreadyReleased(io, options, { projectRoot, sessionId, file }, lease);
82
- return;
83
- }
84
- emitReleaseSuccess(io, options, { projectRoot, sessionId, file }, lease);
85
- }
86
- catch (err) {
87
- printResult(io, fail('vm.release', 'RELEASE_FAILED', getErrorMessage(err), {
88
- leaseId: options.leaseId,
89
- sessionId: options.session ?? process.env.PEAKS_SESSION_ID ?? 'unknown-sid'
90
- }, ['Verify the lease id and re-run.']), options.json ?? false);
91
- process.exitCode = 1;
92
- }
93
- }
94
- export function registerVmReleaseCommand(cmd, io) {
95
- addJsonOption(cmd
96
- .command('release')
97
- .description('Transition a VM lease to released and run the hypervisor destroy command. Idempotent on already-released leases.')
98
- .requiredOption('--lease-id <id>', 'lease id returned by `peaks vm spawn`')
99
- .option('--session <sid>', 'override session id')
100
- .option('--project <path>', 'project root (default: findProjectRoot(cwd))')).action((options) => runVmRelease(io, options));
101
- }
@@ -1,5 +0,0 @@
1
- import type { Command } from 'commander';
2
- import { type ProgramIO } from '../cli-helpers.js';
3
- import { type SpawnOptions } from './vm-command-shared.js';
4
- export declare function runVmSpawn(io: ProgramIO, options: SpawnOptions): void;
5
- export declare function registerVmSpawnCommand(cmd: Command, io: ProgramIO): void;
@@ -1,177 +0,0 @@
1
- // src/cli/commands/vm-spawn-command.ts
2
- //
3
- // `peaks vm spawn` — pick a hypervisor, probe it, spawn the VM and write the
4
- // lease. Split out of `vm-commands.ts`; every refusal code, message, `data`
5
- // field, next-action string and exit code is unchanged.
6
- import { existsSync } from 'node:fs';
7
- import { fail, getErrorMessage, ok } from 'peaks-loop-shared/result';
8
- import { addJsonOption, printResult } from '../cli-helpers.js';
9
- import { findProjectRoot } from '../../services/config/config-safety.js';
10
- import { atomicWriteJson } from '../../services/ide/shared/atomic-json.js';
11
- import { DEFAULT_VM_IMAGE, finalizeVmLease, generateVmLeaseId, vmLeaseFilePath } from '../../services/vm/vm-lease.js';
12
- import { detectHypervisor } from './vm-hypervisor-probe.js';
13
- import { spawnVmWithHypervisor } from './vm-hypervisor-runtime.js';
14
- import { joinPathSession, resolveTtlMs, resolveVmSessionId } from './vm-command-shared.js';
15
- /** Explicit `--hypervisor` wins; otherwise only `/dev/kvm` auto-detects. */
16
- function pickHypervisor(explicit) {
17
- if (explicit !== undefined)
18
- return explicit;
19
- // No platform detector for hyperkit / hyperv — those require --hypervisor.
20
- if (existsSync('/dev/kvm'))
21
- return 'kvm';
22
- return null;
23
- }
24
- function buildSpawnContext(options, projectRoot, sessionId, hypervisor) {
25
- return {
26
- projectRoot,
27
- sessionId,
28
- hypervisor,
29
- image: options.image ?? DEFAULT_VM_IMAGE,
30
- mount: options.mount ?? projectRoot,
31
- ttlMs: resolveTtlMs(options.ttl, options.role),
32
- leaseId: generateVmLeaseId(),
33
- now: Date.now()
34
- };
35
- }
36
- function emitSpawnRefusal(io, options, refusal) {
37
- printResult(io, fail('vm.spawn', refusal.code, refusal.message, refusal.data, refusal.nextActions), options.json ?? false);
38
- process.exitCode = 1;
39
- }
40
- function emitHypervisorUnspecified(io, options, sessionId) {
41
- emitSpawnRefusal(io, options, {
42
- code: 'VM_HYPERVISOR_UNSPECIFIED',
43
- message: 'No --hypervisor given and the host does not advertise /dev/kvm. Pass --hypervisor hyperkit|hyperv to force one.',
44
- data: { rid: options.rid, sessionId },
45
- nextActions: [
46
- 'Linux KVM: ensure /dev/kvm exists and the kvm kernel module is loaded.',
47
- 'macOS HyperKit: install hvftool (brew install hyperkit) and pass --hypervisor hyperkit.',
48
- 'Windows Hyper-V: install the hvc shim and pass --hypervisor hyperv.'
49
- ]
50
- });
51
- }
52
- function emitRuntimeUnavailable(io, options, detail) {
53
- emitSpawnRefusal(io, options, {
54
- code: 'VM_RUNTIME_UNAVAILABLE',
55
- message: `${detail.hypervisor} runtime not available: ${detail.stderr}`,
56
- data: { rid: options.rid, hypervisor: detail.hypervisor, sessionId: detail.sessionId },
57
- nextActions: [
58
- `Install the ${detail.hypervisor} runtime binary on PATH.`,
59
- 'The dispatch fail-fast prevents fallback to a different hypervisor (caller chose this mode for a reason).'
60
- ]
61
- });
62
- }
63
- /** Spawn, or print the spawn failure and return null. */
64
- function spawnOrFail(io, options, ctx) {
65
- try {
66
- return spawnVmWithHypervisor({
67
- hypervisor: ctx.hypervisor,
68
- image: ctx.image,
69
- mount: ctx.mount,
70
- leaseId: ctx.leaseId,
71
- rid: options.rid,
72
- workdir: ctx.projectRoot
73
- }).vmId;
74
- }
75
- catch (err) {
76
- emitSpawnRefusal(io, options, {
77
- code: 'VM_SPAWN_FAILED',
78
- message: getErrorMessage(err),
79
- data: {
80
- rid: options.rid,
81
- hypervisor: ctx.hypervisor,
82
- image: ctx.image,
83
- sessionId: ctx.sessionId
84
- },
85
- nextActions: [
86
- 'Verify the image / vhdx is reachable on the host.',
87
- `For ${ctx.hypervisor}: the spawn helper expects domain XML / hvftool args / hvc shim.`
88
- ]
89
- });
90
- return null;
91
- }
92
- }
93
- function emitSpawnSuccess(io, options, spawned) {
94
- const { ctx, vmId, binary } = spawned;
95
- const lease = finalizeVmLease({
96
- leaseId: ctx.leaseId,
97
- rid: options.rid,
98
- role: options.role,
99
- path: ctx.mount,
100
- hypervisor: ctx.hypervisor,
101
- image: ctx.image,
102
- vmId,
103
- createdAt: ctx.now,
104
- expiresAt: ctx.now + ctx.ttlMs,
105
- purpose: options.purpose
106
- });
107
- atomicWriteJson(vmLeaseFilePath(joinPathSession(ctx.projectRoot, ctx.sessionId), ctx.leaseId), lease);
108
- printResult(io, ok('vm.spawn', {
109
- lease,
110
- sessionId: ctx.sessionId,
111
- projectRoot: ctx.projectRoot,
112
- hypervisor: ctx.hypervisor,
113
- runtime: binary,
114
- ttlMs: ctx.ttlMs,
115
- nextActions: [
116
- `VM domain id: ${vmId}`,
117
- `Image: ${ctx.image}`,
118
- `Lease expires at: ${new Date(lease.expiresAt).toISOString()}`,
119
- 'Run `peaks vm release --lease-id <lease-id>` when done',
120
- 'For inside-the-VM exec, a follow-up rid adds `peaks vm exec` (Part 35 ships lease + spawn/release only).'
121
- ]
122
- }, [], []), options.json ?? false);
123
- }
124
- export function runVmSpawn(io, options) {
125
- try {
126
- const projectRoot = options.project ?? findProjectRoot(process.cwd()) ?? process.cwd();
127
- const sessionId = resolveVmSessionId(projectRoot, options.session);
128
- const detected = pickHypervisor(options.hypervisor);
129
- if (detected === null) {
130
- emitHypervisorUnspecified(io, options, sessionId);
131
- return;
132
- }
133
- const probe = detectHypervisor(detected);
134
- if (!probe.ok) {
135
- emitRuntimeUnavailable(io, options, {
136
- sessionId,
137
- hypervisor: detected,
138
- stderr: probe.stderr
139
- });
140
- return;
141
- }
142
- const ctx = buildSpawnContext(options, projectRoot, sessionId, detected);
143
- const vmId = spawnOrFail(io, options, ctx);
144
- if (vmId === null)
145
- return;
146
- emitSpawnSuccess(io, options, { ctx, vmId, binary: probe.binary });
147
- }
148
- catch (err) {
149
- emitSpawnRefusal(io, options, {
150
- code: 'SPAWN_FAILED',
151
- message: getErrorMessage(err),
152
- data: {
153
- rid: options.rid,
154
- sessionId: options.session ?? process.env.PEAKS_SESSION_ID ?? 'unknown-sid'
155
- },
156
- nextActions: [
157
- 'See error message; if the lease was not written, retry after fixing the underlying issue.'
158
- ]
159
- });
160
- }
161
- }
162
- export function registerVmSpawnCommand(cmd, io) {
163
- addJsonOption(cmd
164
- .command('spawn')
165
- .description('Spawn a VM via the requested hypervisor (kvm | hyperkit | hyperv) and write a VM lease. ' +
166
- 'Default TTL is role-aware (rd=30m / qa=15m / ui=1h); pass --ttl <ms> to override. ' +
167
- 'Default image is `peaks-base:22-slim`; pass --image <name> to override.')
168
- .requiredOption('--rid <rid>', 'peaks request id the lease is associated with')
169
- .requiredOption('--role <role>', 'sub-agent role (rd | qa | ui | sc | prd | general-purpose)')
170
- .requiredOption('--purpose <text>', 'why this VM was spawned (audit log)')
171
- .option('--hypervisor <name>', 'hypervisor to use: kvm | hyperkit | hyperv (default: auto-detect from host)')
172
- .option('--image <name>', `container image / vhdx to boot (default ${DEFAULT_VM_IMAGE})`)
173
- .option('--ttl <ms>', 'time-to-live in ms (default role-aware; override with positive number)')
174
- .option('--mount <path>', 'host path to mount as the VM working dir (default: <projectRoot>)')
175
- .option('--session <sid>', 'override session id')
176
- .option('--project <path>', 'project root (default: findProjectRoot(cwd))')).action((options) => runVmSpawn(io, options));
177
- }
@@ -1,50 +0,0 @@
1
- // src/cli/commands/vm-status-command.ts
2
- //
3
- // `peaks vm status` — the read-only host probe that rides on the `vm` parent.
4
- //
5
- // `peaks vm spawn` refuses with VM_RUNTIME_UNAVAILABLE and
6
- // `peaks sub-agent dispatch --isolation vm` refuses with
7
- // ISOLATION_VM_NOT_YET_IMPLEMENTED, but neither said WHICH prerequisite is
8
- // missing on the machine actually running the command: the hypervisor binary,
9
- // the KVM device node, or a host with no hypervisor at all. The only way to
10
- // find out was to attempt a spawn that was going to fail.
11
- //
12
- // This reports it, and it does not pretend the runtime exists: a probe that
13
- // finds libvirt on PATH still leaves `--isolation vm` refused, because the
14
- // missing piece is peaks' VM runtime (image, `vm exec`, per-OS bindings), not
15
- // the hypervisor. The envelope says so rather than letting a green probe read
16
- // as "vm works now".
17
- //
18
- import { probeHypervisors } from './vm-hypervisor-probe.js';
19
- import { addJsonOption, printResult } from '../cli-helpers.js';
20
- import { fail, ok } from 'peaks-loop-shared/result';
21
- export function registerVmStatusCommand(vm, io) {
22
- addJsonOption(vm
23
- .command('status')
24
- .description('Report which VM hypervisor this host offers (read-only probe; the peaks VM runtime is a separate rid)')).action((options) => {
25
- const rows = probeHypervisors();
26
- const anyAvailable = rows.some((row) => row.available);
27
- const data = {
28
- platform: process.platform,
29
- hypervisors: rows,
30
- anyAvailable,
31
- // The runtime statement, kept next to the probe result so the two can
32
- // never be read apart.
33
- dispatchIsolationVm: 'not implemented'
34
- };
35
- for (const row of rows) {
36
- io.stdout(`${row.hypervisor} ${row.available ? 'present' : 'absent'} ${row.binary}: ${row.detail}`);
37
- }
38
- io.stdout(`platform: ${process.platform}`);
39
- const nextActions = [
40
- 'The peaks VM runtime (image build, `peaks vm exec`, Hyper-V/HyperKit bindings) is not implemented yet: `peaks sub-agent dispatch --isolation vm` stays refused even when a hypervisor is present.',
41
- 'For isolation today use --isolation worktree (L2, production) or --isolation container (L4, docker/podman).'
42
- ];
43
- if (!anyAvailable) {
44
- printResult(io, fail('vm.status', 'VM_RUNTIME_UNAVAILABLE', `no VM hypervisor is usable on ${process.platform}: install one of virsh (KVM/libvirt, Linux), hvftool (HyperKit, macOS) or hvc (Hyper-V, Windows) — and on Linux the /dev/kvm device node — or drop --isolation and use worktree/container.`, data, nextActions), options.json);
45
- process.exitCode = 1;
46
- return;
47
- }
48
- printResult(io, ok('vm.status', data, [], nextActions), options.json);
49
- });
50
- }
@@ -1,23 +0,0 @@
1
- /**
2
- * P2-b sweep 010 — peaks-* runtime contract enforcer (excluding
3
- * peaks-code which has its own sweep 009 enforcer; excluding
4
- * peaks-prd / peaks-rd / peaks-qa / peaks-ui / peaks-sc / peaks-txt
5
- * which have their own per-skill enforcers in earlier sweeps).
6
- *
7
- * Closes 8 of the remaining 22 discovered lines:
8
- * - peaks-audit-skill-md-52, 70, 125, 133
9
- * - peaks-content-skill-md-141, 235
10
- * - peaks-ide-skill-md-12, 114
11
- *
12
- * The contract is the section-marker skeleton that every
13
- * peaks-* SKILL.md must declare. Single enforcer scopes per
14
- * skill via the SkillFile.name field.
15
- */
16
- import type { LintHit, SkillFile } from './lint-style.js';
17
- export declare const lintPeaksAuditRuntime: (skill: SkillFile) => ReadonlyArray<LintHit>;
18
- export declare const lintPeaksContentRuntime: (skill: SkillFile) => ReadonlyArray<LintHit>;
19
- export declare const lintPeaksIdeRuntime: (skill: SkillFile) => ReadonlyArray<LintHit>;
20
- export declare const lintPeaksDoctorRuntime: (skill: SkillFile) => ReadonlyArray<LintHit>;
21
- export declare const lintPeaksIssueFixOrchestratorRuntime: (skill: SkillFile) => ReadonlyArray<LintHit>;
22
- export declare const lintPeaksSopRuntime: (skill: SkillFile) => ReadonlyArray<LintHit>;
23
- export declare const lintPeaksSliceDecomposeRuntime: (skill: SkillFile) => ReadonlyArray<LintHit>;
@@ -1,64 +0,0 @@
1
- function buildContract(markers, scopeName) {
2
- return (skill) => {
3
- if (skill.name !== scopeName)
4
- return [];
5
- const lines = skill.lines.length > 0 ? skill.lines : skill.body.split(/\r?\n/);
6
- const missing = [];
7
- for (const m of markers) {
8
- if (!lines.some((l) => m.pattern.test(l)))
9
- missing.push(m.name);
10
- }
11
- if (missing.length === 0)
12
- return [];
13
- return [
14
- {
15
- catalogId: 'lint-peaks-skill-runtime-' + markers[0]?.name.toLowerCase().replace(/[^a-z0-9]+/g, '-'),
16
- rule: `peaks-* SKILL.md must declare the runtime contract (missing markers: ${missing.join(', ')})`,
17
- file: skill.path,
18
- line: 1,
19
- matchedText: `missing markers: ${missing.join(', ')}`
20
- }
21
- ];
22
- };
23
- }
24
- const PEAKS_AUDIT_MARKERS = Object.freeze([
25
- { name: 'Audit log machine-readable', pattern: /audit log is machine-readable/i },
26
- { name: 'Six-dimension audit', pattern: /six dimensions|6 dimensions/i },
27
- { name: 'Author identity', pattern: /author identity.*local gitconfig/i }
28
- ]);
29
- const PEAKS_CONTENT_MARKERS = Object.freeze([
30
- { name: 'What this skill do', pattern: /what this skill do/i },
31
- { name: 'Failure mode', pattern: /failure mode/i },
32
- { name: 'Each red line is written', pattern: /each red line is written/i }
33
- ]);
34
- const PEAKS_IDE_MARKERS = Object.freeze([
35
- { name: 'For any consumer', pattern: /for any consumer of the v2 envelope/i },
36
- { name: 'What this skill do', pattern: /what this skill do/i },
37
- { name: 'General workflow-gating tool', pattern: /general workflow-gating tool/i }
38
- ]);
39
- export const lintPeaksAuditRuntime = buildContract(PEAKS_AUDIT_MARKERS, 'peaks-audit');
40
- export const lintPeaksContentRuntime = buildContract(PEAKS_CONTENT_MARKERS, 'peaks-content');
41
- export const lintPeaksIdeRuntime = buildContract(PEAKS_IDE_MARKERS, 'peaks-ide');
42
- /** Doctor — single marker, often a one-line contract. */
43
- const PEAKS_DOCTOR_MARKERS = Object.freeze([
44
- {
45
- name: 'peaks-loop doctor is a doctor orchestrator',
46
- pattern: /peaks-loop doctor is a doctor orchestrator/i
47
- }
48
- ]);
49
- const PEAKS_ISSUE_FIX_ORCHESTRATOR_MARKERS = Object.freeze([
50
- { name: 'Deviation note', pattern: /deviation note/i },
51
- { name: 'Autonomous work proceed', pattern: /autonomous work proceed/i }
52
- ]);
53
- const PEAKS_SOP_MARKERS = Object.freeze([
54
- { name: 'Each red line below', pattern: /each red line below is written/i },
55
- { name: 'sop lint reports findings', pattern: /sop lint reports findings/i }
56
- ]);
57
- const PEAKS_SLICE_DECOMPOSE_MARKERS = Object.freeze([
58
- { name: 'What this skill do', pattern: /what this skill do/i },
59
- { name: 'Failure mode ( — read before declaring a', pattern: /failure mode \(/i }
60
- ]);
61
- export const lintPeaksDoctorRuntime = buildContract(PEAKS_DOCTOR_MARKERS, 'peaks-doctor');
62
- export const lintPeaksIssueFixOrchestratorRuntime = buildContract(PEAKS_ISSUE_FIX_ORCHESTRATOR_MARKERS, 'peaks-issue-fix-orchestrator');
63
- export const lintPeaksSopRuntime = buildContract(PEAKS_SOP_MARKERS, 'peaks-sop');
64
- export const lintPeaksSliceDecomposeRuntime = buildContract(PEAKS_SLICE_DECOMPOSE_MARKERS, 'peaks-slice-decompose');
@@ -1,40 +0,0 @@
1
- export type VmHypervisor = 'kvm' | 'hyperkit' | 'hyperv';
2
- export declare const VM_HYPERVISORS: ReadonlyArray<VmHypervisor>;
3
- export declare const DEFAULT_TTL_BY_ROLE: Readonly<Record<string, number>>;
4
- export declare const DEFAULT_TTL_MS: number | undefined;
5
- export declare const DEFAULT_VM_IMAGE = "peaks-base:22-slim";
6
- export type VmLeaseStatus = 'active' | 'released' | 'expired' | 'gc';
7
- export interface VmLease {
8
- readonly leaseId: string;
9
- readonly rid: string;
10
- readonly role: string;
11
- /** Host path mounted into the VM working dir. */
12
- readonly path: string;
13
- /** Hypervisor the VM runs under (kvm | hyperkit | hyperv). */
14
- readonly hypervisor: VmHypervisor;
15
- /** VM image name (e.g. 'peaks-base:22-slim'). */
16
- readonly image: string;
17
- /** VM domain id reported by virsh / hvftool / hvc. */
18
- readonly vmId: string;
19
- /** Unix epoch ms when the lease was created. */
20
- readonly createdAt: number;
21
- /** Unix epoch ms when the lease expires. */
22
- readonly expiresAt: number;
23
- /** Operator-supplied purpose text (audit log). */
24
- readonly purpose: string;
25
- readonly status: VmLeaseStatus;
26
- readonly consumedBySubAgents: ReadonlyArray<string>;
27
- }
28
- export type VmLeaseDraft = Omit<VmLease, 'status' | 'consumedBySubAgents'>;
29
- export declare function vmLeaseStoreDir(sessionRuntimeDir: string): string;
30
- export declare function vmLeaseFilePath(sessionRuntimeDir: string, leaseId: string): string;
31
- export declare function generateVmLeaseId(): string;
32
- export declare function ttlForVmRole(role: string): number;
33
- export declare function finalizeVmLease(draft: VmLeaseDraft): VmLease;
34
- export declare function markVmReleased(lease: VmLease): VmLease;
35
- export declare function markVmExpired(lease: VmLease): VmLease;
36
- export declare function markVmGc(lease: VmLease): VmLease;
37
- export declare function recordVmConsumption(lease: VmLease, subAgentId: string): VmLease;
38
- export declare function isVmLeaseActive(lease: VmLease, now?: number): boolean;
39
- export declare function serializeVmLease(lease: VmLease): string;
40
- export declare function deserializeVmLease(raw: string): VmLease;
@@ -1,160 +0,0 @@
1
- /**
2
- * vm-lease — pure-function lease store for `peaks vm spawn`.
3
- *
4
- * Parallels the design of `worktree-lease.ts` (Part 1) and
5
- * `container-lease.ts` (Part 12). The L4 VM isolation mode
6
- * (`--isolation vm` in dispatch) needs its own lease surface
7
- * so the PreToolUse gate can grant `docker`-class operations
8
- * to sub-agents that own a VM lease.
9
- *
10
- * Hypervisor support:
11
- * - kvm: virsh create + virsh destroy (Linux KVM via libvirt)
12
- * - hyperkit: hvftool create + hvftool stop (macOS HyperKit)
13
- * - hyperv: hvc create + hvc stop (Windows Hyper-V via the
14
- * Hyper-V cmdlets; the operator wires the entry shim)
15
- *
16
- * Each hypervisor has its own spawn pattern; the lease file
17
- * records which hypervisor was used so `peaks vm release`
18
- * can dispatch to the right cleanup command.
19
- */
20
- import { randomBytes } from 'node:crypto';
21
- import { posix as path } from 'node:path';
22
- import { normalizePath } from '../../shared/path-utils.js';
23
- export const VM_HYPERVISORS = Object.freeze([
24
- 'kvm',
25
- 'hyperkit',
26
- 'hyperv'
27
- ]);
28
- // PRD-002b slice 2 — extract lease-TTL primitives (same shape as
29
- // container-lease.ts / worktree-lease.ts). See config diff comment.
30
- const MINUTES_PER_HOUR = 60;
31
- const MS_PER_MINUTE = MINUTES_PER_HOUR * 1_000;
32
- const LEASE_RD_TTL_MINUTES = 30;
33
- const LEASE_QA_TTL_MINUTES = 15;
34
- const LEASE_UI_TTL_MINUTES = MINUTES_PER_HOUR;
35
- const LEASE_SC_TTL_MINUTES = 30;
36
- const LEASE_PRD_TTL_MINUTES = 15;
37
- const LEASE_GENERAL_TTL_MINUTES = 30;
38
- const LEASE_ID_RANDOM_BYTES = 8;
39
- export const DEFAULT_TTL_BY_ROLE = Object.freeze({
40
- rd: LEASE_RD_TTL_MINUTES * MS_PER_MINUTE,
41
- qa: LEASE_QA_TTL_MINUTES * MS_PER_MINUTE,
42
- ui: LEASE_UI_TTL_MINUTES * MS_PER_MINUTE,
43
- sc: LEASE_SC_TTL_MINUTES * MS_PER_MINUTE,
44
- prd: LEASE_PRD_TTL_MINUTES * MS_PER_MINUTE,
45
- general: LEASE_GENERAL_TTL_MINUTES * MS_PER_MINUTE
46
- });
47
- export const DEFAULT_TTL_MS = DEFAULT_TTL_BY_ROLE.rd;
48
- export const DEFAULT_VM_IMAGE = 'peaks-base:22-slim';
49
- export function vmLeaseStoreDir(sessionRuntimeDir) {
50
- return joinPath(sessionRuntimeDir, 'vm-leases');
51
- }
52
- export function vmLeaseFilePath(sessionRuntimeDir, leaseId) {
53
- return joinPath(vmLeaseStoreDir(sessionRuntimeDir), `${leaseId}.json`);
54
- }
55
- export function generateVmLeaseId() {
56
- return randomBytes(LEASE_ID_RANDOM_BYTES).toString('hex');
57
- }
58
- export function ttlForVmRole(role) {
59
- const normalized = role.toLowerCase();
60
- const candidate = DEFAULT_TTL_BY_ROLE[normalized];
61
- const fallback = DEFAULT_TTL_BY_ROLE['rd'] ?? LEASE_RD_TTL_MINUTES * MS_PER_MINUTE;
62
- return candidate ?? fallback;
63
- }
64
- export function finalizeVmLease(draft) {
65
- return { ...draft, status: 'active', consumedBySubAgents: [] };
66
- }
67
- export function markVmReleased(lease) {
68
- return { ...lease, status: 'released' };
69
- }
70
- export function markVmExpired(lease) {
71
- return { ...lease, status: 'expired' };
72
- }
73
- export function markVmGc(lease) {
74
- return { ...lease, status: 'gc' };
75
- }
76
- export function recordVmConsumption(lease, subAgentId) {
77
- if (lease.consumedBySubAgents.includes(subAgentId))
78
- return lease;
79
- return { ...lease, consumedBySubAgents: [...lease.consumedBySubAgents, subAgentId] };
80
- }
81
- export function isVmLeaseActive(lease, now = Date.now()) {
82
- return lease.status === 'active' && lease.expiresAt > now;
83
- }
84
- export function serializeVmLease(lease) {
85
- return JSON.stringify(lease, null, 2) + '\n';
86
- }
87
- export function deserializeVmLease(raw) {
88
- const parsed = JSON.parse(raw);
89
- if (typeof parsed !== 'object' || parsed === null) {
90
- throw new Error('vm lease file must contain a JSON object');
91
- }
92
- const obj = parsed;
93
- const required = [
94
- 'leaseId',
95
- 'rid',
96
- 'role',
97
- 'path',
98
- 'hypervisor',
99
- 'image',
100
- 'vmId',
101
- 'createdAt',
102
- 'expiresAt',
103
- 'purpose',
104
- 'status',
105
- 'consumedBySubAgents'
106
- ];
107
- for (const k of required) {
108
- if (!(k in obj))
109
- throw new Error(`vm lease missing field: ${k}`);
110
- }
111
- if (!VM_HYPERVISORS.includes(obj.hypervisor)) {
112
- throw new Error(`vm lease hypervisor invalid: ${String(obj.hypervisor)}`);
113
- }
114
- if (typeof obj.leaseId !== 'string')
115
- throw new Error('leaseId missing');
116
- if (typeof obj.rid !== 'string')
117
- throw new Error('rid missing');
118
- if (typeof obj.role !== 'string')
119
- throw new Error('role missing');
120
- if (typeof obj.path !== 'string')
121
- throw new Error('path missing');
122
- if (typeof obj.image !== 'string')
123
- throw new Error('image missing');
124
- if (typeof obj.vmId !== 'string')
125
- throw new Error('vmId missing');
126
- if (typeof obj.createdAt !== 'number')
127
- throw new Error('createdAt missing');
128
- if (typeof obj.expiresAt !== 'number')
129
- throw new Error('expiresAt missing');
130
- if (typeof obj.purpose !== 'string')
131
- throw new Error('purpose missing');
132
- if (typeof obj.status !== 'string')
133
- throw new Error('status missing');
134
- if (!Array.isArray(obj.consumedBySubAgents))
135
- throw new Error('consumedBySubAgents missing');
136
- return {
137
- leaseId: obj.leaseId,
138
- rid: obj.rid,
139
- role: obj.role,
140
- path: obj.path,
141
- hypervisor: obj.hypervisor,
142
- image: obj.image,
143
- vmId: obj.vmId,
144
- createdAt: obj.createdAt,
145
- expiresAt: obj.expiresAt,
146
- purpose: obj.purpose,
147
- status: obj.status,
148
- consumedBySubAgents: obj.consumedBySubAgents
149
- };
150
- }
151
- function joinPath(...segments) {
152
- if (segments.length === 0)
153
- return '';
154
- const normalized = segments.map((s) => normalizePath(s));
155
- let acc = normalized[0];
156
- for (let i = 1; i < normalized.length; i++) {
157
- acc = path.join(acc, normalized[i]);
158
- }
159
- return acc;
160
- }