@coding-with-hassan/devkit 0.3.0 → 1.0.0-next.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
@@ -28,6 +28,16 @@ Add a `hassan-devkit` block to your client repo's root `package.json` so the db
28
28
 
29
29
  The docker commands assume `docker/docker-compose.dev.yml` and a `.env` file at the repo root (the convention the template repo ships with).
30
30
 
31
+ Optionally add a `docker.preUp` hook — a shell command `docker:up` runs from the repo root right before `docker compose up`. Use it to refresh values your compose file reads from `.env` (image tags derived from the lockfile, compose profiles, ports) so they can never go stale between ups; a non-zero exit aborts the up:
32
+
33
+ ```json
34
+ {
35
+ "hassan-devkit": {
36
+ "docker": { "preUp": "scripts/worktree.sh env" }
37
+ }
38
+ }
39
+ ```
40
+
31
41
  ## Wire it into your scripts
32
42
 
33
43
  ```json
@@ -43,11 +53,80 @@ The docker commands assume `docker/docker-compose.dev.yml` and a `.env` file at
43
53
  }
44
54
  ```
45
55
 
56
+ ## The way of working (1.0 line)
57
+
58
+ From 1.0 the CLI is the single delivery vehicle for the whole way of working — parallel worktrees with isolated stacks, the pre-commit chain, CI with commit standards, and the Claude Code layer. Design: `docs/design/way-of-working.md` and ADR 0001 in this repo. New features assume an **Nx `apps/*` + `libs/*` pnpm monorepo**; the `docker:*`, `db:*` and `hooks:*` commands above stay layout-agnostic.
59
+
60
+ ### Configure once, derive the rest
61
+
62
+ Everything a project declares lives in the `hassan-devkit` block of the root `package.json` (validated by `hassan-devkit config:check`, unknown keys are rejected):
63
+
64
+ ```jsonc
65
+ "hassan-devkit": {
66
+ "worktree": {
67
+ "baseDir": "../my-app-worktrees", // default ../<root-name>-worktrees
68
+ "projectName": "my-app", // compose project of slot 0
69
+ "ports": { "api": 3000, "db": 5432, "web": 4200 }, // base host ports; slot N adds N*10
70
+ "profiles": { "default": ["api"], "required": ["api"] },
71
+ "seeds": { "service": "backend", "scripts": ["seed:admin-user"] },
72
+ "ready": { "url": "http://localhost:${DEVKIT_PORT_API}/api-json" },
73
+ "env": { "API_PROXY_TARGET": "http://localhost:${DEVKIT_PORT_API}" }
74
+ },
75
+ "tracker": { "kind": "jira", "project": "DAZ", "baseUrl": "https://x.atlassian.net" },
76
+ // | { "kind": "github", "prefix": "GH" } | { "kind": "none" }
77
+ "commits": { "docsUrl": "https://…/Git+Workflow" }, // types/extraScopes/requireSigned/exemptAuthors have defaults
78
+ "ci": { "checks": [{ "name": "translations", "paths": ["^libs/i18n/"], "run": "pnpm exec nx run-many -t check-translations" }] },
79
+ "testCases": { "dir": "docs/testing", "languages": ["en", "nl"] }
80
+ }
81
+ ```
82
+
83
+ Never declared, always derived:
84
+
85
+ | Fact | Source |
86
+ |---|---|
87
+ | Workspace projects (name = dir basename, kind `api` / `spa` / `lib`) | `pnpm-workspace.yaml` globs → dirs with a `package.json`; `nest-cli.json` / `angular.json` decide the kind |
88
+ | Commit scopes | project names + `commits.extraScopes` (default `docker, workspace, docs, deps`) |
89
+ | Compose profile → services / buildable images | `docker compose --profile '*' config` |
90
+ | Dev image tag | sha256 of lockfile, workspace file, every `package.json`, every `docker/Dockerfile*.dev` |
91
+ | Canonical remote | `upstream` when present, else `origin` |
92
+
93
+ Managed `.env` values use fixed keys: `COMPOSE_PROJECT_NAME`, `COMPOSE_PROFILES`, `DEVKIT_IMAGE_TAG`, `DEVKIT_SLOT`, `DEVKIT_BRANCH`, `DEVKIT_PORT_<KEY>` (one per `worktree.ports` entry, upper snake case) plus the expanded `worktree.env` extras. Compose files reference `${DEVKIT_PORT_API}` etc.
94
+
95
+ ### Commands
96
+
97
+ - `hassan-devkit init [--dry-run] [--force]` — idempotent scaffold: merges the config skeleton and default scripts into `package.json` (adds only missing keys), writes the slot-0 managed block into `.env.dist`, creates the `scripts/pre-commit-extra.sh` seam. Files the project edited are kept unless `--force`, which prints a diff first. Re-run after editing the config to refresh `.env.dist`.
98
+ - `hassan-devkit config:show [--json]` — declared + derived values (projects, scopes, compose profiles, image tag).
99
+ - `hassan-devkit config:check` — validate the block; exit 1 with the offending paths.
100
+ - `hassan-devkit commits:show [--json]` — the commit-subject contract shared by CI and the commit-writer agent: ticket token, types, derived scopes and the regex `^<TICKET> (<types>)\((<scopes>)\): [a-z]`.
101
+
102
+ ### Worktrees
103
+
104
+ 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.
105
+
106
+ - `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`.
107
+ - `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.
108
+ - `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).
109
+ - `hassan-devkit worktree:remove <BRANCH> [--keep-data] [--force]` — stack down (volumes deleted unless `--keep-data`), worktree removed, branch kept, unreferenced image tags garbage-collected.
110
+ - `hassan-devkit worktree:prune [--dry-run]` — remove every worktree whose PR is merged (`gh pr list --head`, base repo = `upstream`); dirty trees are never force-removed.
111
+ - `hassan-devkit worktree:list` — worktrees with slot, ports, profiles, image tag; warns on duplicate slots.
112
+
113
+ ### Tracker adapters (`tracker.kind`)
114
+
115
+ | kind | on `worktree:create` | credentials |
116
+ | --- | --- | --- |
117
+ | `jira` | assign the branch's `<PROJECT>-<n>` ticket to you; `To Do` → `In Progress` | `JIRA_EMAIL`, `JIRA_API_TOKEN`, `JIRA_URL` from the environment or `~/.config/jira/env` |
118
+ | `github` | `gh issue edit <n> --add-assignee @me` on the base repo for a `<PREFIX>-<n>-…` branch; PR bodies end with `Closes #<n>` | `gh auth` |
119
+ | `none` | nothing | — |
120
+
121
+ All best effort: a missing token or unreachable tracker prints a `note:` and never blocks the worktree. `init` renders `docs/agents/issue-tracker.md`, `triage-labels.md` and `domain.md` from this config for the engineering skills.
122
+
123
+ `ci:*`, the Claude layer and `test-cases:generate` land in the following prereleases — see the design doc for their contracts.
124
+
46
125
  ## Commands
47
126
 
48
127
  ### Docker
49
128
 
50
- - `hassan-devkit docker:up` — `docker compose up -d --build`
129
+ - `hassan-devkit docker:up` — runs the `docker.preUp` hook when configured, then `docker compose up -d --build`
51
130
  - `hassan-devkit docker:down` — `docker compose down`
52
131
  - `hassan-devkit docker:logs` — tail logs
53
132
  - `hassan-devkit docker:restart <service>` — `docker compose restart <service>`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coding-with-hassan/devkit",
3
- "version": "0.3.0",
3
+ "version": "1.0.0-next.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",
@@ -27,12 +27,16 @@
27
27
  "README.md"
28
28
  ],
29
29
  "dependencies": {
30
- "cac": "^6.7.14"
30
+ "cac": "^6.7.14",
31
+ "yaml": "^2.9.1"
31
32
  },
32
33
  "engines": {
33
34
  "node": ">=20"
34
35
  },
35
36
  "publishConfig": {
36
37
  "access": "public"
38
+ },
39
+ "scripts": {
40
+ "test": "node --test test/*.test.js"
37
41
  }
38
42
  }
@@ -0,0 +1,117 @@
1
+ import { CONFIG_KEY, loadConfig, requireConfig } from '../core/config.js';
2
+ import { loadProfiles } from '../core/compose.js';
3
+ import { baseRemote, commitScopes, commitSubjectPattern, imageTag, imageTagInputs, ticketPattern } from '../core/derive.js';
4
+ import { listProjects } from '../core/workspace.js';
5
+ import { exitOnFailure } from '../util/run.js';
6
+
7
+ /**
8
+ * Inspection commands. `config:show` is the one place to see declared + derived values
9
+ * together; `commits:show` is what the commit-writer agent and `ci:commit-standards` read
10
+ * so the ticket prefix, types and scopes are never mirrored by hand again.
11
+ */
12
+
13
+ export function deriveAll(loaded, { compose = true } = {}) {
14
+ const { root, rootName, config } = loaded;
15
+ const projects = listProjects(root);
16
+ const scopes = commitScopes(projects, config.commits.extraScopes);
17
+ const inputs = imageTagInputs(root, projects);
18
+ let profiles = null;
19
+ let composeError = null;
20
+ if (compose) {
21
+ try {
22
+ profiles = loadProfiles(root);
23
+ } catch (e) {
24
+ composeError = e.stderr?.toString().trim() || e.message;
25
+ }
26
+ }
27
+ return {
28
+ root,
29
+ rootName,
30
+ baseRemote: baseRemote(root),
31
+ projects,
32
+ commits: {
33
+ ticketPattern: ticketPattern(config.tracker),
34
+ types: config.commits.types,
35
+ scopes,
36
+ subjectPattern: commitSubjectPattern(config, scopes),
37
+ },
38
+ image: { inputs, tag: inputs.length ? imageTag(root, inputs) : null },
39
+ compose: profiles,
40
+ composeError,
41
+ };
42
+ }
43
+
44
+ function showConfig({ json }) {
45
+ const loaded = requireConfig();
46
+ const derived = deriveAll(loaded);
47
+ if (json) {
48
+ console.log(JSON.stringify({ config: loaded.config, derived }, null, 2));
49
+ return;
50
+ }
51
+ console.log(`root ${derived.root}`);
52
+ console.log(`root name ${derived.rootName}`);
53
+ console.log(`base remote ${derived.baseRemote}`);
54
+ console.log(`tracker ${JSON.stringify(loaded.config.tracker)}`);
55
+ console.log(`\nprojects (${derived.projects.length})`);
56
+ for (const p of derived.projects) console.log(` ${p.dir.padEnd(28)} ${p.kind.padEnd(4)} ${p.hasEslint ? 'eslint' : ''}`);
57
+ console.log(`\ncommit scopes (${derived.commits.scopes.length})\n ${derived.commits.scopes.join(', ')}`);
58
+ console.log(`\nimage tag ${derived.image.tag ?? '(no inputs)'} from ${derived.image.inputs.length} files`);
59
+ if (derived.compose) {
60
+ console.log(`\ncompose profiles (project "${derived.compose.projectName}")`);
61
+ for (const [profile, services] of Object.entries(derived.compose.profiles)) {
62
+ console.log(` ${profile.padEnd(10)} ${services.join(', ')}${derived.compose.buildable[profile] ? ` [build: ${derived.compose.buildable[profile].join(', ')}]` : ''}`);
63
+ }
64
+ if (derived.compose.always.length) console.log(` (always) ${derived.compose.always.join(', ')}`);
65
+ } else if (derived.composeError) {
66
+ console.log(`\ncompose could not read the model: ${derived.composeError}`);
67
+ } else {
68
+ console.log('\ncompose no docker/docker-compose.dev.yml');
69
+ }
70
+ if (loaded.config.worktree) {
71
+ const wt = loaded.config.worktree;
72
+ console.log(`\nworktree baseDir=${wt.baseDir} maxSlot=${wt.maxSlot} projectName=${wt.projectName}`);
73
+ console.log(` profiles default=[${wt.profiles.default}] required=[${wt.profiles.required}]`);
74
+ console.log(` ports ${JSON.stringify(wt.ports)}`);
75
+ } else {
76
+ console.log(`\nworktree not configured (add "${CONFIG_KEY}.worktree")`);
77
+ }
78
+ }
79
+
80
+ function checkConfig() {
81
+ const loaded = loadConfig();
82
+ if (loaded.errors.length > 0) {
83
+ console.error(`Invalid "${CONFIG_KEY}" block in ${loaded.root}/package.json:`);
84
+ for (const e of loaded.errors) console.error(` - ${e}`);
85
+ process.exit(1);
86
+ }
87
+ console.log(`"${CONFIG_KEY}" block OK (${Object.keys(loaded.raw).length} section(s) declared)`);
88
+ }
89
+
90
+ function showCommits({ json }) {
91
+ const loaded = requireConfig();
92
+ const { commits } = deriveAll(loaded, { compose: false });
93
+ if (json) {
94
+ console.log(JSON.stringify(commits, null, 2));
95
+ return;
96
+ }
97
+ console.log(`ticket ${commits.ticketPattern ? `${commits.ticketPattern} (e.g. "${commits.ticketPattern.replace('[0-9]+', '42')} feat(scope): …")` : 'none (tracker.kind = none)'}`);
98
+ console.log(`types ${commits.types.join(' | ')}`);
99
+ console.log(`scopes ${commits.scopes.join(' | ')}`);
100
+ console.log(`pattern ${commits.subjectPattern}`);
101
+ }
102
+
103
+ export function registerConfig(cli) {
104
+ cli
105
+ .command('config:show', 'Print the resolved hassan-devkit config plus everything derived from the workspace and compose file')
106
+ .option('--json', 'Machine-readable output')
107
+ .action((opts) => exitOnFailure(Promise.resolve().then(() => showConfig({ json: Boolean(opts.json) }))));
108
+
109
+ cli
110
+ .command('config:check', 'Validate the hassan-devkit block in package.json (exit 1 on problems)')
111
+ .action(() => exitOnFailure(Promise.resolve().then(checkConfig)));
112
+
113
+ cli
114
+ .command('commits:show', 'Print the commit-subject contract: ticket token, types, derived scopes and the regex')
115
+ .option('--json', 'Machine-readable output')
116
+ .action((opts) => exitOnFailure(Promise.resolve().then(() => showCommits({ json: Boolean(opts.json) }))));
117
+ }
@@ -1,4 +1,6 @@
1
1
  import { runCommand, exitOnFailure } from '../util/run.js';
2
+ import { readDockerConfig } from '../util/config.js';
3
+ import { loadConfig } from '../core/config.js';
2
4
 
3
5
  const COMPOSE_FILE = 'docker/docker-compose.dev.yml';
4
6
  const ENV_FILE = '.env';
@@ -7,10 +9,28 @@ function compose(args) {
7
9
  return runCommand('docker', ['compose', '--env-file', ENV_FILE, '-f', COMPOSE_FILE, ...args]);
8
10
  }
9
11
 
12
+ async function up() {
13
+ // A repo with a worktree block refreshes its managed .env (slot, profiles, image tag)
14
+ // and builds missing images on every up — the `docker.preUp` hook is no longer needed
15
+ // for that, but still runs afterwards for anything else a project hooks in.
16
+ const loaded = loadConfig();
17
+ if (loaded.errors.length === 0 && loaded.config.worktree) {
18
+ const { cmdEnv, createContext } = await import('../core/worktrees.js');
19
+ await cmdEnv(createContext(loaded));
20
+ }
21
+ const { preUp } = readDockerConfig();
22
+ if (preUp) {
23
+ console.log(`hassan-devkit: docker.preUp → ${preUp}`);
24
+ // Through the shell so the hook can be any command line, not just a binary.
25
+ await runCommand(preUp, [], { shell: true });
26
+ }
27
+ await compose(['up', '-d', '--build']);
28
+ }
29
+
10
30
  export function registerDocker(cli) {
11
31
  cli
12
- .command('docker:up', 'Build and start the dev docker compose stack')
13
- .action(() => exitOnFailure(compose(['up', '-d', '--build'])));
32
+ .command('docker:up', 'Run the docker.preUp hook (if configured), then build and start the dev docker compose stack')
33
+ .action(() => exitOnFailure(up()));
14
34
 
15
35
  cli
16
36
  .command('docker:down', 'Stop the dev docker compose stack')
@@ -0,0 +1,127 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { COMPOSE_FILE, CONFIG_KEY, ENV_DIST_FILE, loadConfig, resolveConfig } from '../core/config.js';
4
+ import { managedValues, writeManagedBlock } from '../core/env-block.js';
5
+ import { agentsDocs } from '../core/agents-docs.js';
6
+ import { applyPlan, formatJson, mergeMissing, planFile } from '../core/scaffold.js';
7
+ import { exitOnFailure } from '../util/run.js';
8
+
9
+ /**
10
+ * `hassan-devkit init` — one-shot scaffold of the way of working into an existing Nx
11
+ * pnpm workspace. Idempotent per file: missing files are created, unchanged files are
12
+ * left alone, files the project edited are kept unless `--force` (which prints a diff).
13
+ *
14
+ * Later features register more files here (CI workflow, Claude stubs, docs/agents, …);
15
+ * each entry is a function of the loaded config so it can be re-run after config edits.
16
+ */
17
+
18
+ const CONFIG_SKELETON = {
19
+ worktree: {
20
+ ports: {},
21
+ profiles: { default: [], required: [] },
22
+ seeds: { scripts: [] },
23
+ env: {},
24
+ },
25
+ tracker: { kind: 'none' },
26
+ commits: {},
27
+ ci: { checks: [] },
28
+ };
29
+
30
+ const DOCKER_SCRIPTS = {
31
+ 'docker:dev:up': 'hassan-devkit docker:up',
32
+ 'docker:dev:down': 'hassan-devkit docker:down',
33
+ 'docker:dev:logs': 'hassan-devkit docker:logs',
34
+ };
35
+ const HOOK_SCRIPTS = { prepare: 'hassan-devkit hooks:install' };
36
+ const SCRIPT_DEFAULTS = { ...DOCKER_SCRIPTS, ...HOOK_SCRIPTS };
37
+
38
+ const usesHusky = (pkg) => Boolean(pkg.devDependencies?.husky || pkg.dependencies?.husky);
39
+
40
+ const PRE_COMMIT_EXTRA = `#!/bin/sh
41
+ # Project-specific pre-commit guards. Invoked first by the shared hook that
42
+ # @coding-with-hassan/devkit installs (\`hassan-devkit hooks:install\`); exit non-zero to
43
+ # block the commit. Keep project-wide standards in the package — only guards that need
44
+ # knowledge of THIS repo belong here.
45
+ exit 0
46
+ `;
47
+
48
+ /**
49
+ * Plan the package.json changes: config skeleton + default scripts, only where missing.
50
+ * Docker scripts only make sense with a compose file, the `prepare` hook installer only
51
+ * with husky as a dependency — a repo without them (this devkit repo itself) gets neither.
52
+ */
53
+ export function planPackageJson(root, pkg) {
54
+ const next = structuredClone(pkg);
55
+ const added = [];
56
+ next[CONFIG_KEY] ??= {};
57
+ added.push(...mergeMissing(next[CONFIG_KEY], structuredClone(CONFIG_SKELETON), CONFIG_KEY));
58
+ next.scripts ??= {};
59
+ const scripts = { ...(existsSync(join(root, COMPOSE_FILE)) ? DOCKER_SCRIPTS : {}), ...(usesHusky(pkg) ? HOOK_SCRIPTS : {}) };
60
+ added.push(...mergeMissing(next.scripts, scripts, 'scripts'));
61
+ return { plan: planFile(root, 'package.json', formatJson(next), { managed: true }), added, next };
62
+ }
63
+
64
+ /** `.env.dist` gets the slot-0 managed block so a fresh clone's `.env` starts valid. */
65
+ export function planEnvDist(root, config, rootName) {
66
+ const wt = config.worktree;
67
+ // An untouched skeleton (no ports, no profiles) would write an empty COMPOSE_PROFILES=
68
+ // that the compose guard rejects — wait until the project has filled the block in.
69
+ if (!wt || (Object.keys(wt.ports).length === 0 && wt.profiles.default.length === 0)) return null;
70
+ const values = managedValues({
71
+ slot: 0,
72
+ projectName: wt.projectName ?? rootName,
73
+ profiles: wt.profiles.default,
74
+ imageTag: 'latest',
75
+ branch: 'main',
76
+ ports: wt.ports,
77
+ extraEnv: wt.env,
78
+ });
79
+ const file = join(root, ENV_DIST_FILE);
80
+ const current = existsSync(file) ? readFileSync(file, 'utf8') : '';
81
+ const profilesHint = wt.profiles.default.length ? wt.profiles.default.join('|') : 'profile';
82
+ const content = writeManagedBlock(current, values, { slot: 0, profilesHint });
83
+ return planFile(root, ENV_DIST_FILE, content, { managed: true });
84
+ }
85
+
86
+ export function buildPlans(loaded) {
87
+ const { root, rootName, pkg } = loaded;
88
+ const plans = [];
89
+ const { plan: pkgPlan, next } = planPackageJson(root, pkg);
90
+ plans.push(pkgPlan);
91
+ // Resolve against the package.json we are ABOUT to write, so `.env.dist` reflects a
92
+ // worktree block the skeleton just added.
93
+ const effective = resolveConfig(next[CONFIG_KEY] ?? {}, { rootName });
94
+ const envDist = planEnvDist(root, effective, rootName);
95
+ if (envDist) plans.push(envDist);
96
+ if (usesHusky(pkg)) plans.push(planFile(root, 'scripts/pre-commit-extra.sh', PRE_COMMIT_EXTRA, { mode: 0o755 }));
97
+ // The skills' tracker/label/domain adapters are a function of the tracker config: managed,
98
+ // so a tracker change (or a devkit bump that rewords them) flows on the next init.
99
+ for (const [path, content] of agentsDocs(effective.tracker)) plans.push(planFile(root, path, content, { managed: true }));
100
+ return plans;
101
+ }
102
+
103
+ export async function init({ force = false, dryRun = false, cwd = process.cwd(), root, log = console.log } = {}) {
104
+ const loaded = loadConfig({ cwd, root });
105
+ if (loaded.errors.length > 0) {
106
+ throw new Error(`Fix the "${CONFIG_KEY}" block first:\n - ${loaded.errors.join('\n - ')}`);
107
+ }
108
+ log(`hassan-devkit init → ${loaded.root}${dryRun ? ' (dry run)' : ''}`);
109
+ const summary = applyPlan(loaded.root, buildPlans(loaded), { force, dryRun, log });
110
+ const next = [
111
+ `Fill in "${CONFIG_KEY}" in package.json (ports, profiles, seeds, tracker) and re-run \`hassan-devkit init\` to refresh ${ENV_DIST_FILE}.`,
112
+ 'Check the result with `hassan-devkit config:show` and `hassan-devkit commits:show`.',
113
+ ];
114
+ log(`\nNext:\n - ${next.join('\n - ')}`);
115
+ return summary;
116
+ }
117
+
118
+ export function registerInit(cli) {
119
+ cli
120
+ .command('init', 'Scaffold the devkit way of working into this workspace (idempotent; --force overwrites edited files)')
121
+ .option('--force', 'Overwrite files that differ from the template (a diff is printed first)')
122
+ .option('--dry-run', 'Show what would change without writing')
123
+ .action((opts) => exitOnFailure(init({ force: Boolean(opts.force), dryRun: Boolean(opts.dryRun) })));
124
+ }
125
+
126
+ // Exported for the tests and for later scaffolds that extend the plan.
127
+ export { CONFIG_SKELETON, SCRIPT_DEFAULTS, PRE_COMMIT_EXTRA };
@@ -0,0 +1,37 @@
1
+ import { requireConfig } from '../core/config.js';
2
+ import { cmdCreate, cmdEnv, cmdList, cmdProfiles, cmdPrune, cmdRemove, createContext } from '../core/worktrees.js';
3
+ import { exitOnFailure } from '../util/run.js';
4
+
5
+ // Config loading may throw synchronously; run every action through a promise so the
6
+ // failure handler prints the message (not a stack trace) and exits 1.
7
+ const withCtx = (fn) => exitOnFailure(Promise.resolve().then(() => fn(createContext(requireConfig()))));
8
+
9
+ export function registerWorktree(cli) {
10
+ cli
11
+ .command('worktree:create <branch>', 'Create a worktree + isolated dev stack for a ticket branch off <remote>/main (prunes merged ones first)')
12
+ .option('--profiles <list>', 'Compose profiles to start with, comma-separated (default: worktree.profiles.default)')
13
+ .option('--no-up', 'Create the worktree and .env but do not start the stack')
14
+ .action((branch, opts) => withCtx((ctx) => cmdCreate(ctx, branch, { profiles: opts.profiles ? String(opts.profiles).split(',') : undefined, up: opts.up !== false })));
15
+
16
+ cli
17
+ .command('worktree:env', 'Refresh this checkout\'s managed .env block (slot, profiles, image tag), build missing images')
18
+ .option('--slot <n>', 'Force a slot (1..maxSlot); refuses one another checkout holds')
19
+ .action((opts) => withCtx((ctx) => cmdEnv(ctx, { slot: opts.slot })));
20
+
21
+ cli
22
+ .command('worktree:profiles [action] [...names]', 'list | add <names> | remove <names> — which compose profiles this stack runs')
23
+ .action((action, names) => withCtx((ctx) => cmdProfiles(ctx, action ?? 'list', names ?? [])));
24
+
25
+ cli
26
+ .command('worktree:remove <name>', 'Stack down (volumes deleted unless --keep-data) and remove the worktree; the branch is kept')
27
+ .option('--keep-data', 'Keep the database and other volumes')
28
+ .option('--force', 'Remove even with uncommitted changes')
29
+ .action((name, opts) => withCtx((ctx) => cmdRemove(ctx, name, { keepData: Boolean(opts.keepData), force: Boolean(opts.force) })));
30
+
31
+ cli
32
+ .command('worktree:prune', 'Remove every worktree whose PR is merged (stack, volumes and branch included)')
33
+ .option('--dry-run', 'Only report what would be removed')
34
+ .action((opts) => withCtx((ctx) => cmdPrune(ctx, { dryRun: Boolean(opts.dryRun) })));
35
+
36
+ cli.command('worktree:list', 'List worktrees with their slots, ports, profiles and image tags').action(() => withCtx((ctx) => cmdList(ctx)));
37
+ }