peaks-loop 4.1.25 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +69 -3
  3. package/dist/cli/commands/core/session-info-command.js +3 -4
  4. package/dist/cli/commands/dashboard-long-run.js +2 -1
  5. package/dist/cli/commands/doctor/invoke-from-code.js +6 -1
  6. package/dist/cli/commands/job-state-root.js +4 -2
  7. package/dist/cli/commands/lease-metrics-commands-support.js +2 -1
  8. package/dist/cli/commands/loop-eval-capture-index.js +2 -1
  9. package/dist/cli/commands/loop-eval-eval-command.js +2 -1
  10. package/dist/cli/commands/mut-commands-helpers.d.ts +9 -28
  11. package/dist/cli/commands/mut-commands-helpers.js +13 -46
  12. package/dist/cli/commands/mut-failure-diagnostic.d.ts +48 -0
  13. package/dist/cli/commands/mut-failure-diagnostic.js +147 -0
  14. package/dist/cli/commands/outer-cache-commands.js +3 -2
  15. package/dist/cli/commands/playwright-session-store.js +5 -2
  16. package/dist/cli/commands/qa-archive-screenshots-command.js +2 -1
  17. package/dist/cli/commands/request-transition-preflight.js +2 -2
  18. package/dist/cli/commands/slice-decompose-artifacts.js +10 -2
  19. package/dist/cli/commands/verdict-aggregate-command.js +4 -3
  20. package/dist/cli/commands/worktree-lease-effects.d.ts +13 -0
  21. package/dist/cli/commands/worktree-lease-effects.js +23 -0
  22. package/dist/cli/commands/worktree-lease-gc-command.d.ts +3 -4
  23. package/dist/cli/commands/worktree-lease-gc-command.js +59 -58
  24. package/dist/cli/commands/worktree-lease-git.d.ts +13 -18
  25. package/dist/cli/commands/worktree-lease-git.js +21 -44
  26. package/dist/cli/commands/worktree-lease-list-command.js +1 -1
  27. package/dist/cli/commands/worktree-lease-load.d.ts +19 -7
  28. package/dist/cli/commands/worktree-lease-load.js +37 -9
  29. package/dist/cli/commands/worktree-lease-release-command.d.ts +4 -5
  30. package/dist/cli/commands/worktree-lease-release-command.js +60 -47
  31. package/dist/cli/commands/worktree-lease-renew-command.d.ts +5 -4
  32. package/dist/cli/commands/worktree-lease-renew-command.js +36 -32
  33. package/dist/cli/commands/worktree-lease-session.d.ts +7 -5
  34. package/dist/cli/commands/worktree-lease-session.js +9 -6
  35. package/dist/cli/commands/worktree-lease-spawn-command.d.ts +4 -3
  36. package/dist/cli/commands/worktree-lease-spawn-command.js +38 -46
  37. package/dist/cli/commands/worktree-lease-status-command.js +1 -1
  38. package/dist/cli/commands/worktree-lease-store.d.ts +3 -2
  39. package/dist/cli/commands/worktree-lease-store.js +3 -2
  40. package/dist/services/artifacts/prerequisite-path-resolver.js +5 -1
  41. package/dist/services/audit/enforcers/lint-output-style.js +5 -1
  42. package/dist/services/audit/enforcers/lint-rd-handoff-coverage.js +9 -4
  43. package/dist/services/audit-independent/handoff-missing-refusal.js +16 -1
  44. package/dist/services/audit-independent/judged-declaration-check.js +5 -1
  45. package/dist/services/audit-independent/perf-audit-service.d.ts +2 -4
  46. package/dist/services/audit-independent/perf-audit-service.js +4 -5
  47. package/dist/services/audit-independent/security-audit-artifact.js +5 -1
  48. package/dist/services/capability-audit-service/runner.js +4 -1
  49. package/dist/services/capability-baseline/store.js +2 -1
  50. package/dist/services/capability-guard-runner/contracts/J05.js +4 -2
  51. package/dist/services/capability-guard-runner/contracts/J12.js +2 -2
  52. package/dist/services/code/emit-handoff.js +8 -1
  53. package/dist/services/code/job-shape-decision.js +13 -2
  54. package/dist/services/code/job-shape-provisional.js +9 -1
  55. package/dist/services/code/post-compact-detector.js +9 -1
  56. package/dist/services/code/step-08-session-readers.js +14 -5
  57. package/dist/services/compact/request-transition-hook.js +6 -1
  58. package/dist/services/compact/suggest-service.js +8 -1
  59. package/dist/services/context/post-compact-reinjection.js +15 -14
  60. package/dist/services/context/spillover-store.js +2 -1
  61. package/dist/services/dispatch/contract-store.d.ts +11 -4
  62. package/dist/services/dispatch/contract-store.js +21 -8
  63. package/dist/services/doctor/doctor-service/checks/workspace-layout.js +8 -3
  64. package/dist/services/doctor/doctor-service/index.js +2 -1
  65. package/dist/services/final-review/final-review-evidence-collect.js +5 -1
  66. package/dist/services/fresh-context/fresh-context-block.js +5 -1
  67. package/dist/services/hooks/worktree-authorization-gate.d.ts +1 -1
  68. package/dist/services/hooks/worktree-authorization-gate.js +14 -11
  69. package/dist/services/loop/evaluator-dispatcher.js +7 -7
  70. package/dist/services/loop/monotonic-runner.js +2 -1
  71. package/dist/services/loop/spec-service.js +10 -9
  72. package/dist/services/observability/jsonl-store.js +4 -1
  73. package/dist/services/polyrepo/polyrepo-dispatcher.js +5 -1
  74. package/dist/services/prd/prd-blocks-checker.js +12 -6
  75. package/dist/services/reviewer/reviewer-artifacts.js +2 -1
  76. package/dist/services/sc/sc-service.js +8 -8
  77. package/dist/services/scan/api-diff-recorded.d.ts +2 -3
  78. package/dist/services/scan/api-diff-recorded.js +5 -5
  79. package/dist/services/session/binding-status-service.js +2 -1
  80. package/dist/services/session/binding-store.js +6 -7
  81. package/dist/services/session/caller-binding-service.js +5 -2
  82. package/dist/services/session/getSessionDir.d.ts +4 -0
  83. package/dist/services/session/getSessionDir.js +38 -13
  84. package/dist/services/session/session-binding-bridge.d.ts +3 -6
  85. package/dist/services/session/session-binding-bridge.js +13 -13
  86. package/dist/services/session/session-checkpoint-service.js +22 -3
  87. package/dist/services/session/session-manager.js +16 -20
  88. package/dist/services/skills/presence-lease-resolver.js +3 -2
  89. package/dist/services/skills/presence-lease-service.js +7 -15
  90. package/dist/services/skills/presence-lease-store.d.ts +26 -0
  91. package/dist/services/skills/presence-lease-store.js +60 -5
  92. package/dist/services/skills/skill-presence-service.js +13 -20
  93. package/dist/services/skills/skill-statusline-model.js +7 -2
  94. package/dist/services/slice/slice-archive-service.js +4 -1
  95. package/dist/services/standards/missing-standards-detector.js +2 -1
  96. package/dist/services/test-cache/test-cache-service.js +2 -1
  97. package/dist/services/workflow/artifact-paths.js +6 -2
  98. package/dist/services/workflow/pipeline-verify-gate-support.d.ts +1 -1
  99. package/dist/services/workflow/pipeline-verify-gate-support.js +23 -11
  100. package/dist/services/workflow/workflow-graph-store-helpers.js +12 -3
  101. package/dist/services/workflow/workflow-state-store.js +11 -4
  102. package/dist/services/workspace/migrate-1-4-1-service.js +2 -1
  103. package/dist/services/workspace/reconcile-migrate.js +2 -2
  104. package/dist/services/workspace/reconcile-service.d.ts +4 -6
  105. package/dist/services/workspace/reconcile-service.js +11 -11
  106. package/dist/services/workspace/workspace-service.js +5 -5
  107. package/dist/services/worktree/dispatch-provenance.d.ts +1 -1
  108. package/dist/services/worktree/dispatch-provenance.js +9 -2
  109. package/dist/services/worktree/host-worktree-reconciler.d.ts +1 -1
  110. package/dist/services/worktree/host-worktree-reconciler.js +5 -3
  111. package/dist/shared/runtime-root.js +6 -1
  112. package/package.json +6 -5
  113. package/skills/peaks-mut/SKILL.md +6 -2
  114. package/dist/services/worktree/git-worktree-parser.d.ts +0 -8
  115. package/dist/services/worktree/git-worktree-parser.js +0 -55
  116. package/dist/services/worktree/worktree-lease-types.d.ts +0 -52
  117. package/dist/services/worktree/worktree-lease-types.js +0 -9
  118. package/dist/services/worktree/worktree-lease.d.ts +0 -116
  119. package/dist/services/worktree/worktree-lease.js +0 -252
@@ -9,6 +9,7 @@ import { spawn } from 'node:child_process';
9
9
  import { existsSync, mkdirSync, readFileSync, writeFileSync, readdirSync, unlinkSync } from 'node:fs';
10
10
  import net from 'node:net';
11
11
  import { join, dirname, resolve } from 'node:path';
12
+ import { defaultStateRoot } from 'peaks-loop-workspace-runtime';
12
13
  import { isUnsafePathInput } from '../../shared/path-safety.js';
13
14
  export const DEFAULT_PORT = 8931;
14
15
  export const MAX_PORT = 8949;
@@ -22,8 +23,10 @@ const TERMINAL_HASH_CHARS = 16;
22
23
  const TERMINAL_ID_MAX_CHARS = 64;
23
24
  export const BROWSERS = ['chromium', 'firefox', 'webkit'];
24
25
  export const PLAYWRIGHT_SESSIONS_DIR = 'playwright-sessions';
26
+ /** The runtime root's non-session child holding per-terminal browser profiles. */
27
+ const PLAYWRIGHT_USERDATA_DIR = 'playwright-userdata';
25
28
  export function playwrightSessionsDir(projectRoot) {
26
- return join(projectRoot, '.peaks', '_runtime', PLAYWRIGHT_SESSIONS_DIR);
29
+ return join(defaultStateRoot(projectRoot), PLAYWRIGHT_SESSIONS_DIR);
27
30
  }
28
31
  export function sessionFilePath(projectRoot, terminalId) {
29
32
  // Terminal-id axis. The derived id is already sanitised (`deriveTerminalId`),
@@ -50,7 +53,7 @@ export function defaultUserDataDir(projectRoot, terminalId) {
50
53
  if (isUnsafePathInput(terminalId)) {
51
54
  throw new Error(`Invalid terminal id: ${terminalId} (must be a single path segment)`);
52
55
  }
53
- return join(projectRoot, '.peaks', '_runtime', 'playwright-userdata', terminalId);
56
+ return join(defaultStateRoot(projectRoot), PLAYWRIGHT_USERDATA_DIR, terminalId);
54
57
  }
55
58
  /**
56
59
  * Derive a stable terminal id from the process environment. Prefers
@@ -13,6 +13,7 @@ import { fail, ok } from 'peaks-loop-shared/result';
13
13
  import { archiveScreenshots } from '../../services/qa/screenshot-archive-service.js';
14
14
  import { getSessionId } from '../../services/session/session-manager.js';
15
15
  import { isUnsafePathInput } from '../../shared/path-safety.js';
16
+ import { getSessionDir } from '../../services/session/getSessionDir.js';
16
17
  import { addJsonOption, printResult } from '../cli-helpers.js';
17
18
  export function registerQaArchiveScreenshotsCommand(qa, io) {
18
19
  addJsonOption(qa
@@ -32,7 +33,7 @@ export function registerQaArchiveScreenshotsCommand(qa, io) {
32
33
  if (isUnsafePathInput(sid)) {
33
34
  throw new Error(`Invalid session id: ${sid} (must be a single path segment)`);
34
35
  }
35
- const targetDir = join(projectRoot, '.peaks', '_runtime', sid, 'qa', 'screenshots');
36
+ const targetDir = join(getSessionDir(projectRoot, sid), 'qa', 'screenshots');
36
37
  const envelope = archiveScreenshots({ sourceDir: options.source, targetDir });
37
38
  printResult(io, ok('qa.archive-screenshots', envelope, [], archiveNextActions(envelope)), options.json);
38
39
  }
@@ -2,9 +2,9 @@
2
2
  // pre-transition refusals `peaks request transition` runs before it touches an
3
3
  // artifact — session-id resolution, the `--allow-incomplete` reason rule, and
4
4
  // the assisted/strict-mode bypass gate.
5
- import { join } from 'node:path';
6
5
  import { fail } from 'peaks-loop-shared/result';
7
6
  import { isUnsafePathInput } from '../../shared/path-safety.js';
7
+ import { getSessionDir } from '../../services/session/getSessionDir.js';
8
8
  import { printResult } from '../cli-helpers.js';
9
9
  import { isBypassLimitReached, recordBypass, MAX_BYPASSES_PER_SESSION } from '../../services/mode/bypass-tracker.js';
10
10
  import { showRequestArtifact } from '../../services/artifacts/request-artifact-service.js';
@@ -71,7 +71,7 @@ async function applyRestrictedBypassGate(io, ctx) {
71
71
  refuseAllowIncompleteRestricted(io, ctx, presence.mode);
72
72
  return false;
73
73
  }
74
- const sessionRoot = join(options.project, '.peaks', '_runtime', resolvedSessionId ?? 'default');
74
+ const sessionRoot = getSessionDir(options.project, resolvedSessionId ?? 'default');
75
75
  if (isBypassLimitReached(sessionRoot)) {
76
76
  refuseBypassLimitReached(io, ctx);
77
77
  return false;
@@ -4,13 +4,21 @@
4
4
  // 300-line file cap.
5
5
  import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync } from 'node:fs';
6
6
  import { join } from 'node:path';
7
+ import { defaultStateRoot } from 'peaks-loop-workspace-runtime';
7
8
  import { slugifyDescription } from '../../shared/incrementing-number.js';
9
+ /**
10
+ * The runtime root's non-session `benchmarks/` child. Named as a module
11
+ * constant because the drift guard's reverse check keeps the registry entry
12
+ * alive through a constant's VALUE — an inline literal is invisible to it once
13
+ * the join no longer spells `'_runtime'`.
14
+ */
15
+ const BENCHMARKS_DIR = 'benchmarks';
8
16
  export function readPrdBody(rid, projectRoot) {
9
17
  // Search all .peaks/**/prd/requests/*-<rid>.md and .peaks/**/prd/requests/<rid>.md
10
18
  const searchRoots = [
11
19
  join(projectRoot, '.peaks', '2026'),
12
20
  join(projectRoot, '.peaks'),
13
- join(projectRoot, '.peaks', '_runtime')
21
+ defaultStateRoot(projectRoot)
14
22
  ];
15
23
  const matchInDir = (dir) => {
16
24
  if (!existsSync(dir))
@@ -70,7 +78,7 @@ export function writeBenchmarkArtifact(rid, benchmark, projectRoot) {
70
78
  // Reuse the current session binding if present; otherwise fall back to
71
79
  // a deterministic local dir under the project root. The CLI may be
72
80
  // invoked from non-CLI contexts (skill layer); we don't require a session.
73
- const dir = join(projectRoot, '.peaks', '_runtime', 'benchmarks');
81
+ const dir = join(defaultStateRoot(projectRoot), BENCHMARKS_DIR);
74
82
  if (!existsSync(dir)) {
75
83
  mkdirSync(dir, { recursive: true });
76
84
  }
@@ -5,6 +5,7 @@ import { parseKarpathyEnvelope, parseMutEnvelope, parseQaEnvelope, parseSecurity
5
5
  import { addJsonOption, printResult } from '../cli-helpers.js';
6
6
  import { fail, ok } from 'peaks-loop-shared/result';
7
7
  import { isUnsafePathInput } from '../../shared/path-safety.js';
8
+ import { getSessionDir } from '../../services/session/getSessionDir.js';
8
9
  import { DEFAULT_REQUEST_TYPE } from '../../services/artifacts/artifact-prerequisites.js';
9
10
  import { REQUEST_ID_PATTERN } from '../../services/artifacts/request-artifact-service.js';
10
11
  import { contractEvidencePaths } from '../../services/workflow/pipeline-verify-gate-support.js';
@@ -154,14 +155,14 @@ export function registerVerdictAggregateCommands(program, io) {
154
155
  }
155
156
  function readAudit(projectRoot, sid, rid, rels, parse) {
156
157
  for (const rel of rels) {
157
- const path = join(projectRoot, '.peaks', '_runtime', sid, rel.replace('<rid>', rid));
158
+ const path = join(getSessionDir(projectRoot, sid), rel.replace('<rid>', rid));
158
159
  if (existsSync(path))
159
160
  return parse(readFileSync(path, 'utf8'));
160
161
  }
161
162
  return null;
162
163
  }
163
164
  async function readMut(projectRoot, sid) {
164
- const path = join(projectRoot, '.peaks', '_runtime', sid, MUT_REL);
165
+ const path = join(getSessionDir(projectRoot, sid), MUT_REL);
165
166
  if (!existsSync(path))
166
167
  return null;
167
168
  const raw = readFileSync(path, 'utf8');
@@ -176,7 +177,7 @@ async function readMut(projectRoot, sid) {
176
177
  return parseMutJson(json);
177
178
  }
178
179
  function readQa(projectRoot, sid, rid) {
179
- const dir = join(projectRoot, '.peaks', '_runtime', sid, QA_REL);
180
+ const dir = join(getSessionDir(projectRoot, sid), QA_REL);
180
181
  const candidates = [`${rid}.md`, `001-${slugifyDescription(rid)}.md`];
181
182
  for (const name of candidates) {
182
183
  const path = join(dir, name);
@@ -0,0 +1,13 @@
1
+ /**
2
+ * The real effects the four write-side `peaks worktree` commands hand to the
3
+ * workspace-runtime package's lifecycle actions.
4
+ *
5
+ * The package takes `fs`, `runGit` and the clock value as parameters, so the
6
+ * host policy stays here: peaks-loop writes every lease through
7
+ * `atomicWriteJson` (same bytes, same rename-over-target), runs git through
8
+ * `runGitCli`, and reads `Date.now()` once per action — exactly what the
9
+ * command bodies did before the extraction.
10
+ */
11
+ import type { LeaseEffects } from 'peaks-loop-workspace-runtime';
12
+ /** One effect bundle per action; `now` is read once here, as before. */
13
+ export declare function leaseEffects(now: number): LeaseEffects;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The real effects the four write-side `peaks worktree` commands hand to the
3
+ * workspace-runtime package's lifecycle actions.
4
+ *
5
+ * The package takes `fs`, `runGit` and the clock value as parameters, so the
6
+ * host policy stays here: peaks-loop writes every lease through
7
+ * `atomicWriteJson` (same bytes, same rename-over-target), runs git through
8
+ * `runGitCli`, and reads `Date.now()` once per action — exactly what the
9
+ * command bodies did before the extraction.
10
+ */
11
+ import { existsSync, readdirSync, readFileSync as readFileSyncNode } from 'node:fs';
12
+ import { atomicWriteJson } from '../../services/ide/shared/atomic-json.js';
13
+ import { runGitCli } from './worktree-lease-git.js';
14
+ const realLeaseFs = {
15
+ readFile: (file) => readFileSyncNode(file, 'utf8'),
16
+ writeFile: (file, contents) => atomicWriteJson(file, JSON.parse(contents)),
17
+ existsSync: (file) => existsSync(file),
18
+ readdir: (dir) => readdirSync(dir)
19
+ };
20
+ /** One effect bundle per action; `now` is read once here, as before. */
21
+ export function leaseEffects(now) {
22
+ return { fs: realLeaseFs, runGit: runGitCli, now };
23
+ }
@@ -1,11 +1,10 @@
1
1
  /**
2
2
  * `peaks worktree gc` — sweep released/expired leases.
3
3
  *
4
- * Extracted verbatim from `worktree-lease-commands.ts` (mechanical move of
5
- * the `.action()` body). The per-lease sweep is now `sweepLease`; the
4
+ * The sweep is `runGc` from `peaks-loop-workspace-runtime`; this file owns the
5
+ * host policy, the effects, the per-lease metric emit and the envelope. The
6
6
  * `--lease-id` / `--dry-run` semantics, the expired-active transition, the
7
- * best-effort git removal + prune, the per-lease metric emit and the
8
- * ok/fail envelopes are unchanged.
7
+ * best-effort git removal + prune and the ok/fail envelopes are unchanged.
9
8
  */
10
9
  import type { Command } from 'commander';
11
10
  import { type ProgramIO } from '../cli-helpers.js';
@@ -1,20 +1,18 @@
1
1
  /**
2
2
  * `peaks worktree gc` — sweep released/expired leases.
3
3
  *
4
- * Extracted verbatim from `worktree-lease-commands.ts` (mechanical move of
5
- * the `.action()` body). The per-lease sweep is now `sweepLease`; the
4
+ * The sweep is `runGc` from `peaks-loop-workspace-runtime`; this file owns the
5
+ * host policy, the effects, the per-lease metric emit and the envelope. The
6
6
  * `--lease-id` / `--dry-run` semantics, the expired-active transition, the
7
- * best-effort git removal + prune, the per-lease metric emit and the
8
- * ok/fail envelopes are unchanged.
7
+ * best-effort git removal + prune and the ok/fail envelopes are unchanged.
9
8
  */
10
9
  import { fail, ok } from 'peaks-loop-shared/result';
10
+ import { defaultStateRoot, runGc } from 'peaks-loop-workspace-runtime';
11
11
  import { addJsonOption, getErrorMessage, printResult } from '../cli-helpers.js';
12
- import { atomicWriteJson } from '../../services/ide/shared/atomic-json.js';
13
12
  import { emitLeaseEvent } from '../../services/observability/observability-service.js';
14
- import { isLeaseGcEligible, leaseFilePath, markExpired, markGc } from '../../services/worktree/worktree-lease.js';
15
- import { pruneWorktreesBestEffort, removeWorktreeBestEffort } from './worktree-lease-git.js';
13
+ import { leaseEffects } from './worktree-lease-effects.js';
16
14
  import { loadLeaseStore, malformedLeaseWarnings } from './worktree-lease-store.js';
17
- import { joinPathSession, resolveProjectRoot, resolveSessionId } from './worktree-lease-session.js';
15
+ import { resolveProjectRoot, resolveSessionId } from './worktree-lease-session.js';
18
16
  const GC_DESCRIPTION = "Sweep released/expired leases: remove their git worktree (if still attached), prune git's " +
19
17
  'worktree references, and mark the lease as "gc". With --lease-id <id>, only that lease is ' +
20
18
  "considered. With --dry-run, report what would be gc'd without mutating. Expired-active " +
@@ -22,40 +20,6 @@ const GC_DESCRIPTION = "Sweep released/expired leases: remove their git worktree
22
20
  'then their worktree is removed.';
23
21
  const GC_LEASE_ID_DESCRIPTION = 'only consider this specific lease';
24
22
  const GC_DRY_RUN_DESCRIPTION = "report what would be gc'd without mutating";
25
- function sweepLease(ctx) {
26
- const { lease, dryRun, now, projectRoot, sessionId } = ctx;
27
- let prevStatus = lease.status;
28
- let updated = lease;
29
- // If the lease is still marked active but past expiresAt, transition to expired first.
30
- if (lease.status === 'active' && lease.expiresAt <= now) {
31
- updated = markExpired(lease);
32
- prevStatus = 'active';
33
- }
34
- if (dryRun) {
35
- return {
36
- leaseId: lease.leaseId,
37
- path: lease.path,
38
- prevStatus,
39
- gitWorktreeRemoveFailed: false
40
- };
41
- }
42
- // `git worktree remove --force` is best-effort — if the path is
43
- // already gone we still mark the lease gc.
44
- const gitWorktreeRemoveFailed = removeWorktreeBestEffort(projectRoot, updated.path);
45
- pruneWorktreesBestEffort(projectRoot);
46
- const finalLease = markGc(updated);
47
- atomicWriteJson(leaseFilePath(joinPathSession(projectRoot, sessionId), lease.leaseId), finalLease);
48
- // Part 4.A: emit gc metric (per swept lease).
49
- emitLeaseEvent({
50
- sessionId,
51
- projectRoot,
52
- kind: 'gc',
53
- leaseId: lease.leaseId,
54
- rid: lease.rid,
55
- role: lease.role
56
- });
57
- return { leaseId: lease.leaseId, path: lease.path, prevStatus, gitWorktreeRemoveFailed };
58
- }
59
23
  function printGcStoreMissing(io, options, ctx) {
60
24
  const { sessionId, projectRoot, storeDir } = ctx;
61
25
  printResult(io, ok('worktree.gc', { sessionId, projectRoot, swept: 0, storeMissing: true }, [], [`No lease store at ${storeDir}; nothing to gc.`]), options.json);
@@ -75,30 +39,67 @@ function printGcFailed(io, options, err, sessionId) {
75
39
  ]), options.json);
76
40
  process.exitCode = 1;
77
41
  }
78
- function runGc(options, io) {
42
+ /**
43
+ * The rid/role the gc metric row needs, keyed by lease id. The package's sweep
44
+ * result carries the id and path but not the lease itself, so the store is
45
+ * read once more here — the single directory scan this command made before.
46
+ */
47
+ function leaseIdentity(projectRoot, sessionId) {
48
+ const listed = loadLeaseStore(projectRoot, sessionId);
49
+ const leases = listed.result.kind === 'ok' ? listed.result.leases : [];
50
+ return new Map(leases.map((lease) => [lease.leaseId, { rid: lease.rid, role: lease.role }]));
51
+ }
52
+ /** Part 4.A: one gc metric per swept lease; a dry run emits nothing. */
53
+ function emitGcMetrics(result, ctx) {
54
+ if (result.kind !== 'ok' || result.dryRun)
55
+ return;
56
+ for (const entry of result.swept) {
57
+ const identity = ctx.identity.get(entry.leaseId);
58
+ // A swept lease came from the store just read, so a miss only happens if
59
+ // the store changed underneath us; never emit a row with an invented rid.
60
+ if (identity === undefined)
61
+ continue;
62
+ emitLeaseEvent({
63
+ sessionId: ctx.sessionId,
64
+ projectRoot: ctx.projectRoot,
65
+ kind: 'gc',
66
+ leaseId: entry.leaseId,
67
+ rid: identity.rid,
68
+ role: identity.role
69
+ });
70
+ }
71
+ }
72
+ function runGcAction(options, io) {
79
73
  const projectRoot = resolveProjectRoot(options);
80
74
  const sessionId = resolveSessionId(options, projectRoot);
81
75
  try {
82
- const { storeDir, result } = loadLeaseStore(projectRoot, sessionId);
76
+ // Read BEFORE the sweep, as before: a store that cannot be read fails the
77
+ // command without having mutated anything.
78
+ const identity = leaseIdentity(projectRoot, sessionId);
79
+ const result = runGc({
80
+ projectRoot,
81
+ stateRoot: defaultStateRoot(projectRoot),
82
+ sessionId,
83
+ // A falsy `--lease-id` means "every lease", as before.
84
+ ...(options.leaseId ? { leaseId: options.leaseId } : {}),
85
+ dryRun: options.dryRun === true
86
+ }, leaseEffects(Date.now()));
83
87
  if (result.kind === 'store-missing') {
84
- printGcStoreMissing(io, options, { sessionId, projectRoot, storeDir });
88
+ printGcStoreMissing(io, options, { sessionId, projectRoot, storeDir: result.storeDir });
85
89
  return;
86
90
  }
87
- const now = Date.now();
88
- const candidates = result.leases
89
- .filter((l) => (options.leaseId ? l.leaseId === options.leaseId : true))
90
- .filter((l) => isLeaseGcEligible(l, now));
91
- const dryRun = options.dryRun === true;
92
- const swept = [];
93
- for (const lease of candidates) {
94
- swept.push(sweepLease({ lease, dryRun, now, projectRoot, sessionId }));
95
- }
91
+ emitGcMetrics(result, { projectRoot, sessionId, identity });
96
92
  printGcOk(io, options, {
97
93
  sessionId,
98
94
  projectRoot,
99
- dryRun,
100
- candidates: candidates.length,
101
- swept,
95
+ dryRun: result.dryRun,
96
+ candidates: result.candidates,
97
+ swept: result.swept.map((entry) => ({
98
+ leaseId: entry.leaseId,
99
+ path: entry.path,
100
+ prevStatus: entry.previousStatus,
101
+ gitWorktreeRemoveFailed: entry.gitWorktreeRemoveFailed
102
+ })),
102
103
  errors: result.errors
103
104
  });
104
105
  }
@@ -113,5 +114,5 @@ export function registerWorktreeLeaseGcCommand(auth, io) {
113
114
  .option('--lease-id <id>', GC_LEASE_ID_DESCRIPTION)
114
115
  .option('--dry-run', GC_DRY_RUN_DESCRIPTION)
115
116
  .option('--session <sid>', 'override session id')
116
- .option('--project <path>', 'project root (default: findProjectRoot(cwd))')).action((options) => runGc(options, io));
117
+ .option('--project <path>', 'project root (default: findProjectRoot(cwd))')).action((options) => runGcAction(options, io));
117
118
  }
@@ -1,22 +1,17 @@
1
1
  /**
2
- * Best-effort `git worktree` shell helpers shared by `release` and `gc`.
2
+ * The peaks-loop `RunGit` implementation handed to the workspace-runtime
3
+ * package.
3
4
  *
4
- * Both commands detach a worktree the same way (and `gc` additionally
5
- * prunes stale admin entries). Extracted verbatim from
6
- * `worktree-lease-commands.ts`: the commands, cwd, stdio/encoding flags
7
- * and the swallow-on-failure posture are unchanged.
8
- */
9
- /**
10
- * `git worktree remove --force` is best-effort: when the path is already
11
- * pruned the caller still marks the lease released / gc. Returns whether
12
- * the git invocation failed.
5
+ * `execFileSync('git', argv, …)`, not a shell command string. The package's
6
+ * `RunGit` contract is an argv array, and the shell is what used to reinterpret
7
+ * it: a path or branch containing `"`, `$(…)` or a backtick reached the shell
8
+ * as syntax because this module quoted the argument by hand. No hand-rolled
9
+ * quoting helper is provably correct for both `cmd.exe` and POSIX `sh`, so the
10
+ * shell is gone rather than escaped.
13
11
  *
14
- * `windowsHide: true` is spelled at each call site rather than shared: the
15
- * guard (`tests/unit/spawn-windows-hide-guard.test.ts`) resolves a same-file
16
- * plain-`const` object literal and a spread of it, but not one declared
17
- * `as const`, frozen, `let`, or imported from another file — measured: both
18
- * call sites below were reported while the shared constant was `as const`.
12
+ * The `{ cwd, stdio, encoding, windowsHide }` object literal is spelled at the
13
+ * call site on purpose: the guard in `tests/unit/spawn-windows-hide-guard.test.ts`
14
+ * resolves an inline object literal, not one imported or declared `as const`.
19
15
  */
20
- export declare function removeWorktreeBestEffort(projectRoot: string, wtPath: string): boolean;
21
- /** `git worktree prune` clears stale admin entries. Best-effort. */
22
- export declare function pruneWorktreesBestEffort(projectRoot: string): void;
16
+ import type { RunGit } from 'peaks-loop-workspace-runtime';
17
+ export declare const runGitCli: RunGit;
@@ -1,48 +1,25 @@
1
1
  /**
2
- * Best-effort `git worktree` shell helpers shared by `release` and `gc`.
2
+ * The peaks-loop `RunGit` implementation handed to the workspace-runtime
3
+ * package.
3
4
  *
4
- * Both commands detach a worktree the same way (and `gc` additionally
5
- * prunes stale admin entries). Extracted verbatim from
6
- * `worktree-lease-commands.ts`: the commands, cwd, stdio/encoding flags
7
- * and the swallow-on-failure posture are unchanged.
8
- */
9
- import { execSync } from 'node:child_process';
10
- /**
11
- * `git worktree remove --force` is best-effort: when the path is already
12
- * pruned the caller still marks the lease released / gc. Returns whether
13
- * the git invocation failed.
5
+ * `execFileSync('git', argv, …)`, not a shell command string. The package's
6
+ * `RunGit` contract is an argv array, and the shell is what used to reinterpret
7
+ * it: a path or branch containing `"`, `$(…)` or a backtick reached the shell
8
+ * as syntax because this module quoted the argument by hand. No hand-rolled
9
+ * quoting helper is provably correct for both `cmd.exe` and POSIX `sh`, so the
10
+ * shell is gone rather than escaped.
14
11
  *
15
- * `windowsHide: true` is spelled at each call site rather than shared: the
16
- * guard (`tests/unit/spawn-windows-hide-guard.test.ts`) resolves a same-file
17
- * plain-`const` object literal and a spread of it, but not one declared
18
- * `as const`, frozen, `let`, or imported from another file — measured: both
19
- * call sites below were reported while the shared constant was `as const`.
12
+ * The `{ cwd, stdio, encoding, windowsHide }` object literal is spelled at the
13
+ * call site on purpose: the guard in `tests/unit/spawn-windows-hide-guard.test.ts`
14
+ * resolves an inline object literal, not one imported or declared `as const`.
20
15
  */
21
- export function removeWorktreeBestEffort(projectRoot, wtPath) {
22
- try {
23
- execSync(`git worktree remove --force "${wtPath}"`, {
24
- cwd: projectRoot,
25
- stdio: 'pipe',
26
- encoding: 'utf8',
27
- windowsHide: true
28
- });
29
- return false;
30
- }
31
- catch {
32
- return true;
33
- }
34
- }
35
- /** `git worktree prune` clears stale admin entries. Best-effort. */
36
- export function pruneWorktreesBestEffort(projectRoot) {
37
- try {
38
- execSync('git worktree prune', {
39
- cwd: projectRoot,
40
- stdio: 'pipe',
41
- encoding: 'utf8',
42
- windowsHide: true
43
- });
44
- }
45
- catch {
46
- // ignore — prune is idempotent
47
- }
48
- }
16
+ import { execFileSync } from 'node:child_process';
17
+ export const runGitCli = (argv, opts) => {
18
+ const stdout = execFileSync('git', argv, {
19
+ cwd: opts.cwd,
20
+ stdio: 'pipe',
21
+ encoding: 'utf8',
22
+ windowsHide: true
23
+ });
24
+ return { ok: true, stdout };
25
+ };
@@ -8,8 +8,8 @@
8
8
  * ok/fail envelopes are unchanged.
9
9
  */
10
10
  import { fail, ok } from 'peaks-loop-shared/result';
11
+ import { isLeaseActive } from 'peaks-loop-workspace-runtime';
11
12
  import { addJsonOption, getErrorMessage, printResult } from '../cli-helpers.js';
12
- import { isLeaseActive } from '../../services/worktree/worktree-lease.js';
13
13
  import { loadLeaseStore, malformedLeaseWarnings } from './worktree-lease-store.js';
14
14
  import { resolveProjectRoot, resolveSessionId } from './worktree-lease-session.js';
15
15
  const LIST_DESCRIPTION = "List every lease under the current session's lease store. " +
@@ -1,15 +1,19 @@
1
1
  /**
2
- * Shared single-lease loader for the three read-by-lease-id commands
2
+ * Shared single-lease failure envelopes for the read-by-lease-id commands
3
3
  * (`release`, `renew`, `lease-status`).
4
4
  *
5
- * All three used to inline the same two failure shapes — a missing lease
6
- * file (`LEASE_NOT_FOUND`) and an unparseable one (`LEASE_FILE_INVALID`) —
7
- * differing only in the envelope `command` string and the two hint lines.
8
- * Both are parameters here. The message text, the `{ leaseId, file }`
9
- * data payload and the caller's `process.exitCode = 1` are unchanged.
5
+ * All of them surface the same two failure shapes — a missing lease file
6
+ * (`LEASE_NOT_FOUND`) and an unparseable one (`LEASE_FILE_INVALID`) — differing
7
+ * only in the envelope `command` string and the two hint lines. Both are
8
+ * parameters here. The message text, the `{ leaseId, file }` data payload and
9
+ * the caller's `process.exitCode = 1` are unchanged.
10
+ *
11
+ * `printLeaseFileFailure` takes the failure record the workspace-runtime
12
+ * package's actions return, so `release` and `renew` keep this exact envelope
13
+ * even though the load now happens inside the package.
10
14
  */
15
+ import { type LeaseFileFailure, type WorktreeLease } from 'peaks-loop-workspace-runtime';
11
16
  import { type ProgramIO } from '../cli-helpers.js';
12
- import { type WorktreeLease } from '../../services/worktree/worktree-lease.js';
13
17
  /** The option surface the loader reads: the lease id and `--json`. */
14
18
  export interface LeaseIdOptions {
15
19
  leaseId: string;
@@ -34,4 +38,12 @@ export type LeaseLoadResult = {
34
38
  stop: false;
35
39
  lease: WorktreeLease;
36
40
  };
41
+ /**
42
+ * Print the envelope for a lease-file failure and report that the caller must
43
+ * stop: `release` and `renew` both set `process.exitCode = 1` on it.
44
+ */
45
+ export declare function stopOnLeaseFileFailure(io: ProgramIO, options: LeaseIdOptions, request: {
46
+ command: string;
47
+ hints: LeaseLoadHints;
48
+ }, failure: LeaseFileFailure): true;
37
49
  export declare function loadLeaseOrStop(io: ProgramIO, options: LeaseIdOptions, request: LeaseLoadRequest): LeaseLoadResult;
@@ -1,28 +1,56 @@
1
1
  /**
2
- * Shared single-lease loader for the three read-by-lease-id commands
2
+ * Shared single-lease failure envelopes for the read-by-lease-id commands
3
3
  * (`release`, `renew`, `lease-status`).
4
4
  *
5
- * All three used to inline the same two failure shapes — a missing lease
6
- * file (`LEASE_NOT_FOUND`) and an unparseable one (`LEASE_FILE_INVALID`) —
7
- * differing only in the envelope `command` string and the two hint lines.
8
- * Both are parameters here. The message text, the `{ leaseId, file }`
9
- * data payload and the caller's `process.exitCode = 1` are unchanged.
5
+ * All of them surface the same two failure shapes — a missing lease file
6
+ * (`LEASE_NOT_FOUND`) and an unparseable one (`LEASE_FILE_INVALID`) — differing
7
+ * only in the envelope `command` string and the two hint lines. Both are
8
+ * parameters here. The message text, the `{ leaseId, file }` data payload and
9
+ * the caller's `process.exitCode = 1` are unchanged.
10
+ *
11
+ * `printLeaseFileFailure` takes the failure record the workspace-runtime
12
+ * package's actions return, so `release` and `renew` keep this exact envelope
13
+ * even though the load now happens inside the package.
10
14
  */
11
15
  import { fail } from 'peaks-loop-shared/result';
12
16
  import { existsSync, readFileSync as readFileSyncNode } from 'node:fs';
17
+ import { deserializeLease } from 'peaks-loop-workspace-runtime';
13
18
  import { getErrorMessage, printResult } from '../cli-helpers.js';
14
- import { deserializeLease } from '../../services/worktree/worktree-lease.js';
19
+ /**
20
+ * Print the envelope for a lease-file failure and report that the caller must
21
+ * stop: `release` and `renew` both set `process.exitCode = 1` on it.
22
+ */
23
+ export function stopOnLeaseFileFailure(io, options, request, failure) {
24
+ printLeaseFileFailure(io, options, request, failure);
25
+ process.exitCode = 1;
26
+ return true;
27
+ }
28
+ /** Print the envelope for a missing or malformed lease file. */
29
+ function printLeaseFileFailure(io, options, request, failure) {
30
+ const { command, hints } = request;
31
+ if (failure.kind === 'lease-not-found') {
32
+ printResult(io, fail(command, 'LEASE_NOT_FOUND', `no lease on disk at ${failure.file}`, { leaseId: options.leaseId, file: failure.file }, hints.missing), options.json);
33
+ return;
34
+ }
35
+ printResult(io, fail(command, 'LEASE_FILE_INVALID', failure.error, { leaseId: options.leaseId, file: failure.file }, hints.invalid), options.json);
36
+ }
15
37
  export function loadLeaseOrStop(io, options, request) {
16
38
  const { command, file, hints } = request;
17
39
  if (!existsSync(file)) {
18
- printResult(io, fail(command, 'LEASE_NOT_FOUND', `no lease on disk at ${file}`, { leaseId: options.leaseId, file }, hints.missing), options.json);
40
+ printLeaseFileFailure(io, options, request, { kind: 'lease-not-found', file });
19
41
  return { stop: true };
20
42
  }
21
43
  try {
44
+ // Re-uses the package's deserializer so a malformed file is rejected by
45
+ // the same validator the lifecycle actions apply.
22
46
  return { stop: false, lease: deserializeLease(readFileSyncNode(file, 'utf8')) };
23
47
  }
24
48
  catch (error) {
25
- printResult(io, fail(command, 'LEASE_FILE_INVALID', getErrorMessage(error), { leaseId: options.leaseId, file }, hints.invalid), options.json);
49
+ printLeaseFileFailure(io, options, { command, hints }, {
50
+ kind: 'lease-invalid',
51
+ file,
52
+ error: getErrorMessage(error)
53
+ });
26
54
  return { stop: true };
27
55
  }
28
56
  }
@@ -2,11 +2,10 @@
2
2
  * `peaks worktree release` — transition a lease to 'released' and run
3
3
  * `git worktree remove`.
4
4
  *
5
- * Extracted verbatim from `worktree-lease-commands.ts` (mechanical move of
6
- * the `.action()` body). The lease-file failures now route through the
7
- * shared `loadLeaseOrStop` (same envelope, same hints, same exit code);
8
- * the idempotent already-released branch, the best-effort git removal and
9
- * the ok/fail envelopes are unchanged.
5
+ * The action body is `runRelease` from `peaks-loop-workspace-runtime`; this
6
+ * file owns the host policy, the effects and the envelope. The idempotent
7
+ * already-released branch, the best-effort git removal, the lease-file failure
8
+ * envelopes and the metric emit are unchanged.
10
9
  */
11
10
  import type { Command } from 'commander';
12
11
  import { type ProgramIO } from '../cli-helpers.js';