@coding-with-hassan/devkit 1.5.0 → 1.6.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/README.md CHANGED
@@ -108,9 +108,10 @@ Managed `.env` values use fixed keys: `COMPOSE_PROJECT_NAME`, `COMPOSE_PROFILES`
108
108
 
109
109
  One worktree per ticket, each with its own Docker stack (own compose project, host ports = base + slot×10, own volumes), sharing the dev images with every checkout on the same dependency manifest. Worktrees live under `worktree.baseDir` (default `../<root-name>-worktrees`); slot 0 is the main checkout. A repo without `docker/docker-compose.dev.yml` gets worktrees without a stack.
110
110
 
111
- - `hassan-devkit worktree:create <BRANCH> [--profiles a,b] [--no-up]` — prune merged worktrees, fetch `upstream`/`origin` `main`, add the worktree off it, allocate the lowest free slot (under a lock), write the managed `.env`, run the tracker hook, `pnpm install`, bootstrap husky (fails loudly if `.husky/_/pre-commit` is missing), build the images the tag lacks, `up`, wait for `worktree.ready.url`, run `worktree.seeds`.
111
+ - `hassan-devkit worktree:create <BRANCH> [--profiles a,b] [--no-up]` — prune merged worktrees, fetch `upstream`/`origin` `main`, add the worktree off it, allocate the lowest free slot (under a lock), write the managed `.env`, run the tracker hook, `pnpm install`, bootstrap husky (fails loudly if `.husky/_/pre-commit` is missing), build the images the tag lacks, `up`, wait for `worktree.ready.url`, run `worktree.seeds`. The stack is set up from the new worktree's own `package.json` and compose file (ports, profiles, `ready`, `seeds`, `env`), not from the checkout the command is run in, which may be behind the remote `main`; only `baseDir` and `maxSlot` are read from that checkout, and a note names the `worktree` keys on which the two differ. The seed step always prints a line: `seeding: pnpm <script> (service <service>)` before each script, `no seed scripts configured (worktree.seeds.scripts)` for an empty list, `not seeding: …` when scripts are configured and the stack was not started. A failing seed script fails the command.
112
112
  - `hassan-devkit worktree:env [--slot N]` — refresh this checkout's managed block (keeps slot + profiles, recomputes the image tag, builds missing images, drops stale `node_modules` volumes). Refuses a slot another checkout holds. `docker:up` runs it implicitly.
113
113
  - `hassan-devkit worktree:profiles list|add|remove <names>` — the compose profiles this stack runs (derived from the compose file; `worktree.profiles.required` cannot be removed).
114
+ - `hassan-devkit worktree:stop` — stop the stack of the checkout it is run from (`docker compose stop` across every profile) and keep everything: containers, volumes, slot and `.env`. `pnpm docker:dev:up` starts the same stack again. It stops only a stack the devkit manages for that checkout: without a compose file, with an empty `worktree` block or without a `.env` it says why, stops nothing and exits 0. A stop that fails exits 1. `/open-pr` runs it once the PR is open.
114
115
  - `hassan-devkit worktree:remove <BRANCH> [--keep-data] [--force]` — stack down (volumes deleted unless `--keep-data`), worktree removed, branch kept, unreferenced image tags garbage-collected.
115
116
  - `hassan-devkit worktree:prune [--dry-run]` — remove every worktree whose PR is merged (`gh pr list --head`, base repo = `upstream`) and report `merged` to the tracker for its ticket; dirty trees are never force-removed.
116
117
  - `hassan-devkit worktree:list` — worktrees with slot, ports, profiles, image tag; warns on duplicate slots.
@@ -199,7 +200,8 @@ The hook never rewrites silently. lint-staged re-stages the fixes `eslint --fix`
199
200
  4. `git push -u origin <branch>`, never forced;
200
201
  5. no open PR for the branch: `gh pr create --assignee @me`, titled `<TICKET> <Short title>` from the branch name, with a body written with the `pr` skill and ending with the tracker's ticket reference (`Closes #<n>` for GitHub); a PR already open: its body rewritten for the branch as it is now;
201
202
  6. `hassan-devkit tracker:transition <TICKET> prOpened`;
202
- 7. the PR link.
203
+ 7. `hassan-devkit worktree:stop`: the checkout's stack is stopped while the PR waits for review, so it no longer holds Docker memory. Nothing is removed (`worktree:prune` does that once the PR is merged), and `pnpm docker:dev:up` starts it again when review feedback needs it. A failed stop is reported and does not fail the skill;
204
+ 8. the PR link.
203
205
 
204
206
  It refuses to run on the base branch. When uncommitted work collides with what the merge brings in, a bare `merge-upstream` stops; here the ask for the commits is given, so the pending work is checked and committed first, then merged, and the checks run again on the merged result. The `pr` skill ships with `mattpocock-skills` from v1.3; on an older tag the body is a plain one (what changed and why, how it was verified, what to review).
205
207
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: open-pr
3
- description: "From finished work to an open pull request in one go, the house way: bring the canonical main in, run ci:check and ci:affected, commit the pending work through the commit-writer plan, push, open the PR (or rewrite the body of the one already open) and report it to the tracker. User-typed only: typing /open-pr is the explicit ask for the commits, the push and the PR."
3
+ description: "From finished work to an open pull request in one go, the house way: bring the canonical main in, run ci:check and ci:affected, commit the pending work through the commit-writer plan, push, open the PR (or rewrite the body of the one already open), report it to the tracker and stop the checkout's Docker stack. User-typed only: typing /open-pr is the explicit ask for the commits, the push and the PR."
4
4
  disable-model-invocation: true
5
5
  ---
6
6
 
@@ -14,8 +14,9 @@ ready to you), stop: that is not consent.
14
14
 
15
15
  Run the steps in order. Stop at the first failure and report it: the step, the output that
16
16
  shows the failure, and what is already done (merged, committed, pushed). Do not repair a failed
17
- check and carry on; the one exception is the hook rewrite in step 3. Never get past a step by
18
- going around it (`--no-verify`, a forced push).
17
+ check and carry on; the one exception is the hook rewrite in step 3. Step 7 is the one step
18
+ whose failure does not stop the skill. Never get past a step by going around it
19
+ (`--no-verify`, a forced push).
19
20
 
20
21
  ## Before step 1: where you are
21
22
 
@@ -40,7 +41,7 @@ Run the `merge-upstream` skill, with these differences:
40
41
  commit it), run the merge again and resolve what conflicts, then run step 2 again on the
41
42
  merged result. Nothing is committed unchecked, and nothing unchecked is pushed.
42
43
  - Do not send its report. Keep the facts (range merged, conflicts resolved, installs run) for
43
- step 7.
44
+ step 8.
44
45
 
45
46
  ## 2. Run what CI runs
46
47
 
@@ -102,9 +103,30 @@ hassan-devkit tracker:transition <TICKET> prOpened
102
103
 
103
104
  Run it whether the PR was created or updated; the branch name works as `<TICKET>`. The command
104
105
  is best effort by design: it exits 0, and a `note:` means the tracker moved nothing. Pass the
105
- note on in step 7; it is not a failure. Skip this step with the tracker `none`.
106
+ note on in step 8; it is not a failure. Skip this step with the tracker `none`.
106
107
 
107
- ## 7. Report
108
+ ## 7. Stop the stack
109
+
110
+ ```sh
111
+ hassan-devkit worktree:stop
112
+ ```
113
+
114
+ Run it whether the PR was created or updated. The PR now waits for review, and until then the
115
+ checkout's containers only hold Docker memory that every session on the machine shares. The
116
+ command stops them and removes nothing: the containers, their data, the slot and `.env` stay,
117
+ and `pnpm docker:dev:up` from the checkout's root starts the same stack again. Removing the
118
+ stack is not part of this skill; `hassan-devkit worktree:prune` does that once the PR is
119
+ merged. Where the checkout has no stack of its own the command says why, stops nothing and
120
+ exits 0.
121
+
122
+ A non-zero exit here is not a failure of the skill: the PR is open. Keep the output for step 8
123
+ and do not try another way to stop the stack.
124
+
125
+ ## 8. Report
108
126
 
109
127
  The PR link first. Then, briefly: created or updated, what step 1 merged (or that the branch
110
- was up to date), the commits made, and any `note:` from step 6.
128
+ was up to date), the commits made, and any `note:` from step 6. Last, what step 7 did, one of:
129
+
130
+ - the stack is stopped, and `pnpm docker:dev:up` starts it again;
131
+ - nothing was stopped, with the reason the command gave;
132
+ - `note:` the stop failed and the stack is still running, with the command's output.
@@ -39,6 +39,11 @@ listing is fine):
39
39
  budget shared by every session on the machine.
40
40
  - `hassan-devkit worktree:list` shows slots, ports and profiles; `worktree:remove <branch>`
41
41
  deletes the stack and its data; `worktree:prune` removes every worktree whose PR is merged.
42
+ - A stack runs only while its ticket is being worked on. `hassan-devkit worktree:stop` stops the
43
+ checkout's containers and keeps them, their data, the slot and `.env`; `pnpm docker:dev:up`
44
+ starts the same stack again. `/open-pr` stops the stack once the PR is open, and
45
+ `worktree:prune` removes it once the PR is merged; start it again when review feedback needs
46
+ it.
42
47
  - Starting work anywhere else (an existing branch, the main checkout): sync first with
43
48
  `git fetch <remote> && git merge --ff-only <remote>/main`.
44
49
  - Bringing the canonical `main` into a branch is the `/merge-upstream` skill, run when the user
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coding-with-hassan/devkit",
3
- "version": "1.5.0",
3
+ "version": "1.6.0",
4
4
  "description": "CLI for the developer workflow shared across Hassan's client projects: docker compose orchestration, db helpers, and husky hook installation.",
5
5
  "license": "MIT",
6
6
  "author": "Hassan Khousheish",
@@ -1,5 +1,5 @@
1
1
  import { requireConfig } from '../core/config.js';
2
- import { cmdCreate, cmdEnv, cmdList, cmdProfiles, cmdPrune, cmdRemove, createContext } from '../core/worktrees.js';
2
+ import { cmdCreate, cmdEnv, cmdList, cmdProfiles, cmdPrune, cmdRemove, cmdStop, createContext } from '../core/worktrees.js';
3
3
  import { exitOnFailure } from '../util/run.js';
4
4
 
5
5
  // Config loading may throw synchronously; run every action through a promise so the
@@ -22,6 +22,11 @@ export function registerWorktree(cli) {
22
22
  .command('worktree:profiles [action] [...names]', 'list | add <names> | remove <names> — which compose profiles this stack runs')
23
23
  .action((action, names) => withCtx((ctx) => cmdProfiles(ctx, action ?? 'list', names ?? [])));
24
24
 
25
+ // No context here: unlike its siblings, `stop` succeeds where the `worktree` block is missing.
26
+ cli
27
+ .command('worktree:stop', "Stop this checkout's stack; containers, volumes, slot and .env are kept (docker:up starts it again)")
28
+ .action(() => exitOnFailure(Promise.resolve().then(() => cmdStop(requireConfig()))));
29
+
25
30
  cli
26
31
  .command('worktree:remove <name>', 'Stack down (volumes deleted unless --keep-data) and remove the worktree; the branch is kept')
27
32
  .option('--keep-data', 'Keep the database and other volumes')
@@ -1,7 +1,7 @@
1
1
  import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
2
2
  import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
3
3
  import { loadProfiles } from './compose.js';
4
- import { CONFIG_KEY, ENV_DIST_FILE, ENV_FILE } from './config.js';
4
+ import { COMPOSE_FILE, CONFIG_KEY, ENV_DIST_FILE, ENV_FILE, requireConfig, resolveConfig } from './config.js';
5
5
  import { expandEnv, imageTag, imageTagInputs, sanitizeName, ticketKeyFromBranch } from './derive.js';
6
6
  import { managedValues, parseEnv, writeManagedBlock } from './env-block.js';
7
7
  import { commandExists, run } from './exec.js';
@@ -135,6 +135,59 @@ export function pruneDecision(states) {
135
135
  return 'closed';
136
136
  }
137
137
 
138
+ /**
139
+ * A compose call that reaches the containers of every profile, whatever `.env` lists. The
140
+ * shell env wins over --env-file, so `COMPOSE_PROFILES` always gets a value: a .env from
141
+ * before profiles were mandatory must not block its own stop or teardown on the compose guard.
142
+ */
143
+ export function everyProfile(args, { known, shellProfiles = process.env.COMPOSE_PROFILES }) {
144
+ return { args: ['--profile', '*', ...args], env: { COMPOSE_PROFILES: shellProfiles || known[0] || 'devkit' } };
145
+ }
146
+
147
+ /**
148
+ * Why `worktree:stop` leaves this checkout alone, or `null` when it has a stack to stop.
149
+ * Only a stack the devkit manages per checkout is stopped: without the managed `.env` the
150
+ * compose project is not this checkout's own, and a stop could hit another checkout's stack.
151
+ */
152
+ export function stopSkipReason({ hasStack, managed, hasEnv }) {
153
+ if (!hasStack) return `no ${COMPOSE_FILE}: this repo has no stack`;
154
+ if (!managed) return `"${CONFIG_KEY}.worktree" is not filled in: the stack is not managed per checkout`;
155
+ if (!hasEnv) return `no ${ENV_FILE}: this checkout has no stack of its own`;
156
+ return null;
157
+ }
158
+
159
+ /**
160
+ * The `worktree` block `worktree:create` sets a new worktree up with: the worktree's `own`
161
+ * block, because its commit decides what its stack is (ports, profiles, ready, seeds, env) and
162
+ * the invoking checkout may be behind it. Only where worktrees live and how many slots exist
163
+ * is shared by every checkout, so those two stay the invoking checkout's.
164
+ */
165
+ export function ownSettings(invoking, own) {
166
+ return { ...own, baseDir: invoking.baseDir, maxSlot: invoking.maxSlot };
167
+ }
168
+
169
+ /** Dotted keys on which two resolved `worktree` blocks differ, in the order the block lists them. */
170
+ export function settingsDrift(a, b) {
171
+ const isRecord = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
172
+ const walk = (x, y, path) => {
173
+ if (isRecord(x) && isRecord(y)) return [...new Set([...Object.keys(x), ...Object.keys(y)])].flatMap((k) => walk(x[k], y[k], path ? `${path}.${k}` : k));
174
+ return JSON.stringify(x) === JSON.stringify(y) ? [] : [path];
175
+ };
176
+ return walk(a, b, '');
177
+ }
178
+
179
+ /**
180
+ * The seed step of `worktree:create`: every entry has the `line` to print and the compose
181
+ * `exec` to run after it (`null`: nothing runs). Never empty, so the step is never silent: a
182
+ * stack that came up without its seed data looks the same as a seeded one until a login fails.
183
+ */
184
+ export function seedPlan(seeds, { hasStack, up }) {
185
+ if (seeds.scripts.length === 0) return [{ line: 'no seed scripts configured (worktree.seeds.scripts)', exec: null }];
186
+ const why = !hasStack ? `no ${COMPOSE_FILE}, so no stack` : !up ? 'the stack was not started (--no-up)' : null;
187
+ if (why) return [{ line: `not seeding: ${why}; skipped ${seeds.scripts.map((s) => `pnpm ${s}`).join(', ')} (service ${seeds.service})`, exec: null }];
188
+ return seeds.scripts.map((script) => ({ line: `seeding: pnpm ${script} (service ${seeds.service})`, exec: ['exec', seeds.service, 'pnpm', script] }));
189
+ }
190
+
138
191
  /** Dockerfiles of the buildable services, relative to `root` (extra image-tag inputs). */
139
192
  export function dockerfilesFromCompose(compose, root) {
140
193
  const files = new Set();
@@ -190,6 +243,20 @@ export function createContext(loaded, { log = console.log, note = (m) => console
190
243
  };
191
244
  }
192
245
 
246
+ /**
247
+ * The context `worktree:create` sets the new worktree at `dir` up with: its own `package.json`
248
+ * and compose file (see `ownSettings`). The tracker stays the invoking checkout's: it is asked
249
+ * about the branch, not about the stack.
250
+ */
251
+ function ownContext(ctx, dir) {
252
+ let loaded = requireConfig({ root: dir });
253
+ // A package.json without a name is named after its directory, here the branch: the defaults
254
+ // derived from the name would differ from the invoking checkout's for no reason.
255
+ if (!loaded.pkg.name) loaded = { ...loaded, rootName: ctx.rootName, config: resolveConfig(loaded.raw, { rootName: ctx.rootName }) };
256
+ const own = createContext(loaded, { log: ctx.log, note: ctx.note });
257
+ return { ...ctx, wt: ownSettings(ctx.wt, own.wt), hasStack: own.hasStack, compose: own.compose, known: own.known, drift: settingsDrift(ctx.wt, own.wt) };
258
+ }
259
+
193
260
  // ───────────────────────── .env bookkeeping ─────────────────────────
194
261
 
195
262
  export function envOf(dir) {
@@ -312,12 +379,8 @@ export function pruneImages(ctx) {
312
379
 
313
380
  /** `down` across every profile (nothing left behind); `wipe` also removes volumes. */
314
381
  export async function stackDown(ctx, dir, { wipe }) {
315
- const ok = await stack.compose(dir, ['--profile', '*', 'down', ...(wipe ? ['-v'] : []), '--remove-orphans'], {
316
- // The shell env wins over --env-file: a .env from before profiles were mandatory must
317
- // not block its own teardown on the compose guard.
318
- env: { COMPOSE_PROFILES: process.env.COMPOSE_PROFILES || ctx.known[0] || 'devkit' },
319
- allowFailure: true,
320
- });
382
+ const call = everyProfile(['down', ...(wipe ? ['-v'] : []), '--remove-orphans'], { known: ctx.known });
383
+ const ok = await stack.compose(dir, call.args, { env: call.env, allowFailure: true });
321
384
  if (!ok) ctx.note(`compose down failed in ${dir} — check 'docker ps -a' for leftovers`);
322
385
  if (wipe) {
323
386
  const project = envOf(dir).COMPOSE_PROJECT_NAME;
@@ -385,7 +448,6 @@ export async function cmdEnv(ctx, { cwd = process.cwd(), slot: requestedSlot } =
385
448
  /** `worktree:create <branch>` */
386
449
  export async function cmdCreate(ctx, branch, { profiles: requested, up = true } = {}) {
387
450
  if (!branch) throw new Error('usage: hassan-devkit worktree:create <BRANCH> [--profiles a,b] [--no-up]');
388
- const profiles = ctx.hasStack ? normalizeProfiles(requested ?? ctx.wt.profiles.default, { known: ctx.known, required: ctx.wt.profiles.required }) : [];
389
451
  await cmdPrune(ctx, {}); // reclaim merged-PR stacks (and their slots) before spending resources on a new one
390
452
  const wtDir = join(ctx.baseDir, branch);
391
453
  if (existsSync(wtDir)) throw new Error(`${wtDir} already exists`);
@@ -396,26 +458,46 @@ export async function cmdCreate(ctx, branch, { profiles: requested, up = true }
396
458
  const fetched = await run('git', ['-C', ctx.mainRoot, 'fetch', remote, 'main'], { allowFailure: true });
397
459
  if (!fetched) throw new Error(`cannot fetch ${remote}/main — refusing to base new work on a possibly stale main`);
398
460
  const base = `refs/remotes/${remote}/main`;
399
- if (git.branchExists(ctx.mainRoot, branch)) {
461
+ const existing = git.branchExists(ctx.mainRoot, branch);
462
+ if (existing) {
400
463
  await git.worktreeAdd(ctx.mainRoot, wtDir, { branch });
401
464
  if (!git.isAncestor(ctx.mainRoot, base, branch)) ctx.note(`existing branch ${branch} is behind ${remote}/main — merge it before starting work`);
402
465
  } else {
403
466
  await git.worktreeAdd(ctx.mainRoot, wtDir, { newBranch: branch, startPoint: base });
404
467
  }
468
+
469
+ // From here on the worktree's own settings decide: the invoking checkout may be behind (or
470
+ // ahead of) the commit that was just checked out, and its stack settings belong to its commit.
471
+ let own;
472
+ let profiles;
473
+ try {
474
+ own = ownContext(ctx, wtDir);
475
+ profiles = own.hasStack ? normalizeProfiles(requested ?? own.wt.profiles.default, { known: own.known, required: own.wt.profiles.required }) : [];
476
+ } catch (e) {
477
+ // Nothing is spent yet (no slot, no ticket, no install): take the worktree back, so the
478
+ // retry is not refused because the directory already exists.
479
+ const removed = await git.worktreeRemove(ctx.mainRoot, wtDir, { force: true });
480
+ if (removed && !existing) await git.branchDelete(ctx.mainRoot, branch);
481
+ const left = removed ? 'the worktree was removed again' : `the worktree is still at ${wtDir} — remove it with: hassan-devkit worktree:remove ${branch} --force`;
482
+ throw new Error(`${e.message}\n(${branch} is set up from its own package.json and compose file; ${left})`, { cause: e });
483
+ }
484
+ if (own.drift.length) {
485
+ ctx.note(`"${CONFIG_KEY}.worktree" of this checkout differs from the new worktree's in ${own.drift.join(', ')} — the new worktree follows its own package.json, except for baseDir and maxSlot (this checkout's)`);
486
+ }
405
487
  if (git.branchExists(ctx.mainRoot, 'main') && !git.isAncestor(ctx.mainRoot, base, 'main')) {
406
488
  ctx.note(`local main is behind ${remote}/main — sync it with: git checkout main && git merge --ff-only ${remote}/main`);
407
489
  }
408
490
 
409
491
  let slot = null;
410
- if (ctx.hasStack) {
492
+ if (own.hasStack) {
411
493
  await withLock(
412
- ctx.baseDir,
494
+ own.baseDir,
413
495
  '.slot.lock',
414
496
  'assigning a slot',
415
497
  120,
416
498
  async () => {
417
- slot = pickFreeSlot(usedSlots(ctx), ctx.wt.maxSlot);
418
- writeEnv(ctx, wtDir, slot, profiles);
499
+ slot = pickFreeSlot(usedSlots(own), own.wt.maxSlot);
500
+ writeEnv(own, wtDir, slot, profiles);
419
501
  },
420
502
  { log: ctx.log },
421
503
  );
@@ -432,19 +514,22 @@ export async function cmdCreate(ctx, branch, { profiles: requested, up = true }
432
514
  }
433
515
 
434
516
  let values = null;
435
- if (ctx.hasStack && up) {
436
- await ensureImages(ctx, wtDir);
517
+ if (own.hasStack && up) {
518
+ await ensureImages(own, wtDir);
437
519
  await stack.compose(wtDir, ['up', '-d', '--build']);
438
520
  values = envOf(wtDir);
439
- if (ctx.wt.ready) await stack.waitForUrl(expandEnv(ctx.wt.ready.url, values), ctx.wt.ready.timeoutSeconds, { log: ctx.log });
440
- for (const script of ctx.wt.seeds.scripts) await stack.compose(wtDir, ['exec', ctx.wt.seeds.service, 'pnpm', script]);
521
+ if (own.wt.ready) await stack.waitForUrl(expandEnv(own.wt.ready.url, values), own.wt.ready.timeoutSeconds, { log: ctx.log });
522
+ }
523
+ for (const step of seedPlan(own.wt.seeds, { hasStack: own.hasStack, up })) {
524
+ ctx.log(step.line);
525
+ if (step.exec) await stack.compose(wtDir, step.exec); // a failing seed fails the command
441
526
  }
442
527
 
443
528
  ctx.log('');
444
529
  ctx.log(`Worktree ready: ${wtDir}${slot !== null ? ` (slot ${slot}, profiles: ${profiles.join(',')})` : ''}`);
445
530
  if (values) {
446
531
  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}`);
447
- const optional = ctx.known.filter((p) => !ctx.wt.profiles.required.includes(p) && !profiles.includes(p));
532
+ const optional = own.known.filter((p) => !own.wt.profiles.required.includes(p) && !profiles.includes(p));
448
533
  if (optional.length) ctx.log(` add a profile with: hassan-devkit worktree:profiles add ${optional.join('|')}`);
449
534
  }
450
535
  return { dir: wtDir, slot, profiles };
@@ -490,6 +575,29 @@ export async function cmdProfiles(ctx, action = 'list', names = [], { cwd = proc
490
575
  }
491
576
  }
492
577
 
578
+ /**
579
+ * `worktree:stop` — stop this checkout's stack across every profile. The containers stay, with
580
+ * their volumes, the slot and `.env`, so `docker:up` starts the same stack again. Takes the
581
+ * loaded config, not a context: where there is nothing to stop it says why and succeeds, also
582
+ * in a repo whose `worktree` block is missing. A stop that fails throws.
583
+ */
584
+ export async function cmdStop(loaded, { log = console.log } = {}) {
585
+ const dir = loaded.root;
586
+ const hasStack = stack.hasComposeFile(dir);
587
+ const skip = stopSkipReason({
588
+ hasStack,
589
+ managed: hasStack && worktreeActive(loaded.config.worktree, { hasStack }),
590
+ hasEnv: existsSync(join(dir, ENV_FILE)),
591
+ });
592
+ if (skip) {
593
+ log(`${skip} — nothing stopped`);
594
+ return;
595
+ }
596
+ const call = everyProfile(['stop'], { known: createContext(loaded, { log }).known });
597
+ await stack.compose(dir, call.args, { env: call.env });
598
+ log(`stopped the stack of ${dir} (containers and data kept) — start it again with: pnpm docker:dev:up`);
599
+ }
600
+
493
601
  /** `worktree:remove <name>` — stack down (volumes gone unless --keep-data), worktree removed, branch kept. */
494
602
  export async function cmdRemove(ctx, name, { keepData = false, force = false } = {}) {
495
603
  if (!name) throw new Error('usage: hassan-devkit worktree:remove <BRANCH> [--keep-data] [--force]');