@coding-with-hassan/devkit 1.1.0 → 1.3.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.
- package/README.md +7 -4
- package/claude/skills/merge-upstream/SKILL.md +84 -0
- package/claude/standards.md +29 -6
- package/hooks/pre-commit.sh +33 -2
- package/package.json +1 -1
- package/src/commands/claude.js +40 -3
- package/src/commands/format.js +23 -0
- package/src/core/ci/affected.js +5 -2
- package/src/core/claude-hooks.js +211 -0
- package/src/core/claude.js +5 -25
- package/src/core/format-file.js +152 -0
- package/src/index.js +2 -0
package/README.md
CHANGED
|
@@ -100,6 +100,7 @@ Managed `.env` values use fixed keys: `COMPOSE_PROJECT_NAME`, `COMPOSE_PROFILES`
|
|
|
100
100
|
- `hassan-devkit config:show [--json]` — declared + derived values (projects, scopes, compose profiles, image tag).
|
|
101
101
|
- `hassan-devkit config:check` — validate the block; exit 1 with the offending paths.
|
|
102
102
|
- `hassan-devkit commits:show [--json]` — the commit-subject contract shared by CI and the commit-writer agent: ticket token, types, derived scopes and the regex `^<TICKET> (<types>)\((<scopes>)\): [a-z]`.
|
|
103
|
+
- `hassan-devkit format:file <...files>` — format files as the pre-commit hook would, ahead of the commit: the Prettier commands of the project's `lint-staged.config.*` (fallback: the derived config) whose globs match each file, run from the repo root. One status line per file (`formatted`, `unchanged`, `no-formatter`, `missing`, `outside`, `failed`); exit 1 only when a formatter failed. The Claude `post-edit` hook is its main caller.
|
|
103
104
|
|
|
104
105
|
### Worktrees
|
|
105
106
|
|
|
@@ -137,7 +138,9 @@ import lintStaged from '@coding-with-hassan/devkit/lint-staged';
|
|
|
137
138
|
export default lintStaged({ exclude: ['api-client'], extra: { 'scripts/**/*.mjs': ['prettier --write'] } });
|
|
138
139
|
```
|
|
139
140
|
|
|
140
|
-
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.
|
|
141
|
+
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. The same config drives `hassan-devkit format:file`, so what Claude's `post-edit` hook formats on edit is exactly what the hook would have rewritten at commit time.
|
|
142
|
+
|
|
143
|
+
The hook never rewrites silently. lint-staged re-stages the fixes `eslint --fix` / `prettier --write` applied, so the hook snapshots the staged tree (`git write-tree`) before and after it runs: when the tree changed, the commit is **aborted** and the rewritten files are listed — the tree that gets committed and pushed must be one that was built and tested (an auto-fix such as `type` → `interface` can break a production build that was green locally). Fixers cascade (Prettier reformats what `eslint --fix` produced only on the next run), so lint-staged is re-run until the staged tree is stable (at most three extra passes) before the files are listed. The fixes stay staged: review them (`git diff --cached`), rebuild what they touch, then run the same `git commit` again — the second attempt on the unchanged tree passes. Clean commits pass in one go with no extra output.
|
|
141
144
|
|
|
142
145
|
`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.
|
|
143
146
|
|
|
@@ -148,7 +151,7 @@ Every project with an ESLint/Prettier config gets `pnpm -C <dir> exec …` entri
|
|
|
148
151
|
- `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`.
|
|
149
152
|
- `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.
|
|
150
153
|
- `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.
|
|
151
|
-
- `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.
|
|
154
|
+
- `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 — an adopted file always counts, even under `docs/` or a `contentOnly` glob (e.g. `"docs/testing/*.ts": "daz-i18n"` for acceptance-case data a lib's `format:check` covers).
|
|
152
155
|
|
|
153
156
|
### Claude Code layer
|
|
154
157
|
|
|
@@ -156,8 +159,8 @@ Every project with an ESLint/Prettier config gets `pnpm -C <dir> exec …` entri
|
|
|
156
159
|
|
|
157
160
|
- 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;
|
|
158
161
|
- `.claude/agents/commit-writer.md` as a **stub** whose body says "read the shipped file and follow it" — the stub never changes, the content ships with the devkit version;
|
|
159
|
-
- one `.claude/skills/<name>/SKILL.md` stub per skill, same pattern: the house `implement-ticket` (
|
|
160
|
-
-
|
|
162
|
+
- one `.claude/skills/<name>/SKILL.md` stub per skill, same pattern: the house skills `implement-ticket` and `merge-upstream` (bodies shipped by the devkit; the latter user-invocable only, since it creates the merge commit) and every skill of the project's `mattpocock-skills` dependency — `init` adds `github:mattpocock/skills#v1.2.3` to `devDependencies`, a GitHub tarball pinned to an upstream release tag that pnpm integrity-locks — except `implement` and `setup-matt-pocock-skills`, which the house skill and `init` replace. The stub copies the skill's frontmatter verbatim (user-invocable-only skills stay user-only) and points at the body under `node_modules`. Stubs are derived on every install and **gitignored** through a managed block, so nothing is committed and a bump changes nothing in git; they are what makes the skills reach every clone and the skill pickers that only scan `.claude/skills` (T3 Code). Renovate bumps the tag (the shared preset automerges it), so an upstream skills release needs no devkit release;
|
|
163
|
+
- two managed hook entries merged idempotently into `.claude/settings.json`, both running `hassan-devkit claude:hook <id>` from the checkout's `node_modules` (recognised by that id, so a reworded command replaces the entry and the inline `jq` hook of devkit ≤ 1.2 is dropped): `pre-bash` (`PreToolUse` on `Bash`) denies `gh pr create` without `--assignee`, `docker compose` run directly, `git worktree add|remove|prune|…` and `git commit` on `ci.baseBranch` — each with the house command to use instead; `post-edit` (`PostToolUse` on `Edit|Write|MultiEdit`) runs `format:file` on the edited file and tells Claude to re-read it when Prettier changed it. The rules live in the package, so a bump adds a guard with nothing to re-commit; every hook fails open (a broken hook never blocks a tool call).
|
|
161
164
|
|
|
162
165
|
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.
|
|
163
166
|
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: merge-upstream
|
|
3
|
+
description: "Bring the canonical remote's main into the current checkout the house way: fetch, stop when up to date, merge (fast-forward only on the base branch), install the merged toolchain BEFORE completing a conflicted merge so the pre-commit fixers run with the presets upstream was formatted with, restore hook-rewritten files, then refresh what the merged files need. User-invocable only: it creates the merge commit."
|
|
4
|
+
disable-model-invocation: true
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
# merge-upstream (body shipped by @coding-with-hassan/devkit)
|
|
8
|
+
|
|
9
|
+
Bring the canonical `main` into the checkout you are in. The user invoking this skill is the
|
|
10
|
+
consent for exactly one commit: the merge commit. Never push; never rebase (branches are shared
|
|
11
|
+
through their PRs and the house merges).
|
|
12
|
+
|
|
13
|
+
## 1. Where you are
|
|
14
|
+
|
|
15
|
+
- Run everything from the checkout's root (`git rev-parse --show-toplevel`).
|
|
16
|
+
- Canonical remote: `upstream` when it exists (`git remote get-url upstream`), else `origin`.
|
|
17
|
+
Base branch: `ci.baseBranch` from `hassan-devkit config:show --json` (default `main`).
|
|
18
|
+
- `git status --porcelain`: uncommitted work is normal in this workflow (work stays uncommitted
|
|
19
|
+
until the user asks to commit). Note the paths; you will check them against the incoming
|
|
20
|
+
change in step 3.
|
|
21
|
+
|
|
22
|
+
## 2. Fetch and short-circuit
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
git fetch <remote> <base>
|
|
26
|
+
git merge-base --is-ancestor <remote>/<base> HEAD && echo up-to-date
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Up to date → report that and stop.
|
|
30
|
+
|
|
31
|
+
## 3. Preview what comes in
|
|
32
|
+
|
|
33
|
+
```sh
|
|
34
|
+
git log --oneline HEAD..<remote>/<base>
|
|
35
|
+
git diff --stat HEAD...<remote>/<base>
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
- If an incoming path is also modified and uncommitted locally, stop and tell the user which
|
|
39
|
+
paths collide: git would refuse the merge, and stashing or committing their work is their
|
|
40
|
+
call, not yours.
|
|
41
|
+
- Note whether the lockfile (`pnpm-lock.yaml`), any `package.json` or the devkit / lint presets
|
|
42
|
+
move: these decide step 5.
|
|
43
|
+
|
|
44
|
+
## 4. Merge
|
|
45
|
+
|
|
46
|
+
- On the base branch itself (a main checkout): `git merge --ff-only <remote>/<base>` and skip
|
|
47
|
+
to step 6 — the base branch never gets a merge commit.
|
|
48
|
+
- On a ticket branch: `git merge --no-edit <remote>/<base>`. A clean merge commits by itself
|
|
49
|
+
without running the pre-commit hook; nothing more to do here.
|
|
50
|
+
- Conflicts: resolve them (the `resolving-merge-conflicts` skill), `git add` the resolved
|
|
51
|
+
files, then do step 5 BEFORE `git commit`.
|
|
52
|
+
|
|
53
|
+
## 5. Install before completing a conflicted merge
|
|
54
|
+
|
|
55
|
+
Completing a conflicted merge is a `git commit`, so the pre-commit hook runs lint-staged's
|
|
56
|
+
`prettier --write` and `eslint --fix` over every staged upstream file — with the toolchain in
|
|
57
|
+
this checkout's CURRENT `node_modules`. When the incoming change bumps the devkit or a lint
|
|
58
|
+
preset, the stale local preset rewrites upstream's files (it strips a directive it does not
|
|
59
|
+
know, reformats with old options) and the hook aborts the commit listing them.
|
|
60
|
+
|
|
61
|
+
1. When the lockfile or a `package.json` came in: `pnpm install --frozen-lockfile --prefer-offline`.
|
|
62
|
+
2. `git commit --no-edit` (a merge commit is exempt from the commit-subject standard and needs
|
|
63
|
+
no `commit-writer` plan).
|
|
64
|
+
3. If the hook still aborts with "rewrote staged files": for each listed file that you did NOT
|
|
65
|
+
resolve by hand, restore upstream's version — `git checkout <remote>/<base> -- <file>`; for a
|
|
66
|
+
file you did resolve, review the rewrite (`git diff --cached -- <file>`) and keep it if it is
|
|
67
|
+
only the merged presets doing their job. Then `git commit --no-edit` again.
|
|
68
|
+
|
|
69
|
+
## 6. Refresh what the merge touched
|
|
70
|
+
|
|
71
|
+
- Lockfile or `package.json` moved and step 5 did not install: `pnpm install --frozen-lockfile --prefer-offline`.
|
|
72
|
+
- Dev servers running in containers do not pick up new files of source-shared libs on their own:
|
|
73
|
+
restart the affected ones with the project's `docker:dev:restart-*` scripts named in its
|
|
74
|
+
`CLAUDE.md`.
|
|
75
|
+
- Generated contracts (API spec, generated clients/types): regenerate them the way the
|
|
76
|
+
project's `CLAUDE.md` prescribes when their sources came in, and check for drift with the
|
|
77
|
+
project's `*:check` script.
|
|
78
|
+
- `hassan-devkit ci:doctor` when the devkit range moved.
|
|
79
|
+
|
|
80
|
+
## 7. Report
|
|
81
|
+
|
|
82
|
+
One short message: the range merged (`<old>..<new>`, count of commits), whether conflicts were
|
|
83
|
+
resolved and in which files, whether `pnpm install` ran, and what the user still has to do
|
|
84
|
+
(restart, regenerate, re-run a build). Do not push.
|
package/claude/standards.md
CHANGED
|
@@ -8,7 +8,8 @@ generated from the project's tracker config and name the concrete tracker.
|
|
|
8
8
|
## Docker
|
|
9
9
|
|
|
10
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`,
|
|
11
|
+
`docker compose` directly (a hook denies it): `pnpm docker:dev:up`, `pnpm docker:dev:down`,
|
|
12
|
+
`pnpm docker:dev:logs`.
|
|
12
13
|
`docker:dev:up` refreshes the checkout's managed `.env` block (slot, profiles, image tag) and
|
|
13
14
|
builds only the dev images the current dependency manifest lacks; a dependency bump needs
|
|
14
15
|
nothing extra. Never set `DEVKIT_IMAGE_TAG`, `DEVKIT_SLOT`, `DEVKIT_PORT_*` or
|
|
@@ -18,7 +19,8 @@ nothing extra. Never set `DEVKIT_IMAGE_TAG`, `DEVKIT_SLOT`, `DEVKIT_PORT_*` or
|
|
|
18
19
|
|
|
19
20
|
Ticket work happens in a git worktree with its own Docker stack (own compose project, host
|
|
20
21
|
ports = base + slot × 10, own volumes), never in the main checkout. Manage worktrees only with
|
|
21
|
-
the devkit — never `git worktree` by hand
|
|
22
|
+
the devkit — never `git worktree` by hand (a hook denies `git worktree add|remove|prune|…`;
|
|
23
|
+
listing is fine):
|
|
22
24
|
|
|
23
25
|
- `hassan-devkit worktree:create <TICKET>-<Short-Title>` prunes merged worktrees, fetches the
|
|
24
26
|
canonical remote (`upstream`, else `origin`), bases the branch on its `main` (never on the
|
|
@@ -35,6 +37,10 @@ the devkit — never `git worktree` by hand:
|
|
|
35
37
|
deletes the stack and its data; `worktree:prune` removes every worktree whose PR is merged.
|
|
36
38
|
- Starting work anywhere else (an existing branch, the main checkout): sync first with
|
|
37
39
|
`git fetch <remote> && git merge --ff-only <remote>/main`.
|
|
40
|
+
- Bringing the canonical `main` into a branch is the `/merge-upstream` skill (user-invoked, since
|
|
41
|
+
it creates the merge commit): fetch, merge, and — when the merge conflicts — `pnpm install`
|
|
42
|
+
BEFORE completing it, so the pre-commit fixers run with the presets upstream was formatted
|
|
43
|
+
with; a file the hook still rewrote is restored from `<remote>/main`.
|
|
38
44
|
|
|
39
45
|
## Committing and pushing
|
|
40
46
|
|
|
@@ -51,8 +57,11 @@ commits and enforces the commit standard CI checks: `hassan-devkit commits:show`
|
|
|
51
57
|
ticket token, the closed type list, the derived scope list and the exact regex. Commits are
|
|
52
58
|
signed. Never add a Co-Authored-By line or any AI attribution.
|
|
53
59
|
|
|
54
|
-
|
|
55
|
-
|
|
60
|
+
A commit on the base branch is denied by a hook: ticket work happens in a worktree, and a
|
|
61
|
+
commit that really belongs on `main` is the developer's to make by hand.
|
|
62
|
+
|
|
63
|
+
Pull requests are created with `gh pr create --assignee @me` (a hook denies the command
|
|
64
|
+
without an assignee) and, for GitHub-tracked issues, end with `Closes #<n>`.
|
|
56
65
|
|
|
57
66
|
## Tickets
|
|
58
67
|
|
|
@@ -87,8 +96,22 @@ its `inputs`/`namedInputs`, or a cached replay can be stale. `.nxignore` is not
|
|
|
87
96
|
also drop files from task hashing. A new workspace package must be added to every Dockerfile's
|
|
88
97
|
`COPY` list (frozen-lockfile installs need all importers present).
|
|
89
98
|
|
|
90
|
-
|
|
91
|
-
|
|
99
|
+
Every file you edit is formatted on the spot by the `post-edit` hook (`hassan-devkit
|
|
100
|
+
format:file`: the Prettier commands of the project's lint-staged config for that path), so the
|
|
101
|
+
pre-commit abort-on-rewrite is left with ESLint fixes only. When the hook reports that it
|
|
102
|
+
reformatted a file, re-read it before editing it again — the on-disk content moved under you.
|
|
103
|
+
|
|
104
|
+
Git hooks: git silently skips ALL pre-commit hooks when `.husky/_` is missing. `worktree:create`
|
|
105
|
+
and `pnpm install` (via `hooks:install`) bootstrap it; `hassan-devkit ci:doctor` reports it.
|
|
106
|
+
|
|
107
|
+
## Claude Code hooks
|
|
108
|
+
|
|
109
|
+
The hooks in `.claude/settings.json` are managed by `hassan-devkit claude:install` and run
|
|
110
|
+
`hassan-devkit claude:hook <id>`: `pre-bash` evaluates the guards named above (PR assignee,
|
|
111
|
+
direct `docker compose`, `git worktree` by hand, a commit on the base branch) and `post-edit`
|
|
112
|
+
formats the edited file. They are rails for Claude, not locks for the developer: every hook
|
|
113
|
+
fails open, and a denial names the house command to use instead — use it rather than looking
|
|
114
|
+
for a way around the guard.
|
|
92
115
|
|
|
93
116
|
## Domain docs
|
|
94
117
|
|
package/hooks/pre-commit.sh
CHANGED
|
@@ -15,5 +15,36 @@ if git diff --cached --name-only | grep -q '^\.github/workflows/ci\.yml$'; then
|
|
|
15
15
|
pnpm exec hassan-devkit ci:doctor || exit 1
|
|
16
16
|
fi
|
|
17
17
|
|
|
18
|
-
# 4. Per-project lint/format on staged files (targets derived from the workspace)
|
|
19
|
-
|
|
18
|
+
# 4. Per-project lint/format on staged files (targets derived from the workspace). The hook
|
|
19
|
+
# never rewrites silently (README → "Pre-commit chain"): the staged tree (`git write-tree`)
|
|
20
|
+
# is compared before and after lint-staged; fixers cascade, so lint-staged is re-run until
|
|
21
|
+
# the tree is stable, then a changed tree aborts the commit with the rewritten files listed.
|
|
22
|
+
max_reruns=3
|
|
23
|
+
before=$(git write-tree) || exit 1
|
|
24
|
+
previous=$before
|
|
25
|
+
reruns=0
|
|
26
|
+
failed=0
|
|
27
|
+
stable=1
|
|
28
|
+
while :; do
|
|
29
|
+
pnpm exec lint-staged || failed=1
|
|
30
|
+
after=$(git write-tree) || exit 1
|
|
31
|
+
[ "$failed" -eq 1 ] && break
|
|
32
|
+
[ "$after" = "$previous" ] && break
|
|
33
|
+
if [ "$reruns" -ge "$max_reruns" ]; then stable=0; break; fi
|
|
34
|
+
previous=$after
|
|
35
|
+
reruns=$((reruns + 1))
|
|
36
|
+
done
|
|
37
|
+
if [ "$before" != "$after" ]; then
|
|
38
|
+
{
|
|
39
|
+
echo ""
|
|
40
|
+
echo "pre-commit: lint-staged rewrote staged files — the fixes are applied and staged, but the commit is aborted:"
|
|
41
|
+
git diff --name-only "$before" "$after" | sed 's/^/ /'
|
|
42
|
+
if [ "$stable" -eq 1 ]; then
|
|
43
|
+
echo "Review them (git diff --cached), rebuild what they touch, then run the same git commit again."
|
|
44
|
+
else
|
|
45
|
+
echo "The fixers were still changing these files after $max_reruns re-runs (conflicting prettier/eslint rules?) — review them (git diff --cached), then run the same git commit again."
|
|
46
|
+
fi
|
|
47
|
+
} >&2
|
|
48
|
+
exit 1
|
|
49
|
+
fi
|
|
50
|
+
exit "$failed"
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@coding-with-hassan/devkit",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.0",
|
|
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",
|
package/src/commands/claude.js
CHANGED
|
@@ -3,14 +3,18 @@ import { existsSync } from 'node:fs';
|
|
|
3
3
|
import { join } from 'node:path';
|
|
4
4
|
import { loadConfig } from '../core/config.js';
|
|
5
5
|
import { claudePlans, stubPath } from '../core/claude.js';
|
|
6
|
+
import { dispatchHook } from '../core/claude-hooks.js';
|
|
6
7
|
import { applyPlan } from '../core/scaffold.js';
|
|
7
8
|
import { exitOnFailure } from '../util/run.js';
|
|
8
9
|
|
|
9
10
|
/**
|
|
10
11
|
* `claude:install` — wire the Claude Code layer into this repo: the `@import` of the shipped
|
|
11
12
|
* standards in CLAUDE.md, the agent stub, one stub per skill (house + the project's
|
|
12
|
-
* `mattpocock-skills` dependency, gitignored through a managed block) and the
|
|
13
|
-
* Idempotent; runs from `prepare` so every checkout has the stubs, and from `init`.
|
|
13
|
+
* `mattpocock-skills` dependency, gitignored through a managed block) and the two house hook
|
|
14
|
+
* entries. Idempotent; runs from `prepare` so every checkout has the stubs, and from `init`.
|
|
15
|
+
*
|
|
16
|
+
* `claude:hook <id>` — the command those entries run: reads the hook event JSON from stdin and
|
|
17
|
+
* answers per Claude Code's hook protocol on stdout. Fails open on purpose (see claude-hooks.js).
|
|
14
18
|
*/
|
|
15
19
|
|
|
16
20
|
/** Stub paths git still tracks: they predate the gitignore block and must be untracked once. */
|
|
@@ -43,9 +47,42 @@ export async function installClaude({ cwd = process.cwd(), env = process.env, lo
|
|
|
43
47
|
return summary;
|
|
44
48
|
}
|
|
45
49
|
|
|
50
|
+
async function readStdin(stream) {
|
|
51
|
+
let text = '';
|
|
52
|
+
for await (const chunk of stream) text += chunk;
|
|
53
|
+
return text;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Entry point of the settings entries. Every failure — unreadable input, an unknown id, a
|
|
58
|
+
* formatter refusing a half-written file — is reported on stderr and exits 0 with no decision,
|
|
59
|
+
* so a broken hook never blocks Claude's tool call.
|
|
60
|
+
*/
|
|
61
|
+
export async function runClaudeHook(id, { input, stdin = process.stdin, cwd = process.cwd(), write = (s) => process.stdout.write(s), warn = (s) => process.stderr.write(s) } = {}) {
|
|
62
|
+
let payload;
|
|
63
|
+
try {
|
|
64
|
+
payload = JSON.parse(input ?? (await readStdin(stdin)));
|
|
65
|
+
} catch (e) {
|
|
66
|
+
warn(`claude:hook ${id}: unreadable hook input, allowing (${e.message})\n`);
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
try {
|
|
70
|
+
const answer = await dispatchHook(id, payload, { cwd });
|
|
71
|
+
if (answer) write(`${JSON.stringify(answer)}\n`);
|
|
72
|
+
return answer;
|
|
73
|
+
} catch (e) {
|
|
74
|
+
warn(`claude:hook ${id}: ${e.message}\n`);
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
46
79
|
export function registerClaude(cli) {
|
|
47
80
|
cli
|
|
48
|
-
.command('claude:install', 'Wire the Claude Code layer (standards import, agent stub, skill stubs from the devkit + mattpocock-skills,
|
|
81
|
+
.command('claude:install', 'Wire the Claude Code layer (standards import, agent stub, skill stubs from the devkit + mattpocock-skills, house hook entries) into this repo')
|
|
49
82
|
.option('--dry-run', 'Show what would change without writing')
|
|
50
83
|
.action((opts) => exitOnFailure(installClaude({ dryRun: Boolean(opts.dryRun) })));
|
|
84
|
+
|
|
85
|
+
cli
|
|
86
|
+
.command('claude:hook <id>', 'Claude Code hook dispatcher run by the entries claude:install writes (stdin: the hook event JSON) — pre-bash guards, post-edit formatting; never blocks on its own failure')
|
|
87
|
+
.action((id) => exitOnFailure(runClaudeHook(id)));
|
|
51
88
|
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { formatFiles } from '../core/format-file.js';
|
|
2
|
+
import { findRepoRoot } from '../core/root.js';
|
|
3
|
+
import { exitOnFailure } from '../util/run.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* `format:file <...files>` — format files the way the pre-commit hook would, before the commit:
|
|
7
|
+
* the Prettier commands of the project's lint-staged config whose globs match each file. Used by
|
|
8
|
+
* the `post-edit` Claude hook; handy by hand after a generator or a bulk edit as well.
|
|
9
|
+
*/
|
|
10
|
+
export async function formatFile({ files, cwd = process.cwd(), log = console.log } = {}) {
|
|
11
|
+
const root = findRepoRoot(cwd);
|
|
12
|
+
const results = await formatFiles(root, files, { cwd });
|
|
13
|
+
for (const r of results) log(` ${r.status.padEnd(12)} ${r.file}${r.error ? `\n${r.error.replace(/^/gm, ' ')}` : ''}`);
|
|
14
|
+
const failed = results.filter((r) => r.status === 'failed');
|
|
15
|
+
if (failed.length) throw new Error(`format:file: ${failed.length} file(s) could not be formatted`);
|
|
16
|
+
return results;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function registerFormat(cli) {
|
|
20
|
+
cli
|
|
21
|
+
.command('format:file <...files>', 'Format files as the pre-commit hook would: the Prettier commands of the lint-staged config whose globs match each file')
|
|
22
|
+
.action((files) => exitOnFailure(formatFile({ files })));
|
|
23
|
+
}
|
package/src/core/ci/affected.js
CHANGED
|
@@ -21,7 +21,9 @@ import { capture, run } from '../exec.js';
|
|
|
21
21
|
*
|
|
22
22
|
* Project-specific lists come from `ci.affected` in the config: `contentOnly` (globs of
|
|
23
23
|
* files copied verbatim into outputs — skipped unless `--with-content`) and `adopted`
|
|
24
|
-
* (glob → project that reads files outside every project root).
|
|
24
|
+
* (glob → project that reads files outside every project root). An adopted file is, by
|
|
25
|
+
* definition, read by a project target, so it is never dropped — not by the docs filter and
|
|
26
|
+
* not by `contentOnly` — even when it lives under `docs/` (acceptance-case data files, say).
|
|
25
27
|
*/
|
|
26
28
|
|
|
27
29
|
export const DOCS_ONLY = [/\.md$/, /^docs\//];
|
|
@@ -53,9 +55,10 @@ export function classifyFiles(changed, { roots, contentOnly = [], adopted = {},
|
|
|
53
55
|
const contentRes = contentOnly.map(globToRegExp);
|
|
54
56
|
const adoptedRes = Object.entries(adopted).map(([glob, project]) => [globToRegExp(glob), project]);
|
|
55
57
|
const ignore = withContent ? DOCS_ONLY : [...DOCS_ONLY, ...contentRes];
|
|
58
|
+
const isAdopted = (f) => adoptedRes.some(([re]) => re.test(f));
|
|
56
59
|
const ignored = [];
|
|
57
60
|
const files = [];
|
|
58
|
-
for (const f of changed) (ignore.some((re) => re.test(f)) ? ignored : files).push(f);
|
|
61
|
+
for (const f of changed) (!isAdopted(f) && ignore.some((re) => re.test(f)) ? ignored : files).push(f);
|
|
59
62
|
const touched = new Set();
|
|
60
63
|
const globals = [];
|
|
61
64
|
const unowned = [];
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import { resolve } from 'node:path';
|
|
2
|
+
import { DEFAULT_BASE_BRANCH, loadConfig } from './config.js';
|
|
3
|
+
import { formatFiles } from './format-file.js';
|
|
4
|
+
import { currentBranch } from './git.js';
|
|
5
|
+
import { findRepoRoot } from './root.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The house Claude Code hooks, in two halves.
|
|
9
|
+
*
|
|
10
|
+
* ENTRIES — what `claude:install` merges into the project's `.claude/settings.json`: one entry
|
|
11
|
+
* per hook event, each running `hassan-devkit claude:hook <id>` from the checkout's own
|
|
12
|
+
* `node_modules`. An entry is recognised by that id, so a reworded command replaces it instead
|
|
13
|
+
* of piling up a second copy, and the entries themselves never need to change: the rules behind
|
|
14
|
+
* them live in this file and reach every project with a devkit bump alone.
|
|
15
|
+
*
|
|
16
|
+
* GUARDS — what the `pre-bash` hook evaluates against the Bash command Claude is about to run:
|
|
17
|
+
* pure predicates that return the denial reason (naming the house command to use instead) or
|
|
18
|
+
* `null`. They mirror the rules of `claude/standards.md` that need no judgment. Everything here
|
|
19
|
+
* fails open: a hook that cannot decide answers nothing and the tool call proceeds — a guard is
|
|
20
|
+
* a rail for Claude, never a lock for the developer.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
/** Runs the dispatcher from the project root even when the hook is started elsewhere. */
|
|
24
|
+
export const HOOK_COMMAND = 'cd "${CLAUDE_PROJECT_DIR:-.}" && node node_modules/@coding-with-hassan/devkit/bin/cli.js claude:hook';
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Where a simple command begins: the start of the input or after a separator (`;`, `&&`, `|`,
|
|
28
|
+
* a subshell, a command substitution, a NEW LINE — Claude routinely writes multi-line Bash),
|
|
29
|
+
* optionally preceded by `VAR=value` assignments and `sudo` / `time`. Keeps
|
|
30
|
+
* `echo "docker compose"` and `pnpm docker:dev:up` out of the docker guard.
|
|
31
|
+
*/
|
|
32
|
+
const COMMAND_START = String.raw`(?:^|[;&|(\n\x60])\s*(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)*(?:(?:sudo|time)\s+)*`;
|
|
33
|
+
/** A path argument: quoted (may hold spaces) or bare. */
|
|
34
|
+
const PATH_ARG = String.raw`(?:"[^"\n]+"|'[^'\n]+'|\S+)`;
|
|
35
|
+
/** git's global options between `git` and the subcommand: `-C <dir>`, `-c k=v`, `--no-pager`, `--git-dir=…`, `-p`/`-P`. */
|
|
36
|
+
const GIT_GLOBALS = String.raw`((?:(?:-C\s+${PATH_ARG}|-c\s+\S+|--[\w-]+(?:=\S*)?|-[pP])\s+)*)`;
|
|
37
|
+
const GH_PR_CREATE = new RegExp(`${COMMAND_START}gh\\s+pr\\s+create(?![\\w-])`);
|
|
38
|
+
const DOCKER_COMPOSE = new RegExp(`${COMMAND_START}docker(?:\\s+compose|-compose)(?![\\w-])`);
|
|
39
|
+
const GIT_WORKTREE = new RegExp(`${COMMAND_START}git\\s+${GIT_GLOBALS}worktree\\s+(?:add|remove|prune|move|lock|unlock|repair)(?![\\w-])`);
|
|
40
|
+
// `(?![\w-])`, not `\b`: `git commit-tree` is plumbing, not a commit.
|
|
41
|
+
const GIT_COMMIT = new RegExp(`${COMMAND_START}git\\s+${GIT_GLOBALS}commit(?![\\w-])`, 'g');
|
|
42
|
+
const GIT_C_OPTION = new RegExp(`(?:^|\\s)-C\\s+(${PATH_ARG})`);
|
|
43
|
+
const LEADING_CD = new RegExp(`^\\s*cd\\s+(${PATH_ARG})\\s*(?:&&|;|\\n)`);
|
|
44
|
+
|
|
45
|
+
const unquote = (s) => s.replace(/^(["'])(.*)\1$/, '$2');
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The directory a `git … commit` in `command` acts on: `cwd`, moved by a leading `cd <dir> &&`,
|
|
49
|
+
* then by `-C <dir>` among git's global options (`gitGlobals`, resolved against that base as
|
|
50
|
+
* git itself does).
|
|
51
|
+
*/
|
|
52
|
+
export function commitDir(command, cwd, gitGlobals = '') {
|
|
53
|
+
const cd = LEADING_CD.exec(command);
|
|
54
|
+
const base = cd ? resolve(cwd, unquote(cd[1])) : cwd;
|
|
55
|
+
const c = GIT_C_OPTION.exec(gitGlobals);
|
|
56
|
+
return c ? resolve(base, unquote(c[1])) : base;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* The guards, in the order their reasons are listed. `test(command, ctx)` → reason or null;
|
|
61
|
+
* `ctx` = `{ cwd, baseBranch, currentBranch(dir) }`, where `currentBranch` returns the checked
|
|
62
|
+
* out branch of `dir` or null (detached, not a checkout, missing directory).
|
|
63
|
+
*/
|
|
64
|
+
export const GUARDS = [
|
|
65
|
+
{
|
|
66
|
+
id: 'pr-assignee',
|
|
67
|
+
rule: '`gh pr create` carries `--assignee` (every PR gets its author assigned at creation)',
|
|
68
|
+
test: (command) =>
|
|
69
|
+
GH_PR_CREATE.test(command) && !/--assignee|(^|\s)-a(\s|=)/.test(command)
|
|
70
|
+
? 'Team git workflow standard: every PR gets its author assigned at creation - re-run gh pr create with --assignee @me.'
|
|
71
|
+
: null,
|
|
72
|
+
},
|
|
73
|
+
{
|
|
74
|
+
id: 'docker-compose',
|
|
75
|
+
rule: '`docker compose` is never run directly (the root npm scripts apply the managed .env)',
|
|
76
|
+
test: (command) =>
|
|
77
|
+
DOCKER_COMPOSE.test(command)
|
|
78
|
+
? 'House Docker rule: never run docker compose directly - use the root npm scripts (pnpm docker:dev:up | docker:dev:down | docker:dev:logs, ...), which apply this checkout\'s managed .env (slot, ports, profiles, image tag) and so hit this checkout\'s stack only.'
|
|
79
|
+
: null,
|
|
80
|
+
},
|
|
81
|
+
{
|
|
82
|
+
id: 'git-worktree',
|
|
83
|
+
rule: 'worktrees are managed by the devkit, never by `git worktree` (listing is fine)',
|
|
84
|
+
test: (command) =>
|
|
85
|
+
GIT_WORKTREE.test(command)
|
|
86
|
+
? 'House worktree rule: never manage worktrees with git directly - use hassan-devkit worktree:create <TICKET>-<Short-Title> | worktree:remove <branch> | worktree:prune (worktree:list is fine).'
|
|
87
|
+
: null,
|
|
88
|
+
},
|
|
89
|
+
{
|
|
90
|
+
id: 'commit-on-base',
|
|
91
|
+
rule: 'no commits on the base branch (ticket work happens in a worktree)',
|
|
92
|
+
test: (command, { cwd, baseBranch, currentBranch: branchOf }) => {
|
|
93
|
+
for (const match of command.matchAll(GIT_COMMIT)) {
|
|
94
|
+
let branch = null;
|
|
95
|
+
try {
|
|
96
|
+
branch = branchOf(commitDir(command, cwd, match[1]));
|
|
97
|
+
} catch {
|
|
98
|
+
branch = null;
|
|
99
|
+
}
|
|
100
|
+
if (branch !== null && branch === baseBranch) {
|
|
101
|
+
return `House worktree rule: no commits on ${baseBranch} - ticket work happens in a worktree (hassan-devkit worktree:create <TICKET>-<Short-Title>). A commit that really belongs on ${baseBranch} is the developer's to make by hand.`;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return null;
|
|
105
|
+
},
|
|
106
|
+
},
|
|
107
|
+
];
|
|
108
|
+
|
|
109
|
+
/** Pure: every guard `command` trips, as `{ id, reason }`. */
|
|
110
|
+
export function evaluateBashGuards(command, ctx) {
|
|
111
|
+
const context = { cwd: process.cwd(), baseBranch: DEFAULT_BASE_BRANCH, currentBranch: () => null, ...ctx };
|
|
112
|
+
const denials = [];
|
|
113
|
+
for (const guard of GUARDS) {
|
|
114
|
+
const reason = guard.test(command ?? '', context);
|
|
115
|
+
if (reason) denials.push({ id: guard.id, reason });
|
|
116
|
+
}
|
|
117
|
+
return denials;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** The PreToolUse answer that denies the call, listing every reason. */
|
|
121
|
+
export const denyDecision = (reasons) => ({
|
|
122
|
+
hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: reasons.join('\n') },
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
/** The PostToolUse answer that hands Claude extra context without blocking anything. */
|
|
126
|
+
export const additionalContext = (text) => ({ hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: text } });
|
|
127
|
+
|
|
128
|
+
/** The base branch of the checkout around `cwd` (`ci.baseBranch`), default `main`. */
|
|
129
|
+
function baseBranchOf(cwd) {
|
|
130
|
+
try {
|
|
131
|
+
return loadConfig({ cwd }).config?.ci?.baseBranch ?? DEFAULT_BASE_BRANCH;
|
|
132
|
+
} catch {
|
|
133
|
+
return DEFAULT_BASE_BRANCH;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* The hook events the house wires, keyed by dispatcher id: the settings entry (`event`,
|
|
139
|
+
* `matcher`, `timeout` in seconds) and the handler `handle(payload, hookCwd)` → the answer to
|
|
140
|
+
* print, or null for "nothing to say". A handler may throw: the dispatcher reports it on stderr
|
|
141
|
+
* and lets the tool call proceed.
|
|
142
|
+
*/
|
|
143
|
+
export const HOOK_EVENTS = {
|
|
144
|
+
'pre-bash': {
|
|
145
|
+
event: 'PreToolUse',
|
|
146
|
+
matcher: 'Bash',
|
|
147
|
+
handle(payload, hookCwd) {
|
|
148
|
+
const command = payload?.tool_input?.command;
|
|
149
|
+
if (typeof command !== 'string' || !command) return null;
|
|
150
|
+
const denials = evaluateBashGuards(command, { cwd: hookCwd, baseBranch: baseBranchOf(hookCwd), currentBranch });
|
|
151
|
+
return denials.length ? denyDecision(denials.map((d) => d.reason)) : null;
|
|
152
|
+
},
|
|
153
|
+
},
|
|
154
|
+
'post-edit': {
|
|
155
|
+
event: 'PostToolUse',
|
|
156
|
+
matcher: 'Edit|Write|MultiEdit',
|
|
157
|
+
timeout: 30,
|
|
158
|
+
async handle(payload, hookCwd) {
|
|
159
|
+
const file = payload?.tool_input?.file_path;
|
|
160
|
+
if (typeof file !== 'string' || !file) return null;
|
|
161
|
+
const [result] = await formatFiles(findRepoRoot(hookCwd), [file], { cwd: hookCwd });
|
|
162
|
+
if (result.status === 'failed') throw new Error(result.error);
|
|
163
|
+
if (result.status !== 'formatted') return null;
|
|
164
|
+
return additionalContext(
|
|
165
|
+
`Prettier reformatted ${result.file} (house format-on-edit hook: the project's lint-staged Prettier command for that path). The file on disk is now the formatted version - re-read it before editing it again.`,
|
|
166
|
+
);
|
|
167
|
+
},
|
|
168
|
+
},
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
function hookSpec(id) {
|
|
172
|
+
const spec = HOOK_EVENTS[id];
|
|
173
|
+
if (!spec) throw new Error(`unknown hook id "${id}" (known: ${Object.keys(HOOK_EVENTS).join(', ')})`);
|
|
174
|
+
return spec;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Pure: the settings entry for one dispatcher id. */
|
|
178
|
+
export function hookEntry(id) {
|
|
179
|
+
const spec = hookSpec(id);
|
|
180
|
+
const hook = { type: 'command', command: `${HOOK_COMMAND} ${id}` };
|
|
181
|
+
if (spec.timeout) hook.timeout = spec.timeout;
|
|
182
|
+
return { matcher: spec.matcher, hooks: [hook] };
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** The answer for hook `id` given the parsed event payload (`payload.cwd` wins over `cwd`), or null. */
|
|
186
|
+
export async function dispatchHook(id, payload, { cwd = process.cwd() } = {}) {
|
|
187
|
+
const hookCwd = typeof payload?.cwd === 'string' && payload.cwd ? payload.cwd : cwd;
|
|
188
|
+
return hookSpec(id).handle(payload, hookCwd);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const commandsOf = (entry) => (entry?.hooks ?? []).map((h) => h?.command).filter((c) => typeof c === 'string');
|
|
192
|
+
const ownsId = (entry, id) => commandsOf(entry).some((c) => new RegExp(`claude:hook ${id}(?:\\s|$)`).test(c));
|
|
193
|
+
/** The inline `jq` PR-assignee hook written by devkit ≤ 1.2: superseded by the `pre-bash` dispatcher. */
|
|
194
|
+
const isLegacyPrHook = (entry) => commandsOf(entry).some((c) => c.startsWith('jq ') && c.includes('gh pr create') && c.includes('--assignee'));
|
|
195
|
+
|
|
196
|
+
/** Pure: merge the house entries into a settings object; everything the project added is kept. */
|
|
197
|
+
export function mergeSettingsHooks(settings) {
|
|
198
|
+
const next = structuredClone(settings ?? {});
|
|
199
|
+
next.hooks ??= {};
|
|
200
|
+
for (const [id, spec] of Object.entries(HOOK_EVENTS)) {
|
|
201
|
+
const list = (next.hooks[spec.event] ??= []);
|
|
202
|
+
if (spec.event === 'PreToolUse') {
|
|
203
|
+
for (let i = list.length - 1; i >= 0; i--) if (isLegacyPrHook(list[i])) list.splice(i, 1);
|
|
204
|
+
}
|
|
205
|
+
const entry = hookEntry(id);
|
|
206
|
+
const idx = list.findIndex((e) => ownsId(e, id));
|
|
207
|
+
if (idx === -1) list.push(entry);
|
|
208
|
+
else list[idx] = entry;
|
|
209
|
+
}
|
|
210
|
+
return next;
|
|
211
|
+
}
|
package/src/core/claude.js
CHANGED
|
@@ -2,12 +2,15 @@ import { existsSync, readFileSync, readdirSync } from 'node:fs';
|
|
|
2
2
|
import { join, posix } from 'node:path';
|
|
3
3
|
import { fileURLToPath } from 'node:url';
|
|
4
4
|
import { formatJson, planFile, upsertMarkedBlock } from './scaffold.js';
|
|
5
|
+
import { mergeSettingsHooks } from './claude-hooks.js';
|
|
5
6
|
|
|
6
7
|
/**
|
|
7
8
|
* The Claude Code layer. Nothing here is copied content: the project's `CLAUDE.md` imports the
|
|
8
9
|
* standards text from `node_modules` and the agent/skill files are stubs that read the shipped
|
|
9
10
|
* body at runtime, so a devkit bump changes what Claude does without a re-commit. Only the
|
|
10
|
-
* settings hook
|
|
11
|
+
* settings hook entries are merged into a committed file, and that merge is idempotent
|
|
12
|
+
* (claude-hooks.js: two entries that run `hassan-devkit claude:hook <id>`, so the guards behind
|
|
13
|
+
* them change with the devkit version too).
|
|
11
14
|
*
|
|
12
15
|
* Skills come from two places and get the same treatment — one stub per skill, frontmatter
|
|
13
16
|
* copied verbatim from the body file (name, description, invocation flags: what Claude Code and
|
|
@@ -58,29 +61,6 @@ it exactly. That file is the agent's body; it ships with the installed devkit ve
|
|
|
58
61
|
stub never needs to change.
|
|
59
62
|
`;
|
|
60
63
|
|
|
61
|
-
/** The PreToolUse hook that denies `gh pr create` without an assignee (team PR standard). */
|
|
62
|
-
export const PR_ASSIGNEE_HOOK = {
|
|
63
|
-
matcher: 'Bash',
|
|
64
|
-
hooks: [
|
|
65
|
-
{
|
|
66
|
-
type: 'command',
|
|
67
|
-
command:
|
|
68
|
-
'jq -c \'if (.tool_input.command // "" | test("gh pr create")) and ((.tool_input.command // "" | test("--assignee|(^|\\\\s)-a(\\\\s|=)")) | not) then {hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"Team git workflow standard: every PR gets its author assigned at creation - re-run gh pr create with --assignee @me."}} else empty end\'',
|
|
69
|
-
},
|
|
70
|
-
],
|
|
71
|
-
};
|
|
72
|
-
|
|
73
|
-
const isPrHook = (entry) => (entry?.hooks ?? []).some((h) => typeof h.command === 'string' && h.command.includes('gh pr create') && h.command.includes('--assignee'));
|
|
74
|
-
|
|
75
|
-
/** Pure: merge the PR hook into a settings object (adds once; existing entry left alone). */
|
|
76
|
-
export function mergeSettingsHook(settings) {
|
|
77
|
-
const next = structuredClone(settings ?? {});
|
|
78
|
-
next.hooks ??= {};
|
|
79
|
-
next.hooks.PreToolUse ??= [];
|
|
80
|
-
if (!next.hooks.PreToolUse.some(isPrHook)) next.hooks.PreToolUse.push(structuredClone(PR_ASSIGNEE_HOOK));
|
|
81
|
-
return next;
|
|
82
|
-
}
|
|
83
|
-
|
|
84
64
|
/**
|
|
85
65
|
* Pure: the CLAUDE.md text with the import line. Imports resolve relative to the file that
|
|
86
66
|
* contains them, so the path depends on where the file lives (`.claude/CLAUDE.md` vs root).
|
|
@@ -204,7 +184,7 @@ export function claudePlans(root, { notes = [] } = {}) {
|
|
|
204
184
|
throw new Error(`.claude/settings.json is not valid JSON: ${e.message}`);
|
|
205
185
|
}
|
|
206
186
|
}
|
|
207
|
-
plans.push(planFile(root, '.claude/settings.json', formatJson(
|
|
187
|
+
plans.push(planFile(root, '.claude/settings.json', formatJson(mergeSettingsHooks(settings)), { managed: true }));
|
|
208
188
|
return plans;
|
|
209
189
|
}
|
|
210
190
|
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';
|
|
3
|
+
import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
import lintStaged from '../../lint-staged.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Format files exactly as the pre-commit hook would, ahead of the commit: the Prettier
|
|
9
|
+
* commands of the project's lint-staged config whose globs match each file. Reusing that config
|
|
10
|
+
* (not a second rule set) is the point — per-project configs, `exclude` and the `extra` entries
|
|
11
|
+
* for files outside any project apply here as they do at commit time, so a file formatted on
|
|
12
|
+
* edit is a file the hook has nothing left to rewrite. ESLint fixers are deliberately left to
|
|
13
|
+
* the hook: type-aware lint on one file takes seconds and can change code, not just layout.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
export const LINT_STAGED_CONFIG_FILES = [
|
|
17
|
+
'lint-staged.config.mjs',
|
|
18
|
+
'lint-staged.config.js',
|
|
19
|
+
'lint-staged.config.cjs',
|
|
20
|
+
'.lintstagedrc.mjs',
|
|
21
|
+
'.lintstagedrc.js',
|
|
22
|
+
'.lintstagedrc.cjs',
|
|
23
|
+
'.lintstagedrc.json',
|
|
24
|
+
'.lintstagedrc',
|
|
25
|
+
];
|
|
26
|
+
|
|
27
|
+
const escapeRe = (s) => s.replace(/[.+^${}()|[\]\\]/g, '\\$&');
|
|
28
|
+
|
|
29
|
+
/** Pure: a lint-staged (micromatch) glob as an anchored RegExp — `**`, `*`, `?` and `{a,b}` (alternatives may hold globs too). */
|
|
30
|
+
export function globToRegExp(glob) {
|
|
31
|
+
return new RegExp(`^${globBody(glob)}$`);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function globBody(glob) {
|
|
35
|
+
let re = '';
|
|
36
|
+
for (let i = 0; i < glob.length; i++) {
|
|
37
|
+
const c = glob[i];
|
|
38
|
+
if (c === '*' && glob[i + 1] === '*') {
|
|
39
|
+
i++;
|
|
40
|
+
if (glob[i + 1] === '/') {
|
|
41
|
+
i++;
|
|
42
|
+
re += '(?:.*/)?';
|
|
43
|
+
} else re += '.*';
|
|
44
|
+
} else if (c === '*') re += '[^/]*';
|
|
45
|
+
else if (c === '?') re += '[^/]';
|
|
46
|
+
else if (c === '{') {
|
|
47
|
+
const end = glob.indexOf('}', i);
|
|
48
|
+
if (end === -1) re += '\\{';
|
|
49
|
+
else {
|
|
50
|
+
re += `(?:${glob.slice(i + 1, end).split(',').map(globBody).join('|')})`;
|
|
51
|
+
i = end;
|
|
52
|
+
}
|
|
53
|
+
} else re += escapeRe(c);
|
|
54
|
+
}
|
|
55
|
+
return re;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Pure: lint-staged semantics — a glob without a slash matches the basename at any depth. */
|
|
59
|
+
export function matchesGlob(glob, relPath) {
|
|
60
|
+
const pattern = glob.replace(/^\.\//, '');
|
|
61
|
+
const target = pattern.includes('/') ? relPath : basename(relPath);
|
|
62
|
+
return globToRegExp(pattern).test(target);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Pure: the Prettier commands of `config` (glob → command | command[]) that apply to `relPath`, deduplicated in order. */
|
|
66
|
+
export function prettierCommandsFor(config, relPath) {
|
|
67
|
+
const commands = [];
|
|
68
|
+
for (const [glob, value] of Object.entries(config ?? {})) {
|
|
69
|
+
if (!matchesGlob(glob, relPath)) continue;
|
|
70
|
+
for (const cmd of Array.isArray(value) ? value : [value]) {
|
|
71
|
+
if (typeof cmd === 'string' && /\bprettier\b/.test(cmd) && !commands.includes(cmd)) commands.push(cmd);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return commands;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* The project's lint-staged config as a plain glob → commands object, or `null` when there is
|
|
79
|
+
* none or it is a function (whose globs cannot be read). A JS config is imported, so its own
|
|
80
|
+
* imports (`@coding-with-hassan/devkit/lint-staged`) resolve from the project root as usual.
|
|
81
|
+
*/
|
|
82
|
+
export async function loadLintStagedConfig(root) {
|
|
83
|
+
const file = LINT_STAGED_CONFIG_FILES.map((f) => join(root, f)).find((f) => existsSync(f));
|
|
84
|
+
if (!file) return null;
|
|
85
|
+
if (/\.json$|\/\.lintstagedrc$/.test(file)) return JSON.parse(readFileSync(file, 'utf8'));
|
|
86
|
+
// The mtime query defeats the ESM module cache: a one-shot hook never needs it, a long-lived
|
|
87
|
+
// caller (the test runner, a future watch mode) sees a config edit instead of the first import.
|
|
88
|
+
const mod = await import(`${pathToFileURL(file).href}?mtime=${statSync(file).mtimeMs}`);
|
|
89
|
+
const config = mod.default ?? mod;
|
|
90
|
+
return typeof config === 'function' || config === null || typeof config !== 'object' ? null : config;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** realpath of `p`, resolving through the deepest existing ancestor when `p` itself does not exist. */
|
|
94
|
+
const real = (p) => {
|
|
95
|
+
try {
|
|
96
|
+
return realpathSync(p);
|
|
97
|
+
} catch {
|
|
98
|
+
const parent = dirname(p);
|
|
99
|
+
return parent === p ? p : join(real(parent), basename(p));
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
/** Run one lint-staged command on one file from the repo root, the way lint-staged appends the path. */
|
|
104
|
+
export function runFormatter(command, absFile, root) {
|
|
105
|
+
try {
|
|
106
|
+
execFileSync('sh', ['-c', `${command} "$0"`, absFile], { cwd: root, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
107
|
+
} catch (e) {
|
|
108
|
+
const stderr = e.stderr ? e.stderr.toString().trim() : '';
|
|
109
|
+
throw new Error(`${command} ${absFile} failed${stderr ? `:\n${stderr}` : ` (exit ${e.status ?? '?'})`}`);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Format `files` (paths relative to `cwd` or absolute) with the project's Prettier commands.
|
|
115
|
+
* Returns one `{ file, status, commands?, error? }` per input, `status` being `formatted`,
|
|
116
|
+
* `unchanged`, `no-formatter` (no matching Prettier command), `missing` or `outside` (not under
|
|
117
|
+
* `root`); `failed` carries the tool's message — Prettier refusing a file it cannot parse is a
|
|
118
|
+
* normal outcome mid-edit and never throws.
|
|
119
|
+
*/
|
|
120
|
+
export async function formatFiles(root, files, { cwd = root, exec = runFormatter, config } = {}) {
|
|
121
|
+
const resolved = config ?? (await loadLintStagedConfig(root)) ?? lintStaged({ root });
|
|
122
|
+
// Compare real paths: git reports a symlinked checkout (macOS /var → /private/var, a linked
|
|
123
|
+
// worktree dir) by its target while the editor hands over the path it was given.
|
|
124
|
+
const realRoot = real(root);
|
|
125
|
+
const results = [];
|
|
126
|
+
for (const file of files) {
|
|
127
|
+
const abs = real(resolve(cwd, file));
|
|
128
|
+
const rel = relative(realRoot, abs).split('\\').join('/');
|
|
129
|
+
if (rel.startsWith('..') || isAbsolute(rel)) {
|
|
130
|
+
results.push({ file: rel, status: 'outside' });
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
if (!existsSync(abs)) {
|
|
134
|
+
results.push({ file: rel, status: 'missing' });
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
const commands = prettierCommandsFor(resolved, rel);
|
|
138
|
+
if (commands.length === 0) {
|
|
139
|
+
results.push({ file: rel, status: 'no-formatter' });
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
const before = readFileSync(abs, 'utf8');
|
|
143
|
+
try {
|
|
144
|
+
for (const command of commands) exec(command, abs, root);
|
|
145
|
+
} catch (e) {
|
|
146
|
+
results.push({ file: rel, status: 'failed', commands, error: e.message });
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
results.push({ file: rel, status: readFileSync(abs, 'utf8') === before ? 'unchanged' : 'formatted', commands });
|
|
150
|
+
}
|
|
151
|
+
return results;
|
|
152
|
+
}
|
package/src/index.js
CHANGED
|
@@ -8,6 +8,7 @@ import { registerConfig } from './commands/config.js';
|
|
|
8
8
|
import { registerWorktree } from './commands/worktree.js';
|
|
9
9
|
import { registerCi } from './commands/ci.js';
|
|
10
10
|
import { registerClaude } from './commands/claude.js';
|
|
11
|
+
import { registerFormat } from './commands/format.js';
|
|
11
12
|
import { registerTestCases } from './commands/test-cases.js';
|
|
12
13
|
|
|
13
14
|
export function run(argv) {
|
|
@@ -18,6 +19,7 @@ export function run(argv) {
|
|
|
18
19
|
registerWorktree(cli);
|
|
19
20
|
registerCi(cli);
|
|
20
21
|
registerClaude(cli);
|
|
22
|
+
registerFormat(cli);
|
|
21
23
|
registerTestCases(cli);
|
|
22
24
|
registerDocker(cli);
|
|
23
25
|
registerDb(cli);
|