@helmsmith/workbrokr 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js ADDED
@@ -0,0 +1,3280 @@
1
+ // ../../platform/core/cli-kit-lib/src/auth-provider.ts
2
+ var noopAuthProvider = {
3
+ async getToken() {
4
+ throw new Error(
5
+ "noopAuthProvider.getToken() called \u2014 wire a real AuthProvider via createCli({ auth })"
6
+ );
7
+ },
8
+ async whoami() {
9
+ return null;
10
+ }
11
+ };
12
+
13
+ // ../../platform/core/cli-kit-lib/src/create-cli.ts
14
+ import { Command } from "commander";
15
+ function createCli(opts) {
16
+ const program2 = new Command();
17
+ program2.name(opts.name).version(opts.version);
18
+ if (opts.description) program2.description(opts.description);
19
+ program2.configureOutput({
20
+ outputError: (str, write) => write(str)
21
+ });
22
+ return { program: program2, auth: opts.auth ?? noopAuthProvider };
23
+ }
24
+
25
+ // src/commands/audit.ts
26
+ import chalk3 from "chalk";
27
+
28
+ // src/lib/context.ts
29
+ import chalk from "chalk";
30
+
31
+ // src/core/config.ts
32
+ import {
33
+ appendFileSync,
34
+ existsSync as existsSync2,
35
+ mkdirSync as mkdirSync2,
36
+ readFileSync,
37
+ realpathSync as realpathSync2,
38
+ writeFileSync
39
+ } from "fs";
40
+ import { join as join2 } from "path";
41
+
42
+ // src/core/errors.ts
43
+ var REFUSALS = /* @__PURE__ */ new Set([
44
+ "MANIFEST_INVALID",
45
+ "AREA_UNKNOWN",
46
+ "TASK_INVALID",
47
+ "TYPE_UNKNOWN",
48
+ "MODE_UNKNOWN",
49
+ "MODE_MISMATCH",
50
+ "SCOPE_REQUIRES_TASK",
51
+ "SCOPE_OUTSIDE_AREA",
52
+ "MAIN_CHECKOUT",
53
+ "WORKTREE_INVALID",
54
+ "PROTECTED_BRANCH",
55
+ "EFFORT_OPEN",
56
+ "EFFORT_NOT_FOUND",
57
+ "SCOPE_CONFLICT",
58
+ "COMMONS_LOCKED",
59
+ "NO_FREE_SLOT",
60
+ "LEASE_NOT_FOUND",
61
+ "PORT_RANGE_TAKEN",
62
+ "SYNC_CONFLICT",
63
+ "DIRTY_WORKTREE",
64
+ "UNPUSHED"
65
+ ]);
66
+ function exitCodeFor(code) {
67
+ return REFUSALS.has(code) ? 2 : 1;
68
+ }
69
+ var WorkkitError = class extends Error {
70
+ code;
71
+ details;
72
+ constructor(code, message, details) {
73
+ super(message);
74
+ this.name = "WorkkitError";
75
+ this.code = code;
76
+ if (details) this.details = details;
77
+ }
78
+ };
79
+ function toErrorBody(err) {
80
+ if (err instanceof WorkkitError) {
81
+ return err.details ? { code: err.code, message: err.message, details: err.details } : { code: err.code, message: err.message };
82
+ }
83
+ return { code: "INTERNAL", message: err instanceof Error ? err.message : String(err) };
84
+ }
85
+
86
+ // src/core/git.ts
87
+ import { spawnSync } from "child_process";
88
+ import { existsSync, mkdirSync, realpathSync, rmSync, statSync } from "fs";
89
+ import { dirname, join, resolve, sep } from "path";
90
+ var realpathOr = (p) => {
91
+ try {
92
+ return realpathSync(p);
93
+ } catch {
94
+ return p;
95
+ }
96
+ };
97
+ var SAFE_SUBMODULE_NAME = /^[^\p{Cc}\s=]+$/u;
98
+ var Git = class _Git {
99
+ constructor(cwd) {
100
+ this.cwd = cwd;
101
+ }
102
+ cwd;
103
+ tryRun(args) {
104
+ const r = spawnSync("git", args, { cwd: this.cwd, encoding: "utf8" });
105
+ return { code: r.status ?? 1, out: r.stdout ?? "", err: r.stderr ?? "" };
106
+ }
107
+ run(args) {
108
+ const r = this.tryRun(args);
109
+ if (r.code !== 0) {
110
+ throw new WorkkitError(
111
+ "GIT_FAILED",
112
+ `git ${args.join(" ")} (in ${this.cwd}): ${r.err.trim() || r.out.trim()}`,
113
+ {
114
+ args,
115
+ cwd: this.cwd
116
+ }
117
+ );
118
+ }
119
+ return r.out;
120
+ }
121
+ lines(args) {
122
+ return this.run(args).split("\n").map((l) => l.trim()).filter(Boolean);
123
+ }
124
+ /** The checkout's top level (symlinks resolved). */
125
+ root() {
126
+ return realpathSync(this.run(["rev-parse", "--show-toplevel"]).trim());
127
+ }
128
+ /** The main checkout's top level, from any worktree of the repo. */
129
+ mainRoot() {
130
+ const common = realpathSync(
131
+ this.run(["rev-parse", "--path-format=absolute", "--git-common-dir"]).trim()
132
+ );
133
+ return dirname(common);
134
+ }
135
+ /** The main checkout is the one whose git dir IS the common dir (compared as absolute realpaths). */
136
+ isMainCheckout() {
137
+ const gitDir = realpathSync(
138
+ this.run(["rev-parse", "--path-format=absolute", "--git-dir"]).trim()
139
+ );
140
+ const common = realpathSync(
141
+ this.run(["rev-parse", "--path-format=absolute", "--git-common-dir"]).trim()
142
+ );
143
+ return gitDir === common;
144
+ }
145
+ currentBranch() {
146
+ return this.run(["branch", "--show-current"]).trim();
147
+ }
148
+ branchExists(name) {
149
+ return this.tryRun(["rev-parse", "--verify", "-q", `refs/heads/${name}`]).code === 0;
150
+ }
151
+ remoteBranchExists(name) {
152
+ return this.run(["ls-remote", "--heads", "origin", name]).trim().length > 0;
153
+ }
154
+ fetch(branch) {
155
+ this.run(["fetch", "-q", "origin", branch]);
156
+ }
157
+ hasUpstream() {
158
+ return this.tryRun(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"]).code === 0;
159
+ }
160
+ /** Commits on HEAD that origin does not have: against the upstream, else the same-named remote branch, else origin/<base>. */
161
+ unpushedCount(base) {
162
+ let ref = `origin/${base}`;
163
+ if (this.hasUpstream()) ref = "@{u}";
164
+ else if (this.remoteBranchExists(this.currentBranch())) ref = `origin/${this.currentBranch()}`;
165
+ return this.lines(["rev-list", `${ref}..HEAD`]).length;
166
+ }
167
+ isDirty() {
168
+ return this.run(["status", "--porcelain"]).trim().length > 0;
169
+ }
170
+ changedPathsStaged() {
171
+ return this.lines(["diff", "--cached", "--name-only"]);
172
+ }
173
+ changedPaths(from, to) {
174
+ return this.lines(["diff", "--name-only", "--no-renames", from, to]);
175
+ }
176
+ /** Paths this branch changed since it diverged from origin/<base> (three-dot), without the base's own changes. */
177
+ changedSince(base) {
178
+ return this.lines(["diff", "--name-only", "--no-renames", `origin/${base}...HEAD`]);
179
+ }
180
+ commitsNotOn(base) {
181
+ return this.lines(["rev-list", `origin/${base}..HEAD`]);
182
+ }
183
+ rev(ref) {
184
+ return this.run(["rev-parse", ref]).trim();
185
+ }
186
+ /** Fast-forward when HEAD has no own commits, otherwise merge; never rebase. A conflict is left in place. */
187
+ syncFrom(base) {
188
+ const target = `origin/${base}`;
189
+ const before = this.rev("HEAD");
190
+ const targetRev = this.rev(target);
191
+ if (before === targetRev) return { kind: "up-to-date", before, after: before, conflicted: [] };
192
+ if (this.tryRun(["merge-base", "--is-ancestor", "HEAD", target]).code === 0) {
193
+ this.run(["merge", "--ff-only", "-q", target]);
194
+ return { kind: "ff", before, after: this.rev("HEAD"), conflicted: [] };
195
+ }
196
+ if (this.tryRun(["merge-base", "--is-ancestor", target, "HEAD"]).code === 0) {
197
+ return { kind: "up-to-date", before, after: before, conflicted: [] };
198
+ }
199
+ const merged = this.tryRun(["merge", "--no-edit", "-q", target]);
200
+ if (merged.code === 0)
201
+ return { kind: "merge", before, after: this.rev("HEAD"), conflicted: [] };
202
+ const conflicted = this.lines(["diff", "--name-only", "--diff-filter=U"]);
203
+ return { kind: "conflict", before, after: before, conflicted };
204
+ }
205
+ worktreeAdd(path, branch, startPoint) {
206
+ mkdirSync(dirname(path), { recursive: true });
207
+ if (this.branchExists(branch)) this.run(["worktree", "add", "-q", path, branch]);
208
+ else
209
+ this.run(["worktree", "add", "-q", "--no-track", "-b", branch, path, startPoint ?? "HEAD"]);
210
+ }
211
+ worktreeRemove(path) {
212
+ this.run(["worktree", "remove", "--force", path]);
213
+ }
214
+ checkout(branch, createFrom) {
215
+ if (this.branchExists(branch)) this.run(["checkout", "-q", branch]);
216
+ else this.run(["checkout", "-q", "--no-track", "-b", branch, createFrom ?? "HEAD"]);
217
+ }
218
+ push(branch) {
219
+ this.run(["push", "-q", "-u", "origin", branch]);
220
+ }
221
+ deleteLocalBranch(branch) {
222
+ this.run(["branch", "-q", "-D", branch]);
223
+ }
224
+ isAncestor(ancestor, descendant) {
225
+ return this.tryRun(["merge-base", "--is-ancestor", ancestor, descendant]).code === 0;
226
+ }
227
+ /** True when HEAD's tree matches origin/<base>, or every commit on HEAD is patch-equivalent to origin/<base> (squash-merged). */
228
+ isEquivalentToBase(base) {
229
+ const target = `origin/${base}`;
230
+ if (this.tryRun(["diff", "--quiet", target, "HEAD"]).code === 0) return true;
231
+ const cherry = this.tryRun(["cherry", target, "HEAD"]);
232
+ if (cherry.code !== 0) return false;
233
+ const lines = cherry.out.split("\n").map((l) => l.trim()).filter(Boolean);
234
+ return lines.length > 0 && lines.every((l) => l.startsWith("- "));
235
+ }
236
+ /**
237
+ * Give a linked worktree its own clone of every submodule the main checkout has initialized,
238
+ * cloned locally from the main checkout's module directory (no network) and then re-pointed at
239
+ * the real URL. `git worktree add` under submodule.recurse leaves a gitfile aimed at a module
240
+ * directory that was never cloned; a gitfile aimed at the MAIN checkout's module directory is
241
+ * worse, because that module's core.worktree is the main checkout's submodule, so any git
242
+ * command in the worktree's submodule (checkout -f, reset, merge) rewrites the human's files.
243
+ * Both shapes are replaced; a submodule that is already its own working tree is left alone.
244
+ */
245
+ repairSubmodules(mainRoot, log = () => {
246
+ }) {
247
+ const gitmodules = join(this.cwd, ".gitmodules");
248
+ if (!existsSync(gitmodules)) return;
249
+ const cfg = this.tryRun([
250
+ "config",
251
+ "-f",
252
+ ".gitmodules",
253
+ "--get-regexp",
254
+ "^submodule\\..*\\.path$"
255
+ ]);
256
+ if (cfg.code !== 0) return;
257
+ const wtGitDir = this.run(["rev-parse", "--path-format=absolute", "--git-dir"]).trim();
258
+ for (const line of cfg.out.split("\n").filter(Boolean)) {
259
+ const m = /^submodule\.(.+)\.path\s+(.+)$/.exec(line.trim());
260
+ if (!m) continue;
261
+ const [, name, subPath] = m;
262
+ const modulesDir = resolve(wtGitDir, "modules");
263
+ const moduleDir = resolve(modulesDir, name);
264
+ if (!SAFE_SUBMODULE_NAME.test(name) || name.split(/[\\/]/).some((seg) => seg === "" || seg === "." || seg === "..") || !moduleDir.startsWith(modulesDir + sep)) {
265
+ log(`submodule ${subPath}: refusing name ${JSON.stringify(name)}; not repaired`);
266
+ continue;
267
+ }
268
+ const wtSub = join(this.cwd, subPath);
269
+ const wtGit = join(wtSub, ".git");
270
+ if (this.isOwnSubmodule(wtSub, wtGit)) continue;
271
+ const mainSub = join(mainRoot, subPath);
272
+ if (!existsSync(join(mainSub, ".git"))) continue;
273
+ const src = new _Git(mainSub).tryRun(["rev-parse", "--path-format=absolute", "--git-dir"]);
274
+ if (src.code !== 0 || !src.out.trim()) continue;
275
+ if (existsSync(wtGit) && statSync(wtGit).isFile()) rmSync(wtGit);
276
+ rmSync(moduleDir, { recursive: true, force: true });
277
+ const r = this.tryRun([
278
+ "-c",
279
+ "protocol.file.allow=always",
280
+ "-c",
281
+ `submodule.${name}.url=${src.out.trim()}`,
282
+ "submodule",
283
+ "update",
284
+ "--init",
285
+ "--",
286
+ subPath
287
+ ]);
288
+ if (r.code !== 0) {
289
+ log(
290
+ `submodule ${subPath}: not repaired (${(r.err || r.out).trim()}); the project's refresh steps may still set it up`
291
+ );
292
+ continue;
293
+ }
294
+ this.tryRun(["submodule", "sync", "-q", "--", subPath]);
295
+ }
296
+ }
297
+ /** A submodule is the worktree's own when git, run inside it, says its top level IS that directory. */
298
+ isOwnSubmodule(wtSub, wtGit) {
299
+ if (!existsSync(wtGit)) return false;
300
+ const top = new _Git(wtSub).tryRun(["rev-parse", "--show-toplevel"]);
301
+ if (top.code !== 0) return false;
302
+ return realpathOr(top.out.trim()) === realpathOr(wtSub);
303
+ }
304
+ };
305
+
306
+ // src/core/config.ts
307
+ function renderTemplate(s, vars) {
308
+ return s.replace(/\$\{([A-Z0-9_]+)\}/g, (_, name) => {
309
+ if (!(name in vars)) {
310
+ throw new WorkkitError(
311
+ "MANIFEST_INVALID",
312
+ `template references ${name}, which this effort does not define`
313
+ );
314
+ }
315
+ return vars[name];
316
+ });
317
+ }
318
+ function storybookHostFor(m, worktree) {
319
+ if (!worktree) return "";
320
+ return m.storybook?.hostRoot ? join2(worktree, m.storybook.hostRoot) : worktree;
321
+ }
322
+ function slotVars(m, o) {
323
+ const vars = {
324
+ SLOT: o.slot === void 0 ? "" : String(o.slot),
325
+ PROJECT: m.project,
326
+ AREA: o.area ?? "",
327
+ BRANCH: o.branch ?? "",
328
+ WORKTREE: o.worktree ?? "",
329
+ LOG_DIR: o.logDir ?? "",
330
+ PORT_STORYBOOK: o.storybookPort === void 0 ? "" : String(o.storybookPort),
331
+ STORYBROKR_HOST: storybookHostFor(m, o.worktree)
332
+ };
333
+ for (const service of Object.keys(m.ports.services)) {
334
+ const p = o.ports[service];
335
+ vars[`PORT_${service.toUpperCase()}`] = p === void 0 ? "" : String(p);
336
+ }
337
+ return vars;
338
+ }
339
+ function ensureExcluded(worktree, patterns) {
340
+ const r = new Git(worktree).tryRun(["rev-parse", "--path-format=absolute", "--git-common-dir"]);
341
+ if (r.code !== 0) return;
342
+ const common = realpathSync2(r.out.trim());
343
+ const file = join2(common, "info", "exclude");
344
+ mkdirSync2(join2(common, "info"), { recursive: true });
345
+ const present = new Set(
346
+ existsSync2(file) ? readFileSync(file, "utf8").split("\n").map((l) => l.trim()) : []
347
+ );
348
+ const missing = patterns.filter((p) => !present.has(p));
349
+ if (missing.length === 0) return;
350
+ appendFileSync(
351
+ file,
352
+ `${present.size ? "\n" : ""}# written by @helmsmith/workbrokr: per-worktree config and logs
353
+ ${missing.join("\n")}
354
+ `
355
+ );
356
+ }
357
+ function emitWorktreeConfig(a) {
358
+ ensureExcluded(a.worktree, [
359
+ ".slot",
360
+ a.m.env.file,
361
+ `${a.m.logs.dir.replace(/\/+$/, "")}/`,
362
+ `${a.m.worktreeRoot.replace(/\/+$/, "")}/`
363
+ ]);
364
+ const logDir = join2(a.worktree, a.m.logs.dir);
365
+ mkdirSync2(logDir, { recursive: true });
366
+ const vars = slotVars(a.m, { ...a, logDir });
367
+ const envFile = join2(a.worktree, a.m.env.file);
368
+ const lines = Object.entries(a.m.env.template).map(([k, v]) => `${k}=${renderTemplate(v, vars)}`);
369
+ writeFileSync(envFile, `${lines.join("\n")}
370
+ `);
371
+ let slotFile;
372
+ if (a.slot !== void 0) {
373
+ slotFile = join2(a.worktree, ".slot");
374
+ writeFileSync(slotFile, `${a.slot}
375
+ `);
376
+ }
377
+ return slotFile ? { envFile, slotFile, logDir, vars } : { envFile, logDir, vars };
378
+ }
379
+
380
+ // src/core/guards.ts
381
+ import { existsSync as existsSync3, realpathSync as realpathSync3 } from "fs";
382
+
383
+ // src/core/scopes.ts
384
+ import picomatch from "picomatch";
385
+ function areaVars(area) {
386
+ const parts = area.split("/");
387
+ return { group: parts.slice(0, -1).join("/"), section: parts[parts.length - 1] };
388
+ }
389
+ function fill(template, vars) {
390
+ let missing = false;
391
+ const out = template.replace(/\{(group|section|module)\}/g, (_, name) => {
392
+ const v = vars[name];
393
+ if (v === void 0 || v === "") {
394
+ missing = true;
395
+ return "";
396
+ }
397
+ return v;
398
+ });
399
+ return missing ? null : out;
400
+ }
401
+ function extraScopesForMode(spec, mode) {
402
+ if (!spec.extraScopes) return [];
403
+ if (Array.isArray(spec.extraScopes)) {
404
+ return mode === "frontend" || mode === "fullstack" ? spec.extraScopes : [];
405
+ }
406
+ const out = [];
407
+ if (mode === "frontend" || mode === "fullstack") out.push(...spec.extraScopes.frontend ?? []);
408
+ if (mode === "backend" || mode === "fullstack") out.push(...spec.extraScopes.backend ?? []);
409
+ return out;
410
+ }
411
+ var normalizeGlob = (g) => g.replace(/^\.\//, "").replace(/\/+$/, "");
412
+ var hasWildcard = (s) => /[*?[{]/.test(s);
413
+ function isSubGlob(child, parent) {
414
+ const c = normalizeGlob(child);
415
+ const p = normalizeGlob(parent);
416
+ if (c === p) return true;
417
+ const cSegs = c.split("/");
418
+ const pSegs = p.split("/");
419
+ for (let i = 0; i < pSegs.length; i++) {
420
+ const ps = pSegs[i];
421
+ if (ps === "**") return true;
422
+ const cs = cSegs[i];
423
+ if (cs === void 0 || cs === "**") return false;
424
+ if (!hasWildcard(ps) && !hasWildcard(cs)) {
425
+ if (ps !== cs) return false;
426
+ continue;
427
+ }
428
+ if (!hasWildcard(cs) && hasWildcard(ps)) {
429
+ if (!picomatch.isMatch(cs, ps, { dot: true })) return false;
430
+ continue;
431
+ }
432
+ if (cs !== ps) return false;
433
+ }
434
+ return cSegs.length === pSegs.length;
435
+ }
436
+ function expandScopes(m, area, mode, narrowedScopes, hasTask = false) {
437
+ const spec = m.areas[area];
438
+ if (!spec)
439
+ throw new WorkkitError(
440
+ "AREA_UNKNOWN",
441
+ `unknown area "${area}" (known: ${Object.keys(m.areas).join(", ")})`
442
+ );
443
+ const vars = { ...areaVars(area), module: spec.module };
444
+ const out = [];
445
+ if (mode === "frontend" || mode === "fullstack") {
446
+ for (const t of m.scopes.frontend) {
447
+ const g = fill(t, vars);
448
+ if (g) out.push(g);
449
+ }
450
+ }
451
+ if (mode === "backend" || mode === "fullstack") {
452
+ if (!spec.module) {
453
+ throw new WorkkitError(
454
+ "MANIFEST_INVALID",
455
+ `area "${area}" has no module, so a ${mode} effort cannot hold a backend scope; add areas["${area}"].module or use --mode frontend`
456
+ );
457
+ }
458
+ for (const t of m.scopes.backend) {
459
+ const g = fill(t, vars);
460
+ if (g) out.push(g);
461
+ }
462
+ }
463
+ out.push(...extraScopesForMode(spec, mode));
464
+ if (!narrowedScopes || narrowedScopes.length === 0) return out;
465
+ if (!hasTask) {
466
+ throw new WorkkitError(
467
+ "SCOPE_REQUIRES_TASK",
468
+ "--scope narrowing requires --task <slug> so primary area efforts always protect the full area"
469
+ );
470
+ }
471
+ const allowed = [...out, ...spec.sharedScopes ?? []];
472
+ for (const g of narrowedScopes) {
473
+ if (!allowed.some((base) => isSubGlob(g, base))) {
474
+ throw new WorkkitError(
475
+ "SCOPE_OUTSIDE_AREA",
476
+ `narrowed scope "${g}" is outside ${area}'s ${mode} scopes (${allowed.join(", ")})`,
477
+ { area, mode, scope: g, allowed }
478
+ );
479
+ }
480
+ }
481
+ return narrowedScopes;
482
+ }
483
+ function allowedScopesForEffort(m, effort) {
484
+ const shared = m.areas[effort.area]?.sharedScopes ?? [];
485
+ const allCommons = Object.values(m.commons).flat();
486
+ return [...effort.scopes, ...shared, ...allCommons];
487
+ }
488
+ function segmentsOverlap(sx, sy) {
489
+ if (sx === sy) return true;
490
+ const wx = hasWildcard(sx);
491
+ const wy = hasWildcard(sy);
492
+ if (!wx && !wy) return false;
493
+ if (!wx && wy) return picomatch.isMatch(sx, sy, { dot: true });
494
+ if (wx && !wy) return picomatch.isMatch(sy, sx, { dot: true });
495
+ const starToken = /^\*([^*?[{]+)\*$/;
496
+ const mx = starToken.exec(sx);
497
+ const my = starToken.exec(sy);
498
+ if (mx && my) {
499
+ const tx = mx[1];
500
+ const ty = my[1];
501
+ return tx.includes(ty) || ty.includes(tx);
502
+ }
503
+ return true;
504
+ }
505
+ function twoGlobsOverlap(x, y) {
506
+ const xs = normalizeGlob(x).split("/");
507
+ const ys = normalizeGlob(y).split("/");
508
+ const len = Math.min(xs.length, ys.length);
509
+ for (let i = 0; i < len; i++) {
510
+ if (xs[i] === "**" || ys[i] === "**") return true;
511
+ if (!segmentsOverlap(xs[i], ys[i])) return false;
512
+ }
513
+ if (xs.length === ys.length) return true;
514
+ const longer = xs.length > ys.length ? xs : ys;
515
+ return longer[len] === "**";
516
+ }
517
+ function globsOverlap(a, b) {
518
+ const pairs = [];
519
+ for (const x of a) {
520
+ for (const y of b) {
521
+ if (twoGlobsOverlap(x, y)) pairs.push(`${x} ~ ${y}`);
522
+ }
523
+ }
524
+ return pairs;
525
+ }
526
+ function pathsMatching(paths, globs) {
527
+ if (globs.length === 0) return [];
528
+ const isMatch = picomatch(globs, { dot: true });
529
+ return paths.filter((p) => isMatch(p));
530
+ }
531
+ function commonsTouched(m, paths) {
532
+ return Object.entries(m.commons).filter(([, globs]) => pathsMatching(paths, globs).length > 0).map(([name]) => name);
533
+ }
534
+
535
+ // src/core/guards.ts
536
+ function assertNotProtected(m, branch) {
537
+ if (m.protectedBranches.includes(branch)) {
538
+ throw new WorkkitError(
539
+ "PROTECTED_BRANCH",
540
+ `branch "${branch}" is protected (${m.protectedBranches.join(", ")}): work happens on <type>/<area> branches, never here`,
541
+ { branch }
542
+ );
543
+ }
544
+ }
545
+ var same = (a, b) => {
546
+ try {
547
+ return realpathSync3(a) === realpathSync3(b);
548
+ } catch {
549
+ return a === b;
550
+ }
551
+ };
552
+ var effortLabel = (e) => e.task ? `${e.area}--${e.task}` : e.area;
553
+ function checkCommit(c) {
554
+ const refusals = [];
555
+ const warnings = [];
556
+ if (c.m.protectedBranches.includes(c.branch)) {
557
+ refusals.push(
558
+ `branch "${c.branch}" is protected (${c.m.protectedBranches.join(", ")}): work happens on <type>/<area> branches, never here`
559
+ );
560
+ }
561
+ const allEfforts = c.registry.efforts({ project: c.project });
562
+ const efforts = new Map(allEfforts.map((e) => [e.id, e]));
563
+ for (const lease of c.registry.leases({ project: c.project, kind: "commons" })) {
564
+ const holder = efforts.get(lease.effort);
565
+ const holderHasWorktree = Boolean(holder && existsSync3(holder.worktree));
566
+ if (holder && holderHasWorktree && c.checkoutRoot) {
567
+ if (same(holder.worktree, c.checkoutRoot)) continue;
568
+ } else if (lease.owner.session === c.ownerSession) {
569
+ continue;
570
+ }
571
+ const globs = c.m.commons[String(lease.value)] ?? [];
572
+ const hit = pathsMatching(c.stagedPaths, globs);
573
+ if (hit.length > 0) {
574
+ refusals.push(
575
+ `commons "${lease.value}" is write-locked by ${lease.owner.session} (effort ${lease.effort}, since ${lease.touched}); staged: ${hit.join(", ")}`
576
+ );
577
+ }
578
+ }
579
+ const openEfforts = allEfforts.filter((e) => e.state === "active" || e.state === "starting");
580
+ for (const other of openEfforts) {
581
+ if (c.checkoutRoot && existsSync3(other.worktree) && same(other.worktree, c.checkoutRoot)) {
582
+ continue;
583
+ }
584
+ if (!c.checkoutRoot && other.branch === c.branch) continue;
585
+ const hit = pathsMatching(c.stagedPaths, other.scopes);
586
+ if (hit.length > 0) {
587
+ refusals.push(
588
+ `path(s) ${hit.join(", ")} are inside the active scope of ${effortLabel(other)} (${other.branch}, owned by ${other.owner.session})`
589
+ );
590
+ }
591
+ }
592
+ const mine = openEfforts.find(
593
+ (e) => c.checkoutRoot && existsSync3(e.worktree) ? same(e.worktree, c.checkoutRoot) : e.branch === c.branch
594
+ );
595
+ if (mine && c.stagedPaths.length > 0) {
596
+ const allowed = allowedScopesForEffort(c.m, mine);
597
+ const inScope = new Set(pathsMatching(c.stagedPaths, allowed));
598
+ const outside = c.stagedPaths.filter((p) => !inScope.has(p));
599
+ if (outside.length > 0) {
600
+ warnings.push(
601
+ `${outside.length} staged path(s) are outside the effort's scope (${effortLabel(mine)}): ${outside.join(", ")}`
602
+ );
603
+ }
604
+ }
605
+ return { refusals, warnings };
606
+ }
607
+ function checkPush(c) {
608
+ const refusals = [];
609
+ const warnings = [];
610
+ const destination = (c.remoteRef ?? `refs/heads/${c.branch}`).replace(/^refs\/heads\//, "");
611
+ if (c.m.protectedBranches.includes(destination)) {
612
+ refusals.push(
613
+ c.isDelete ? `refusing to delete protected branch "${destination}"` : `"${destination}" is protected (${c.m.protectedBranches.join(", ")}): nothing is pushed to it directly, open a PR from ${c.branch || "an area branch"}`
614
+ );
615
+ return { refusals, warnings };
616
+ }
617
+ if (c.isDelete) return { refusals, warnings };
618
+ const effort = c.registry.efforts({ project: c.project }).find((e) => (e.state === "active" || e.state === "parked") && e.branch === c.branch);
619
+ const commons = commonsTouched(c.m, c.changedPaths);
620
+ if (effort) {
621
+ const allowed = allowedScopesForEffort(c.m, effort);
622
+ const inScope = new Set(pathsMatching(c.changedPaths, allowed));
623
+ const outside = c.changedPaths.filter((p) => !inScope.has(p));
624
+ if (outside.length > 0) {
625
+ warnings.push(
626
+ `${outside.length} changed path(s) are outside the effort's scope (${effortLabel(effort)}): ${outside.join(", ")} \u2014 add a scope template or expect a merge collision`
627
+ );
628
+ }
629
+ }
630
+ for (const name of commons)
631
+ warnings.push(`commons ${name} touched: the other areas are told at \`work finish\``);
632
+ return { refusals, warnings };
633
+ }
634
+
635
+ // src/core/hooks.ts
636
+ import { chmodSync, lstatSync, mkdirSync as mkdirSync3, writeFileSync as writeFileSync2 } from "fs";
637
+ import { join as join4 } from "path";
638
+
639
+ // src/core/manifest.ts
640
+ import { existsSync as existsSync4, readFileSync as readFileSync2 } from "fs";
641
+ import { join as join3 } from "path";
642
+ import { pathToFileURL } from "url";
643
+ import { z } from "zod";
644
+ var MANIFEST_FILES = [
645
+ "helmsmith.config.ts",
646
+ "helmsmith.config.mjs",
647
+ "helmsmith.config.json"
648
+ ];
649
+ var BRANCH_NAME = /^[A-Za-z0-9][A-Za-z0-9._/-]*$/;
650
+ var BRANCH_NAME_HINT = 'must be a plain ref name: letters, digits, ".", "_", "/", "-"';
651
+ var TASK_SLUG = /^(?!.*--)[a-z0-9][a-z0-9_-]{0,47}$/;
652
+ var Service = z.object({
653
+ start: z.string().min(1),
654
+ stop: z.string().min(1),
655
+ health: z.string().min(1),
656
+ healthyCodes: z.array(z.number().int()).optional(),
657
+ reset: z.string().optional(),
658
+ healthTimeoutMs: z.number().int().positive().optional(),
659
+ modes: z.array(z.enum(["backend", "fullstack"])).optional()
660
+ });
661
+ var ExtraScopes = z.union([
662
+ z.array(z.string()),
663
+ z.object({
664
+ frontend: z.array(z.string()).optional(),
665
+ backend: z.array(z.string()).optional()
666
+ })
667
+ ]);
668
+ var Schema = z.object({
669
+ project: z.string().regex(/^[a-z0-9][a-z0-9-]*$/),
670
+ baseBranch: z.string().regex(BRANCH_NAME, BRANCH_NAME_HINT),
671
+ protectedBranches: z.array(z.string().regex(BRANCH_NAME, BRANCH_NAME_HINT)).optional(),
672
+ worktreeRoot: z.string().default(".claude/worktrees"),
673
+ branch: z.object({ types: z.array(z.string().regex(/^[a-z]+$/)).min(1) }).default({ types: ["feature", "chore", "fix"] }),
674
+ slots: z.object({
675
+ count: z.number().int().min(1).max(100),
676
+ reserved: z.array(z.number().int().min(0))
677
+ }).default({ count: 10, reserved: [0] }),
678
+ ports: z.object({
679
+ services: z.record(z.string(), z.object({ base: z.number().int().min(1024).max(65535) }))
680
+ }),
681
+ services: z.record(z.string(), Service),
682
+ storybook: z.object({ hostRoot: z.string() }).optional(),
683
+ logs: z.object({ dir: z.string() }).default({ dir: ".logs" }),
684
+ env: z.object({ file: z.string(), template: z.record(z.string(), z.string()) }).optional(),
685
+ seed: z.array(z.string().min(1)).optional(),
686
+ refresh: z.array(
687
+ z.object({
688
+ when: z.string().optional(),
689
+ always: z.boolean().optional(),
690
+ run: z.string().optional(),
691
+ mark: z.string().optional(),
692
+ restoreWhenIfClean: z.boolean().optional()
693
+ })
694
+ ).default([]),
695
+ scopes: z.object({ frontend: z.array(z.string()), backend: z.array(z.string()) }),
696
+ areas: z.record(
697
+ z.string().regex(/^(?!.*--)[a-z0-9-]+(\/[a-z0-9-]+)*$/),
698
+ z.object({
699
+ module: z.string().optional(),
700
+ commons: z.array(z.string()).optional(),
701
+ extraScopes: ExtraScopes.optional(),
702
+ sharedScopes: z.array(z.string()).optional()
703
+ })
704
+ ),
705
+ commons: z.record(z.string(), z.array(z.string())).default({}),
706
+ expiry: z.object({
707
+ slotHours: z.number().positive(),
708
+ commonsHours: z.number().positive(),
709
+ storybookHours: z.number().positive()
710
+ }).default({ slotHours: 12, commonsHours: 4, storybookHours: 2 }),
711
+ archive: z.object({
712
+ paths: z.array(z.string()),
713
+ keepDays: z.number().int().positive(),
714
+ keepPerArea: z.number().int().positive()
715
+ }).default({ paths: [], keepDays: 30, keepPerArea: 5 })
716
+ });
717
+ function templateVariables(m) {
718
+ const vars = /* @__PURE__ */ new Set([
719
+ "SLOT",
720
+ "LOG_DIR",
721
+ "PROJECT",
722
+ "AREA",
723
+ "BRANCH",
724
+ "WORKTREE",
725
+ "PORT_STORYBOOK",
726
+ "STORYBROKR_HOST"
727
+ ]);
728
+ for (const s of Object.keys(m.ports.services)) vars.add(`PORT_${s.toUpperCase()}`);
729
+ return vars;
730
+ }
731
+ function defaultEnv(services) {
732
+ const template = {
733
+ // biome-ignore lint/suspicious/noTemplateCurlyInString: manifest template placeholder
734
+ SLOT: "${SLOT}",
735
+ // biome-ignore lint/suspicious/noTemplateCurlyInString: manifest template placeholder
736
+ LOG_DIR: "${LOG_DIR}",
737
+ // biome-ignore lint/suspicious/noTemplateCurlyInString: manifest template placeholder
738
+ STORYBROKR_HOST: "${STORYBROKR_HOST}"
739
+ };
740
+ for (const s of services) template[`PORT_${s.toUpperCase()}`] = `\${PORT_${s.toUpperCase()}}`;
741
+ return { file: ".env.slot", template };
742
+ }
743
+ function validateManifest(raw) {
744
+ const parsed = Schema.safeParse(raw);
745
+ if (!parsed.success) {
746
+ throw new WorkkitError(
747
+ "MANIFEST_INVALID",
748
+ parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ")
749
+ );
750
+ }
751
+ const m = parsed.data;
752
+ const problems = [];
753
+ const areas = Object.keys(m.areas).sort();
754
+ for (const a of areas) {
755
+ for (const b of areas) {
756
+ if (a !== b && b.startsWith(`${a}/`)) {
757
+ problems.push(`area "${a}" is an ancestor of "${b}": areas must be leaves`);
758
+ }
759
+ }
760
+ }
761
+ for (const s of Object.keys(m.services)) {
762
+ if (!m.ports.services[s]) problems.push(`service "${s}" has no port base under ports.services`);
763
+ }
764
+ for (const s of Object.keys(m.ports.services)) {
765
+ if (!m.services[s] && s !== "storybook") problems.push(`port "${s}" names no service`);
766
+ }
767
+ for (const r of m.slots.reserved) {
768
+ if (r >= m.slots.count) problems.push(`reserved slot ${r} is outside 0..${m.slots.count - 1}`);
769
+ }
770
+ const env = m.env ?? defaultEnv(Object.keys(m.ports.services));
771
+ const allowed = templateVariables(m);
772
+ for (const [k, v] of Object.entries(env.template)) {
773
+ for (const [, name] of v.matchAll(/\$\{([A-Z0-9_]+)\}/g)) {
774
+ if (!allowed.has(name)) {
775
+ problems.push(
776
+ `env.template.${k} references ${name}, which no slot derives (allowed: ${[...allowed].join(", ")})`
777
+ );
778
+ }
779
+ }
780
+ }
781
+ for (const [area, spec] of Object.entries(m.areas)) {
782
+ for (const c of spec.commons ?? []) {
783
+ if (!m.commons[c])
784
+ problems.push(`area "${area}" names commons "${c}", which is not declared`);
785
+ }
786
+ }
787
+ if (problems.length) throw new WorkkitError("MANIFEST_INVALID", problems.join("; "));
788
+ return { ...m, protectedBranches: m.protectedBranches ?? [m.baseBranch], env };
789
+ }
790
+ async function loadManifest(repoRoot) {
791
+ for (const name of MANIFEST_FILES) {
792
+ const file = join3(repoRoot, name);
793
+ if (!existsSync4(file)) continue;
794
+ if (name.endsWith(".json")) return validateManifest(JSON.parse(readFileSync2(file, "utf8")));
795
+ const mod = await import(`${pathToFileURL(file).href}?t=${Date.now()}`);
796
+ return validateManifest(mod.default);
797
+ }
798
+ throw new WorkkitError(
799
+ "MANIFEST_NOT_FOUND",
800
+ `no ${MANIFEST_FILES.join(" | ")} in ${repoRoot}; run \`work init\``
801
+ );
802
+ }
803
+
804
+ // src/core/hooks.ts
805
+ var HOOKS_DIR = ".helmsmith/hooks";
806
+ function preCommitScript(protectedBranches) {
807
+ return `#!/bin/sh
808
+ # Installed by \`work init\` (@helmsmith/workbrokr). The protected-branch rule lives here; the rest in workbrokr.
809
+ PROTECTED="${protectedBranches.join(" ")}"
810
+ branch=$(git symbolic-ref --short -q HEAD)
811
+ for p in $PROTECTED; do
812
+ if [ "$branch" = "$p" ]; then
813
+ echo "work: branch \\"$branch\\" is protected ($PROTECTED): work happens on <type>/<area> branches, never here" >&2
814
+ exit 2
815
+ fi
816
+ done
817
+ if command -v workbrokr >/dev/null 2>&1; then
818
+ workbrokr hook pre-commit "$@" || exit $?
819
+ else
820
+ echo "work: workbrokr is not on PATH; commons and scope checks skipped (npm i -g @helmsmith/workbrokr)" >&2
821
+ fi
822
+ COMMON_DIR=$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null)
823
+ LEGACY="$COMMON_DIR/hooks/pre-commit"
824
+ if [ -n "$COMMON_DIR" ] && [ -x "$LEGACY" ]; then
825
+ SELF_DIR=$(cd "$(dirname "$0")" && pwd)
826
+ LEGACY_DIR=$(cd "$(dirname "$LEGACY")" && pwd)
827
+ if [ "$SELF_DIR" != "$LEGACY_DIR" ]; then
828
+ exec "$LEGACY" "$@"
829
+ fi
830
+ fi
831
+ exit 0
832
+ `;
833
+ }
834
+ function prePushScript(protectedBranches) {
835
+ return `#!/bin/sh
836
+ # Installed by \`work init\` (@helmsmith/workbrokr). Refuses a push to, or a delete of, a protected branch here; the rest in workbrokr.
837
+ PROTECTED="${protectedBranches.join(" ")}"
838
+ input=$(cat)
839
+ printf '%s\\n' "$input" | while read -r lref lsha rref rsha; do
840
+ [ -n "$rref" ] || continue
841
+ dest=\${rref#refs/heads/}
842
+ for p in $PROTECTED; do
843
+ if [ "$dest" = "$p" ]; then
844
+ echo "work: \\"$dest\\" is protected ($PROTECTED): nothing is pushed to it directly, open a PR from an area branch" >&2
845
+ exit 2
846
+ fi
847
+ done
848
+ done || exit 2
849
+ if command -v workbrokr >/dev/null 2>&1; then
850
+ printf '%s\\n' "$input" | workbrokr hook pre-push "$@" || exit $?
851
+ else
852
+ echo "work: workbrokr is not on PATH; scope and commons warnings skipped" >&2
853
+ fi
854
+ COMMON_DIR=$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null)
855
+ LEGACY="$COMMON_DIR/hooks/pre-push"
856
+ if [ -n "$COMMON_DIR" ] && [ -x "$LEGACY" ]; then
857
+ SELF_DIR=$(cd "$(dirname "$0")" && pwd)
858
+ LEGACY_DIR=$(cd "$(dirname "$LEGACY")" && pwd)
859
+ if [ "$SELF_DIR" != "$LEGACY_DIR" ]; then
860
+ printf '%s\\n' "$input" | exec "$LEGACY" "$@"
861
+ fi
862
+ fi
863
+ exit 0
864
+ `;
865
+ }
866
+ function installHooks(repoRoot, opts) {
867
+ for (const b of opts.protectedBranches) {
868
+ if (!BRANCH_NAME.test(b))
869
+ throw new WorkkitError("MANIFEST_INVALID", `protected branch "${b}" is not a plain ref name`);
870
+ }
871
+ const hooksDir = join4(repoRoot, HOOKS_DIR);
872
+ mkdirSync3(hooksDir, { recursive: true });
873
+ const files = [];
874
+ const scripts = [
875
+ ["pre-commit", preCommitScript(opts.protectedBranches)],
876
+ ["pre-push", prePushScript(opts.protectedBranches)]
877
+ ];
878
+ for (const [name, body] of scripts) {
879
+ const file = join4(hooksDir, name);
880
+ let existing;
881
+ try {
882
+ existing = lstatSync(file);
883
+ } catch {
884
+ existing = void 0;
885
+ }
886
+ if (existing?.isSymbolicLink()) {
887
+ throw new WorkkitError("INTERNAL", `refusing to write hook ${file}: it is a symlink`, {
888
+ file
889
+ });
890
+ }
891
+ writeFileSync2(file, body);
892
+ chmodSync(file, 493);
893
+ files.push(file);
894
+ }
895
+ new Git(repoRoot).run(["config", "core.hooksPath", HOOKS_DIR]);
896
+ return { hooksDir, files };
897
+ }
898
+
899
+ // src/core/paths.ts
900
+ import { homedir } from "os";
901
+ import { join as join5 } from "path";
902
+ function homeDir(env = process.env) {
903
+ return env.HELMSMITH_HOME && env.HELMSMITH_HOME.length > 0 ? env.HELMSMITH_HOME : join5(homedir(), ".cache", "helmsmith");
904
+ }
905
+ var registryFile = (home) => join5(home, "registry.json");
906
+ var lockDir = (home) => join5(home, "registry.lock");
907
+
908
+ // src/core/ports.ts
909
+ function portsForSlot(m, slot) {
910
+ return Object.fromEntries(
911
+ Object.entries(m.ports.services).map(([service, { base }]) => [service, base + slot])
912
+ );
913
+ }
914
+ function rangesFor(m) {
915
+ return Object.fromEntries(
916
+ Object.entries(m.ports.services).map(([service, { base }]) => [
917
+ service,
918
+ { base, count: m.slots.count }
919
+ ])
920
+ );
921
+ }
922
+ function rangesOverlap(a, b) {
923
+ return a.base < b.base + b.count && b.base < a.base + a.count;
924
+ }
925
+ function claimRanges(registry, m, repoRoot) {
926
+ const mine = rangesFor(m);
927
+ const others = Object.entries(registry.read().projects).filter(([name]) => name !== m.project);
928
+ for (const [service, range] of Object.entries(mine)) {
929
+ for (const [name, entry] of others) {
930
+ for (const [theirService, theirs] of Object.entries(entry.ranges)) {
931
+ if (rangesOverlap(range, theirs)) {
932
+ throw new WorkkitError(
933
+ "PORT_RANGE_TAKEN",
934
+ `ports ${range.base}-${range.base + range.count - 1} for "${service}" overlap project "${name}" (${theirService}: ${theirs.base}-${theirs.base + theirs.count - 1}); pick another base in ports.services.${service}`,
935
+ { project: name, service, theirs }
936
+ );
937
+ }
938
+ }
939
+ }
940
+ }
941
+ registry.upsertProject(m.project, { root: repoRoot, ranges: mine });
942
+ }
943
+
944
+ // src/core/refresh.ts
945
+ import { spawnSync as spawnSync2 } from "child_process";
946
+ import { createHash } from "crypto";
947
+ import { existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync3, writeFileSync as writeFileSync3 } from "fs";
948
+ import { dirname as dirname2, join as join6 } from "path";
949
+ import picomatch2 from "picomatch";
950
+ function matchesWhen(glob) {
951
+ const isMatch = picomatch2(glob, { dot: true });
952
+ return (p) => isMatch(p);
953
+ }
954
+ function readStamps(stampFile) {
955
+ if (!stampFile || !existsSync5(stampFile)) return {};
956
+ try {
957
+ return JSON.parse(readFileSync3(stampFile, "utf8"));
958
+ } catch {
959
+ return {};
960
+ }
961
+ }
962
+ function writeStamps(stampFile, stamps) {
963
+ mkdirSync4(dirname2(stampFile), { recursive: true });
964
+ writeFileSync3(stampFile, `${JSON.stringify(stamps, null, 2)}
965
+ `);
966
+ }
967
+ function matchedFilesInWorktree(worktree, whenGlob) {
968
+ if (!/[*?[{]/.test(whenGlob)) {
969
+ return existsSync5(join6(worktree, whenGlob)) ? [whenGlob] : [];
970
+ }
971
+ const r = spawnSync2("git", ["ls-files"], { cwd: worktree, encoding: "utf8" });
972
+ if (r.status !== 0) return [];
973
+ const isMatch = matchesWhen(whenGlob);
974
+ return (r.stdout ?? "").split("\n").map((l) => l.trim()).filter((l) => l.length > 0 && isMatch(l) && existsSync5(join6(worktree, l)));
975
+ }
976
+ function hashFiles(worktree, relPaths) {
977
+ if (relPaths.length === 0) return null;
978
+ const h = createHash("sha256");
979
+ for (const rel of [...relPaths].sort()) {
980
+ const abs = join6(worktree, rel);
981
+ if (!existsSync5(abs)) continue;
982
+ h.update(`${rel}\0`);
983
+ h.update(readFileSync3(abs));
984
+ h.update("\0");
985
+ }
986
+ return h.digest("hex");
987
+ }
988
+ function isFileCleanInGit(worktree, relPath) {
989
+ const r = spawnSync2("git", ["status", "--porcelain", "--", relPath], {
990
+ cwd: worktree,
991
+ encoding: "utf8"
992
+ });
993
+ return r.status === 0 && (r.stdout ?? "").trim().length === 0;
994
+ }
995
+ function selectRefresh(entries, changedPaths, opts) {
996
+ const runs = [];
997
+ const marks = [];
998
+ const stored = readStamps(opts?.stampFile);
999
+ const pendingStamps = { ...stored };
1000
+ const cleanWhenFiles = /* @__PURE__ */ new Set();
1001
+ for (const e of entries) {
1002
+ let hit = e.always === true;
1003
+ let matchedFiles = [];
1004
+ if (e.when !== void 0) {
1005
+ const byChanged = changedPaths.some(matchesWhen(e.when));
1006
+ if (opts?.worktree) {
1007
+ matchedFiles = matchedFilesInWorktree(opts.worktree, e.when);
1008
+ const digest = hashFiles(opts.worktree, matchedFiles);
1009
+ if (digest !== null) {
1010
+ if (stored[e.when] !== digest) hit = true;
1011
+ pendingStamps[e.when] = digest;
1012
+ }
1013
+ }
1014
+ if (byChanged) hit = true;
1015
+ }
1016
+ if (!hit) continue;
1017
+ if (e.run) {
1018
+ runs.push(e.run);
1019
+ if (opts?.worktree && e.when && e.restoreWhenIfClean !== false) {
1020
+ for (const f of matchedFiles) {
1021
+ if (isFileCleanInGit(opts.worktree, f)) cleanWhenFiles.add(f);
1022
+ }
1023
+ }
1024
+ }
1025
+ if (e.mark) marks.push(e.mark);
1026
+ }
1027
+ if (!opts?.worktree) return { runs, marks };
1028
+ return {
1029
+ runs,
1030
+ marks,
1031
+ pendingStamps,
1032
+ cleanWhenFiles: [...cleanWhenFiles]
1033
+ };
1034
+ }
1035
+ function runRefresh(runs, cwd, log, env = process.env, opts) {
1036
+ for (const cmd of runs) {
1037
+ log(`$ ${cmd}`);
1038
+ const r = spawnSync2("sh", ["-c", cmd], { cwd, env, encoding: "utf8" });
1039
+ if (r.stdout) log(r.stdout.trimEnd());
1040
+ if (r.stderr) log(r.stderr.trimEnd());
1041
+ if (r.status !== 0) {
1042
+ throw new WorkkitError("INTERNAL", `refresh command failed (${r.status}): ${cmd}`, {
1043
+ cmd,
1044
+ status: r.status
1045
+ });
1046
+ }
1047
+ }
1048
+ if (opts?.restoreFiles && opts.restoreFiles.length > 0) {
1049
+ for (const rel of opts.restoreFiles) {
1050
+ if (!isFileCleanInGit(cwd, rel)) {
1051
+ spawnSync2("git", ["checkout", "--", rel], { cwd, encoding: "utf8" });
1052
+ }
1053
+ }
1054
+ }
1055
+ if (opts?.stampFile && opts.pendingStamps) {
1056
+ writeStamps(opts.stampFile, opts.pendingStamps);
1057
+ }
1058
+ }
1059
+
1060
+ // src/core/registry.ts
1061
+ import { randomBytes } from "crypto";
1062
+ import {
1063
+ existsSync as existsSync6,
1064
+ mkdirSync as mkdirSync5,
1065
+ readFileSync as readFileSync4,
1066
+ renameSync,
1067
+ rmSync as rmSync2,
1068
+ statSync as statSync2,
1069
+ writeFileSync as writeFileSync4
1070
+ } from "fs";
1071
+ var newId = (prefix) => `${prefix}_${randomBytes(4).toString("hex")}`;
1072
+ var EMPTY = { version: 1, projects: {}, leases: [], efforts: [] };
1073
+ var LOCK_STALE_MS = 3e4;
1074
+ var LOCK_WAIT_MS = 5e3;
1075
+ function sleep(ms) {
1076
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
1077
+ }
1078
+ var Registry = class _Registry {
1079
+ constructor(home, now2) {
1080
+ this.home = home;
1081
+ this.now = now2;
1082
+ }
1083
+ home;
1084
+ now;
1085
+ static open(home, now2 = () => /* @__PURE__ */ new Date()) {
1086
+ mkdirSync5(home, { recursive: true });
1087
+ return new _Registry(home, now2);
1088
+ }
1089
+ /** The registry as it is on disk. A file that does not parse is refused, never replaced. */
1090
+ read() {
1091
+ const file = registryFile(this.home);
1092
+ if (!existsSync6(file)) return structuredClone(EMPTY);
1093
+ let parsed;
1094
+ try {
1095
+ parsed = JSON.parse(readFileSync4(file, "utf8"));
1096
+ } catch (err) {
1097
+ throw new WorkkitError(
1098
+ "INTERNAL",
1099
+ `${file} is corrupt (${err instanceof Error ? err.message : String(err)}); nothing was changed. Move it aside (mv ${file} ${file}.corrupt-$(date +%s)) to start fresh, knowing its leases and running pids are lost`,
1100
+ { file }
1101
+ );
1102
+ }
1103
+ const r = parsed;
1104
+ if (!r || typeof r !== "object" || r.version !== 1) {
1105
+ throw new WorkkitError(
1106
+ "INTERNAL",
1107
+ `${file} has an unknown registry version (${String(r?.version)}); this build reads version 1`,
1108
+ { file }
1109
+ );
1110
+ }
1111
+ return {
1112
+ version: 1,
1113
+ projects: r.projects ?? {},
1114
+ leases: r.leases ?? [],
1115
+ efforts: r.efforts ?? [],
1116
+ notices: r.notices ?? []
1117
+ };
1118
+ }
1119
+ /** Lock, re-read, mutate, write atomically, unlock. The only way state changes. */
1120
+ update(fn) {
1121
+ const lock = lockDir(this.home);
1122
+ const started = Date.now();
1123
+ for (; ; ) {
1124
+ try {
1125
+ mkdirSync5(lock);
1126
+ break;
1127
+ } catch {
1128
+ try {
1129
+ if (Date.now() - statSync2(lock).mtimeMs > LOCK_STALE_MS) {
1130
+ rmSync2(lock, { recursive: true, force: true });
1131
+ continue;
1132
+ }
1133
+ } catch {
1134
+ continue;
1135
+ }
1136
+ if (Date.now() - started > LOCK_WAIT_MS) {
1137
+ throw new WorkkitError(
1138
+ "INTERNAL",
1139
+ `registry lock ${lock} held for over ${LOCK_WAIT_MS} ms`
1140
+ );
1141
+ }
1142
+ sleep(25);
1143
+ }
1144
+ }
1145
+ try {
1146
+ const r = this.read();
1147
+ const out = fn(r);
1148
+ const file = registryFile(this.home);
1149
+ const tmp = `${file}.${process.pid}.tmp`;
1150
+ writeFileSync4(tmp, `${JSON.stringify(r, null, 2)}
1151
+ `);
1152
+ renameSync(tmp, file);
1153
+ return out;
1154
+ } finally {
1155
+ rmSync2(lock, { recursive: true, force: true });
1156
+ }
1157
+ }
1158
+ project(name) {
1159
+ return this.read().projects[name];
1160
+ }
1161
+ upsertProject(name, entry) {
1162
+ this.update((r) => {
1163
+ r.projects[name] = entry;
1164
+ });
1165
+ }
1166
+ leases(filter = {}) {
1167
+ return this.read().leases.filter(
1168
+ (l) => Object.entries(filter).every(([k, v]) => l[k] === v)
1169
+ );
1170
+ }
1171
+ efforts(filter = {}) {
1172
+ return this.read().efforts.filter(
1173
+ (e) => Object.entries(filter).every(([k, v]) => e[k] === v)
1174
+ );
1175
+ }
1176
+ activeEffortFor(project, area, task) {
1177
+ return this.efforts({ project, area, state: "active" }).find(
1178
+ (e) => (e.task ?? void 0) === (task ?? void 0)
1179
+ );
1180
+ }
1181
+ /** An effort that is being started counts as open: nobody else may start on the same (area, task) meanwhile. */
1182
+ openEffortFor(project, area, task) {
1183
+ return this.efforts({ project, area }).find(
1184
+ (e) => (e.state === "starting" || e.state === "active") && (e.task ?? void 0) === (task ?? void 0)
1185
+ );
1186
+ }
1187
+ addNotice(project, area, notice) {
1188
+ this.update((r) => {
1189
+ const existing = r.notices ?? [];
1190
+ const dup = existing.findIndex(
1191
+ (n) => n.project === project && n.area === area && n.notice.from === notice.from && n.notice.text === notice.text
1192
+ );
1193
+ if (dup >= 0) {
1194
+ existing[dup] = { project, area, notice };
1195
+ r.notices = existing;
1196
+ } else {
1197
+ r.notices = [...existing, { project, area, notice }];
1198
+ }
1199
+ });
1200
+ }
1201
+ notices(project, area) {
1202
+ return (this.read().notices ?? []).filter((n) => n.project === project && n.area === area).map((n) => n.notice);
1203
+ }
1204
+ clearNotices(project, area) {
1205
+ this.update((r) => {
1206
+ r.notices = (r.notices ?? []).filter((n) => !(n.project === project && n.area === area));
1207
+ });
1208
+ }
1209
+ clearNoticesFrom(project, branches) {
1210
+ const set = new Set(branches);
1211
+ this.update((r) => {
1212
+ r.notices = (r.notices ?? []).filter(
1213
+ (n) => !(n.project === project && set.has(n.notice.from))
1214
+ );
1215
+ });
1216
+ }
1217
+ pruneNoticesWhere(project, area, remove) {
1218
+ this.update((r) => {
1219
+ r.notices = (r.notices ?? []).filter(
1220
+ (n) => !(n.project === project && n.area === area && remove(n.notice))
1221
+ );
1222
+ });
1223
+ }
1224
+ allocateSlot(project, m, owner, effort, exclude = /* @__PURE__ */ new Set()) {
1225
+ return this.update((r) => {
1226
+ const taken = new Set(
1227
+ r.leases.filter((l) => l.project === project && l.kind === "slot").map((l) => l.value)
1228
+ );
1229
+ const reserved = new Set(m.slots.reserved);
1230
+ let slot = -1;
1231
+ for (let n = 0; n < m.slots.count; n++) {
1232
+ if (!taken.has(n) && !reserved.has(n) && !exclude.has(n)) {
1233
+ slot = n;
1234
+ break;
1235
+ }
1236
+ }
1237
+ if (slot < 0) {
1238
+ throw new WorkkitError(
1239
+ "NO_FREE_SLOT",
1240
+ `no free slot in ${project} (0..${m.slots.count - 1}, reserved ${[...reserved].join(",")})`
1241
+ );
1242
+ }
1243
+ const lease = this.lease(
1244
+ project,
1245
+ "slot",
1246
+ slot,
1247
+ owner,
1248
+ effort,
1249
+ m.expiry.slotHours,
1250
+ portsForSlot(m, slot)
1251
+ );
1252
+ r.leases.push(lease);
1253
+ return lease;
1254
+ });
1255
+ }
1256
+ addLease(kind, project, value, owner, effort, hours, extra = {}) {
1257
+ return this.update((r) => {
1258
+ const l = { ...this.lease(project, kind, value, owner, effort, hours), ...extra };
1259
+ r.leases.push(l);
1260
+ return l;
1261
+ });
1262
+ }
1263
+ lease(project, kind, value, owner, effort, hours, ports) {
1264
+ const now2 = this.now();
1265
+ return {
1266
+ id: newId("lease"),
1267
+ project,
1268
+ kind,
1269
+ value,
1270
+ ...ports ? { ports } : {},
1271
+ owner,
1272
+ effort,
1273
+ created: now2.toISOString(),
1274
+ touched: now2.toISOString(),
1275
+ expires: new Date(now2.getTime() + hours * 36e5).toISOString()
1276
+ };
1277
+ }
1278
+ touch(leaseId, hours) {
1279
+ this.update((r) => {
1280
+ const l = r.leases.find((x) => x.id === leaseId);
1281
+ if (!l) throw new WorkkitError("LEASE_NOT_FOUND", leaseId);
1282
+ const now2 = this.now();
1283
+ l.touched = now2.toISOString();
1284
+ l.expires = new Date(now2.getTime() + hours * 36e5).toISOString();
1285
+ });
1286
+ }
1287
+ patchLease(leaseId, patch) {
1288
+ this.update((r) => {
1289
+ const i = r.leases.findIndex((x) => x.id === leaseId);
1290
+ if (i < 0) throw new WorkkitError("LEASE_NOT_FOUND", leaseId);
1291
+ r.leases[i] = { ...r.leases[i], ...patch };
1292
+ });
1293
+ }
1294
+ release(leaseId) {
1295
+ this.update((r) => {
1296
+ r.leases = r.leases.filter((l) => l.id !== leaseId);
1297
+ });
1298
+ }
1299
+ expired(now2 = this.now()) {
1300
+ return this.read().leases.filter((l) => Date.parse(l.expires) < now2.getTime());
1301
+ }
1302
+ addEffort(e) {
1303
+ this.update((r) => {
1304
+ r.efforts.push(e);
1305
+ });
1306
+ }
1307
+ updateEffort(id, patch) {
1308
+ return this.update((r) => {
1309
+ const i = r.efforts.findIndex((e) => e.id === id);
1310
+ if (i < 0) throw new WorkkitError("EFFORT_NOT_FOUND", `no effort ${id}`);
1311
+ r.efforts[i] = { ...r.efforts[i], ...patch };
1312
+ return r.efforts[i];
1313
+ });
1314
+ }
1315
+ removeEfforts(predicate) {
1316
+ return this.update((r) => {
1317
+ const before = r.efforts.length;
1318
+ r.efforts = r.efforts.filter((e) => !predicate(e));
1319
+ return before - r.efforts.length;
1320
+ });
1321
+ }
1322
+ };
1323
+
1324
+ // src/core/runner.ts
1325
+ import { spawn, spawnSync as spawnSync3 } from "child_process";
1326
+ import { closeSync, openSync } from "fs";
1327
+ import { join as join7 } from "path";
1328
+ var DEFAULT_HEALTH_TIMEOUT_MS = 18e4;
1329
+ var HEALTH_POLL_MS = 1e3;
1330
+ var PROBE_CAP_MS = 1e4;
1331
+ var STOP_COMMAND_TIMEOUT_MS = 15e3;
1332
+ var STOP_GRACE_MS = 5e3;
1333
+ var sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
1334
+ function isAlive(pid) {
1335
+ try {
1336
+ process.kill(pid, 0);
1337
+ return true;
1338
+ } catch {
1339
+ return false;
1340
+ }
1341
+ }
1342
+ function pidSignature(pid) {
1343
+ const r = spawnSync3("ps", ["-o", "lstart=", "-p", String(pid)], { encoding: "utf8" });
1344
+ return r.status === 0 ? (r.stdout ?? "").trim() : "";
1345
+ }
1346
+ function serviceModes(name, spec) {
1347
+ if (spec.modes && spec.modes.length > 0) return spec.modes;
1348
+ return name === "frontend" ? ["fullstack"] : ["backend", "fullstack"];
1349
+ }
1350
+ function probe(spec, cwd, env, timeoutMs = PROBE_CAP_MS) {
1351
+ const r = spawnSync3("sh", ["-c", spec.health], {
1352
+ cwd,
1353
+ env,
1354
+ encoding: "utf8",
1355
+ timeout: Math.max(100, timeoutMs)
1356
+ });
1357
+ const out = (r.stdout ?? "").trim();
1358
+ const last = out.split(/\s+/).filter(Boolean).pop() ?? "";
1359
+ if (r.error) return { healthy: false, last: `probe ${r.error.message}` };
1360
+ if (r.status !== 0) return { healthy: false, last: (r.stderr ?? "").trim() || out };
1361
+ if (spec.healthyCodes && spec.healthyCodes.length > 0)
1362
+ return { healthy: spec.healthyCodes.includes(Number(last)), last };
1363
+ return { healthy: true, last };
1364
+ }
1365
+ async function waitHealthy(o) {
1366
+ const budget = o.timeoutMs ?? o.spec.healthTimeoutMs ?? DEFAULT_HEALTH_TIMEOUT_MS;
1367
+ const deadline = Date.now() + budget;
1368
+ let last = "";
1369
+ while (Date.now() < deadline) {
1370
+ const p = probe(o.spec, o.cwd, o.env, Math.min(PROBE_CAP_MS, deadline - Date.now()));
1371
+ if (p.healthy) return;
1372
+ last = p.last;
1373
+ if (Date.now() >= deadline) break;
1374
+ await sleep2(Math.min(HEALTH_POLL_MS, Math.max(0, deadline - Date.now())));
1375
+ }
1376
+ throw new WorkkitError(
1377
+ "HEALTH_TIMEOUT",
1378
+ `service "${o.name}" was not healthy within ${(budget / 1e3).toFixed(0)} s (last probe: ${last || "no output"})`,
1379
+ { service: o.name, last }
1380
+ );
1381
+ }
1382
+ function spawnService(name, spec, a) {
1383
+ const fd = openSync(join7(a.logDir, `${name}.log`), "a");
1384
+ try {
1385
+ const child = spawn("sh", ["-c", spec.start], {
1386
+ cwd: a.cwd,
1387
+ env: a.env,
1388
+ detached: true,
1389
+ stdio: ["ignore", fd, fd]
1390
+ });
1391
+ child.unref();
1392
+ if (child.pid === void 0) {
1393
+ throw new WorkkitError("SERVICE_FAILED", `service "${name}" did not spawn: ${spec.start}`, {
1394
+ service: name
1395
+ });
1396
+ }
1397
+ return child.pid;
1398
+ } finally {
1399
+ closeSync(fd);
1400
+ }
1401
+ }
1402
+ async function startServices(a) {
1403
+ const pids = {};
1404
+ const signatures = {};
1405
+ const targetMode = a.mode ?? "fullstack";
1406
+ const entries = Object.entries(a.m.services).filter(([name, spec]) => {
1407
+ if (a.onlyServices) return a.onlyServices.includes(name);
1408
+ return serviceModes(name, spec).includes(targetMode);
1409
+ });
1410
+ for (const [name, spec] of entries) {
1411
+ a.onLog?.(`starting ${name}: ${spec.start}`);
1412
+ pids[name] = spawnService(name, spec, a);
1413
+ signatures[name] = pidSignature(pids[name]);
1414
+ a.onSpawn?.(name, pids[name], signatures[name]);
1415
+ try {
1416
+ await waitHealthy({ name, spec, cwd: a.cwd, env: a.env });
1417
+ } catch (err) {
1418
+ await stopServices({ m: a.m, cwd: a.cwd, env: a.env, pids, signatures, onLog: a.onLog });
1419
+ throw err;
1420
+ }
1421
+ a.onLog?.(`${name} healthy (pid ${pids[name]})`);
1422
+ }
1423
+ return { pids, signatures };
1424
+ }
1425
+ function killGroup(pid, signal) {
1426
+ try {
1427
+ process.kill(-pid, signal);
1428
+ } catch {
1429
+ try {
1430
+ process.kill(pid, signal);
1431
+ } catch {
1432
+ }
1433
+ }
1434
+ }
1435
+ async function stopServices(o) {
1436
+ const names = Object.keys(o.m.services).filter((n) => o.pids[n] !== void 0).reverse();
1437
+ if (!o.skipStopCommands) {
1438
+ for (const name of names) {
1439
+ const spec = o.m.services[name];
1440
+ o.onLog?.(`stopping ${name}: ${spec.stop}`);
1441
+ const r = spawnSync3("sh", ["-c", spec.stop], {
1442
+ cwd: o.cwd,
1443
+ env: o.env,
1444
+ encoding: "utf8",
1445
+ timeout: STOP_COMMAND_TIMEOUT_MS
1446
+ });
1447
+ if (r.error) o.onLog?.(`stop command for ${name} ${r.error.message}`);
1448
+ }
1449
+ }
1450
+ const ours = names.filter((n) => {
1451
+ const pid = o.pids[n];
1452
+ if (!isAlive(pid)) return false;
1453
+ const expected = o.signatures?.[n];
1454
+ if (expected === void 0) return true;
1455
+ const actual = pidSignature(pid);
1456
+ if (actual !== expected) {
1457
+ o.onLog?.(
1458
+ `not signalling pid ${pid} (${n}): it is no longer the process started for this lease`
1459
+ );
1460
+ return false;
1461
+ }
1462
+ return true;
1463
+ });
1464
+ const alive = () => ours.filter((n) => isAlive(o.pids[n]));
1465
+ if (alive().length === 0) return;
1466
+ for (const n of alive()) killGroup(o.pids[n], "SIGTERM");
1467
+ const deadline = Date.now() + STOP_GRACE_MS;
1468
+ while (alive().length > 0 && Date.now() < deadline) await sleep2(200);
1469
+ for (const n of alive()) killGroup(o.pids[n], "SIGKILL");
1470
+ const hardDeadline = Date.now() + STOP_GRACE_MS;
1471
+ while (alive().length > 0 && Date.now() < hardDeadline) await sleep2(100);
1472
+ }
1473
+
1474
+ // src/core/session.ts
1475
+ import { hostname, userInfo } from "os";
1476
+ function currentOwner(env = process.env) {
1477
+ const named = [env.WORK_SESSION, env.CLAUDE_SESSION_NAME, env.CLAUDE_CODE_SESSION_ID].find(
1478
+ (v) => v !== void 0 && v.length > 0
1479
+ );
1480
+ return { session: named ?? `${userInfo().username}@${hostname()}`, pid: process.pid };
1481
+ }
1482
+
1483
+ // src/lib/storybrokr.ts
1484
+ import { spawnSync as spawnSync4 } from "child_process";
1485
+ var MIN_STORYBROKR_VERSION = "0.3.0";
1486
+ var versionChecked = false;
1487
+ function compareSemver(a, b) {
1488
+ const pa = a.trim().replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10) || 0);
1489
+ const pb = b.trim().replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10) || 0);
1490
+ for (let i = 0; i < 3; i++) {
1491
+ const diff = (pa[i] ?? 0) - (pb[i] ?? 0);
1492
+ if (diff !== 0) return diff;
1493
+ }
1494
+ return 0;
1495
+ }
1496
+ function run(args) {
1497
+ const r = spawnSync4("storybrokr", args, { encoding: "utf8" });
1498
+ if (r.error) {
1499
+ throw new WorkkitError(
1500
+ "STORYBROKR_FAILED",
1501
+ `storybrokr is not installed (npm i -g @helmsmith/storybrokr): ${r.error.message}`
1502
+ );
1503
+ }
1504
+ return { code: r.status ?? 1, out: r.stdout ?? "", err: r.stderr ?? "" };
1505
+ }
1506
+ function assertStorybrokrVersion() {
1507
+ if (versionChecked) return;
1508
+ const r = run(["--version"]);
1509
+ const found = r.out.trim();
1510
+ if (r.code !== 0 || compareSemver(found, MIN_STORYBROKR_VERSION) < 0) {
1511
+ throw new WorkkitError(
1512
+ "STORYBROKR_FAILED",
1513
+ `storybrokr >= ${MIN_STORYBROKR_VERSION} required (found ${found || "unknown"}); upgrade @helmsmith/storybrokr`
1514
+ );
1515
+ }
1516
+ versionChecked = true;
1517
+ }
1518
+ var storybrokrCli = {
1519
+ async up(story, hostRoot, opts) {
1520
+ assertStorybrokrVersion();
1521
+ const args = ["up", story, "--host", hostRoot, "--json"];
1522
+ if (opts?.ttlMinutes !== void 0) args.push("--ttl", String(opts.ttlMinutes));
1523
+ const r = run(args);
1524
+ if (r.code !== 0) {
1525
+ throw new WorkkitError(
1526
+ "STORYBROKR_FAILED",
1527
+ `storybrokr up ${story} failed: ${r.err.trim() || r.out.trim()}`
1528
+ );
1529
+ }
1530
+ const record = JSON.parse(r.out);
1531
+ return { id: record.id, port: record.port, url: record.url };
1532
+ },
1533
+ async down(id) {
1534
+ const r = run(["down", id]);
1535
+ if (r.code !== 0)
1536
+ throw new WorkkitError("STORYBROKR_FAILED", `storybrokr down ${id} failed: ${r.err.trim()}`);
1537
+ },
1538
+ async downHost(hostRoot) {
1539
+ const r = spawnSync4("storybrokr", ["down", "--host", hostRoot, "--json"], { encoding: "utf8" });
1540
+ void r;
1541
+ },
1542
+ async touch(id) {
1543
+ const r = spawnSync4("storybrokr", ["touch", id], { encoding: "utf8" });
1544
+ void r;
1545
+ }
1546
+ };
1547
+
1548
+ // src/lib/context.ts
1549
+ function resolveRepoRoot(cwd, override) {
1550
+ if (override) return override;
1551
+ return new Git(cwd).mainRoot();
1552
+ }
1553
+ async function buildCtx(opts = {}) {
1554
+ const repoRoot = resolveRepoRoot(opts.cwd ?? process.cwd(), opts.projectRoot);
1555
+ const manifest = await loadManifest(repoRoot);
1556
+ const home = homeDir();
1557
+ const registry = Registry.open(home);
1558
+ if (!registry.project(manifest.project)) claimRanges(registry, manifest, repoRoot);
1559
+ return {
1560
+ home,
1561
+ repoRoot,
1562
+ manifest,
1563
+ registry,
1564
+ owner: currentOwner(),
1565
+ runner: { start: startServices, stop: stopServices },
1566
+ storybrokr: storybrokrCli,
1567
+ log: opts.quiet ? () => {
1568
+ } : (line) => console.error(chalk.gray(line))
1569
+ };
1570
+ }
1571
+
1572
+ // src/lib/effort.ts
1573
+ import {
1574
+ appendFileSync as appendFileSync2,
1575
+ cpSync,
1576
+ existsSync as existsSync7,
1577
+ mkdirSync as mkdirSync6,
1578
+ readdirSync,
1579
+ realpathSync as realpathSync4,
1580
+ rmSync as rmSync3,
1581
+ statSync as statSync3
1582
+ } from "fs";
1583
+ import { connect, createServer } from "net";
1584
+ import { dirname as dirname3, join as join8 } from "path";
1585
+ var worktreePathFor = (ctx, area, task) => task ? join8(ctx.repoRoot, ctx.manifest.worktreeRoot, "_tasks", `${area}--${task}`) : join8(ctx.repoRoot, ctx.manifest.worktreeRoot, area);
1586
+ var branchFor = (type, area, task) => task ? `${type}/${area}--${task}` : `${type}/${area}`;
1587
+ var effortLabel2 = (area, task) => task ? `${area}--${task}` : area;
1588
+ var now = () => (/* @__PURE__ */ new Date()).toISOString();
1589
+ var STARTING_GRACE_MS = 30 * 6e4;
1590
+ var JOIN_WAIT_MS = 6e4;
1591
+ var sleep3 = (ms) => new Promise((r) => setTimeout(r, ms));
1592
+ var realpathOr2 = (p) => {
1593
+ try {
1594
+ return realpathSync4(p);
1595
+ } catch {
1596
+ return p;
1597
+ }
1598
+ };
1599
+ function fetchBaseOnce(ctx) {
1600
+ new Git(ctx.repoRoot).tryRun(["fetch", "-q", "origin", ctx.manifest.baseBranch]);
1601
+ }
1602
+ function hoursFor(m, kind) {
1603
+ return {
1604
+ slot: m.expiry.slotHours,
1605
+ storybook: m.expiry.storybookHours,
1606
+ commons: m.expiry.commonsHours
1607
+ }[kind];
1608
+ }
1609
+ function modeCovers(existing, requested) {
1610
+ if (existing === "fullstack") return true;
1611
+ return existing === requested;
1612
+ }
1613
+ var STORYBROKR_TOUCH_THROTTLE_MS = 6e4;
1614
+ function touchEffort(ctx, effort) {
1615
+ const prevMs = Date.parse(effort.lastActivity);
1616
+ const shouldTouchStorybrokr = Number.isNaN(prevMs) || Date.now() - prevMs >= STORYBROKR_TOUCH_THROTTLE_MS;
1617
+ for (const l of ctx.registry.leases({ effort: effort.id })) {
1618
+ ctx.registry.touch(l.id, hoursFor(ctx.manifest, l.kind));
1619
+ if (l.kind === "storybook" && shouldTouchStorybrokr) {
1620
+ void Promise.resolve(ctx.storybrokr.touch?.(String(l.value))).catch(() => {
1621
+ });
1622
+ }
1623
+ }
1624
+ ctx.registry.updateEffort(effort.id, { lastActivity: now() });
1625
+ }
1626
+ function portBusy(port) {
1627
+ return new Promise((resolve4) => {
1628
+ const srv = createServer();
1629
+ srv.once("error", () => resolve4(true));
1630
+ srv.listen(port, "127.0.0.1", () => srv.close(() => resolve4(false)));
1631
+ });
1632
+ }
1633
+ async function busyPorts(ports) {
1634
+ const out = [];
1635
+ for (const [service, port] of Object.entries(ports))
1636
+ if (await portBusy(port)) out.push(`${service}=${port}`);
1637
+ return out;
1638
+ }
1639
+ function portAnswers(port) {
1640
+ return new Promise((resolve4) => {
1641
+ const sock = connect({ port, host: "127.0.0.1" });
1642
+ const done = (v) => {
1643
+ sock.destroy();
1644
+ resolve4(v);
1645
+ };
1646
+ sock.setTimeout(300, () => done(false));
1647
+ sock.once("connect", () => done(true));
1648
+ sock.once("error", () => done(false));
1649
+ });
1650
+ }
1651
+ async function anyPortAnswers(ports) {
1652
+ for (const port of Object.values(ports ?? {})) if (await portAnswers(port)) return true;
1653
+ return false;
1654
+ }
1655
+ async function claimFreeSlot(ctx, effortId, warnings) {
1656
+ const m = ctx.manifest;
1657
+ const exclude = /* @__PURE__ */ new Set();
1658
+ const busyNotes = [];
1659
+ for (; ; ) {
1660
+ const candidate = ctx.registry.allocateSlot(m.project, m, ctx.owner, effortId, exclude);
1661
+ const busy = await busyPorts(candidate.ports ?? {});
1662
+ if (busy.length === 0) {
1663
+ if (busyNotes.length) warnings.push(...busyNotes);
1664
+ return candidate;
1665
+ }
1666
+ ctx.registry.release(candidate.id);
1667
+ exclude.add(candidate.value);
1668
+ busyNotes.push(`slot ${candidate.value}: ${busy.join(", ")} already in use`);
1669
+ ctx.log(busyNotes[busyNotes.length - 1]);
1670
+ }
1671
+ }
1672
+ function guardStart(ctx, o) {
1673
+ const m = ctx.manifest;
1674
+ const spec = m.areas[o.area];
1675
+ if (!spec)
1676
+ throw new WorkkitError(
1677
+ "AREA_UNKNOWN",
1678
+ `unknown area "${o.area}" (known: ${Object.keys(m.areas).join(", ")})`,
1679
+ { area: o.area }
1680
+ );
1681
+ if (o.task !== void 0 && !TASK_SLUG.test(o.task))
1682
+ throw new WorkkitError(
1683
+ "TASK_INVALID",
1684
+ `invalid task slug "${o.task}" (must match /^[a-z0-9][a-z0-9_-]{0,47}$/ with no "--")`,
1685
+ { task: o.task }
1686
+ );
1687
+ if (!m.branch.types.includes(o.type))
1688
+ throw new WorkkitError(
1689
+ "TYPE_UNKNOWN",
1690
+ `unknown type "${o.type}" (allowed: ${m.branch.types.join(", ")})`,
1691
+ { type: o.type }
1692
+ );
1693
+ if (o.mode !== "frontend" && o.mode !== "backend" && o.mode !== "fullstack")
1694
+ throw new WorkkitError(
1695
+ "MODE_UNKNOWN",
1696
+ `unknown mode "${o.mode}" (frontend | backend | fullstack)`
1697
+ );
1698
+ const branch = branchFor(o.type, o.area, o.task);
1699
+ assertNotProtected(m, branch);
1700
+ const scopes = expandScopes(m, o.area, o.mode, o.scopes, Boolean(o.task));
1701
+ const commons = spec.commons ?? [];
1702
+ const warnings = [];
1703
+ if (commons.length > 0) {
1704
+ for (const e of ctx.registry.efforts({ project: m.project })) {
1705
+ if (e.area === o.area && (e.task ?? void 0) === (o.task ?? void 0) || e.state !== "active" && e.state !== "starting" || !existsSync7(e.worktree))
1706
+ continue;
1707
+ const changed = new Git(e.worktree).tryRun(["diff", "--name-only", "--no-renames", `origin/${m.baseBranch}...HEAD`]).out.split("\n").filter(Boolean);
1708
+ const hit = commonsTouched(m, changed).filter((c) => commons.includes(c));
1709
+ if (hit.length > 0)
1710
+ warnings.push(
1711
+ `${effortLabel2(e.area, e.task)} (${e.branch}, ${e.owner.session}) already has commits under commons ${hit.join(", ")}: coordinate or wait for its merge`
1712
+ );
1713
+ }
1714
+ }
1715
+ return { branch, scopes, commons, warnings };
1716
+ }
1717
+ function reserveEffort(ctx, o, branch, scopes, commons) {
1718
+ const m = ctx.manifest;
1719
+ const effort = {
1720
+ id: newId("eff"),
1721
+ project: m.project,
1722
+ area: o.area,
1723
+ ...o.task ? { task: o.task } : {},
1724
+ type: o.type,
1725
+ mode: o.mode,
1726
+ branch,
1727
+ worktree: worktreePathFor(ctx, o.area, o.task),
1728
+ owner: ctx.owner,
1729
+ state: "starting",
1730
+ scopes,
1731
+ commons,
1732
+ leases: [],
1733
+ notices: [],
1734
+ started: now(),
1735
+ lastActivity: now()
1736
+ };
1737
+ ctx.registry.update((r) => {
1738
+ const open = r.efforts.filter(
1739
+ (e) => e.project === m.project && (e.state === "active" || e.state === "starting")
1740
+ );
1741
+ const onTarget = open.find(
1742
+ (e) => e.area === o.area && (e.task ?? void 0) === (o.task ?? void 0)
1743
+ );
1744
+ if (onTarget) {
1745
+ const label = effortLabel2(o.area, o.task);
1746
+ throw new WorkkitError(
1747
+ "EFFORT_OPEN",
1748
+ `an effort is open on ${label} (${onTarget.branch}, ${onTarget.mode}) owned by ${onTarget.owner.session} since ${onTarget.started}; finish it, or pass --join to work in the same checkout`,
1749
+ { owner: onTarget.owner.session, effort: onTarget.id, branch: onTarget.branch }
1750
+ );
1751
+ }
1752
+ for (const e of open) {
1753
+ const pairs = globsOverlap(scopes, e.scopes);
1754
+ if (pairs.length > 0) {
1755
+ const otherLabel = effortLabel2(e.area, e.task);
1756
+ throw new WorkkitError(
1757
+ "SCOPE_CONFLICT",
1758
+ `scope overlaps the open effort on ${otherLabel} (${e.branch}, owner ${e.owner.session}): ${pairs.join("; ")}`,
1759
+ { with: otherLabel, owner: e.owner.session, effort: e.id, pairs }
1760
+ );
1761
+ }
1762
+ }
1763
+ r.efforts.push(effort);
1764
+ });
1765
+ return effort;
1766
+ }
1767
+ function ensureWorktree(ctx, area, branch, task) {
1768
+ const m = ctx.manifest;
1769
+ const path = worktreePathFor(ctx, area, task);
1770
+ const main = new Git(ctx.repoRoot);
1771
+ if (!existsSync7(path)) {
1772
+ main.worktreeAdd(path, branch, `origin/${m.baseBranch}`);
1773
+ const wg2 = new Git(path);
1774
+ wg2.repairSubmodules(ctx.repoRoot, ctx.log);
1775
+ return { wg: wg2, created: true };
1776
+ }
1777
+ const registered = main.run(["worktree", "list", "--porcelain"]).split("\n").filter((l) => l.startsWith("worktree ")).map((l) => realpathOr2(l.slice(9)));
1778
+ const real = realpathOr2(path);
1779
+ const wg = new Git(path);
1780
+ const topLevel = wg.tryRun(["rev-parse", "--show-toplevel"]);
1781
+ if (!registered.includes(real) || topLevel.code !== 0 || realpathOr2(topLevel.out.trim()) !== real || wg.isMainCheckout()) {
1782
+ throw new WorkkitError(
1783
+ "WORKTREE_INVALID",
1784
+ `${path} exists but is not this repository's worktree for ${effortLabel2(area, task)} (a leftover directory?); move it away, or \`git worktree prune\` and retry`,
1785
+ { worktree: path }
1786
+ );
1787
+ }
1788
+ wg.repairSubmodules(ctx.repoRoot, ctx.log);
1789
+ const current = wg.currentBranch();
1790
+ if (current !== branch) {
1791
+ if (wg.isDirty())
1792
+ throw new WorkkitError(
1793
+ "DIRTY_WORKTREE",
1794
+ `${path} has uncommitted changes on ${current}; commit or park them before switching to ${branch}`,
1795
+ { worktree: path }
1796
+ );
1797
+ const unshipped = wg.commitsNotOn(m.baseBranch);
1798
+ if (unshipped.length > 0 && !wg.isEquivalentToBase(m.baseBranch)) {
1799
+ throw new WorkkitError(
1800
+ "EFFORT_OPEN",
1801
+ `${current} holds ${unshipped.length} commit(s) not yet on ${m.baseBranch}: ship or finish it first, or --join it`,
1802
+ { branch: current, area }
1803
+ );
1804
+ }
1805
+ wg.checkout(branch, `origin/${m.baseBranch}`);
1806
+ if (!wg.isDirty() && wg.commitsNotOn(m.baseBranch).length > 0 && wg.isEquivalentToBase(m.baseBranch)) {
1807
+ wg.run(["reset", "--hard", `origin/${m.baseBranch}`]);
1808
+ }
1809
+ } else if (!wg.isDirty() && wg.commitsNotOn(m.baseBranch).length > 0 && wg.isEquivalentToBase(m.baseBranch)) {
1810
+ wg.run(["reset", "--hard", `origin/${m.baseBranch}`]);
1811
+ }
1812
+ return { wg, created: false };
1813
+ }
1814
+ function appendLog(file, line) {
1815
+ appendFileSync2(file, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
1816
+ `);
1817
+ }
1818
+ async function startEffort(ctx, o) {
1819
+ const m = ctx.manifest;
1820
+ fetchBaseOnce(ctx);
1821
+ const { branch, scopes, commons, warnings } = guardStart(ctx, o);
1822
+ const notices = ctx.registry.notices(m.project, o.area);
1823
+ let open = ctx.registry.openEffortFor(m.project, o.area, o.task);
1824
+ if (open && o.join) {
1825
+ const deadline = Date.now() + JOIN_WAIT_MS;
1826
+ while (open && open.state === "starting" && Date.now() < deadline) {
1827
+ await sleep3(200);
1828
+ open = ctx.registry.openEffortFor(m.project, o.area, o.task);
1829
+ }
1830
+ if (!open || open.state !== "active") {
1831
+ throw new WorkkitError(
1832
+ "EFFORT_NOT_FOUND",
1833
+ `effort on ${effortLabel2(o.area, o.task)} did not become active in time to join`,
1834
+ { area: o.area, task: o.task }
1835
+ );
1836
+ }
1837
+ if (!modeCovers(open.mode, o.mode)) {
1838
+ const label = effortLabel2(o.area, o.task);
1839
+ throw new WorkkitError(
1840
+ "MODE_MISMATCH",
1841
+ `open effort on ${label} is in ${open.mode} mode, which does not cover ${o.mode}; run \`work promote --area ${o.area}${o.task ? ` --task ${o.task}` : ""} --mode fullstack\` first`,
1842
+ { area: o.area, task: o.task, openMode: open.mode, requestedMode: o.mode }
1843
+ );
1844
+ }
1845
+ const currentLeases = ctx.registry.leases({ effort: open.id });
1846
+ if (o.story && !currentLeases.some((l) => l.kind === "storybook")) {
1847
+ const hostRoot = storybookHostFor(m, open.worktree);
1848
+ const inst = await ctx.storybrokr.up(o.story, hostRoot, {
1849
+ ttlMinutes: Math.ceil(m.expiry.storybookHours * 60)
1850
+ });
1851
+ const sbLease = ctx.registry.addLease(
1852
+ "storybook",
1853
+ m.project,
1854
+ inst.id,
1855
+ ctx.owner,
1856
+ open.id,
1857
+ m.expiry.storybookHours,
1858
+ { ports: { storybook: inst.port } }
1859
+ );
1860
+ open = ctx.registry.updateEffort(open.id, {
1861
+ leases: [...open.leases, sbLease.id]
1862
+ });
1863
+ }
1864
+ const existingParticipants = open.participants ?? [];
1865
+ const isAlreadyMember = open.owner.session === ctx.owner.session || existingParticipants.some((p) => p.session === ctx.owner.session);
1866
+ if (!isAlreadyMember) {
1867
+ open = ctx.registry.updateEffort(open.id, {
1868
+ participants: [...existingParticipants, ctx.owner]
1869
+ });
1870
+ }
1871
+ touchEffort(ctx, open);
1872
+ return {
1873
+ effort: open,
1874
+ leases: ctx.registry.leases({ effort: open.id }),
1875
+ sync: "skipped",
1876
+ refreshed: [],
1877
+ marks: [],
1878
+ joined: true,
1879
+ warnings,
1880
+ notices
1881
+ };
1882
+ }
1883
+ const effort = reserveEffort(ctx, o, branch, scopes, commons);
1884
+ const leases = [];
1885
+ const abandon = async (stopPids) => {
1886
+ for (const l of ctx.registry.leases({ effort: effort.id })) {
1887
+ if (stopPids && l.kind === "slot" && l.pids && Object.keys(l.pids).length > 0) {
1888
+ await ctx.runner.stop({
1889
+ m,
1890
+ cwd: effort.worktree,
1891
+ env: process.env,
1892
+ pids: l.pids,
1893
+ signatures: l.signatures,
1894
+ onLog: ctx.log
1895
+ }).catch(() => void 0);
1896
+ } else if (stopPids && l.kind === "storybook") {
1897
+ await ctx.storybrokr.down(String(l.value)).catch(() => void 0);
1898
+ }
1899
+ ctx.registry.release(l.id);
1900
+ }
1901
+ ctx.registry.removeEfforts((e) => e.id === effort.id);
1902
+ };
1903
+ const onSignal = () => {
1904
+ abandon(true).finally(() => process.exit(130));
1905
+ };
1906
+ process.once("SIGINT", onSignal);
1907
+ process.once("SIGTERM", onSignal);
1908
+ try {
1909
+ const { wg, created } = ensureWorktree(ctx, o.area, branch, o.task);
1910
+ const worktree = wg.root();
1911
+ ctx.registry.updateEffort(effort.id, { worktree });
1912
+ effort.worktree = worktree;
1913
+ const logDir = join8(worktree, m.logs.dir);
1914
+ mkdirSync6(logDir, { recursive: true });
1915
+ const refreshLog = join8(logDir, "refresh.log");
1916
+ const stampFile = join8(logDir, ".refresh-stamps.json");
1917
+ if (created && m.seed && m.seed.length > 0) {
1918
+ runRefresh(
1919
+ m.seed,
1920
+ worktree,
1921
+ (l) => {
1922
+ appendLog(refreshLog, l);
1923
+ ctx.log(l);
1924
+ },
1925
+ { ...process.env, WORKTREE: worktree, MAIN_ROOT: ctx.repoRoot }
1926
+ );
1927
+ }
1928
+ let sync = "skipped";
1929
+ let changed = [];
1930
+ if (o.sync !== false) {
1931
+ const r = wg.syncFrom(m.baseBranch);
1932
+ if (r.kind === "conflict") {
1933
+ throw new WorkkitError(
1934
+ "SYNC_CONFLICT",
1935
+ `merging origin/${m.baseBranch} into ${branch} conflicts in ${r.conflicted.join(", ")}; resolve in ${worktree}, commit, then rerun with --no-sync`,
1936
+ { conflicted: r.conflicted, worktree }
1937
+ );
1938
+ }
1939
+ sync = r.kind;
1940
+ if (r.kind === "ff" || r.kind === "merge") changed = wg.changedPaths(r.before, r.after);
1941
+ ctx.registry.pruneNoticesWhere(
1942
+ m.project,
1943
+ o.area,
1944
+ (n) => wg.isAncestor(`origin/${n.from}`, "HEAD") || wg.isAncestor(n.from, "HEAD")
1945
+ );
1946
+ }
1947
+ const sel = selectRefresh(m.refresh, changed, { worktree, stampFile });
1948
+ runRefresh(
1949
+ sel.runs,
1950
+ worktree,
1951
+ (l) => {
1952
+ appendLog(refreshLog, l);
1953
+ ctx.log(l);
1954
+ },
1955
+ process.env,
1956
+ {
1957
+ stampFile,
1958
+ pendingStamps: sel.pendingStamps,
1959
+ restoreFiles: sel.cleanWhenFiles
1960
+ }
1961
+ );
1962
+ const baseSha = wg.rev("HEAD");
1963
+ for (const name of commons)
1964
+ leases.push(
1965
+ ctx.registry.addLease(
1966
+ "commons",
1967
+ m.project,
1968
+ name,
1969
+ ctx.owner,
1970
+ effort.id,
1971
+ m.expiry.commonsHours
1972
+ )
1973
+ );
1974
+ if (o.mode === "fullstack" || o.mode === "backend") {
1975
+ const slot = await claimFreeSlot(ctx, effort.id, warnings);
1976
+ leases.push(slot);
1977
+ const cfg = emitWorktreeConfig({
1978
+ m,
1979
+ worktree,
1980
+ slot: slot.value,
1981
+ ports: slot.ports ?? {},
1982
+ area: o.area,
1983
+ branch
1984
+ });
1985
+ const env = { ...process.env, ...cfg.vars };
1986
+ if (sel.marks.includes("db-reset") && m.services.postgres?.reset) {
1987
+ runRefresh([m.services.postgres.reset], worktree, (l) => appendLog(refreshLog, l), env);
1988
+ }
1989
+ const pids = {};
1990
+ const signatures = {};
1991
+ const result = await ctx.runner.start({
1992
+ m,
1993
+ cwd: worktree,
1994
+ env,
1995
+ logDir,
1996
+ mode: o.mode,
1997
+ onLog: ctx.log,
1998
+ onSpawn: (service, pid, signature) => {
1999
+ pids[service] = pid;
2000
+ signatures[service] = signature;
2001
+ ctx.registry.patchLease(slot.id, { pids: { ...pids }, signatures: { ...signatures } });
2002
+ }
2003
+ });
2004
+ ctx.registry.patchLease(slot.id, {
2005
+ pids: result.pids,
2006
+ signatures: result.signatures ?? signatures
2007
+ });
2008
+ } else {
2009
+ let storybookPort;
2010
+ if (o.story) {
2011
+ const hostRoot = storybookHostFor(m, worktree);
2012
+ const inst = await ctx.storybrokr.up(o.story, hostRoot, {
2013
+ ttlMinutes: Math.ceil(m.expiry.storybookHours * 60)
2014
+ });
2015
+ storybookPort = inst.port;
2016
+ leases.push(
2017
+ ctx.registry.addLease(
2018
+ "storybook",
2019
+ m.project,
2020
+ inst.id,
2021
+ ctx.owner,
2022
+ effort.id,
2023
+ m.expiry.storybookHours,
2024
+ { ports: { storybook: inst.port } }
2025
+ )
2026
+ );
2027
+ }
2028
+ emitWorktreeConfig({ m, worktree, ports: {}, storybookPort, area: o.area, branch });
2029
+ }
2030
+ const active = ctx.registry.updateEffort(effort.id, {
2031
+ state: "active",
2032
+ baseSha,
2033
+ leases: leases.map((l) => l.id),
2034
+ lastActivity: now()
2035
+ });
2036
+ return {
2037
+ effort: active,
2038
+ leases: ctx.registry.leases({ effort: effort.id }),
2039
+ sync,
2040
+ refreshed: sel.runs,
2041
+ marks: sel.marks,
2042
+ joined: false,
2043
+ warnings,
2044
+ notices
2045
+ };
2046
+ } catch (err) {
2047
+ await abandon(true);
2048
+ throw err;
2049
+ } finally {
2050
+ process.off("SIGINT", onSignal);
2051
+ process.off("SIGTERM", onSignal);
2052
+ }
2053
+ }
2054
+ async function promoteEffort(ctx, o) {
2055
+ const m = ctx.manifest;
2056
+ if (o.mode !== "backend" && o.mode !== "fullstack") {
2057
+ throw new WorkkitError("MODE_UNKNOWN", `promote target mode must be backend or fullstack`);
2058
+ }
2059
+ const open = ctx.registry.openEffortFor(m.project, o.area, o.task);
2060
+ if (!open) {
2061
+ throw new WorkkitError(
2062
+ "EFFORT_NOT_FOUND",
2063
+ `no open effort on ${effortLabel2(o.area, o.task)} to promote`,
2064
+ { area: o.area, task: o.task }
2065
+ );
2066
+ }
2067
+ if (open.mode === "fullstack" && o.mode === "backend" || open.mode === "frontend" && o.mode === "backend") {
2068
+ throw new WorkkitError(
2069
+ "MODE_MISMATCH",
2070
+ `cannot transition effort on ${effortLabel2(o.area, o.task)} from ${open.mode} to ${o.mode}`,
2071
+ { from: open.mode, to: o.mode }
2072
+ );
2073
+ }
2074
+ const modeScopes = expandScopes(m, o.area, o.mode);
2075
+ const nextScopes = open.task ? [.../* @__PURE__ */ new Set([...open.scopes, ...modeScopes])] : modeScopes;
2076
+ ctx.registry.update((r) => {
2077
+ const others = r.efforts.filter(
2078
+ (e) => e.project === m.project && e.id !== open.id && (e.state === "active" || e.state === "starting")
2079
+ );
2080
+ for (const e of others) {
2081
+ const pairs = globsOverlap(nextScopes, e.scopes);
2082
+ if (pairs.length > 0) {
2083
+ const otherLabel = effortLabel2(e.area, e.task);
2084
+ throw new WorkkitError(
2085
+ "SCOPE_CONFLICT",
2086
+ `promoting ${effortLabel2(o.area, o.task)} to ${o.mode} overlaps ${otherLabel} (${e.branch}): ${pairs.join("; ")}`,
2087
+ { with: otherLabel, owner: e.owner.session, effort: e.id, pairs }
2088
+ );
2089
+ }
2090
+ }
2091
+ const idx = r.efforts.findIndex((e) => e.id === open.id);
2092
+ if (idx >= 0) {
2093
+ r.efforts[idx] = { ...r.efforts[idx], mode: o.mode, scopes: nextScopes, lastActivity: now() };
2094
+ }
2095
+ });
2096
+ const warnings = [];
2097
+ let slot = ctx.registry.leases({ effort: open.id, kind: "slot" })[0];
2098
+ const sb = ctx.registry.leases({ effort: open.id, kind: "storybook" })[0];
2099
+ if (!slot) {
2100
+ slot = await claimFreeSlot(ctx, open.id, warnings);
2101
+ ctx.registry.updateEffort(open.id, { leases: [...open.leases, slot.id] });
2102
+ }
2103
+ const cfg = emitWorktreeConfig({
2104
+ m,
2105
+ worktree: open.worktree,
2106
+ slot: slot.value,
2107
+ ports: slot.ports ?? {},
2108
+ storybookPort: sb?.ports?.storybook,
2109
+ area: o.area,
2110
+ branch: open.branch
2111
+ });
2112
+ const env = { ...process.env, ...cfg.vars };
2113
+ const logDir = join8(open.worktree, m.logs.dir);
2114
+ mkdirSync6(logDir, { recursive: true });
2115
+ const existingPids = { ...slot.pids ?? {} };
2116
+ const existingSigs = { ...slot.signatures ?? {} };
2117
+ const missingServices = Object.entries(m.services).filter(([name, spec]) => serviceModes(name, spec).includes(o.mode) && !existingPids[name]).map(([name]) => name);
2118
+ if (missingServices.length > 0) {
2119
+ const result = await ctx.runner.start({
2120
+ m,
2121
+ cwd: open.worktree,
2122
+ env,
2123
+ logDir,
2124
+ mode: o.mode,
2125
+ onlyServices: missingServices,
2126
+ onLog: ctx.log,
2127
+ onSpawn: (service, pid, signature) => {
2128
+ existingPids[service] = pid;
2129
+ existingSigs[service] = signature;
2130
+ ctx.registry.patchLease(slot.id, {
2131
+ pids: { ...existingPids },
2132
+ signatures: { ...existingSigs }
2133
+ });
2134
+ }
2135
+ });
2136
+ ctx.registry.patchLease(slot.id, {
2137
+ pids: { ...existingPids, ...result.pids },
2138
+ signatures: { ...existingSigs, ...result.signatures ?? {} }
2139
+ });
2140
+ }
2141
+ const updated = ctx.registry.updateEffort(open.id, { lastActivity: now() });
2142
+ touchEffort(ctx, updated);
2143
+ return {
2144
+ effort: updated,
2145
+ leases: ctx.registry.leases({ effort: open.id }),
2146
+ startedServices: missingServices,
2147
+ warnings
2148
+ };
2149
+ }
2150
+ function behindBase(ctx, worktree) {
2151
+ if (!existsSync7(worktree)) return 0;
2152
+ const g = new Git(worktree);
2153
+ const r = g.tryRun(["rev-list", "--count", `HEAD..origin/${ctx.manifest.baseBranch}`]);
2154
+ return r.code === 0 ? Number(r.out.trim()) || 0 : 0;
2155
+ }
2156
+ function statusFor(ctx, area, task) {
2157
+ const m = ctx.manifest;
2158
+ fetchBaseOnce(ctx);
2159
+ const names = (area ? [area] : Object.keys(m.areas)).sort();
2160
+ const areas = names.map((name) => {
2161
+ const effort = ctx.registry.openEffortFor(m.project, name, area ? task : void 0);
2162
+ if (effort && area) touchEffort(ctx, effort);
2163
+ const worktree = worktreePathFor(ctx, name, area ? task : void 0);
2164
+ const out = {
2165
+ area: area && task ? `${name}--${task}` : name,
2166
+ leases: effort ? ctx.registry.leases({ effort: effort.id }) : [],
2167
+ behindBase: behindBase(ctx, worktree),
2168
+ notices: ctx.registry.notices(m.project, name)
2169
+ };
2170
+ if (effort) out.effort = effort;
2171
+ if (existsSync7(worktree)) out.worktree = worktree;
2172
+ return out;
2173
+ });
2174
+ return { project: m.project, areas, leases: ctx.registry.leases({ project: m.project }) };
2175
+ }
2176
+ function slotEnv(m, slot) {
2177
+ return slotVars(m, { slot, ports: portsForSlot(m, slot) });
2178
+ }
2179
+ function effortEnv(ctx, area, task) {
2180
+ const m = ctx.manifest;
2181
+ const effort = ctx.registry.openEffortFor(m.project, area, task);
2182
+ if (!effort)
2183
+ throw new WorkkitError(
2184
+ "EFFORT_NOT_FOUND",
2185
+ `no open effort on ${effortLabel2(area, task)}; \`work start --area ${area} \u2026\` first`,
2186
+ { area, task }
2187
+ );
2188
+ touchEffort(ctx, effort);
2189
+ const slot = ctx.registry.leases({ effort: effort.id, kind: "slot" })[0];
2190
+ const sb = ctx.registry.leases({ effort: effort.id, kind: "storybook" })[0];
2191
+ const vars = slotVars(m, {
2192
+ slot: slot ? slot.value : void 0,
2193
+ ports: slot?.ports ?? {},
2194
+ storybookPort: sb?.ports?.storybook,
2195
+ area,
2196
+ branch: effort.branch,
2197
+ worktree: effort.worktree,
2198
+ logDir: join8(effort.worktree, m.logs.dir)
2199
+ });
2200
+ return { ...vars, MODE: effort.mode };
2201
+ }
2202
+ function leaseEnv(ctx, effort, lease) {
2203
+ const vars = slotVars(ctx.manifest, {
2204
+ slot: lease.kind === "slot" ? lease.value : void 0,
2205
+ ports: lease.ports ?? {},
2206
+ area: effort.area,
2207
+ branch: effort.branch,
2208
+ worktree: effort.worktree,
2209
+ logDir: join8(effort.worktree, ctx.manifest.logs.dir)
2210
+ });
2211
+ return { ...process.env, ...vars };
2212
+ }
2213
+ async function releaseLease(ctx, effort, lease) {
2214
+ try {
2215
+ if (lease.kind === "slot" && lease.pids && Object.keys(lease.pids).length > 0) {
2216
+ const hasWorktree = effort !== void 0 && existsSync7(effort.worktree);
2217
+ await ctx.runner.stop({
2218
+ m: ctx.manifest,
2219
+ cwd: hasWorktree && effort ? effort.worktree : ctx.repoRoot,
2220
+ env: effort ? leaseEnv(ctx, effort, lease) : process.env,
2221
+ pids: lease.pids,
2222
+ signatures: lease.signatures,
2223
+ skipStopCommands: !hasWorktree,
2224
+ onLog: ctx.log
2225
+ });
2226
+ } else if (lease.kind === "storybook") {
2227
+ await ctx.storybrokr.down(String(lease.value));
2228
+ }
2229
+ } catch (err) {
2230
+ ctx.log(
2231
+ `while releasing ${lease.kind} ${lease.value}: ${err instanceof Error ? err.message : String(err)}`
2232
+ );
2233
+ }
2234
+ ctx.registry.release(lease.id);
2235
+ }
2236
+ function leaveNotices(ctx, effort, commons) {
2237
+ if (commons.length === 0) return 0;
2238
+ const notice = {
2239
+ from: effort.branch,
2240
+ text: `commons ${commons.join(", ")} changed on ${effort.branch}: sync and re-verify`,
2241
+ at: now()
2242
+ };
2243
+ let count = 0;
2244
+ for (const area of Object.keys(ctx.manifest.areas)) {
2245
+ if (area === effort.area) continue;
2246
+ ctx.registry.addNotice(ctx.manifest.project, area, notice);
2247
+ count++;
2248
+ }
2249
+ return count;
2250
+ }
2251
+ async function finishEffort(ctx, o) {
2252
+ const m = ctx.manifest;
2253
+ const effort = ctx.registry.openEffortFor(m.project, o.area, o.task) ?? ctx.registry.efforts({ project: m.project, area: o.area, state: "parked" }).filter((e) => (e.task ?? void 0) === (o.task ?? void 0)).sort((a, b) => b.started.localeCompare(a.started))[0];
2254
+ if (!effort)
2255
+ throw new WorkkitError(
2256
+ "EFFORT_NOT_FOUND",
2257
+ `no open or parked effort on ${effortLabel2(o.area, o.task)}`,
2258
+ { area: o.area, task: o.task }
2259
+ );
2260
+ if (!o.force && effort.participants && effort.participants.length > 0) {
2261
+ if (ctx.owner.session === effort.owner.session) {
2262
+ const [nextOwner, ...rest] = effort.participants;
2263
+ const updated = ctx.registry.updateEffort(effort.id, {
2264
+ owner: nextOwner,
2265
+ participants: rest,
2266
+ lastActivity: now()
2267
+ });
2268
+ touchEffort(ctx, updated);
2269
+ return { effort: updated, pushed: false, parked: false, left: true, notices: 0 };
2270
+ }
2271
+ if (effort.participants.some((p) => p.session === ctx.owner.session)) {
2272
+ const updated = ctx.registry.updateEffort(effort.id, {
2273
+ participants: effort.participants.filter((p) => p.session !== ctx.owner.session),
2274
+ lastActivity: now()
2275
+ });
2276
+ touchEffort(ctx, updated);
2277
+ return { effort: updated, pushed: false, parked: false, left: true, notices: 0 };
2278
+ }
2279
+ }
2280
+ const label = effortLabel2(effort.area, effort.task);
2281
+ const g = new Git(effort.worktree);
2282
+ let parked = false;
2283
+ if (g.isDirty()) {
2284
+ if (!o.park) {
2285
+ throw new WorkkitError(
2286
+ "DIRTY_WORKTREE",
2287
+ `${effort.worktree} has uncommitted changes: commit them, or \`work finish --park\` to commit them as wip(${label}) and push`,
2288
+ { worktree: effort.worktree }
2289
+ );
2290
+ }
2291
+ g.run(["add", "-A"]);
2292
+ g.run(["commit", "-q", "-m", `wip(${label}): parked ${now()}`]);
2293
+ parked = true;
2294
+ }
2295
+ if (o.intoArea) {
2296
+ if (!effort.task) {
2297
+ throw new WorkkitError(
2298
+ "MANIFEST_INVALID",
2299
+ "--into-area requires a task sub-effort (--task <slug>)",
2300
+ { area: effort.area }
2301
+ );
2302
+ }
2303
+ fetchBaseOnce(ctx);
2304
+ const parentBranch = branchFor(effort.type, effort.area);
2305
+ const { wg: areaGit } = ensureWorktree(ctx, effort.area, parentBranch);
2306
+ if (areaGit.isDirty()) {
2307
+ throw new WorkkitError(
2308
+ "DIRTY_WORKTREE",
2309
+ `parent area worktree ${areaGit.cwd} has uncommitted changes; commit or clean it before merging task ${effort.branch} --into-area`,
2310
+ { worktree: areaGit.cwd }
2311
+ );
2312
+ }
2313
+ const merged = areaGit.tryRun(["merge", "--no-edit", "-q", effort.branch]);
2314
+ if (merged.code !== 0) {
2315
+ const conflicted = areaGit.tryRun(["diff", "--name-only", "--diff-filter=U"]).out.split("\n").map((l) => l.trim()).filter(Boolean);
2316
+ areaGit.tryRun(["merge", "--abort"]);
2317
+ throw new WorkkitError(
2318
+ "SYNC_CONFLICT",
2319
+ `merging ${effort.branch} into ${parentBranch} conflicts in ${conflicted.join(", ")}; resolve in ${effort.worktree} before retrying \`work finish --into-area\``,
2320
+ { conflicted, worktree: areaGit.cwd }
2321
+ );
2322
+ }
2323
+ }
2324
+ for (const lease of ctx.registry.leases({ effort: effort.id }))
2325
+ await releaseLease(ctx, effort, lease);
2326
+ await Promise.resolve(ctx.storybrokr.downHost?.(storybookHostFor(m, effort.worktree))).catch(
2327
+ () => void 0
2328
+ );
2329
+ let notices = 0;
2330
+ if (!o.intoArea) {
2331
+ g.push(effort.branch);
2332
+ if (g.commitsNotOn(m.baseBranch).length > 0 && !g.isEquivalentToBase(m.baseBranch)) {
2333
+ const since = g.changedSince(m.baseBranch);
2334
+ const sinceSet = new Set(since);
2335
+ const changed = effort.baseSha ? g.changedPaths(effort.baseSha, "HEAD").filter((p) => sinceSet.has(p)) : since;
2336
+ notices = leaveNotices(ctx, effort, commonsTouched(m, changed));
2337
+ }
2338
+ }
2339
+ if (effort.task) {
2340
+ archiveWorktree(ctx, label, effort.worktree);
2341
+ const main = new Git(ctx.repoRoot);
2342
+ main.worktreeRemove(effort.worktree);
2343
+ if (o.intoArea) {
2344
+ main.deleteLocalBranch(effort.branch);
2345
+ }
2346
+ const finished2 = { ...effort, state: "finished", lastActivity: now() };
2347
+ ctx.registry.removeEfforts((e) => e.id === effort.id);
2348
+ return {
2349
+ effort: finished2,
2350
+ pushed: !o.intoArea,
2351
+ parked,
2352
+ mergedIntoArea: Boolean(o.intoArea),
2353
+ notices
2354
+ };
2355
+ }
2356
+ const finished = ctx.registry.updateEffort(effort.id, { state: "finished", lastActivity: now() });
2357
+ return { effort: finished, pushed: true, parked, notices };
2358
+ }
2359
+ async function reapLeases(ctx, o = {}) {
2360
+ const m = ctx.manifest;
2361
+ const at = o.now ?? /* @__PURE__ */ new Date();
2362
+ const efforts = new Map(ctx.registry.efforts({ project: m.project }).map((e) => [e.id, e]));
2363
+ const leases = ctx.registry.leases({ project: m.project });
2364
+ const doomed = /* @__PURE__ */ new Set();
2365
+ for (const l of leases) {
2366
+ const effort = efforts.get(l.effort);
2367
+ if (effort?.state === "starting" && Date.now() - Date.parse(effort.started) < STARTING_GRACE_MS)
2368
+ continue;
2369
+ const expired = Date.parse(l.expires) < at.getTime();
2370
+ const orphaned = !effort || !existsSync7(effort.worktree);
2371
+ const garbage = orphaned && !await anyPortAnswers(l.ports);
2372
+ if (expired || garbage) doomed.add(l.effort);
2373
+ }
2374
+ const reaped = leases.filter((l) => doomed.has(l.effort));
2375
+ if (o.dryRun) return { reaped };
2376
+ for (const lease of reaped) await releaseLease(ctx, efforts.get(lease.effort), lease);
2377
+ for (const id of doomed) {
2378
+ const effort = efforts.get(id);
2379
+ if (effort) {
2380
+ await Promise.resolve(ctx.storybrokr.downHost?.(storybookHostFor(m, effort.worktree))).catch(
2381
+ () => void 0
2382
+ );
2383
+ if (effort.state === "active" || effort.state === "starting") {
2384
+ ctx.registry.updateEffort(effort.id, {
2385
+ state: "parked",
2386
+ parkedReason: `idle: a lease expired by ${at.toISOString()}`,
2387
+ lastActivity: now()
2388
+ });
2389
+ }
2390
+ }
2391
+ }
2392
+ return { reaped };
2393
+ }
2394
+ var ARCHIVE_DIR = ".slot-archive";
2395
+ function dirSize(path) {
2396
+ if (!existsSync7(path)) return 0;
2397
+ let total = 0;
2398
+ for (const entry of readdirSync(path, { withFileTypes: true })) {
2399
+ const p = join8(path, entry.name);
2400
+ total += entry.isDirectory() ? dirSize(p) : statSync3(p).size;
2401
+ }
2402
+ return total;
2403
+ }
2404
+ function archiveWorktree(ctx, area, worktree) {
2405
+ const m = ctx.manifest;
2406
+ const areaRoot = join8(ctx.repoRoot, ARCHIVE_DIR, area);
2407
+ const stamp = now().replace(/[-:]/g, "").replace("T", "-").slice(0, 15);
2408
+ const target = join8(areaRoot, stamp);
2409
+ const archived = [];
2410
+ for (const rel of m.archive.paths) {
2411
+ const src = join8(worktree, rel);
2412
+ if (!existsSync7(src)) continue;
2413
+ const dst = join8(target, rel);
2414
+ mkdirSync6(dirname3(dst), { recursive: true });
2415
+ cpSync(src, dst, { recursive: true });
2416
+ archived.push(dst);
2417
+ }
2418
+ if (archived.length > 0) ensureExcluded(ctx.repoRoot, [`${ARCHIVE_DIR}/`]);
2419
+ if (existsSync7(areaRoot)) {
2420
+ const stamps = readdirSync(areaRoot, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name).sort().reverse();
2421
+ const cutoff = Date.now() - m.archive.keepDays * 864e5;
2422
+ stamps.forEach((d, i) => {
2423
+ const t = statSync3(join8(areaRoot, d)).mtimeMs;
2424
+ if (i >= m.archive.keepPerArea || t < cutoff)
2425
+ rmSync3(join8(areaRoot, d), { recursive: true, force: true });
2426
+ });
2427
+ }
2428
+ return archived;
2429
+ }
2430
+ async function retireArea(ctx, o) {
2431
+ const m = ctx.manifest;
2432
+ if (!m.areas[o.area])
2433
+ throw new WorkkitError("AREA_UNKNOWN", `unknown area "${o.area}"`, { area: o.area });
2434
+ const open = ctx.registry.efforts({ project: m.project, area: o.area }).find((e) => e.state === "starting" || e.state === "active");
2435
+ if (open)
2436
+ throw new WorkkitError(
2437
+ "EFFORT_OPEN",
2438
+ `an effort is open on ${effortLabel2(open.area, open.task)} (${open.owner.session}); \`work finish\` it first`,
2439
+ { owner: open.owner.session }
2440
+ );
2441
+ const worktree = realpathOr2(worktreePathFor(ctx, o.area));
2442
+ const main = new Git(ctx.repoRoot);
2443
+ let archived = [];
2444
+ await Promise.resolve(ctx.storybrokr.downHost?.(storybookHostFor(m, worktree))).catch(
2445
+ () => void 0
2446
+ );
2447
+ if (existsSync7(worktree)) {
2448
+ const g = new Git(worktree);
2449
+ if (g.isDirty())
2450
+ throw new WorkkitError(
2451
+ "UNPUSHED",
2452
+ `${worktree} has uncommitted changes; commit and push them (or \`work finish --park\`) before retiring`,
2453
+ { worktree }
2454
+ );
2455
+ const unpushed = g.unpushedCount(m.baseBranch);
2456
+ if (unpushed > 0)
2457
+ throw new WorkkitError(
2458
+ "UNPUSHED",
2459
+ `${g.currentBranch()} has ${unpushed} commit(s) not on origin; push before retiring`,
2460
+ { worktree, unpushed }
2461
+ );
2462
+ archived = archiveWorktree(ctx, o.area, worktree);
2463
+ main.worktreeRemove(worktree);
2464
+ }
2465
+ const branchesDeleted = [];
2466
+ const branchesKept = [];
2467
+ const allAreaBranches = m.branch.types.map((type) => `${type}/${o.area}`);
2468
+ for (const branch of allAreaBranches) {
2469
+ if (!main.branchExists(branch)) continue;
2470
+ const onOrigin = main.remoteBranchExists(branch) && main.tryRun(["rev-list", "--count", `origin/${branch}..${branch}`]).out.trim() === "0";
2471
+ if (onOrigin) {
2472
+ main.deleteLocalBranch(branch);
2473
+ branchesDeleted.push(branch);
2474
+ } else branchesKept.push(branch);
2475
+ }
2476
+ ctx.registry.removeEfforts((e) => e.project === m.project && e.area === o.area);
2477
+ ctx.registry.clearNotices(m.project, o.area);
2478
+ ctx.registry.clearNoticesFrom(m.project, allAreaBranches);
2479
+ return { archived, removed: worktree, branchesDeleted, branchesKept };
2480
+ }
2481
+ var BEHIND_LIMIT = 20;
2482
+ var NOTICE_STALE_MS = 7 * 864e5;
2483
+ var ARCHIVE_LIMIT_BYTES = 5 * 1024 ** 3;
2484
+ function registeredWorktrees(ctx) {
2485
+ const out = [];
2486
+ const porcelain = new Git(ctx.repoRoot).run(["worktree", "list", "--porcelain"]);
2487
+ let current = null;
2488
+ for (const line of porcelain.split("\n")) {
2489
+ if (line.startsWith("worktree ")) current = { path: line.slice(9), branch: "" };
2490
+ else if (line.startsWith("branch ") && current)
2491
+ current.branch = line.slice(7).replace(/^refs\/heads\//, "");
2492
+ else if (line === "" && current) {
2493
+ out.push(current);
2494
+ current = null;
2495
+ }
2496
+ }
2497
+ if (current) out.push(current);
2498
+ const wtRoot = join8(realpathOr2(ctx.repoRoot), ctx.manifest.worktreeRoot);
2499
+ return out.filter((w) => existsSync7(w.path) && realpathOr2(w.path).startsWith(wtRoot));
2500
+ }
2501
+ async function auditProject(ctx) {
2502
+ const m = ctx.manifest;
2503
+ fetchBaseOnce(ctx);
2504
+ const findings = [];
2505
+ const types = m.branch.types.join("|");
2506
+ const areaOf = (branch) => {
2507
+ const match = new RegExp(`^(${types})/(.+?)(?:--([a-z0-9][a-z0-9_-]*))?$`).exec(branch);
2508
+ return match && m.areas[match[2]] ? match[2] : null;
2509
+ };
2510
+ for (const w of registeredWorktrees(ctx)) {
2511
+ const area = areaOf(w.branch);
2512
+ if (!area) {
2513
+ findings.push({
2514
+ kind: "foreign-branch",
2515
+ detail: `${w.path} is on "${w.branch || "detached HEAD"}", not a <type>/<area> branch of a declared area`
2516
+ });
2517
+ continue;
2518
+ }
2519
+ const g = new Git(w.path);
2520
+ if (g.isDirty())
2521
+ findings.push({
2522
+ kind: "dirty",
2523
+ area,
2524
+ detail: `${w.path} has uncommitted changes on ${w.branch}`
2525
+ });
2526
+ const unpushed = g.unpushedCount(m.baseBranch);
2527
+ if (unpushed > 0)
2528
+ findings.push({
2529
+ kind: "unpushed",
2530
+ area,
2531
+ detail: `${w.branch} has ${unpushed} commit(s) not on origin`
2532
+ });
2533
+ const behind = behindBase(ctx, w.path);
2534
+ if (behind > BEHIND_LIMIT)
2535
+ findings.push({
2536
+ kind: "behind-base",
2537
+ area,
2538
+ detail: `${w.branch} is ${behind} commits behind ${m.baseBranch}`
2539
+ });
2540
+ }
2541
+ const nowMs = Date.now();
2542
+ for (const l of ctx.registry.leases({ project: m.project })) {
2543
+ const half = (Date.parse(l.touched) + Date.parse(l.expires)) / 2;
2544
+ if (nowMs > half)
2545
+ findings.push({
2546
+ kind: "lease-aging",
2547
+ detail: `${l.kind} ${l.value} held by ${l.owner.session}, last used ${l.touched}, expires ${l.expires}`
2548
+ });
2549
+ }
2550
+ for (const area of Object.keys(m.areas)) {
2551
+ for (const n of ctx.registry.notices(m.project, area)) {
2552
+ if (nowMs - Date.parse(n.at) > NOTICE_STALE_MS)
2553
+ findings.push({ kind: "notice-stale", area, detail: `${n.text} (since ${n.at})` });
2554
+ }
2555
+ }
2556
+ const bytes = dirSize(join8(ctx.repoRoot, ARCHIVE_DIR));
2557
+ if (bytes > ARCHIVE_LIMIT_BYTES)
2558
+ findings.push({
2559
+ kind: "archive-size",
2560
+ detail: `${ARCHIVE_DIR} holds ${(bytes / 1024 ** 3).toFixed(1)} GB`
2561
+ });
2562
+ return findings;
2563
+ }
2564
+
2565
+ // src/commands/_shared/output.ts
2566
+ import chalk2 from "chalk";
2567
+ function printJson(value) {
2568
+ console.log(JSON.stringify(value, null, 2));
2569
+ }
2570
+ function fail(err, json) {
2571
+ const body = toErrorBody(err);
2572
+ if (json) console.error(JSON.stringify(body));
2573
+ else {
2574
+ console.error(chalk2.red(`${body.code}: ${body.message}`));
2575
+ if (body.details) console.error(chalk2.gray(` ${JSON.stringify(body.details)}`));
2576
+ }
2577
+ process.exit(exitCodeFor(body.code));
2578
+ }
2579
+ function warn(line) {
2580
+ console.error(chalk2.yellow(`! ${line}`));
2581
+ }
2582
+
2583
+ // src/commands/audit.ts
2584
+ function registerAudit(program2) {
2585
+ program2.command("audit").description(
2586
+ "List what would otherwise be forgotten: unsaved work, stray checkouts, aging leases, drift, stale notices"
2587
+ ).option("--project-root <dir>", "repository root (default: the main checkout of the cwd)").option("--json", "print the findings as JSON").action(async (o) => {
2588
+ try {
2589
+ const ctx = await buildCtx({ projectRoot: o.projectRoot, quiet: true });
2590
+ const findings = await auditProject(ctx);
2591
+ if (o.json) printJson(findings);
2592
+ else if (findings.length === 0) console.log(chalk3.green("nothing forgotten"));
2593
+ else
2594
+ for (const f of findings)
2595
+ console.log(
2596
+ `${chalk3.yellow(f.kind.padEnd(14))} ${f.area ? `${f.area} ` : ""}${f.detail}`
2597
+ );
2598
+ } catch (err) {
2599
+ fail(err, Boolean(o.json));
2600
+ }
2601
+ });
2602
+ }
2603
+
2604
+ // src/commands/env.ts
2605
+ function registerEnv(program2) {
2606
+ program2.command("env").description("The slot-derived variables of an area's open effort, or of a slot number alone").option("--area <area>", "the area whose open effort to read").option("--task <slug>", "intra-area task slug").option(
2607
+ "--slot <n>",
2608
+ "compute the variables for this slot from the manifest alone",
2609
+ (v) => Number(v)
2610
+ ).option("--project-root <dir>", "repository root (default: the main checkout of the cwd)").option("--json", "print as JSON (default: KEY=value lines)").option("--sh", "print KEY=value lines (the default)").action(
2611
+ async (o) => {
2612
+ try {
2613
+ const ctx = await buildCtx({ projectRoot: o.projectRoot, quiet: true });
2614
+ let vars;
2615
+ if (o.area) vars = effortEnv(ctx, o.area, o.task);
2616
+ else if (o.slot !== void 0 && Number.isInteger(o.slot))
2617
+ vars = slotEnv(ctx.manifest, o.slot);
2618
+ else throw new WorkkitError("EFFORT_NOT_FOUND", "pass --area <area> or --slot <n>");
2619
+ if (o.json) printJson(vars);
2620
+ else for (const [k, v] of Object.entries(vars)) console.log(`${k}=${v}`);
2621
+ } catch (err) {
2622
+ fail(err, Boolean(o.json));
2623
+ }
2624
+ }
2625
+ );
2626
+ }
2627
+
2628
+ // src/commands/finish.ts
2629
+ import chalk4 from "chalk";
2630
+ function registerFinish(program2) {
2631
+ program2.command("finish").description(
2632
+ "Stop the effort's runner, release its leases, push its branch (or merge --into-area); area worktrees stay, task worktrees are cleaned up"
2633
+ ).requiredOption("--area <area>", "the area whose open effort to finish").option("--task <slug>", "finish an intra-area task sub-effort").option("--park", "commit uncommitted changes as wip(<area>) instead of refusing").option("--into-area", "merge task branch into <type>/<area> instead of pushing to origin").option("--force", "stop and finish even if other joined participants remain").option("--project-root <dir>", "repository root (default: the main checkout of the cwd)").option("--json", "print the result as JSON").action(
2634
+ async (o) => {
2635
+ try {
2636
+ const ctx = await buildCtx({ projectRoot: o.projectRoot, quiet: Boolean(o.json) });
2637
+ const r = await finishEffort(ctx, {
2638
+ area: o.area,
2639
+ task: o.task,
2640
+ park: o.park,
2641
+ intoArea: o.intoArea,
2642
+ force: o.force
2643
+ });
2644
+ if (o.json) printJson(r);
2645
+ else {
2646
+ const label = r.effort.task ? `${r.effort.area}--${r.effort.task}` : r.effort.area;
2647
+ if (r.left) {
2648
+ console.log(`${chalk4.bold(label)}: left shared effort (other participants remain)`);
2649
+ } else if (r.mergedIntoArea) {
2650
+ console.log(
2651
+ `${chalk4.bold(label)} finished: ${r.effort.branch} merged into ${r.effort.type}/${r.effort.area}`
2652
+ );
2653
+ } else {
2654
+ console.log(
2655
+ `${chalk4.bold(label)} finished: ${r.effort.branch} pushed${r.parked ? " (uncommitted changes parked as wip)" : ""}`
2656
+ );
2657
+ }
2658
+ if (r.notices) console.log(` ${r.notices} area(s) told about commons changes`);
2659
+ }
2660
+ } catch (err) {
2661
+ fail(err, Boolean(o.json));
2662
+ }
2663
+ }
2664
+ );
2665
+ }
2666
+
2667
+ // src/commands/hook.ts
2668
+ import { readFileSync as readFileSync5, realpathSync as realpathSync5 } from "fs";
2669
+ import { resolve as resolve2 } from "path";
2670
+ import chalk5 from "chalk";
2671
+ var ZEROS = /^0+$/;
2672
+ async function hookContext(cwd) {
2673
+ const git = new Git(cwd);
2674
+ const repoRoot = git.mainRoot();
2675
+ try {
2676
+ const manifest = await loadManifest(repoRoot);
2677
+ return { git, repoRoot, manifest, registry: Registry.open(homeDir()) };
2678
+ } catch (err) {
2679
+ if (err instanceof WorkkitError && err.code === "MANIFEST_NOT_FOUND") return null;
2680
+ throw err;
2681
+ }
2682
+ }
2683
+ async function runPreCommit(cwd) {
2684
+ const c = await hookContext(cwd);
2685
+ if (!c) return 0;
2686
+ const root = c.git.root();
2687
+ touchByWorktree(c.registry, c.manifest, root);
2688
+ const { refusals, warnings } = checkCommit({
2689
+ m: c.manifest,
2690
+ registry: c.registry,
2691
+ git: c.git,
2692
+ project: c.manifest.project,
2693
+ branch: c.git.currentBranch(),
2694
+ stagedPaths: c.git.changedPathsStaged(),
2695
+ ownerSession: currentOwner().session,
2696
+ checkoutRoot: root
2697
+ });
2698
+ for (const w of warnings) console.error(chalk5.yellow(`work: ${w}`));
2699
+ for (const r of refusals) console.error(chalk5.red(`work: ${r}`));
2700
+ return refusals.length ? 2 : 0;
2701
+ }
2702
+ async function runPrePush(cwd, stdin) {
2703
+ const c = await hookContext(cwd);
2704
+ if (!c) return 0;
2705
+ touchByWorktree(c.registry, c.manifest, c.git.root());
2706
+ let code = 0;
2707
+ for (const line of stdin.split("\n").filter(Boolean)) {
2708
+ const [localRef, localSha, remoteRef, remoteSha] = line.split(/\s+/);
2709
+ if (!localRef || !localSha || !remoteRef) continue;
2710
+ const isDelete = ZEROS.test(localSha);
2711
+ const branch = isDelete ? "" : localRef.replace(/^refs\/heads\//, "");
2712
+ let changed = [];
2713
+ if (!isDelete) {
2714
+ const from = remoteSha && !ZEROS.test(remoteSha) ? remoteSha : `origin/${c.manifest.baseBranch}`;
2715
+ const range = remoteSha && !ZEROS.test(remoteSha) ? `${from}..${localSha}` : `${from}...${localSha}`;
2716
+ changed = c.git.tryRun(["diff", "--name-only", "--no-renames", range]).out.split("\n").filter(Boolean);
2717
+ }
2718
+ const { refusals, warnings } = checkPush({
2719
+ m: c.manifest,
2720
+ registry: c.registry,
2721
+ git: c.git,
2722
+ project: c.manifest.project,
2723
+ branch,
2724
+ remoteRef,
2725
+ isDelete,
2726
+ changedPaths: changed
2727
+ });
2728
+ for (const w of warnings) console.error(chalk5.yellow(`work: ${w}`));
2729
+ for (const r of refusals) console.error(chalk5.red(`work: ${r}`));
2730
+ if (refusals.length) code = 2;
2731
+ }
2732
+ return code;
2733
+ }
2734
+ function touchByWorktree(registry, m, root) {
2735
+ const same2 = (p) => {
2736
+ try {
2737
+ return realpathSync5(p) === realpathSync5(root);
2738
+ } catch {
2739
+ return false;
2740
+ }
2741
+ };
2742
+ const hours = {
2743
+ slot: m.expiry.slotHours,
2744
+ storybook: m.expiry.storybookHours,
2745
+ commons: m.expiry.commonsHours
2746
+ };
2747
+ for (const e of registry.efforts({ project: m.project })) {
2748
+ if (e.state !== "active" && e.state !== "starting" || !same2(e.worktree)) continue;
2749
+ for (const l of registry.leases({ effort: e.id })) registry.touch(l.id, hours[l.kind]);
2750
+ registry.updateEffort(e.id, { lastActivity: (/* @__PURE__ */ new Date()).toISOString() });
2751
+ }
2752
+ }
2753
+ function registerHook(program2) {
2754
+ const hook = program2.command("hook").description("Entry points the installed git hooks call");
2755
+ hook.command("pre-commit").description("Refuse commits on protected branches and writes under write-locked commons").action(async () => {
2756
+ try {
2757
+ process.exit(await runPreCommit(process.cwd()));
2758
+ } catch (err) {
2759
+ fail(err, false);
2760
+ }
2761
+ });
2762
+ hook.command("pre-push").description(
2763
+ "Refuse pushes to protected branches; warn when paths leave the effort scope or touch commons"
2764
+ ).argument("[remote]", "passed by git, unused").argument("[url]", "passed by git, unused").action(async () => {
2765
+ try {
2766
+ const stdin = process.stdin.isTTY ? "" : readFileSync5(0, "utf8");
2767
+ process.exit(await runPrePush(process.cwd(), stdin));
2768
+ } catch (err) {
2769
+ fail(err, false);
2770
+ }
2771
+ });
2772
+ const hooks = program2.command("hooks").description("Manage the git hooks in a clone");
2773
+ hooks.command("install").description(
2774
+ "Write .helmsmith/hooks and point this clone's core.hooksPath at them (for a repo whose manifest already exists)"
2775
+ ).option("--project-root <dir>", "repository root (default: the main checkout of the cwd)").option("--json", "print the result as JSON").action(async (o) => {
2776
+ try {
2777
+ const repoRoot = o.projectRoot ? resolve2(o.projectRoot) : new Git(process.cwd()).mainRoot();
2778
+ const manifest = await loadManifest(repoRoot);
2779
+ const out = installHooks(repoRoot, { protectedBranches: manifest.protectedBranches });
2780
+ if (o.json) printJson(out);
2781
+ else for (const f of out.files) console.log(`installed ${f}`);
2782
+ } catch (err) {
2783
+ fail(err, Boolean(o.json));
2784
+ }
2785
+ });
2786
+ }
2787
+
2788
+ // src/commands/init.ts
2789
+ import { existsSync as existsSync8, writeFileSync as writeFileSync5 } from "fs";
2790
+ import { join as join9, resolve as resolve3 } from "path";
2791
+ var STORYBOOK_BASE = 6100;
2792
+ function defaultService(name) {
2793
+ const PORT = `\${PORT_${name.toUpperCase()}}`;
2794
+ if (name === "postgres" || name === "db") {
2795
+ return {
2796
+ start: `docker compose up -d ${name}`,
2797
+ stop: `docker compose stop ${name}`,
2798
+ health: `pg_isready -h 127.0.0.1 -p ${PORT} -q`,
2799
+ healthTimeoutMs: 12e4
2800
+ };
2801
+ }
2802
+ return {
2803
+ start: `make -C ${name} dev`,
2804
+ stop: `make -C ${name} dev-stop`,
2805
+ health: `curl -sf -o /dev/null http://127.0.0.1:${PORT}/health`,
2806
+ healthTimeoutMs: 3e5
2807
+ };
2808
+ }
2809
+ function buildStarterManifest(o) {
2810
+ const ports = {};
2811
+ const services = {};
2812
+ for (const spec of o.services) {
2813
+ const m = /^([a-z][a-z0-9_-]*)=(\d{4,5})$/.exec(spec);
2814
+ if (!m)
2815
+ throw new WorkkitError("MANIFEST_INVALID", `--service expects name=port, got "${spec}"`);
2816
+ ports[m[1]] = { base: Number(m[2]) };
2817
+ services[m[1]] = defaultService(m[1]);
2818
+ }
2819
+ if (o.storybookHost) ports.storybook = { base: STORYBOOK_BASE };
2820
+ const manifest = {
2821
+ project: o.project,
2822
+ baseBranch: o.baseBranch,
2823
+ protectedBranches: [o.baseBranch],
2824
+ worktreeRoot: o.worktreeRoot ?? ".claude/worktrees",
2825
+ branch: { types: ["feature", "chore", "fix"] },
2826
+ slots: { count: 10, reserved: [0] },
2827
+ ports: { services: ports },
2828
+ services,
2829
+ ...o.storybookHost ? { storybook: { hostRoot: o.storybookHost } } : {},
2830
+ logs: { dir: ".logs" },
2831
+ refresh: [],
2832
+ scopes: {
2833
+ frontend: [
2834
+ "app/{group}/{section}/**",
2835
+ "components/{group}/{section}/**",
2836
+ "app/api/{section}/**"
2837
+ ],
2838
+ backend: ["services/{module}/**"]
2839
+ },
2840
+ areas: {},
2841
+ commons: {},
2842
+ expiry: { slotHours: 12, commonsHours: 4, storybookHours: 2 },
2843
+ archive: { paths: [], keepDays: 30, keepPerArea: 5 }
2844
+ };
2845
+ validateManifest(manifest);
2846
+ return manifest;
2847
+ }
2848
+ var HEADER = `// biome-ignore-all lint/suspicious/noTemplateCurlyInString: \${PORT_*} are the manifest's own placeholders
2849
+ // helmsmith.config.mjs \u2014 read by \`work\` (@helmsmith/workbrokr). Written by \`work init\`.
2850
+ // Edit: the services' start/stop/health commands, the scope templates, the areas (leaves only,
2851
+ // each with its backend module) and the commons. Nothing here is read by the application.
2852
+ `;
2853
+ function runInit(o) {
2854
+ const repoRoot = resolve3(o.repoRoot);
2855
+ for (const name of MANIFEST_FILES) {
2856
+ if (existsSync8(join9(repoRoot, name)) && !o.force) {
2857
+ throw new WorkkitError(
2858
+ "MANIFEST_INVALID",
2859
+ `${name} already exists in ${repoRoot}; pass --force to overwrite`
2860
+ );
2861
+ }
2862
+ }
2863
+ const manifest = buildStarterManifest(o);
2864
+ const manifestPath = join9(repoRoot, "helmsmith.config.mjs");
2865
+ writeFileSync5(manifestPath, `${HEADER}export default ${JSON.stringify(manifest, null, 2)};
2866
+ `);
2867
+ claimRanges(Registry.open(o.home), validateManifest(manifest), repoRoot);
2868
+ const hooks = o.hooks ? installHooks(repoRoot, { protectedBranches: [o.baseBranch] }).files : [];
2869
+ return { manifestPath, hooks };
2870
+ }
2871
+ function defaultRepoRoot() {
2872
+ try {
2873
+ return new Git(process.cwd()).mainRoot();
2874
+ } catch {
2875
+ return process.cwd();
2876
+ }
2877
+ }
2878
+ function defaultBaseBranch(repoRoot) {
2879
+ const g = new Git(repoRoot);
2880
+ const head = g.tryRun(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"]);
2881
+ if (head.code === 0) return head.out.trim().replace(/^origin\//, "");
2882
+ return "main";
2883
+ }
2884
+ function registerInit(program2) {
2885
+ program2.command("init").description(
2886
+ "Write helmsmith.config.mjs for this repo, claim its port ranges, install the git hooks"
2887
+ ).requiredOption("--project <name>", "project name (lowercase, digits, dashes)").option("--base-branch <branch>", "base branch (default: origin's HEAD, else main)").option(
2888
+ "--service <name=port>",
2889
+ "a service and its slot-0 port; repeat per service",
2890
+ (v, acc) => [...acc, v],
2891
+ []
2892
+ ).option("--storybook-host <dir>", "the package whose .storybook storybrokr boots from").option("--worktree-root <dir>", "where area worktrees live (default .claude/worktrees)").option("--repo-root <dir>", "repository root (default: the main checkout of the cwd)").option("--no-hooks", "do not install the git hooks").option("--force", "overwrite an existing manifest").option("--json", "print the result as JSON").action(
2893
+ (o) => {
2894
+ try {
2895
+ const repoRoot = o.repoRoot ? resolve3(o.repoRoot) : defaultRepoRoot();
2896
+ if (o.service.length === 0)
2897
+ throw new WorkkitError(
2898
+ "MANIFEST_INVALID",
2899
+ "at least one --service name=port is required"
2900
+ );
2901
+ const out = runInit({
2902
+ repoRoot,
2903
+ home: homeDir(),
2904
+ project: o.project,
2905
+ baseBranch: o.baseBranch ?? defaultBaseBranch(repoRoot),
2906
+ services: o.service,
2907
+ storybookHost: o.storybookHost,
2908
+ worktreeRoot: o.worktreeRoot,
2909
+ hooks: o.hooks,
2910
+ force: o.force === true
2911
+ });
2912
+ if (o.json) printJson(out);
2913
+ else {
2914
+ console.log(`wrote ${out.manifestPath}`);
2915
+ for (const h of out.hooks) console.log(`installed ${h}`);
2916
+ console.log(
2917
+ "next: edit the services and areas, commit helmsmith.config.mjs and .helmsmith/hooks, then `work start`"
2918
+ );
2919
+ }
2920
+ } catch (err) {
2921
+ fail(err, Boolean(o.json));
2922
+ }
2923
+ }
2924
+ );
2925
+ }
2926
+
2927
+ // src/mcp/server.ts
2928
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2929
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
2930
+ import { z as z2 } from "zod";
2931
+
2932
+ // src/version.ts
2933
+ import { existsSync as existsSync9, readFileSync as readFileSync6 } from "fs";
2934
+ import { dirname as dirname4, join as join10 } from "path";
2935
+ import { fileURLToPath } from "url";
2936
+ function findPackageJson(startDir) {
2937
+ let dir = startDir;
2938
+ for (; ; ) {
2939
+ const candidate = join10(dir, "package.json");
2940
+ if (existsSync9(candidate)) return candidate;
2941
+ const parent = dirname4(dir);
2942
+ if (parent === dir) throw new Error(`package.json not found above ${startDir}`);
2943
+ dir = parent;
2944
+ }
2945
+ }
2946
+ var pkgFile = findPackageJson(dirname4(fileURLToPath(import.meta.url)));
2947
+ var VERSION = JSON.parse(readFileSync6(pkgFile, "utf8")).version;
2948
+
2949
+ // src/mcp/server.ts
2950
+ var ok = (value) => ({
2951
+ content: [{ type: "text", text: JSON.stringify(value, null, 2) }]
2952
+ });
2953
+ var failed = (err) => ({
2954
+ content: [{ type: "text", text: JSON.stringify(toErrorBody(err)) }],
2955
+ isError: true
2956
+ });
2957
+ async function guard(fn) {
2958
+ try {
2959
+ return ok(await fn());
2960
+ } catch (err) {
2961
+ return failed(err);
2962
+ }
2963
+ }
2964
+ function buildMcpServer(ctxFactory) {
2965
+ const server = new McpServer({ name: "work", version: VERSION });
2966
+ server.registerTool(
2967
+ "work_start",
2968
+ {
2969
+ description: "Start an effort on an area (or intra-area task): its worktree on <type>/<area> (or <type>/<area>--<task>), synced from the base branch, refreshed, leased (a slot for fullstack/backend, a storybrokr instance for frontend with a story) and running. Refuses with EFFORT_OPEN (another effort is open; join=true to share it), SCOPE_CONFLICT, SYNC_CONFLICT (resolve in the worktree, rerun with sync=false).",
2970
+ inputSchema: {
2971
+ area: z2.string().describe("a leaf area from helmsmith.config (e.g. org/applications)"),
2972
+ task: z2.string().optional().describe("optional intra-area task slug for parallel sub-efforts (<type>/<area>--<task>)"),
2973
+ type: z2.string().describe("feature | chore | fix"),
2974
+ mode: z2.enum(["frontend", "backend", "fullstack"]),
2975
+ scopes: z2.array(z2.string()).optional().describe("optional narrowed scope globs for a task sub-effort"),
2976
+ story: z2.string().optional().describe(
2977
+ "frontend: story file or component folder for storybrokr, relative to its host"
2978
+ ),
2979
+ join: z2.boolean().optional().describe("work in the already-open effort instead of refusing"),
2980
+ sync: z2.boolean().optional().describe("fetch and merge the base branch first (default true)"),
2981
+ projectRoot: z2.string().optional().describe("optional repository root path override")
2982
+ }
2983
+ },
2984
+ async ({ area, task, type, mode, scopes, story, join: join11, sync, projectRoot }) => guard(
2985
+ async () => startEffort(await ctxFactory(projectRoot), {
2986
+ area,
2987
+ task,
2988
+ type,
2989
+ mode,
2990
+ scopes,
2991
+ story,
2992
+ join: join11,
2993
+ sync
2994
+ })
2995
+ )
2996
+ );
2997
+ server.registerTool(
2998
+ "work_promote",
2999
+ {
3000
+ description: "Promote an open effort in place to backend or fullstack mode, claiming a slot if needed and starting only newly required services.",
3001
+ inputSchema: {
3002
+ area: z2.string().describe("the area of the open effort"),
3003
+ task: z2.string().optional().describe("optional intra-area task slug"),
3004
+ mode: z2.enum(["backend", "fullstack"]).describe("target mode to promote into"),
3005
+ story: z2.string().optional().describe("optional story path"),
3006
+ projectRoot: z2.string().optional().describe("optional repository root path override")
3007
+ }
3008
+ },
3009
+ async ({ area, task, mode, story, projectRoot }) => guard(async () => promoteEffort(await ctxFactory(projectRoot), { area, task, mode, story }))
3010
+ );
3011
+ server.registerTool(
3012
+ "work_status",
3013
+ {
3014
+ description: "Per area: the open effort, its leases, how far behind the base branch it is, pending notices; plus every lease of the project.",
3015
+ inputSchema: {
3016
+ area: z2.string().optional(),
3017
+ task: z2.string().optional(),
3018
+ projectRoot: z2.string().optional().describe("optional repository root path override")
3019
+ }
3020
+ },
3021
+ async ({ area, task, projectRoot }) => guard(async () => statusFor(await ctxFactory(projectRoot), area, task))
3022
+ );
3023
+ server.registerTool(
3024
+ "work_finish",
3025
+ {
3026
+ description: "Stop the effort's runner, release its leases, push its branch (or merge --into-area for task sub-efforts), leave commons notices. Refuses DIRTY_WORKTREE unless park=true (commits as wip).",
3027
+ inputSchema: {
3028
+ area: z2.string(),
3029
+ task: z2.string().optional().describe("optional intra-area task slug"),
3030
+ park: z2.boolean().optional(),
3031
+ intoArea: z2.boolean().optional().describe("merge task branch into <type>/<area> instead of pushing to origin"),
3032
+ force: z2.boolean().optional().describe("stop and finish even if other joined participants remain"),
3033
+ projectRoot: z2.string().optional().describe("optional repository root path override")
3034
+ }
3035
+ },
3036
+ async ({ area, task, park, intoArea, force, projectRoot }) => guard(
3037
+ async () => finishEffort(await ctxFactory(projectRoot), { area, task, park, intoArea, force })
3038
+ )
3039
+ );
3040
+ server.registerTool(
3041
+ "work_reap",
3042
+ {
3043
+ description: "Expire idle leases: stop only what they started, release them, park their efforts. dryRun lists without touching.",
3044
+ inputSchema: {
3045
+ dryRun: z2.boolean().optional(),
3046
+ projectRoot: z2.string().optional().describe("optional repository root path override")
3047
+ }
3048
+ },
3049
+ async ({ dryRun, projectRoot }) => guard(async () => reapLeases(await ctxFactory(projectRoot), { dryRun }))
3050
+ );
3051
+ server.registerTool(
3052
+ "work_audit",
3053
+ {
3054
+ description: "Findings: dirty or unpushed area worktrees, foreign worktrees, aging leases, drift from the base branch, stale notices, archive size.",
3055
+ inputSchema: {
3056
+ projectRoot: z2.string().optional().describe("optional repository root path override")
3057
+ }
3058
+ },
3059
+ async ({ projectRoot }) => guard(async () => auditProject(await ctxFactory(projectRoot)))
3060
+ );
3061
+ server.registerTool(
3062
+ "work_env",
3063
+ {
3064
+ description: "The slot-derived variables of an area's open effort (PORT_*, SLOT, LOG_DIR, WORKTREE, BRANCH, MODE).",
3065
+ inputSchema: {
3066
+ area: z2.string(),
3067
+ task: z2.string().optional(),
3068
+ projectRoot: z2.string().optional().describe("optional repository root path override")
3069
+ }
3070
+ },
3071
+ async ({ area, task, projectRoot }) => guard(async () => effortEnv(await ctxFactory(projectRoot), area, task))
3072
+ );
3073
+ return server;
3074
+ }
3075
+ async function runStdio() {
3076
+ const server = buildMcpServer((projectRoot) => buildCtx({ projectRoot, quiet: true }));
3077
+ await server.connect(new StdioServerTransport());
3078
+ }
3079
+
3080
+ // src/commands/mcp.ts
3081
+ function registerMcp(program2) {
3082
+ program2.command("mcp").description("Serve the MCP stdio interface (the same verbs as the CLI)").action(async () => {
3083
+ await runStdio();
3084
+ });
3085
+ }
3086
+
3087
+ // src/commands/promote.ts
3088
+ import chalk6 from "chalk";
3089
+ function registerPromote(program2) {
3090
+ program2.command("promote").description("Promote an open effort in place to backend or fullstack mode").requiredOption("--area <area>", "the area of the open effort").option("--task <slug>", "intra-area task slug if promoting a task sub-effort").requiredOption("--mode <mode>", "target mode: backend | fullstack").option("--story <path>", "optional story path to attach via storybrokr").option("--project-root <dir>", "repository root (default: the main checkout of the cwd)").option("--json", "print the result as JSON").action(
3091
+ async (o) => {
3092
+ try {
3093
+ const ctx = await buildCtx({ projectRoot: o.projectRoot, quiet: Boolean(o.json) });
3094
+ const r = await promoteEffort(ctx, {
3095
+ area: o.area,
3096
+ task: o.task,
3097
+ mode: o.mode,
3098
+ story: o.story
3099
+ });
3100
+ if (o.json) printJson(r);
3101
+ else {
3102
+ const label = r.effort.task ? `${r.effort.area}--${r.effort.task}` : r.effort.area;
3103
+ console.log(
3104
+ `${chalk6.bold(label)} promoted to ${r.effort.mode}${r.startedServices.length ? ` (started: ${r.startedServices.join(", ")})` : ""}`
3105
+ );
3106
+ for (const w of r.warnings) warn(w);
3107
+ }
3108
+ } catch (err) {
3109
+ fail(err, Boolean(o.json));
3110
+ }
3111
+ }
3112
+ );
3113
+ }
3114
+
3115
+ // src/commands/reap.ts
3116
+ import chalk7 from "chalk";
3117
+ function registerReap(program2) {
3118
+ program2.command("reap").description(
3119
+ "Expire idle leases: stop only what they started, release them, park their efforts"
3120
+ ).option("--dry-run", "list what would be reaped without touching anything").option("--project-root <dir>", "repository root (default: the main checkout of the cwd)").option("--json", "print the result as JSON").action(async (o) => {
3121
+ try {
3122
+ const ctx = await buildCtx({ projectRoot: o.projectRoot, quiet: Boolean(o.json) });
3123
+ const r = await reapLeases(ctx, { dryRun: o.dryRun });
3124
+ if (o.json) printJson(r);
3125
+ else if (r.reaped.length === 0) console.log(chalk7.gray("nothing to reap"));
3126
+ else
3127
+ for (const l of r.reaped)
3128
+ console.log(
3129
+ `${o.dryRun ? "would reap" : "reaped"} ${l.kind} ${l.value} (${l.owner.session}, expired ${l.expires})`
3130
+ );
3131
+ } catch (err) {
3132
+ fail(err, Boolean(o.json));
3133
+ }
3134
+ });
3135
+ }
3136
+
3137
+ // src/commands/retire.ts
3138
+ import chalk8 from "chalk";
3139
+ function registerRetire(program2) {
3140
+ program2.command("retire").description(
3141
+ "Archive an area's evidence, remove its worktree and its local branches that are on origin (the only destructive verb)"
3142
+ ).requiredOption("--area <area>", "the area to retire").option("--project-root <dir>", "repository root (default: the main checkout of the cwd)").option("--json", "print the result as JSON").action(async (o) => {
3143
+ try {
3144
+ const ctx = await buildCtx({ projectRoot: o.projectRoot, quiet: Boolean(o.json) });
3145
+ const r = await retireArea(ctx, { area: o.area });
3146
+ if (o.json) printJson(r);
3147
+ else {
3148
+ console.log(`${chalk8.bold(o.area)} retired: removed ${r.removed}`);
3149
+ for (const a of r.archived) console.log(` archived ${a}`);
3150
+ for (const b of r.branchesDeleted) console.log(` deleted local branch ${b}`);
3151
+ for (const b of r.branchesKept)
3152
+ console.log(chalk8.yellow(` kept ${b}: not fully on origin`));
3153
+ }
3154
+ } catch (err) {
3155
+ fail(err, Boolean(o.json));
3156
+ }
3157
+ });
3158
+ }
3159
+
3160
+ // src/commands/start.ts
3161
+ import chalk9 from "chalk";
3162
+ function printStart(r) {
3163
+ const e = r.effort;
3164
+ const label = e.task ? `${e.area}--${e.task}` : e.area;
3165
+ console.log(
3166
+ `${chalk9.bold(label)} ${e.type}/${e.mode} ${e.branch}${r.joined ? chalk9.yellow(" (joined)") : ""}`
3167
+ );
3168
+ console.log(` worktree ${e.worktree}`);
3169
+ console.log(
3170
+ ` sync ${r.sync}${r.refreshed.length ? ` refreshed: ${r.refreshed.join("; ")}` : ""}`
3171
+ );
3172
+ for (const l of r.leases) {
3173
+ const ports = l.ports ? ` ${Object.entries(l.ports).map(([k, v]) => `${k}=${v}`).join(" ")}` : "";
3174
+ console.log(` lease ${l.kind} ${l.value}${ports} expires ${l.expires}`);
3175
+ }
3176
+ for (const w of r.warnings) warn(w);
3177
+ for (const n of r.notices) console.log(chalk9.yellow(` notice ${n.text} (${n.at})`));
3178
+ }
3179
+ function registerStart(program2) {
3180
+ program2.command("start").description(
3181
+ "Start an effort: the area's worktree on <type>/<area> (or <type>/<area>--<task>), synced from the base branch, leased and running"
3182
+ ).requiredOption("--area <area>", "a leaf area from helmsmith.config (e.g. org/applications)").option("--task <slug>", "intra-area task slug for parallel sub-efforts (<type>/<area>--<slug>)").requiredOption("--type <type>", "feature | chore | fix (as the manifest allows)").requiredOption("--mode <mode>", "fullstack | backend (a slot) | frontend (storybrokr)").option("--scope <glob...>", "narrow exclusive scope globs for this task sub-effort").option(
3183
+ "--story <path>",
3184
+ "frontend: the story file or component folder storybrokr boots, relative to the Storybook host"
3185
+ ).option("--join", "work in the already-open effort on this area instead of refusing").option("--no-sync", "skip the fetch and merge from the base branch (reproducing something)").option("--project-root <dir>", "repository root (default: the main checkout of the cwd)").option("--json", "print the result as JSON").action(
3186
+ async (o) => {
3187
+ try {
3188
+ const ctx = await buildCtx({ projectRoot: o.projectRoot, quiet: Boolean(o.json) });
3189
+ const r = await startEffort(ctx, {
3190
+ area: o.area,
3191
+ task: o.task,
3192
+ type: o.type,
3193
+ mode: o.mode,
3194
+ scopes: o.scope,
3195
+ story: o.story,
3196
+ join: o.join,
3197
+ sync: o.sync
3198
+ });
3199
+ if (o.json) printJson(r);
3200
+ else printStart(r);
3201
+ } catch (err) {
3202
+ fail(err, Boolean(o.json));
3203
+ }
3204
+ }
3205
+ );
3206
+ }
3207
+
3208
+ // src/commands/status.ts
3209
+ import chalk10 from "chalk";
3210
+ var age = (iso) => {
3211
+ const mins = Math.max(0, Math.round((Date.now() - Date.parse(iso)) / 6e4));
3212
+ return mins < 60 ? `${mins}m` : mins < 1440 ? `${Math.round(mins / 60)}h` : `${Math.round(mins / 1440)}d`;
3213
+ };
3214
+ var expiresIn = (iso) => {
3215
+ const mins = Math.round((Date.parse(iso) - Date.now()) / 6e4);
3216
+ return mins <= 0 ? chalk10.red("expired") : mins < 60 ? `${mins}m` : `${Math.round(mins / 60)}h`;
3217
+ };
3218
+ function printStatus(r) {
3219
+ console.log(chalk10.bold(`${r.project}`));
3220
+ const cols = ["AREA", "TYPE/MODE", "BRANCH", "OWNER", "STARTED", "LEASES", "BEHIND", "NOTICES"];
3221
+ const rows = r.areas.map((a) => [
3222
+ a.area,
3223
+ a.effort ? `${a.effort.type}/${a.effort.mode}` : chalk10.gray("-"),
3224
+ a.effort?.branch ?? chalk10.gray("-"),
3225
+ a.effort?.owner.session ?? chalk10.gray("-"),
3226
+ a.effort ? age(a.effort.started) : chalk10.gray("-"),
3227
+ a.leases.length ? a.leases.map((l) => `${l.kind}:${l.value}`).join(",") : chalk10.gray("-"),
3228
+ a.behindBase > 0 ? chalk10.yellow(String(a.behindBase)) : "0",
3229
+ a.notices.length ? chalk10.yellow(String(a.notices.length)) : "0"
3230
+ ]);
3231
+ const plain = (s) => s.replace(/\u001b\[[0-9;]*m/g, "");
3232
+ const widths = cols.map((c, i) => Math.max(c.length, ...rows.map((row) => plain(row[i]).length)));
3233
+ const line = (cells) => cells.map((c, i) => c + " ".repeat(widths[i] - plain(c).length)).join(" ");
3234
+ console.log(chalk10.bold(line(cols)));
3235
+ for (const row of rows) console.log(line(row));
3236
+ if (r.leases.length) {
3237
+ console.log("");
3238
+ console.log(chalk10.bold("KIND VALUE OWNER AGE EXPIRES-IN"));
3239
+ for (const l of r.leases) {
3240
+ console.log(
3241
+ `${l.kind.padEnd(10)} ${String(l.value).padEnd(12)} ${l.owner.session.padEnd(21)} ${age(l.created).padEnd(5)} ${expiresIn(l.expires)}`
3242
+ );
3243
+ }
3244
+ }
3245
+ }
3246
+ function registerStatus(program2) {
3247
+ program2.command("status").description("Open efforts, leases, drift from the base branch and notices, per area").option("--area <area>", "one area only").option("--task <slug>", "intra-area task slug").option("--project-root <dir>", "repository root (default: the main checkout of the cwd)").option("--json", "print the report as JSON").action(async (o) => {
3248
+ try {
3249
+ const ctx = await buildCtx({ projectRoot: o.projectRoot, quiet: true });
3250
+ const r = statusFor(ctx, o.area, o.task);
3251
+ if (o.json) printJson(r);
3252
+ else printStatus(r);
3253
+ } catch (err) {
3254
+ fail(err, Boolean(o.json));
3255
+ }
3256
+ });
3257
+ }
3258
+
3259
+ // src/cli.ts
3260
+ var { program } = createCli({
3261
+ name: "work",
3262
+ version: VERSION,
3263
+ description: "Area-based work: start, promote, status, finish, reap, retire, audit."
3264
+ });
3265
+ registerInit(program);
3266
+ registerStart(program);
3267
+ registerPromote(program);
3268
+ registerStatus(program);
3269
+ registerEnv(program);
3270
+ registerFinish(program);
3271
+ registerReap(program);
3272
+ registerRetire(program);
3273
+ registerAudit(program);
3274
+ registerHook(program);
3275
+ registerMcp(program);
3276
+ program.parseAsync(process.argv).catch((err) => {
3277
+ console.error(err instanceof Error ? err.message : String(err));
3278
+ process.exit(1);
3279
+ });
3280
+ //# sourceMappingURL=cli.js.map