peaks-loop-workspace-runtime 0.0.0-stage → 0.0.2

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Peaks contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,5 @@
1
+ /** The `peaks-loop-workspace-runtime` entry: every public entry point of the package. */
2
+ export * from './state-root.js';
3
+ export * from './lease/index.js';
4
+ export * from './worktree/index.js';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,yFAAyF;AACzF,cAAc,iBAAiB,CAAC;AAChC,cAAc,kBAAkB,CAAC;AACjC,cAAc,qBAAqB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ /** The `peaks-loop-workspace-runtime` entry: every public entry point of the package. */
2
+ export * from './state-root.js';
3
+ export * from './lease/index.js';
4
+ export * from './worktree/index.js';
@@ -0,0 +1,4 @@
1
+ /** The `peaks-loop-workspace-runtime/lease` entry: the lease store and its action bodies. */
2
+ export * from './store.js';
3
+ export * from './lifecycle.js';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/lease/index.ts"],"names":[],"mappings":"AAAA,6FAA6F;AAC7F,cAAc,YAAY,CAAC;AAC3B,cAAc,gBAAgB,CAAC"}
@@ -0,0 +1,3 @@
1
+ /** The `peaks-loop-workspace-runtime/lease` entry: the lease store and its action bodies. */
2
+ export * from './store.js';
3
+ export * from './lifecycle.js';
@@ -0,0 +1,122 @@
1
+ /**
2
+ * lease/lifecycle — the spawn / renew / release / gc action bodies.
3
+ *
4
+ * These are the behaviours behind `peaks worktree <verb>`, with every effect
5
+ * injected: `fs`, `runGit`, the clock value, and the random source. Nothing
6
+ * here prints, exits, reads the environment, or resolves a directory from the
7
+ * working directory — the caller decides all of that and passes it in.
8
+ *
9
+ * A caller-visible outcome (a missing lease, a malformed one, a non-renewable
10
+ * status) is a structured result, not a throw.
11
+ */
12
+ import { type SessionScope } from '../state-root.js';
13
+ import { type RunGit } from '../worktree/git.js';
14
+ import { type RandomBytes } from './store.js';
15
+ import type { LeaseReadError, WorktreeLease, WorktreeLeaseStatus } from './types.js';
16
+ /** The filesystem seam used by the lifecycle actions. */
17
+ export interface LeaseFs {
18
+ readonly readFile: (file: string) => string;
19
+ /** Write exactly these contents; create parent directories as needed. */
20
+ readonly writeFile: (file: string, contents: string) => void;
21
+ readonly existsSync: (file: string) => boolean;
22
+ readonly readdir: (dir: string) => ReadonlyArray<string>;
23
+ }
24
+ /** Every effect an action can have. `now` is read once per action, as the CLI does. */
25
+ export interface LeaseEffects {
26
+ readonly fs: LeaseFs;
27
+ readonly runGit: RunGit;
28
+ readonly now: number;
29
+ readonly randomBytes?: RandomBytes;
30
+ }
31
+ /** A state root, a session beneath it, and the git directory the worktree calls run from. */
32
+ export interface LeaseScope extends SessionScope {
33
+ readonly projectRoot: string;
34
+ }
35
+ export interface SpawnInput extends LeaseScope {
36
+ readonly rid: string;
37
+ readonly role: string;
38
+ readonly purpose: string;
39
+ /** Absent means the role's default TTL. */
40
+ readonly ttlMs?: number;
41
+ /** Absent means a branch name derived from `rid`. */
42
+ readonly branch?: string;
43
+ }
44
+ export type SpawnResult = {
45
+ readonly kind: 'ok';
46
+ readonly lease: WorktreeLease;
47
+ readonly leaseFile: string;
48
+ readonly ttlMs: number;
49
+ } | {
50
+ readonly kind: 'failed';
51
+ readonly error: string;
52
+ };
53
+ /**
54
+ * Write the lease AFTER `git worktree add` succeeds, so a failed add never
55
+ * leaves a lease that points at a worktree which does not exist.
56
+ */
57
+ export declare function runSpawn(input: SpawnInput, effects: LeaseEffects): SpawnResult;
58
+ export type LeaseFileFailure = {
59
+ readonly kind: 'lease-not-found';
60
+ readonly file: string;
61
+ } | {
62
+ readonly kind: 'lease-invalid';
63
+ readonly file: string;
64
+ readonly error: string;
65
+ };
66
+ export interface RenewInput extends LeaseScope {
67
+ readonly leaseId: string;
68
+ /** Absent means the role's default TTL. */
69
+ readonly ttlMs?: number;
70
+ }
71
+ export type RenewResult = LeaseFileFailure | {
72
+ readonly kind: 'not-renewable';
73
+ readonly lease: WorktreeLease;
74
+ } | {
75
+ readonly kind: 'invalid-ttl';
76
+ readonly ttlMs: number | undefined;
77
+ } | {
78
+ readonly kind: 'ok';
79
+ readonly lease: WorktreeLease;
80
+ readonly previous: WorktreeLease;
81
+ readonly ttlMs: number;
82
+ };
83
+ export declare function runRenew(input: RenewInput, effects: LeaseEffects): RenewResult;
84
+ export interface ReleaseInput extends LeaseScope {
85
+ readonly leaseId: string;
86
+ }
87
+ export type ReleaseResult = LeaseFileFailure | {
88
+ readonly kind: 'already-released';
89
+ readonly lease: WorktreeLease;
90
+ } | {
91
+ readonly kind: 'ok';
92
+ readonly lease: WorktreeLease;
93
+ readonly previous: WorktreeLease;
94
+ readonly gitWorktreeRemoveFailed: boolean;
95
+ };
96
+ /** Idempotent on an already-released lease: no git call, no write. */
97
+ export declare function runRelease(input: ReleaseInput, effects: LeaseEffects): ReleaseResult;
98
+ export interface GcInput extends LeaseScope {
99
+ /** Only consider this specific lease. */
100
+ readonly leaseId?: string;
101
+ /** Report what would be swept without mutating anything. */
102
+ readonly dryRun?: boolean;
103
+ }
104
+ export interface SweptLease {
105
+ readonly leaseId: string;
106
+ readonly path: string;
107
+ readonly previousStatus: WorktreeLeaseStatus;
108
+ readonly gitWorktreeRemoveFailed: boolean;
109
+ }
110
+ export type GcResult = {
111
+ readonly kind: 'store-missing';
112
+ readonly storeDir: string;
113
+ } | {
114
+ readonly kind: 'ok';
115
+ readonly storeDir: string;
116
+ readonly dryRun: boolean;
117
+ readonly candidates: number;
118
+ readonly swept: ReadonlyArray<SweptLease>;
119
+ readonly errors: ReadonlyArray<LeaseReadError>;
120
+ };
121
+ export declare function runGc(input: GcInput, effects: LeaseEffects): GcResult;
122
+ //# sourceMappingURL=lifecycle.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lifecycle.d.ts","sourceRoot":"","sources":["../../src/lease/lifecycle.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAqB,KAAK,YAAY,EAAE,MAAM,kBAAkB,CAAC;AACxE,OAAO,EAIL,KAAK,MAAM,EACZ,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAeL,KAAK,WAAW,EACjB,MAAM,YAAY,CAAC;AACpB,OAAO,KAAK,EAAE,cAAc,EAAE,aAAa,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAErF,yDAAyD;AACzD,MAAM,WAAW,OAAO;IACtB,QAAQ,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,CAAC;IAC5C,yEAA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,YAAY,GAAG,QAAQ,CAuBrE"}
@@ -0,0 +1,144 @@
1
+ /**
2
+ * lease/lifecycle — the spawn / renew / release / gc action bodies.
3
+ *
4
+ * These are the behaviours behind `peaks worktree <verb>`, with every effect
5
+ * injected: `fs`, `runGit`, the clock value, and the random source. Nothing
6
+ * here prints, exits, reads the environment, or resolves a directory from the
7
+ * working directory — the caller decides all of that and passes it in.
8
+ *
9
+ * A caller-visible outcome (a missing lease, a malformed one, a non-renewable
10
+ * status) is a structured result, not a throw.
11
+ */
12
+ import { sessionRuntimeDir } from '../state-root.js';
13
+ import { addWorktree, pruneWorktreesBestEffort, removeWorktreeBestEffort } from '../worktree/git.js';
14
+ import { deserializeLease, finalizeLease, generateLeaseId, isLeaseGcEligible, leaseFilePath, leaseStoreDir, listLeasesSync, markExpired, markGc, markReleased, renewLease, serializeLease, ttlForRole, worktreePath } from './store.js';
15
+ const MAX_BRANCH_NAME_LENGTH = 80;
16
+ /**
17
+ * Write the lease AFTER `git worktree add` succeeds, so a failed add never
18
+ * leaves a lease that points at a worktree which does not exist.
19
+ */
20
+ export function runSpawn(input, effects) {
21
+ const runtimeDir = sessionRuntimeDir(input);
22
+ const leaseId = generateLeaseId({ randomBytes: effects.randomBytes });
23
+ const ttlMs = input.ttlMs ?? ttlForRole(input.role);
24
+ const branch = input.branch ?? deriveBranch(input.rid);
25
+ const wtPath = worktreePath(runtimeDir, leaseId);
26
+ const leaseFile = leaseFilePath(runtimeDir, leaseId);
27
+ const lease = finalizeLease({
28
+ leaseId,
29
+ rid: input.rid,
30
+ role: input.role,
31
+ path: wtPath,
32
+ branch,
33
+ createdAt: effects.now,
34
+ expiresAt: effects.now + ttlMs,
35
+ purpose: input.purpose
36
+ });
37
+ try {
38
+ addWorktree(effects.runGit, input.projectRoot, wtPath, branch);
39
+ effects.fs.writeFile(leaseFile, serializeLease(lease));
40
+ }
41
+ catch (error) {
42
+ return { kind: 'failed', error: errorMessage(error) };
43
+ }
44
+ return { kind: 'ok', lease, leaseFile, ttlMs };
45
+ }
46
+ /** Branch names must be safe for git ref-format; the cap keeps a pathological rid usable. */
47
+ function deriveBranch(rid) {
48
+ return rid.replace(/[^A-Za-z0-9._/-]/g, '-').slice(0, MAX_BRANCH_NAME_LENGTH);
49
+ }
50
+ /** A missing or malformed lease file is a result, never a throw. */
51
+ function loadLease(fs, file) {
52
+ if (!fs.existsSync(file))
53
+ return { ok: false, failure: { kind: 'lease-not-found', file } };
54
+ try {
55
+ return { ok: true, lease: deserializeLease(fs.readFile(file)) };
56
+ }
57
+ catch (error) {
58
+ return { ok: false, failure: { kind: 'lease-invalid', file, error: errorMessage(error) } };
59
+ }
60
+ }
61
+ export function runRenew(input, effects) {
62
+ const file = leaseFilePath(sessionRuntimeDir(input), input.leaseId);
63
+ const loaded = loadLease(effects.fs, file);
64
+ if (!loaded.ok)
65
+ return loaded.failure;
66
+ const lease = loaded.lease;
67
+ if (lease.status === 'released' || lease.status === 'gc') {
68
+ return { kind: 'not-renewable', lease };
69
+ }
70
+ const ttlMs = input.ttlMs ?? ttlForRole(lease.role);
71
+ if (!Number.isInteger(ttlMs) || ttlMs <= 0) {
72
+ return { kind: 'invalid-ttl', ttlMs: input.ttlMs };
73
+ }
74
+ const renewed = renewLease(lease, effects.now + ttlMs);
75
+ effects.fs.writeFile(file, serializeLease(renewed));
76
+ return { kind: 'ok', lease: renewed, previous: lease, ttlMs };
77
+ }
78
+ /** Idempotent on an already-released lease: no git call, no write. */
79
+ export function runRelease(input, effects) {
80
+ const file = leaseFilePath(sessionRuntimeDir(input), input.leaseId);
81
+ const loaded = loadLease(effects.fs, file);
82
+ if (!loaded.ok)
83
+ return loaded.failure;
84
+ const lease = loaded.lease;
85
+ if (lease.status === 'released')
86
+ return { kind: 'already-released', lease };
87
+ const gitWorktreeRemoveFailed = removeWorktreeBestEffort(effects.runGit, input.projectRoot, lease.path);
88
+ const released = markReleased(lease);
89
+ effects.fs.writeFile(file, serializeLease(released));
90
+ return { kind: 'ok', lease: released, previous: lease, gitWorktreeRemoveFailed };
91
+ }
92
+ export function runGc(input, effects) {
93
+ const runtimeDir = sessionRuntimeDir(input);
94
+ const storeDir = leaseStoreDir(runtimeDir);
95
+ const listed = listLeasesSync(storeDir, {
96
+ readdir: effects.fs.readdir,
97
+ readFile: effects.fs.readFile,
98
+ existsSync: effects.fs.existsSync
99
+ });
100
+ if (listed.kind === 'store-missing')
101
+ return { kind: 'store-missing', storeDir };
102
+ const dryRun = input.dryRun === true;
103
+ const candidates = listed.leases
104
+ .filter((lease) => input.leaseId === undefined || lease.leaseId === input.leaseId)
105
+ .filter((lease) => isLeaseGcEligible(lease, effects.now));
106
+ const ctx = { input, effects, runtimeDir, dryRun };
107
+ const swept = candidates.map((lease) => sweepLease(lease, ctx));
108
+ return {
109
+ kind: 'ok',
110
+ storeDir,
111
+ dryRun,
112
+ candidates: candidates.length,
113
+ swept,
114
+ errors: listed.errors
115
+ };
116
+ }
117
+ /**
118
+ * An active lease past its expiry is marked expired first, then gc. With
119
+ * `dryRun` nothing is mutated: no git call, no prune, no write.
120
+ */
121
+ function sweepLease(lease, ctx) {
122
+ const { input, effects, runtimeDir, dryRun } = ctx;
123
+ const expired = lease.status === 'active' && lease.expiresAt <= effects.now ? markExpired(lease) : lease;
124
+ if (dryRun) {
125
+ return {
126
+ leaseId: lease.leaseId,
127
+ path: lease.path,
128
+ previousStatus: lease.status,
129
+ gitWorktreeRemoveFailed: false
130
+ };
131
+ }
132
+ const gitWorktreeRemoveFailed = removeWorktreeBestEffort(effects.runGit, input.projectRoot, expired.path);
133
+ pruneWorktreesBestEffort(effects.runGit, input.projectRoot);
134
+ effects.fs.writeFile(leaseFilePath(runtimeDir, lease.leaseId), serializeLease(markGc(expired)));
135
+ return {
136
+ leaseId: lease.leaseId,
137
+ path: lease.path,
138
+ previousStatus: lease.status,
139
+ gitWorktreeRemoveFailed
140
+ };
141
+ }
142
+ function errorMessage(error) {
143
+ return error instanceof Error ? error.message : String(error);
144
+ }
@@ -0,0 +1,107 @@
1
+ /**
2
+ * worktree-lease store — pure-function lease records for `peaks worktree spawn`.
3
+ *
4
+ * The store is a pure module: every helper takes the lease directory path as an
5
+ * argument and returns structured data. Filesystem writes happen at the call
6
+ * site (`lifecycle.ts` takes them through an injected `fs`), which keeps these
7
+ * helpers trivially testable. Time and randomness are parameters with
8
+ * production defaults, so a caller can make a run deterministic; a caller that
9
+ * wants them can also leave them alone.
10
+ *
11
+ * Why a separate lease (vs reusing `peaks worktree auth grant`):
12
+ * - `auth grant` is a single-shot, short-lived token file consulted by the
13
+ * PreToolUse hook BEFORE `git worktree add` runs. It answers
14
+ * "is the LLM allowed to do this right now?"
15
+ * - `lease` is a long-lived lifecycle object that owns the worktree path,
16
+ * branch, expiry, and consumption log. It answers
17
+ * "what worktrees does this session own, and which are still alive?"
18
+ */
19
+ import type { LeaseListResult, WorktreeLease, WorktreeLeaseDraft } from './types.js';
20
+ export type { LeaseListResult, LeaseReadError, WorktreeLease, WorktreeLeaseDraft, WorktreeLeaseStatus } from './types.js';
21
+ /**
22
+ * Per-role default TTL. Sub-agent dispatch duration varies by role:
23
+ * - rd (long planning + impl) → 30 min
24
+ * - qa (test design + browser validation) → 15 min
25
+ * - ui (high-fidelity prototype iteration) → 1 h
26
+ * - general / unknown → 30 min (rd-like)
27
+ *
28
+ * A caller MAY override with its own `ttlMs`.
29
+ */
30
+ export declare const DEFAULT_TTL_BY_ROLE: Readonly<Record<string, number>>;
31
+ export declare const DEFAULT_TTL_MS: number;
32
+ /** The randomness seam: `node:crypto#randomBytes` unless a caller injects one. */
33
+ export type RandomBytes = (size: number) => Buffer;
34
+ /**
35
+ * Compose a deterministic lease path under the per-session runtime dir.
36
+ * Pure: same inputs → same output. The layout is
37
+ * `<sessionRuntimeDir>/worktree-leases/<leaseId>.json`.
38
+ */
39
+ export declare function leaseStoreDir(sessionRuntimeDir: string): string;
40
+ export declare function leaseFilePath(sessionRuntimeDir: string, leaseId: string): string;
41
+ /** Compose the absolute worktree path (the `git worktree add <path>` target). */
42
+ export declare function worktreePath(sessionRuntimeDir: string, leaseId: string): string;
43
+ /**
44
+ * Generate a 16-hex lease id (8 random bytes, hex-encoded). The id is unique
45
+ * enough for the per-session scope; collisions across sessions are irrelevant
46
+ * because each session has its own lease directory.
47
+ */
48
+ export declare function generateLeaseId(options?: {
49
+ readonly randomBytes?: RandomBytes;
50
+ }): string;
51
+ /**
52
+ * Compute the TTL ms for a role, falling back to `DEFAULT_TTL_MS` for unknown
53
+ * roles. The caller overrides with a positive `ttlMs` when it has one.
54
+ */
55
+ export declare function ttlForRole(role: string): number;
56
+ /**
57
+ * Pure: produce a fresh `WorktreeLease` from a draft.
58
+ * `status` starts at `'active'`; `consumedBySubAgents` starts empty.
59
+ */
60
+ export declare function finalizeLease(draft: WorktreeLeaseDraft): WorktreeLease;
61
+ /** Pure: lease status transitions to 'released'. Returns a new lease. */
62
+ export declare function markReleased(lease: WorktreeLease): WorktreeLease;
63
+ /** Pure: lease status transitions to 'expired'. Returns a new lease. */
64
+ export declare function markExpired(lease: WorktreeLease): WorktreeLease;
65
+ /** Pure: lease status transitions to 'gc'. Returns a new lease. */
66
+ export declare function markGc(lease: WorktreeLease): WorktreeLease;
67
+ /** Pure: append a sub-agent batch / dispatch id to the consumption log. Returns a new lease. */
68
+ export declare function recordConsumption(lease: WorktreeLease, subAgentId: string): WorktreeLease;
69
+ /**
70
+ * Pure: is the lease still active (status === 'active' AND not past expiry).
71
+ * Expired leases are NOT auto-released; the gc action is the only path that
72
+ * transitions them. Until then the on-disk status stays 'active' but this
73
+ * helper returns false so consumers skip the lease.
74
+ */
75
+ export declare function isLeaseActive(lease: WorktreeLease, now?: number): boolean;
76
+ /**
77
+ * List every lease file under the session's lease store dir.
78
+ *
79
+ * Pure with respect to its inputs: it does NOT sort or filter, and it does NOT
80
+ * mark anything expired. Callers apply their own sort/filter and treat an
81
+ * over-expiry lease as an expired candidate. A malformed file is surfaced as a
82
+ * `{ file, error }` record rather than thrown, so one bad file cannot hide the
83
+ * rest of the store.
84
+ */
85
+ export declare function listLeasesSync(storeDir: string, fs: {
86
+ readdir: (path: string) => ReadonlyArray<string>;
87
+ readFile: (path: string) => string;
88
+ existsSync: (path: string) => boolean;
89
+ }): LeaseListResult;
90
+ /**
91
+ * Pure: a lease is eligible for gc if its status is one of {released, expired}
92
+ * or it is still 'active' but past its expiry. A 'gc' lease is terminal.
93
+ */
94
+ export declare function isLeaseGcEligible(lease: WorktreeLease, now?: number): boolean;
95
+ /**
96
+ * Pure: derive a new lease from an existing one with an extended `expiresAt`.
97
+ * Other fields are preserved; the status returns to 'active'.
98
+ */
99
+ export declare function renewLease(lease: WorktreeLease, newExpiresAt: number): WorktreeLease;
100
+ /** Pure: serialize a lease to JSON with stable field order (deterministic output). */
101
+ export declare function serializeLease(lease: WorktreeLease): string;
102
+ /**
103
+ * Pure: deserialize a lease from JSON. Throws on malformed input — callers
104
+ * catch and surface the reason instead of failing open on a malformed lease.
105
+ */
106
+ export declare function deserializeLease(raw: string): WorktreeLease;
107
+ //# sourceMappingURL=store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/lease/store.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAIH,OAAO,KAAK,EACV,eAAe,EAEf,aAAa,EACb,kBAAkB,EAEnB,MAAM,YAAY,CAAC;AAEpB,YAAY,EACV,eAAe,EACf,cAAc,EACd,aAAa,EACb,kBAAkB,EAClB,mBAAmB,EACpB,MAAM,YAAY,CAAC;AAYpB;;;;;;;;GAQG;AACH,eAAO,MAAM,mBAAmB,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAO/D,CAAC;AAEH,eAAO,MAAM,cAAc,QAAyB,CAAC;AAErD,kFAAkF;AAClF,MAAM,MAAM,WAAW,GAAG,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,CAAC;AAEnD;;;;GAIG;AACH,wBAAgB,aAAa,C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AC;CACvC,GACA,eAAe,CAgBjB;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,aAAa,EAAE,GAAG,GAAE,MAAmB,GAAG,OAAO,CAIzF;AAED;;;GAGG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,GAAG,aAAa,CAEpF;AAED,sFAAsF;AACtF,wBAAgB,cAAc,CAAC,KAAK,EAAE,aAAa,GAAG,MAAM,CAE3D;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,GAAG,aAAa,CA4B3D"}
@@ -0,0 +1,224 @@
1
+ /**
2
+ * worktree-lease store — pure-function lease records for `peaks worktree spawn`.
3
+ *
4
+ * The store is a pure module: every helper takes the lease directory path as an
5
+ * argument and returns structured data. Filesystem writes happen at the call
6
+ * site (`lifecycle.ts` takes them through an injected `fs`), which keeps these
7
+ * helpers trivially testable. Time and randomness are parameters with
8
+ * production defaults, so a caller can make a run deterministic; a caller that
9
+ * wants them can also leave them alone.
10
+ *
11
+ * Why a separate lease (vs reusing `peaks worktree auth grant`):
12
+ * - `auth grant` is a single-shot, short-lived token file consulted by the
13
+ * PreToolUse hook BEFORE `git worktree add` runs. It answers
14
+ * "is the LLM allowed to do this right now?"
15
+ * - `lease` is a long-lived lifecycle object that owns the worktree path,
16
+ * branch, expiry, and consumption log. It answers
17
+ * "what worktrees does this session own, and which are still alive?"
18
+ */
19
+ import { randomBytes as cryptoRandomBytes } from 'node:crypto';
20
+ import { posix as path } from 'node:path';
21
+ const MINUTES_PER_HOUR = 60;
22
+ const MS_PER_MINUTE = MINUTES_PER_HOUR * 1_000;
23
+ const LEASE_RD_TTL_MINUTES = 30;
24
+ const LEASE_QA_TTL_MINUTES = 15;
25
+ const LEASE_UI_TTL_MINUTES = MINUTES_PER_HOUR;
26
+ const LEASE_SC_TTL_MINUTES = 30;
27
+ const LEASE_PRD_TTL_MINUTES = 15;
28
+ const LEASE_GENERAL_TTL_MINUTES = 30;
29
+ const LEASE_ID_RANDOM_BYTES = 8;
30
+ /**
31
+ * Per-role default TTL. Sub-agent dispatch duration varies by role:
32
+ * - rd (long planning + impl) → 30 min
33
+ * - qa (test design + browser validation) → 15 min
34
+ * - ui (high-fidelity prototype iteration) → 1 h
35
+ * - general / unknown → 30 min (rd-like)
36
+ *
37
+ * A caller MAY override with its own `ttlMs`.
38
+ */
39
+ export const DEFAULT_TTL_BY_ROLE = Object.freeze({
40
+ rd: LEASE_RD_TTL_MINUTES * MS_PER_MINUTE,
41
+ qa: LEASE_QA_TTL_MINUTES * MS_PER_MINUTE,
42
+ ui: LEASE_UI_TTL_MINUTES * MS_PER_MINUTE,
43
+ sc: LEASE_SC_TTL_MINUTES * MS_PER_MINUTE,
44
+ prd: LEASE_PRD_TTL_MINUTES * MS_PER_MINUTE,
45
+ general: LEASE_GENERAL_TTL_MINUTES * MS_PER_MINUTE
46
+ });
47
+ export const DEFAULT_TTL_MS = DEFAULT_TTL_BY_ROLE.rd;
48
+ /**
49
+ * Compose a deterministic lease path under the per-session runtime dir.
50
+ * Pure: same inputs → same output. The layout is
51
+ * `<sessionRuntimeDir>/worktree-leases/<leaseId>.json`.
52
+ */
53
+ export function leaseStoreDir(sessionRuntimeDir) {
54
+ return joinPath(sessionRuntimeDir, 'worktree-leases');
55
+ }
56
+ export function leaseFilePath(sessionRuntimeDir, leaseId) {
57
+ return joinPath(leaseStoreDir(sessionRuntimeDir), `${leaseId}.json`);
58
+ }
59
+ /** Compose the absolute worktree path (the `git worktree add <path>` target). */
60
+ export function worktreePath(sessionRuntimeDir, leaseId) {
61
+ return joinPath(sessionRuntimeDir, 'worktrees', leaseId);
62
+ }
63
+ /**
64
+ * Generate a 16-hex lease id (8 random bytes, hex-encoded). The id is unique
65
+ * enough for the per-session scope; collisions across sessions are irrelevant
66
+ * because each session has its own lease directory.
67
+ */
68
+ export function generateLeaseId(options = {}) {
69
+ const draw = options.randomBytes ?? cryptoRandomBytes;
70
+ return draw(LEASE_ID_RANDOM_BYTES).toString('hex');
71
+ }
72
+ /**
73
+ * Compute the TTL ms for a role, falling back to `DEFAULT_TTL_MS` for unknown
74
+ * roles. The caller overrides with a positive `ttlMs` when it has one.
75
+ */
76
+ export function ttlForRole(role) {
77
+ const normalized = role.toLowerCase();
78
+ const candidate = DEFAULT_TTL_BY_ROLE[normalized];
79
+ const fallback = DEFAULT_TTL_BY_ROLE['rd'] ?? LEASE_RD_TTL_MINUTES * MS_PER_MINUTE;
80
+ return candidate ?? fallback;
81
+ }
82
+ /**
83
+ * Pure: produce a fresh `WorktreeLease` from a draft.
84
+ * `status` starts at `'active'`; `consumedBySubAgents` starts empty.
85
+ */
86
+ export function finalizeLease(draft) {
87
+ return {
88
+ ...draft,
89
+ status: 'active',
90
+ consumedBySubAgents: []
91
+ };
92
+ }
93
+ /** Pure: lease status transitions to 'released'. Returns a new lease. */
94
+ export function markReleased(lease) {
95
+ return { ...lease, status: 'released' };
96
+ }
97
+ /** Pure: lease status transitions to 'expired'. Returns a new lease. */
98
+ export function markExpired(lease) {
99
+ return { ...lease, status: 'expired' };
100
+ }
101
+ /** Pure: lease status transitions to 'gc'. Returns a new lease. */
102
+ export function markGc(lease) {
103
+ return { ...lease, status: 'gc' };
104
+ }
105
+ /** Pure: append a sub-agent batch / dispatch id to the consumption log. Returns a new lease. */
106
+ export function recordConsumption(lease, subAgentId) {
107
+ if (lease.consumedBySubAgents.includes(subAgentId))
108
+ return lease;
109
+ return { ...lease, consumedBySubAgents: [...lease.consumedBySubAgents, subAgentId] };
110
+ }
111
+ /**
112
+ * Pure: is the lease still active (status === 'active' AND not past expiry).
113
+ * Expired leases are NOT auto-released; the gc action is the only path that
114
+ * transitions them. Until then the on-disk status stays 'active' but this
115
+ * helper returns false so consumers skip the lease.
116
+ */
117
+ export function isLeaseActive(lease, now = Date.now()) {
118
+ return lease.status === 'active' && lease.expiresAt > now;
119
+ }
120
+ /**
121
+ * List every lease file under the session's lease store dir.
122
+ *
123
+ * Pure with respect to its inputs: it does NOT sort or filter, and it does NOT
124
+ * mark anything expired. Callers apply their own sort/filter and treat an
125
+ * over-expiry lease as an expired candidate. A malformed file is surfaced as a
126
+ * `{ file, error }` record rather than thrown, so one bad file cannot hide the
127
+ * rest of the store.
128
+ */
129
+ export function listLeasesSync(storeDir, fs) {
130
+ if (!fs.existsSync(storeDir)) {
131
+ return { kind: 'store-missing', storeDir };
132
+ }
133
+ const files = fs.readdir(storeDir).filter((f) => f.endsWith('.json'));
134
+ const leases = [];
135
+ const errors = [];
136
+ for (const f of files) {
137
+ const file = `${storeDir.replace(/[\\/]+$/, '')}/${f}`;
138
+ try {
139
+ leases.push(deserializeLease(fs.readFile(file)));
140
+ }
141
+ catch (err) {
142
+ errors.push({ file, error: err instanceof Error ? err.message : String(err) });
143
+ }
144
+ }
145
+ return { kind: 'ok', leases, errors };
146
+ }
147
+ /**
148
+ * Pure: a lease is eligible for gc if its status is one of {released, expired}
149
+ * or it is still 'active' but past its expiry. A 'gc' lease is terminal.
150
+ */
151
+ export function isLeaseGcEligible(lease, now = Date.now()) {
152
+ if (lease.status === 'gc')
153
+ return false;
154
+ if (lease.status === 'released')
155
+ return true;
156
+ return lease.expiresAt <= now;
157
+ }
158
+ /**
159
+ * Pure: derive a new lease from an existing one with an extended `expiresAt`.
160
+ * Other fields are preserved; the status returns to 'active'.
161
+ */
162
+ export function renewLease(lease, newExpiresAt) {
163
+ return { ...lease, expiresAt: newExpiresAt, status: 'active' };
164
+ }
165
+ /** Pure: serialize a lease to JSON with stable field order (deterministic output). */
166
+ export function serializeLease(lease) {
167
+ return JSON.stringify(lease, null, 2) + '\n';
168
+ }
169
+ /**
170
+ * Pure: deserialize a lease from JSON. Throws on malformed input — callers
171
+ * catch and surface the reason instead of failing open on a malformed lease.
172
+ */
173
+ export function deserializeLease(raw) {
174
+ const parsed = JSON.parse(raw);
175
+ if (typeof parsed !== 'object' || parsed === null) {
176
+ throw new Error('lease file must contain a JSON object');
177
+ }
178
+ const obj = parsed;
179
+ if (typeof obj.leaseId !== 'string')
180
+ throw new Error('leaseId missing');
181
+ if (typeof obj.rid !== 'string')
182
+ throw new Error('rid missing');
183
+ if (typeof obj.role !== 'string')
184
+ throw new Error('role missing');
185
+ if (typeof obj.path !== 'string')
186
+ throw new Error('path missing');
187
+ if (typeof obj.branch !== 'string')
188
+ throw new Error('branch missing');
189
+ if (typeof obj.createdAt !== 'number')
190
+ throw new Error('createdAt missing');
191
+ if (typeof obj.expiresAt !== 'number')
192
+ throw new Error('expiresAt missing');
193
+ if (typeof obj.purpose !== 'string')
194
+ throw new Error('purpose missing');
195
+ if (typeof obj.status !== 'string')
196
+ throw new Error('status missing');
197
+ if (!Array.isArray(obj.consumedBySubAgents))
198
+ throw new Error('consumedBySubAgents missing');
199
+ return {
200
+ leaseId: obj.leaseId,
201
+ rid: obj.rid,
202
+ role: obj.role,
203
+ path: obj.path,
204
+ branch: obj.branch,
205
+ createdAt: obj.createdAt,
206
+ expiresAt: obj.expiresAt,
207
+ purpose: obj.purpose,
208
+ status: obj.status,
209
+ consumedBySubAgents: obj.consumedBySubAgents
210
+ };
211
+ }
212
+ /** Internal: fold separators to forward slashes, then posix-join. A Windows
213
+ * caller passes `C:\dir`; posix.join sees the backslashes and mangles the
214
+ * path, so both the read and the write here go through this one function. */
215
+ function joinPath(...segments) {
216
+ if (segments.length === 0)
217
+ return '';
218
+ const normalized = segments.map((s) => s.replace(/\\/g, '/'));
219
+ let acc = normalized[0];
220
+ for (let i = 1; i < normalized.length; i++) {
221
+ acc = path.join(acc, normalized[i]);
222
+ }
223
+ return acc;
224
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * worktree-lease-types — the pure declaration surface of the worktree lease
3
+ * store (`store.ts`).
4
+ *
5
+ * This module owns only the shapes (lifecycle status, lease record, creation
6
+ * draft, and the list-read result); the store imports and re-exports every name
7
+ * here, so an importer can resolve them from either module.
8
+ */
9
+ export type WorktreeLeaseStatus = 'active' | 'released' | 'expired' | 'gc';
10
+ export interface WorktreeLease {
11
+ /** Random 16-hex lease id; emitted to the operator as the lease handle. */
12
+ readonly leaseId: string;
13
+ /** The peaks request id (rid) that the lease was spawned for. */
14
+ readonly rid: string;
15
+ /** Sub-agent role (rd | qa | ui | sc | prd | general-purpose | ...). */
16
+ readonly role: string;
17
+ /** Absolute worktree path on disk (the session runtime dir's `worktrees/<leaseId>/`). */
18
+ readonly path: string;
19
+ /** Branch name (one of the worktree's --branch / -b args). */
20
+ readonly branch: string;
21
+ /** Unix epoch ms when the lease was created. */
22
+ readonly createdAt: number;
23
+ /** Unix epoch ms when the lease expires. */
24
+ readonly expiresAt: number;
25
+ /** Operator-supplied purpose text (audit log). */
26
+ readonly purpose: string;
27
+ /** Lifecycle status; updated by the release and gc actions. */
28
+ readonly status: WorktreeLeaseStatus;
29
+ /** Sub-agent batch / dispatch ids that have consumed this lease. */
30
+ readonly consumedBySubAgents: ReadonlyArray<string>;
31
+ }
32
+ /** Subset of WorktreeLease that the spawn action writes on creation. Starts at 'active'. */
33
+ export type WorktreeLeaseDraft = Omit<WorktreeLease, 'status' | 'consumedBySubAgents'>;
34
+ /**
35
+ * Pure: read every lease file under the session's lease store dir.
36
+ * Returns leases in the order returned by `readdir` (no sort).
37
+ * Malformed files are surfaced as `{ file, error }` records so the caller can
38
+ * warn without aborting the whole list. A missing directory is not an error —
39
+ * it returns a `store-missing` result.
40
+ */
41
+ export interface LeaseReadError {
42
+ readonly file: string;
43
+ readonly error: string;
44
+ }
45
+ export type LeaseListResult = {
46
+ readonly kind: 'ok';
47
+ readonly leases: ReadonlyArray<WorktreeLease>;
48
+ readonly errors: ReadonlyArray<LeaseReadError>;
49
+ } | {
50
+ readonly kind: 'store-missing';
51
+ readonly storeDir: string;
52
+ };
53
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/lease/types.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG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QAAQ,EAAE,MAAM,CAAA;CAAE,CAAC"}
@@ -0,0 +1,9 @@
1
+ /**
2
+ * worktree-lease-types — the pure declaration surface of the worktree lease
3
+ * store (`store.ts`).
4
+ *
5
+ * This module owns only the shapes (lifecycle status, lease record, creation
6
+ * draft, and the list-read result); the store imports and re-exports every name
7
+ * here, so an importer can resolve them from either module.
8
+ */
9
+ export {};
@@ -0,0 +1,3 @@
1
+ /** The `peaks-loop-workspace-runtime/lease` entry: re-exports the nested `lease/` directory. */
2
+ export * from './lease/index.js';
3
+ //# sourceMappingURL=lease.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lease.d.ts","sourceRoot":"","sources":["../src/lease.ts"],"names":[],"mappings":"AAAA,gGAAgG;AAChG,cAAc,kBAAkB,CAAC"}
package/dist/lease.js ADDED
@@ -0,0 +1,2 @@
1
+ /** The `peaks-loop-workspace-runtime/lease` entry: re-exports the nested `lease/` directory. */
2
+ export * from './lease/index.js';
@@ -0,0 +1,31 @@
1
+ /**
2
+ * state-root — the one place this package composes a path from a project root.
3
+ *
4
+ * Every other entry takes an already-resolved `stateRoot`, so a host with a
5
+ * different layout (an app-data directory, a temp tree, another repository's
6
+ * convention) passes its own and this package never has to guess. Only
7
+ * `defaultStateRoot` names the peaks-loop layout.
8
+ *
9
+ * Paths are emitted with forward slashes so a Windows host and a POSIX host
10
+ * produce the same string for the same directory. The lease store joins through
11
+ * the same normalization, so reads and writes always agree.
12
+ */
13
+ /** A caller-supplied state root plus the one session segment beneath it. */
14
+ export interface SessionScope {
15
+ readonly stateRoot: string;
16
+ readonly sessionId: string;
17
+ }
18
+ /**
19
+ * The peaks-loop layout: the project root followed by the runtime directory.
20
+ * This is the only function in the package that knows that layout; a host that
21
+ * stores its runtime state elsewhere never calls it.
22
+ */
23
+ export declare function defaultStateRoot(projectRoot: string): string;
24
+ /**
25
+ * `<stateRoot>/<sessionId>`. Throws when `sessionId` is not a single path
26
+ * segment, because it is the last caller-supplied segment of every
27
+ * session-scoped path this package produces.
28
+ */
29
+ export declare function sessionRuntimeDir({ stateRoot, sessionId }: SessionScope): string;
30
+ export declare function isSinglePathSegment(sessionId: string): boolean;
31
+ //# sourceMappingURL=state-root.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"state-root.d.ts","sourceRoot":"","sources":["../src/state-root.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAIH,4EAA4E;AAC5E,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;CAC5B;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAE5D;AAED;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,EAAE,SAAS,EAAE,SAAS,EAAE,EAAE,YAAY,GAAG,MAAM,CAKhF;AAED,wBAAgB,mBAAmB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAM9D"}
@@ -0,0 +1,46 @@
1
+ /**
2
+ * state-root — the one place this package composes a path from a project root.
3
+ *
4
+ * Every other entry takes an already-resolved `stateRoot`, so a host with a
5
+ * different layout (an app-data directory, a temp tree, another repository's
6
+ * convention) passes its own and this package never has to guess. Only
7
+ * `defaultStateRoot` names the peaks-loop layout.
8
+ *
9
+ * Paths are emitted with forward slashes so a Windows host and a POSIX host
10
+ * produce the same string for the same directory. The lease store joins through
11
+ * the same normalization, so reads and writes always agree.
12
+ */
13
+ import { posix as path } from 'node:path';
14
+ /**
15
+ * The peaks-loop layout: the project root followed by the runtime directory.
16
+ * This is the only function in the package that knows that layout; a host that
17
+ * stores its runtime state elsewhere never calls it.
18
+ */
19
+ export function defaultStateRoot(projectRoot) {
20
+ return `${projectRoot.replace(/[\\/]+$/, '')}/.peaks/_runtime`;
21
+ }
22
+ /**
23
+ * `<stateRoot>/<sessionId>`. Throws when `sessionId` is not a single path
24
+ * segment, because it is the last caller-supplied segment of every
25
+ * session-scoped path this package produces.
26
+ */
27
+ export function sessionRuntimeDir({ stateRoot, sessionId }) {
28
+ if (!isSinglePathSegment(sessionId)) {
29
+ throw new Error(`Invalid session id: ${sessionId} (must be a single path segment)`);
30
+ }
31
+ return path.join(normalizePath(stateRoot), sessionId);
32
+ }
33
+ export function isSinglePathSegment(sessionId) {
34
+ if (sessionId.length === 0)
35
+ return false;
36
+ if (sessionId === '.' || sessionId === '..')
37
+ return false;
38
+ if (sessionId.includes('/') || sessionId.includes('\\'))
39
+ return false;
40
+ if (sessionId.includes('\0'))
41
+ return false;
42
+ return true;
43
+ }
44
+ function normalizePath(value) {
45
+ return value.replace(/\\/g, '/');
46
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * worktree/git — the three git calls the worktree lifecycle makes, with the
3
+ * process itself left to the caller.
4
+ *
5
+ * `runGit` is a parameter. peaks-loop passes a shell-based implementation and
6
+ * peaks-harness passes one that never touches a shell; neither choice belongs
7
+ * in this package, and neither is made here.
8
+ */
9
+ export interface GitResult {
10
+ readonly ok: boolean;
11
+ readonly stdout: string;
12
+ readonly stderr?: string;
13
+ }
14
+ /** Run git with `argv`, from `cwd`. The caller owns the process and its exit code. */
15
+ export type RunGit = (argv: readonly string[], opts: {
16
+ readonly cwd: string;
17
+ }) => GitResult;
18
+ /** `git worktree add <path> -b <branch>`. Throws when the call reports failure. */
19
+ export declare function addWorktree(runGit: RunGit, projectRoot: string, wtPath: string, branch: string): void;
20
+ /**
21
+ * `git worktree remove --force` is best-effort: when the path is already
22
+ * pruned the caller still marks the lease released / gc. Returns whether the
23
+ * git invocation failed.
24
+ */
25
+ export declare function removeWorktreeBestEffort(runGit: RunGit, projectRoot: string, wtPath: string): boolean;
26
+ /** `git worktree prune` clears stale admin entries. Best-effort. */
27
+ export declare function pruneWorktreesBestEffort(runGit: RunGit, projectRoot: string): void;
28
+ //# sourceMappingURL=git.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"git.d.ts","sourceRoot":"","sources":["../../src/worktree/git.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,MAAM,WAAW,SAAS;IACxB,QAAQ,CAAC,EAAE,EAAE,OAAO,CAAC;IACrB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED,sFAAsF;AACtF,MAAM,MAAM,MAAM,GAAG,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,EAAE,IAAI,EAAE;IAAE,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;CAAE,KAAK,SAAS,CAAC;AAE5F,mFAAmF;AACnF,wBAAgB,WAAW,CACzB,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,MAAM,EACnB,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,GACb,IAAI,CAKN;AAED;;;;GAIG;AACH,wBAAgB,wBAAwB,CACtC,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,MAAM,EACnB,MAAM,EAAE,MAAM,GACb,OAAO,CAMT;AAED,oEAAoE;AACpE,wBAAgB,wBAAwB,CAAC,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,IAAI,CAMlF"}
@@ -0,0 +1,38 @@
1
+ /**
2
+ * worktree/git — the three git calls the worktree lifecycle makes, with the
3
+ * process itself left to the caller.
4
+ *
5
+ * `runGit` is a parameter. peaks-loop passes a shell-based implementation and
6
+ * peaks-harness passes one that never touches a shell; neither choice belongs
7
+ * in this package, and neither is made here.
8
+ */
9
+ /** `git worktree add <path> -b <branch>`. Throws when the call reports failure. */
10
+ export function addWorktree(runGit, projectRoot, wtPath, branch) {
11
+ const result = runGit(['worktree', 'add', wtPath, '-b', branch], { cwd: projectRoot });
12
+ if (result.ok)
13
+ return;
14
+ const detail = (result.stderr ?? '').trim() || result.stdout.trim() || '(no output)';
15
+ throw new Error(`git worktree add failed: ${detail}`);
16
+ }
17
+ /**
18
+ * `git worktree remove --force` is best-effort: when the path is already
19
+ * pruned the caller still marks the lease released / gc. Returns whether the
20
+ * git invocation failed.
21
+ */
22
+ export function removeWorktreeBestEffort(runGit, projectRoot, wtPath) {
23
+ try {
24
+ return !runGit(['worktree', 'remove', '--force', wtPath], { cwd: projectRoot }).ok;
25
+ }
26
+ catch {
27
+ return true;
28
+ }
29
+ }
30
+ /** `git worktree prune` clears stale admin entries. Best-effort. */
31
+ export function pruneWorktreesBestEffort(runGit, projectRoot) {
32
+ try {
33
+ runGit(['worktree', 'prune'], { cwd: projectRoot });
34
+ }
35
+ catch {
36
+ // ignore — prune is idempotent
37
+ }
38
+ }
@@ -0,0 +1,4 @@
1
+ /** The `peaks-loop-workspace-runtime/worktree` entry: the porcelain parser and the git calls. */
2
+ export * from './parser.js';
3
+ export * from './git.js';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/worktree/index.ts"],"names":[],"mappings":"AAAA,iGAAiG;AACjG,cAAc,aAAa,CAAC;AAC5B,cAAc,UAAU,CAAC"}
@@ -0,0 +1,3 @@
1
+ /** The `peaks-loop-workspace-runtime/worktree` entry: the porcelain parser and the git calls. */
2
+ export * from './parser.js';
3
+ export * from './git.js';
@@ -0,0 +1,9 @@
1
+ export type GitWorktreeRecord = {
2
+ readonly path: string;
3
+ readonly head: string | null;
4
+ readonly branch: string | null;
5
+ readonly prunable: boolean;
6
+ };
7
+ export declare function parseGitWorktreePorcelain(raw: string): ReadonlyArray<GitWorktreeRecord>;
8
+ export declare function isPathInside(parent: string, candidate: string): boolean;
9
+ //# sourceMappingURL=parser.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"parser.d.ts","sourceRoot":"","sources":["../../src/worktree/parser.ts"],"names":[],"mappings":"AAEA,MAAM,MAAM,iBAAiB,GAAG;IAC9B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;CAC5B,CAAC;AASF,wBAAgB,yBAAyB,CAAC,GAAG,EAAE,MAAM,GAAG,aAAa,CAAC,iBAAiB,CAAC,CA8CvF;AAED,wBAAgB,YAAY,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAGvE"}
@@ -0,0 +1,55 @@
1
+ import { relative, resolve, sep } from 'node:path';
2
+ export function parseGitWorktreePorcelain(raw) {
3
+ const records = [];
4
+ let current = null;
5
+ const flush = () => {
6
+ if (current !== null) {
7
+ records.push({
8
+ path: current.path,
9
+ head: current.head,
10
+ branch: current.branch,
11
+ prunable: current.prunable
12
+ });
13
+ }
14
+ current = null;
15
+ };
16
+ for (const line of raw.split(/\r?\n/)) {
17
+ if (line.length === 0) {
18
+ flush();
19
+ continue;
20
+ }
21
+ const space = line.indexOf(' ');
22
+ const key = space === -1 ? line : line.slice(0, space);
23
+ const value = space === -1 ? '' : line.slice(space + 1);
24
+ if (key === 'worktree') {
25
+ flush();
26
+ const next = { path: value, head: null, branch: null, prunable: false };
27
+ current = next;
28
+ }
29
+ else if (current !== null && key === 'HEAD') {
30
+ current = {
31
+ path: current.path,
32
+ head: value,
33
+ branch: current.branch,
34
+ prunable: current.prunable
35
+ };
36
+ }
37
+ else if (current !== null && key === 'branch') {
38
+ current = {
39
+ path: current.path,
40
+ head: current.head,
41
+ branch: value.replace(/^refs\/heads\//, ''),
42
+ prunable: current.prunable
43
+ };
44
+ }
45
+ else if (current !== null && key === 'prunable') {
46
+ current = { path: current.path, head: current.head, branch: current.branch, prunable: true };
47
+ }
48
+ }
49
+ flush();
50
+ return records;
51
+ }
52
+ export function isPathInside(parent, candidate) {
53
+ const rel = relative(resolve(parent), resolve(candidate));
54
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${sep}`) && !rel.startsWith(sep));
55
+ }
@@ -0,0 +1,3 @@
1
+ /** The `peaks-loop-workspace-runtime/worktree` entry: re-exports the nested `worktree/` directory. */
2
+ export * from './worktree/index.js';
3
+ //# sourceMappingURL=worktree.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worktree.d.ts","sourceRoot":"","sources":["../src/worktree.ts"],"names":[],"mappings":"AAAA,sGAAsG;AACtG,cAAc,qBAAqB,CAAC"}
@@ -0,0 +1,2 @@
1
+ /** The `peaks-loop-workspace-runtime/worktree` entry: re-exports the nested `worktree/` directory. */
2
+ export * from './worktree/index.js';
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "peaks-loop-workspace-runtime",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.0.2",
4
+ "description": "Worktree and session runtime primitives shared by peaks-loop and peaks-harness: state roots, worktree leases, and injectable git/fs/clock/random effects.",
5
+ "keywords": [
6
+ "peaks-loop",
7
+ "peaks-loop-workspace-runtime",
8
+ "loop-engineering",
9
+ "worktree",
10
+ "lease",
11
+ "session-runtime",
12
+ "ai-orchestration",
13
+ "monorepo",
14
+ "typescript",
15
+ "esm"
16
+ ],
17
+ "license": "MIT",
18
+ "type": "module",
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "default": "./dist/index.js"
23
+ },
24
+ "./state-root": {
25
+ "types": "./dist/state-root.d.ts",
26
+ "default": "./dist/state-root.js"
27
+ },
28
+ "./lease": {
29
+ "types": "./dist/lease/index.d.ts",
30
+ "default": "./dist/lease/index.js"
31
+ },
32
+ "./worktree": {
33
+ "types": "./dist/worktree/index.d.ts",
34
+ "default": "./dist/worktree/index.js"
35
+ }
36
+ },
37
+ "files": [
38
+ "dist/**"
39
+ ],
40
+ "engines": {
41
+ "node": ">=20.0.0"
42
+ },
43
+ "publishConfig": {
44
+ "access": "public"
45
+ },
46
+ "repository": {
47
+ "type": "git",
48
+ "url": "https://github.com/SquabbyZ/peaks-loop.git"
49
+ },
50
+ "bugs": {
51
+ "url": "https://github.com/SquabbyZ/peaks-loop/issues"
52
+ },
53
+ "scripts": {
54
+ "build": "tsc -p tsconfig.json",
55
+ "test": "vitest run"
56
+ }
6
57
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.