@coding-with-hassan/devkit 0.4.0 → 1.0.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +115 -0
  2. package/claude/agents/commit-writer.md +84 -0
  3. package/claude/skills/implement-ticket/SKILL.md +17 -0
  4. package/claude/standards.md +99 -0
  5. package/hooks/pre-commit.sh +9 -3
  6. package/lint-staged.js +81 -0
  7. package/package.json +21 -3
  8. package/src/commands/ci.js +186 -0
  9. package/src/commands/claude.js +24 -0
  10. package/src/commands/config.js +117 -0
  11. package/src/commands/docker.js +10 -0
  12. package/src/commands/hooks.js +27 -20
  13. package/src/commands/init.js +211 -0
  14. package/src/commands/test-cases.js +31 -0
  15. package/src/commands/worktree.js +37 -0
  16. package/src/core/agents-docs.js +225 -0
  17. package/src/core/ci/affected.js +155 -0
  18. package/src/core/ci/commit-standards.js +59 -0
  19. package/src/core/ci/nx-cache.js +74 -0
  20. package/src/core/ci/workflow.js +87 -0
  21. package/src/core/claude.js +113 -0
  22. package/src/core/compose.js +69 -0
  23. package/src/core/config.js +324 -0
  24. package/src/core/derive.js +130 -0
  25. package/src/core/env-block.js +76 -0
  26. package/src/core/exec.js +45 -0
  27. package/src/core/git.js +77 -0
  28. package/src/core/locks.js +60 -0
  29. package/src/core/root.js +30 -0
  30. package/src/core/scaffold.js +131 -0
  31. package/src/core/stack.js +63 -0
  32. package/src/core/test-cases/generate.js +287 -0
  33. package/src/core/test-cases/loader.mjs +40 -0
  34. package/src/core/tracker/github.js +29 -0
  35. package/src/core/tracker/index.js +37 -0
  36. package/src/core/tracker/jira.js +101 -0
  37. package/src/core/workspace.js +105 -0
  38. package/src/core/worktrees.js +580 -0
  39. package/src/index.js +12 -0
  40. package/test-cases.d.ts +48 -0
  41. package/test-cases.js +26 -0
@@ -0,0 +1,580 @@
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
2
+ import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
3
+ import { loadProfiles } from './compose.js';
4
+ import { CONFIG_KEY, ENV_DIST_FILE, ENV_FILE } from './config.js';
5
+ import { expandEnv, imageTag, imageTagInputs, sanitizeName } from './derive.js';
6
+ import { managedValues, parseEnv, writeManagedBlock } from './env-block.js';
7
+ import { commandExists, run } from './exec.js';
8
+ import * as git from './git.js';
9
+ import { withLock } from './locks.js';
10
+ import * as stack from './stack.js';
11
+ import { startTicket } from './tracker/index.js';
12
+ import { listProjects } from './workspace.js';
13
+
14
+ /**
15
+ * Parallel-development worktrees: one per ticket, each with its own Docker stack (own
16
+ * compose project, host ports and volumes) sharing the dev images with every other
17
+ * checkout on the same dependency manifest. Port of car-rental's `scripts/worktree.sh`.
18
+ *
19
+ * Pure decision functions come first (tested); the orchestration below composes them with
20
+ * git/docker/pnpm side effects. A repo without a compose file gets worktrees without a
21
+ * stack: no `.env`, no slot, no images — just branch + install + tracker.
22
+ */
23
+
24
+ // ───────────────────────── pure ─────────────────────────
25
+
26
+ /**
27
+ * Is the worktree feature switched on? The block must exist AND, when the repo has a compose
28
+ * file, name at least one port or a default profile: `init` merges an EMPTY skeleton into
29
+ * every package.json, and that skeleton must stay inert until the project fills it in —
30
+ * otherwise `docker:up` would manage `.env` (and build a second image set) behind the
31
+ * project's existing tooling. A repo without a compose file needs no ports, so `{}` is active.
32
+ */
33
+ export function worktreeActive(wt, { hasStack }) {
34
+ if (!wt) return false;
35
+ if (!hasStack) return true;
36
+ return Object.keys(wt.ports).length > 0 || wt.profiles.default.length > 0;
37
+ }
38
+
39
+ /** Compose project of a checkout: slot 0 keeps the configured name; others use the branch. */
40
+ export function projectNameFor({ slot, branch, projectName }) {
41
+ if (slot === 0) return projectName;
42
+ const fromBranch = String(branch ?? '')
43
+ .toLowerCase()
44
+ .replace(/[^a-z0-9_-]/g, '-');
45
+ return fromBranch || `${projectName}-wt${slot}`;
46
+ }
47
+
48
+ /**
49
+ * Validate + order a requested profile list: required profiles first (always present),
50
+ * then the rest in the compose file's order; unknown names throw. With no profiles in
51
+ * the compose file the result is always `[]`.
52
+ */
53
+ export function normalizeProfiles(requested, { known, required }) {
54
+ if (known.length === 0) return [];
55
+ const wanted = new Set(
56
+ (Array.isArray(requested) ? requested : String(requested ?? '').split(','))
57
+ .map((p) => p.trim())
58
+ .filter(Boolean),
59
+ );
60
+ for (const p of wanted) {
61
+ if (!known.includes(p)) throw new Error(`unknown profile '${p}' (known: ${known.join(' ')})`);
62
+ }
63
+ for (const r of required) wanted.add(r);
64
+ return [...required.filter((r) => wanted.has(r)), ...known.filter((k) => wanted.has(k) && !required.includes(k))];
65
+ }
66
+
67
+ /** Lowest slot in 1..maxSlot not in `used` (slot 0 is the main checkout). */
68
+ export function pickFreeSlot(used, maxSlot) {
69
+ const taken = new Set([0, ...used.map(Number)]);
70
+ for (let s = 1; s <= maxSlot; s++) if (!taken.has(s)) return s;
71
+ throw new Error(`no free slot (all ${maxSlot} in use) — remove a worktree first`);
72
+ }
73
+
74
+ export function validateSlot(value, maxSlot) {
75
+ const n = Number(value);
76
+ if (!/^\d+$/.test(String(value)) || n < 1 || n > maxSlot) {
77
+ throw new Error(`slot must be a number 1-${maxSlot} (0 is the main checkout), got '${value}'`);
78
+ }
79
+ return n;
80
+ }
81
+
82
+ /** Image repository of a `repo[:tag]` reference (registry ports are not tags). */
83
+ export function imageRepo(ref) {
84
+ const slash = ref.lastIndexOf('/');
85
+ const colon = ref.lastIndexOf(':');
86
+ return colon > slash ? ref.slice(0, colon) : ref;
87
+ }
88
+
89
+ /** `{ service, image }` for every buildable service of the active profiles at `tag`. */
90
+ export function imagesFor(compose, profiles, tag) {
91
+ const out = [];
92
+ const seen = new Set();
93
+ const active = new Set(profiles);
94
+ for (const [service, svc] of Object.entries(compose.services)) {
95
+ if (!svc.build || !svc.image) continue;
96
+ const inScope = svc.profiles.length === 0 || svc.profiles.some((p) => active.has(p));
97
+ if (!inScope || seen.has(service)) continue;
98
+ seen.add(service);
99
+ out.push({ service, image: `${imageRepo(svc.image)}:${tag}` });
100
+ }
101
+ return out.sort((a, b) => a.service.localeCompare(b.service));
102
+ }
103
+
104
+ /** Repositories of every buildable service (the dev images this repo owns). */
105
+ export function ownedImageRepos(compose) {
106
+ return [...new Set(Object.values(compose.services).filter((s) => s.build && s.image).map((s) => imageRepo(s.image)))].sort();
107
+ }
108
+
109
+ /** node_modules volumes of `project` that belong to another image tag. */
110
+ export function staleVolumes(volumes, project, tag) {
111
+ const re = new RegExp(`^${escapeRe(project)}_.*_node_modules_`);
112
+ return volumes.filter((v) => re.test(v) && !v.endsWith(`_node_modules_${tag}`));
113
+ }
114
+
115
+ /** Every node_modules volume of `project` (for a full teardown). */
116
+ export function projectVolumes(volumes, project) {
117
+ const re = new RegExp(`^${escapeRe(project)}_.*_node_modules_`);
118
+ return volumes.filter((v) => re.test(v));
119
+ }
120
+
121
+ /** Owned dev images whose tag no checkout references and no container uses. */
122
+ export function unreferencedImages(images, { repos, referencedTags, inUse }) {
123
+ const referenced = new Set(['latest', ...referencedTags]);
124
+ const used = new Set(inUse);
125
+ const owned = new Set(repos);
126
+ return images.filter((img) => owned.has(imageRepo(img)) && !referenced.has(img.slice(imageRepo(img).length + 1)) && !used.has(img));
127
+ }
128
+
129
+ /** What `prune` does with a worktree given the `gh pr list` state summary. */
130
+ export function pruneDecision(states) {
131
+ if (states === null) return 'error';
132
+ if (states === '') return 'none';
133
+ if (states.includes('OPEN')) return 'open';
134
+ if (states.includes('MERGED')) return 'merged';
135
+ return 'closed';
136
+ }
137
+
138
+ /** Dockerfiles of the buildable services, relative to `root` (extra image-tag inputs). */
139
+ export function dockerfilesFromCompose(compose, root) {
140
+ const files = new Set();
141
+ for (const svc of Object.values(compose?.services ?? {})) {
142
+ if (!svc.build) continue;
143
+ const context = svc.build.context ?? '.';
144
+ const dockerfile = svc.build.dockerfile ?? 'Dockerfile';
145
+ const abs = isAbsolute(dockerfile) ? dockerfile : resolve(isAbsolute(context) ? context : join(root, context), dockerfile);
146
+ const rel = relative(root, abs).split('\\').join('/');
147
+ if (!rel.startsWith('..')) files.add(rel);
148
+ }
149
+ return [...files].sort();
150
+ }
151
+
152
+ const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
153
+
154
+ // ───────────────────────── context ─────────────────────────
155
+
156
+ /**
157
+ * Everything the commands need, resolved once. `hasStack` is false when the repo has no
158
+ * compose file; then every docker/env step is skipped.
159
+ */
160
+ export function createContext(loaded, { log = console.log, note = (m) => console.error(`note: ${m}`) } = {}) {
161
+ const { root, rootName, config } = loaded;
162
+ const wt = config.worktree;
163
+ if (!wt) throw new Error(`Missing "${CONFIG_KEY}.worktree" in ${join(root, 'package.json')} — add it (or run \`hassan-devkit init\`).`);
164
+ const hasStack = stack.hasComposeFile(root);
165
+ if (!worktreeActive(wt, { hasStack })) {
166
+ throw new Error(`"${CONFIG_KEY}.worktree" is still the empty skeleton — fill in worktree.ports (base host ports) and worktree.profiles.default before using the worktree commands; until then the stack keeps being managed by whatever the project used before.`);
167
+ }
168
+ const main = git.mainRoot(root);
169
+ const baseDir = resolve(main, wt.baseDir);
170
+ let compose = null;
171
+ if (hasStack) {
172
+ compose = loadProfiles(root);
173
+ for (const r of wt.profiles.required) {
174
+ if (!(r in compose.profiles)) throw new Error(`${CONFIG_KEY}.worktree.profiles.required names "${r}", but the compose file has no service with that profile`);
175
+ }
176
+ }
177
+ const known = compose ? Object.keys(compose.profiles) : [];
178
+ return {
179
+ root,
180
+ mainRoot: main,
181
+ baseDir,
182
+ rootName,
183
+ wt,
184
+ tracker: config.tracker,
185
+ hasStack,
186
+ compose,
187
+ known,
188
+ log,
189
+ note,
190
+ };
191
+ }
192
+
193
+ // ───────────────────────── .env bookkeeping ─────────────────────────
194
+
195
+ export function envOf(dir) {
196
+ const file = join(dir, ENV_FILE);
197
+ return existsSync(file) ? parseEnv(readFileSync(file, 'utf8')) : {};
198
+ }
199
+
200
+ /** `[{ dir, env }]` for the main checkout and every worktree under baseDir that has a .env. */
201
+ export function allCheckouts(ctx) {
202
+ const dirs = [ctx.mainRoot];
203
+ if (existsSync(ctx.baseDir)) {
204
+ for (const entry of readdirSync(ctx.baseDir, { withFileTypes: true })) {
205
+ if (entry.isDirectory() && !entry.name.startsWith('.')) dirs.push(join(ctx.baseDir, entry.name));
206
+ }
207
+ }
208
+ return dirs.filter((d) => existsSync(join(d, ENV_FILE))).map((d) => ({ dir: d, env: envOf(d) }));
209
+ }
210
+
211
+ export function slotHolders(ctx, slot, exclude) {
212
+ return allCheckouts(ctx)
213
+ .filter(({ dir, env }) => env.DEVKIT_SLOT === String(slot) && (!exclude || resolve(dir) !== resolve(exclude)))
214
+ .map(({ dir }) => basename(dir));
215
+ }
216
+
217
+ export function usedSlots(ctx) {
218
+ return allCheckouts(ctx)
219
+ .filter(({ dir }) => resolve(dir) !== resolve(ctx.mainRoot))
220
+ .map(({ env }) => env.DEVKIT_SLOT)
221
+ .filter((s) => s !== undefined && s !== '');
222
+ }
223
+
224
+ function currentImageTag(ctx, dir) {
225
+ const projects = listProjects(dir);
226
+ const inputs = imageTagInputs(dir, projects, dockerfilesFromCompose(ctx.compose, dir));
227
+ if (inputs.length === 0) throw new Error(`cannot hash the dev image inputs: ${dir} is not a checkout of this repo`);
228
+ return imageTag(dir, inputs);
229
+ }
230
+
231
+ /**
232
+ * Write the managed block of `dir/.env`: own `.env` first (keeps local edits), then the
233
+ * main checkout's, then `.env.dist`; atomic via rename. Returns the managed values.
234
+ */
235
+ export function writeEnv(ctx, dir, slot, profiles) {
236
+ const sources = [join(dir, ENV_FILE), join(ctx.mainRoot, ENV_FILE), join(ctx.mainRoot, ENV_DIST_FILE)];
237
+ const src = sources.find((f) => existsSync(f));
238
+ const current = src ? readFileSync(src, 'utf8') : '';
239
+ const branch = git.currentBranch(dir) ?? '';
240
+ const tag = currentImageTag(ctx, dir);
241
+ const values = managedValues({
242
+ slot,
243
+ projectName: projectNameFor({ slot, branch, projectName: ctx.wt.projectName }),
244
+ profiles,
245
+ imageTag: tag,
246
+ branch,
247
+ ports: ctx.wt.ports,
248
+ extraEnv: ctx.wt.env,
249
+ });
250
+ const text = writeManagedBlock(current, values, { slot, profilesHint: ctx.known.length ? ctx.known.join('|') : 'profile' });
251
+ const tmp = join(dir, `${ENV_FILE}.tmp`);
252
+ writeFileSync(tmp, text);
253
+ renameSync(tmp, join(dir, ENV_FILE));
254
+ const ports = Object.entries(values)
255
+ .filter(([k]) => k.startsWith('DEVKIT_PORT_'))
256
+ .map(([k, v]) => `${k.slice('DEVKIT_PORT_'.length).toLowerCase()}=${v}`)
257
+ .join(' ');
258
+ ctx.log(`wrote ${join(dir, ENV_FILE)} (slot ${slot}, profiles ${profiles.join(',') || '-'}, image tag ${tag}${ports ? `: ${ports}` : ''})`);
259
+ return values;
260
+ }
261
+
262
+ // ───────────────────────── images & volumes ─────────────────────────
263
+
264
+ function missingImages(ctx, dir) {
265
+ const env = envOf(dir);
266
+ const profiles = (env.COMPOSE_PROFILES ?? '').split(',').filter(Boolean);
267
+ return imagesFor(ctx.compose, profiles, env.DEVKIT_IMAGE_TAG ?? 'latest').filter(({ image }) => !stack.imageExists(image));
268
+ }
269
+
270
+ /** Build the active profiles' images when the tag is new; serialized across checkouts. */
271
+ export async function ensureImages(ctx, dir) {
272
+ if (missingImages(ctx, dir).length === 0) return;
273
+ await withLock(
274
+ ctx.baseDir,
275
+ '.image-build.lock',
276
+ 'building the shared dev images',
277
+ 1800,
278
+ async () => {
279
+ const missing = missingImages(ctx, dir); // someone may have built them while we waited
280
+ if (missing.length === 0) return;
281
+ ctx.log(`building shared dev image(s) ${missing.map((m) => m.image).join(', ')} — every checkout on the same lockfile reuses them`);
282
+ await stack.compose(dir, ['build', ...missing.map((m) => m.service)]);
283
+ },
284
+ { log: ctx.log },
285
+ );
286
+ }
287
+
288
+ /** Drop this project's node_modules volumes that belong to other image tags. */
289
+ export function cleanStaleVolumes(ctx, dir) {
290
+ const env = envOf(dir);
291
+ if (!env.COMPOSE_PROJECT_NAME || !env.DEVKIT_IMAGE_TAG) return;
292
+ for (const v of staleVolumes(stack.listVolumes(), env.COMPOSE_PROJECT_NAME, env.DEVKIT_IMAGE_TAG)) {
293
+ if (stack.removeVolume(v)) ctx.log(`removed stale node_modules volume ${v}`);
294
+ else ctx.log(`note: stale volume ${v} is still in use (container on the old image tag) — left alone`);
295
+ }
296
+ }
297
+
298
+ /** Remove owned image tags no checkout's .env references and no container uses. */
299
+ export function pruneImages(ctx) {
300
+ if (!ctx.compose) return;
301
+ const referencedTags = allCheckouts(ctx)
302
+ .map(({ env }) => env.DEVKIT_IMAGE_TAG)
303
+ .filter(Boolean);
304
+ const targets = unreferencedImages(stack.listImages(), { repos: ownedImageRepos(ctx.compose), referencedTags, inUse: stack.imagesInUse() });
305
+ for (const img of targets) {
306
+ if (stack.removeImage(img)) ctx.log(`removed unreferenced dev image ${img}`);
307
+ else ctx.note(`could not remove unreferenced dev image ${img}`);
308
+ }
309
+ }
310
+
311
+ /** `down` across every profile (nothing left behind); `wipe` also removes volumes. */
312
+ export async function stackDown(ctx, dir, { wipe }) {
313
+ const ok = await stack.compose(dir, ['--profile', '*', 'down', ...(wipe ? ['-v'] : []), '--remove-orphans'], {
314
+ // The shell env wins over --env-file: a .env from before profiles were mandatory must
315
+ // not block its own teardown on the compose guard.
316
+ env: { COMPOSE_PROFILES: process.env.COMPOSE_PROFILES || ctx.known[0] || 'devkit' },
317
+ allowFailure: true,
318
+ });
319
+ if (!ok) ctx.note(`compose down failed in ${dir} — check 'docker ps -a' for leftovers`);
320
+ if (wipe) {
321
+ const project = envOf(dir).COMPOSE_PROJECT_NAME;
322
+ if (project) {
323
+ for (const v of projectVolumes(stack.listVolumes(), project)) {
324
+ if (stack.removeVolume(v)) ctx.log(`removed volume ${v}`);
325
+ else ctx.note(`could not remove volume ${v}`);
326
+ }
327
+ }
328
+ }
329
+ }
330
+
331
+ async function refreshEnv(ctx, dir, slot, profiles) {
332
+ writeEnv(ctx, dir, slot, profiles);
333
+ await ensureImages(ctx, dir);
334
+ cleanStaleVolumes(ctx, dir);
335
+ }
336
+
337
+ function currentProfiles(ctx, dir) {
338
+ const raw = (envOf(dir).COMPOSE_PROFILES ?? '').split(',').filter(Boolean);
339
+ const valid = raw.filter((p) => ctx.known.includes(p)); // a stale name from an old .env is dropped, not fatal
340
+ return normalizeProfiles(valid.length ? valid : ctx.wt.profiles.default, { known: ctx.known, required: ctx.wt.profiles.required });
341
+ }
342
+
343
+ function isMain(ctx, dir) {
344
+ return resolve(dir) === resolve(ctx.mainRoot);
345
+ }
346
+
347
+ // ───────────────────────── commands ─────────────────────────
348
+
349
+ /** `worktree:env` — refresh this checkout's managed block, images and volumes. */
350
+ export async function cmdEnv(ctx, { cwd = process.cwd(), slot: requestedSlot } = {}) {
351
+ if (!ctx.hasStack) {
352
+ ctx.log('no docker/docker-compose.dev.yml — nothing to refresh');
353
+ return;
354
+ }
355
+ const dir = git.toplevel(cwd);
356
+ const env = envOf(dir);
357
+ let slot = requestedSlot !== undefined ? validateSlot(requestedSlot, ctx.wt.maxSlot) : isMain(ctx, dir) ? 0 : env.DEVKIT_SLOT ? Number(env.DEVKIT_SLOT) : null;
358
+ const profiles = currentProfiles(ctx, dir);
359
+ // This runs on every `docker:up`: the one place to catch two checkouts on one slot
360
+ // before their stacks fight over the ports.
361
+ await withLock(
362
+ ctx.baseDir,
363
+ '.slot.lock',
364
+ 'assigning a slot',
365
+ 120,
366
+ async () => {
367
+ if (slot === null) slot = pickFreeSlot(usedSlots(ctx), ctx.wt.maxSlot);
368
+ const holders = slotHolders(ctx, slot, dir);
369
+ if (holders.length) {
370
+ throw new Error(`slot ${slot} is already used by: ${holders.join(' ')} — two stacks on one slot share host ports; run 'hassan-devkit worktree:env --slot <free slot>' in one of them (see 'hassan-devkit worktree:list')`);
371
+ }
372
+ writeEnv(ctx, dir, slot, profiles);
373
+ },
374
+ { log: ctx.log },
375
+ );
376
+ await ensureImages(ctx, dir);
377
+ cleanStaleVolumes(ctx, dir);
378
+ if (!existsSync(join(dir, 'node_modules')) || (existsSync(join(dir, '.husky')) && !existsSync(join(dir, '.husky/_')))) {
379
+ ctx.note(`${dir} is missing node_modules or .husky/_ — run 'pnpm install' there, otherwise git SILENTLY SKIPS the pre-commit hooks`);
380
+ }
381
+ }
382
+
383
+ /** `worktree:create <branch>` */
384
+ export async function cmdCreate(ctx, branch, { profiles: requested, up = true } = {}) {
385
+ if (!branch) throw new Error('usage: hassan-devkit worktree:create <BRANCH> [--profiles a,b] [--no-up]');
386
+ const profiles = ctx.hasStack ? normalizeProfiles(requested ?? ctx.wt.profiles.default, { known: ctx.known, required: ctx.wt.profiles.required }) : [];
387
+ await cmdPrune(ctx, {}); // reclaim merged-PR stacks (and their slots) before spending resources on a new one
388
+ const wtDir = join(ctx.baseDir, branch);
389
+ if (existsSync(wtDir)) throw new Error(`${wtDir} already exists`);
390
+ mkdirSync(ctx.baseDir, { recursive: true });
391
+
392
+ // Always start from the freshest main of the canonical remote — never the local main.
393
+ const remote = git.hasRemote(ctx.mainRoot, 'upstream') ? 'upstream' : 'origin';
394
+ const fetched = await run('git', ['-C', ctx.mainRoot, 'fetch', remote, 'main'], { allowFailure: true });
395
+ if (!fetched) throw new Error(`cannot fetch ${remote}/main — refusing to base new work on a possibly stale main`);
396
+ const base = `refs/remotes/${remote}/main`;
397
+ if (git.branchExists(ctx.mainRoot, branch)) {
398
+ await git.worktreeAdd(ctx.mainRoot, wtDir, { branch });
399
+ if (!git.isAncestor(ctx.mainRoot, base, branch)) ctx.note(`existing branch ${branch} is behind ${remote}/main — merge it before starting work`);
400
+ } else {
401
+ await git.worktreeAdd(ctx.mainRoot, wtDir, { newBranch: branch, startPoint: base });
402
+ }
403
+ if (git.branchExists(ctx.mainRoot, 'main') && !git.isAncestor(ctx.mainRoot, base, 'main')) {
404
+ ctx.note(`local main is behind ${remote}/main — sync it with: git checkout main && git merge --ff-only ${remote}/main`);
405
+ }
406
+
407
+ let slot = null;
408
+ if (ctx.hasStack) {
409
+ await withLock(
410
+ ctx.baseDir,
411
+ '.slot.lock',
412
+ 'assigning a slot',
413
+ 120,
414
+ async () => {
415
+ slot = pickFreeSlot(usedSlots(ctx), ctx.wt.maxSlot);
416
+ writeEnv(ctx, wtDir, slot, profiles);
417
+ },
418
+ { log: ctx.log },
419
+ );
420
+ }
421
+
422
+ await startTicket({ branch, tracker: ctx.tracker, cwd: wtDir, log: ctx.log, note: ctx.note });
423
+
424
+ await run('pnpm', ['install', '--frozen-lockfile'], { cwd: wtDir });
425
+ if (existsSync(join(wtDir, '.husky'))) {
426
+ // husky's shim dir (.husky/_) is per-worktree and git SILENTLY skips every hook when
427
+ // core.hooksPath points at a missing dir — bootstrap it and fail loudly if it didn't take.
428
+ await run('pnpm', ['exec', 'husky'], { cwd: wtDir });
429
+ if (!existsSync(join(wtDir, '.husky/_/pre-commit'))) throw new Error(`husky shims missing in ${wtDir} — git would silently skip all hooks`);
430
+ }
431
+
432
+ let values = null;
433
+ if (ctx.hasStack && up) {
434
+ await ensureImages(ctx, wtDir);
435
+ await stack.compose(wtDir, ['up', '-d', '--build']);
436
+ values = envOf(wtDir);
437
+ if (ctx.wt.ready) await stack.waitForUrl(expandEnv(ctx.wt.ready.url, values), ctx.wt.ready.timeoutSeconds, { log: ctx.log });
438
+ for (const script of ctx.wt.seeds.scripts) await stack.compose(wtDir, ['exec', ctx.wt.seeds.service, 'pnpm', script]);
439
+ }
440
+
441
+ ctx.log('');
442
+ ctx.log(`Worktree ready: ${wtDir}${slot !== null ? ` (slot ${slot}, profiles: ${profiles.join(',')})` : ''}`);
443
+ if (values) {
444
+ for (const [k, v] of Object.entries(values)) if (k.startsWith('DEVKIT_PORT_')) ctx.log(` ${k.slice('DEVKIT_PORT_'.length).toLowerCase().padEnd(14)} localhost:${v}`);
445
+ const optional = ctx.known.filter((p) => !ctx.wt.profiles.required.includes(p) && !profiles.includes(p));
446
+ if (optional.length) ctx.log(` add a profile with: hassan-devkit worktree:profiles add ${optional.join('|')}`);
447
+ }
448
+ return { dir: wtDir, slot, profiles };
449
+ }
450
+
451
+ /** `worktree:profiles list|add|remove [names…]` */
452
+ export async function cmdProfiles(ctx, action = 'list', names = [], { cwd = process.cwd() } = {}) {
453
+ if (!ctx.hasStack) throw new Error('no docker/docker-compose.dev.yml — this repo has no stack profiles');
454
+ const dir = git.toplevel(cwd);
455
+ const env = envOf(dir);
456
+ const slot = isMain(ctx, dir) ? 0 : env.DEVKIT_SLOT ? Number(env.DEVKIT_SLOT) : null;
457
+ if (slot === null) throw new Error(`no managed .env in ${dir} — run 'hassan-devkit worktree:env' first`);
458
+ const current = currentProfiles(ctx, dir);
459
+ switch (action) {
460
+ case 'list':
461
+ ctx.log(`active: ${current.join(',') || '-'}`);
462
+ ctx.log(`available: ${ctx.known.join(' ')}${ctx.wt.profiles.required.length ? ` (${ctx.wt.profiles.required.join(', ')} mandatory)` : ''}`);
463
+ return current;
464
+ case 'add': {
465
+ if (names.length === 0) throw new Error(`usage: hassan-devkit worktree:profiles add <${ctx.known.join('|')}> [...]`);
466
+ const next = normalizeProfiles([...current, ...names], { known: ctx.known, required: ctx.wt.profiles.required });
467
+ await refreshEnv(ctx, dir, slot, next);
468
+ // `up -d` is idempotent for running services; only the new profile's containers appear.
469
+ await stack.compose(dir, ['up', '-d']);
470
+ return next;
471
+ }
472
+ case 'remove': {
473
+ if (names.length === 0) throw new Error(`usage: hassan-devkit worktree:profiles remove <${ctx.known.join('|')}> [...]`);
474
+ for (const p of names) {
475
+ if (ctx.wt.profiles.required.includes(p)) throw new Error(`the ${p} profile is mandatory and cannot be removed`);
476
+ if (!ctx.known.includes(p)) throw new Error(`unknown profile '${p}' (known: ${ctx.known.join(' ')})`);
477
+ }
478
+ const next = normalizeProfiles(current.filter((p) => !names.includes(p)), { known: ctx.known, required: ctx.wt.profiles.required });
479
+ writeEnv(ctx, dir, slot, next);
480
+ for (const p of names) {
481
+ // The profile is no longer active, so a plain up/down would not see its containers.
482
+ await stack.compose(dir, ['--profile', p, 'rm', '-sf', ...ctx.compose.profiles[p]], { allowFailure: true });
483
+ }
484
+ return next;
485
+ }
486
+ default:
487
+ throw new Error('usage: hassan-devkit worktree:profiles list|add|remove [name ...]');
488
+ }
489
+ }
490
+
491
+ /** `worktree:remove <name>` — stack down (volumes gone unless --keep-data), worktree removed, branch kept. */
492
+ export async function cmdRemove(ctx, name, { keepData = false, force = false } = {}) {
493
+ if (!name) throw new Error('usage: hassan-devkit worktree:remove <BRANCH> [--keep-data] [--force]');
494
+ const dir = existsSync(name) && existsSync(join(name, '.git')) ? resolve(name) : join(ctx.baseDir, name);
495
+ if (!existsSync(dir)) throw new Error(`no worktree at ${dir}`);
496
+ if (ctx.hasStack && existsSync(join(dir, ENV_FILE))) await stackDown(ctx, dir, { wipe: !keepData });
497
+ const removed = await git.worktreeRemove(ctx.mainRoot, dir, { force });
498
+ if (!removed) throw new Error(`git worktree remove failed for ${dir} — stray changes? re-run with --force`);
499
+ pruneImages(ctx);
500
+ ctx.log(`removed ${dir} (branch kept — delete it with: git branch -D ${basename(dir)})`);
501
+ }
502
+
503
+ /** `worktree:prune` — remove every worktree whose PR is merged (GitHub is the oracle). */
504
+ export async function cmdPrune(ctx, { dryRun = false } = {}) {
505
+ if (!commandExists('gh')) {
506
+ ctx.note('gh not installed — cannot check PR states, skipping prune');
507
+ return [];
508
+ }
509
+ const removed = [];
510
+ if (!existsSync(ctx.baseDir)) return removed;
511
+ for (const entry of readdirSync(ctx.baseDir, { withFileTypes: true })) {
512
+ if (!entry.isDirectory() || entry.name.startsWith('.')) continue;
513
+ const dir = join(ctx.baseDir, entry.name);
514
+ if (!existsSync(join(dir, '.git'))) continue;
515
+ const branch = git.currentBranch(dir);
516
+ if (!branch) {
517
+ ctx.note(`prune: ${entry.name}: no branch checked out — keeping`);
518
+ continue;
519
+ }
520
+ // PRs live on the base repo (fork model): ask upstream, not origin. `pr view` cannot
521
+ // see fork-owned heads, so filter `pr list` by head ref name instead.
522
+ const baseRepo = git.remoteUrl(dir, 'upstream') ?? git.remoteUrl(dir, 'origin');
523
+ if (!baseRepo) {
524
+ ctx.note(`prune: ${entry.name}: no git remote — keeping`);
525
+ continue;
526
+ }
527
+ const states = ghPrStates(baseRepo, branch);
528
+ const decision = pruneDecision(states);
529
+ if (decision !== 'merged') {
530
+ const why = { error: 'gh could not answer', none: 'no PR', open: 'PR open', closed: 'PR closed without merge' }[decision];
531
+ ctx.log(`prune: ${entry.name}: ${why} — keeping`);
532
+ continue;
533
+ }
534
+ if (dryRun) {
535
+ ctx.log(`prune: ${entry.name}: PR merged — would remove worktree, containers, volumes, and branch`);
536
+ removed.push(entry.name);
537
+ continue;
538
+ }
539
+ ctx.log(`prune: ${entry.name}: PR merged — removing worktree, containers, volumes, and branch`);
540
+ if (ctx.hasStack && existsSync(join(dir, ENV_FILE))) await stackDown(ctx, dir, { wipe: true });
541
+ if (await git.worktreeRemove(ctx.mainRoot, dir)) {
542
+ await git.branchDelete(ctx.mainRoot, branch);
543
+ removed.push(entry.name);
544
+ } else {
545
+ ctx.note(`prune: ${entry.name} has stray changes — check them, then run: hassan-devkit worktree:remove ${entry.name} --force && git branch -D ${branch}`);
546
+ }
547
+ }
548
+ if (!dryRun) pruneImages(ctx);
549
+ return removed;
550
+ }
551
+
552
+ function ghPrStates(repoUrl, branch) {
553
+ const { capture } = stackExecShim;
554
+ return capture('gh', ['pr', 'list', '--repo', repoUrl, '--head', branch, '--state', 'all', '--json', 'state', '--jq', '[.[].state] | unique | join(",")'], { allowFailure: true });
555
+ }
556
+
557
+ /** `worktree:list` */
558
+ export function cmdList(ctx) {
559
+ for (const w of git.listWorktrees(ctx.mainRoot)) ctx.log(`${w.path} ${w.head ? w.head.slice(0, 8) : ''} [${w.branch ?? 'detached'}]`);
560
+ const checkouts = allCheckouts(ctx).filter(({ env }) => env.DEVKIT_SLOT !== undefined && env.DEVKIT_SLOT !== '');
561
+ for (const { dir, env } of checkouts) {
562
+ const ports = Object.entries(env)
563
+ .filter(([k]) => k.startsWith('DEVKIT_PORT_'))
564
+ .map(([k, v]) => `${k.slice('DEVKIT_PORT_'.length).toLowerCase()} :${v}`)
565
+ .join(', ');
566
+ ctx.log(` ${basename(dir)}: slot ${env.DEVKIT_SLOT} (${ports}), profiles [${env.COMPOSE_PROFILES ?? ''}], image tag [${env.DEVKIT_IMAGE_TAG ?? ''}]`);
567
+ }
568
+ const bySlot = new Map();
569
+ for (const { dir, env } of checkouts) bySlot.set(env.DEVKIT_SLOT, [...(bySlot.get(env.DEVKIT_SLOT) ?? []), basename(dir)]);
570
+ for (const [slot, names] of bySlot) {
571
+ if (names.length > 1) ctx.note(`slot ${slot} is used by ${names.join(' ')} — run 'hassan-devkit worktree:env --slot <free slot>' in all but one of them`);
572
+ }
573
+ }
574
+
575
+ // `capture` is imported lazily through this shim so the pure functions above can be unit
576
+ // tested without touching child_process at module load.
577
+ import { capture as captureImpl } from './exec.js';
578
+ const stackExecShim = { capture: captureImpl };
579
+
580
+ export { sanitizeName, dirname };
package/src/index.js CHANGED
@@ -3,10 +3,22 @@ import { registerDocker } from './commands/docker.js';
3
3
  import { registerDb } from './commands/db.js';
4
4
  import { registerHooks } from './commands/hooks.js';
5
5
  import { registerI18n } from './commands/i18n.js';
6
+ import { registerInit } from './commands/init.js';
7
+ import { registerConfig } from './commands/config.js';
8
+ import { registerWorktree } from './commands/worktree.js';
9
+ import { registerCi } from './commands/ci.js';
10
+ import { registerClaude } from './commands/claude.js';
11
+ import { registerTestCases } from './commands/test-cases.js';
6
12
 
7
13
  export function run(argv) {
8
14
  const cli = cac('hassan-devkit');
9
15
 
16
+ registerInit(cli);
17
+ registerConfig(cli);
18
+ registerWorktree(cli);
19
+ registerCi(cli);
20
+ registerClaude(cli);
21
+ registerTestCases(cli);
10
22
  registerDocker(cli);
11
23
  registerDb(cli);
12
24
  registerHooks(cli);
@@ -0,0 +1,48 @@
1
+ export type Lang = string;
2
+ export type Priority = 'H' | 'M' | 'L';
3
+
4
+ /** One text per language code (`{ en: '…', nl: '…' }`). */
5
+ export type Localized = Record<Lang, string>;
6
+
7
+ export interface TestCase {
8
+ id: string;
9
+ priority: Priority;
10
+ title: Localized;
11
+ pre: Localized;
12
+ steps: Localized;
13
+ expected: Localized;
14
+ }
15
+
16
+ export interface Area {
17
+ key: string;
18
+ name: Localized;
19
+ /** Sheet tab colour, six hex digits without `#`. */
20
+ tab: string;
21
+ cases: TestCase[];
22
+ }
23
+
24
+ export interface KnownIssue {
25
+ id: string;
26
+ desc: Localized;
27
+ impact: Localized;
28
+ }
29
+
30
+ export type ReadmeSection = [string, string[]];
31
+ export type Readme = Record<Lang, ReadmeSection[]>;
32
+
33
+ /** Build one bilingual (en/nl) test case positionally — the house default. */
34
+ export function tc(
35
+ id: string,
36
+ priority: Priority,
37
+ titleEn: string,
38
+ titleNl: string,
39
+ preEn: string,
40
+ preNl: string,
41
+ stepsEn: string,
42
+ stepsNl: string,
43
+ expectedEn: string,
44
+ expectedNl: string,
45
+ ): TestCase;
46
+
47
+ /** Build a test case for any language set from localized objects. */
48
+ export function tcase(input: TestCase): TestCase;
package/test-cases.js ADDED
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Shared vocabulary for the bilingual acceptance test cases (`docs/testing/tc-data-*.ts`).
3
+ *
4
+ * import { tc, type Area, type KnownIssue, type Readme } from '@coding-with-hassan/devkit/test-cases';
5
+ *
6
+ * Use the `type` modifier for the types: the data files are loaded with Node's type
7
+ * stripping, which keeps import specifiers verbatim, so a value import of a type would fail.
8
+ * Types live in `test-cases.d.ts` next to this file.
9
+ */
10
+
11
+ /** Build one bilingual (en/nl) test case positionally — the house default. */
12
+ export function tc(id, priority, titleEn, titleNl, preEn, preNl, stepsEn, stepsNl, expectedEn, expectedNl) {
13
+ return {
14
+ id,
15
+ priority,
16
+ title: { en: titleEn, nl: titleNl },
17
+ pre: { en: preEn, nl: preNl },
18
+ steps: { en: stepsEn, nl: stepsNl },
19
+ expected: { en: expectedEn, nl: expectedNl },
20
+ };
21
+ }
22
+
23
+ /** Build a test case for any language set from localized objects. */
24
+ export function tcase({ id, priority, title, pre, steps, expected }) {
25
+ return { id, priority, title, pre, steps, expected };
26
+ }