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
@@ -2,20 +2,18 @@
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 { fail, ok } from 'peaks-loop-shared/result';
11
+ import { defaultStateRoot, runRelease } from 'peaks-loop-workspace-runtime';
12
12
  import { addJsonOption, getErrorMessage, printResult } from '../cli-helpers.js';
13
- import { atomicWriteJson } from '../../services/ide/shared/atomic-json.js';
14
13
  import { emitLeaseEvent } from '../../services/observability/observability-service.js';
15
- import { leaseFilePath, markReleased } from '../../services/worktree/worktree-lease.js';
16
- import { loadLeaseOrStop } from './worktree-lease-load.js';
17
- import { removeWorktreeBestEffort } from './worktree-lease-git.js';
18
- import { joinPathSession, resolveProjectRoot, resolveSessionId } from './worktree-lease-session.js';
14
+ import { leaseEffects } from './worktree-lease-effects.js';
15
+ import { stopOnLeaseFileFailure } from './worktree-lease-load.js';
16
+ import { resolveProjectRoot, resolveSessionId } from './worktree-lease-session.js';
19
17
  const RELEASE_DESCRIPTION = 'Transition a lease to released and run `git worktree remove`. Idempotent on already-released leases.';
20
18
  const RELEASE_MISSING_HINTS = [
21
19
  'Run `peaks worktree list` to inspect active leases.',
@@ -47,48 +45,63 @@ function printReleaseFailed(io, options, error, sessionId) {
47
45
  printResult(io, fail('worktree.release', 'RELEASE_FAILED', getErrorMessage(error), { leaseId: options.leaseId, sessionId }, ['Verify the lease id and re-run.', 'If the lease was never spawned, no-op.']), options.json);
48
46
  process.exitCode = 1;
49
47
  }
50
- function runRelease(options, io) {
48
+ /**
49
+ * The success tail: the release metric, then the envelope.
50
+ * Part 4.A: the manual path emits here; auto-release is recorded in
51
+ * dispatch-record-writer's tryAutoReleaseLease.
52
+ */
53
+ function finishRelease(io, options, ctx) {
54
+ const { lease, released, sessionId, projectRoot, gitWorktreeRemoveFailed } = ctx;
55
+ emitLeaseEvent({
56
+ sessionId,
57
+ projectRoot,
58
+ kind: 'release',
59
+ leaseId: released.leaseId,
60
+ rid: released.rid,
61
+ role: released.role
62
+ });
63
+ printReleaseDone(io, options, {
64
+ lease,
65
+ released,
66
+ sessionId,
67
+ projectRoot,
68
+ gitWorktreeRemoveFailed
69
+ });
70
+ }
71
+ function runReleaseAction(options, io) {
51
72
  const projectRoot = resolveProjectRoot(options);
52
73
  const sessionId = resolveSessionId(options, projectRoot);
53
74
  try {
54
- const file = leaseFilePath(joinPathSession(projectRoot, sessionId), options.leaseId);
55
- const loaded = loadLeaseOrStop(io, options, {
56
- command: 'worktree.release',
57
- file,
58
- hints: { missing: RELEASE_MISSING_HINTS, invalid: RELEASE_INVALID_HINTS }
59
- });
60
- if (loaded.stop) {
61
- process.exitCode = 1;
62
- return;
63
- }
64
- const lease = loaded.lease;
65
- if (lease.status === 'released') {
66
- printReleaseAlreadyReleased(io, options, { lease, sessionId, projectRoot });
67
- return;
68
- }
69
- // Run `git worktree remove` from the project root. If the path is
70
- // missing on disk (e.g. manually pruned), this fails; we still
71
- // update the lease state so the L2 hook (Part 2) treats it as
72
- // released.
73
- const gitWorktreeRemoveFailed = removeWorktreeBestEffort(projectRoot, lease.path);
74
- const released = markReleased(lease);
75
- atomicWriteJson(file, released);
76
- // Part 4.A: emit release metric (manual path; auto-release is
77
- // recorded in dispatch-record-writer's tryAutoReleaseLease).
78
- emitLeaseEvent({
79
- sessionId,
75
+ const result = runRelease({
80
76
  projectRoot,
81
- kind: 'release',
82
- leaseId: released.leaseId,
83
- rid: released.rid,
84
- role: released.role
85
- });
86
- printReleaseDone(io, options, {
87
- lease,
88
- released,
77
+ stateRoot: defaultStateRoot(projectRoot),
78
+ sessionId,
79
+ leaseId: options.leaseId
80
+ }, leaseEffects(Date.now()));
81
+ switch (result.kind) {
82
+ case 'lease-not-found':
83
+ case 'lease-invalid':
84
+ stopOnLeaseFileFailure(io, options, {
85
+ command: 'worktree.release',
86
+ hints: { missing: RELEASE_MISSING_HINTS, invalid: RELEASE_INVALID_HINTS }
87
+ }, result);
88
+ return;
89
+ case 'already-released':
90
+ printReleaseAlreadyReleased(io, options, {
91
+ lease: result.lease,
92
+ sessionId,
93
+ projectRoot
94
+ });
95
+ return;
96
+ case 'ok':
97
+ break;
98
+ }
99
+ finishRelease(io, options, {
100
+ lease: result.previous,
101
+ released: result.lease,
89
102
  sessionId,
90
103
  projectRoot,
91
- gitWorktreeRemoveFailed
104
+ gitWorktreeRemoveFailed: result.gitWorktreeRemoveFailed
92
105
  });
93
106
  }
94
107
  catch (error) {
@@ -101,5 +114,5 @@ export function registerWorktreeLeaseReleaseCommand(auth, io) {
101
114
  .description(RELEASE_DESCRIPTION)
102
115
  .requiredOption('--lease-id <id>', 'lease id returned by `peaks worktree spawn`')
103
116
  .option('--session <sid>', 'override session id')
104
- .option('--project <path>', 'project root (default: findProjectRoot(cwd))')).action((options) => runRelease(options, io));
117
+ .option('--project <path>', 'project root (default: findProjectRoot(cwd))')).action((options) => runReleaseAction(options, io));
105
118
  }
@@ -1,10 +1,11 @@
1
1
  /**
2
2
  * `peaks worktree renew` — extend an active lease's `expiresAt`.
3
3
  *
4
- * Extracted verbatim from `worktree-lease-commands.ts` (mechanical move of
5
- * the `.action()` body). The lease-file failures route through the shared
6
- * `loadLeaseOrStop`; the LEASE_NOT_RENEWABLE / INVALID_TTL guards, the
7
- * renewal write, the metric emit and the ok/fail envelopes are unchanged.
4
+ * The action body is `runRenew` from `peaks-loop-workspace-runtime`; this file
5
+ * owns the host policy, the effects and the envelope. Every result kind is
6
+ * mapped back onto the envelope/exit code it produced before the extraction
7
+ * (LEASE_NOT_FOUND / LEASE_FILE_INVALID / LEASE_NOT_RENEWABLE / INVALID_TTL),
8
+ * and the metric emit stays here.
8
9
  */
9
10
  import type { Command } from 'commander';
10
11
  import { type ProgramIO } from '../cli-helpers.js';
@@ -1,18 +1,19 @@
1
1
  /**
2
2
  * `peaks worktree renew` — extend an active lease's `expiresAt`.
3
3
  *
4
- * Extracted verbatim from `worktree-lease-commands.ts` (mechanical move of
5
- * the `.action()` body). The lease-file failures route through the shared
6
- * `loadLeaseOrStop`; the LEASE_NOT_RENEWABLE / INVALID_TTL guards, the
7
- * renewal write, the metric emit and the ok/fail envelopes are unchanged.
4
+ * The action body is `runRenew` from `peaks-loop-workspace-runtime`; this file
5
+ * owns the host policy, the effects and the envelope. Every result kind is
6
+ * mapped back onto the envelope/exit code it produced before the extraction
7
+ * (LEASE_NOT_FOUND / LEASE_FILE_INVALID / LEASE_NOT_RENEWABLE / INVALID_TTL),
8
+ * and the metric emit stays here.
8
9
  */
9
10
  import { fail, ok } from 'peaks-loop-shared/result';
11
+ import { defaultStateRoot, runRenew } from 'peaks-loop-workspace-runtime';
10
12
  import { addJsonOption, getErrorMessage, printResult } from '../cli-helpers.js';
11
- import { atomicWriteJson } from '../../services/ide/shared/atomic-json.js';
12
13
  import { emitLeaseEvent } from '../../services/observability/observability-service.js';
13
- import { leaseFilePath, renewLease, ttlForRole } from '../../services/worktree/worktree-lease.js';
14
- import { loadLeaseOrStop } from './worktree-lease-load.js';
15
- import { joinPathSession, resolveProjectRoot, resolveSessionId } from './worktree-lease-session.js';
14
+ import { leaseEffects } from './worktree-lease-effects.js';
15
+ import { stopOnLeaseFileFailure } from './worktree-lease-load.js';
16
+ import { resolveProjectRoot, resolveSessionId } from './worktree-lease-session.js';
16
17
  const RENEW_DESCRIPTION = "Extend an active lease's `expiresAt` and persist it. Idempotent for already-active leases. " +
17
18
  'Default TTL uses `DEFAULT_TTL_BY_ROLE[<lease.role>]`; pass --ttl <ms> to override.';
18
19
  const RENEW_MISSING_HINTS = [
@@ -46,33 +47,36 @@ function printRenewFailed(io, options, err, sessionId) {
46
47
  printResult(io, fail('worktree.renew', 'RENEW_FAILED', getErrorMessage(err), { leaseId: options.leaseId, sessionId }, ['Re-run after fixing the failure (see cause in the error message).']), options.json);
47
48
  process.exitCode = 1;
48
49
  }
49
- function runRenew(options, io) {
50
+ function runRenewAction(options, io) {
50
51
  const projectRoot = resolveProjectRoot(options);
51
52
  const sessionId = resolveSessionId(options, projectRoot);
52
53
  try {
53
- const file = leaseFilePath(joinPathSession(projectRoot, sessionId), options.leaseId);
54
- const loaded = loadLeaseOrStop(io, options, {
55
- command: 'worktree.renew',
56
- file,
57
- hints: { missing: RENEW_MISSING_HINTS, invalid: RENEW_INVALID_HINTS }
58
- });
59
- if (loaded.stop) {
60
- process.exitCode = 1;
61
- return;
62
- }
63
- const lease = loaded.lease;
64
- if (lease.status === 'released' || lease.status === 'gc') {
65
- printRenewNotRenewable(io, options, lease);
66
- return;
67
- }
68
- const now = Date.now();
69
- const ttlMs = options.ttl === undefined ? ttlForRole(lease.role) : Number.parseInt(options.ttl, 10);
70
- if (!Number.isInteger(ttlMs) || ttlMs <= 0) {
71
- printRenewInvalidTtl(io, options);
72
- return;
54
+ const result = runRenew({
55
+ projectRoot,
56
+ stateRoot: defaultStateRoot(projectRoot),
57
+ sessionId,
58
+ leaseId: options.leaseId,
59
+ // `exactOptionalPropertyTypes`: absent means the role's default TTL.
60
+ ...(options.ttl === undefined ? {} : { ttlMs: Number.parseInt(options.ttl, 10) })
61
+ }, leaseEffects(Date.now()));
62
+ switch (result.kind) {
63
+ case 'lease-not-found':
64
+ case 'lease-invalid':
65
+ stopOnLeaseFileFailure(io, options, {
66
+ command: 'worktree.renew',
67
+ hints: { missing: RENEW_MISSING_HINTS, invalid: RENEW_INVALID_HINTS }
68
+ }, result);
69
+ return;
70
+ case 'not-renewable':
71
+ printRenewNotRenewable(io, options, result.lease);
72
+ return;
73
+ case 'invalid-ttl':
74
+ printRenewInvalidTtl(io, options);
75
+ return;
76
+ case 'ok':
77
+ break;
73
78
  }
74
- const renewed = renewLease(lease, now + ttlMs);
75
- atomicWriteJson(file, renewed);
79
+ const { lease: renewed, previous: lease, ttlMs } = result;
76
80
  // Part 4.A: emit renew metric.
77
81
  emitLeaseEvent({
78
82
  sessionId,
@@ -95,5 +99,5 @@ export function registerWorktreeLeaseRenewCommand(auth, io) {
95
99
  .requiredOption('--lease-id <id>', 'lease id returned by `peaks worktree spawn`')
96
100
  .option('--ttl <ms>', 'time-to-live in ms from now (default: role-default)')
97
101
  .option('--session <sid>', 'override session id')
98
- .option('--project <path>', 'project root (default: findProjectRoot(cwd))')).action((options) => runRenew(options, io));
102
+ .option('--project <path>', 'project root (default: findProjectRoot(cwd))')).action((options) => runRenewAction(options, io));
99
103
  }
@@ -2,10 +2,12 @@
2
2
  * Session / project-root resolution shared by every `peaks worktree
3
3
  * <spawn|release|renew|list|gc|lease-status>` sub-command.
4
4
  *
5
- * Extracted verbatim from `worktree-lease-commands.ts` so each
6
- * `worktree-lease-<name>-command.ts` sibling can resolve the same roots
7
- * without importing the registrar module (the dependency direction stays
8
- * one-way: siblings → this module → services).
5
+ * The host policy lives here — the package reads no env, no cwd and no
6
+ * `session.json` (S1 rule 2). `joinPathSession` is now a delegation to the
7
+ * workspace-runtime package's `defaultStateRoot` + `sessionRuntimeDir`, the
8
+ * single implementation shared with peaks-harness. The exported name and
9
+ * signature are unchanged so the six commands and `worktree-lease-store.ts`
10
+ * keep their shape.
9
11
  */
10
12
  export declare function resolveSessionId(options: {
11
13
  session?: string;
@@ -14,7 +16,7 @@ export declare function resolveProjectRoot(options: {
14
16
  project?: string;
15
17
  }): string;
16
18
  /**
17
- * Resolve the per-session runtime directory: `<projectRoot>/.peaks/_runtime/<sessionId>`.
19
+ * Resolve the per-session runtime directory.
18
20
  * The runtime tree is gitignored; the spawn CLI writes the lease file
19
21
  * under `<this>/worktree-leases/<leaseId>.json` and the worktree itself
20
22
  * under `<this>/worktrees/<leaseId>/`.
@@ -2,11 +2,14 @@
2
2
  * Session / project-root resolution shared by every `peaks worktree
3
3
  * <spawn|release|renew|list|gc|lease-status>` sub-command.
4
4
  *
5
- * Extracted verbatim from `worktree-lease-commands.ts` so each
6
- * `worktree-lease-<name>-command.ts` sibling can resolve the same roots
7
- * without importing the registrar module (the dependency direction stays
8
- * one-way: siblings → this module → services).
5
+ * The host policy lives here — the package reads no env, no cwd and no
6
+ * `session.json` (S1 rule 2). `joinPathSession` is now a delegation to the
7
+ * workspace-runtime package's `defaultStateRoot` + `sessionRuntimeDir`, the
8
+ * single implementation shared with peaks-harness. The exported name and
9
+ * signature are unchanged so the six commands and `worktree-lease-store.ts`
10
+ * keep their shape.
9
11
  */
12
+ import { defaultStateRoot, sessionRuntimeDir } from 'peaks-loop-workspace-runtime';
10
13
  import { findProjectRoot } from '../../services/config/config-safety.js';
11
14
  import { getCurrentSessionId } from '../../services/skills/skill-presence-service.js';
12
15
  export function resolveSessionId(options, projectRoot) {
@@ -19,11 +22,11 @@ export function resolveProjectRoot(options) {
19
22
  return options.project ?? findProjectRoot(process.cwd()) ?? process.cwd();
20
23
  }
21
24
  /**
22
- * Resolve the per-session runtime directory: `<projectRoot>/.peaks/_runtime/<sessionId>`.
25
+ * Resolve the per-session runtime directory.
23
26
  * The runtime tree is gitignored; the spawn CLI writes the lease file
24
27
  * under `<this>/worktree-leases/<leaseId>.json` and the worktree itself
25
28
  * under `<this>/worktrees/<leaseId>/`.
26
29
  */
27
30
  export function joinPathSession(projectRoot, sessionId) {
28
- return `${projectRoot.replace(/[\\/]+$/, '')}/.peaks/_runtime/${sessionId}`;
31
+ return sessionRuntimeDir({ stateRoot: defaultStateRoot(projectRoot), sessionId });
29
32
  }
@@ -1,9 +1,10 @@
1
1
  /**
2
2
  * `peaks worktree spawn` — write a lease and run `git worktree add`.
3
3
  *
4
- * Extracted verbatim from `worktree-lease-commands.ts` (mechanical move of
5
- * the `.action()` body plus its two local helpers). The command name,
6
- * every option and its help text, the ok/fail envelopes and the
4
+ * The action body is `runSpawn` from `peaks-loop-workspace-runtime`; this file
5
+ * owns the host policy (project root, session id, TTL parsing, `Date.now()`),
6
+ * the effects (`./worktree-lease-effects.ts`) and the envelope. The command
7
+ * name, every option and its help text, the ok/fail envelopes and the
7
8
  * `process.exitCode = 1` on failure are unchanged.
8
9
  */
9
10
  import type { Command } from 'commander';
@@ -1,27 +1,24 @@
1
1
  /**
2
2
  * `peaks worktree spawn` — write a lease and run `git worktree add`.
3
3
  *
4
- * Extracted verbatim from `worktree-lease-commands.ts` (mechanical move of
5
- * the `.action()` body plus its two local helpers). The command name,
6
- * every option and its help text, the ok/fail envelopes and the
4
+ * The action body is `runSpawn` from `peaks-loop-workspace-runtime`; this file
5
+ * owns the host policy (project root, session id, TTL parsing, `Date.now()`),
6
+ * the effects (`./worktree-lease-effects.ts`) and the envelope. The command
7
+ * name, every option and its help text, the ok/fail envelopes and the
7
8
  * `process.exitCode = 1` on failure are unchanged.
8
9
  */
9
10
  import { fail, ok } from 'peaks-loop-shared/result';
10
- import { execSync } from 'node:child_process';
11
+ import { defaultStateRoot, runSpawn, ttlForRole } from 'peaks-loop-workspace-runtime';
11
12
  import { addJsonOption, getErrorMessage, printResult } from '../cli-helpers.js';
12
- import { atomicWriteJson } from '../../services/ide/shared/atomic-json.js';
13
13
  import { emitLeaseEvent } from '../../services/observability/observability-service.js';
14
- import { finalizeLease, generateLeaseId, leaseFilePath, ttlForRole, worktreePath } from '../../services/worktree/worktree-lease.js';
15
- import { joinPathSession, resolveProjectRoot, resolveSessionId } from './worktree-lease-session.js';
14
+ import { leaseEffects } from './worktree-lease-effects.js';
15
+ import { resolveProjectRoot, resolveSessionId } from './worktree-lease-session.js';
16
16
  const SPAWN_DESCRIPTION = `Spawn a worktree under .peaks/_runtime/<sid>/worktrees/<leaseId>/ with a managed lease. ` +
17
17
  `The lease is the source of truth for the L2 hook gate (Part 2 of this slice); ` +
18
18
  `until the hook integration ships, sub-agents may still invoke raw \`git worktree add\` ` +
19
19
  `with a current \`peaks worktree auth grant\` token. Default TTL is role-aware ` +
20
20
  `(rd=30m / qa=15m / ui=1h); pass --ttl <ms> to override.`;
21
21
  const SPAWN_TTL_DESCRIPTION = `time-to-live in ms (default role-aware; override with positive number)`;
22
- // Branch names must be safe for git ref-format; the cap keeps a pathological
23
- // rid from producing an unusable ref.
24
- const MAX_BRANCH_NAME_LENGTH = 80;
25
22
  function resolveTtlMs(raw, role) {
26
23
  if (typeof raw !== 'string' || raw.length === 0)
27
24
  return ttlForRole(role);
@@ -30,11 +27,6 @@ function resolveTtlMs(raw, role) {
30
27
  return ttlForRole(role);
31
28
  return parsed;
32
29
  }
33
- function deriveBranch(rid) {
34
- // Branch names must be safe for git ref-format. Strip leading
35
- // `rid-` if present and replace any non-safe chars with `-`.
36
- return rid.replace(/[^A-Za-z0-9._/-]/g, '-').slice(0, MAX_BRANCH_NAME_LENGTH);
37
- }
38
30
  function printSpawnOk(io, options, ctx) {
39
31
  const { lease, sessionId, projectRoot, ttlMs, wtPath, branch } = ctx;
40
32
  printResult(io, ok('worktree.spawn', {
@@ -52,57 +44,57 @@ function printSpawnOk(io, options, ctx) {
52
44
  }, [], []), options.json);
53
45
  }
54
46
  function printSpawnFailed(io, options, error, sessionId) {
55
- printResult(io, fail('worktree.spawn', 'SPAWN_FAILED', getErrorMessage(error), { rid: options.rid, role: options.role, sessionId }, [
47
+ printResult(io, fail('worktree.spawn', 'SPAWN_FAILED', error, { rid: options.rid, role: options.role, sessionId }, [
56
48
  'Verify `git worktree add` succeeded (output above).',
57
49
  'If the lease file was NOT written, retry; the lease directory is .peaks/_runtime/<sid>/worktree-leases/.',
58
50
  'For an existing branch, pass --branch <name> explicitly (the spawn refuses to overwrite an active branch).'
59
51
  ]), options.json);
60
52
  process.exitCode = 1;
61
53
  }
62
- function runSpawn(options, io) {
54
+ function runSpawnAction(options, io) {
63
55
  const projectRoot = resolveProjectRoot(options);
64
56
  const sessionId = resolveSessionId(options, projectRoot);
65
57
  try {
66
- const leaseId = generateLeaseId();
67
- const now = Date.now();
68
- const ttlMs = resolveTtlMs(options.ttl, options.role);
69
- const branch = options.branch ?? deriveBranch(options.rid);
70
- const wtPath = worktreePath(joinPathSession(projectRoot, sessionId), leaseId);
71
- const lease = finalizeLease({
72
- leaseId,
58
+ // `runSpawn` runs `git worktree add` first and writes the lease only once
59
+ // it succeeds, so a failed add never leaves a lease pointing at a
60
+ // worktree that does not exist.
61
+ const result = runSpawn({
62
+ projectRoot,
63
+ stateRoot: defaultStateRoot(projectRoot),
64
+ sessionId,
73
65
  rid: options.rid,
74
66
  role: options.role,
75
- path: wtPath,
76
- branch,
77
- createdAt: now,
78
- expiresAt: now + ttlMs,
79
- purpose: options.purpose
80
- });
81
- // Run `git worktree add` from the project root. The PreToolUse hook
82
- // (Part 2 of this slice) will consult the lease file we just wrote
83
- // and authorize this very `git worktree add`; for Part 1 we still
84
- // require a current `peaks worktree auth grant` token to remain
85
- // consistent with the slice-027 hard gate contract.
86
- execSync(`git worktree add "${wtPath}" -b "${branch}"`, {
87
- cwd: projectRoot,
88
- stdio: 'pipe',
89
- encoding: 'utf8',
90
- windowsHide: true
91
- });
92
- atomicWriteJson(leaseFilePath(joinPathSession(projectRoot, sessionId), leaseId), lease);
67
+ purpose: options.purpose,
68
+ ttlMs: resolveTtlMs(options.ttl, options.role),
69
+ // `exactOptionalPropertyTypes`: absent means "derive from rid", so the
70
+ // key is omitted rather than set to undefined.
71
+ ...(options.branch === undefined ? {} : { branch: options.branch })
72
+ }, leaseEffects(Date.now()));
73
+ if (result.kind === 'failed') {
74
+ printSpawnFailed(io, options, result.error, sessionId);
75
+ return;
76
+ }
77
+ const { lease, ttlMs } = result;
93
78
  // Part 4.A: emit spawn metric (fire-and-forget; never blocks).
94
79
  emitLeaseEvent({
95
80
  sessionId,
96
81
  projectRoot,
97
82
  kind: 'spawn',
98
- leaseId,
83
+ leaseId: lease.leaseId,
99
84
  rid: options.rid,
100
85
  role: options.role
101
86
  });
102
- printSpawnOk(io, options, { lease, sessionId, projectRoot, ttlMs, wtPath, branch });
87
+ printSpawnOk(io, options, {
88
+ lease,
89
+ sessionId,
90
+ projectRoot,
91
+ ttlMs,
92
+ wtPath: lease.path,
93
+ branch: lease.branch
94
+ });
103
95
  }
104
96
  catch (error) {
105
- printSpawnFailed(io, options, error, sessionId);
97
+ printSpawnFailed(io, options, getErrorMessage(error), sessionId);
106
98
  }
107
99
  }
108
100
  export function registerWorktreeLeaseSpawnCommand(auth, io) {
@@ -115,5 +107,5 @@ export function registerWorktreeLeaseSpawnCommand(auth, io) {
115
107
  .option('--ttl <ms>', SPAWN_TTL_DESCRIPTION)
116
108
  .option('--branch <name>', 'git branch name (default: derived from rid)')
117
109
  .option('--session <sid>', 'override session id')
118
- .option('--project <path>', 'project root (default: findProjectRoot(cwd))')).action((options) => runSpawn(options, io));
110
+ .option('--project <path>', 'project root (default: findProjectRoot(cwd))')).action((options) => runSpawnAction(options, io));
119
111
  }
@@ -8,8 +8,8 @@
8
8
  */
9
9
  import { fail, ok } from 'peaks-loop-shared/result';
10
10
  import { existsSync, statSync } from 'node:fs';
11
+ import { isLeaseActive, leaseFilePath } from 'peaks-loop-workspace-runtime';
11
12
  import { addJsonOption, getErrorMessage, printResult } from '../cli-helpers.js';
12
- import { isLeaseActive, leaseFilePath } from '../../services/worktree/worktree-lease.js';
13
13
  import { loadLeaseOrStop } from './worktree-lease-load.js';
14
14
  import { joinPathSession, resolveProjectRoot, resolveSessionId } from './worktree-lease-session.js';
15
15
  const LEASE_STATUS_DESCRIPTION = 'Show one lease in detail: full lease record + computed `live` flag (active AND not past ' +
@@ -4,9 +4,10 @@
4
4
  * Both enumerate the session's lease directory through the pure
5
5
  * `listLeasesSync` helper with the same real-fs bindings, and both render
6
6
  * the same `Malformed lease: <file> (<error>)` warning line per unreadable
7
- * file. Extracted verbatim from `worktree-lease-commands.ts`.
7
+ * file. The helpers now come from `peaks-loop-workspace-runtime`, the one
8
+ * implementation shared with peaks-harness.
8
9
  */
9
- import { type LeaseListResult } from '../../services/worktree/worktree-lease.js';
10
+ import { type LeaseListResult } from 'peaks-loop-workspace-runtime';
10
11
  export interface LeaseStoreSnapshot {
11
12
  storeDir: string;
12
13
  result: LeaseListResult;
@@ -4,10 +4,11 @@
4
4
  * Both enumerate the session's lease directory through the pure
5
5
  * `listLeasesSync` helper with the same real-fs bindings, and both render
6
6
  * the same `Malformed lease: <file> (<error>)` warning line per unreadable
7
- * file. Extracted verbatim from `worktree-lease-commands.ts`.
7
+ * file. The helpers now come from `peaks-loop-workspace-runtime`, the one
8
+ * implementation shared with peaks-harness.
8
9
  */
9
10
  import { existsSync, readdirSync, readFileSync as readFileSyncNode } from 'node:fs';
10
- import { leaseStoreDir, listLeasesSync } from '../../services/worktree/worktree-lease.js';
11
+ import { leaseStoreDir, listLeasesSync } from 'peaks-loop-workspace-runtime';
11
12
  import { joinPathSession } from './worktree-lease-session.js';
12
13
  export function loadLeaseStore(projectRoot, sessionId) {
13
14
  const storeDir = leaseStoreDir(joinPathSession(projectRoot, sessionId));
@@ -12,14 +12,18 @@ import { join, dirname, basename } from 'node:path';
12
12
  import { readdir } from 'node:fs/promises';
13
13
  import { pathExists } from 'peaks-loop-shared/fs';
14
14
  import { NUMBERED_PREFIX_RE, slugifyDescription } from '../../shared/incrementing-number.js';
15
+ import { tryGetSessionDir } from '../session/getSessionDir.js';
15
16
  export function resolvePrerequisitePath(prerequisite, requestId) {
16
17
  return prerequisite.relativePath.replace('<rid>', requestId);
17
18
  }
18
19
  export function sessionRootsFor(projectRoot, sessionId) {
19
20
  if (sessionId === undefined)
20
21
  return { canonical: null, legacy: null };
22
+ // A bad id resolves to "no canonical tier" rather than a hand-rolled path:
23
+ // the resolver below already treats an absent tier as "probe the next one".
24
+ const canonical = tryGetSessionDir(projectRoot, sessionId);
21
25
  return {
22
- canonical: join(projectRoot, '.peaks', '_runtime', sessionId),
26
+ canonical: canonical.ok ? canonical.dir : null,
23
27
  legacy: join(projectRoot, '.peaks', sessionId)
24
28
  };
25
29
  }
@@ -14,6 +14,7 @@
14
14
  */
15
15
  import { readFileSync } from 'node:fs';
16
16
  import { join } from 'node:path';
17
+ import { tryGetSessionDir } from '../../session/getSessionDir.js';
17
18
  const FLUFF_GREETINGS = [
18
19
  /\b你好[!!。,,.]?\s*$/m,
19
20
  /^\s*你好[!!。,,.]?\s*$/m,
@@ -85,7 +86,10 @@ export function lintNoClosingPrompt(skill) {
85
86
  * empty array (the runtime check is elsewhere).
86
87
  */
87
88
  export function lintStatusHeader(projectRoot, sessionId) {
88
- const logPath = join(projectRoot, '.peaks', '_runtime', sessionId, 'session.log');
89
+ const resolved = tryGetSessionDir(projectRoot, sessionId);
90
+ if (!resolved.ok)
91
+ return [];
92
+ const logPath = join(resolved.dir, 'session.log');
89
93
  let body;
90
94
  try {
91
95
  body = readFileSync(logPath, 'utf8');
@@ -27,17 +27,17 @@
27
27
  */
28
28
  import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
29
29
  import { join } from 'node:path';
30
+ import { defaultStateRoot } from 'peaks-loop-workspace-runtime';
31
+ import { tryGetSessionDir } from '../../session/getSessionDir.js';
30
32
  const COVERAGE_TARGET = /100%\s*coverage target[^\n]*testable files/i;
31
33
  const NO_PADDING = /must not write coverage-padding tests/i;
32
- /** The artifact whose absence makes an RD→QA handoff invalid. */
33
- const RD_ARTIFACT_RELATIVE = '.peaks/_runtime';
34
34
  /**
35
35
  * Resolve the bound session id from `.peaks/_runtime/session.json`. Both
36
36
  * key spellings are accepted: the file has shipped as `peakSessionId` and
37
37
  * as `sessionId`, and reading only one silently disables the check.
38
38
  */
39
39
  function resolveSessionBinding(projectRoot) {
40
- const sessionJsonPath = join(projectRoot, '.peaks', '_runtime', 'session.json');
40
+ const sessionJsonPath = join(defaultStateRoot(projectRoot), 'session.json');
41
41
  if (!existsSync(sessionJsonPath)) {
42
42
  return { sessionId: null, reason: 'no .peaks/_runtime/session.json' };
43
43
  }
@@ -103,7 +103,12 @@ export function lintRdHandoffContract(skill, projectRoot) {
103
103
  const binding = resolveSessionBinding(projectRoot);
104
104
  if (binding.sessionId === null)
105
105
  return [];
106
- const requestsDir = join(projectRoot, RD_ARTIFACT_RELATIVE, binding.sessionId, 'rd', 'requests');
106
+ // An id that names no session directory is the same soft-pass as no binding:
107
+ // this enforcer never refuses on a value it cannot resolve.
108
+ const sessionDir = tryGetSessionDir(projectRoot, binding.sessionId);
109
+ if (!sessionDir.ok)
110
+ return [];
111
+ const requestsDir = join(sessionDir.dir, 'rd', 'requests');
107
112
  const artifactCount = countNonEmptyArtifacts(requestsDir);
108
113
  if (artifactCount > 0)
109
114
  return [];
@@ -22,6 +22,7 @@
22
22
  */
23
23
  import { join } from 'node:path';
24
24
  import { handoffRelativePath } from '../prd/handoff-service.js';
25
+ import { tryGetSessionDir } from '../session/getSessionDir.js';
25
26
  /** Per-role names, so the two arms differ by data rather than by copy-paste. */
26
27
  const ROLE = {
27
28
  security: { skill: 'peaks-security-audit', validator: 'isSecurityAuditEnvelope' },
@@ -54,6 +55,20 @@ function printable(value) {
54
55
  }
55
56
  return rendered;
56
57
  }
58
+ /**
59
+ * The session's `prd/` directory, as text the refusal can print.
60
+ *
61
+ * The TOTAL entry, deliberately: this module's contract is that a hostile
62
+ * `--sid` is RENDERED inert, never thrown on (see the a11y block in
63
+ * `handoff-missing-refusal.test.ts`), and `sid` is guarded only by
64
+ * `isUnsafePathInput`, which admits NUL and C0/C1 controls. An id the seam
65
+ * refuses names no directory, so its reason takes the directory's place and is
66
+ * sanitised by `printable` at the interpolation like every other printed value.
67
+ */
68
+ function sessionPrdDir(projectRoot, sessionId) {
69
+ const resolved = tryGetSessionDir(projectRoot, sessionId);
70
+ return resolved.ok ? join(resolved.dir, 'prd') : resolved.reason;
71
+ }
57
72
  /**
58
73
  * Build the refusal payload for a `handoff-missing` detect result.
59
74
  *
@@ -74,7 +89,7 @@ export function handoffMissingRefusal(opts) {
74
89
  // runs on exactly the bytes `resolveHandoffPath` would probe. Each value is
75
90
  // sanitised at the point it is interpolated, below — not here — so the render
76
91
  // is the only thing that changes.
77
- const prdDir = join(opts.projectRoot, '.peaks', '_runtime', opts.sessionId, 'prd');
92
+ const prdDir = sessionPrdDir(opts.projectRoot, opts.sessionId);
78
93
  // The path the creating command WRITES. With a rid that is the slice-scoped
79
94
  // capsule; `resolveHandoffPath` already ran `handoffRelativePath` for these
80
95
  // same ids on the way in, so this join cannot throw where that one did not.