@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,37 @@
1
+ import { requireConfig } from '../core/config.js';
2
+ import { cmdCreate, cmdEnv, cmdList, cmdProfiles, cmdPrune, cmdRemove, createContext } from '../core/worktrees.js';
3
+ import { exitOnFailure } from '../util/run.js';
4
+
5
+ // Config loading may throw synchronously; run every action through a promise so the
6
+ // failure handler prints the message (not a stack trace) and exits 1.
7
+ const withCtx = (fn) => exitOnFailure(Promise.resolve().then(() => fn(createContext(requireConfig()))));
8
+
9
+ export function registerWorktree(cli) {
10
+ cli
11
+ .command('worktree:create <branch>', 'Create a worktree + isolated dev stack for a ticket branch off <remote>/main (prunes merged ones first)')
12
+ .option('--profiles <list>', 'Compose profiles to start with, comma-separated (default: worktree.profiles.default)')
13
+ .option('--no-up', 'Create the worktree and .env but do not start the stack')
14
+ .action((branch, opts) => withCtx((ctx) => cmdCreate(ctx, branch, { profiles: opts.profiles ? String(opts.profiles).split(',') : undefined, up: opts.up !== false })));
15
+
16
+ cli
17
+ .command('worktree:env', 'Refresh this checkout\'s managed .env block (slot, profiles, image tag), build missing images')
18
+ .option('--slot <n>', 'Force a slot (1..maxSlot); refuses one another checkout holds')
19
+ .action((opts) => withCtx((ctx) => cmdEnv(ctx, { slot: opts.slot })));
20
+
21
+ cli
22
+ .command('worktree:profiles [action] [...names]', 'list | add <names> | remove <names> — which compose profiles this stack runs')
23
+ .action((action, names) => withCtx((ctx) => cmdProfiles(ctx, action ?? 'list', names ?? [])));
24
+
25
+ cli
26
+ .command('worktree:remove <name>', 'Stack down (volumes deleted unless --keep-data) and remove the worktree; the branch is kept')
27
+ .option('--keep-data', 'Keep the database and other volumes')
28
+ .option('--force', 'Remove even with uncommitted changes')
29
+ .action((name, opts) => withCtx((ctx) => cmdRemove(ctx, name, { keepData: Boolean(opts.keepData), force: Boolean(opts.force) })));
30
+
31
+ cli
32
+ .command('worktree:prune', 'Remove every worktree whose PR is merged (stack, volumes and branch included)')
33
+ .option('--dry-run', 'Only report what would be removed')
34
+ .action((opts) => withCtx((ctx) => cmdPrune(ctx, { dryRun: Boolean(opts.dryRun) })));
35
+
36
+ cli.command('worktree:list', 'List worktrees with their slots, ports, profiles and image tags').action(() => withCtx((ctx) => cmdList(ctx)));
37
+ }
@@ -0,0 +1,225 @@
1
+ /**
2
+ * `docs/agents/*.md` — the repo-local adapters the engineering skills read ("publish to
3
+ * the issue tracker", "apply the AFK-ready label", "read the domain docs"). Rendered from
4
+ * the tracker config so the endpoints and vocabulary can never drift from what
5
+ * `worktree:create` actually does. Regenerated by `hassan-devkit init`.
6
+ */
7
+
8
+ export const GENERATED_HEADER = (source) =>
9
+ `<!-- Generated by @coding-with-hassan/devkit from ${source} — edit package.json and re-run \`hassan-devkit init\`; do not edit by hand. -->\n\n`;
10
+
11
+ export const TRIAGE_LABELS = [
12
+ ['needs-triage', 'Maintainer needs to evaluate this issue'],
13
+ ['needs-info', 'Waiting on reporter for more information'],
14
+ ['ready-for-agent', 'Fully specified, ready for an AFK agent'],
15
+ ['ready-for-human', 'Requires human implementation'],
16
+ ['wontfix', 'Will not be actioned'],
17
+ ];
18
+
19
+ export function renderIssueTrackerDoc(tracker) {
20
+ const head = GENERATED_HEADER('the "hassan-devkit.tracker" config');
21
+ if (tracker.kind === 'jira') return head + jiraDoc(tracker);
22
+ if (tracker.kind === 'github') return head + githubDoc(tracker);
23
+ return (
24
+ head +
25
+ `# Issue tracker: none configured
26
+
27
+ This repo has no issue tracker wired into the devkit (\`hassan-devkit.tracker.kind\` is \`none\`).
28
+ When a skill says "publish to the issue tracker" or "fetch the relevant ticket", ask the user
29
+ where the work is tracked instead of inventing a destination. Branch names carry no ticket
30
+ token and commit subjects need none.
31
+ `
32
+ );
33
+ }
34
+
35
+ function jiraDoc({ project, baseUrl }) {
36
+ const site = baseUrl ?? 'the Jira site from `JIRA_URL` in `~/.config/jira/env`';
37
+ const k = `${project}-<n>`;
38
+ return `# Issue tracker: Jira (${project})
39
+
40
+ Issues and specs for this repo live in the Jira project **${project}** at ${site}. Use the
41
+ Atlassian MCP tools when connected (createJiraIssue, getJiraIssue, searchJiraIssuesUsingJql,
42
+ editJiraIssue, addCommentToJiraIssue, transitionJiraIssue); fall back to the REST API with
43
+ \`curl\` using the credentials in \`~/.config/jira/env\` (JIRA_URL, JIRA_EMAIL, JIRA_API_TOKEN —
44
+ basic auth).
45
+
46
+ ## Issue types
47
+
48
+ - **Task** — technical work (refactors, infra, chores)
49
+ - **New Feature** — net-new functionality
50
+ - **Story** — changes to existing behavior
51
+
52
+ Pick the type by this rule, not by gut feel.
53
+
54
+ ## Conventions
55
+
56
+ - **Branches and commits** carry the ticket key: branch \`${project}-<n>-Short-Title\`, commit
57
+ subject \`${project}-<n> type(scope): …\` (see \`hassan-devkit commits:show\`).
58
+ - **Create an issue**: MCP \`createJiraIssue\` with projectKey \`${project}\`, or \`POST /rest/api/3/issue\`.
59
+ - **Read an issue**: MCP \`getJiraIssue\` (include comments), or
60
+ \`GET /rest/api/3/issue/${k}?expand=renderedFields\` + \`GET /rest/api/3/issue/${k}/comment\`.
61
+ - **List issues**: MCP \`searchJiraIssuesUsingJql\`, e.g.
62
+ \`project = ${project} AND statusCategory != Done ORDER BY created DESC\`.
63
+ - **Comment**: MCP \`addCommentToJiraIssue\`, or \`POST .../comment\`.
64
+ - **Assign — always to the current user when you start a ticket**: whoever starts the work
65
+ owns the issue. \`hassan-devkit worktree:create ${project}-<n>-…\` does it for the branch's
66
+ ticket (alongside the To Do → In Progress transition); for any other way of picking up a
67
+ ticket, do it yourself first: MCP \`editJiraIssue\` on the \`assignee\` field, or
68
+ \`GET /rest/api/3/myself\` for your \`accountId\` and \`PUT /rest/api/3/issue/${k}/assignee\`
69
+ with \`{"accountId": "<id>"}\`. Never leave a ticket you are working on unassigned or
70
+ assigned to someone else.
71
+ - **Labels**: set via \`editJiraIssue\` on the \`labels\` field (add/remove by updating the array).
72
+ - **Close**: MCP \`transitionJiraIssue\` — fetch available transitions first with
73
+ \`getTransitionsForJiraIssue\`; the workflow decides valid target states.
74
+ - **Never try to delete issues** — the Jira Free plan doesn't allow it. Close/transition instead.
75
+
76
+ ## When a skill says "publish to the issue tracker"
77
+
78
+ Create a Jira issue in ${project} (choose the issue type per the table above).
79
+
80
+ ## When a skill says "fetch the relevant ticket"
81
+
82
+ Fetch the ${project} issue with its comments.
83
+
84
+ ## Wayfinding operations
85
+
86
+ The **map** is a single ${project} issue labelled \`wayfinder-map\`; child tickets are issues
87
+ linked to it ("relates to" or parent link where available) with a \`Part of ${k}\` line at the
88
+ top of the description and a \`wayfinder-<type>\` label (\`research\`/\`prototype\`/\`grilling\`/\`task\`).
89
+ Blocking uses Jira's native "is blocked by" issue links. Claim = assign to yourself;
90
+ resolve = comment with the answer, then transition to Done.
91
+ `;
92
+ }
93
+
94
+ function githubDoc({ prefix }) {
95
+ return `# Issue tracker: GitHub Issues
96
+
97
+ Issues and specs for this repo live in GitHub Issues of the **base repository** (the
98
+ \`upstream\` remote in the fork model, else \`origin\`). Use the \`gh\` CLI; it is authenticated on
99
+ this machine.
100
+
101
+ ## Conventions
102
+
103
+ - **Branches and commits** carry the issue as \`${prefix}-<n>\`: branch \`${prefix}-<n>-Short-Title\`,
104
+ commit subject \`${prefix}-<n> type(scope): …\` (see \`hassan-devkit commits:show\`). A leading
105
+ \`#<n>\` is never used in a subject — git treats \`#\` lines as comments in the editor.
106
+ - **PR body** ends with \`Closes #<n>\` so the issue closes on merge.
107
+ - **Create an issue**: \`gh issue create --repo <owner/repo> --title … --body …\`.
108
+ - **Read an issue**: \`gh issue view <n> --comments\`.
109
+ - **List issues**: \`gh issue list --state open\` (add \`--label\` / \`--assignee @me\` as needed).
110
+ - **Comment**: \`gh issue comment <n> --body …\`.
111
+ - **Assign — always to the current user when you start an issue**: whoever starts the work
112
+ owns it. \`hassan-devkit worktree:create ${prefix}-<n>-…\` runs \`gh issue edit <n> --add-assignee @me\`
113
+ for the branch's issue; for any other way of picking up an issue, run that yourself first.
114
+ There is no status field: an open PR is the progress signal.
115
+ - **Labels**: \`gh issue edit <n> --add-label … / --remove-label …\`.
116
+ - **Close**: \`gh issue close <n>\` (or let the PR's \`Closes #<n>\` do it).
117
+
118
+ ## When a skill says "publish to the issue tracker"
119
+
120
+ Create a GitHub issue on the base repository.
121
+
122
+ ## When a skill says "fetch the relevant ticket"
123
+
124
+ Fetch the issue with its comments (\`gh issue view <n> --comments\`).
125
+
126
+ ## Wayfinding operations
127
+
128
+ The **map** is a single issue labelled \`wayfinder-map\`; child issues carry a \`Part of #<map>\`
129
+ line at the top of the body and a \`wayfinder-<type>\` label (\`research\`/\`prototype\`/\`grilling\`/\`task\`).
130
+ Blocking is a \`Blocked by #<n>\` line in the body (GitHub has no native blocking link outside
131
+ Projects). Claim = assign to yourself; resolve = comment with the answer, then close.
132
+ `;
133
+ }
134
+
135
+ export function renderTriageLabelsDoc() {
136
+ const rows = TRIAGE_LABELS.map(([label, meaning]) => `| \`${label}\` | \`${label}\` | ${meaning} |`).join('\n');
137
+ return `${GENERATED_HEADER('the devkit triage vocabulary')}# Triage Labels
138
+
139
+ The skills speak in terms of five canonical triage roles. This file maps those roles to the
140
+ label strings used in this repo's issue tracker — identical by convention, so a label travels
141
+ unchanged between repos.
142
+
143
+ | Label in mattpocock/skills | Label in our tracker | Meaning |
144
+ | --- | --- | --- |
145
+ ${rows}
146
+
147
+ When a skill mentions a role (e.g. "apply the AFK-ready triage label"), use the corresponding
148
+ label string from this table.
149
+ `;
150
+ }
151
+
152
+ export function renderDomainDoc() {
153
+ return `${GENERATED_HEADER('the devkit domain-docs convention')}# Domain Docs
154
+
155
+ How the engineering skills should consume this repo's domain documentation when exploring
156
+ the codebase.
157
+
158
+ ## Before exploring, read these
159
+
160
+ - **\`CONTEXT.md\`** at the repo root, or
161
+ - **\`CONTEXT-MAP.md\`** at the repo root if it exists — it points at one \`CONTEXT.md\` per
162
+ context. Read each one relevant to the topic.
163
+ - **\`docs/adr/\`** — read ADRs that touch the area you're about to work in. In multi-context
164
+ repos, also check \`src/<context>/docs/adr/\` for context-scoped decisions.
165
+
166
+ If any of these files don't exist, **proceed silently**. Don't flag their absence; don't
167
+ suggest creating them upfront. The \`/domain-modeling\` skill (reached via \`/grill-with-docs\`
168
+ and \`/improve-codebase-architecture\`) creates them lazily when terms or decisions actually
169
+ get resolved.
170
+
171
+ ## File structure
172
+
173
+ Single-context repo (most repos):
174
+
175
+ \`\`\`
176
+ /
177
+ ├── CONTEXT.md
178
+ ├── docs/adr/
179
+ │ ├── 0001-event-sourced-orders.md
180
+ │ └── 0002-postgres-for-write-model.md
181
+ └── src/
182
+ \`\`\`
183
+
184
+ Multi-context repo (presence of \`CONTEXT-MAP.md\` at the root):
185
+
186
+ \`\`\`
187
+ /
188
+ ├── CONTEXT-MAP.md
189
+ ├── docs/adr/ ← system-wide decisions
190
+ └── src/
191
+ ├── ordering/
192
+ │ ├── CONTEXT.md
193
+ │ └── docs/adr/ ← context-specific decisions
194
+ └── billing/
195
+ ├── CONTEXT.md
196
+ └── docs/adr/
197
+ \`\`\`
198
+
199
+ ## Use the glossary's vocabulary
200
+
201
+ When your output names a domain concept (in an issue title, a refactor proposal, a
202
+ hypothesis, a test name), use the term as defined in \`CONTEXT.md\`. Don't drift to synonyms
203
+ the glossary explicitly avoids.
204
+
205
+ If the concept you need isn't in the glossary yet, that's a signal — either you're inventing
206
+ language the project doesn't use (reconsider) or there's a real gap (note it for
207
+ \`/domain-modeling\`).
208
+
209
+ ## Flag ADR conflicts
210
+
211
+ If your output contradicts an existing ADR, surface it explicitly rather than silently
212
+ overriding:
213
+
214
+ > _Contradicts ADR-0007 (event-sourced orders) — but worth reopening because…_
215
+ `;
216
+ }
217
+
218
+ /** The three files as `init` plans expect them: `[path, content]`. */
219
+ export function agentsDocs(tracker) {
220
+ return [
221
+ ['docs/agents/issue-tracker.md', renderIssueTrackerDoc(tracker)],
222
+ ['docs/agents/triage-labels.md', renderTriageLabelsDoc()],
223
+ ['docs/agents/domain.md', renderDomainDoc()],
224
+ ];
225
+ }
@@ -0,0 +1,155 @@
1
+ import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import { dirname, join } from 'node:path';
4
+ import { capture, run } from '../exec.js';
5
+
6
+ /**
7
+ * Affected lint/build/format:check that ignores files which cannot change the outcome.
8
+ *
9
+ * `nx affected` maps changed files → projects → dependents and does NOT look at target
10
+ * inputs, so a translation-JSON edit in a shared lib marks every app affected. This wrapper
11
+ * computes the changed-file list itself, drops the files no target reads, and hands the
12
+ * rest to Nx. `.nxignore` would achieve the same affected result but also removes the files
13
+ * from task hashing (a cached build would replay stale content) — hence the filter lives
14
+ * here and the Nx cache is left intact.
15
+ *
16
+ * Two kinds of targets:
17
+ * - graph targets (`build`): the touched projects AND their dependents, exactly as
18
+ * `nx affected` computes them from the filtered file list;
19
+ * - own-files targets (`lint`, `format:check`, …): only projects that own a changed file.
20
+ * Valid as long as no ESLint config uses type-aware rules across projects.
21
+ *
22
+ * Project-specific lists come from `ci.affected` in the config: `contentOnly` (globs of
23
+ * files copied verbatim into outputs — skipped unless `--with-content`) and `adopted`
24
+ * (glob → project that reads files outside every project root).
25
+ */
26
+
27
+ export const DOCS_ONLY = [/\.md$/, /^docs\//];
28
+ export const WORKSPACE_GLOBALS = [/^package\.json$/, /^pnpm-lock\.yaml$/, /^pnpm-workspace\.yaml$/, /^nx\.json$/, /^tsconfig[^/]*\.json$/, /^\.npmrc$/];
29
+ export const GRAPH_TARGETS = new Set(['build']);
30
+
31
+ /** Pure: minimal glob → anchored RegExp (`**`, `*`, `?`). */
32
+ export function globToRegExp(glob) {
33
+ let re = '';
34
+ for (let i = 0; i < glob.length; i++) {
35
+ const ch = glob[i];
36
+ if (ch === '*') {
37
+ if (glob[i + 1] === '*') {
38
+ const slash = glob[i + 2] === '/';
39
+ re += slash ? '(?:.*/)?' : '.*';
40
+ i += slash ? 2 : 1;
41
+ } else re += '[^/]*';
42
+ } else if (ch === '?') re += '[^/]';
43
+ else re += ch.replace(/[.+^${}()|[\]\\]/g, '\\$&');
44
+ }
45
+ return new RegExp(`^${re}$`);
46
+ }
47
+
48
+ /**
49
+ * Pure: split the changed files into ignored / relevant, and map the relevant ones to
50
+ * owning projects, workspace globals or "unowned".
51
+ */
52
+ export function classifyFiles(changed, { roots, contentOnly = [], adopted = {}, withContent = false }) {
53
+ const contentRes = contentOnly.map(globToRegExp);
54
+ const adoptedRes = Object.entries(adopted).map(([glob, project]) => [globToRegExp(glob), project]);
55
+ const ignore = withContent ? DOCS_ONLY : [...DOCS_ONLY, ...contentRes];
56
+ const ignored = [];
57
+ const files = [];
58
+ for (const f of changed) (ignore.some((re) => re.test(f)) ? ignored : files).push(f);
59
+ const touched = new Set();
60
+ const globals = [];
61
+ const unowned = [];
62
+ const byLength = Object.entries(roots).sort((a, b) => b[1].length - a[1].length);
63
+ for (const file of files) {
64
+ const owner = byLength.find(([, root]) => file === root || file.startsWith(`${root}/`))?.[0] ?? adoptedRes.find(([re]) => re.test(file))?.[1];
65
+ if (owner) touched.add(owner);
66
+ else if (WORKSPACE_GLOBALS.some((re) => re.test(file))) globals.push(file);
67
+ else unowned.push(file);
68
+ }
69
+ return { ignored, files, touched, globals, unowned };
70
+ }
71
+
72
+ /** Pure: target → project list, given the Nx answers injected as functions. */
73
+ export function planTargets(targets, { files, touched, globals }, { affectedFor, withTarget }) {
74
+ const plan = new Map();
75
+ for (const target of targets) {
76
+ let projects;
77
+ if (GRAPH_TARGETS.has(target)) projects = affectedFor(files, target);
78
+ else if (globals.length) projects = withTarget(target);
79
+ else projects = withTarget(target).filter((p) => touched.has(p));
80
+ plan.set(target, [...projects].sort());
81
+ }
82
+ return plan;
83
+ }
84
+
85
+ /** Pure: one `nx run-many` per distinct project set keeps lint+build of the same projects in one task graph. */
86
+ export function groupPlan(plan) {
87
+ const groups = new Map();
88
+ for (const [target, projects] of plan) {
89
+ if (projects.length === 0) continue;
90
+ const key = projects.join(',');
91
+ groups.set(key, [...(groups.get(key) ?? []), target]);
92
+ }
93
+ return [...groups].map(([projects, targets]) => ({ projects: projects.split(','), targets }));
94
+ }
95
+
96
+ // ───────────────────────── git / nx side ─────────────────────────
97
+
98
+ const gitLines = (root, args) => capture('git', args, { cwd: root }).split('\n').filter(Boolean);
99
+
100
+ /** Same semantics as `nx affected`: merge-base(base, head)..head, plus the working tree when no head is given. */
101
+ export function changedFiles(root, { base = 'main', head } = {}) {
102
+ const target = head ?? 'HEAD';
103
+ const mergeBase = capture('git', ['merge-base', base, target], { cwd: root, allowFailure: true }) ?? base;
104
+ const files = new Set(gitLines(root, ['diff', '--name-only', mergeBase, target]));
105
+ if (head === undefined) {
106
+ for (const f of gitLines(root, ['diff', '--name-only', 'HEAD'])) files.add(f);
107
+ for (const f of gitLines(root, ['ls-files', '--others', '--exclude-standard'])) files.add(f);
108
+ }
109
+ return { base: mergeBase.slice(0, 12), head: target.slice(0, 12), files: [...files].sort() };
110
+ }
111
+
112
+ const nxBin = (root) => join(root, 'node_modules', '.bin', 'nx');
113
+
114
+ export function projectRoots(root) {
115
+ const dir = mkdtempSync(join(tmpdir(), 'devkit-affected-'));
116
+ const file = join(dir, 'graph.json');
117
+ capture(nxBin(root), ['graph', `--file=${file}`], { cwd: root });
118
+ const { graph } = JSON.parse(readFileSync(file, 'utf8'));
119
+ rmSync(dirname(file), { recursive: true, force: true });
120
+ return Object.fromEntries(Object.entries(graph.nodes).map(([name, node]) => [name, node.data.root]));
121
+ }
122
+
123
+ export function nxAffected(root, files, target) {
124
+ return JSON.parse(capture(nxBin(root), ['show', 'projects', '--affected', '--stdin', '--with-target', target, '--json'], { cwd: root, input: `${files.join('\n')}\n` }));
125
+ }
126
+
127
+ export function nxProjectsWithTarget(root, target) {
128
+ return JSON.parse(capture(nxBin(root), ['show', 'projects', '--with-target', target, '--json'], { cwd: root }));
129
+ }
130
+
131
+ /** The whole command. Returns the plan; runs nx unless `dryRun`. */
132
+ export async function affected(root, { targets = ['lint', 'build'], base, head, withContent = false, dryRun = false, passthrough = [], config, log = console.log }) {
133
+ const { base: b, head: h, files: changed } = changedFiles(root, { base, head });
134
+ const classified = classifyFiles(changed, { roots: changed.length ? projectRoots(root) : {}, contentOnly: config.contentOnly, adopted: config.adopted, withContent });
135
+ log(`affected: ${b}..${h}`);
136
+ log(` ${changed.length} changed file(s), ${classified.ignored.length} ignored, ${classified.files.length} relevant`);
137
+ if (classified.files.length === 0) {
138
+ log(' nothing to run');
139
+ return new Map();
140
+ }
141
+ log(` touched projects: ${[...classified.touched].sort().join(', ') || '(none)'}`);
142
+ if (classified.globals.length) log(` workspace-level change (${classified.globals.join(', ')}) → own-files targets run for all projects`);
143
+ const plan = planTargets(targets, classified, {
144
+ affectedFor: (files, target) => nxAffected(root, files, target),
145
+ withTarget: (target) => nxProjectsWithTarget(root, target),
146
+ });
147
+ for (const [target, projects] of plan) log(` ${target}: ${projects.join(', ') || '(none)'}`);
148
+ if (dryRun) return plan;
149
+ const groups = groupPlan(plan);
150
+ if (groups.length === 0) log(' nothing to run');
151
+ for (const { projects, targets: groupTargets } of groups) {
152
+ await run(nxBin(root), ['run-many', '-t', ...groupTargets, '-p', projects.join(','), ...passthrough], { cwd: root });
153
+ }
154
+ return plan;
155
+ }
@@ -0,0 +1,59 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { capture } from '../exec.js';
3
+
4
+ /**
5
+ * The commit-standards gate: every non-merge commit of a PR must match the derived
6
+ * subject pattern (`hassan-devkit commits:show`) and, when `commits.requireSigned`, be
7
+ * Verified on GitHub. PRs by `commits.exemptAuthors` (renovate) skip the check entirely.
8
+ */
9
+
10
+ /** Pure: evaluate the commits a PR carries. `commits` = [{ sha, subject, verified, parents }]. */
11
+ export function checkCommits(commits, { pattern, requireSigned }) {
12
+ const re = new RegExp(pattern);
13
+ const results = [];
14
+ for (const c of commits) {
15
+ const short = c.sha.slice(0, 7);
16
+ if (c.parents > 1) {
17
+ results.push({ sha: short, status: 'skip', subject: c.subject, reason: 'merge commit' });
18
+ continue;
19
+ }
20
+ const problems = [];
21
+ if (!re.test(c.subject)) problems.push('message does not match the commit standard');
22
+ if (requireSigned && !c.verified) problems.push('not Verified on GitHub (sign with a key registered on your account)');
23
+ results.push({ sha: short, status: problems.length ? 'fail' : 'ok', subject: c.subject, problems });
24
+ }
25
+ return { results, failed: results.filter((r) => r.status === 'fail') };
26
+ }
27
+
28
+ /** Pure: shape `gh api …/pulls/N/commits` JSON into the check's input. */
29
+ export function fromGithubCommits(json) {
30
+ return json.map((c) => ({
31
+ sha: c.sha,
32
+ subject: (c.commit?.message ?? '').split('\n')[0],
33
+ verified: Boolean(c.commit?.verification?.verified),
34
+ parents: (c.parents ?? []).length,
35
+ }));
36
+ }
37
+
38
+ /** PR coordinates from the Actions environment (or explicit overrides). */
39
+ export function prContext({ env = process.env, repo, pr } = {}) {
40
+ let event = null;
41
+ if (env.GITHUB_EVENT_PATH) {
42
+ try {
43
+ event = JSON.parse(readFileSync(env.GITHUB_EVENT_PATH, 'utf8'));
44
+ } catch {
45
+ event = null;
46
+ }
47
+ }
48
+ return {
49
+ repo: repo ?? env.GITHUB_REPOSITORY ?? null,
50
+ pr: pr ?? event?.pull_request?.number ?? (env.PR ? Number(env.PR) : null),
51
+ author: event?.pull_request?.user?.login ?? null,
52
+ };
53
+ }
54
+
55
+ export function fetchPrCommits(repo, pr, { cwd } = {}) {
56
+ const out = capture('gh', ['api', `repos/${repo}/pulls/${pr}/commits`, '--paginate', '--slurp'], { cwd });
57
+ const pages = JSON.parse(out);
58
+ return fromGithubCommits(Array.isArray(pages[0]) ? pages.flat() : pages);
59
+ }
@@ -0,0 +1,74 @@
1
+ import { copyFileSync, cpSync, existsSync, mkdirSync, readdirSync, renameSync, rmSync, statSync } from 'node:fs';
2
+ import { createRequire } from 'node:module';
3
+ import { join } from 'node:path';
4
+
5
+ /**
6
+ * Move Nx's local task cache between the repo and a folder GitHub Actions can cache, so a
7
+ * CI rerun replays every task whose inputs did not change.
8
+ *
9
+ * Nx keeps the cache in two places: the artifacts in `.nx/cache` and a SQLite index in
10
+ * `.nx/workspace-data` named after the machine id (`<machine-id>-v<schema>.db`). Lookups go
11
+ * through the index only — restored artifacts without a matching index are never hit, and
12
+ * every runner has a different machine id, so the index cannot simply be restored in place.
13
+ * `attach` therefore lets Nx's own native binding create this runner's (empty) index, learns
14
+ * its name, and copies the saved index over it. The staging folder lives outside `.nx` so Nx
15
+ * never prunes it; the workflow keys the cache on the lockfile, so an Nx upgrade (new schema)
16
+ * starts fresh.
17
+ */
18
+
19
+ export const STAGE_DIR = '.nx-ci-cache';
20
+ const WORKSPACE_DATA = '.nx/workspace-data';
21
+
22
+ function indexFiles(dir) {
23
+ return existsSync(dir) ? readdirSync(dir).filter((f) => f.endsWith('.db')).map((f) => join(dir, f)) : [];
24
+ }
25
+
26
+ function entryCount(dir) {
27
+ return existsSync(dir) ? readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory()).length : 0;
28
+ }
29
+
30
+ /** Let Nx create this machine's index in `workspaceData` (needs the consumer's `nx`). */
31
+ export function connectNxDb(root, workspaceData) {
32
+ const require = createRequire(join(root, 'package.json'));
33
+ require('nx/src/native').connectToNxDb(workspaceData);
34
+ }
35
+
36
+ export function attach(root, { log = console.log, connect = connectNxDb } = {}) {
37
+ const stage = join(root, STAGE_DIR);
38
+ const workspaceData = join(root, WORKSPACE_DATA);
39
+ if (!existsSync(join(stage, 'index.db')) || !existsSync(join(stage, 'cache'))) {
40
+ log('nx cache: nothing restored, starting cold');
41
+ return false;
42
+ }
43
+ mkdirSync(workspaceData, { recursive: true });
44
+ connect(root, workspaceData);
45
+ const indexes = indexFiles(workspaceData);
46
+ if (indexes.length !== 1) {
47
+ log(`nx cache: expected one index in ${WORKSPACE_DATA}, found ${indexes.length} — starting cold`);
48
+ return false;
49
+ }
50
+ rmSync(join(root, '.nx/cache'), { recursive: true, force: true });
51
+ renameSync(join(stage, 'cache'), join(root, '.nx/cache'));
52
+ copyFileSync(join(stage, 'index.db'), indexes[0]);
53
+ log(`nx cache: attached ${entryCount(join(root, '.nx/cache'))} entries as ${indexes[0]}`);
54
+ return true;
55
+ }
56
+
57
+ export function detach(root, { log = console.log } = {}) {
58
+ const stage = join(root, STAGE_DIR);
59
+ const workspaceData = join(root, WORKSPACE_DATA);
60
+ rmSync(stage, { recursive: true, force: true });
61
+ mkdirSync(stage, { recursive: true });
62
+ if (existsSync(join(root, '.nx/cache'))) renameSync(join(root, '.nx/cache'), join(stage, 'cache'));
63
+ // The most recently written index is the one this run's tasks used.
64
+ const index = indexFiles(workspaceData).sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs)[0];
65
+ if (!index) {
66
+ log('nx cache: no index written by this run, nothing to save');
67
+ return false;
68
+ }
69
+ copyFileSync(index, join(stage, 'index.db'));
70
+ log(`nx cache: staged ${entryCount(join(stage, 'cache'))} entries for saving`);
71
+ return true;
72
+ }
73
+
74
+ export { cpSync };
@@ -0,0 +1,87 @@
1
+ /**
2
+ * The thin CI workflow `init` scaffolds. Every decision lives in the `hassan-devkit ci:*`
3
+ * commands (so a devkit bump updates it); the skeleton below only sequences them, and
4
+ * `ci:doctor` fails when a project's copy drifts from this template.
5
+ */
6
+
7
+ export const WORKFLOW_PATH = '.github/workflows/ci.yml';
8
+
9
+ export function renderWorkflow({ nodeVersion, baseBranch = 'main', exemptAuthors = [] }) {
10
+ const skip = exemptAuthors.map((a) => `github.event.pull_request.user.login != '${a}'`).join(' && ');
11
+ return `# Scaffolded by hassan-devkit init — the steps only sequence \`hassan-devkit ci:*\`, whose
12
+ # logic (commit standard, checks, affected targets, Nx cache) ships with the installed devkit
13
+ # version. \`hassan-devkit ci:doctor\` fails when this file drifts from the devkit's template;
14
+ # re-run \`hassan-devkit init --force\` to refresh it.
15
+ name: CI
16
+
17
+ on:
18
+ pull_request:
19
+ branches: [${baseBranch}]
20
+
21
+ # PRs may come from forks: keep the token read-only and use no repo secrets.
22
+ permissions:
23
+ contents: read
24
+
25
+ concurrency:
26
+ group: ci-\${{ github.ref }}
27
+ cancel-in-progress: true
28
+
29
+ jobs:
30
+ commit-standards:
31
+ name: Commit standards
32
+ runs-on: ubuntu-latest${skip ? `\n if: ${skip}` : ''}
33
+ timeout-minutes: 5
34
+ permissions:
35
+ contents: read
36
+ pull-requests: read
37
+ steps:
38
+ - uses: actions/checkout@v5
39
+ - uses: pnpm/action-setup@v4
40
+ - uses: actions/setup-node@v5
41
+ with:
42
+ node-version: ${nodeVersion}
43
+ cache: pnpm
44
+ - run: pnpm install --frozen-lockfile
45
+ - name: Validate PR commits
46
+ env:
47
+ GH_TOKEN: \${{ github.token }}
48
+ run: pnpm exec hassan-devkit ci:commit-standards
49
+
50
+ ci:
51
+ name: Lint & build (affected)
52
+ runs-on: ubuntu-latest
53
+ timeout-minutes: 25
54
+ steps:
55
+ - uses: actions/checkout@v5
56
+ with:
57
+ fetch-depth: 0
58
+ - uses: pnpm/action-setup@v4
59
+ - uses: actions/setup-node@v5
60
+ with:
61
+ node-version: ${nodeVersion}
62
+ cache: pnpm
63
+ - run: pnpm install --frozen-lockfile
64
+ - name: Restore Nx task cache
65
+ uses: actions/cache/restore@v4
66
+ with:
67
+ path: .nx-ci-cache
68
+ key: nx-cache-\${{ hashFiles('pnpm-lock.yaml') }}-\${{ github.run_id }}-\${{ github.run_attempt }}
69
+ restore-keys: nx-cache-\${{ hashFiles('pnpm-lock.yaml') }}-
70
+ - run: pnpm exec hassan-devkit ci:cache attach
71
+ - uses: nrwl/nx-set-shas@v4
72
+ with:
73
+ main-branch-name: ${baseBranch}
74
+ - name: Doctor, formatting and path-triggered checks
75
+ run: pnpm exec hassan-devkit ci:check --base=$NX_BASE --head=$NX_HEAD
76
+ - name: Lint & build affected projects
77
+ run: pnpm exec hassan-devkit ci:affected --base=$NX_BASE --head=$NX_HEAD
78
+ - if: always()
79
+ run: pnpm exec hassan-devkit ci:cache detach
80
+ - name: Save Nx task cache
81
+ if: always() && hashFiles('.nx-ci-cache/index.db') != ''
82
+ uses: actions/cache/save@v4
83
+ with:
84
+ path: .nx-ci-cache
85
+ key: nx-cache-\${{ hashFiles('pnpm-lock.yaml') }}-\${{ github.run_id }}-\${{ github.run_attempt }}
86
+ `;
87
+ }