peaks-loop 4.1.26 → 4.2.1

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 (157) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +160 -0
  3. package/contracts/readonly-argv-whitelist.json +116 -0
  4. package/dist/cli/commands/code-auto-compact-command.js +15 -3
  5. package/dist/cli/commands/core/session-info-command.js +3 -4
  6. package/dist/cli/commands/core/skill-presence-housekeeping-commands.js +7 -1
  7. package/dist/cli/commands/dashboard-long-run.js +2 -1
  8. package/dist/cli/commands/doctor/invoke-from-code.js +6 -1
  9. package/dist/cli/commands/job-state-root.js +4 -2
  10. package/dist/cli/commands/lease-metrics-commands-support.js +2 -1
  11. package/dist/cli/commands/loop-eval-capture-index.js +2 -1
  12. package/dist/cli/commands/loop-eval-eval-command.js +2 -1
  13. package/dist/cli/commands/mut-commands-helpers.d.ts +9 -28
  14. package/dist/cli/commands/mut-commands-helpers.js +53 -80
  15. package/dist/cli/commands/mut-failure-diagnostic.d.ts +48 -0
  16. package/dist/cli/commands/mut-failure-diagnostic.js +147 -0
  17. package/dist/cli/commands/outer-cache-commands.js +3 -2
  18. package/dist/cli/commands/playwright-session-store.js +5 -2
  19. package/dist/cli/commands/project-context-command.js +7 -2
  20. package/dist/cli/commands/qa-archive-screenshots-command.js +2 -1
  21. package/dist/cli/commands/request-transition-preflight.js +2 -2
  22. package/dist/cli/commands/slice-decompose-artifacts.js +10 -2
  23. package/dist/cli/commands/verdict-aggregate-command.js +4 -3
  24. package/dist/cli/commands/workspace/init-actions.js +5 -0
  25. package/dist/cli/commands/workspace/init-context.js +1 -0
  26. package/dist/cli/commands/worktree-lease-effects.d.ts +13 -0
  27. package/dist/cli/commands/worktree-lease-effects.js +23 -0
  28. package/dist/cli/commands/worktree-lease-gc-command.d.ts +3 -4
  29. package/dist/cli/commands/worktree-lease-gc-command.js +59 -58
  30. package/dist/cli/commands/worktree-lease-git.d.ts +13 -18
  31. package/dist/cli/commands/worktree-lease-git.js +21 -44
  32. package/dist/cli/commands/worktree-lease-list-command.js +1 -1
  33. package/dist/cli/commands/worktree-lease-load.d.ts +19 -7
  34. package/dist/cli/commands/worktree-lease-load.js +37 -9
  35. package/dist/cli/commands/worktree-lease-release-command.d.ts +4 -5
  36. package/dist/cli/commands/worktree-lease-release-command.js +60 -47
  37. package/dist/cli/commands/worktree-lease-renew-command.d.ts +5 -4
  38. package/dist/cli/commands/worktree-lease-renew-command.js +36 -32
  39. package/dist/cli/commands/worktree-lease-session.d.ts +7 -5
  40. package/dist/cli/commands/worktree-lease-session.js +9 -6
  41. package/dist/cli/commands/worktree-lease-spawn-command.d.ts +4 -3
  42. package/dist/cli/commands/worktree-lease-spawn-command.js +38 -46
  43. package/dist/cli/commands/worktree-lease-status-command.js +1 -1
  44. package/dist/cli/commands/worktree-lease-store.d.ts +3 -2
  45. package/dist/cli/commands/worktree-lease-store.js +3 -2
  46. package/dist/services/artifacts/prerequisite-path-resolver.js +5 -1
  47. package/dist/services/audit/enforcers/lint-output-style.js +5 -1
  48. package/dist/services/audit/enforcers/lint-rd-handoff-coverage.js +9 -4
  49. package/dist/services/audit-independent/handoff-missing-refusal.js +16 -1
  50. package/dist/services/audit-independent/judged-declaration-check.js +5 -1
  51. package/dist/services/audit-independent/perf-audit-service.d.ts +2 -4
  52. package/dist/services/audit-independent/perf-audit-service.js +4 -5
  53. package/dist/services/audit-independent/security-audit-artifact.js +5 -1
  54. package/dist/services/capability-audit-service/runner.js +4 -1
  55. package/dist/services/capability-baseline/store.js +2 -1
  56. package/dist/services/capability-guard-runner/contracts/J05.js +4 -2
  57. package/dist/services/capability-guard-runner/contracts/J12.js +2 -2
  58. package/dist/services/code/auto-compact-artifacts.js +42 -10
  59. package/dist/services/code/auto-compact-checkpoint-content.d.ts +49 -0
  60. package/dist/services/code/auto-compact-checkpoint-content.js +157 -0
  61. package/dist/services/code/auto-compact-envelopes.d.ts +11 -2
  62. package/dist/services/code/auto-compact-envelopes.js +18 -4
  63. package/dist/services/code/auto-compact-orchestrator.js +1 -1
  64. package/dist/services/code/emit-handoff.js +8 -1
  65. package/dist/services/code/job-shape-decision.js +13 -2
  66. package/dist/services/code/job-shape-provisional.js +9 -1
  67. package/dist/services/code/post-compact-detector.js +9 -1
  68. package/dist/services/code/step-08-session-readers.js +14 -5
  69. package/dist/services/compact/request-transition-hook.js +6 -1
  70. package/dist/services/compact/suggest-service.js +8 -1
  71. package/dist/services/context/post-compact-reinjection.js +15 -14
  72. package/dist/services/context/spillover-store.js +2 -1
  73. package/dist/services/dispatch/contract-store.d.ts +11 -4
  74. package/dist/services/dispatch/contract-store.js +21 -8
  75. package/dist/services/doctor/doctor-service/checks/workspace-layout.js +8 -3
  76. package/dist/services/doctor/doctor-service/index.js +2 -1
  77. package/dist/services/final-review/final-review-evidence-collect.js +5 -1
  78. package/dist/services/fresh-context/fresh-context-block.js +5 -1
  79. package/dist/services/hooks/auto-compact-hook-install.d.ts +13 -3
  80. package/dist/services/hooks/auto-compact-hook-install.js +13 -3
  81. package/dist/services/hooks/worktree-authorization-gate.d.ts +1 -1
  82. package/dist/services/hooks/worktree-authorization-gate.js +14 -11
  83. package/dist/services/loop/evaluator-dispatcher.js +7 -7
  84. package/dist/services/loop/monotonic-runner.js +2 -1
  85. package/dist/services/loop/spec-service.js +10 -9
  86. package/dist/services/mcp/context-tool.d.ts +3 -0
  87. package/dist/services/mcp/context-tool.js +135 -0
  88. package/dist/services/mcp/surface.js +7 -1
  89. package/dist/services/mcp/tools.js +3 -1
  90. package/dist/services/memory/project-context-service.d.ts +10 -1
  91. package/dist/services/memory/project-context-service.js +13 -6
  92. package/dist/services/observability/jsonl-store.js +4 -1
  93. package/dist/services/polyrepo/polyrepo-dispatcher.js +5 -1
  94. package/dist/services/prd/prd-blocks-checker.js +12 -6
  95. package/dist/services/prd/project-scan-body-tables.d.ts +33 -0
  96. package/dist/services/prd/project-scan-body-tables.js +185 -0
  97. package/dist/services/prd/project-scan-bootstrap-service.d.ts +16 -3
  98. package/dist/services/prd/project-scan-bootstrap-service.js +127 -231
  99. package/dist/services/prd/project-scan-content.d.ts +24 -0
  100. package/dist/services/prd/project-scan-content.js +207 -0
  101. package/dist/services/prd/project-scan-existing-state.d.ts +22 -0
  102. package/dist/services/prd/project-scan-existing-state.js +61 -0
  103. package/dist/services/prd/project-scan-field-refresh.d.ts +87 -0
  104. package/dist/services/prd/project-scan-field-refresh.js +217 -0
  105. package/dist/services/prd/project-scan-frontmatter.d.ts +32 -0
  106. package/dist/services/prd/project-scan-frontmatter.js +34 -0
  107. package/dist/services/prd/project-scan-library-versions.d.ts +60 -0
  108. package/dist/services/prd/project-scan-library-versions.js +135 -0
  109. package/dist/services/prd/project-scan-techstack.d.ts +34 -0
  110. package/dist/services/prd/project-scan-techstack.js +167 -0
  111. package/dist/services/reviewer/reviewer-artifacts.js +2 -1
  112. package/dist/services/sc/sc-service.js +8 -8
  113. package/dist/services/scan/api-diff-recorded.d.ts +2 -3
  114. package/dist/services/scan/api-diff-recorded.js +5 -5
  115. package/dist/services/session/binding-status-service.js +2 -1
  116. package/dist/services/session/binding-store.js +6 -7
  117. package/dist/services/session/caller-binding-service.js +5 -2
  118. package/dist/services/session/getSessionDir.d.ts +4 -0
  119. package/dist/services/session/getSessionDir.js +38 -13
  120. package/dist/services/session/session-binding-bridge.d.ts +3 -6
  121. package/dist/services/session/session-binding-bridge.js +13 -13
  122. package/dist/services/session/session-checkpoint-service.js +22 -3
  123. package/dist/services/session/session-manager.js +16 -20
  124. package/dist/services/skills/presence-lease-resolver.js +3 -2
  125. package/dist/services/skills/presence-lease-service.js +7 -15
  126. package/dist/services/skills/presence-lease-store.d.ts +26 -0
  127. package/dist/services/skills/presence-lease-store.js +60 -5
  128. package/dist/services/skills/skill-presence-service.js +13 -20
  129. package/dist/services/skills/skill-statusline-model.js +7 -2
  130. package/dist/services/slice/slice-archive-service.js +4 -1
  131. package/dist/services/standards/missing-standards-detector.js +2 -1
  132. package/dist/services/test-cache/test-cache-service.js +2 -1
  133. package/dist/services/workflow/artifact-paths.js +6 -2
  134. package/dist/services/workflow/pipeline-verify-gate-support.d.ts +1 -1
  135. package/dist/services/workflow/pipeline-verify-gate-support.js +23 -11
  136. package/dist/services/workflow/workflow-graph-store-helpers.js +12 -3
  137. package/dist/services/workflow/workflow-state-store.js +11 -4
  138. package/dist/services/workspace/migrate-1-4-1-service.js +2 -1
  139. package/dist/services/workspace/reconcile-migrate.js +2 -2
  140. package/dist/services/workspace/reconcile-service.d.ts +4 -6
  141. package/dist/services/workspace/reconcile-service.js +11 -11
  142. package/dist/services/workspace/workspace-service.js +5 -5
  143. package/dist/services/worktree/dispatch-provenance.d.ts +1 -1
  144. package/dist/services/worktree/dispatch-provenance.js +9 -2
  145. package/dist/services/worktree/host-worktree-reconciler.d.ts +1 -1
  146. package/dist/services/worktree/host-worktree-reconciler.js +5 -3
  147. package/dist/shared/runtime-root.js +6 -1
  148. package/package.json +6 -5
  149. package/skills/peaks-code/SKILL.md +1 -1
  150. package/skills/peaks-code/references/project-scan-checklist.md +3 -1
  151. package/skills/peaks-mut/SKILL.md +6 -2
  152. package/dist/services/worktree/git-worktree-parser.d.ts +0 -8
  153. package/dist/services/worktree/git-worktree-parser.js +0 -55
  154. package/dist/services/worktree/worktree-lease-types.d.ts +0 -52
  155. package/dist/services/worktree/worktree-lease-types.js +0 -9
  156. package/dist/services/worktree/worktree-lease.d.ts +0 -116
  157. package/dist/services/worktree/worktree-lease.js +0 -252
@@ -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.
@@ -20,6 +20,7 @@
20
20
  import { existsSync, readFileSync } from 'node:fs';
21
21
  import { execFileSync } from 'node:child_process';
22
22
  import { join } from 'node:path';
23
+ import { tryGetSessionDir } from '../session/getSessionDir.js';
23
24
  import { JUDGED_HEADING, parseJudgedDeclaration, sha256OfFile } from './judged-declaration.js';
24
25
  /**
25
26
  * What a refusal means, partitioned by THE ONE QUESTION its codes answer:
@@ -92,7 +93,10 @@ export function securityArtifactTiers(rid) {
92
93
  ];
93
94
  }
94
95
  export function resolveSecurityArtifact(projectRoot, sessionId, rid) {
95
- const root = join(projectRoot, '.peaks', '_runtime', sessionId);
96
+ const resolved = tryGetSessionDir(projectRoot, sessionId);
97
+ if (!resolved.ok)
98
+ return null;
99
+ const root = resolved.dir;
96
100
  for (const relative of securityArtifactTiers(rid)) {
97
101
  const absolute = join(root, ...relative.split('/'));
98
102
  if (existsSync(absolute))
@@ -129,11 +129,9 @@ export declare function renderPerfAuditArtifact(env: PerfAuditEnvelope, opts: {
129
129
  verdict: PerfAuditVerdict;
130
130
  };
131
131
  /**
132
- * Write the rendered audit artifact to
133
- * `.peaks/_runtime/<sid>/audit/perf-<rid>.md`.
132
+ * Write the rendered audit artifact to `.peaks/_runtime/<sid>/audit/perf-<rid>.md`.
134
133
  *
135
- * Atomic write (tmp + rename) to avoid partial writes on crash.
136
- * Returns the absolute path on success.
134
+ * Atomic write (tmp + rename); returns the absolute path on success.
137
135
  */
138
136
  export declare function writePerfAuditArtifact(projectRoot: string, sessionId: string, rid: string, body: string): string;
139
137
  /**
@@ -25,6 +25,7 @@ import { join, resolve, isAbsolute } from 'node:path';
25
25
  import { createHash } from 'node:crypto';
26
26
  import { REQUEST_ID_PATTERN } from '../artifacts/request-artifact-service.js';
27
27
  import { resolveHandoffPath } from '../prd/handoff-service.js';
28
+ import { getSessionDir } from '../session/getSessionDir.js';
28
29
  import { handoffMissingRefusal } from './handoff-missing-refusal.js';
29
30
  /**
30
31
  * Validate a raw value as a PerfAuditEnvelope. Mirrors the
@@ -282,11 +283,9 @@ export function renderPerfAuditArtifact(env, opts) {
282
283
  };
283
284
  }
284
285
  /**
285
- * Write the rendered audit artifact to
286
- * `.peaks/_runtime/<sid>/audit/perf-<rid>.md`.
286
+ * Write the rendered audit artifact to `.peaks/_runtime/<sid>/audit/perf-<rid>.md`.
287
287
  *
288
- * Atomic write (tmp + rename) to avoid partial writes on crash.
289
- * Returns the absolute path on success.
288
+ * Atomic write (tmp + rename); returns the absolute path on success.
290
289
  */
291
290
  export function writePerfAuditArtifact(projectRoot, sessionId, rid, body) {
292
291
  // The rid is a filename below, and the write is tmp+rename, so an
@@ -295,7 +294,7 @@ export function writePerfAuditArtifact(projectRoot, sessionId, rid, body) {
295
294
  if (!REQUEST_ID_PATTERN.test(rid)) {
296
295
  throw new Error(`Invalid request id: ${rid} (expected letters, digits, dots, underscores, or dashes)`);
297
296
  }
298
- const targetDir = join(projectRoot, '.peaks', '_runtime', sessionId, 'audit');
297
+ const targetDir = join(getSessionDir(projectRoot, sessionId), 'audit');
299
298
  mkdirSync(targetDir, { recursive: true });
300
299
  const targetPath = join(targetDir, `perf-${rid}.md`);
301
300
  // tmp + rename for atomicity
@@ -6,6 +6,7 @@
6
6
  import { mkdirSync, renameSync, writeFileSync } from 'node:fs';
7
7
  import { join } from 'node:path';
8
8
  import { REQUEST_ID_PATTERN } from '../artifacts/request-artifact-service.js';
9
+ import { getSessionDir } from '../session/getSessionDir.js';
9
10
  /**
10
11
  * Render a SecurityAuditEnvelope to the canonical audit artifact body
11
12
  * (markdown). Produce a markdown body with all required sections, ready to
@@ -78,7 +79,10 @@ export function writeSecurityAuditArtifact(projectRoot, sessionId, rid, body) {
78
79
  if (!REQUEST_ID_PATTERN.test(rid)) {
79
80
  throw new Error(`Invalid request id: ${rid} (expected letters, digits, dots, underscores, or dashes)`);
80
81
  }
81
- const targetDir = join(projectRoot, '.peaks', '_runtime', sessionId, 'audit');
82
+ // This is a WRITE target and is one segment below the session dir, so it
83
+ // takes the throwing entry: a bad sid refuses here the same way a bad rid
84
+ // does above, instead of composing a path outside the session.
85
+ const targetDir = join(getSessionDir(projectRoot, sessionId), 'audit');
82
86
  mkdirSync(targetDir, { recursive: true });
83
87
  const targetPath = join(targetDir, `security-${rid}.md`);
84
88
  // tmp + rename for atomicity
@@ -1,5 +1,6 @@
1
1
  import { mkdirSync, writeFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
+ import { getSessionDir } from '../session/getSessionDir.js';
3
4
  import { crossCheck } from './cross-check.js';
4
5
  import { runIndependentCheck } from './independent-checker.js';
5
6
  function scoreFor(status) {
@@ -102,7 +103,9 @@ export async function runAudit(input) {
102
103
  findings: check === null ? null : check.findings,
103
104
  coverage: check === null ? null : check.coverage
104
105
  };
105
- const dir = join(input.projectRoot, '.peaks', '_runtime', input.sessionId, 'capability-audit');
106
+ // Write target: the throwing entry, so a refused sid cannot produce a
107
+ // directory outside the session.
108
+ const dir = join(getSessionDir(input.projectRoot, input.sessionId), 'capability-audit');
106
109
  mkdirSync(dir, { recursive: true });
107
110
  writeFileSync(join(dir, `${auditId}.json`), JSON.stringify(out, null, 2));
108
111
  return out;
@@ -2,10 +2,11 @@
2
2
  import { createHash } from 'node:crypto';
3
3
  import { existsSync, mkdirSync, readFileSync, writeFileSync, copyFileSync } from 'node:fs';
4
4
  import { dirname, join } from 'node:path';
5
+ import { getSessionDir } from '../session/getSessionDir.js';
5
6
  const CURRENT_DIR = (root) => join(root, 'openspec', 'baselines', 'current');
6
7
  const FILE_PATH = (root) => join(CURRENT_DIR(root), 'capability-baseline.json');
7
8
  const LOCK_PATH = (root) => join(CURRENT_DIR(root), 'capability-baseline.lock');
8
- const POINTER = (root, sessionId) => join(root, '.peaks', '_runtime', sessionId, 'baselines', 'current.json');
9
+ const POINTER = (root, sessionId) => join(getSessionDir(root, sessionId), 'baselines', 'current.json');
9
10
  function hashFor(file) {
10
11
  const stripped = {
11
12
  schemaVersion: file.schemaVersion,
@@ -2,6 +2,7 @@ import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
2
2
  import { tmpdir } from 'node:os';
3
3
  import { join } from 'node:path';
4
4
  import { IncompleteFinalReviewError, MAX_EVIDENCE_BYTES_PER_FILE, outputBudgetForEvidence, prepareFinalReview, resolveOutputBudget, undeliverableDimensions } from '../../final-review/final-review-service.js';
5
+ import { getSessionDir } from '../../session/getSessionDir.js';
5
6
  import { combineProbes, fail, missingSourceFiles, pass, probe, requireBaselineRow } from './_shared.js';
6
7
  /** The four dimensions the frozen baseline names. The 5th is NOT one of them. */
7
8
  const FOUR_DIMENSIONS = [
@@ -84,8 +85,9 @@ async function probePrepareFinalReview() {
84
85
  const root = mkdtempSync(join(tmpdir(), 'cbl-J05-'));
85
86
  try {
86
87
  const sessionId = 'guard-J05';
87
- mkdirSync(join(root, '.peaks', '_runtime', sessionId, 'audit-goal'), { recursive: true });
88
- writeFileSync(join(root, '.peaks', '_runtime', sessionId, 'audit-goal', 'J05-fixture.json'), JSON.stringify({ successCriteria: ['c'] }));
88
+ const fixtureDir = join(getSessionDir(root, sessionId), 'audit-goal');
89
+ mkdirSync(fixtureDir, { recursive: true });
90
+ writeFileSync(join(fixtureDir, 'J05-fixture.json'), JSON.stringify({ successCriteria: ['c'] }));
89
91
  const opts = { projectRoot: root, sessionId };
90
92
  let rejected = false;
91
93
  let rejectName = 'none';