@warren-dean/code-kit 0.3.15 → 0.5.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/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/CHANGELOG.md +34 -0
- package/README.md +46 -26
- package/bin/code-kit.mjs +128 -17
- package/hooks/guard-bash.mjs +79 -29
- package/hooks/hooks.json +1 -0
- package/hooks/lane-audit.mjs +17 -6
- package/hooks/lib/config.mjs +30 -5
- package/hooks/lib/diff.mjs +5 -1
- package/hooks/lib/next.mjs +13 -2
- package/hooks/lib/plan.mjs +18 -7
- package/hooks/lib/registry.mjs +37 -3
- package/hooks/lib/reviews.mjs +39 -0
- package/hooks/lib/rules.mjs +66 -4
- package/hooks/lib/shell.mjs +94 -0
- package/hooks/lib/trace.mjs +4 -2
- package/hooks/lib/verify.mjs +74 -3
- package/hooks/mod/register.mjs +359 -0
- package/hooks/mod/register.test.ts +716 -0
- package/hooks/mod/view.mjs +427 -0
- package/hooks/stop-check.mjs +12 -1
- package/package.json +2 -2
- package/skills/init/SKILL.md +10 -2
- package/skills/review/SKILL.md +9 -1
- package/templates/agent.md +1 -1
package/hooks/guard-bash.mjs
CHANGED
|
@@ -5,19 +5,22 @@
|
|
|
5
5
|
// approval log on commit and scans commits for secrets. Shell writes are also checked afterwards by
|
|
6
6
|
// lane-audit.mjs. With `approvals.lead` on, the lead may act for the person on what they say in chat:
|
|
7
7
|
// record their approvals (`code-kit approve`) and run blocked commands marked `person`.
|
|
8
|
-
import { appendFileSync } from 'node:fs';
|
|
8
|
+
import { appendFileSync, existsSync, readFileSync } from 'node:fs';
|
|
9
9
|
import { spawnSync } from 'node:child_process';
|
|
10
10
|
import { join, resolve } from 'node:path';
|
|
11
|
-
import { addedPackages, dependencyApproval } from './lib/dependencies.mjs';
|
|
11
|
+
import { addedPackages, dependencyApproval, isDependencyFile } from './lib/dependencies.mjs';
|
|
12
|
+
import { CODE_KIT, GIT, codeOf, runs } from './lib/shell.mjs';
|
|
12
13
|
import { block, start } from './lib/hook.mjs';
|
|
13
14
|
import {
|
|
14
15
|
APPROVAL_LOG,
|
|
15
16
|
actorFor,
|
|
17
|
+
arrivesWithMerge,
|
|
16
18
|
approval,
|
|
17
19
|
approvalHowTo,
|
|
18
20
|
currentBranch,
|
|
19
21
|
dependencyChange,
|
|
20
22
|
dependencyGrants,
|
|
23
|
+
useApproval,
|
|
21
24
|
owns,
|
|
22
25
|
protectedEntry,
|
|
23
26
|
recordRequest,
|
|
@@ -27,28 +30,46 @@ import {
|
|
|
27
30
|
const { input, project, config, error } = start();
|
|
28
31
|
const cmd = String(input.tool_input?.command || '');
|
|
29
32
|
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
+
// Commands are recognised where they run (lib/shell.mjs), so a commit message, a heredoc, a quoted
|
|
34
|
+
// --text or a grep pattern that mentions one doesn't trip its rule.
|
|
35
|
+
const RUNS = [
|
|
36
|
+
[
|
|
37
|
+
new RegExp(String.raw`^${GIT}push\b.*(--force\b|\s-f\b|--force-with-lease\b)`),
|
|
38
|
+
'Force-push is not allowed.',
|
|
39
|
+
],
|
|
40
|
+
[new RegExp(String.raw`^${GIT}\S+\b.*\s--no-verify\b`), 'Skipping git hooks is not allowed.'],
|
|
33
41
|
[
|
|
34
|
-
|
|
42
|
+
/^rm\s+-rf?\s+(\/|~|\$HOME|\.\.?)(\s|$)/,
|
|
35
43
|
'Refusing a destructive delete of a root, home or parent directory.',
|
|
36
44
|
],
|
|
37
|
-
|
|
38
|
-
|
|
45
|
+
];
|
|
46
|
+
for (const [re, why] of RUNS) {
|
|
47
|
+
if (runs(cmd, re, { quoted: false })) block(`Blocked: ${why}\nCommand: ${cmd}`);
|
|
48
|
+
}
|
|
49
|
+
// These read the command whole: a pipe spans commands, and an approval or the log can be written
|
|
50
|
+
// through a quoted path.
|
|
51
|
+
const ALWAYS = [
|
|
52
|
+
[
|
|
53
|
+
/\b(curl|wget)\b[^|]*\|\s*(sh|bash|zsh)\b/,
|
|
54
|
+
'Piping downloads into a shell is not allowed.',
|
|
55
|
+
codeOf(cmd),
|
|
56
|
+
],
|
|
57
|
+
[/\.claude\/approvals/, 'Approvals are created only by a person, with a `!` shell command.', cmd],
|
|
39
58
|
[
|
|
40
59
|
/approval-log\.jsonl/,
|
|
41
60
|
'The approval audit log is appended only by the commit hook; nobody edits it.',
|
|
61
|
+
cmd,
|
|
42
62
|
],
|
|
43
63
|
];
|
|
44
|
-
for (const [re, why] of ALWAYS) {
|
|
45
|
-
if (re.test(
|
|
64
|
+
for (const [re, why, text] of ALWAYS) {
|
|
65
|
+
if (re.test(text)) block(`Blocked: ${why}\nCommand: ${cmd}`);
|
|
46
66
|
}
|
|
47
67
|
const packages = addedPackages(cmd);
|
|
48
|
-
const approves =
|
|
49
|
-
const delegatedMerge =
|
|
68
|
+
const approves = runs(cmd, new RegExp(String.raw`^${CODE_KIT}\s+approve\b`));
|
|
69
|
+
const delegatedMerge = runs(cmd, new RegExp(String.raw`^${CODE_KIT}\s+merge\b`));
|
|
70
|
+
const commits = runs(cmd, new RegExp(String.raw`^${GIT}commit\b`));
|
|
50
71
|
if (error) {
|
|
51
|
-
if (
|
|
72
|
+
if (commits) block(`Blocked: ${error}\nFix the config before committing.`);
|
|
52
73
|
if (approves) block(`Blocked: ${error}\nApprovals wait until the config is valid.`);
|
|
53
74
|
if (delegatedMerge) block(`Blocked: ${error}\nMerges wait until the config is valid.`);
|
|
54
75
|
if (packages.length)
|
|
@@ -62,23 +83,35 @@ const branches = config.branches.protected
|
|
|
62
83
|
// The branch is read before the command runs, so a command that switches to a protected branch and then
|
|
63
84
|
// commits or merges in the same breath is judged by what it does, not by where it starts. Moving a
|
|
64
85
|
// protected branch directly (branch -f, update-ref) is a commit on it by another name.
|
|
65
|
-
const writesHistory =
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
)
|
|
69
|
-
const
|
|
70
|
-
|
|
71
|
-
`\\bgit\\s+branch\\s+(?:\\S+\\s+)*(?:-f|--force|-M|-C)\\b.*\\b(${branches})(?![\\w./-])`,
|
|
72
|
-
).test(cmd) ||
|
|
86
|
+
const writesHistory = runs(
|
|
87
|
+
cmd,
|
|
88
|
+
new RegExp(String.raw`^${GIT}(commit|merge|cherry-pick|rebase|revert|am)\b`),
|
|
89
|
+
);
|
|
90
|
+
const switchesToProtected = runs(
|
|
91
|
+
cmd,
|
|
73
92
|
new RegExp(
|
|
74
|
-
|
|
75
|
-
)
|
|
93
|
+
String.raw`^${GIT}(?:switch|checkout)\s+(?:-[^\s]+\s+)*(${branches})(?![\w./-])(?!\s+--)`,
|
|
94
|
+
),
|
|
95
|
+
);
|
|
96
|
+
const movesProtected =
|
|
97
|
+
runs(
|
|
98
|
+
cmd,
|
|
99
|
+
new RegExp(
|
|
100
|
+
String.raw`^${GIT}branch\s+(?:\S+\s+)*(?:-f|--force|-M|-C)\b.*\b(${branches})(?![\w./-])`,
|
|
101
|
+
),
|
|
102
|
+
) ||
|
|
103
|
+
runs(
|
|
104
|
+
cmd,
|
|
105
|
+
new RegExp(
|
|
106
|
+
String.raw`^${GIT}update-ref\s+(?:-\S+\s+)*(?:refs/heads/)?(${branches})(?![\w./-])`,
|
|
107
|
+
),
|
|
108
|
+
);
|
|
76
109
|
if ((switchesToProtected && writesHistory) || movesProtected) {
|
|
77
110
|
block(
|
|
78
111
|
`Blocked: never commit to, merge into or move ${config.branches.protected.join(' or ')}, even by switching to it first. Work on a branch; a person merges after review${config.approvals.delegate?.merge ? ', or the lead merges a verified branch with `code-kit merge <branch> --delegated`' : ''}.\nCommand: ${cmd}`,
|
|
79
112
|
);
|
|
80
113
|
}
|
|
81
|
-
if (new RegExp(
|
|
114
|
+
if (runs(cmd, new RegExp(String.raw`^${GIT}push\b.*\b(${branches})\b`))) {
|
|
82
115
|
block(
|
|
83
116
|
`Blocked: push to your own branch; a person merges to ${config.branches.protected[0]} after review.\nCommand: ${cmd}`,
|
|
84
117
|
);
|
|
@@ -180,10 +213,7 @@ try {
|
|
|
180
213
|
} catch {
|
|
181
214
|
// not a git repository yet
|
|
182
215
|
}
|
|
183
|
-
if (
|
|
184
|
-
/\bgit\s+(commit|merge|cherry-pick|rebase|revert)\b/.test(cmd) &&
|
|
185
|
-
config.branches.protected.includes(branch)
|
|
186
|
-
) {
|
|
216
|
+
if (writesHistory && config.branches.protected.includes(branch)) {
|
|
187
217
|
block(
|
|
188
218
|
`Blocked: never commit or merge on ${branch}. Work on a branch; a person merges after review.`,
|
|
189
219
|
);
|
|
@@ -253,6 +283,8 @@ function recordApprovals() {
|
|
|
253
283
|
}),
|
|
254
284
|
);
|
|
255
285
|
for (const file of files) {
|
|
286
|
+
// Concluding a merge: what arrives as the other branch has it was logged there, with its approvals.
|
|
287
|
+
if (arrivesWithMerge(root, file, { staged: true })) continue;
|
|
256
288
|
const entry = protectedEntry(file, config);
|
|
257
289
|
const granted = entry && approval(root, entry.approval, actor);
|
|
258
290
|
const byDependency = actor.kind === 'lane' && dependencyChange(actor, file, root, config);
|
|
@@ -283,12 +315,30 @@ function recordApprovals() {
|
|
|
283
315
|
grantedAt: null,
|
|
284
316
|
});
|
|
285
317
|
}
|
|
318
|
+
// A dependency approval is used up by the commit that adds its package to a manifest or lockfile.
|
|
319
|
+
const manifests = files.filter((f) => isDependencyFile(f));
|
|
320
|
+
if (manifests.length && actor.kind !== 'readonly') {
|
|
321
|
+
// The lines each manifest gains on HEAD, read from the working tree: this hook runs before
|
|
322
|
+
// `git add … && git commit` has staged anything, and a new manifest isn't tracked yet.
|
|
323
|
+
const added = manifests
|
|
324
|
+
.flatMap((f) => {
|
|
325
|
+
const before = new Set(git('show', `HEAD:${f}`).split('\n'));
|
|
326
|
+
const now = existsSync(join(root, f)) ? readFileSync(join(root, f), 'utf8') : '';
|
|
327
|
+
return now.split('\n').filter((l) => !before.has(l));
|
|
328
|
+
})
|
|
329
|
+
.join('\n');
|
|
330
|
+
for (const g of dependencyGrants(root, actor)) {
|
|
331
|
+
const pkg = g.name.slice('dep-'.length).replaceAll('+', '/');
|
|
332
|
+
const quoted = pkg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
333
|
+
if (new RegExp(`["'\\s/]${quoted}["'@=:\\s]`).test(added)) useApproval(root, g.name, actor);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
286
336
|
if (lines.length === 0) return;
|
|
287
337
|
appendFileSync(join(root, APPROVAL_LOG), `${lines.join('\n')}\n`);
|
|
288
338
|
git('add', APPROVAL_LOG);
|
|
289
339
|
}
|
|
290
340
|
|
|
291
|
-
if (
|
|
341
|
+
if (commits) {
|
|
292
342
|
recordApprovals();
|
|
293
343
|
const scan = spawnSync('gitleaks', ['protect', '--staged', '--redact', '--no-banner'], {
|
|
294
344
|
cwd: root,
|
package/hooks/hooks.json
CHANGED
package/hooks/lane-audit.mjs
CHANGED
|
@@ -5,7 +5,14 @@
|
|
|
5
5
|
import { readFileSync } from 'node:fs';
|
|
6
6
|
import { spawnSync } from 'node:child_process';
|
|
7
7
|
import { join } from 'node:path';
|
|
8
|
-
import {
|
|
8
|
+
import {
|
|
9
|
+
APPROVAL_LOG,
|
|
10
|
+
LANE_FILE,
|
|
11
|
+
actorFor,
|
|
12
|
+
actorRoot,
|
|
13
|
+
arrivesWithMerge,
|
|
14
|
+
writeProblem,
|
|
15
|
+
} from './lib/rules.mjs';
|
|
9
16
|
|
|
10
17
|
// The commit hook appends to the approval log and stages it; if that commit then fails, the
|
|
11
18
|
// appended lines are left uncommitted. That is the only change to the log that is not a problem.
|
|
@@ -36,11 +43,15 @@ export function auditProblems(input, config) {
|
|
|
36
43
|
const root = actorRoot(input);
|
|
37
44
|
if (!root) return [];
|
|
38
45
|
const actor = actorFor(input, root, config);
|
|
39
|
-
return
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
46
|
+
return (
|
|
47
|
+
changedFiles(root)
|
|
48
|
+
.filter((rel) => !(rel === APPROVAL_LOG && appendedOnly(root, rel)))
|
|
49
|
+
// Mid-merge, the incoming branch's changes are its own, not this actor's writes.
|
|
50
|
+
.filter((rel) => !arrivesWithMerge(root, rel))
|
|
51
|
+
.map((rel) => [rel, writeProblem(actor, rel, root, config)])
|
|
52
|
+
.filter(([, problem]) => problem)
|
|
53
|
+
.map(([rel, problem]) => `${rel}: ${problem.split('\n')[0]}`)
|
|
54
|
+
);
|
|
44
55
|
}
|
|
45
56
|
|
|
46
57
|
if (import.meta.url === `file://${process.argv[1]}`) {
|
package/hooks/lib/config.mjs
CHANGED
|
@@ -31,6 +31,9 @@ export function loadConfig(projectDir) {
|
|
|
31
31
|
/** The rules the hooks enforce: the project's config, the kit's defaults, and any active adapters. */
|
|
32
32
|
export const effectiveConfig = (raw, root) => applyAdapters(withDefaults(raw), raw, root);
|
|
33
33
|
|
|
34
|
+
/** An anyActor entry's glob: entries are globs, or { glob, reviewer } naming who reviews changes to it. */
|
|
35
|
+
export const anyActorGlob = (e) => (typeof e === 'string' ? e : e?.glob);
|
|
36
|
+
|
|
34
37
|
/** The engine's fixed rules, merged into the project's: the kit and Claude's own files belong to the lead. */
|
|
35
38
|
export function withDefaults(c) {
|
|
36
39
|
return {
|
|
@@ -39,7 +42,11 @@ export function withDefaults(c) {
|
|
|
39
42
|
paths: [...c.lead.paths, '.claude/**'],
|
|
40
43
|
outside: [...(c.lead.outside ?? []), ...CLAUDE_OWN],
|
|
41
44
|
},
|
|
42
|
-
anyActor: [...(c.anyActor ?? []), '.claude/state/**'],
|
|
45
|
+
anyActor: [...(c.anyActor ?? []).map(anyActorGlob), '.claude/state/**'],
|
|
46
|
+
// Who reviews changes to files any agent may write; the lead unless an entry names a lane.
|
|
47
|
+
anyActorReviewers: (c.anyActor ?? [])
|
|
48
|
+
.filter((e) => typeof e === 'object' && e?.reviewer)
|
|
49
|
+
.map((e) => ({ glob: e.glob, reviewer: e.reviewer })),
|
|
43
50
|
protected: [KIT, ...(c.protected ?? []).filter((p) => p.glob !== KIT.glob)],
|
|
44
51
|
layers: c.layers ?? [],
|
|
45
52
|
importAliases: c.importAliases ?? {},
|
|
@@ -71,7 +78,12 @@ function delegateRules(d) {
|
|
|
71
78
|
],
|
|
72
79
|
minWeeklyDownloads: d.dependencies.minWeeklyDownloads ?? 10_000,
|
|
73
80
|
maxMonthsSinceRelease: d.dependencies.maxMonthsSinceRelease ?? 18,
|
|
74
|
-
|
|
81
|
+
// true (any), false (none), or the kinds allowed: binary, build (lib/registry.mjs).
|
|
82
|
+
allowInstallScripts:
|
|
83
|
+
d.dependencies.allowInstallScripts === true ||
|
|
84
|
+
(Array.isArray(d.dependencies.allowInstallScripts)
|
|
85
|
+
? d.dependencies.allowInstallScripts
|
|
86
|
+
: false),
|
|
75
87
|
}
|
|
76
88
|
: null,
|
|
77
89
|
};
|
|
@@ -113,9 +125,20 @@ export function validate(c) {
|
|
|
113
125
|
c.lead?.outside === undefined || isList(c.lead.outside),
|
|
114
126
|
'"lead.outside" must be a list of globs',
|
|
115
127
|
);
|
|
116
|
-
need(c.anyActor === undefined || isList(c.anyActor), '"anyActor" must be a list of globs');
|
|
117
128
|
validateLanes(c, need);
|
|
118
129
|
const lanes = Object.keys(isObj(c.lanes) ? c.lanes : {});
|
|
130
|
+
need(
|
|
131
|
+
c.anyActor === undefined ||
|
|
132
|
+
(Array.isArray(c.anyActor) &&
|
|
133
|
+
c.anyActor.every(
|
|
134
|
+
(e) =>
|
|
135
|
+
isStr(e) ||
|
|
136
|
+
(isObj(e) &&
|
|
137
|
+
isStr(e.glob) &&
|
|
138
|
+
(e.reviewer === undefined || e.reviewer === 'lead' || lanes.includes(e.reviewer))),
|
|
139
|
+
)),
|
|
140
|
+
'"anyActor" must be a list of globs, or { "glob", "reviewer" } with the lead or a lane as reviewer',
|
|
141
|
+
);
|
|
119
142
|
each('protected', (e, at) => {
|
|
120
143
|
need(isStr(e.glob) && isStr(e.why), `${at} needs "glob" and "why"`);
|
|
121
144
|
need(
|
|
@@ -159,8 +182,10 @@ export function validate(c) {
|
|
|
159
182
|
(dep.licences === undefined || isList(dep.licences)) &&
|
|
160
183
|
isCount(dep.minWeeklyDownloads) &&
|
|
161
184
|
isCount(dep.maxMonthsSinceRelease) &&
|
|
162
|
-
[undefined, true, false].includes(dep.allowInstallScripts)
|
|
163
|
-
|
|
185
|
+
([undefined, true, false].includes(dep.allowInstallScripts) ||
|
|
186
|
+
(isList(dep.allowInstallScripts) &&
|
|
187
|
+
dep.allowInstallScripts.every((k) => ['binary', 'build', 'other'].includes(k))))))),
|
|
188
|
+
'"approvals.delegate" must be { protected?: [approval names], merge?: true|false, dependencies?: { licences?, minWeeklyDownloads?, maxMonthsSinceRelease?, allowInstallScripts?: true|false|["binary","build","other"] } }',
|
|
164
189
|
);
|
|
165
190
|
need(
|
|
166
191
|
c.branches === undefined || isList(c.branches?.protected),
|
package/hooks/lib/diff.mjs
CHANGED
|
@@ -2,6 +2,10 @@
|
|
|
2
2
|
// lanes, layers and rules added, removed or changed, and which files would change owner.
|
|
3
3
|
import { ownerOf } from './rules.mjs';
|
|
4
4
|
|
|
5
|
+
/** An anyActor entry in words: its glob, with its reviewer when named. */
|
|
6
|
+
const anyActorText = (e) =>
|
|
7
|
+
typeof e === 'string' ? e : `${e.glob} (reviewed by ${e.reviewer ?? 'the lead'})`;
|
|
8
|
+
|
|
5
9
|
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
6
10
|
const lists = (a = [], b = []) => ({
|
|
7
11
|
added: b.filter((x) => !a.includes(x)),
|
|
@@ -95,7 +99,7 @@ export function diffConfigs(before, after) {
|
|
|
95
99
|
for (const [label, a, b] of [
|
|
96
100
|
['lead paths', before.lead?.paths, after.lead?.paths],
|
|
97
101
|
['lead outside paths', before.lead?.outside, after.lead?.outside],
|
|
98
|
-
['any-actor paths', before.anyActor, after.anyActor],
|
|
102
|
+
['any-actor paths', before.anyActor?.map(anyActorText), after.anyActor?.map(anyActorText)],
|
|
99
103
|
['protected branches', before.branches?.protected, after.branches?.protected],
|
|
100
104
|
]) {
|
|
101
105
|
const change = listChange('', a, b);
|
package/hooks/lib/next.mjs
CHANGED
|
@@ -150,7 +150,9 @@ export function nextStep(root, base) {
|
|
|
150
150
|
);
|
|
151
151
|
|
|
152
152
|
const ids = (state) => status.stories.filter((s) => s.state === state).map((s) => s.id);
|
|
153
|
-
const [review, building, blocked] = ['review', 'in progress', 'blocked'].map(
|
|
153
|
+
const [review, building, blocked, fixes] = ['review', 'in progress', 'blocked', 'sent back'].map(
|
|
154
|
+
ids,
|
|
155
|
+
);
|
|
154
156
|
// A ready story with a gap (unknown lane, a requirement no spec defines) waits for the plan's fix.
|
|
155
157
|
const defined = new Set(status.requirements.map((r) => r.id));
|
|
156
158
|
const buildable = (s) =>
|
|
@@ -167,13 +169,22 @@ export function nextStep(root, base) {
|
|
|
167
169
|
`${unbuildable.join(', ')} can't be dispatched until the plan's gaps are fixed.`,
|
|
168
170
|
);
|
|
169
171
|
const then = [];
|
|
170
|
-
|
|
172
|
+
// A sent-back story goes back to its lane with the review's findings, before new work starts.
|
|
173
|
+
const toDispatch = [...fixes, ...ready];
|
|
174
|
+
if (review.length && toDispatch.length)
|
|
175
|
+
then.push({ step: 'dispatch', args: toDispatch.join(' ') });
|
|
171
176
|
if (forLead.length) then.push({ step: 'lead', args: forLead.join(' ') });
|
|
172
177
|
if (review.length)
|
|
173
178
|
return result('review', `${review.join(', ')} finished and wait for review.`, {
|
|
174
179
|
args: review.join(' '),
|
|
175
180
|
then,
|
|
176
181
|
});
|
|
182
|
+
if (fixes.length)
|
|
183
|
+
return result(
|
|
184
|
+
'dispatch',
|
|
185
|
+
`${fixes.join(', ')} ${fixes.length === 1 ? 'was' : 'were'} sent back and ${fixes.length === 1 ? 'waits' : 'wait'} for the lane's fix: dispatch ${fixes.length === 1 ? 'it' : 'each'} again with the review's findings${ready.length ? `, then ${ready.join(', ')}` : ''}.`,
|
|
186
|
+
{ args: toDispatch.join(' '), then },
|
|
187
|
+
);
|
|
177
188
|
if (ready.length)
|
|
178
189
|
return result('dispatch', `${ready.join(', ')} can start: their dependencies are done.`, {
|
|
179
190
|
args: ready.join(' '),
|
package/hooks/lib/plan.mjs
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
import { execFileSync } from 'node:child_process';
|
|
8
8
|
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
|
9
9
|
import { join } from 'node:path';
|
|
10
|
+
import { sentBack } from './reviews.mjs';
|
|
10
11
|
|
|
11
12
|
export const REQUIREMENT = /\b(?!ST-)([A-Z][A-Z0-9]*-\d+)\b/g;
|
|
12
13
|
const STORY_HEADING = /^###\s+(ST-\d+)\b\s*(.*)$/;
|
|
@@ -125,18 +126,22 @@ function worktrees(root) {
|
|
|
125
126
|
* Where each story is. The plan's `done` stands (the lead marks it after merging, and merged
|
|
126
127
|
* branches are often deleted or squashed). Otherwise git decides: a branch with commits not in
|
|
127
128
|
* `base` is in review; one level with it is in progress, or done once the plan had it in review.
|
|
128
|
-
*
|
|
129
|
-
*
|
|
129
|
+
* A branch still at the commit a review sent back is `sent back`, waiting for its lane's fix.
|
|
130
|
+
* Without a branch, the plan's status stands. A story is `blocked` while a story it depends on
|
|
131
|
+
* isn't done, whatever its branch holds; a todo story whose dependencies are done is `ready`.
|
|
130
132
|
*/
|
|
131
133
|
export function storyStates(root, stories, base) {
|
|
132
134
|
const trees = worktrees(root);
|
|
135
|
+
const backs = sentBack(root);
|
|
133
136
|
const states = stories.map((story) => {
|
|
134
137
|
const branch = storyBranch(story);
|
|
135
138
|
const ref = story.lane ? branchRef(root, branch) : null;
|
|
136
139
|
const ahead = ref ? Number(git(root, 'rev-list', '--count', `${base}..${ref}`) ?? 0) : 0;
|
|
137
140
|
let state = story.status;
|
|
138
141
|
if (ref && story.status !== 'done') {
|
|
139
|
-
|
|
142
|
+
const head = backs[branch] ? git(root, 'rev-parse', ref) : null;
|
|
143
|
+
if (head && head === backs[branch].sha) state = 'sent back';
|
|
144
|
+
else if (ahead > 0) state = 'review';
|
|
140
145
|
else state = story.status === 'review' ? 'done' : 'in progress';
|
|
141
146
|
}
|
|
142
147
|
return {
|
|
@@ -151,9 +156,10 @@ export function storyStates(root, stories, base) {
|
|
|
151
156
|
});
|
|
152
157
|
const done = new Set(states.filter((s) => s.state === 'done').map((s) => s.id));
|
|
153
158
|
for (const s of states) {
|
|
154
|
-
if (s.state
|
|
159
|
+
if (s.state === 'done') continue;
|
|
155
160
|
s.waitingOn = s.dependsOn.filter((d) => !done.has(d));
|
|
156
|
-
|
|
161
|
+
if (s.waitingOn.length) s.state = 'blocked';
|
|
162
|
+
else if (s.state === 'todo') s.state = 'ready';
|
|
157
163
|
}
|
|
158
164
|
return states;
|
|
159
165
|
}
|
|
@@ -200,13 +206,18 @@ export function buildStatus(root, config, base, files) {
|
|
|
200
206
|
let state = 'no story';
|
|
201
207
|
if (r.removed) state = 'removed';
|
|
202
208
|
else if (covering.length && covering.every((s) => s.state === 'done')) state = 'done';
|
|
203
|
-
else if (covering.some((s) => ['in progress', 'review', 'done'].includes(s.state)))
|
|
209
|
+
else if (covering.some((s) => ['in progress', 'review', 'sent back', 'done'].includes(s.state)))
|
|
204
210
|
state = 'in progress';
|
|
205
211
|
else if (covering.length) state = 'todo';
|
|
206
212
|
return { ...r, state, stories: covering.map((s) => s.id), tests: tested[r.id] ?? [] };
|
|
207
213
|
});
|
|
208
214
|
const drift = stories
|
|
209
|
-
.filter(
|
|
215
|
+
.filter(
|
|
216
|
+
(s) =>
|
|
217
|
+
!['ready', 'blocked'].includes(s.state) &&
|
|
218
|
+
s.state !== s.status &&
|
|
219
|
+
!(s.state === 'sent back' && s.status === 'in progress'),
|
|
220
|
+
)
|
|
210
221
|
.map((s) => ({ story: s.id, plan: s.status, actual: s.state }));
|
|
211
222
|
return { stories, requirements: byRequirement, problems, drift };
|
|
212
223
|
}
|
package/hooks/lib/registry.mjs
CHANGED
|
@@ -12,7 +12,35 @@ export const packageOf = (approvalName) =>
|
|
|
12
12
|
|
|
13
13
|
const INSTALL_SCRIPTS = ['preinstall', 'install', 'postinstall'];
|
|
14
14
|
|
|
15
|
-
|
|
15
|
+
// Kinds of install script, for the rule's allowInstallScripts:
|
|
16
|
+
// binary fetches a prebuilt binary for this platform (esbuild, sharp): a prebuild tool, or a script
|
|
17
|
+
// beside optional dependencies built per platform;
|
|
18
|
+
// build compiles native code from source (node-gyp);
|
|
19
|
+
// other anything else: code the package runs on install.
|
|
20
|
+
const BINARY_TOOLS =
|
|
21
|
+
/\b(prebuild-install|node-pre-gyp|node-gyp-build|prebuildify|napi-postinstall)\b/;
|
|
22
|
+
const PLATFORM = /(darwin|linux|win32|windows|freebsd|android|musl|arm64|x64|ia32)/;
|
|
23
|
+
|
|
24
|
+
/** The kind of install script a package version runs (binary, build or other), or null for none. */
|
|
25
|
+
export function installScriptKind(version) {
|
|
26
|
+
const scripts = INSTALL_SCRIPTS.map((s) => version?.scripts?.[s]).filter(Boolean);
|
|
27
|
+
if (!scripts.length) return null;
|
|
28
|
+
const text = scripts.join(' && ');
|
|
29
|
+
const perPlatform = Object.keys(version?.optionalDependencies ?? {}).filter((d) =>
|
|
30
|
+
PLATFORM.test(d),
|
|
31
|
+
);
|
|
32
|
+
if (BINARY_TOOLS.test(text) || perPlatform.length >= 2) return 'binary';
|
|
33
|
+
if (/\bnode-gyp\b|\bcmake-js\b/.test(text)) return 'build';
|
|
34
|
+
return 'other';
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const KIND_WORDS = {
|
|
38
|
+
binary: 'downloads a prebuilt binary',
|
|
39
|
+
build: 'compiles native code',
|
|
40
|
+
other: 'runs its own code',
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
/** { licence, weeklyDownloads, lastRelease (ISO), installScripts, installScriptKind } for `pkg`, or { error }. */
|
|
16
44
|
export async function npmFacts(pkg) {
|
|
17
45
|
const name = pkg.startsWith('@')
|
|
18
46
|
? `@${encodeURIComponent(pkg.slice(1))}`
|
|
@@ -34,6 +62,7 @@ export async function npmFacts(pkg) {
|
|
|
34
62
|
weeklyDownloads,
|
|
35
63
|
lastRelease: (latest && doc.time?.[latest]) ?? doc.time?.modified ?? null,
|
|
36
64
|
installScripts: INSTALL_SCRIPTS.some((s) => version?.scripts?.[s]),
|
|
65
|
+
installScriptKind: installScriptKind(version),
|
|
37
66
|
};
|
|
38
67
|
} catch (e) {
|
|
39
68
|
return { error: `couldn't reach the npm registry (${e.message})` };
|
|
@@ -57,7 +86,12 @@ export function dependencyRuleProblems(facts, rule, now = Date.now()) {
|
|
|
57
86
|
problems.push(
|
|
58
87
|
`its last release was ${Number.isFinite(months) ? `${Math.floor(months)} months` : 'never'} ago, over ${rule.maxMonthsSinceRelease}`,
|
|
59
88
|
);
|
|
60
|
-
if (facts.installScripts
|
|
61
|
-
|
|
89
|
+
if (facts.installScripts) {
|
|
90
|
+
const kind = facts.installScriptKind ?? 'other';
|
|
91
|
+
const allowed =
|
|
92
|
+
rule.allowInstallScripts === true ||
|
|
93
|
+
(Array.isArray(rule.allowInstallScripts) && rule.allowInstallScripts.includes(kind));
|
|
94
|
+
if (!allowed) problems.push(`installing it runs a script that ${KIND_WORDS[kind]}`);
|
|
95
|
+
}
|
|
62
96
|
return problems;
|
|
63
97
|
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// The lead's send-backs: which commit of a branch a review sent back. Until the branch moves past it,
|
|
2
|
+
// status reads the story as waiting for its lane's fix, not as finished again (and next proposes the
|
|
3
|
+
// fix, not a second review of the same commits). Kept beside the requests, in the main checkout.
|
|
4
|
+
import { appendFileSync, mkdirSync, readFileSync } from 'node:fs';
|
|
5
|
+
import { dirname, join } from 'node:path';
|
|
6
|
+
import { projectWorktrees } from './rules.mjs';
|
|
7
|
+
|
|
8
|
+
export const REVIEWS_FILE = '.claude/state/reviews.jsonl';
|
|
9
|
+
const reviewsFile = (root) => join(projectWorktrees(root)[0] ?? root, REVIEWS_FILE);
|
|
10
|
+
|
|
11
|
+
/** Records that the review of `branch` at commit `sha` sent it back, and why. */
|
|
12
|
+
export function recordSentBack(root, branch, sha, reason, now = Date.now()) {
|
|
13
|
+
const file = reviewsFile(root);
|
|
14
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
15
|
+
appendFileSync(
|
|
16
|
+
file,
|
|
17
|
+
`${JSON.stringify({ at: new Date(now).toISOString(), branch, sha, verdict: 'sent back', reason: reason ?? null })}\n`,
|
|
18
|
+
);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** The latest send-back of each branch: { branch: { at, sha, reason } }. */
|
|
22
|
+
export function sentBack(root) {
|
|
23
|
+
const found = {};
|
|
24
|
+
let lines = [];
|
|
25
|
+
try {
|
|
26
|
+
lines = readFileSync(reviewsFile(root), 'utf8').split('\n').filter(Boolean);
|
|
27
|
+
} catch {
|
|
28
|
+
return found;
|
|
29
|
+
}
|
|
30
|
+
for (const line of lines) {
|
|
31
|
+
try {
|
|
32
|
+
const r = JSON.parse(line);
|
|
33
|
+
if (r.verdict === 'sent back' && r.branch && r.sha) found[r.branch] = r;
|
|
34
|
+
} catch {
|
|
35
|
+
// a line being written, or not one of ours
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return found;
|
|
39
|
+
}
|
package/hooks/lib/rules.mjs
CHANGED
|
@@ -20,12 +20,13 @@ import {
|
|
|
20
20
|
readFileSync,
|
|
21
21
|
readdirSync,
|
|
22
22
|
realpathSync,
|
|
23
|
+
rmSync,
|
|
23
24
|
statSync,
|
|
24
25
|
writeFileSync,
|
|
25
26
|
} from 'node:fs';
|
|
26
27
|
import { execFileSync } from 'node:child_process';
|
|
27
28
|
import { homedir } from 'node:os';
|
|
28
|
-
import { dirname, join, relative, resolve } from 'node:path';
|
|
29
|
+
import { basename, dirname, join, relative, resolve } from 'node:path';
|
|
29
30
|
import { fileURLToPath } from 'node:url';
|
|
30
31
|
import { DEPENDENCY_APPROVAL, isDependencyFile } from './dependencies.mjs';
|
|
31
32
|
import { globToRegExp, matchesAny } from './glob.mjs';
|
|
@@ -33,6 +34,23 @@ import { globToRegExp, matchesAny } from './glob.mjs';
|
|
|
33
34
|
export const APPROVAL_LOG = '.claude/approval-log.jsonl';
|
|
34
35
|
export const APPROVALS_DIR = '.claude/approvals';
|
|
35
36
|
export const APPROVAL_MINUTES = 60;
|
|
37
|
+
// A dependency approval lasts until the lane commits the install it allows (the story may resume
|
|
38
|
+
// hours later), and at most a week, so a forgotten one doesn't linger.
|
|
39
|
+
export const DEPENDENCY_APPROVAL_DAYS = 7;
|
|
40
|
+
|
|
41
|
+
/** How long an approval named `name` lasts, in minutes. */
|
|
42
|
+
export const approvalMinutes = (name) =>
|
|
43
|
+
String(name).startsWith(DEPENDENCY_APPROVAL)
|
|
44
|
+
? DEPENDENCY_APPROVAL_DAYS * 24 * 60
|
|
45
|
+
: APPROVAL_MINUTES;
|
|
46
|
+
|
|
47
|
+
/** How long approvals for `names` last, in words. */
|
|
48
|
+
export function approvalLifetime(names) {
|
|
49
|
+
const list = [names].flat();
|
|
50
|
+
return list.every((n) => String(n).startsWith(DEPENDENCY_APPROVAL))
|
|
51
|
+
? `until the install is committed, at most ${DEPENDENCY_APPROVAL_DAYS} days`
|
|
52
|
+
: `for ${APPROVAL_MINUTES} minutes`;
|
|
53
|
+
}
|
|
36
54
|
// Marks a worktree as a lane's, for a person running that lane; the lead creates it, and it is never work.
|
|
37
55
|
export const LANE_FILE = '.lane';
|
|
38
56
|
const NEVER_WRITABLE = [`${APPROVALS_DIR}/**`, APPROVAL_LOG];
|
|
@@ -80,7 +98,7 @@ export function approvalHowTo(names, actor, root, allows = 'these edits', config
|
|
|
80
98
|
: '';
|
|
81
99
|
return (
|
|
82
100
|
`${lines.join('\n')}\n` +
|
|
83
|
-
`(a person runs it; the reason is recorded in ${APPROVAL_LOG}, and it allows ${allows} for ${whom},
|
|
101
|
+
`(a person runs it; the reason is recorded in ${APPROVAL_LOG}, and it allows ${allows} for ${whom}, ${approvalLifetime(names)})${relay}${delegated}`
|
|
84
102
|
);
|
|
85
103
|
}
|
|
86
104
|
|
|
@@ -211,7 +229,7 @@ export function owns(actor, rel, config) {
|
|
|
211
229
|
function inForce(file) {
|
|
212
230
|
if (!existsSync(file) || !statSync(file).isFile()) return null;
|
|
213
231
|
const { mtimeMs } = statSync(file);
|
|
214
|
-
if (Date.now() - mtimeMs >=
|
|
232
|
+
if (Date.now() - mtimeMs >= approvalMinutes(basename(file)) * 60_000) return null;
|
|
215
233
|
const reason = readFileSync(file, 'utf8').trim();
|
|
216
234
|
return reason ? { reason, grantedAt: new Date(mtimeMs).toISOString() } : null;
|
|
217
235
|
}
|
|
@@ -223,6 +241,16 @@ export function approval(root, name, actor) {
|
|
|
223
241
|
return lane ?? inForce(join(dir, name));
|
|
224
242
|
}
|
|
225
243
|
|
|
244
|
+
/** Uses up the approval in force for `name` and `actor`: a dependency approval, once its install is committed. */
|
|
245
|
+
export function useApproval(root, name, actor) {
|
|
246
|
+
const dir = approvalsDir(root);
|
|
247
|
+
for (const file of [
|
|
248
|
+
...(actor?.kind === 'lane' ? [join(dir, actor.lane, name)] : []),
|
|
249
|
+
join(dir, name),
|
|
250
|
+
])
|
|
251
|
+
if (inForce(file)) return rmSync(file, { force: true });
|
|
252
|
+
}
|
|
253
|
+
|
|
226
254
|
const requestsFile = (root) => join(projectWorktrees(root)[0] ?? root, REQUESTS_FILE);
|
|
227
255
|
const sameRequest = (a, b) =>
|
|
228
256
|
a.actor === b.actor &&
|
|
@@ -306,7 +334,7 @@ export function approvalsInForce(root, now = Date.now()) {
|
|
|
306
334
|
}
|
|
307
335
|
const a = inForce(file);
|
|
308
336
|
if (!a) continue;
|
|
309
|
-
const left =
|
|
337
|
+
const left = approvalMinutes(name) - (now - Date.parse(a.grantedAt)) / 60_000;
|
|
310
338
|
found.push({
|
|
311
339
|
name,
|
|
312
340
|
...(lane ? { lane } : {}),
|
|
@@ -336,6 +364,33 @@ export function dependencyGrants(root, actor) {
|
|
|
336
364
|
.filter((g) => g.reason);
|
|
337
365
|
}
|
|
338
366
|
|
|
367
|
+
/**
|
|
368
|
+
* During a merge, whether `rel` is exactly as the incoming branch (MERGE_HEAD) has it: then its change
|
|
369
|
+
* arrives with that branch's history, approvals and audit-log entries, not from the actor concluding
|
|
370
|
+
* the merge. `staged` compares what will be committed; otherwise the working tree. A file both sides
|
|
371
|
+
* delete counts too. verify still holds the branch to its rules afterwards.
|
|
372
|
+
*/
|
|
373
|
+
export function arrivesWithMerge(root, rel, { staged = false } = {}) {
|
|
374
|
+
const run = (...args) => {
|
|
375
|
+
try {
|
|
376
|
+
return execFileSync('git', ['-C', root, ...args], {
|
|
377
|
+
encoding: 'utf8',
|
|
378
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
379
|
+
}).trim();
|
|
380
|
+
} catch {
|
|
381
|
+
return null;
|
|
382
|
+
}
|
|
383
|
+
};
|
|
384
|
+
if (run('rev-parse', '--verify', '--quiet', 'MERGE_HEAD') === null) return false;
|
|
385
|
+
const incoming = run('rev-parse', '--verify', '--quiet', `MERGE_HEAD:${rel}`);
|
|
386
|
+
const mine = staged
|
|
387
|
+
? run('rev-parse', '--verify', '--quiet', `:${rel}`)
|
|
388
|
+
: existsSync(join(root, rel))
|
|
389
|
+
? run('hash-object', '--', rel)
|
|
390
|
+
: null;
|
|
391
|
+
return incoming === mine;
|
|
392
|
+
}
|
|
393
|
+
|
|
339
394
|
/**
|
|
340
395
|
* Whether a dependency approval lets `actor` change `rel`: a manifest or lockfile no other lane owns,
|
|
341
396
|
* changed while the actor has a dependency approval in force. Installing a package rewrites them.
|
|
@@ -415,6 +470,13 @@ export function laneOf(rel, config) {
|
|
|
415
470
|
);
|
|
416
471
|
}
|
|
417
472
|
|
|
473
|
+
/** Who reviews a change to a file any agent may write: the lane an anyActor entry names, else the lead. Null for other files. */
|
|
474
|
+
export function reviewerOf(rel, config) {
|
|
475
|
+
if (!matchesAny(rel, config.anyActor)) return null;
|
|
476
|
+
const named = (config.anyActorReviewers ?? []).find((e) => matchesAny(rel, [e.glob]));
|
|
477
|
+
return named?.reviewer ?? 'lead';
|
|
478
|
+
}
|
|
479
|
+
|
|
418
480
|
export function ownerOf(rel, config) {
|
|
419
481
|
const lane = laneOf(rel, config);
|
|
420
482
|
if (lane) return `${lane} lane / ${config.lanes[lane].agent}`;
|