@coding-with-hassan/devkit 0.4.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
@@ -53,6 +53,75 @@ Optionally add a `docker.preUp` hook — a shell command `docker:up` runs from t
53
53
  }
54
54
  ```
55
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
+
56
125
  ## Commands
57
126
 
58
127
  ### Docker
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coding-with-hassan/devkit",
3
- "version": "0.4.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,5 +1,6 @@
1
1
  import { runCommand, exitOnFailure } from '../util/run.js';
2
2
  import { readDockerConfig } from '../util/config.js';
3
+ import { loadConfig } from '../core/config.js';
3
4
 
4
5
  const COMPOSE_FILE = 'docker/docker-compose.dev.yml';
5
6
  const ENV_FILE = '.env';
@@ -9,6 +10,14 @@ function compose(args) {
9
10
  }
10
11
 
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
+ }
12
21
  const { preUp } = readDockerConfig();
13
22
  if (preUp) {
14
23
  console.log(`hassan-devkit: docker.preUp → ${preUp}`);
@@ -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
+ }
@@ -0,0 +1,225 @@
1
+ /**
2
+ * `docs/agents/*.md` — the repo-local adapters the engineering skills read ("publish to
3
+ * the issue tracker", "apply the AFK-ready label", "read the domain docs"). Rendered from
4
+ * the tracker config so the endpoints and vocabulary can never drift from what
5
+ * `worktree:create` actually does. Regenerated by `hassan-devkit init`.
6
+ */
7
+
8
+ export const GENERATED_HEADER = (source) =>
9
+ `<!-- Generated by @coding-with-hassan/devkit from ${source} — edit package.json and re-run \`hassan-devkit init\`; do not edit by hand. -->\n\n`;
10
+
11
+ export const TRIAGE_LABELS = [
12
+ ['needs-triage', 'Maintainer needs to evaluate this issue'],
13
+ ['needs-info', 'Waiting on reporter for more information'],
14
+ ['ready-for-agent', 'Fully specified, ready for an AFK agent'],
15
+ ['ready-for-human', 'Requires human implementation'],
16
+ ['wontfix', 'Will not be actioned'],
17
+ ];
18
+
19
+ export function renderIssueTrackerDoc(tracker) {
20
+ const head = GENERATED_HEADER('the "hassan-devkit.tracker" config');
21
+ if (tracker.kind === 'jira') return head + jiraDoc(tracker);
22
+ if (tracker.kind === 'github') return head + githubDoc(tracker);
23
+ return (
24
+ head +
25
+ `# Issue tracker: none configured
26
+
27
+ This repo has no issue tracker wired into the devkit (\`hassan-devkit.tracker.kind\` is \`none\`).
28
+ When a skill says "publish to the issue tracker" or "fetch the relevant ticket", ask the user
29
+ where the work is tracked instead of inventing a destination. Branch names carry no ticket
30
+ token and commit subjects need none.
31
+ `
32
+ );
33
+ }
34
+
35
+ function jiraDoc({ project, baseUrl }) {
36
+ const site = baseUrl ?? 'the Jira site from `JIRA_URL` in `~/.config/jira/env`';
37
+ const k = `${project}-<n>`;
38
+ return `# Issue tracker: Jira (${project})
39
+
40
+ Issues and specs for this repo live in the Jira project **${project}** at ${site}. Use the
41
+ Atlassian MCP tools when connected (createJiraIssue, getJiraIssue, searchJiraIssuesUsingJql,
42
+ editJiraIssue, addCommentToJiraIssue, transitionJiraIssue); fall back to the REST API with
43
+ \`curl\` using the credentials in \`~/.config/jira/env\` (JIRA_URL, JIRA_EMAIL, JIRA_API_TOKEN —
44
+ basic auth).
45
+
46
+ ## Issue types
47
+
48
+ - **Task** — technical work (refactors, infra, chores)
49
+ - **New Feature** — net-new functionality
50
+ - **Story** — changes to existing behavior
51
+
52
+ Pick the type by this rule, not by gut feel.
53
+
54
+ ## Conventions
55
+
56
+ - **Branches and commits** carry the ticket key: branch \`${project}-<n>-Short-Title\`, commit
57
+ subject \`${project}-<n> type(scope): …\` (see \`hassan-devkit commits:show\`).
58
+ - **Create an issue**: MCP \`createJiraIssue\` with projectKey \`${project}\`, or \`POST /rest/api/3/issue\`.
59
+ - **Read an issue**: MCP \`getJiraIssue\` (include comments), or
60
+ \`GET /rest/api/3/issue/${k}?expand=renderedFields\` + \`GET /rest/api/3/issue/${k}/comment\`.
61
+ - **List issues**: MCP \`searchJiraIssuesUsingJql\`, e.g.
62
+ \`project = ${project} AND statusCategory != Done ORDER BY created DESC\`.
63
+ - **Comment**: MCP \`addCommentToJiraIssue\`, or \`POST .../comment\`.
64
+ - **Assign — always to the current user when you start a ticket**: whoever starts the work
65
+ owns the issue. \`hassan-devkit worktree:create ${project}-<n>-…\` does it for the branch's
66
+ ticket (alongside the To Do → In Progress transition); for any other way of picking up a
67
+ ticket, do it yourself first: MCP \`editJiraIssue\` on the \`assignee\` field, or
68
+ \`GET /rest/api/3/myself\` for your \`accountId\` and \`PUT /rest/api/3/issue/${k}/assignee\`
69
+ with \`{"accountId": "<id>"}\`. Never leave a ticket you are working on unassigned or
70
+ assigned to someone else.
71
+ - **Labels**: set via \`editJiraIssue\` on the \`labels\` field (add/remove by updating the array).
72
+ - **Close**: MCP \`transitionJiraIssue\` — fetch available transitions first with
73
+ \`getTransitionsForJiraIssue\`; the workflow decides valid target states.
74
+ - **Never try to delete issues** — the Jira Free plan doesn't allow it. Close/transition instead.
75
+
76
+ ## When a skill says "publish to the issue tracker"
77
+
78
+ Create a Jira issue in ${project} (choose the issue type per the table above).
79
+
80
+ ## When a skill says "fetch the relevant ticket"
81
+
82
+ Fetch the ${project} issue with its comments.
83
+
84
+ ## Wayfinding operations
85
+
86
+ The **map** is a single ${project} issue labelled \`wayfinder-map\`; child tickets are issues
87
+ linked to it ("relates to" or parent link where available) with a \`Part of ${k}\` line at the
88
+ top of the description and a \`wayfinder-<type>\` label (\`research\`/\`prototype\`/\`grilling\`/\`task\`).
89
+ Blocking uses Jira's native "is blocked by" issue links. Claim = assign to yourself;
90
+ resolve = comment with the answer, then transition to Done.
91
+ `;
92
+ }
93
+
94
+ function githubDoc({ prefix }) {
95
+ return `# Issue tracker: GitHub Issues
96
+
97
+ Issues and specs for this repo live in GitHub Issues of the **base repository** (the
98
+ \`upstream\` remote in the fork model, else \`origin\`). Use the \`gh\` CLI; it is authenticated on
99
+ this machine.
100
+
101
+ ## Conventions
102
+
103
+ - **Branches and commits** carry the issue as \`${prefix}-<n>\`: branch \`${prefix}-<n>-Short-Title\`,
104
+ commit subject \`${prefix}-<n> type(scope): …\` (see \`hassan-devkit commits:show\`). A leading
105
+ \`#<n>\` is never used in a subject — git treats \`#\` lines as comments in the editor.
106
+ - **PR body** ends with \`Closes #<n>\` so the issue closes on merge.
107
+ - **Create an issue**: \`gh issue create --repo <owner/repo> --title … --body …\`.
108
+ - **Read an issue**: \`gh issue view <n> --comments\`.
109
+ - **List issues**: \`gh issue list --state open\` (add \`--label\` / \`--assignee @me\` as needed).
110
+ - **Comment**: \`gh issue comment <n> --body …\`.
111
+ - **Assign — always to the current user when you start an issue**: whoever starts the work
112
+ owns it. \`hassan-devkit worktree:create ${prefix}-<n>-…\` runs \`gh issue edit <n> --add-assignee @me\`
113
+ for the branch's issue; for any other way of picking up an issue, run that yourself first.
114
+ There is no status field: an open PR is the progress signal.
115
+ - **Labels**: \`gh issue edit <n> --add-label … / --remove-label …\`.
116
+ - **Close**: \`gh issue close <n>\` (or let the PR's \`Closes #<n>\` do it).
117
+
118
+ ## When a skill says "publish to the issue tracker"
119
+
120
+ Create a GitHub issue on the base repository.
121
+
122
+ ## When a skill says "fetch the relevant ticket"
123
+
124
+ Fetch the issue with its comments (\`gh issue view <n> --comments\`).
125
+
126
+ ## Wayfinding operations
127
+
128
+ The **map** is a single issue labelled \`wayfinder-map\`; child issues carry a \`Part of #<map>\`
129
+ line at the top of the body and a \`wayfinder-<type>\` label (\`research\`/\`prototype\`/\`grilling\`/\`task\`).
130
+ Blocking is a \`Blocked by #<n>\` line in the body (GitHub has no native blocking link outside
131
+ Projects). Claim = assign to yourself; resolve = comment with the answer, then close.
132
+ `;
133
+ }
134
+
135
+ export function renderTriageLabelsDoc() {
136
+ const rows = TRIAGE_LABELS.map(([label, meaning]) => `| \`${label}\` | \`${label}\` | ${meaning} |`).join('\n');
137
+ return `${GENERATED_HEADER('the devkit triage vocabulary')}# Triage Labels
138
+
139
+ The skills speak in terms of five canonical triage roles. This file maps those roles to the
140
+ label strings used in this repo's issue tracker — identical by convention, so a label travels
141
+ unchanged between repos.
142
+
143
+ | Label in mattpocock/skills | Label in our tracker | Meaning |
144
+ | --- | --- | --- |
145
+ ${rows}
146
+
147
+ When a skill mentions a role (e.g. "apply the AFK-ready triage label"), use the corresponding
148
+ label string from this table.
149
+ `;
150
+ }
151
+
152
+ export function renderDomainDoc() {
153
+ return `${GENERATED_HEADER('the devkit domain-docs convention')}# Domain Docs
154
+
155
+ How the engineering skills should consume this repo's domain documentation when exploring
156
+ the codebase.
157
+
158
+ ## Before exploring, read these
159
+
160
+ - **\`CONTEXT.md\`** at the repo root, or
161
+ - **\`CONTEXT-MAP.md\`** at the repo root if it exists — it points at one \`CONTEXT.md\` per
162
+ context. Read each one relevant to the topic.
163
+ - **\`docs/adr/\`** — read ADRs that touch the area you're about to work in. In multi-context
164
+ repos, also check \`src/<context>/docs/adr/\` for context-scoped decisions.
165
+
166
+ If any of these files don't exist, **proceed silently**. Don't flag their absence; don't
167
+ suggest creating them upfront. The \`/domain-modeling\` skill (reached via \`/grill-with-docs\`
168
+ and \`/improve-codebase-architecture\`) creates them lazily when terms or decisions actually
169
+ get resolved.
170
+
171
+ ## File structure
172
+
173
+ Single-context repo (most repos):
174
+
175
+ \`\`\`
176
+ /
177
+ ├── CONTEXT.md
178
+ ├── docs/adr/
179
+ │ ├── 0001-event-sourced-orders.md
180
+ │ └── 0002-postgres-for-write-model.md
181
+ └── src/
182
+ \`\`\`
183
+
184
+ Multi-context repo (presence of \`CONTEXT-MAP.md\` at the root):
185
+
186
+ \`\`\`
187
+ /
188
+ ├── CONTEXT-MAP.md
189
+ ├── docs/adr/ ← system-wide decisions
190
+ └── src/
191
+ ├── ordering/
192
+ │ ├── CONTEXT.md
193
+ │ └── docs/adr/ ← context-specific decisions
194
+ └── billing/
195
+ ├── CONTEXT.md
196
+ └── docs/adr/
197
+ \`\`\`
198
+
199
+ ## Use the glossary's vocabulary
200
+
201
+ When your output names a domain concept (in an issue title, a refactor proposal, a
202
+ hypothesis, a test name), use the term as defined in \`CONTEXT.md\`. Don't drift to synonyms
203
+ the glossary explicitly avoids.
204
+
205
+ If the concept you need isn't in the glossary yet, that's a signal — either you're inventing
206
+ language the project doesn't use (reconsider) or there's a real gap (note it for
207
+ \`/domain-modeling\`).
208
+
209
+ ## Flag ADR conflicts
210
+
211
+ If your output contradicts an existing ADR, surface it explicitly rather than silently
212
+ overriding:
213
+
214
+ > _Contradicts ADR-0007 (event-sourced orders) — but worth reopening because…_
215
+ `;
216
+ }
217
+
218
+ /** The three files as `init` plans expect them: `[path, content]`. */
219
+ export function agentsDocs(tracker) {
220
+ return [
221
+ ['docs/agents/issue-tracker.md', renderIssueTrackerDoc(tracker)],
222
+ ['docs/agents/triage-labels.md', renderTriageLabelsDoc()],
223
+ ['docs/agents/domain.md', renderDomainDoc()],
224
+ ];
225
+ }