@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,113 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { join, posix } from 'node:path';
3
+ import { formatJson, planFile } from './scaffold.js';
4
+
5
+ /**
6
+ * The Claude Code layer. Nothing here is copied content: the project's `CLAUDE.md` imports the
7
+ * standards text from `node_modules` and the agent/skill files are stubs that read the shipped
8
+ * body at runtime, so a devkit bump changes what Claude does without a re-commit. Only the
9
+ * settings hook is merged into a committed file, and that merge is idempotent.
10
+ */
11
+
12
+ export const PACKAGE_DIR = 'node_modules/@coding-with-hassan/devkit';
13
+ export const STANDARDS_IMPORT_TARGET = `${PACKAGE_DIR}/claude/standards.md`;
14
+ export const IMPORT_MARKER = '<!-- devkit standards: house rules shipped by @coding-with-hassan/devkit; project rules follow -->';
15
+
16
+ const AGENT_STUB = `---
17
+ name: commit-writer
18
+ description: >
19
+ Plans the commit series for this repo's pending changes and drafts each message to pass
20
+ the commit-standards CI job. Invoke it ONLY after the user has explicitly asked, in their
21
+ own words in the current request, to commit — finishing a task, approving a plan, or a
22
+ skill/command whose instructions say to commit is NOT consent. When the user has asked, it
23
+ MUST be used BEFORE any git commit in this repo (main checkout and worktrees) — invoke it
24
+ on the full pending change set, before staging anything. Give it the ticket key if known;
25
+ it inspects the working tree itself and returns an ordered plan: for each commit, the
26
+ exact files to stage and the exact message to use. It only plans: it never stages,
27
+ commits, or pushes anything itself.
28
+ tools: Bash, Read, Grep, Glob
29
+ ---
30
+
31
+ Read \`${PACKAGE_DIR}/claude/agents/commit-writer.md\` (relative to the repo root) and follow
32
+ it exactly. That file is the agent's body; it ships with the installed devkit version so this
33
+ stub never needs to change.
34
+ `;
35
+
36
+ const SKILL_STUB = `---
37
+ name: implement-ticket
38
+ description: "Implement a piece of work based on a spec or set of tickets, the house way: in the ticket's worktree, with acceptance cases, without committing. (Model-invocable; renamed from the plugin's user-invocable 'implement' to avoid the name collision.)"
39
+ ---
40
+
41
+ Read \`${PACKAGE_DIR}/claude/skills/implement-ticket/SKILL.md\` (relative to the repo root)
42
+ and follow it exactly. That file is the skill's body; it ships with the installed devkit
43
+ version so this stub never needs to change.
44
+ `;
45
+
46
+ /** The PreToolUse hook that denies `gh pr create` without an assignee (team PR standard). */
47
+ export const PR_ASSIGNEE_HOOK = {
48
+ matcher: 'Bash',
49
+ hooks: [
50
+ {
51
+ type: 'command',
52
+ command:
53
+ 'jq -c \'if (.tool_input.command // "" | test("gh pr create")) and ((.tool_input.command // "" | test("--assignee|(^|\\\\s)-a(\\\\s|=)")) | not) then {hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"Team git workflow standard: every PR gets its author assigned at creation - re-run gh pr create with --assignee @me."}} else empty end\'',
54
+ },
55
+ ],
56
+ };
57
+
58
+ const isPrHook = (entry) => (entry?.hooks ?? []).some((h) => typeof h.command === 'string' && h.command.includes('gh pr create') && h.command.includes('--assignee'));
59
+
60
+ /** Pure: merge the PR hook into a settings object (adds once; existing entry left alone). */
61
+ export function mergeSettingsHook(settings) {
62
+ const next = structuredClone(settings ?? {});
63
+ next.hooks ??= {};
64
+ next.hooks.PreToolUse ??= [];
65
+ if (!next.hooks.PreToolUse.some(isPrHook)) next.hooks.PreToolUse.push(structuredClone(PR_ASSIGNEE_HOOK));
66
+ return next;
67
+ }
68
+
69
+ /**
70
+ * Pure: the CLAUDE.md text with the import line. Imports resolve relative to the file that
71
+ * contains them, so the path depends on where the file lives (`.claude/CLAUDE.md` vs root).
72
+ */
73
+ export function withStandardsImport(text, claudeMdRelativeDir) {
74
+ const importPath = posix.relative(claudeMdRelativeDir || '.', STANDARDS_IMPORT_TARGET);
75
+ const line = `@${importPath}`;
76
+ const current = text ?? '';
77
+ if (current.split('\n').some((l) => l.trim() === line)) return current;
78
+ const block = `${IMPORT_MARKER}\n${line}\n`;
79
+ const lines = current.split('\n');
80
+ // Keep a leading H1 on top; the import goes right under it (or at the very top).
81
+ if (lines[0]?.startsWith('# ')) return `${lines[0]}\n\n${block}${lines.slice(1).join('\n').replace(/^\n+/, '\n')}`;
82
+ return `${block}\n${current}`.replace(/\n{3,}$/, '\n');
83
+ }
84
+
85
+ /** Where the project's CLAUDE.md lives (existing one wins; default `.claude/CLAUDE.md`). */
86
+ export function claudeMdPath(root) {
87
+ if (existsSync(join(root, '.claude/CLAUDE.md'))) return '.claude/CLAUDE.md';
88
+ if (existsSync(join(root, 'CLAUDE.md'))) return 'CLAUDE.md';
89
+ return '.claude/CLAUDE.md';
90
+ }
91
+
92
+ /** Plans for the whole Claude layer. */
93
+ export function claudePlans(root) {
94
+ const plans = [];
95
+ const mdPath = claudeMdPath(root);
96
+ const current = existsSync(join(root, mdPath)) ? readFileSync(join(root, mdPath), 'utf8') : '';
97
+ plans.push(planFile(root, mdPath, withStandardsImport(current, posix.dirname(mdPath)), { managed: true }));
98
+ plans.push(planFile(root, '.claude/agents/commit-writer.md', AGENT_STUB));
99
+ plans.push(planFile(root, '.claude/skills/implement-ticket/SKILL.md', SKILL_STUB));
100
+ const settingsFile = join(root, '.claude/settings.json');
101
+ let settings = {};
102
+ if (existsSync(settingsFile)) {
103
+ try {
104
+ settings = JSON.parse(readFileSync(settingsFile, 'utf8'));
105
+ } catch (e) {
106
+ throw new Error(`.claude/settings.json is not valid JSON: ${e.message}`);
107
+ }
108
+ }
109
+ plans.push(planFile(root, '.claude/settings.json', formatJson(mergeSettingsHook(settings)), { managed: true }));
110
+ return plans;
111
+ }
112
+
113
+ export { AGENT_STUB, SKILL_STUB };
@@ -0,0 +1,69 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { existsSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { COMPOSE_FILE, ENV_FILE } from './config.js';
5
+
6
+ /**
7
+ * Profile → service maps are derived from the compose file itself, never declared.
8
+ * `docker compose config` is asked for the fully resolved model with EVERY profile
9
+ * active (`--profile '*'`); without that, a service whose dependency sits behind an
10
+ * inactive profile makes the model invalid.
11
+ */
12
+
13
+ /** Run `docker compose config --format json` and return the parsed model. */
14
+ export function readComposeModel(root, { composeFile = COMPOSE_FILE, envFile = ENV_FILE } = {}) {
15
+ const file = join(root, composeFile);
16
+ if (!existsSync(file)) return null;
17
+ const args = ['compose', '--profile', '*'];
18
+ if (existsSync(join(root, envFile))) args.push('--env-file', envFile);
19
+ args.push('-f', composeFile, 'config', '--format', 'json');
20
+ const out = execFileSync('docker', args, {
21
+ cwd: root,
22
+ // The profiles guard (`${COMPOSE_PROFILES:?…}`) must see a value even for a checkout
23
+ // whose .env predates profiles; the shell env wins over .env in interpolation.
24
+ env: { ...process.env, COMPOSE_PROFILES: process.env.COMPOSE_PROFILES || 'devkit-derive' },
25
+ stdio: ['ignore', 'pipe', 'pipe'],
26
+ maxBuffer: 16 * 1024 * 1024,
27
+ });
28
+ return JSON.parse(out.toString());
29
+ }
30
+
31
+ /**
32
+ * Pure: turn a compose model into the maps the worktree commands need.
33
+ *
34
+ * profiles — { api: ['db', 'backend'], web: ['frontend'] } (services per profile)
35
+ * always — services with no `profiles:` (active in every stack)
36
+ * buildable — services per profile that have a `build:` (the images we tag + share)
37
+ * services — per service: profiles, build ({ context, dockerfile } | null), image, ports
38
+ */
39
+ export function deriveProfiles(model) {
40
+ const services = {};
41
+ const profiles = {};
42
+ const buildable = {};
43
+ const always = [];
44
+ for (const [name, svc] of Object.entries(model?.services ?? {})) {
45
+ const svcProfiles = Array.isArray(svc.profiles) ? [...svc.profiles] : [];
46
+ const ports = (svc.ports ?? []).map((p) => (typeof p === 'object' ? String(p.published ?? '') : String(p).split(':')[0])).filter(Boolean);
47
+ const build = svc.build ? { context: svc.build.context ?? '.', dockerfile: svc.build.dockerfile ?? 'Dockerfile' } : null;
48
+ services[name] = { profiles: svcProfiles, build, image: svc.image ?? null, ports };
49
+ if (svcProfiles.length === 0) always.push(name);
50
+ for (const p of svcProfiles) {
51
+ (profiles[p] ??= []).push(name);
52
+ if (svc.build) (buildable[p] ??= []).push(name);
53
+ }
54
+ }
55
+ const sortValues = (o) => Object.fromEntries(Object.entries(o).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => [k, v.sort()]));
56
+ return {
57
+ projectName: model?.name ?? null,
58
+ services,
59
+ always: always.sort(),
60
+ profiles: sortValues(profiles),
61
+ buildable: sortValues(buildable),
62
+ };
63
+ }
64
+
65
+ /** Convenience: read + derive, or `null` when the repo has no compose file. */
66
+ export function loadProfiles(root, opts) {
67
+ const model = readComposeModel(root, opts);
68
+ return model ? deriveProfiles(model) : null;
69
+ }
@@ -0,0 +1,324 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { basename, join } from 'node:path';
3
+ import { findRepoRoot } from './root.js';
4
+ import { sanitizeName } from './derive.js';
5
+
6
+ /**
7
+ * The `hassan-devkit` block of the consumer's root package.json — the one place a
8
+ * project declares its values. Everything that can be derived (workspace projects,
9
+ * commit scopes, compose profile maps, image names) is NOT declared here; see derive.js,
10
+ * workspace.js and compose.js.
11
+ *
12
+ * Shape (every key optional; defaults below):
13
+ *
14
+ * "hassan-devkit": {
15
+ * "worktree": {
16
+ * "baseDir": "../<root-name>-worktrees",
17
+ * "maxSlot": 30,
18
+ * "projectName": "<root-name>", // compose project of slot 0
19
+ * "ports": { "api": 3000, "db": 5432 }, // base host ports, slot N adds N*10
20
+ * "profiles": { "default": ["api"], "required": ["api"] },
21
+ * "seeds": { "service": "backend", "scripts": ["seed:admin-user"] },
22
+ * "ready": { "url": "http://localhost:${DEVKIT_PORT_API}/api-json", "timeoutSeconds": 600 },
23
+ * "env": { "API_PROXY_TARGET": "http://localhost:${DEVKIT_PORT_API}" }
24
+ * },
25
+ * "tracker": { "kind": "jira", "project": "DAZ", "baseUrl": "https://x.atlassian.net" }
26
+ * | { "kind": "github", "prefix": "GH" }
27
+ * | { "kind": "none" },
28
+ * "commits": { "types": [...], "extraScopes": [...], "requireSigned": true,
29
+ * "exemptAuthors": ["renovate[bot]"], "docsUrl": "https://..." },
30
+ * "ci": { "nodeVersion": "24", "baseBranch": "main",
31
+ * "checks": [{ "name": "translations", "paths": ["^libs/i18n/"], "run": "pnpm ..." }],
32
+ * "affected": { "contentOnly": ["libs/i18n/src/**\/*.json"], "adopted": { "scripts/*.mjs": "daz-i18n" } } },
33
+ * "testCases": { "dir": "docs/testing", "languages": ["en", "nl"], "title": "My Project" },
34
+ * "db": { "service": "db", "user": "postgres", "name": "app" },
35
+ * "docker": { "preUp": "..." },
36
+ * "i18n": { "dir": "public/assets/i18n", "languages": ["en", "nl"] }
37
+ * }
38
+ */
39
+
40
+ export const CONFIG_KEY = 'hassan-devkit';
41
+ export const COMPOSE_FILE = 'docker/docker-compose.dev.yml';
42
+ export const ENV_FILE = '.env';
43
+ export const ENV_DIST_FILE = '.env.dist';
44
+
45
+ export const DEFAULT_COMMIT_TYPES = ['feat', 'fix', 'refactor', 'chore', 'docs', 'test', 'perf'];
46
+ export const DEFAULT_EXTRA_SCOPES = ['docker', 'workspace', 'docs', 'deps'];
47
+ export const DEFAULT_EXEMPT_AUTHORS = ['renovate[bot]'];
48
+ export const DEFAULT_MAX_SLOT = 30;
49
+ export const DEFAULT_GITHUB_PREFIX = 'GH';
50
+ export const DEFAULT_NODE_VERSION = '24';
51
+ export const DEFAULT_BASE_BRANCH = 'main';
52
+ export const TRACKER_KINDS = ['jira', 'github', 'none'];
53
+
54
+ const isString = (v) => typeof v === 'string';
55
+ const isNonEmptyString = (v) => isString(v) && v.trim().length > 0;
56
+ const isBoolean = (v) => typeof v === 'boolean';
57
+ const isInteger = (v) => Number.isInteger(v);
58
+ const isPort = (v) => isInteger(v) && v > 0 && v < 65536;
59
+ const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
60
+ const isStringArray = (v) => Array.isArray(v) && v.every(isNonEmptyString);
61
+ const isStringRecord = (v) => isPlainObject(v) && Object.values(v).every(isString);
62
+
63
+ /**
64
+ * Validate the raw block. Returns a list of `path: problem` strings; empty = valid.
65
+ * Unknown keys are reported too, since a typo in a key silently disables a feature.
66
+ */
67
+ export function validateConfig(raw) {
68
+ const errors = [];
69
+ if (raw === undefined) return errors;
70
+ if (!isPlainObject(raw)) return [`${CONFIG_KEY}: expected an object`];
71
+
72
+ const known = ['worktree', 'tracker', 'commits', 'ci', 'testCases', 'db', 'docker', 'i18n'];
73
+ for (const key of Object.keys(raw)) {
74
+ if (!known.includes(key)) errors.push(`${CONFIG_KEY}.${key}: unknown key (known: ${known.join(', ')})`);
75
+ }
76
+
77
+ const expect = (path, value, pred, what) => {
78
+ if (value !== undefined && !pred(value)) errors.push(`${path}: expected ${what}`);
79
+ };
80
+
81
+ const wt = raw.worktree;
82
+ if (wt !== undefined) {
83
+ if (!isPlainObject(wt)) errors.push(`${CONFIG_KEY}.worktree: expected an object`);
84
+ else {
85
+ const p = `${CONFIG_KEY}.worktree`;
86
+ expect(`${p}.baseDir`, wt.baseDir, isNonEmptyString, 'a non-empty string');
87
+ expect(`${p}.maxSlot`, wt.maxSlot, (v) => isInteger(v) && v >= 1, 'an integer >= 1');
88
+ expect(`${p}.projectName`, wt.projectName, isNonEmptyString, 'a non-empty string');
89
+ expect(`${p}.ports`, wt.ports, (v) => isPlainObject(v) && Object.values(v).every(isPort), 'an object of port numbers');
90
+ if (wt.profiles !== undefined) {
91
+ if (!isPlainObject(wt.profiles)) errors.push(`${p}.profiles: expected an object`);
92
+ else {
93
+ expect(`${p}.profiles.default`, wt.profiles.default, isStringArray, 'an array of profile names');
94
+ expect(`${p}.profiles.required`, wt.profiles.required, isStringArray, 'an array of profile names');
95
+ if (isStringArray(wt.profiles.default) && isStringArray(wt.profiles.required)) {
96
+ for (const r of wt.profiles.required) {
97
+ if (!wt.profiles.default.includes(r)) errors.push(`${p}.profiles.default: must include required profile "${r}"`);
98
+ }
99
+ }
100
+ }
101
+ }
102
+ if (wt.seeds !== undefined) {
103
+ if (!isPlainObject(wt.seeds)) errors.push(`${p}.seeds: expected an object`);
104
+ else {
105
+ expect(`${p}.seeds.service`, wt.seeds.service, isNonEmptyString, 'a compose service name');
106
+ expect(`${p}.seeds.scripts`, wt.seeds.scripts, isStringArray, 'an array of npm script names');
107
+ if (isStringArray(wt.seeds.scripts) && wt.seeds.scripts.length > 0 && !isNonEmptyString(wt.seeds.service)) {
108
+ errors.push(`${p}.seeds.service: required when seeds.scripts is set`);
109
+ }
110
+ }
111
+ }
112
+ if (wt.ready !== undefined) {
113
+ if (!isPlainObject(wt.ready)) errors.push(`${p}.ready: expected an object`);
114
+ else {
115
+ expect(`${p}.ready.url`, wt.ready.url, isNonEmptyString, 'a URL (may use ${DEVKIT_PORT_*})');
116
+ expect(`${p}.ready.timeoutSeconds`, wt.ready.timeoutSeconds, (v) => isInteger(v) && v > 0, 'a positive integer');
117
+ }
118
+ }
119
+ expect(`${p}.env`, wt.env, isStringRecord, 'an object of string values');
120
+ }
121
+ }
122
+
123
+ const tr = raw.tracker;
124
+ if (tr !== undefined) {
125
+ if (!isPlainObject(tr)) errors.push(`${CONFIG_KEY}.tracker: expected an object`);
126
+ else if (!TRACKER_KINDS.includes(tr.kind)) {
127
+ errors.push(`${CONFIG_KEY}.tracker.kind: expected one of ${TRACKER_KINDS.join(' | ')}`);
128
+ } else if (tr.kind === 'jira') {
129
+ if (!isNonEmptyString(tr.project) || !/^[A-Z][A-Z0-9_]*$/.test(tr.project)) {
130
+ errors.push(`${CONFIG_KEY}.tracker.project: expected a Jira project key like "DAZ"`);
131
+ }
132
+ expect(`${CONFIG_KEY}.tracker.baseUrl`, tr.baseUrl, (v) => isNonEmptyString(v) && /^https?:\/\//.test(v), 'an http(s) URL');
133
+ } else if (tr.kind === 'github') {
134
+ expect(`${CONFIG_KEY}.tracker.prefix`, tr.prefix, (v) => isNonEmptyString(v) && /^[A-Z][A-Z0-9]*$/.test(v), 'an upper-case token like "GH"');
135
+ }
136
+ }
137
+
138
+ const cm = raw.commits;
139
+ if (cm !== undefined) {
140
+ if (!isPlainObject(cm)) errors.push(`${CONFIG_KEY}.commits: expected an object`);
141
+ else {
142
+ const p = `${CONFIG_KEY}.commits`;
143
+ expect(`${p}.types`, cm.types, (v) => isStringArray(v) && v.length > 0, 'a non-empty array of commit types');
144
+ expect(`${p}.extraScopes`, cm.extraScopes, isStringArray, 'an array of scope names');
145
+ expect(`${p}.requireSigned`, cm.requireSigned, isBoolean, 'a boolean');
146
+ expect(`${p}.exemptAuthors`, cm.exemptAuthors, isStringArray, 'an array of GitHub logins');
147
+ expect(`${p}.docsUrl`, cm.docsUrl, isNonEmptyString, 'a URL');
148
+ }
149
+ }
150
+
151
+ const ci = raw.ci;
152
+ if (ci !== undefined) {
153
+ if (!isPlainObject(ci)) errors.push(`${CONFIG_KEY}.ci: expected an object`);
154
+ else {
155
+ const p = `${CONFIG_KEY}.ci`;
156
+ expect(`${p}.nodeVersion`, ci.nodeVersion, (v) => (isNonEmptyString(v) && /^\d+(\.\d+)*$/.test(v)) || (isInteger(v) && v > 0), 'a Node major like "24"');
157
+ expect(`${p}.baseBranch`, ci.baseBranch, isNonEmptyString, 'a branch name');
158
+ if (ci.checks !== undefined) {
159
+ if (!Array.isArray(ci.checks)) errors.push(`${p}.checks: expected an array`);
160
+ else {
161
+ ci.checks.forEach((c, i) => {
162
+ const cp = `${p}.checks[${i}]`;
163
+ if (!isPlainObject(c)) return errors.push(`${cp}: expected an object`);
164
+ if (!isNonEmptyString(c.name)) errors.push(`${cp}.name: expected a non-empty string`);
165
+ if (!isStringArray(c.paths) || c.paths.length === 0) errors.push(`${cp}.paths: expected a non-empty array of regexes`);
166
+ else {
167
+ for (const re of c.paths) {
168
+ try {
169
+ new RegExp(re);
170
+ } catch (e) {
171
+ errors.push(`${cp}.paths: invalid regex ${JSON.stringify(re)} (${e.message})`);
172
+ }
173
+ }
174
+ }
175
+ if (!isNonEmptyString(c.run)) errors.push(`${cp}.run: expected a shell command`);
176
+ });
177
+ }
178
+ }
179
+ if (ci.affected !== undefined) {
180
+ if (!isPlainObject(ci.affected)) errors.push(`${p}.affected: expected an object`);
181
+ else {
182
+ expect(`${p}.affected.contentOnly`, ci.affected.contentOnly, isStringArray, 'an array of globs');
183
+ expect(`${p}.affected.adopted`, ci.affected.adopted, isStringRecord, 'an object of glob → project name');
184
+ }
185
+ }
186
+ }
187
+ }
188
+
189
+ const tc = raw.testCases;
190
+ if (tc !== undefined) {
191
+ if (!isPlainObject(tc)) errors.push(`${CONFIG_KEY}.testCases: expected an object`);
192
+ else {
193
+ expect(`${CONFIG_KEY}.testCases.dir`, tc.dir, isNonEmptyString, 'a directory path');
194
+ expect(`${CONFIG_KEY}.testCases.languages`, tc.languages, (v) => isStringArray(v) && v.length > 0, 'a non-empty array of language codes');
195
+ expect(`${CONFIG_KEY}.testCases.title`, tc.title, isNonEmptyString, 'the project name shown in the workbook title');
196
+ }
197
+ }
198
+
199
+ const db = raw.db;
200
+ if (db !== undefined) {
201
+ if (!isPlainObject(db)) errors.push(`${CONFIG_KEY}.db: expected an object`);
202
+ else {
203
+ for (const k of ['service', 'user', 'name']) {
204
+ if (!isNonEmptyString(db[k])) errors.push(`${CONFIG_KEY}.db.${k}: expected a non-empty string`);
205
+ }
206
+ }
207
+ }
208
+
209
+ const dk = raw.docker;
210
+ if (dk !== undefined) {
211
+ if (!isPlainObject(dk)) errors.push(`${CONFIG_KEY}.docker: expected an object`);
212
+ else expect(`${CONFIG_KEY}.docker.preUp`, dk.preUp, (v) => v === null || isString(v), 'a shell command or null');
213
+ }
214
+
215
+ const i18n = raw.i18n;
216
+ if (i18n !== undefined) {
217
+ if (!isPlainObject(i18n)) errors.push(`${CONFIG_KEY}.i18n: expected an object`);
218
+ else {
219
+ expect(`${CONFIG_KEY}.i18n.dir`, i18n.dir, isNonEmptyString, 'a directory path');
220
+ expect(`${CONFIG_KEY}.i18n.languages`, i18n.languages, isStringArray, 'an array of language codes');
221
+ }
222
+ }
223
+
224
+ return errors;
225
+ }
226
+
227
+ /**
228
+ * Apply defaults. `rootName` is the sanitized root package name (or directory name),
229
+ * used for the worktree base dir, the slot-0 compose project and dev image names.
230
+ * Sections a project has not declared resolve to `null` (worktree, testCases, db) so
231
+ * commands can tell "not configured" from "configured with defaults".
232
+ */
233
+ export function resolveConfig(raw = {}, { rootName }) {
234
+ const wt = raw.worktree;
235
+ const worktree =
236
+ wt === undefined
237
+ ? null
238
+ : {
239
+ baseDir: wt.baseDir ?? `../${rootName}-worktrees`,
240
+ maxSlot: wt.maxSlot ?? DEFAULT_MAX_SLOT,
241
+ projectName: wt.projectName ?? rootName,
242
+ ports: { ...(wt.ports ?? {}) },
243
+ profiles: {
244
+ default: [...(wt.profiles?.default ?? [])],
245
+ required: [...(wt.profiles?.required ?? [])],
246
+ },
247
+ seeds: { service: wt.seeds?.service ?? null, scripts: [...(wt.seeds?.scripts ?? [])] },
248
+ ready: wt.ready?.url ? { url: wt.ready.url, timeoutSeconds: wt.ready.timeoutSeconds ?? 600 } : null,
249
+ env: { ...(wt.env ?? {}) },
250
+ };
251
+
252
+ const tr = raw.tracker ?? { kind: 'none' };
253
+ const tracker =
254
+ tr.kind === 'jira'
255
+ ? { kind: 'jira', project: tr.project, baseUrl: tr.baseUrl ?? null }
256
+ : tr.kind === 'github'
257
+ ? { kind: 'github', prefix: tr.prefix ?? DEFAULT_GITHUB_PREFIX }
258
+ : { kind: 'none' };
259
+
260
+ const cm = raw.commits ?? {};
261
+ const commits = {
262
+ types: [...(cm.types ?? DEFAULT_COMMIT_TYPES)],
263
+ extraScopes: [...(cm.extraScopes ?? DEFAULT_EXTRA_SCOPES)],
264
+ requireSigned: cm.requireSigned ?? true,
265
+ exemptAuthors: [...(cm.exemptAuthors ?? DEFAULT_EXEMPT_AUTHORS)],
266
+ docsUrl: cm.docsUrl ?? null,
267
+ };
268
+
269
+ const ci = {
270
+ nodeVersion: String(raw.ci?.nodeVersion ?? DEFAULT_NODE_VERSION),
271
+ baseBranch: raw.ci?.baseBranch ?? DEFAULT_BASE_BRANCH,
272
+ checks: (raw.ci?.checks ?? []).map((c) => ({ name: c.name, paths: [...c.paths], run: c.run })),
273
+ affected: {
274
+ contentOnly: [...(raw.ci?.affected?.contentOnly ?? [])],
275
+ adopted: { ...(raw.ci?.affected?.adopted ?? {}) },
276
+ },
277
+ };
278
+
279
+ const tc = raw.testCases;
280
+ const testCases = tc === undefined ? null : { dir: tc.dir ?? 'docs/testing', languages: [...(tc.languages ?? ['en', 'nl'])], title: tc.title ?? null };
281
+
282
+ const db = raw.db ? { service: raw.db.service, user: raw.db.user, name: raw.db.name } : null;
283
+ const docker = { preUp: typeof raw.docker?.preUp === 'string' && raw.docker.preUp.trim() ? raw.docker.preUp.trim() : null };
284
+ const i18n = { dir: raw.i18n?.dir ?? 'public/assets/i18n', languages: [...(raw.i18n?.languages ?? ['en', 'nl'])] };
285
+
286
+ return { worktree, tracker, commits, ci, testCases, db, docker, i18n };
287
+ }
288
+
289
+ /**
290
+ * Load, validate and resolve the config of the repo containing `cwd` (or of an explicit
291
+ * `root`). Never throws for a missing block — `raw` is `{}` and every section takes defaults.
292
+ */
293
+ export function loadConfig({ cwd = process.cwd(), root: explicitRoot } = {}) {
294
+ const root = explicitRoot ?? findRepoRoot(cwd);
295
+ let pkg = {};
296
+ try {
297
+ pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
298
+ } catch {
299
+ pkg = {};
300
+ }
301
+ const raw = pkg[CONFIG_KEY] ?? {};
302
+ const rootName = sanitizeName(pkg.name || basename(root));
303
+ const errors = validateConfig(pkg[CONFIG_KEY]);
304
+ const config = errors.length === 0 ? resolveConfig(raw, { rootName }) : null;
305
+ return { root, rootName, pkg, raw, errors, config };
306
+ }
307
+
308
+ /** `loadConfig` that throws an actionable error when the block is invalid. */
309
+ export function requireConfig(opts) {
310
+ const loaded = loadConfig(opts);
311
+ if (loaded.errors.length > 0) {
312
+ throw new Error(`Invalid "${CONFIG_KEY}" block in ${join(loaded.root, 'package.json')}:\n - ${loaded.errors.join('\n - ')}`);
313
+ }
314
+ return loaded;
315
+ }
316
+
317
+ /** Sections that must be present for a feature; throws with the exact key to add. */
318
+ export function requireSection(loaded, section) {
319
+ const value = loaded.config?.[section];
320
+ if (value === null || value === undefined) {
321
+ throw new Error(`Missing "${CONFIG_KEY}.${section}" in ${join(loaded.root, 'package.json')} — run \`hassan-devkit init\` to scaffold it.`);
322
+ }
323
+ return value;
324
+ }
@@ -0,0 +1,130 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+
6
+ /**
7
+ * Everything a project must NOT declare because it follows from the workspace, the
8
+ * tracker kind or the repo: commit scopes, ticket tokens, the commit-subject regex,
9
+ * dev image names and the content-addressed image tag, the canonical remote.
10
+ */
11
+
12
+ /** `@scope/My Name` → `my-name`; used for the worktree base dir, compose project, images. */
13
+ export function sanitizeName(name) {
14
+ return String(name ?? '')
15
+ .replace(/^@[^/]+\//, '')
16
+ .toLowerCase()
17
+ .replace(/[^a-z0-9]+/g, '-')
18
+ .replace(/^-+|-+$/g, '') || 'project';
19
+ }
20
+
21
+ /** Commit scopes = every workspace project name + the fixed extras, sorted, unique. */
22
+ export function commitScopes(projects, extraScopes = []) {
23
+ return [...new Set([...projects.map((p) => p.name), ...extraScopes])].sort();
24
+ }
25
+
26
+ /** Regex source for the ticket token at the start of a branch name / commit subject. */
27
+ export function ticketPattern(tracker) {
28
+ if (tracker?.kind === 'jira') return `${tracker.project}-[0-9]+`;
29
+ if (tracker?.kind === 'github') return `${tracker.prefix}-[0-9]+`;
30
+ return null;
31
+ }
32
+
33
+ /** `DAZ-42-FE-Some-Feature` → `DAZ-42`; `null` when the branch carries no ticket. */
34
+ export function ticketKeyFromBranch(branch, tracker) {
35
+ const pattern = ticketPattern(tracker);
36
+ if (!pattern) return null;
37
+ const m = new RegExp(`^(${pattern})(?:-|$)`).exec(branch ?? '');
38
+ return m ? m[1] : null;
39
+ }
40
+
41
+ /** GitHub issue number from a ticket key (`GH-12` → 12); Jira keys return `null`. */
42
+ export function issueNumberFromKey(key, tracker) {
43
+ if (tracker?.kind !== 'github' || !key) return null;
44
+ const m = new RegExp(`^${tracker.prefix}-([0-9]+)$`).exec(key);
45
+ return m ? Number(m[1]) : null;
46
+ }
47
+
48
+ const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
49
+
50
+ /**
51
+ * The commit-subject regex CI and the commit-writer agent share:
52
+ * `^<TICKET> (<types>)\((<scopes>)\): [a-z]` (ticket part omitted for tracker `none`)
53
+ */
54
+ export function commitSubjectPattern({ tracker, commits }, scopes) {
55
+ const ticket = ticketPattern(tracker);
56
+ const types = commits.types.map(escapeRe).join('|');
57
+ const scopeAlt = scopes.map(escapeRe).join('|');
58
+ return `^${ticket ? `${ticket} ` : ''}(${types})\\((${scopeAlt})\\): [a-z]`;
59
+ }
60
+
61
+ export function imageName(rootName, service, tag) {
62
+ return `${rootName}-dev-${service}:${tag}`;
63
+ }
64
+
65
+ const DEV_DOCKERFILE_RE = /^Dockerfile(\..+)?\.dev$/;
66
+
67
+ /**
68
+ * The files whose content decides a dev image: lockfile, workspace file, root + every
69
+ * project package.json, the Dockerfiles of the compose file's buildable services (`extra`,
70
+ * derived from `docker compose config`) and, as a fallback, every `docker/Dockerfile*.dev`.
71
+ * Sorted, relative to root, missing files dropped.
72
+ */
73
+ export function imageTagInputs(root, projects, extra = []) {
74
+ const files = ['pnpm-lock.yaml', 'pnpm-workspace.yaml', 'package.json', ...extra];
75
+ for (const p of projects) files.push(`${p.dir}/package.json`);
76
+ const dockerDir = join(root, 'docker');
77
+ if (extra.length === 0 && existsSync(dockerDir)) {
78
+ for (const f of readdirSync(dockerDir)) if (DEV_DOCKERFILE_RE.test(f)) files.push(`docker/${f}`);
79
+ }
80
+ return [...new Set(files)].filter((f) => existsSync(join(root, f))).sort();
81
+ }
82
+
83
+ /** sha256 over `<path>\n<content>` of every input, first 12 hex chars. */
84
+ export function imageTag(root, inputs) {
85
+ const hash = createHash('sha256');
86
+ for (const rel of inputs) {
87
+ hash.update(rel);
88
+ hash.update('\n');
89
+ hash.update(readFileSync(join(root, rel)));
90
+ hash.update('\n');
91
+ }
92
+ return hash.digest('hex').slice(0, 12);
93
+ }
94
+
95
+ /** The canonical remote: `upstream` when the fork model is in use, else `origin`. */
96
+ export function baseRemote(root) {
97
+ try {
98
+ const remotes = execFileSync('git', ['remote'], { cwd: root, stdio: ['ignore', 'pipe', 'ignore'] })
99
+ .toString()
100
+ .split('\n')
101
+ .map((s) => s.trim())
102
+ .filter(Boolean);
103
+ return remotes.includes('upstream') ? 'upstream' : 'origin';
104
+ } catch {
105
+ return 'origin';
106
+ }
107
+ }
108
+
109
+ /** `minioConsole` → `MINIO_CONSOLE`; `api` → `API`. */
110
+ export function toEnvKey(name) {
111
+ return String(name)
112
+ .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
113
+ .replace(/[^A-Za-z0-9]+/g, '_')
114
+ .toUpperCase();
115
+ }
116
+
117
+ /** Host ports of slot N: every base port + N*10, keyed `DEVKIT_PORT_<KEY>`. */
118
+ export function portsForSlot(ports, slot) {
119
+ const offset = slot * 10;
120
+ return Object.fromEntries(
121
+ Object.entries(ports)
122
+ .map(([name, base]) => [`DEVKIT_PORT_${toEnvKey(name)}`, base + offset])
123
+ .sort(([a], [b]) => a.localeCompare(b)),
124
+ );
125
+ }
126
+
127
+ /** Expand `${DEVKIT_*}` references in a string against the managed values. */
128
+ export function expandEnv(template, values) {
129
+ return String(template).replace(/\$\{([A-Z0-9_]+)\}/g, (m, key) => (key in values ? String(values[key]) : m));
130
+ }