peaks-loop 4.1.5 → 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 (86) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +36 -0
  3. package/README-en.md +47 -183
  4. package/README.md +24 -188
  5. package/dist/cli/commands/best-practice-scan-command.d.ts +11 -6
  6. package/dist/cli/commands/best-practice-scan-command.js +35 -20
  7. package/dist/cli/commands/best-practice-scan-helpers.d.ts +47 -0
  8. package/dist/cli/commands/best-practice-scan-helpers.js +88 -5
  9. package/dist/cli/commands/best-practice-scan-lookup-results.d.ts +13 -0
  10. package/dist/cli/commands/best-practice-scan-lookup-results.js +237 -0
  11. package/dist/cli/commands/dispatch-command-spec.js +1 -1
  12. package/dist/cli/commands/dispatch-isolation-lease.d.ts +1 -1
  13. package/dist/cli/commands/dispatch-isolation-lease.js +6 -53
  14. package/dist/cli/commands/dispatch-prompt-blocks.d.ts +1 -1
  15. package/dist/cli/commands/dispatch-prompt-composition.d.ts +1 -1
  16. package/dist/cli/commands/dispatch-record-write.d.ts +1 -1
  17. package/dist/cli/commands/dispatch-tool-call.d.ts +1 -1
  18. package/dist/cli/commands/openspec-command-shared.js +2 -2
  19. package/dist/cli/commands/request-transition-failures.js +31 -4
  20. package/dist/cli/commands/request-transition-preflight.js +1 -1
  21. package/dist/cli/commands/slice-decompose-artifacts.js +2 -1
  22. package/dist/cli/commands/verdict-aggregate-command.js +2 -1
  23. package/dist/cli/commands/workflow-gate-commands.js +4 -4
  24. package/dist/cli/program.js +0 -2
  25. package/dist/services/artifacts/artifact-contract-block.js +21 -2
  26. package/dist/services/artifacts/artifact-prerequisites.js +7 -7
  27. package/dist/services/artifacts/rd-transition-gates.d.ts +33 -0
  28. package/dist/services/artifacts/rd-transition-gates.js +71 -0
  29. package/dist/services/artifacts/request-artifact-service.js +22 -20
  30. package/dist/services/artifacts/request-artifact-state-helpers.d.ts +9 -1
  31. package/dist/services/artifacts/request-artifact-state-helpers.js +6 -4
  32. package/dist/services/audit-independent/judged-declaration-check.d.ts +1 -0
  33. package/dist/services/audit-independent/judged-declaration-check.js +62 -1
  34. package/dist/services/context/build-dispatch-system-prompt.d.ts +5 -9
  35. package/dist/services/context/build-dispatch-system-prompt.js +11 -11
  36. package/dist/services/context/post-compact-reinjection.js +1 -1
  37. package/dist/services/dispatch/test-tool-detection.d.ts +17 -1
  38. package/dist/services/dispatch/test-tool-detection.js +12 -1
  39. package/dist/services/evidence/evidence-generator.js +8 -4
  40. package/dist/services/openspec/coverage-evidence-reader.d.ts +9 -9
  41. package/dist/services/openspec/coverage-evidence-reader.js +8 -8
  42. package/dist/services/openspec/openspec-archive-service.d.ts +1 -1
  43. package/dist/services/openspec/openspec-archive-service.js +6 -6
  44. package/dist/services/scan/file-size-baseline.d.ts +13 -6
  45. package/dist/services/scan/file-size-baseline.js +54 -31
  46. package/dist/services/scan/file-size-scan.d.ts +7 -14
  47. package/dist/services/scan/file-size-scan.js +6 -1
  48. package/dist/services/scan/type-corroboration.d.ts +32 -0
  49. package/dist/services/scan/type-corroboration.js +51 -0
  50. package/dist/services/scan/type-sanity-service.d.ts +14 -0
  51. package/dist/services/scan/type-sanity-service.js +10 -19
  52. package/dist/services/security/safe-settings-path.d.ts +5 -0
  53. package/dist/services/security/safe-settings-path.js +64 -8
  54. package/dist/services/skill/resume-detector.js +8 -8
  55. package/dist/services/workflow/pipeline-verify-gate-support.d.ts +24 -8
  56. package/dist/services/workflow/pipeline-verify-gate-support.js +32 -38
  57. package/dist/services/workflow/pipeline-verify-qa-phase.d.ts +102 -0
  58. package/dist/services/workflow/pipeline-verify-qa-phase.js +176 -0
  59. package/dist/services/workflow/pipeline-verify-service.js +26 -27
  60. package/dist/services/workflow/request-type-resolution.d.ts +99 -0
  61. package/dist/services/workflow/request-type-resolution.js +130 -0
  62. package/dist/services/workflow/workflow-skip-service.d.ts +1 -0
  63. package/dist/services/workflow/workflow-skip-service.js +19 -21
  64. package/dist/services/workflow/workflow-state-store.d.ts +9 -0
  65. package/dist/services/workflow/workflow-state-store.js +26 -1
  66. package/dist/shared/incrementing-number.d.ts +23 -2
  67. package/dist/shared/incrementing-number.js +57 -15
  68. package/package.json +5 -7
  69. package/skills/bee/peaks-prd/SKILL.md +3 -2
  70. package/skills/peaks-code/SKILL.md +32 -15
  71. package/dist/cli/commands/vm-command-shared.d.ts +0 -23
  72. package/dist/cli/commands/vm-command-shared.js +0 -23
  73. package/dist/cli/commands/vm-commands.d.ts +0 -3
  74. package/dist/cli/commands/vm-commands.js +0 -45
  75. package/dist/cli/commands/vm-hypervisor-probe.d.ts +0 -27
  76. package/dist/cli/commands/vm-hypervisor-probe.js +0 -78
  77. package/dist/cli/commands/vm-hypervisor-runtime.d.ts +0 -15
  78. package/dist/cli/commands/vm-hypervisor-runtime.js +0 -64
  79. package/dist/cli/commands/vm-release-command.d.ts +0 -5
  80. package/dist/cli/commands/vm-release-command.js +0 -101
  81. package/dist/cli/commands/vm-spawn-command.d.ts +0 -5
  82. package/dist/cli/commands/vm-spawn-command.js +0 -177
  83. package/dist/cli/commands/vm-status-command.d.ts +0 -3
  84. package/dist/cli/commands/vm-status-command.js +0 -50
  85. package/dist/services/vm/vm-lease.d.ts +0 -40
  86. package/dist/services/vm/vm-lease.js +0 -160
@@ -262,25 +262,42 @@ language-aware, LLM-recommended best-practice scan** before RD kicks off.
262
262
  **Trigger:** Fires at peak-prd exit when business-goal is non-empty + sub-step not yet
263
263
  triggered for this intent.
264
264
 
265
- **Action sequence:**
265
+ **Action sequence — the LLM performs the lookup; the CLI never calls Context7:**
266
266
  1. Detect project language (TS / JS / Python / Go / Java) via `language-detector` (5-lang
267
- priority chain).
268
- 2. Query Context7 (`@upstash/context7-mcp@^4.0.2`, installed as peaks-loop production dep)
269
- priority-1 with 30s timeout.
270
- 3. WebSearch fallback when Context7 returns empty / errors.
271
- 4. Synthesize 8-row markdown comparison table per `output-formatter`.
267
+ priority chain), or let the CLI auto-detect it.
268
+ 2. **You** query Context7 (`@upstash/context7-mcp`) with your own MCP tool — priority 1, 30s budget —
269
+ and WebSearch as the priority-2 fallback when Context7 answers nothing.
270
+ 3. **You** write those results to `.peaks/_runtime/<sessionId>/best-practice/lookup-results.json` in
271
+ the scan seam's own vocabulary — `{ "intent": "<the --intent value>", "context7": { "ok": …,
272
+ "results": [{ "title", "url", "snippet" }] }, "websearch": { … } }` — then run
273
+ `peaks best-practice-scan --project <repo> --intent "<goal>" --lookup-results <that file>`. The
274
+ path is resolved against your cwd, so pass it explicitly. A lookup that returned nothing is
275
+ `"ok": false, "results": []`; `"ok": true` with an empty `results` is refused, because that is
276
+ the shape a fabrication would take. Each fragment may carry `title`/`url`/`snippet` and nothing
277
+ else, and **the `url` is yours to construct** — Context7's response contains no URL, only a
278
+ library ID (`/org/project`), so state that when the recommendation is read.
279
+ 4. The CLI validates the file and renders the 8-row markdown comparison table per `output-formatter`
280
+ into `<project>/best-practice/<date>-<intent-slug>.md`.
272
281
  5. LLM picks one recommendation (★ marker) with reasoning block.
273
282
  6. **Mandatory ⚠️ catch gate** — user explicitly acks / picks alt / rejects + reason.
274
283
 
275
- **When the scan cannot be performed, the sub-step is SKIPPED — never fabricated.** The lookups behind
276
- this scan are stubs in the current build: they return synthetic fragments marked internally as
277
- synthetic. When the scan runs on a synthetic result it **refuses** — `ok:false`,
278
- `BEST_PRACTICE_SCAN_SYNTHETIC_LOOKUP`, exit 1 — and prints no recommendation, no comparison table and
279
- no ⚠️ catch gate, because there is nothing real for the user to judge. Record the sub-step as
280
- **skipped with reason `synthetic-lookup`** and carry on; do not synthesise a recommendation to satisfy
281
- the gate. `--intent <text>` is required (the business goal, not the project path) — omitting it is
282
- `BEST_PRACTICE_SCAN_INTENT_REQUIRED`, also exit 1. A real scan renders the full table and the gate
283
- normally; wiring the real Context7 / WebSearch lookup is a future slice.
284
+ **When the scan cannot be performed, the sub-step is SKIPPED — never fabricated.** With no
285
+ `--lookup-results`, the CLI's built-in lookups are stubs and return synthetic fragments: the scan
286
+ **refuses** — `ok:false`, `BEST_PRACTICE_SCAN_SYNTHETIC_LOOKUP`, exit 1 — and prints no recommendation,
287
+ no comparison table and no ⚠️ catch gate, because there is nothing real for the user to judge. Record
288
+ the sub-step as **skipped with reason `synthetic-lookup`** and carry on; do not synthesise a
289
+ recommendation to satisfy the gate. **Every miss is refused**, in one of two ways: with no real
290
+ WebSearch behind a Context7 miss the fall-through lands on the stub and gives the refusal above; when
291
+ you supply the `websearch` seam and it *also* reports `ok: false`, the chain is real and found nothing,
292
+ and the command refuses with `BEST_PRACTICE_SCAN_NO_FRAGMENTS` and writes no artifact at all. A scan
293
+ with zero fragments never renders — a table with a `★` on it and nothing behind it is the fabrication
294
+ this sub-step exists to prevent. `--intent <text>` is required (the business goal, not the project
295
+ path) — omitting it is `BEST_PRACTICE_SCAN_INTENT_REQUIRED`, also exit 1. Supply real results with
296
+ `--lookup-results <file>`; a malformed, mismatched or empty-results file is refused as
297
+ `BEST_PRACTICE_SCAN_INVALID_RESULTS` without scanning. A real scan renders the full table and the gate
298
+ normally. Run the injected scan **after** the PRD state transition, so the real recommendation is the
299
+ artifact left on disk; a refusal never overwrites it — it is recorded under
300
+ `<project>/best-practice/skipped/` instead.
284
301
 
285
302
  **Out of scope for this sub-step:**
286
303
  - ❌ No changes to RD dispatch Karpathy prose (Step 3 unchanged)
@@ -1,23 +0,0 @@
1
- import { type VmHypervisor } from '../../services/vm/vm-lease.js';
2
- export type VmOptions = {
3
- session?: string;
4
- project?: string;
5
- json?: boolean;
6
- };
7
- export type SpawnOptions = VmOptions & {
8
- rid: string;
9
- role: string;
10
- purpose: string;
11
- hypervisor?: VmHypervisor;
12
- image?: string;
13
- ttl?: string;
14
- mount?: string;
15
- };
16
- export type ReleaseOptions = VmOptions & {
17
- leaseId: string;
18
- };
19
- /** `--session`, else `PEAKS_SESSION_ID`, else the project's bound session, else `unknown-sid`. */
20
- export declare function resolveVmSessionId(projectRoot: string, session: string | undefined): string;
21
- /** `<projectRoot>/.peaks/_runtime/<sessionId>` — trailing separators collapsed. */
22
- export declare function joinPathSession(projectRoot: string, sessionId: string): string;
23
- export declare function resolveTtlMs(raw: string | undefined, role: string): number;
@@ -1,23 +0,0 @@
1
- // src/cli/commands/vm-command-shared.ts
2
- //
3
- // What `peaks vm` verbs share: the option shapes, the session-id resolution and
4
- // the role-aware TTL. Split out of `vm-commands.ts`; every resolution order and
5
- // default is unchanged.
6
- import { getCurrentSessionId } from '../../services/skills/skill-presence-service.js';
7
- import { ttlForVmRole } from '../../services/vm/vm-lease.js';
8
- /** `--session`, else `PEAKS_SESSION_ID`, else the project's bound session, else `unknown-sid`. */
9
- export function resolveVmSessionId(projectRoot, session) {
10
- return (session ?? process.env.PEAKS_SESSION_ID ?? getCurrentSessionId(projectRoot) ?? 'unknown-sid');
11
- }
12
- /** `<projectRoot>/.peaks/_runtime/<sessionId>` — trailing separators collapsed. */
13
- export function joinPathSession(projectRoot, sessionId) {
14
- return `${projectRoot.replace(/[\\/]+$/, '')}/.peaks/_runtime/${sessionId}`;
15
- }
16
- export function resolveTtlMs(raw, role) {
17
- if (typeof raw !== 'string' || raw.length === 0)
18
- return ttlForVmRole(role);
19
- const parsed = Number.parseInt(raw, 10);
20
- if (!Number.isInteger(parsed) || parsed <= 0)
21
- return ttlForVmRole(role);
22
- return parsed;
23
- }
@@ -1,3 +0,0 @@
1
- import type { Command } from 'commander';
2
- import type { ProgramIO } from '../cli-helpers.js';
3
- export declare function registerVmCommand(program: Command, io: ProgramIO): void;
@@ -1,45 +0,0 @@
1
- // src/cli/commands/vm-commands.ts
2
- //
3
- // L4 VM isolation: the `peaks vm` parent, its status probe, and the
4
- // spawn/release pair. Split out of the single file this used to be; the parent
5
- // description, the registration order and every verb's surface are unchanged.
6
- //
7
- // Hypervisor dispatch:
8
- // - `kvm` : `virsh create` + `virsh destroy` (Linux KVM via libvirt)
9
- // - `hyperkit` : `hvftool create` + `hvftool stop` (macOS HyperKit)
10
- // - `hyperv` : `hvc create` + `hvftool stop` (Windows Hyper-V via
11
- // the operator-installed `hvc` shim)
12
- //
13
- // The runtime check: which hypervisor binary is on PATH +
14
- // (for kvm) whether the host kernel exposes /dev/kvm. The
15
- // spawn is fail-fast: if the requested hypervisor is not
16
- // available, the CLI returns VM_RUNTIME_UNAVAILABLE with a
17
- // remediation hint rather than falling through to a different
18
- // hypervisor (the caller chose a specific mode for a reason).
19
- //
20
- // Each spawned VM runs `sleep infinity` as the entrypoint; the
21
- // VM's working dir is mounted from the host path, and the
22
- // `peaks.leaseId` / `peaks.rid` labels are propagated via
23
- // cloud-init metadata. Real workloads are expected to use
24
- // `peaks vm exec` (a follow-up rid) to run commands inside
25
- // the VM; Part 35 ships the lease + spawn/release surface
26
- // only.
27
- //
28
- // The verb bodies live beside this file (`vm-spawn-command.ts`,
29
- // `vm-release-command.ts`), over the shared vocabulary in
30
- // `vm-command-shared.ts` and the dispatch helpers in
31
- // `vm-hypervisor-runtime.ts`; `vm-hypervisor-probe.ts` and
32
- // `vm-status-command.ts` were already siblings.
33
- import { registerVmStatusCommand } from './vm-status-command.js';
34
- import { registerVmSpawnCommand } from './vm-spawn-command.js';
35
- import { registerVmReleaseCommand } from './vm-release-command.js';
36
- export function registerVmCommand(program, io) {
37
- const cmd = program
38
- .command('vm')
39
- .description('L4 VM isolation: spawn/release VM leases via kvm | hyperkit | hyperv (Part 35; pairs with --isolation vm on dispatch).');
40
- // The host probe rides on the same parent, so `peaks vm status`
41
- // can say which prerequisite is missing before a spawn fails.
42
- registerVmStatusCommand(cmd, io);
43
- registerVmSpawnCommand(cmd, io);
44
- registerVmReleaseCommand(cmd, io);
45
- }
@@ -1,27 +0,0 @@
1
- import type { VmHypervisor } from '../../services/vm/vm-lease.js';
2
- export type HypervisorProbeRow = {
3
- readonly hypervisor: VmHypervisor;
4
- readonly binary: string;
5
- readonly available: boolean;
6
- /** The version line when available; why not when it is not. */
7
- readonly detail: string;
8
- };
9
- /** Every hypervisor the CLI can dispatch to, and the binary it shells out to. */
10
- export declare const VM_HYPERVISOR_BINARIES: ReadonlyArray<{
11
- hypervisor: VmHypervisor;
12
- binary: string;
13
- }>;
14
- export declare function binaryForHypervisor(requested: VmHypervisor): string;
15
- /**
16
- * Is this hypervisor usable here right now? `kvm` needs both the libvirt CLI
17
- * and the kernel device node; the others need their binary to answer.
18
- */
19
- export declare function detectHypervisor(requested: VmHypervisor): {
20
- ok: true;
21
- binary: string;
22
- } | {
23
- ok: false;
24
- stderr: string;
25
- };
26
- /** Probe every dispatchable hypervisor, in the order the CLI lists them. */
27
- export declare function probeHypervisors(): HypervisorProbeRow[];
@@ -1,78 +0,0 @@
1
- // src/cli/commands/vm-hypervisor-probe.ts
2
- //
3
- // The host-side question every `peaks vm` path has to answer: is there a
4
- // hypervisor on this machine that a VM could actually be created with?
5
- //
6
- // Split out of `vm-commands.ts` because two consumers need it — `vm spawn`
7
- // (fail-fast before leasing) and `vm status` (report every hypervisor,
8
- // including the ones that are absent) — and because a command file that both
9
- // registers commands and answers host questions is the shape this repo keeps
10
- // paying for in `max-lines` findings.
11
- //
12
- // Detection is a real probe, not a platform guess: the binary must answer
13
- // `--version`, and for KVM the kernel device node must exist. That means the
14
- // answer can change between two calls (an operator installs libvirt mid-run),
15
- // which is exactly why `vm status` reports it instead of caching it.
16
- import { execSync } from 'node:child_process';
17
- import { existsSync } from 'node:fs';
18
- /** Every hypervisor the CLI can dispatch to, and the binary it shells out to. */
19
- export const VM_HYPERVISOR_BINARIES = [
20
- { hypervisor: 'kvm', binary: 'virsh' },
21
- { hypervisor: 'hyperkit', binary: 'hvftool' },
22
- { hypervisor: 'hyperv', binary: 'hvc' }
23
- ];
24
- export function binaryForHypervisor(requested) {
25
- const entry = VM_HYPERVISOR_BINARIES.find((row) => row.hypervisor === requested);
26
- if (entry === undefined) {
27
- throw new Error(`unknown hypervisor: ${requested}`);
28
- }
29
- return entry.binary;
30
- }
31
- /**
32
- * Is this hypervisor usable here right now? `kvm` needs both the libvirt CLI
33
- * and the kernel device node; the others need their binary to answer.
34
- */
35
- export function detectHypervisor(requested) {
36
- const binary = binaryForHypervisor(requested);
37
- try {
38
- const version = execSync(`${binary} --version`, {
39
- stdio: ['ignore', 'pipe', 'pipe'],
40
- encoding: 'utf8',
41
- windowsHide: true
42
- });
43
- if (requested === 'kvm' && !existsSync('/dev/kvm')) {
44
- return { ok: false, stderr: 'KVM kernel module not loaded (/dev/kvm absent)' };
45
- }
46
- return { ok: true, binary: `${binary} (${version.trim().split('\n')[0] ?? ''})` };
47
- }
48
- catch (error) {
49
- const message = error.message;
50
- // A binary that is not installed fails at exec time, and on Windows that
51
- // error arrives in the console codepage — it renders as mojibake in the
52
- // terminal. Name the cause instead of quoting it.
53
- const absent = /not recognized|not found|ENOENT|Command failed/i.test(message);
54
- return {
55
- ok: false,
56
- stderr: absent ? `${binary} is not on PATH` : (message.split('\n')[0] ?? '')
57
- };
58
- }
59
- }
60
- /** Probe every dispatchable hypervisor, in the order the CLI lists them. */
61
- export function probeHypervisors() {
62
- return VM_HYPERVISOR_BINARIES.map((entry) => {
63
- const detected = detectHypervisor(entry.hypervisor);
64
- return detected.ok
65
- ? {
66
- hypervisor: entry.hypervisor,
67
- binary: entry.binary,
68
- available: true,
69
- detail: detected.binary
70
- }
71
- : {
72
- hypervisor: entry.hypervisor,
73
- binary: entry.binary,
74
- available: false,
75
- detail: detected.stderr
76
- };
77
- });
78
- }
@@ -1,15 +0,0 @@
1
- import type { VmHypervisor } from '../../services/vm/vm-lease.js';
2
- export declare function spawnVmWithHypervisor(args: {
3
- hypervisor: VmHypervisor;
4
- image: string;
5
- mount: string;
6
- leaseId: string;
7
- rid: string;
8
- workdir: string;
9
- }): {
10
- vmId: string;
11
- };
12
- export declare function destroyVmWithHypervisor(args: {
13
- hypervisor: VmHypervisor;
14
- vmId: string;
15
- }): boolean;
@@ -1,64 +0,0 @@
1
- // src/cli/commands/vm-hypervisor-runtime.ts
2
- //
3
- // The two hypervisor dispatch helpers `peaks vm spawn` / `peaks vm release`
4
- // call: create a domain and destroy one. Split out of `vm-commands.ts`; every
5
- // command line, cwd, stdio tuple and `windowsHide` flag is unchanged.
6
- import { execSync } from 'node:child_process';
7
- import { writeFileSync } from 'node:fs';
8
- export function spawnVmWithHypervisor(args) {
9
- if (args.hypervisor === 'kvm') {
10
- // virsh create expects a domain XML file. We emit a minimal
11
- // XML with the image, mount, and our peaks labels.
12
- const xml = `<?xml version="1.0"?>
13
- <domain type="kvm">
14
- <name>peaks-${args.leaseId}</name>
15
- <metadata><peaks:label xmlns:peaks="urn:peaks">peaks.leaseId=${args.leaseId};peaks.rid=${args.rid}</peaks:label></metadata>
16
- <memory>1048576</memory>
17
- <vcpu>1</vcpu>
18
- <os><type arch="x86_64">hvm</type></os>
19
- <devices>
20
- <disk type="file"><source file="${args.image}"/><target dev="vda"/></disk>
21
- <filesystem type="mount"><source dir="${args.mount}"/><target dir="/work"/></filesystem>
22
- </devices>
23
- </domain>`;
24
- const xmlPath = `${args.workdir}/.peaks-vm-${args.leaseId}.xml`;
25
- writeFileSync(xmlPath, xml, 'utf8');
26
- const out = execSync(`virsh create ${xmlPath}`, {
27
- cwd: args.workdir,
28
- stdio: ['ignore', 'pipe', 'pipe'],
29
- encoding: 'utf8',
30
- windowsHide: true
31
- });
32
- return { vmId: out.trim() };
33
- }
34
- if (args.hypervisor === 'hyperkit') {
35
- const out = execSync(`hvftool create --image ${args.image} --mount ${args.mount}:/work --label peaks.leaseId=${args.leaseId} --label peaks.rid=${args.rid} --entrypoint sleep -- infinity`, { cwd: args.workdir, stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8', windowsHide: true });
36
- return { vmId: out.trim() };
37
- }
38
- // hyperv: the hvc shim writes a vhdx + emits the new VM id.
39
- const out = execSync(`hvc create --image ${args.image} --mount ${args.mount} --label peaks.leaseId=${args.leaseId} --label peaks.rid=${args.rid}`, { cwd: args.workdir, stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8', windowsHide: true });
40
- return { vmId: out.trim() };
41
- }
42
- export function destroyVmWithHypervisor(args) {
43
- try {
44
- if (args.hypervisor === 'kvm') {
45
- execSync(`virsh destroy ${args.vmId}`, {
46
- stdio: ['ignore', 'pipe', 'pipe'],
47
- windowsHide: true
48
- });
49
- }
50
- else if (args.hypervisor === 'hyperkit') {
51
- execSync(`hvftool stop ${args.vmId}`, {
52
- stdio: ['ignore', 'pipe', 'pipe'],
53
- windowsHide: true
54
- });
55
- }
56
- else {
57
- execSync(`hvc stop ${args.vmId}`, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
58
- }
59
- return true;
60
- }
61
- catch {
62
- return false;
63
- }
64
- }
@@ -1,5 +0,0 @@
1
- import type { Command } from 'commander';
2
- import { type ProgramIO } from '../cli-helpers.js';
3
- import { type ReleaseOptions } from './vm-command-shared.js';
4
- export declare function runVmRelease(io: ProgramIO, options: ReleaseOptions): void;
5
- export declare function registerVmReleaseCommand(cmd: Command, io: ProgramIO): void;
@@ -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,3 +0,0 @@
1
- import type { Command } from 'commander';
2
- import { type ProgramIO } from '../cli-helpers.js';
3
- export declare function registerVmStatusCommand(vm: Command, io: ProgramIO): void;