@coding-with-hassan/devkit 0.3.0 → 1.0.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
+ }
@@ -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,316 @@
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": { "checks": [{ "name": "translations", "paths": ["^libs/i18n/"], "run": "pnpm ..." }],
31
+ * "affected": { "contentOnly": ["libs/i18n/src/**\/*.json"], "adopted": { "scripts/*.mjs": "daz-i18n" } } },
32
+ * "testCases": { "dir": "docs/testing", "languages": ["en", "nl"] },
33
+ * "db": { "service": "db", "user": "postgres", "name": "app" },
34
+ * "docker": { "preUp": "..." },
35
+ * "i18n": { "dir": "public/assets/i18n", "languages": ["en", "nl"] }
36
+ * }
37
+ */
38
+
39
+ export const CONFIG_KEY = 'hassan-devkit';
40
+ export const COMPOSE_FILE = 'docker/docker-compose.dev.yml';
41
+ export const ENV_FILE = '.env';
42
+ export const ENV_DIST_FILE = '.env.dist';
43
+
44
+ export const DEFAULT_COMMIT_TYPES = ['feat', 'fix', 'refactor', 'chore', 'docs', 'test', 'perf'];
45
+ export const DEFAULT_EXTRA_SCOPES = ['docker', 'workspace', 'docs', 'deps'];
46
+ export const DEFAULT_EXEMPT_AUTHORS = ['renovate[bot]'];
47
+ export const DEFAULT_MAX_SLOT = 30;
48
+ export const DEFAULT_GITHUB_PREFIX = 'GH';
49
+ export const TRACKER_KINDS = ['jira', 'github', 'none'];
50
+
51
+ const isString = (v) => typeof v === 'string';
52
+ const isNonEmptyString = (v) => isString(v) && v.trim().length > 0;
53
+ const isBoolean = (v) => typeof v === 'boolean';
54
+ const isInteger = (v) => Number.isInteger(v);
55
+ const isPort = (v) => isInteger(v) && v > 0 && v < 65536;
56
+ const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
57
+ const isStringArray = (v) => Array.isArray(v) && v.every(isNonEmptyString);
58
+ const isStringRecord = (v) => isPlainObject(v) && Object.values(v).every(isString);
59
+
60
+ /**
61
+ * Validate the raw block. Returns a list of `path: problem` strings; empty = valid.
62
+ * Unknown keys are reported too, since a typo in a key silently disables a feature.
63
+ */
64
+ export function validateConfig(raw) {
65
+ const errors = [];
66
+ if (raw === undefined) return errors;
67
+ if (!isPlainObject(raw)) return [`${CONFIG_KEY}: expected an object`];
68
+
69
+ const known = ['worktree', 'tracker', 'commits', 'ci', 'testCases', 'db', 'docker', 'i18n'];
70
+ for (const key of Object.keys(raw)) {
71
+ if (!known.includes(key)) errors.push(`${CONFIG_KEY}.${key}: unknown key (known: ${known.join(', ')})`);
72
+ }
73
+
74
+ const expect = (path, value, pred, what) => {
75
+ if (value !== undefined && !pred(value)) errors.push(`${path}: expected ${what}`);
76
+ };
77
+
78
+ const wt = raw.worktree;
79
+ if (wt !== undefined) {
80
+ if (!isPlainObject(wt)) errors.push(`${CONFIG_KEY}.worktree: expected an object`);
81
+ else {
82
+ const p = `${CONFIG_KEY}.worktree`;
83
+ expect(`${p}.baseDir`, wt.baseDir, isNonEmptyString, 'a non-empty string');
84
+ expect(`${p}.maxSlot`, wt.maxSlot, (v) => isInteger(v) && v >= 1, 'an integer >= 1');
85
+ expect(`${p}.projectName`, wt.projectName, isNonEmptyString, 'a non-empty string');
86
+ expect(`${p}.ports`, wt.ports, (v) => isPlainObject(v) && Object.values(v).every(isPort), 'an object of port numbers');
87
+ if (wt.profiles !== undefined) {
88
+ if (!isPlainObject(wt.profiles)) errors.push(`${p}.profiles: expected an object`);
89
+ else {
90
+ expect(`${p}.profiles.default`, wt.profiles.default, isStringArray, 'an array of profile names');
91
+ expect(`${p}.profiles.required`, wt.profiles.required, isStringArray, 'an array of profile names');
92
+ if (isStringArray(wt.profiles.default) && isStringArray(wt.profiles.required)) {
93
+ for (const r of wt.profiles.required) {
94
+ if (!wt.profiles.default.includes(r)) errors.push(`${p}.profiles.default: must include required profile "${r}"`);
95
+ }
96
+ }
97
+ }
98
+ }
99
+ if (wt.seeds !== undefined) {
100
+ if (!isPlainObject(wt.seeds)) errors.push(`${p}.seeds: expected an object`);
101
+ else {
102
+ expect(`${p}.seeds.service`, wt.seeds.service, isNonEmptyString, 'a compose service name');
103
+ expect(`${p}.seeds.scripts`, wt.seeds.scripts, isStringArray, 'an array of npm script names');
104
+ if (isStringArray(wt.seeds.scripts) && wt.seeds.scripts.length > 0 && !isNonEmptyString(wt.seeds.service)) {
105
+ errors.push(`${p}.seeds.service: required when seeds.scripts is set`);
106
+ }
107
+ }
108
+ }
109
+ if (wt.ready !== undefined) {
110
+ if (!isPlainObject(wt.ready)) errors.push(`${p}.ready: expected an object`);
111
+ else {
112
+ expect(`${p}.ready.url`, wt.ready.url, isNonEmptyString, 'a URL (may use ${DEVKIT_PORT_*})');
113
+ expect(`${p}.ready.timeoutSeconds`, wt.ready.timeoutSeconds, (v) => isInteger(v) && v > 0, 'a positive integer');
114
+ }
115
+ }
116
+ expect(`${p}.env`, wt.env, isStringRecord, 'an object of string values');
117
+ }
118
+ }
119
+
120
+ const tr = raw.tracker;
121
+ if (tr !== undefined) {
122
+ if (!isPlainObject(tr)) errors.push(`${CONFIG_KEY}.tracker: expected an object`);
123
+ else if (!TRACKER_KINDS.includes(tr.kind)) {
124
+ errors.push(`${CONFIG_KEY}.tracker.kind: expected one of ${TRACKER_KINDS.join(' | ')}`);
125
+ } else if (tr.kind === 'jira') {
126
+ if (!isNonEmptyString(tr.project) || !/^[A-Z][A-Z0-9_]*$/.test(tr.project)) {
127
+ errors.push(`${CONFIG_KEY}.tracker.project: expected a Jira project key like "DAZ"`);
128
+ }
129
+ expect(`${CONFIG_KEY}.tracker.baseUrl`, tr.baseUrl, (v) => isNonEmptyString(v) && /^https?:\/\//.test(v), 'an http(s) URL');
130
+ } else if (tr.kind === 'github') {
131
+ expect(`${CONFIG_KEY}.tracker.prefix`, tr.prefix, (v) => isNonEmptyString(v) && /^[A-Z][A-Z0-9]*$/.test(v), 'an upper-case token like "GH"');
132
+ }
133
+ }
134
+
135
+ const cm = raw.commits;
136
+ if (cm !== undefined) {
137
+ if (!isPlainObject(cm)) errors.push(`${CONFIG_KEY}.commits: expected an object`);
138
+ else {
139
+ const p = `${CONFIG_KEY}.commits`;
140
+ expect(`${p}.types`, cm.types, (v) => isStringArray(v) && v.length > 0, 'a non-empty array of commit types');
141
+ expect(`${p}.extraScopes`, cm.extraScopes, isStringArray, 'an array of scope names');
142
+ expect(`${p}.requireSigned`, cm.requireSigned, isBoolean, 'a boolean');
143
+ expect(`${p}.exemptAuthors`, cm.exemptAuthors, isStringArray, 'an array of GitHub logins');
144
+ expect(`${p}.docsUrl`, cm.docsUrl, isNonEmptyString, 'a URL');
145
+ }
146
+ }
147
+
148
+ const ci = raw.ci;
149
+ if (ci !== undefined) {
150
+ if (!isPlainObject(ci)) errors.push(`${CONFIG_KEY}.ci: expected an object`);
151
+ else {
152
+ const p = `${CONFIG_KEY}.ci`;
153
+ if (ci.checks !== undefined) {
154
+ if (!Array.isArray(ci.checks)) errors.push(`${p}.checks: expected an array`);
155
+ else {
156
+ ci.checks.forEach((c, i) => {
157
+ const cp = `${p}.checks[${i}]`;
158
+ if (!isPlainObject(c)) return errors.push(`${cp}: expected an object`);
159
+ if (!isNonEmptyString(c.name)) errors.push(`${cp}.name: expected a non-empty string`);
160
+ if (!isStringArray(c.paths) || c.paths.length === 0) errors.push(`${cp}.paths: expected a non-empty array of regexes`);
161
+ else {
162
+ for (const re of c.paths) {
163
+ try {
164
+ new RegExp(re);
165
+ } catch (e) {
166
+ errors.push(`${cp}.paths: invalid regex ${JSON.stringify(re)} (${e.message})`);
167
+ }
168
+ }
169
+ }
170
+ if (!isNonEmptyString(c.run)) errors.push(`${cp}.run: expected a shell command`);
171
+ });
172
+ }
173
+ }
174
+ if (ci.affected !== undefined) {
175
+ if (!isPlainObject(ci.affected)) errors.push(`${p}.affected: expected an object`);
176
+ else {
177
+ expect(`${p}.affected.contentOnly`, ci.affected.contentOnly, isStringArray, 'an array of globs');
178
+ expect(`${p}.affected.adopted`, ci.affected.adopted, isStringRecord, 'an object of glob → project name');
179
+ }
180
+ }
181
+ }
182
+ }
183
+
184
+ const tc = raw.testCases;
185
+ if (tc !== undefined) {
186
+ if (!isPlainObject(tc)) errors.push(`${CONFIG_KEY}.testCases: expected an object`);
187
+ else {
188
+ expect(`${CONFIG_KEY}.testCases.dir`, tc.dir, isNonEmptyString, 'a directory path');
189
+ expect(`${CONFIG_KEY}.testCases.languages`, tc.languages, (v) => isStringArray(v) && v.length > 0, 'a non-empty array of language codes');
190
+ }
191
+ }
192
+
193
+ const db = raw.db;
194
+ if (db !== undefined) {
195
+ if (!isPlainObject(db)) errors.push(`${CONFIG_KEY}.db: expected an object`);
196
+ else {
197
+ for (const k of ['service', 'user', 'name']) {
198
+ if (!isNonEmptyString(db[k])) errors.push(`${CONFIG_KEY}.db.${k}: expected a non-empty string`);
199
+ }
200
+ }
201
+ }
202
+
203
+ const dk = raw.docker;
204
+ if (dk !== undefined) {
205
+ if (!isPlainObject(dk)) errors.push(`${CONFIG_KEY}.docker: expected an object`);
206
+ else expect(`${CONFIG_KEY}.docker.preUp`, dk.preUp, (v) => v === null || isString(v), 'a shell command or null');
207
+ }
208
+
209
+ const i18n = raw.i18n;
210
+ if (i18n !== undefined) {
211
+ if (!isPlainObject(i18n)) errors.push(`${CONFIG_KEY}.i18n: expected an object`);
212
+ else {
213
+ expect(`${CONFIG_KEY}.i18n.dir`, i18n.dir, isNonEmptyString, 'a directory path');
214
+ expect(`${CONFIG_KEY}.i18n.languages`, i18n.languages, isStringArray, 'an array of language codes');
215
+ }
216
+ }
217
+
218
+ return errors;
219
+ }
220
+
221
+ /**
222
+ * Apply defaults. `rootName` is the sanitized root package name (or directory name),
223
+ * used for the worktree base dir, the slot-0 compose project and dev image names.
224
+ * Sections a project has not declared resolve to `null` (worktree, testCases, db) so
225
+ * commands can tell "not configured" from "configured with defaults".
226
+ */
227
+ export function resolveConfig(raw = {}, { rootName }) {
228
+ const wt = raw.worktree;
229
+ const worktree =
230
+ wt === undefined
231
+ ? null
232
+ : {
233
+ baseDir: wt.baseDir ?? `../${rootName}-worktrees`,
234
+ maxSlot: wt.maxSlot ?? DEFAULT_MAX_SLOT,
235
+ projectName: wt.projectName ?? rootName,
236
+ ports: { ...(wt.ports ?? {}) },
237
+ profiles: {
238
+ default: [...(wt.profiles?.default ?? [])],
239
+ required: [...(wt.profiles?.required ?? [])],
240
+ },
241
+ seeds: { service: wt.seeds?.service ?? null, scripts: [...(wt.seeds?.scripts ?? [])] },
242
+ ready: wt.ready?.url ? { url: wt.ready.url, timeoutSeconds: wt.ready.timeoutSeconds ?? 600 } : null,
243
+ env: { ...(wt.env ?? {}) },
244
+ };
245
+
246
+ const tr = raw.tracker ?? { kind: 'none' };
247
+ const tracker =
248
+ tr.kind === 'jira'
249
+ ? { kind: 'jira', project: tr.project, baseUrl: tr.baseUrl ?? null }
250
+ : tr.kind === 'github'
251
+ ? { kind: 'github', prefix: tr.prefix ?? DEFAULT_GITHUB_PREFIX }
252
+ : { kind: 'none' };
253
+
254
+ const cm = raw.commits ?? {};
255
+ const commits = {
256
+ types: [...(cm.types ?? DEFAULT_COMMIT_TYPES)],
257
+ extraScopes: [...(cm.extraScopes ?? DEFAULT_EXTRA_SCOPES)],
258
+ requireSigned: cm.requireSigned ?? true,
259
+ exemptAuthors: [...(cm.exemptAuthors ?? DEFAULT_EXEMPT_AUTHORS)],
260
+ docsUrl: cm.docsUrl ?? null,
261
+ };
262
+
263
+ const ci = {
264
+ checks: (raw.ci?.checks ?? []).map((c) => ({ name: c.name, paths: [...c.paths], run: c.run })),
265
+ affected: {
266
+ contentOnly: [...(raw.ci?.affected?.contentOnly ?? [])],
267
+ adopted: { ...(raw.ci?.affected?.adopted ?? {}) },
268
+ },
269
+ };
270
+
271
+ const tc = raw.testCases;
272
+ const testCases = tc === undefined ? null : { dir: tc.dir ?? 'docs/testing', languages: [...(tc.languages ?? ['en', 'nl'])] };
273
+
274
+ const db = raw.db ? { service: raw.db.service, user: raw.db.user, name: raw.db.name } : null;
275
+ const docker = { preUp: typeof raw.docker?.preUp === 'string' && raw.docker.preUp.trim() ? raw.docker.preUp.trim() : null };
276
+ const i18n = { dir: raw.i18n?.dir ?? 'public/assets/i18n', languages: [...(raw.i18n?.languages ?? ['en', 'nl'])] };
277
+
278
+ return { worktree, tracker, commits, ci, testCases, db, docker, i18n };
279
+ }
280
+
281
+ /**
282
+ * Load, validate and resolve the config of the repo containing `cwd` (or of an explicit
283
+ * `root`). Never throws for a missing block — `raw` is `{}` and every section takes defaults.
284
+ */
285
+ export function loadConfig({ cwd = process.cwd(), root: explicitRoot } = {}) {
286
+ const root = explicitRoot ?? findRepoRoot(cwd);
287
+ let pkg = {};
288
+ try {
289
+ pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
290
+ } catch {
291
+ pkg = {};
292
+ }
293
+ const raw = pkg[CONFIG_KEY] ?? {};
294
+ const rootName = sanitizeName(pkg.name || basename(root));
295
+ const errors = validateConfig(pkg[CONFIG_KEY]);
296
+ const config = errors.length === 0 ? resolveConfig(raw, { rootName }) : null;
297
+ return { root, rootName, pkg, raw, errors, config };
298
+ }
299
+
300
+ /** `loadConfig` that throws an actionable error when the block is invalid. */
301
+ export function requireConfig(opts) {
302
+ const loaded = loadConfig(opts);
303
+ if (loaded.errors.length > 0) {
304
+ throw new Error(`Invalid "${CONFIG_KEY}" block in ${join(loaded.root, 'package.json')}:\n - ${loaded.errors.join('\n - ')}`);
305
+ }
306
+ return loaded;
307
+ }
308
+
309
+ /** Sections that must be present for a feature; throws with the exact key to add. */
310
+ export function requireSection(loaded, section) {
311
+ const value = loaded.config?.[section];
312
+ if (value === null || value === undefined) {
313
+ throw new Error(`Missing "${CONFIG_KEY}.${section}" in ${join(loaded.root, 'package.json')} — run \`hassan-devkit init\` to scaffold it.`);
314
+ }
315
+ return value;
316
+ }