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,116 +0,0 @@
1
- /**
2
- * worktree-lease — pure-function lease store for `peaks worktree spawn`.
3
- *
4
- * governance complement to Layer 3 (`permissions.deny` for the superpowers
5
- * chain) and Layer 1 (sub-agent dispatch prompt refusal). Together the
6
- * three layers close the superpowers-chain jailbreak that previously
7
- * bypassed peaks-loop's worktree posture.
8
- *
9
- * The store is a pure function module: every helper takes the lease
10
- * directory path as an argument and returns structured data. Atomic
11
- * filesystem writes happen at the call site (CLI command), keeping the
12
- * helpers trivially testable. The CLI surface lives in
13
- *
14
- * Why a separate lease (vs reusing `peaks worktree auth grant`):
15
- * - `auth grant` is a single-shot, short-lived token file consulted by
16
- * the PreToolUse hook BEFORE `git worktree add` runs. It answers
17
- * "is the LLM allowed to do this right now?"
18
- * - `lease` is a long-lived lifecycle object that owns the worktree
19
- * path, branch, expiry, and consumption log. It answers
20
- * "what worktrees does this session own, and which are still alive?"
21
- * The two coexist: `spawn` writes a lease; the lease's existence
22
- * implicitly authorizes worktree operations on its path (the hook
23
- * integration is Part 2 of this slice).
24
- */
25
- import type { LeaseListResult, WorktreeLease, WorktreeLeaseDraft } from './worktree-lease-types.js';
26
- export type { LeaseListResult, LeaseReadError, WorktreeLease, WorktreeLeaseDraft, WorktreeLeaseStatus } from './worktree-lease-types.js';
27
- export declare const DEFAULT_TTL_BY_ROLE: Readonly<Record<string, number>>;
28
- export declare const DEFAULT_TTL_MS: number | undefined;
29
- /**
30
- * Compose a deterministic lease path under the per-session runtime dir.
31
- * The function is pure: same inputs → same output. The caller passes
32
- * `<sessionId>` (NOT a bare `<sid>` per the 2.7.1 single-scope-axis rule).
33
- *
34
- * Path layout:
35
- * .peaks/_runtime/<sessionId>/worktree-leases/<leaseId>.json
36
- *
37
- * The `worktree-leases/` directory is gitignored per the .peaks/_runtime/
38
- * rule (committed in .gitignore for all runtime artifacts).
39
- */
40
- export declare function leaseStoreDir(sessionRuntimeDir: string): string;
41
- export declare function leaseFilePath(sessionRuntimeDir: string, leaseId: string): string;
42
- /**
43
- * Compose the absolute worktree path (the `git worktree add <path>` target).
44
- * Sits adjacent to the lease file under the same runtime dir.
45
- */
46
- export declare function worktreePath(sessionRuntimeDir: string, leaseId: string): string;
47
- /**
48
- * Generate a 16-hex lease id (8 random bytes, hex-encoded). The id is
49
- * unique enough for the per-session scope; collisions across sessions
50
- * are irrelevant because each session has its own lease directory.
51
- */
52
- export declare function generateLeaseId(): string;
53
- /**
54
- * Compute the TTL ms for a role, falling back to DEFAULT_TTL_MS for
55
- * unknown roles. The CLI overrides with `--ttl <ms>` when the user
56
- * passes a positive value.
57
- */
58
- export declare function ttlForRole(role: string): number;
59
- /**
60
- * Pure: produce a fresh `WorktreeLease` from a draft + status.
61
- * `status` defaults to `'active'`; `consumedBySubAgents` defaults to [].
62
- * Used by the CLI's atomicWriteJson call.
63
- */
64
- export declare function finalizeLease(draft: WorktreeLeaseDraft): WorktreeLease;
65
- /** Pure: lease status transitions to 'released'. Returns a new lease. */
66
- export declare function markReleased(lease: WorktreeLease): WorktreeLease;
67
- /** Pure: lease status transitions to 'expired'. Returns a new lease. */
68
- export declare function markExpired(lease: WorktreeLease): WorktreeLease;
69
- /** Pure: lease status transitions to 'gc'. Returns a new lease. */
70
- export declare function markGc(lease: WorktreeLease): WorktreeLease;
71
- /** Pure: append a sub-agent batch / dispatch id to the consumption log. Returns a new lease. */
72
- export declare function recordConsumption(lease: WorktreeLease, subAgentId: string): WorktreeLease;
73
- /**
74
- * Pure: is the lease still active (status === 'active' AND not past expiry).
75
- * Expired leases are NOT auto-released; the gc CLI is the only path that
76
- * transitions them to 'gc'. Until then, the on-disk state stays 'active'
77
- * but `isLeaseActive` returns false so consumers skip the lease.
78
- */
79
- export declare function isLeaseActive(lease: WorktreeLease, now?: number): boolean;
80
- /**
81
- * List every lease file under the session's lease store dir.
82
- *
83
- * Pure with respect to its inputs: it does NOT sort or filter, and it
84
- * does NOT mark anything expired. Callers (the `list` CLI) apply their
85
- * own sort/filter and run `markExpired` lazily.
86
- */
87
- export declare function listLeasesSync(storeDir: string, fs: {
88
- readdir: (path: string) => ReadonlyArray<string>;
89
- readFile: (path: string) => string;
90
- existsSync: (path: string) => boolean;
91
- }): LeaseListResult;
92
- /**
93
- * Pure: a lease is eligible for `gc` if its status is one of {released,
94
- * expired} AND its worktree path is no longer attached to git (`git
95
- * worktree list` would not include it). The CLI re-checks with git and
96
- * uses this helper as a coarse pre-filter.
97
- */
98
- export declare function isLeaseGcEligible(lease: WorktreeLease, now?: number): boolean;
99
- /**
100
- * Pure: derive a new lease from an existing one with an extended
101
- * `expiresAt`. Other fields are preserved. The CLI writes the new lease
102
- * atomically. Used by `peaks worktree renew --lease-id <id> --ttl <ms>`.
103
- */
104
- export declare function renewLease(lease: WorktreeLease, newExpiresAt: number): WorktreeLease;
105
- /**
106
- * Pure: serialize a lease to JSON with stable field order (deterministic
107
- * output for diff-friendly audit logs). The CLI passes the result to
108
- * `atomicWriteJson`. The function does NOT mutate the input.
109
- */
110
- export declare function serializeLease(lease: WorktreeLease): string;
111
- /**
112
- * Pure: deserialize a lease from JSON. Throws on malformed input — the
113
- * CLI catches and returns a `LEASE_FILE_INVALID` envelope (mirroring the
114
- * `peaks worktree auth` FILE_INVALID convention).
115
- */
116
- export declare function deserializeLease(raw: string): WorktreeLease;
@@ -1,252 +0,0 @@
1
- /**
2
- * worktree-lease — pure-function lease store for `peaks worktree spawn`.
3
- *
4
- * governance complement to Layer 3 (`permissions.deny` for the superpowers
5
- * chain) and Layer 1 (sub-agent dispatch prompt refusal). Together the
6
- * three layers close the superpowers-chain jailbreak that previously
7
- * bypassed peaks-loop's worktree posture.
8
- *
9
- * The store is a pure function module: every helper takes the lease
10
- * directory path as an argument and returns structured data. Atomic
11
- * filesystem writes happen at the call site (CLI command), keeping the
12
- * helpers trivially testable. The CLI surface lives in
13
- *
14
- * Why a separate lease (vs reusing `peaks worktree auth grant`):
15
- * - `auth grant` is a single-shot, short-lived token file consulted by
16
- * the PreToolUse hook BEFORE `git worktree add` runs. It answers
17
- * "is the LLM allowed to do this right now?"
18
- * - `lease` is a long-lived lifecycle object that owns the worktree
19
- * path, branch, expiry, and consumption log. It answers
20
- * "what worktrees does this session own, and which are still alive?"
21
- * The two coexist: `spawn` writes a lease; the lease's existence
22
- * implicitly authorizes worktree operations on its path (the hook
23
- * integration is Part 2 of this slice).
24
- */
25
- import { randomBytes } from 'node:crypto';
26
- import { posix as path } from 'node:path';
27
- import { normalizePath } from '../../shared/path-utils.js';
28
- /**
29
- * Per-role default TTL. Sub-agent dispatch duration varies by role:
30
- * - rd (long planning + impl) → 30 min
31
- * - qa (test design + browser validation) → 15 min
32
- * - ui (high-fidelity prototype iteration) → 1 h
33
- * - txt (handoff capsule, no worktree expected) → n/a (no worktree)
34
- * - general-purpose / unknown → 30 min (rd-like)
35
- *
36
- * Users MAY override with `--ttl <duration>` (e.g. `--ttl 4h`).
37
- */
38
- // PRD-002b slice 2 — extract lease-TTL primitives (same shape as
39
- // container-lease.ts / vm-lease.ts). See config diff comment.
40
- const MINUTES_PER_HOUR = 60;
41
- const MS_PER_MINUTE = MINUTES_PER_HOUR * 1_000;
42
- const LEASE_RD_TTL_MINUTES = 30;
43
- const LEASE_QA_TTL_MINUTES = 15;
44
- const LEASE_UI_TTL_MINUTES = MINUTES_PER_HOUR;
45
- const LEASE_SC_TTL_MINUTES = 30;
46
- const LEASE_PRD_TTL_MINUTES = 15;
47
- const LEASE_GENERAL_TTL_MINUTES = 30;
48
- const LEASE_ID_RANDOM_BYTES = 8;
49
- export const DEFAULT_TTL_BY_ROLE = Object.freeze({
50
- rd: LEASE_RD_TTL_MINUTES * MS_PER_MINUTE,
51
- qa: LEASE_QA_TTL_MINUTES * MS_PER_MINUTE,
52
- ui: LEASE_UI_TTL_MINUTES * MS_PER_MINUTE,
53
- sc: LEASE_SC_TTL_MINUTES * MS_PER_MINUTE,
54
- prd: LEASE_PRD_TTL_MINUTES * MS_PER_MINUTE,
55
- general: LEASE_GENERAL_TTL_MINUTES * MS_PER_MINUTE
56
- });
57
- export const DEFAULT_TTL_MS = DEFAULT_TTL_BY_ROLE.rd;
58
- /**
59
- * Compose a deterministic lease path under the per-session runtime dir.
60
- * The function is pure: same inputs → same output. The caller passes
61
- * `<sessionId>` (NOT a bare `<sid>` per the 2.7.1 single-scope-axis rule).
62
- *
63
- * Path layout:
64
- * .peaks/_runtime/<sessionId>/worktree-leases/<leaseId>.json
65
- *
66
- * The `worktree-leases/` directory is gitignored per the .peaks/_runtime/
67
- * rule (committed in .gitignore for all runtime artifacts).
68
- */
69
- export function leaseStoreDir(sessionRuntimeDir) {
70
- return joinPath(sessionRuntimeDir, 'worktree-leases');
71
- }
72
- export function leaseFilePath(sessionRuntimeDir, leaseId) {
73
- return joinPath(leaseStoreDir(sessionRuntimeDir), `${leaseId}.json`);
74
- }
75
- /**
76
- * Compose the absolute worktree path (the `git worktree add <path>` target).
77
- * Sits adjacent to the lease file under the same runtime dir.
78
- */
79
- export function worktreePath(sessionRuntimeDir, leaseId) {
80
- return joinPath(sessionRuntimeDir, 'worktrees', leaseId);
81
- }
82
- /**
83
- * Generate a 16-hex lease id (8 random bytes, hex-encoded). The id is
84
- * unique enough for the per-session scope; collisions across sessions
85
- * are irrelevant because each session has its own lease directory.
86
- */
87
- export function generateLeaseId() {
88
- return randomBytes(LEASE_ID_RANDOM_BYTES).toString('hex');
89
- }
90
- /**
91
- * Compute the TTL ms for a role, falling back to DEFAULT_TTL_MS for
92
- * unknown roles. The CLI overrides with `--ttl <ms>` when the user
93
- * passes a positive value.
94
- */
95
- export function ttlForRole(role) {
96
- const normalized = role.toLowerCase();
97
- const candidate = DEFAULT_TTL_BY_ROLE[normalized];
98
- const fallback = DEFAULT_TTL_BY_ROLE['rd'] ?? LEASE_RD_TTL_MINUTES * MS_PER_MINUTE;
99
- return candidate ?? fallback;
100
- }
101
- /**
102
- * Pure: produce a fresh `WorktreeLease` from a draft + status.
103
- * `status` defaults to `'active'`; `consumedBySubAgents` defaults to [].
104
- * Used by the CLI's atomicWriteJson call.
105
- */
106
- export function finalizeLease(draft) {
107
- return {
108
- ...draft,
109
- status: 'active',
110
- consumedBySubAgents: []
111
- };
112
- }
113
- /** Pure: lease status transitions to 'released'. Returns a new lease. */
114
- export function markReleased(lease) {
115
- return { ...lease, status: 'released' };
116
- }
117
- /** Pure: lease status transitions to 'expired'. Returns a new lease. */
118
- export function markExpired(lease) {
119
- return { ...lease, status: 'expired' };
120
- }
121
- /** Pure: lease status transitions to 'gc'. Returns a new lease. */
122
- export function markGc(lease) {
123
- return { ...lease, status: 'gc' };
124
- }
125
- /** Pure: append a sub-agent batch / dispatch id to the consumption log. Returns a new lease. */
126
- export function recordConsumption(lease, subAgentId) {
127
- if (lease.consumedBySubAgents.includes(subAgentId))
128
- return lease;
129
- return { ...lease, consumedBySubAgents: [...lease.consumedBySubAgents, subAgentId] };
130
- }
131
- /**
132
- * Pure: is the lease still active (status === 'active' AND not past expiry).
133
- * Expired leases are NOT auto-released; the gc CLI is the only path that
134
- * transitions them to 'gc'. Until then, the on-disk state stays 'active'
135
- * but `isLeaseActive` returns false so consumers skip the lease.
136
- */
137
- export function isLeaseActive(lease, now = Date.now()) {
138
- return lease.status === 'active' && lease.expiresAt > now;
139
- }
140
- /**
141
- * List every lease file under the session's lease store dir.
142
- *
143
- * Pure with respect to its inputs: it does NOT sort or filter, and it
144
- * does NOT mark anything expired. Callers (the `list` CLI) apply their
145
- * own sort/filter and run `markExpired` lazily.
146
- */
147
- export function listLeasesSync(storeDir, fs) {
148
- if (!fs.existsSync(storeDir)) {
149
- return { kind: 'store-missing', storeDir };
150
- }
151
- const files = fs.readdir(storeDir).filter((f) => f.endsWith('.json'));
152
- const leases = [];
153
- const errors = [];
154
- for (const f of files) {
155
- const file = `${storeDir.replace(/[\\/]+$/, '')}/${f}`;
156
- try {
157
- leases.push(deserializeLease(fs.readFile(file)));
158
- }
159
- catch (err) {
160
- errors.push({ file, error: err instanceof Error ? err.message : String(err) });
161
- }
162
- }
163
- return { kind: 'ok', leases, errors };
164
- }
165
- /**
166
- * Pure: a lease is eligible for `gc` if its status is one of {released,
167
- * expired} AND its worktree path is no longer attached to git (`git
168
- * worktree list` would not include it). The CLI re-checks with git and
169
- * uses this helper as a coarse pre-filter.
170
- */
171
- export function isLeaseGcEligible(lease, now = Date.now()) {
172
- if (lease.status === 'gc')
173
- return false;
174
- if (lease.status === 'released')
175
- return true;
176
- // status === 'active' but past expiry → treat as expired candidate
177
- return lease.expiresAt <= now;
178
- }
179
- /**
180
- * Pure: derive a new lease from an existing one with an extended
181
- * `expiresAt`. Other fields are preserved. The CLI writes the new lease
182
- * atomically. Used by `peaks worktree renew --lease-id <id> --ttl <ms>`.
183
- */
184
- export function renewLease(lease, newExpiresAt) {
185
- return { ...lease, expiresAt: newExpiresAt, status: 'active' };
186
- }
187
- /**
188
- * Pure: serialize a lease to JSON with stable field order (deterministic
189
- * output for diff-friendly audit logs). The CLI passes the result to
190
- * `atomicWriteJson`. The function does NOT mutate the input.
191
- */
192
- export function serializeLease(lease) {
193
- return JSON.stringify(lease, null, 2) + '\n';
194
- }
195
- /**
196
- * Pure: deserialize a lease from JSON. Throws on malformed input — the
197
- * CLI catches and returns a `LEASE_FILE_INVALID` envelope (mirroring the
198
- * `peaks worktree auth` FILE_INVALID convention).
199
- */
200
- export function deserializeLease(raw) {
201
- const parsed = JSON.parse(raw);
202
- if (typeof parsed !== 'object' || parsed === null) {
203
- throw new Error('lease file must contain a JSON object');
204
- }
205
- const obj = parsed;
206
- if (typeof obj.leaseId !== 'string')
207
- throw new Error('leaseId missing');
208
- if (typeof obj.rid !== 'string')
209
- throw new Error('rid missing');
210
- if (typeof obj.role !== 'string')
211
- throw new Error('role missing');
212
- if (typeof obj.path !== 'string')
213
- throw new Error('path missing');
214
- if (typeof obj.branch !== 'string')
215
- throw new Error('branch missing');
216
- if (typeof obj.createdAt !== 'number')
217
- throw new Error('createdAt missing');
218
- if (typeof obj.expiresAt !== 'number')
219
- throw new Error('expiresAt missing');
220
- if (typeof obj.purpose !== 'string')
221
- throw new Error('purpose missing');
222
- if (typeof obj.status !== 'string')
223
- throw new Error('status missing');
224
- if (!Array.isArray(obj.consumedBySubAgents))
225
- throw new Error('consumedBySubAgents missing');
226
- return {
227
- leaseId: obj.leaseId,
228
- rid: obj.rid,
229
- role: obj.role,
230
- path: obj.path,
231
- branch: obj.branch,
232
- createdAt: obj.createdAt,
233
- expiresAt: obj.expiresAt,
234
- purpose: obj.purpose,
235
- status: obj.status,
236
- consumedBySubAgents: obj.consumedBySubAgents
237
- };
238
- }
239
- /** Internal: normalize a path segment to forward slashes (Windows
240
- * callers pass `C:\Users\...`; posix.join sees the backslash and
241
- * silently mangles). Then posix-join. The CLI uses the same module
242
- * so reads + writes always agree. */
243
- function joinPath(...segments) {
244
- if (segments.length === 0)
245
- return '';
246
- const normalized = segments.map((s) => normalizePath(s));
247
- let acc = normalized[0];
248
- for (let i = 1; i < normalized.length; i++) {
249
- acc = path.join(acc, normalized[i]);
250
- }
251
- return acc;
252
- }