@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,186 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { dirname, join, resolve } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { loadConfig, requireConfig } from '../core/config.js';
5
+ import { affected, changedFiles } from '../core/ci/affected.js';
6
+ import { checkCommits, fetchPrCommits, prContext } from '../core/ci/commit-standards.js';
7
+ import { attach, detach } from '../core/ci/nx-cache.js';
8
+ import { WORKFLOW_PATH, renderWorkflow } from '../core/ci/workflow.js';
9
+ import { commitScopes, commitSubjectPattern } from '../core/derive.js';
10
+ import { lineDiff } from '../core/scaffold.js';
11
+ import { listProjects } from '../core/workspace.js';
12
+ import { run } from '../core/exec.js';
13
+ import { exitOnFailure } from '../util/run.js';
14
+
15
+ /**
16
+ * `ci:*` — the CI job's logic, so the project's workflow file only sequences these steps
17
+ * and a devkit bump updates what they do. Every command reads `NX_BASE`/`NX_HEAD` (set by
18
+ * nrwl/nx-set-shas) unless `--base/--head` are given.
19
+ */
20
+
21
+ const here = dirname(fileURLToPath(import.meta.url));
22
+ export const DEVKIT_PACKAGE = '@coding-with-hassan/devkit';
23
+
24
+ export function installedDevkitVersion() {
25
+ return JSON.parse(readFileSync(resolve(here, '../../package.json'), 'utf8')).version;
26
+ }
27
+
28
+ /** Pure: does `installed` satisfy the declared range? Exact, `^`, `~` and prerelease-aware. */
29
+ export function versionSatisfies(installed, range) {
30
+ if (!range) return true;
31
+ const parse = (v) => {
32
+ const m = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/.exec(String(v).trim());
33
+ return m ? { major: +m[1], minor: +m[2], patch: +m[3], pre: m[4] ?? null } : null;
34
+ };
35
+ const cmp = (a, b) => a.major - b.major || a.minor - b.minor || a.patch - b.patch || (a.pre === b.pre ? 0 : a.pre === null ? 1 : b.pre === null ? -1 : a.pre.localeCompare(b.pre));
36
+ const have = parse(installed);
37
+ const op = /^[\^~]/.exec(range)?.[0] ?? '';
38
+ const want = parse(range.replace(/^[\^~]/, ''));
39
+ if (!have || !want) return true; // workspace:*, tags, ranges we do not model → do not nag
40
+ if (cmp(have, want) < 0) return false;
41
+ if (op === '^') return want.major === 0 ? have.major === 0 && have.minor === want.minor : have.major === want.major;
42
+ if (op === '~') return have.major === want.major && have.minor === want.minor;
43
+ return cmp(have, want) === 0;
44
+ }
45
+
46
+ export function declaredDevkitRange(pkg) {
47
+ return pkg.devDependencies?.[DEVKIT_PACKAGE] ?? pkg.dependencies?.[DEVKIT_PACKAGE] ?? null;
48
+ }
49
+
50
+ /** Pure: the workflow drift check. Returns the diff lines (empty = in sync) or null when absent. */
51
+ export function workflowDrift(current, config) {
52
+ if (current === null) return null;
53
+ const expected = renderWorkflow({ nodeVersion: config.ci.nodeVersion, baseBranch: config.ci.baseBranch, exemptAuthors: config.commits.exemptAuthors });
54
+ return current === expected ? [] : lineDiff(current, expected);
55
+ }
56
+
57
+ export function doctor({ cwd = process.cwd(), log = console.log } = {}) {
58
+ const loaded = loadConfig({ cwd });
59
+ const problems = [];
60
+ if (loaded.errors.length) problems.push(...loaded.errors.map((e) => `config: ${e}`));
61
+ const range = declaredDevkitRange(loaded.pkg);
62
+ const installed = installedDevkitVersion();
63
+ if (range && !versionSatisfies(installed, range)) {
64
+ problems.push(`installed ${DEVKIT_PACKAGE}@${installed} does not satisfy the declared ${range} — run \`pnpm install\` (a stale node_modules silently loses features)`);
65
+ }
66
+ if (existsSync(join(loaded.root, '.husky')) && !existsSync(join(loaded.root, '.husky/_/pre-commit'))) {
67
+ problems.push('.husky/_/pre-commit is missing — git silently skips every hook here; run `pnpm exec husky`');
68
+ }
69
+ if (loaded.config) {
70
+ const file = join(loaded.root, WORKFLOW_PATH);
71
+ const drift = workflowDrift(existsSync(file) ? readFileSync(file, 'utf8') : null, loaded.config);
72
+ if (drift && drift.length) {
73
+ problems.push(`${WORKFLOW_PATH} differs from the devkit ${installed} template — run \`hassan-devkit init --force\` (diff below)`);
74
+ for (const line of drift) log(` ${line}`);
75
+ }
76
+ }
77
+ if (problems.length) {
78
+ for (const p of problems) log(`doctor: ${p}`);
79
+ throw new Error(`ci:doctor found ${problems.length} problem(s)`);
80
+ }
81
+ log(`ci:doctor OK (${DEVKIT_PACKAGE}@${installed}${range ? ` satisfies ${range}` : ''})`);
82
+ }
83
+
84
+ function commitStandards({ repo, pr, log = console.log } = {}) {
85
+ const loaded = requireConfig();
86
+ const ctx = prContext({ repo, pr });
87
+ if (!ctx.repo || !ctx.pr) throw new Error('ci:commit-standards needs a PR: run inside a pull_request workflow or pass --repo owner/name --pr <n>');
88
+ const { commits, tracker } = loaded.config;
89
+ if (ctx.author && commits.exemptAuthors.includes(ctx.author)) {
90
+ log(`commit standards: PR by ${ctx.author} is exempt`);
91
+ return;
92
+ }
93
+ const scopes = commitScopes(listProjects(loaded.root), commits.extraScopes);
94
+ const pattern = commitSubjectPattern({ tracker, commits }, scopes);
95
+ const { results, failed } = checkCommits(fetchPrCommits(ctx.repo, ctx.pr, { cwd: loaded.root }), { pattern, requireSigned: commits.requireSigned });
96
+ for (const r of results) {
97
+ if (r.status === 'skip') log(`SKIP ${r.sha} (${r.reason}): ${r.subject}`);
98
+ else if (r.status === 'ok') log(`ok ${r.sha}: ${r.subject}`);
99
+ else for (const p of r.problems) log(`FAIL ${r.sha} ${p}: ${r.subject}`);
100
+ }
101
+ if (failed.length) {
102
+ log('');
103
+ log(`Expected: ${pattern}`);
104
+ if (commits.docsUrl) log(`Commit standard: ${commits.docsUrl}`);
105
+ throw new Error(`${failed.length} commit(s) violate the commit standard`);
106
+ }
107
+ log(`All ${results.length} commits follow the commit standard.`);
108
+ }
109
+
110
+ function shas(opts) {
111
+ return { base: opts.base ?? process.env.NX_BASE ?? undefined, head: opts.head ?? process.env.NX_HEAD ?? undefined };
112
+ }
113
+
114
+ /** format:check for the projects owning a changed file (content files included), then every path-triggered check. */
115
+ async function check(opts, log = console.log) {
116
+ const loaded = requireConfig();
117
+ doctor({ cwd: loaded.root, log });
118
+ const { base, head } = shas(opts);
119
+ await affected(loaded.root, { targets: ['format:check'], base, head, withContent: true, config: loaded.config.ci.affected, log });
120
+ const { files } = changedFiles(loaded.root, { base, head });
121
+ for (const gate of loaded.config.ci.checks) {
122
+ const hit = files.find((f) => gate.paths.some((re) => new RegExp(re).test(f)));
123
+ if (!hit) {
124
+ log(`check ${gate.name}: no matching change, skipped`);
125
+ continue;
126
+ }
127
+ log(`check ${gate.name}: triggered by ${hit} → ${gate.run}`);
128
+ await run('sh', ['-c', gate.run], { cwd: loaded.root });
129
+ }
130
+ }
131
+
132
+ export function registerCi(cli) {
133
+ cli
134
+ .command('ci:doctor', 'Check the installed devkit against the manifest, the config block, the husky shims and the CI workflow template (exit 1 on drift)')
135
+ .action(() => exitOnFailure(Promise.resolve().then(() => doctor())));
136
+
137
+ cli
138
+ .command('ci:commit-standards', 'Validate every PR commit against the derived commit standard (and signing); needs GH_TOKEN')
139
+ .option('--repo <owner/name>', 'Repository (default: GITHUB_REPOSITORY)')
140
+ .option('--pr <n>', 'Pull request number (default: from the Actions event)')
141
+ .action((opts) => exitOnFailure(Promise.resolve().then(() => commitStandards({ repo: opts.repo, pr: opts.pr ? Number(opts.pr) : undefined }))));
142
+
143
+ cli
144
+ .command('ci:cache <action>', 'attach | detach — move the Nx task cache between .nx and the cacheable .nx-ci-cache folder')
145
+ .action((action) =>
146
+ exitOnFailure(
147
+ Promise.resolve().then(() => {
148
+ const { root } = requireConfig();
149
+ if (action === 'attach') return attach(root);
150
+ if (action === 'detach') return detach(root);
151
+ throw new Error('usage: hassan-devkit ci:cache attach|detach');
152
+ }),
153
+ ),
154
+ );
155
+
156
+ cli
157
+ .command('ci:check', 'Doctor, format:check for changed projects, then the path-triggered ci.checks')
158
+ .option('--base <sha>', 'Base SHA (default NX_BASE)')
159
+ .option('--head <sha>', 'Head SHA (default NX_HEAD)')
160
+ .action((opts) => exitOnFailure(check(opts)));
161
+
162
+ cli
163
+ .command('ci:affected', 'Run targets for the affected projects, ignoring files no target reads (default targets: lint,build)')
164
+ .option('--targets <list>', 'Comma-separated targets', { default: 'lint,build' })
165
+ .option('--base <sha>', 'Base SHA (default NX_BASE, else main)')
166
+ .option('--head <sha>', 'Head SHA (default NX_HEAD, else working tree)')
167
+ .option('--with-content', 'Keep content-only files (translation catalogs, assets) in the changed set')
168
+ .option('--dry-run', 'Print the plan only')
169
+ .action((opts) =>
170
+ exitOnFailure(
171
+ Promise.resolve().then(() => {
172
+ const loaded = requireConfig();
173
+ const { base, head } = shas(opts);
174
+ return affected(loaded.root, {
175
+ targets: String(opts.targets).split(',').filter(Boolean),
176
+ base,
177
+ head,
178
+ withContent: Boolean(opts.withContent),
179
+ dryRun: Boolean(opts.dryRun),
180
+ passthrough: opts['--'] ?? [],
181
+ config: loaded.config.ci.affected,
182
+ });
183
+ }),
184
+ ),
185
+ );
186
+ }
@@ -0,0 +1,24 @@
1
+ import { loadConfig } from '../core/config.js';
2
+ import { claudePlans } from '../core/claude.js';
3
+ import { applyPlan } from '../core/scaffold.js';
4
+ import { exitOnFailure } from '../util/run.js';
5
+
6
+ /**
7
+ * `claude:install` — wire the Claude Code layer into this repo: the `@import` of the shipped
8
+ * standards in CLAUDE.md, the agent/skill stubs and the PR-assignee hook. Idempotent; runs from
9
+ * `prepare` so every checkout has it, and from `init`.
10
+ */
11
+ export async function installClaude({ cwd = process.cwd(), log = console.log, dryRun = false } = {}) {
12
+ const { root } = loadConfig({ cwd });
13
+ const summary = applyPlan(root, claudePlans(root), { dryRun, log });
14
+ const touched = summary.created.length + summary.updated.length;
15
+ log(touched ? `claude layer: ${touched} file(s) written` : 'claude layer: up to date');
16
+ return summary;
17
+ }
18
+
19
+ export function registerClaude(cli) {
20
+ cli
21
+ .command('claude:install', 'Wire the Claude Code layer (standards import, agent/skill stubs, PR-assignee hook) into this repo')
22
+ .option('--dry-run', 'Show what would change without writing')
23
+ .action((opts) => exitOnFailure(installClaude({ dryRun: Boolean(opts.dryRun) })));
24
+ }
@@ -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,15 @@ 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, worktreeActive } = await import('../core/worktrees.js');
19
+ // An unfilled skeleton (init's default) must not take over .env management.
20
+ if (worktreeActive(loaded.config.worktree, { hasStack: true })) await cmdEnv(createContext(loaded));
21
+ }
12
22
  const { preUp } = readDockerConfig();
13
23
  if (preUp) {
14
24
  console.log(`hassan-devkit: docker.preUp → ${preUp}`);
@@ -6,31 +6,38 @@ import { runCommand, exitOnFailure } from '../util/run.js';
6
6
  const here = dirname(fileURLToPath(import.meta.url));
7
7
  const HOOK_SOURCE = resolve(here, '../../hooks/pre-commit.sh');
8
8
 
9
+ /**
10
+ * `hooks:install` runs from the consumer's `prepare` script, i.e. on every `pnpm install`
11
+ * — in the main checkout AND in every worktree. Husky's shim directory (`.husky/_`) is
12
+ * per-checkout and `husky init` only runs when `.husky` is absent, so a fresh worktree
13
+ * would have the committed hook but no shims — and git SILENTLY skips every hook when
14
+ * `core.hooksPath` points at a missing directory. `pnpm exec husky` (re)creates the shims.
15
+ */
16
+ export async function installHooks({ cwd = process.cwd(), log = console.log } = {}) {
17
+ const husky = resolve(cwd, '.husky');
18
+ if (!existsSync(husky)) {
19
+ await runCommand('pnpm', ['exec', 'husky', 'init'], { cwd });
20
+ } else if (!existsSync(resolve(husky, '_'))) {
21
+ await runCommand('pnpm', ['exec', 'husky'], { cwd });
22
+ }
23
+ const target = resolve(husky, 'pre-commit');
24
+ mkdirSync(dirname(target), { recursive: true });
25
+ copyFileSync(HOOK_SOURCE, target);
26
+ chmodSync(target, 0o755);
27
+ log(`Wrote ${target}`);
28
+ if (!existsSync(resolve(husky, '_', 'pre-commit'))) {
29
+ throw new Error(`husky shims missing in ${husky}/_ — git would silently skip all hooks; run \`pnpm exec husky\``);
30
+ }
31
+ }
32
+
9
33
  export function registerHooks(cli) {
10
34
  cli
11
- .command('hooks:install', 'Install husky and the shared pre-commit hook into the current repo')
12
- .action(() =>
13
- exitOnFailure(
14
- (async () => {
15
- if (!existsSync('.husky')) {
16
- await runCommand('pnpm', ['exec', 'husky', 'init']);
17
- }
18
- const target = resolve(process.cwd(), '.husky/pre-commit');
19
- mkdirSync(dirname(target), { recursive: true });
20
- copyFileSync(HOOK_SOURCE, target);
21
- chmodSync(target, 0o755);
22
- console.log(`Wrote ${target}`);
23
- })(),
24
- ),
25
- );
35
+ .command('hooks:install', 'Install husky (and its per-checkout shims) and the shared pre-commit hook into the current repo')
36
+ .action(() => exitOnFailure(installHooks()));
26
37
 
27
38
  cli
28
39
  .command('pre-commit', 'Body of the shared pre-commit hook (called from .husky/pre-commit)')
29
- .action(() =>
30
- exitOnFailure(
31
- runCommand('sh', [HOOK_SOURCE]),
32
- ),
33
- );
40
+ .action(() => exitOnFailure(runCommand('sh', [HOOK_SOURCE])));
34
41
 
35
42
  cli
36
43
  .command('hooks:print', 'Print the shared pre-commit hook content to stdout')
@@ -0,0 +1,211 @@
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 { WORKFLOW_PATH, renderWorkflow } from '../core/ci/workflow.js';
7
+ import { claudePlans } from '../core/claude.js';
8
+ import { listDataFiles } from '../core/test-cases/generate.js';
9
+ import { worktreeActive } from '../core/worktrees.js';
10
+ import { applyPlan, formatJson, mergeMissing, planFile } from '../core/scaffold.js';
11
+ import { exitOnFailure } from '../util/run.js';
12
+
13
+ /**
14
+ * `hassan-devkit init` — one-shot scaffold of the way of working into an existing Nx
15
+ * pnpm workspace. Idempotent per file: missing files are created, unchanged files are
16
+ * left alone, files the project edited are kept unless `--force` (which prints a diff).
17
+ *
18
+ * Later features register more files here (CI workflow, Claude stubs, docs/agents, …);
19
+ * each entry is a function of the loaded config so it can be re-run after config edits.
20
+ */
21
+
22
+ const CONFIG_SKELETON = {
23
+ worktree: {
24
+ ports: {},
25
+ profiles: { default: [], required: [] },
26
+ seeds: { scripts: [] },
27
+ env: {},
28
+ },
29
+ tracker: { kind: 'none' },
30
+ commits: {},
31
+ ci: { checks: [] },
32
+ };
33
+
34
+ const DOCKER_SCRIPTS = {
35
+ 'docker:dev:up': 'hassan-devkit docker:up',
36
+ 'docker:dev:down': 'hassan-devkit docker:down',
37
+ 'docker:dev:logs': 'hassan-devkit docker:logs',
38
+ };
39
+ const HOOK_SCRIPTS = { prepare: 'hassan-devkit hooks:install && hassan-devkit claude:install' };
40
+ const CLAUDE_ONLY_SCRIPTS = { prepare: 'hassan-devkit claude:install' };
41
+ const SCRIPT_DEFAULTS = { ...DOCKER_SCRIPTS, ...HOOK_SCRIPTS };
42
+
43
+ const usesHusky = (pkg) => Boolean(pkg.devDependencies?.husky || pkg.dependencies?.husky);
44
+
45
+ const LINT_STAGED_CONFIG = `// Targets are derived from the workspace (every project with an ESLint/Prettier config).
46
+ // Options: { exclude: ['api-client'] } to leave a project alone (e.g. generated code that must
47
+ // stay as its generator wrote it), { extra: { 'scripts/**/*.mjs': ['prettier --write'] } } for
48
+ // files outside any project.
49
+ import lintStaged from '@coding-with-hassan/devkit/lint-staged';
50
+
51
+ export default lintStaged();
52
+ `;
53
+
54
+ const PRE_COMMIT_EXTRA = `#!/bin/sh
55
+ # Project-specific pre-commit guards. Invoked first by the shared hook that
56
+ # @coding-with-hassan/devkit installs (\`hassan-devkit hooks:install\`); exit non-zero to
57
+ # block the commit. Keep project-wide standards in the package — only guards that need
58
+ # knowledge of THIS repo belong here.
59
+ exit 0
60
+ `;
61
+
62
+ const TC_DATA_STARTER = `// Bilingual acceptance test cases — the quality gate of this project (see CLAUDE.md).
63
+ // Every change to user-facing behaviour updates the cases here; regenerate the workbooks with
64
+ // \`hassan-devkit test-cases:generate\` (they are gitignored artifacts — commit this file only).
65
+ // One file per suite (\`tc-data-<suite>.ts\`), one area per epic, case IDs \`<AREA>-<nn>\`.
66
+ import { tc, type Area, type KnownIssue, type Readme } from '@coding-with-hassan/devkit/test-cases';
67
+
68
+ export const APP_AREAS: Area[] = [
69
+ {
70
+ key: 'AUTH',
71
+ name: { en: 'Authentication', nl: 'Authenticatie' },
72
+ tab: '1F3864',
73
+ cases: [
74
+ tc('AUTH-01', 'H', 'Sign in with valid credentials', 'Inloggen met geldige gegevens', 'A user account exists.', 'Er bestaat een gebruikersaccount.', '1. Open the sign-in page.\\n2. Enter the credentials and submit.', '1. Open de inlogpagina.\\n2. Vul de gegevens in en verzend.', 'The user lands on the start page, signed in.', 'De gebruiker komt ingelogd op de startpagina.'),
75
+ ],
76
+ },
77
+ ];
78
+
79
+ export const APP_KNOWN_ISSUES: KnownIssue[] = [];
80
+
81
+ export const APP_README: Readme = {
82
+ en: [['How to test', ['Work through every sheet; set Status per case and note findings in Notes.']]],
83
+ nl: [['Hoe te testen', ['Loop elk tabblad door; zet per test de Status en noteer bevindingen bij Notities.']]],
84
+ };
85
+ `;
86
+
87
+ /**
88
+ * Plan the package.json changes: config skeleton + default scripts, only where missing.
89
+ * Docker scripts only make sense with a compose file, the `prepare` hook installer only
90
+ * with husky as a dependency — a repo without them (this devkit repo itself) gets neither.
91
+ */
92
+ export function planPackageJson(root, pkg) {
93
+ const next = structuredClone(pkg);
94
+ const added = [];
95
+ next[CONFIG_KEY] ??= {};
96
+ added.push(...mergeMissing(next[CONFIG_KEY], structuredClone(CONFIG_SKELETON), CONFIG_KEY));
97
+ next.scripts ??= {};
98
+ const scripts = { ...(existsSync(join(root, COMPOSE_FILE)) ? DOCKER_SCRIPTS : {}), ...(usesHusky(pkg) ? HOOK_SCRIPTS : CLAUDE_ONLY_SCRIPTS) };
99
+ added.push(...mergeMissing(next.scripts, scripts, 'scripts'));
100
+ return { plan: planFile(root, 'package.json', formatJson(next), { managed: true }), added, next };
101
+ }
102
+
103
+ /** `.env.dist` gets the slot-0 managed block so a fresh clone's `.env` starts valid. */
104
+ export function planEnvDist(root, config, rootName) {
105
+ const wt = config.worktree;
106
+ // An untouched skeleton would write an empty COMPOSE_PROFILES= that the compose guard
107
+ // rejects — same activation rule as the worktree commands and docker:up.
108
+ if (!worktreeActive(wt, { hasStack: existsSync(join(root, COMPOSE_FILE)) }) || Object.keys(wt.ports).length === 0) return null;
109
+ const values = managedValues({
110
+ slot: 0,
111
+ projectName: wt.projectName ?? rootName,
112
+ profiles: wt.profiles.default,
113
+ imageTag: 'latest',
114
+ branch: 'main',
115
+ ports: wt.ports,
116
+ extraEnv: wt.env,
117
+ });
118
+ const file = join(root, ENV_DIST_FILE);
119
+ const current = existsSync(file) ? readFileSync(file, 'utf8') : '';
120
+ const profilesHint = wt.profiles.default.length ? wt.profiles.default.join('|') : 'profile';
121
+ const content = writeManagedBlock(current, values, { slot: 0, profilesHint });
122
+ return planFile(root, ENV_DIST_FILE, content, { managed: true });
123
+ }
124
+
125
+ /**
126
+ * The parts `init` can scaffold; `--only a,b` restricts a run to some of them so an existing
127
+ * repo can adopt the way of working one piece at a time (config first, the Claude layer last).
128
+ */
129
+ export const INIT_PARTS = {
130
+ config: 'the hassan-devkit block and default scripts in package.json',
131
+ env: 'the slot-0 managed block in .env.dist',
132
+ hooks: 'the pre-commit seam and lint-staged.config.mjs',
133
+ agents: 'docs/agents/*.md rendered from the tracker config',
134
+ ci: 'the thin .github/workflows/ci.yml',
135
+ claude: 'the CLAUDE.md import, agent/skill stubs and the PR-assignee hook',
136
+ 'test-cases': 'a starter docs/testing data file',
137
+ };
138
+
139
+ export function parseOnly(only) {
140
+ if (only === undefined || only === null || only === true) return null;
141
+ const parts = (Array.isArray(only) ? only : String(only).split(',')).map((p) => p.trim()).filter(Boolean);
142
+ const unknown = parts.filter((p) => !(p in INIT_PARTS));
143
+ if (unknown.length) throw new Error(`unknown init part(s) ${unknown.join(', ')} — known: ${Object.keys(INIT_PARTS).join(', ')}`);
144
+ return new Set(parts);
145
+ }
146
+
147
+ export function buildPlans(loaded, notes = [], { only = null } = {}) {
148
+ const { root, rootName, pkg } = loaded;
149
+ const want = (part) => only === null || only.has(part);
150
+ const plans = [];
151
+ const { plan: pkgPlan, next } = planPackageJson(root, pkg);
152
+ if (want('config')) plans.push(pkgPlan);
153
+ // Resolve against the package.json we are ABOUT to write, so `.env.dist` reflects a
154
+ // worktree block the skeleton just added.
155
+ const effective = resolveConfig(next[CONFIG_KEY] ?? {}, { rootName });
156
+ const envDist = want('env') ? planEnvDist(root, effective, rootName) : null;
157
+ if (envDist) plans.push(envDist);
158
+ if (want('hooks') && usesHusky(pkg)) {
159
+ plans.push(planFile(root, 'scripts/pre-commit-extra.sh', PRE_COMMIT_EXTRA, { mode: 0o755 }));
160
+ // lint-staged only reads one config file; a legacy hand-written `.js` must go first.
161
+ const legacy = ['lint-staged.config.js', 'lint-staged.config.cjs', '.lintstagedrc', '.lintstagedrc.js', '.lintstagedrc.json'].find((f) => existsSync(join(root, f)));
162
+ if (legacy) notes.push(`${legacy} exists — lint-staged reads only one config; replace it with the scaffolded lint-staged.config.mjs (derived targets) or delete the new file`);
163
+ plans.push(planFile(root, 'lint-staged.config.mjs', LINT_STAGED_CONFIG));
164
+ }
165
+ // The skills' tracker/label/domain adapters are a function of the tracker config: managed,
166
+ // so a tracker change (or a devkit bump that rewords them) flows on the next init.
167
+ if (want('agents')) for (const [path, content] of agentsDocs(effective.tracker)) plans.push(planFile(root, path, content, { managed: true }));
168
+ // The thin CI workflow: only for Nx workspaces (ci:affected / ci:cache need nx). Not
169
+ // managed — a project may have edited it, so drift is reported by ci:doctor and fixed
170
+ // with --force.
171
+ if (want('ci') && existsSync(join(root, 'nx.json'))) {
172
+ plans.push(planFile(root, WORKFLOW_PATH, renderWorkflow({ nodeVersion: effective.ci.nodeVersion, baseBranch: effective.ci.baseBranch, exemptAuthors: effective.commits.exemptAuthors })));
173
+ }
174
+ // The Claude layer: standards import, agent/skill stubs, PR-assignee hook.
175
+ if (want('claude')) plans.push(...claudePlans(root));
176
+ // Acceptance cases: a starter data file when the section is configured and none exists.
177
+ if (want('test-cases') && effective.testCases && listDataFiles(join(root, effective.testCases.dir)).length === 0) {
178
+ plans.push(planFile(root, `${effective.testCases.dir}/tc-data-app.ts`, TC_DATA_STARTER));
179
+ }
180
+ return plans;
181
+ }
182
+
183
+ export async function init({ force = false, dryRun = false, only, cwd = process.cwd(), root, log = console.log } = {}) {
184
+ const parts = parseOnly(only);
185
+ const loaded = loadConfig({ cwd, root });
186
+ if (loaded.errors.length > 0) {
187
+ throw new Error(`Fix the "${CONFIG_KEY}" block first:\n - ${loaded.errors.join('\n - ')}`);
188
+ }
189
+ log(`hassan-devkit init → ${loaded.root}${parts ? ` (only: ${[...parts].join(', ')})` : ''}${dryRun ? ' (dry run)' : ''}`);
190
+ const notes = [];
191
+ const summary = applyPlan(loaded.root, buildPlans(loaded, notes, { only: parts }), { force, dryRun, log });
192
+ for (const n of notes) log(` note: ${n}`);
193
+ const next = [
194
+ `Fill in "${CONFIG_KEY}" in package.json (ports, profiles, seeds, tracker) and re-run \`hassan-devkit init\` to refresh ${ENV_DIST_FILE}.`,
195
+ 'Check the result with `hassan-devkit config:show` and `hassan-devkit commits:show`.',
196
+ ];
197
+ log(`\nNext:\n - ${next.join('\n - ')}`);
198
+ return summary;
199
+ }
200
+
201
+ export function registerInit(cli) {
202
+ cli
203
+ .command('init', 'Scaffold the devkit way of working into this workspace (idempotent; --force overwrites edited files)')
204
+ .option('--force', 'Overwrite files that differ from the template (a diff is printed first)')
205
+ .option('--dry-run', 'Show what would change without writing')
206
+ .option('--only <parts>', `Scaffold only these parts (comma-separated): ${Object.keys(INIT_PARTS).join(', ')}`)
207
+ .action((opts) => exitOnFailure(init({ force: Boolean(opts.force), dryRun: Boolean(opts.dryRun), only: opts.only })));
208
+ }
209
+
210
+ // Exported for the tests and for later scaffolds that extend the plan.
211
+ export { CONFIG_SKELETON, SCRIPT_DEFAULTS, PRE_COMMIT_EXTRA };
@@ -0,0 +1,31 @@
1
+ import { join } from 'node:path';
2
+ import { requireConfig, requireSection } from '../core/config.js';
3
+ import { generate } from '../core/test-cases/generate.js';
4
+ import { exitOnFailure } from '../util/run.js';
5
+
6
+ /**
7
+ * `test-cases:generate` — the acceptance-case workbooks from `<testCases.dir>/tc-data-*.ts`.
8
+ * Languages come from `testCases.languages`, the title from `testCases.title` (default: the
9
+ * root package name). Workbooks are written next to the data and are gitignored artifacts.
10
+ */
11
+ export function registerTestCases(cli) {
12
+ cli
13
+ .command('test-cases:generate', 'Generate the bilingual acceptance-test workbooks from docs/testing/tc-data-*.ts')
14
+ .option('--lang <code>', 'Only this language')
15
+ .option('--testers <file>', 'JSON array of testers; writes one personalised workbook per tester')
16
+ .action((opts) =>
17
+ exitOnFailure(
18
+ Promise.resolve().then(() => {
19
+ const loaded = requireConfig();
20
+ const tc = requireSection(loaded, 'testCases');
21
+ return generate({
22
+ dir: join(loaded.root, tc.dir),
23
+ languages: tc.languages,
24
+ project: tc.title ?? loaded.pkg.name ?? loaded.rootName,
25
+ onlyLang: opts.lang ?? null,
26
+ testersFile: opts.testers ? join(process.cwd(), opts.testers) : null,
27
+ });
28
+ }),
29
+ ),
30
+ );
31
+ }