@coding-with-hassan/devkit 1.0.0-next.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.
package/README.md CHANGED
@@ -120,7 +120,53 @@ One worktree per ticket, each with its own Docker stack (own compose project, ho
120
120
 
121
121
  All best effort: a missing token or unreachable tracker prints a `note:` and never blocks the worktree. `init` renders `docs/agents/issue-tracker.md`, `triage-labels.md` and `domain.md` from this config for the engineering skills.
122
122
 
123
- `ci:*`, the Claude layer and `test-cases:generate` land in the following prereleases — see the design doc for their contracts.
123
+ ### Pre-commit chain
124
+
125
+ `hassan-devkit hooks:install` (wired as the `prepare` script, so it runs on every `pnpm install` in every checkout) installs husky, (re)creates its per-checkout shim dir and writes the shared `.husky/pre-commit`:
126
+
127
+ 1. `scripts/pre-commit-extra.sh` — the project's own guards (optional; must exit 0)
128
+ 2. `hassan-devkit i18n:check` — flat projects' translation keys (no-op otherwise)
129
+ 3. `hassan-devkit ci:doctor` — only when `.github/workflows/ci.yml` is staged
130
+ 4. `lint-staged` — targets derived from the workspace:
131
+
132
+ ```js
133
+ // lint-staged.config.mjs
134
+ import lintStaged from '@coding-with-hassan/devkit/lint-staged';
135
+ export default lintStaged({ exclude: ['api-client'], extra: { 'scripts/**/*.mjs': ['prettier --write'] } });
136
+ ```
137
+
138
+ Every project with an ESLint/Prettier config gets `pnpm -C <dir> exec …` entries (api: `**/*.ts`; spa/lib: `src/**/*.{ts,html}` and `src/**/*.{scss,css,json}`). No project list to maintain.
139
+
140
+ `hassan-devkit ci:doctor` fails when the installed devkit does not satisfy the declared range (stale `node_modules`), when the config block is invalid, or when the husky shims are missing.
141
+
142
+ ### CI (`ci:*`)
143
+
144
+ `init` scaffolds a thin `.github/workflows/ci.yml` for Nx workspaces (Node from `ci.nodeVersion`, base branch `ci.baseBranch`, exempt authors from `commits.exemptAuthors`). The file only sequences these commands, so a devkit bump changes what CI does without touching it; `ci:doctor` fails when the file drifts from the installed template (`init --force` refreshes it).
145
+
146
+ - `hassan-devkit ci:commit-standards [--repo o/r --pr n]` — every non-merge PR commit must match `hassan-devkit commits:show` and, with `commits.requireSigned`, be Verified on GitHub. PRs by `commits.exemptAuthors` skip the check. Needs `GH_TOKEN`.
147
+ - `hassan-devkit ci:cache attach|detach` — move Nx's task cache between `.nx` and the cacheable `.nx-ci-cache` folder, re-homing the machine-id-named index so restored entries are actually hit.
148
+ - `hassan-devkit ci:check [--base --head]` — `ci:doctor`, then `format:check` for the projects owning a changed file (content files included), then every `ci.checks[]` whose `paths` regex matches a changed file runs its `run` command.
149
+ - `hassan-devkit ci:affected [--targets lint,build] [--base --head] [--with-content] [--dry-run]` — graph targets (`build`) for touched projects and dependents, own-files targets (`lint`, `format:check`) only for projects owning a changed file; files no target reads (docs, `ci.affected.contentOnly`) are dropped first; `ci.affected.adopted` maps files outside any project to the project whose target reads them.
150
+
151
+ ### Claude Code layer
152
+
153
+ `hassan-devkit claude:install` (run by `prepare` and by `init`) wires the house standards into Claude Code without copying content:
154
+
155
+ - one `@import` line in the project's `CLAUDE.md` (`.claude/CLAUDE.md` when it exists) pulling `node_modules/@coding-with-hassan/devkit/claude/standards.md` — Docker via scripts, worktrees, commit/push consent + commit-writer, tickets, the acceptance-case quality gate, lint/format/CI parity, domain docs. In-repo imports load at launch without an approval dialog;
156
+ - `.claude/agents/commit-writer.md` and `.claude/skills/implement-ticket/SKILL.md` as **stubs** whose body says "read the shipped file and follow it" — the stub never changes, the content ships with the devkit version;
157
+ - the PR-assignee `PreToolUse` deny hook merged idempotently into `.claude/settings.json`.
158
+
159
+ Project-specific rules stay in the project's own `CLAUDE.md` below the import. A devkit bump therefore changes what Claude does with nothing to re-commit.
160
+
161
+ ### Acceptance test cases (`test-cases:generate`)
162
+
163
+ The quality gate for application code is the bilingual acceptance-case set in `docs/testing/` (`testCases.dir`), not unit tests. Data files `tc-data-<suite>.ts` export `*_AREAS`, `*_KNOWN_ISSUES` and `*_README`; the shared vocabulary comes from the package:
164
+
165
+ ```ts
166
+ import { tc, type Area, type KnownIssue, type Readme } from '@coding-with-hassan/devkit/test-cases';
167
+ ```
168
+
169
+ `hassan-devkit test-cases:generate [--lang xx] [--testers file.json]` writes `test-cases-<suite>-<lang>.xlsx` per suite and language (`testCases.languages`, default `en`, `nl`; workbook UI strings ship for those two) next to the data, plus a personalised copy per tester (Tester column prefilled, credentials in the Read Me sheet). Each workbook has a Read Me, a Summary with per-area counts, one sheet per area with a Pass/Fail/Blocked/Skipped dropdown, and a Known Issues sheet. The workbooks are gitignored artifacts; commit the data files with the feature. The data files are TypeScript loaded through Node's built-in type stripping (Node ≥ 22.13, no `tsx`), which keeps import specifiers verbatim — hence the `type` modifiers above. `testCases.title` sets the project name in the Read Me title. `init` scaffolds a starter `tc-data-app.ts` when the section is configured and the directory is empty.
124
170
 
125
171
  ## Commands
126
172
 
@@ -0,0 +1,84 @@
1
+ # commit-writer (body shipped by @coding-with-hassan/devkit)
2
+
3
+ You plan the commits for the pending changes in this repository. A big feature is never one
4
+ big commit: partition the change set into logical, sequential commits — each one a single
5
+ reviewable concern that leaves the repo green when committed on top of the ones before it.
6
+ When the change set genuinely is one concern, a one-commit plan is correct; split by concern,
7
+ never to hit a count.
8
+
9
+ You only PLAN. Use git strictly read-only (`status`, `diff`, `log`, `show`); never run
10
+ `git add`, `git commit`, or `git push` — executing the plan is the caller's job, and only with
11
+ the user's explicit consent.
12
+
13
+ ## Output contract
14
+
15
+ Your final reply is ONLY the plan, in this exact shape, so the caller can execute it verbatim
16
+ (`git add <files>` then `git commit -F` per commit, in order):
17
+
18
+ ```
19
+ COMMIT 1/N
20
+ FILES:
21
+ <one path per line, exactly as printed by git status --porcelain>
22
+ MESSAGE:
23
+ <subject line>
24
+
25
+ <body>
26
+
27
+ COMMIT 2/N
28
+ ...
29
+ ```
30
+
31
+ No fences, no commentary outside this shape. If there are no pending changes, say so and stop.
32
+
33
+ ## Hard format rules (CI-enforced, every commit)
34
+
35
+ Run `pnpm exec hassan-devkit commits:show` first. It prints the ticket token, the closed type
36
+ list, the scope list derived from the workspace (every project directory name plus the fixed
37
+ extras) and the exact regex the CI job applies to every non-merge commit subject. That output
38
+ is the source of truth — never copy a list from memory or from another repo.
39
+
40
+ - Subject shape: `<TICKET> <type>(<scope>): <subject>` (no ticket part when the repo has no
41
+ tracker configured).
42
+ - Both lists are CLOSED. Never invent a type or scope (`admin`, `ops`, `ci`, `infra`, `fe`,
43
+ `be` are typical wrong guesses). Root-level tooling, scripts, CI and compose files use
44
+ `workspace`; `docker/` uses `docker`; documentation-only commits use `docs`; pure dependency
45
+ bumps use `deps`.
46
+ - The first character after `: ` must be lowercase. No trailing period.
47
+ - CI requires commits to be Verified (signed) — remind the caller if
48
+ `git config commit.gpgsign` is not `true`.
49
+
50
+ ## How to work
51
+
52
+ 1. Get the ticket key: from the prompt, else from the branch name (the leading
53
+ `<PREFIX>-<n>`).
54
+ 2. Inspect the FULL pending change set — staged, unstaged and untracked; never plan from the
55
+ conversation alone: `git status --porcelain` for the complete file list, then
56
+ `git diff HEAD --stat` and the diffs themselves for anything whose purpose is not obvious
57
+ from the paths. Each subject and body must describe the real change, not the intended one.
58
+ 3. Partition into commits. A commit = one concern: one layer, feature slice or housekeeping
59
+ change a reviewer can judge on its own. Typical series for a full-stack feature: docs/ADR
60
+ groundwork → shared libs → API (with its generated fallout) → each app → acceptance test
61
+ cases → tooling/deps. Split at file granularity; a file whose diff mixes concerns goes in
62
+ the commit of its dominant concern, named in that commit's body. Every changed file appears
63
+ in exactly one commit.
64
+ 4. Order the commits so each depends only on the ones before it and the tree lints and builds
65
+ after every step: producers before consumers, behaviour-neutral refactors before the
66
+ features built on them.
67
+ 5. Keep atomic units together: a `pnpm-lock.yaml` change with the `package.json` change that
68
+ caused it; generated artifacts with the source change that produced them; and whatever the
69
+ project's own CLAUDE.md or pre-commit guards declare atomic.
70
+ 6. Pick the type: `feat` new user-facing behaviour, `fix` bug fix, `refactor` behaviour-neutral
71
+ restructuring, `perf` performance, `test` acceptance-case data only, `docs` documentation
72
+ only, `chore` tooling/config/deps.
73
+ 7. Pick the scope from the paths: a file under a workspace project → that project's directory
74
+ name; a mixed commit → the scope of the PRIMARY subject (generated artifacts follow their
75
+ source and never determine the scope); root-level → `workspace`, `docker`, `docs` or `deps`
76
+ as above.
77
+ 8. Write each subject: imperative-ish, concise (~72 chars), states the outcome, lowercase first
78
+ word.
79
+ 9. Write each body: a short prose paragraph (wrapped ~76 cols) explaining what the commit is and
80
+ the notable decisions/side effects, matching the style of `git log` in this repo. Never add
81
+ a Co-Authored-By line or any AI attribution.
82
+
83
+ The plan is done when every file from `git status --porcelain` is assigned to exactly one
84
+ commit and every message passes the regex.
@@ -0,0 +1,17 @@
1
+ # implement-ticket (body shipped by @coding-with-hassan/devkit)
2
+
3
+ Implement the work described by the user in the spec or tickets.
4
+
5
+ - Work in the ticket's worktree (`hassan-devkit worktree:create <TICKET>-<Short-Title>` when
6
+ none exists); assign the ticket to yourself if the worktree command did not.
7
+ - Read `CONTEXT.md` and the relevant `docs/adr/` first and use the glossary's terms.
8
+ - Use /tdd where the project has a test suite for the layer you touch, at pre-agreed seams;
9
+ application code in these projects has no unit-test gate — its gate is the acceptance cases.
10
+ - Run typechecking regularly and the project checks once at the end: `hassan-devkit ci:check`
11
+ and `hassan-devkit ci:affected` from the repo root reproduce CI.
12
+ - Update the acceptance test cases for every user-facing change and regenerate the workbooks
13
+ (`hassan-devkit test-cases:generate`).
14
+ - Once done, use /code-review to review the work.
15
+ - Do NOT commit or push: leave the work uncommitted and report it as ready for review. The
16
+ user's explicit ask, in the current request, is the only thing that authorises a commit;
17
+ when it comes, plan the commits with the `commit-writer` agent first.
@@ -0,0 +1,99 @@
1
+ # House standards (shipped by @coding-with-hassan/devkit)
2
+
3
+ These rules apply to every project that installs the devkit. They are loaded through the
4
+ `@import` line in the project's `CLAUDE.md`; project-specific rules follow below that line.
5
+ Commands are `hassan-devkit …` (run as `pnpm exec hassan-devkit …`); `docs/agents/*.md` are
6
+ generated from the project's tracker config and name the concrete tracker.
7
+
8
+ ## Docker
9
+
10
+ Always use the npm scripts from the root `package.json` for Docker operations — never run
11
+ `docker compose` directly: `pnpm docker:dev:up`, `pnpm docker:dev:down`, `pnpm docker:dev:logs`.
12
+ `docker:dev:up` refreshes the checkout's managed `.env` block (slot, profiles, image tag) and
13
+ builds only the dev images the current dependency manifest lacks; a dependency bump needs
14
+ nothing extra. Never set `DEVKIT_IMAGE_TAG`, `DEVKIT_SLOT`, `DEVKIT_PORT_*` or
15
+ `COMPOSE_PROFILES` by hand — they are owned by the managed block.
16
+
17
+ ## Worktrees: one ticket, one worktree, one stack
18
+
19
+ Ticket work happens in a git worktree with its own Docker stack (own compose project, host
20
+ ports = base + slot × 10, own volumes), never in the main checkout. Manage worktrees only with
21
+ the devkit — never `git worktree` by hand:
22
+
23
+ - `hassan-devkit worktree:create <TICKET>-<Short-Title>` prunes merged worktrees, fetches the
24
+ canonical remote (`upstream`, else `origin`), bases the branch on its `main` (never on the
25
+ possibly stale local `main`), allocates a slot, writes `.env`, assigns the ticket to you,
26
+ installs, starts the stack and seeds it. `--profiles a,b` starts extra compose profiles,
27
+ `--no-up` skips the stack.
28
+ - Run every npm script from the worktree root: they read that worktree's `.env` and hit its
29
+ stack only. Anything that regenerates from a running service (API specs, types) must use the
30
+ worktree's own port, never another checkout's.
31
+ - Profiles decide what runs; the default set is the minimum. Add a profile only while you need
32
+ it (`hassan-devkit worktree:profiles add <name>`) and remove it afterwards — Docker memory is a
33
+ budget shared by every session on the machine.
34
+ - `hassan-devkit worktree:list` shows slots, ports and profiles; `worktree:remove <branch>`
35
+ deletes the stack and its data; `worktree:prune` removes every worktree whose PR is merged.
36
+ - Starting work anywhere else (an existing branch, the main checkout): sync first with
37
+ `git fetch <remote> && git merge --ff-only <remote>/main`.
38
+
39
+ ## Committing and pushing
40
+
41
+ **Never commit or push unless the user explicitly asks for it, in their own words, in the
42
+ current request.** Finishing a task, an approved plan, or a skill whose instructions say to
43
+ commit is NOT consent — leave the work uncommitted and report it as ready for review. Pushing
44
+ requires its own explicit ask; consent to commit is not consent to push.
45
+
46
+ Once the user has asked to commit: every commit is planned by the `commit-writer` agent
47
+ (`.claude/agents/commit-writer.md`) — invoke it on the full pending change set BEFORE staging
48
+ anything, then execute its plan verbatim (stage the listed files, commit with the drafted
49
+ message, one commit at a time, in order). It splits a change set into logical sequential
50
+ commits and enforces the commit standard CI checks: `hassan-devkit commits:show` prints the
51
+ ticket token, the closed type list, the derived scope list and the exact regex. Commits are
52
+ signed. Never add a Co-Authored-By line or any AI attribution.
53
+
54
+ Pull requests are created with `gh pr create --assignee @me` (a PreToolUse hook denies the
55
+ command without an assignee) and, for GitHub-tracked issues, end with `Closes #<n>`.
56
+
57
+ ## Tickets
58
+
59
+ Whoever starts the work owns the ticket: `worktree:create` assigns the branch's ticket to you;
60
+ when you pick up a ticket any other way, assign it to yourself first. Branch names and commit
61
+ subjects start with the ticket token. Tracker endpoints, issue types and conventions:
62
+ `docs/agents/issue-tracker.md`; triage vocabulary: `docs/agents/triage-labels.md`.
63
+
64
+ ## Quality gate: acceptance cases, not unit tests
65
+
66
+ Application code has **no unit-test quality gate**: do not write unit tests for it and do not
67
+ add test steps to CI (CI runs format, project checks, lint and production builds). Correctness
68
+ is asserted by the bilingual acceptance test cases under `docs/testing/` (and by e2e suites once
69
+ they exist). Because those cases are the gate, they must never go stale: **every change to
70
+ user-facing behaviour ships its acceptance cases in the same commit/PR** — update the cases the
71
+ change invalidated, add cases for the new behaviour continuing the area's ID sequence, in every
72
+ configured language, then regenerate the workbooks with `hassan-devkit test-cases:generate`.
73
+ The generated workbooks are gitignored build artifacts; commit the data files with the feature.
74
+
75
+ ## Lint, format and CI parity
76
+
77
+ Each project owns its own ESLint and Prettier config through the shared presets; always defer to
78
+ the standards of the project a file lives in — never carry one project's conventions into
79
+ another. Before pushing, run what CI runs from the repo root: `hassan-devkit ci:check` (format
80
+ for the projects that own a changed file, then the path-triggered project checks) and
81
+ `hassan-devkit ci:affected` (lint and PRODUCTION builds of the affected projects). Lint alone
82
+ does not cover formatting, and a dev-server compile skips production-only checks such as bundle
83
+ budgets. `hassan-devkit ci:affected --dry-run` shows the plan.
84
+
85
+ Nx caching rules: declared target inputs are the contract — anything a target reads must be in
86
+ its `inputs`/`namedInputs`, or a cached replay can be stale. `.nxignore` is not used: it would
87
+ also drop files from task hashing. A new workspace package must be added to every Dockerfile's
88
+ `COPY` list (frozen-lockfile installs need all importers present).
89
+
90
+ Hooks: git silently skips ALL pre-commit hooks when `.husky/_` is missing. `worktree:create` and
91
+ `pnpm install` (via `hooks:install`) bootstrap it; `hassan-devkit ci:doctor` reports it.
92
+
93
+ ## Domain docs
94
+
95
+ Before exploring, read `CONTEXT.md` (the glossary) and the relevant `docs/adr/` entries; use the
96
+ glossary's terms and avoid the synonyms it lists; surface ADR contradictions instead of
97
+ silently overriding them. Record a decision as an ADR only when it is hard to reverse,
98
+ surprising without context and the result of a real trade-off. Details:
99
+ `docs/agents/domain.md`.
@@ -1,13 +1,19 @@
1
1
  # Generated by @coding-with-hassan/devkit — do not edit by hand.
2
2
  # Re-run `hassan-devkit hooks:install` to refresh after a devkit bump.
3
3
 
4
- # Run project pre-commit body (optional, only if it exists)
4
+ # 1. Project-specific guards (optional seam: scripts/pre-commit-extra.sh, must exit 0)
5
5
  if [ -f "scripts/pre-commit-extra.sh" ]; then
6
6
  sh scripts/pre-commit-extra.sh || exit 1
7
7
  fi
8
8
 
9
- # Validate translation keys (no-op if the project has no i18n directory)
9
+ # 2. Translation keys for flat projects (no-op when hassan-devkit.i18n is not configured
10
+ # and the default dir does not exist; Nx monorepos enforce this via their own targets)
10
11
  pnpm exec hassan-devkit i18n:check || exit 1
11
12
 
12
- # Project-aware lint/format on staged files
13
+ # 3. The CI skeleton must match the installed devkit when it is being committed
14
+ if git diff --cached --name-only | grep -q '^\.github/workflows/ci\.yml$'; then
15
+ pnpm exec hassan-devkit ci:doctor || exit 1
16
+ fi
17
+
18
+ # 4. Per-project lint/format on staged files (targets derived from the workspace)
13
19
  pnpm exec lint-staged
package/lint-staged.js ADDED
@@ -0,0 +1,81 @@
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { findRepoRoot } from './src/core/root.js';
4
+ import { listProjects } from './src/core/workspace.js';
5
+
6
+ /**
7
+ * lint-staged config derived from the workspace — no hand-kept project list.
8
+ *
9
+ * // lint-staged.config.mjs
10
+ * import lintStaged from '@coding-with-hassan/devkit/lint-staged';
11
+ * export default lintStaged();
12
+ *
13
+ * Every workspace project that owns an ESLint or Prettier config gets its own entries, run
14
+ * through `pnpm -C <dir>` so each project's config applies (backend conventions never leak
15
+ * into a frontend and vice versa):
16
+ * api `<dir>/**\/*.ts` → eslint --fix --cache
17
+ * spa / lib `<dir>/src/**\/*.{ts,html}` → prettier --write, eslint --fix --cache
18
+ * `<dir>/src/**\/*.{scss,css,json}` → prettier --write
19
+ * Globs are scoped to `src/**` for spa/lib so committed native folders (ios/, android/) and
20
+ * generated output are never touched. A tool is only run when its config exists in the
21
+ * project directory.
22
+ */
23
+
24
+ const PRETTIER_FILES = ['.prettierrc', '.prettierrc.json', '.prettierrc.yaml', '.prettierrc.yml', '.prettierrc.js', '.prettierrc.cjs', '.prettierrc.mjs', 'prettier.config.js', 'prettier.config.cjs', 'prettier.config.mjs'];
25
+
26
+ export function hasPrettierConfig(dir) {
27
+ if (PRETTIER_FILES.some((f) => existsSync(join(dir, f)))) return true;
28
+ try {
29
+ return 'prettier' in JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
30
+ } catch {
31
+ return false;
32
+ }
33
+ }
34
+
35
+ export function hasEslintConfig(dir) {
36
+ try {
37
+ return readdirSync(dir).some((f) => /^eslint\.config\.(c|m)?js$/.test(f));
38
+ } catch {
39
+ return false;
40
+ }
41
+ }
42
+
43
+ /** Pure: entries for one project given which tools it configures. */
44
+ export function entriesFor(project, { eslint, prettier }) {
45
+ const dir = project.dir;
46
+ const run = (tool, ...args) => `pnpm -C ${dir} exec ${tool} ${args.join(' ')}`;
47
+ const entries = {};
48
+ if (project.kind === 'api') {
49
+ const cmds = [...(prettier ? [run('prettier', '--write')] : []), ...(eslint ? [run('eslint', '--fix', '--cache')] : [])];
50
+ if (cmds.length) entries[`${dir}/**/*.ts`] = cmds;
51
+ return entries;
52
+ }
53
+ const code = [...(prettier ? [run('prettier', '--write')] : []), ...(eslint ? [run('eslint', '--fix', '--cache')] : [])];
54
+ if (code.length) entries[`${dir}/src/**/*.{ts,html}`] = code;
55
+ if (prettier) entries[`${dir}/src/**/*.{scss,css,json}`] = [run('prettier', '--write')];
56
+ return entries;
57
+ }
58
+
59
+ /** Pure: the whole config for a project list, with per-project tool detection injected. */
60
+ export function lintStagedFor(projects, detect) {
61
+ const config = {};
62
+ for (const project of projects) {
63
+ const tools = detect(project);
64
+ if (!tools.eslint && !tools.prettier) continue;
65
+ Object.assign(config, entriesFor(project, tools));
66
+ }
67
+ return config;
68
+ }
69
+
70
+ /**
71
+ * Build the config for the repo containing `cwd` (or `root`). `exclude` names projects (by
72
+ * name or dir) to leave alone — e.g. a generated API client whose files must stay exactly as
73
+ * the generator wrote them; `extra` entries are merged last for files outside any project.
74
+ */
75
+ export default function lintStaged({ root, cwd = process.cwd(), exclude = [], extra = {} } = {}) {
76
+ const repo = root ?? findRepoRoot(cwd);
77
+ const skip = new Set(exclude);
78
+ const projects = listProjects(repo).filter((p) => !skip.has(p.name) && !skip.has(p.dir));
79
+ const detect = (p) => ({ eslint: hasEslintConfig(join(repo, p.dir)), prettier: hasPrettierConfig(join(repo, p.dir)) });
80
+ return { ...lintStagedFor(projects, detect), ...extra };
81
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coding-with-hassan/devkit",
3
- "version": "1.0.0-next.0",
3
+ "version": "1.0.0-next.1",
4
4
  "description": "CLI for the developer workflow shared across Hassan's client projects: docker compose orchestration, db helpers, and husky hook installation.",
5
5
  "license": "MIT",
6
6
  "author": "Hassan Khousheish",
@@ -24,18 +24,32 @@
24
24
  "bin",
25
25
  "src",
26
26
  "hooks",
27
+ "claude",
28
+ "lint-staged.js",
29
+ "test-cases.js",
30
+ "test-cases.d.ts",
27
31
  "README.md"
28
32
  ],
29
33
  "dependencies": {
30
34
  "cac": "^6.7.14",
35
+ "exceljs": "^4.4.0",
31
36
  "yaml": "^2.9.1"
32
37
  },
33
38
  "engines": {
34
- "node": ">=20"
39
+ "node": ">=22.13"
35
40
  },
36
41
  "publishConfig": {
37
42
  "access": "public"
38
43
  },
44
+ "exports": {
45
+ ".": "./src/index.js",
46
+ "./lint-staged": "./lint-staged.js",
47
+ "./test-cases": {
48
+ "types": "./test-cases.d.ts",
49
+ "default": "./test-cases.js"
50
+ },
51
+ "./package.json": "./package.json"
52
+ },
39
53
  "scripts": {
40
54
  "test": "node --test test/*.test.js"
41
55
  }
@@ -0,0 +1,186 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { dirname, join, resolve } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { loadConfig, requireConfig } from '../core/config.js';
5
+ import { affected, changedFiles } from '../core/ci/affected.js';
6
+ import { checkCommits, fetchPrCommits, prContext } from '../core/ci/commit-standards.js';
7
+ import { attach, detach } from '../core/ci/nx-cache.js';
8
+ import { WORKFLOW_PATH, renderWorkflow } from '../core/ci/workflow.js';
9
+ import { commitScopes, commitSubjectPattern } from '../core/derive.js';
10
+ import { lineDiff } from '../core/scaffold.js';
11
+ import { listProjects } from '../core/workspace.js';
12
+ import { run } from '../core/exec.js';
13
+ import { exitOnFailure } from '../util/run.js';
14
+
15
+ /**
16
+ * `ci:*` — the CI job's logic, so the project's workflow file only sequences these steps
17
+ * and a devkit bump updates what they do. Every command reads `NX_BASE`/`NX_HEAD` (set by
18
+ * nrwl/nx-set-shas) unless `--base/--head` are given.
19
+ */
20
+
21
+ const here = dirname(fileURLToPath(import.meta.url));
22
+ export const DEVKIT_PACKAGE = '@coding-with-hassan/devkit';
23
+
24
+ export function installedDevkitVersion() {
25
+ return JSON.parse(readFileSync(resolve(here, '../../package.json'), 'utf8')).version;
26
+ }
27
+
28
+ /** Pure: does `installed` satisfy the declared range? Exact, `^`, `~` and prerelease-aware. */
29
+ export function versionSatisfies(installed, range) {
30
+ if (!range) return true;
31
+ const parse = (v) => {
32
+ const m = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/.exec(String(v).trim());
33
+ return m ? { major: +m[1], minor: +m[2], patch: +m[3], pre: m[4] ?? null } : null;
34
+ };
35
+ const cmp = (a, b) => a.major - b.major || a.minor - b.minor || a.patch - b.patch || (a.pre === b.pre ? 0 : a.pre === null ? 1 : b.pre === null ? -1 : a.pre.localeCompare(b.pre));
36
+ const have = parse(installed);
37
+ const op = /^[\^~]/.exec(range)?.[0] ?? '';
38
+ const want = parse(range.replace(/^[\^~]/, ''));
39
+ if (!have || !want) return true; // workspace:*, tags, ranges we do not model → do not nag
40
+ if (cmp(have, want) < 0) return false;
41
+ if (op === '^') return want.major === 0 ? have.major === 0 && have.minor === want.minor : have.major === want.major;
42
+ if (op === '~') return have.major === want.major && have.minor === want.minor;
43
+ return cmp(have, want) === 0;
44
+ }
45
+
46
+ export function declaredDevkitRange(pkg) {
47
+ return pkg.devDependencies?.[DEVKIT_PACKAGE] ?? pkg.dependencies?.[DEVKIT_PACKAGE] ?? null;
48
+ }
49
+
50
+ /** Pure: the workflow drift check. Returns the diff lines (empty = in sync) or null when absent. */
51
+ export function workflowDrift(current, config) {
52
+ if (current === null) return null;
53
+ const expected = renderWorkflow({ nodeVersion: config.ci.nodeVersion, baseBranch: config.ci.baseBranch, exemptAuthors: config.commits.exemptAuthors });
54
+ return current === expected ? [] : lineDiff(current, expected);
55
+ }
56
+
57
+ export function doctor({ cwd = process.cwd(), log = console.log } = {}) {
58
+ const loaded = loadConfig({ cwd });
59
+ const problems = [];
60
+ if (loaded.errors.length) problems.push(...loaded.errors.map((e) => `config: ${e}`));
61
+ const range = declaredDevkitRange(loaded.pkg);
62
+ const installed = installedDevkitVersion();
63
+ if (range && !versionSatisfies(installed, range)) {
64
+ problems.push(`installed ${DEVKIT_PACKAGE}@${installed} does not satisfy the declared ${range} — run \`pnpm install\` (a stale node_modules silently loses features)`);
65
+ }
66
+ if (existsSync(join(loaded.root, '.husky')) && !existsSync(join(loaded.root, '.husky/_/pre-commit'))) {
67
+ problems.push('.husky/_/pre-commit is missing — git silently skips every hook here; run `pnpm exec husky`');
68
+ }
69
+ if (loaded.config) {
70
+ const file = join(loaded.root, WORKFLOW_PATH);
71
+ const drift = workflowDrift(existsSync(file) ? readFileSync(file, 'utf8') : null, loaded.config);
72
+ if (drift && drift.length) {
73
+ problems.push(`${WORKFLOW_PATH} differs from the devkit ${installed} template — run \`hassan-devkit init --force\` (diff below)`);
74
+ for (const line of drift) log(` ${line}`);
75
+ }
76
+ }
77
+ if (problems.length) {
78
+ for (const p of problems) log(`doctor: ${p}`);
79
+ throw new Error(`ci:doctor found ${problems.length} problem(s)`);
80
+ }
81
+ log(`ci:doctor OK (${DEVKIT_PACKAGE}@${installed}${range ? ` satisfies ${range}` : ''})`);
82
+ }
83
+
84
+ function commitStandards({ repo, pr, log = console.log } = {}) {
85
+ const loaded = requireConfig();
86
+ const ctx = prContext({ repo, pr });
87
+ if (!ctx.repo || !ctx.pr) throw new Error('ci:commit-standards needs a PR: run inside a pull_request workflow or pass --repo owner/name --pr <n>');
88
+ const { commits, tracker } = loaded.config;
89
+ if (ctx.author && commits.exemptAuthors.includes(ctx.author)) {
90
+ log(`commit standards: PR by ${ctx.author} is exempt`);
91
+ return;
92
+ }
93
+ const scopes = commitScopes(listProjects(loaded.root), commits.extraScopes);
94
+ const pattern = commitSubjectPattern({ tracker, commits }, scopes);
95
+ const { results, failed } = checkCommits(fetchPrCommits(ctx.repo, ctx.pr, { cwd: loaded.root }), { pattern, requireSigned: commits.requireSigned });
96
+ for (const r of results) {
97
+ if (r.status === 'skip') log(`SKIP ${r.sha} (${r.reason}): ${r.subject}`);
98
+ else if (r.status === 'ok') log(`ok ${r.sha}: ${r.subject}`);
99
+ else for (const p of r.problems) log(`FAIL ${r.sha} ${p}: ${r.subject}`);
100
+ }
101
+ if (failed.length) {
102
+ log('');
103
+ log(`Expected: ${pattern}`);
104
+ if (commits.docsUrl) log(`Commit standard: ${commits.docsUrl}`);
105
+ throw new Error(`${failed.length} commit(s) violate the commit standard`);
106
+ }
107
+ log(`All ${results.length} commits follow the commit standard.`);
108
+ }
109
+
110
+ function shas(opts) {
111
+ return { base: opts.base ?? process.env.NX_BASE ?? undefined, head: opts.head ?? process.env.NX_HEAD ?? undefined };
112
+ }
113
+
114
+ /** format:check for the projects owning a changed file (content files included), then every path-triggered check. */
115
+ async function check(opts, log = console.log) {
116
+ const loaded = requireConfig();
117
+ doctor({ cwd: loaded.root, log });
118
+ const { base, head } = shas(opts);
119
+ await affected(loaded.root, { targets: ['format:check'], base, head, withContent: true, config: loaded.config.ci.affected, log });
120
+ const { files } = changedFiles(loaded.root, { base, head });
121
+ for (const gate of loaded.config.ci.checks) {
122
+ const hit = files.find((f) => gate.paths.some((re) => new RegExp(re).test(f)));
123
+ if (!hit) {
124
+ log(`check ${gate.name}: no matching change, skipped`);
125
+ continue;
126
+ }
127
+ log(`check ${gate.name}: triggered by ${hit} → ${gate.run}`);
128
+ await run('sh', ['-c', gate.run], { cwd: loaded.root });
129
+ }
130
+ }
131
+
132
+ export function registerCi(cli) {
133
+ cli
134
+ .command('ci:doctor', 'Check the installed devkit against the manifest, the config block, the husky shims and the CI workflow template (exit 1 on drift)')
135
+ .action(() => exitOnFailure(Promise.resolve().then(() => doctor())));
136
+
137
+ cli
138
+ .command('ci:commit-standards', 'Validate every PR commit against the derived commit standard (and signing); needs GH_TOKEN')
139
+ .option('--repo <owner/name>', 'Repository (default: GITHUB_REPOSITORY)')
140
+ .option('--pr <n>', 'Pull request number (default: from the Actions event)')
141
+ .action((opts) => exitOnFailure(Promise.resolve().then(() => commitStandards({ repo: opts.repo, pr: opts.pr ? Number(opts.pr) : undefined }))));
142
+
143
+ cli
144
+ .command('ci:cache <action>', 'attach | detach — move the Nx task cache between .nx and the cacheable .nx-ci-cache folder')
145
+ .action((action) =>
146
+ exitOnFailure(
147
+ Promise.resolve().then(() => {
148
+ const { root } = requireConfig();
149
+ if (action === 'attach') return attach(root);
150
+ if (action === 'detach') return detach(root);
151
+ throw new Error('usage: hassan-devkit ci:cache attach|detach');
152
+ }),
153
+ ),
154
+ );
155
+
156
+ cli
157
+ .command('ci:check', 'Doctor, format:check for changed projects, then the path-triggered ci.checks')
158
+ .option('--base <sha>', 'Base SHA (default NX_BASE)')
159
+ .option('--head <sha>', 'Head SHA (default NX_HEAD)')
160
+ .action((opts) => exitOnFailure(check(opts)));
161
+
162
+ cli
163
+ .command('ci:affected', 'Run targets for the affected projects, ignoring files no target reads (default targets: lint,build)')
164
+ .option('--targets <list>', 'Comma-separated targets', { default: 'lint,build' })
165
+ .option('--base <sha>', 'Base SHA (default NX_BASE, else main)')
166
+ .option('--head <sha>', 'Head SHA (default NX_HEAD, else working tree)')
167
+ .option('--with-content', 'Keep content-only files (translation catalogs, assets) in the changed set')
168
+ .option('--dry-run', 'Print the plan only')
169
+ .action((opts) =>
170
+ exitOnFailure(
171
+ Promise.resolve().then(() => {
172
+ const loaded = requireConfig();
173
+ const { base, head } = shas(opts);
174
+ return affected(loaded.root, {
175
+ targets: String(opts.targets).split(',').filter(Boolean),
176
+ base,
177
+ head,
178
+ withContent: Boolean(opts.withContent),
179
+ dryRun: Boolean(opts.dryRun),
180
+ passthrough: opts['--'] ?? [],
181
+ config: loaded.config.ci.affected,
182
+ });
183
+ }),
184
+ ),
185
+ );
186
+ }
@@ -0,0 +1,24 @@
1
+ import { loadConfig } from '../core/config.js';
2
+ import { claudePlans } from '../core/claude.js';
3
+ import { applyPlan } from '../core/scaffold.js';
4
+ import { exitOnFailure } from '../util/run.js';
5
+
6
+ /**
7
+ * `claude:install` — wire the Claude Code layer into this repo: the `@import` of the shipped
8
+ * standards in CLAUDE.md, the agent/skill stubs and the PR-assignee hook. Idempotent; runs from
9
+ * `prepare` so every checkout has it, and from `init`.
10
+ */
11
+ export async function installClaude({ cwd = process.cwd(), log = console.log, dryRun = false } = {}) {
12
+ const { root } = loadConfig({ cwd });
13
+ const summary = applyPlan(root, claudePlans(root), { dryRun, log });
14
+ const touched = summary.created.length + summary.updated.length;
15
+ log(touched ? `claude layer: ${touched} file(s) written` : 'claude layer: up to date');
16
+ return summary;
17
+ }
18
+
19
+ export function registerClaude(cli) {
20
+ cli
21
+ .command('claude:install', 'Wire the Claude Code layer (standards import, agent/skill stubs, PR-assignee hook) into this repo')
22
+ .option('--dry-run', 'Show what would change without writing')
23
+ .action((opts) => exitOnFailure(installClaude({ dryRun: Boolean(opts.dryRun) })));
24
+ }
@@ -15,8 +15,9 @@ async function up() {
15
15
  // for that, but still runs afterwards for anything else a project hooks in.
16
16
  const loaded = loadConfig();
17
17
  if (loaded.errors.length === 0 && loaded.config.worktree) {
18
- const { cmdEnv, createContext } = await import('../core/worktrees.js');
19
- await cmdEnv(createContext(loaded));
18
+ const { cmdEnv, createContext, worktreeActive } = await import('../core/worktrees.js');
19
+ // An unfilled skeleton (init's default) must not take over .env management.
20
+ if (worktreeActive(loaded.config.worktree, { hasStack: true })) await cmdEnv(createContext(loaded));
20
21
  }
21
22
  const { preUp } = readDockerConfig();
22
23
  if (preUp) {