@warren-dean/code-kit 0.22.1 → 0.24.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 +26 -0
- package/README.md +6 -5
- package/bin/code-kit.mjs +105 -77
- package/hooks/guard-agent.mjs +42 -1
- package/hooks/guard-bash.mjs +62 -17
- package/hooks/lib/checks.mjs +3 -1
- package/hooks/lib/config.mjs +13 -2
- package/hooks/lib/dispatches.mjs +76 -0
- package/hooks/lib/harness.mjs +2 -2
- package/hooks/lib/instructions.mjs +2 -1
- package/hooks/lib/journal.mjs +16 -3
- package/hooks/lib/next.mjs +37 -27
- package/hooks/lib/plan.mjs +6 -1
- package/hooks/lib/registry.mjs +70 -3
- package/hooks/lib/report.mjs +76 -7
- package/hooks/lib/rules.mjs +12 -4
- package/hooks/lib/schedule.mjs +46 -0
- package/hooks/lib/verify.mjs +27 -8
- package/hooks/lib/worktrees.mjs +286 -0
- package/hooks/mod/decisions.mjs +27 -1
- package/hooks/mod/loop.mjs +11 -7
- package/hooks/mod/register.mjs +68 -10
- package/hooks/mod/register.test.ts +145 -2
- package/hooks/mod/view.mjs +14 -2
- package/hooks/session.mjs +20 -3
- package/package.json +1 -1
- package/skills/dispatch/SKILL.md +1 -1
- package/skills/init/SKILL.md +1 -1
- package/skills/spec-design/SKILL.md +1 -1
- package/templates/plan.md +2 -1
package/hooks/lib/report.mjs
CHANGED
|
@@ -7,7 +7,16 @@
|
|
|
7
7
|
// them the new-issue link to open; a report someone already filed gets a comment instead of a second issue.
|
|
8
8
|
import { createHash } from 'node:crypto';
|
|
9
9
|
import { execFileSync } from 'node:child_process';
|
|
10
|
-
import {
|
|
10
|
+
import {
|
|
11
|
+
appendFileSync,
|
|
12
|
+
closeSync,
|
|
13
|
+
mkdirSync,
|
|
14
|
+
openSync,
|
|
15
|
+
readFileSync,
|
|
16
|
+
realpathSync,
|
|
17
|
+
statSync,
|
|
18
|
+
unlinkSync,
|
|
19
|
+
} from 'node:fs';
|
|
11
20
|
import { homedir, platform, release } from 'node:os';
|
|
12
21
|
import { dirname, join } from 'node:path';
|
|
13
22
|
import { fileURLToPath } from 'node:url';
|
|
@@ -21,6 +30,47 @@ const PLUGIN = JSON.parse(
|
|
|
21
30
|
export const REPO = PLUGIN.repository.replace(/^https:\/\/github\.com\//, '').replace(/\.git$/, '');
|
|
22
31
|
|
|
23
32
|
const fileOf = (root) => join(projectWorktrees(root)[0] ?? root, REPORTS_FILE);
|
|
33
|
+
/** REPORT-3: held while a report is being sent, so a second Send can't file it again. */
|
|
34
|
+
const sendingOf = (root, id) => join(dirname(fileOf(root)), `report-sending-${id}`);
|
|
35
|
+
/** A send that's held its claim this long died before it finished, and the report is a draft again. */
|
|
36
|
+
const SENDING_MS = 5 * 60 * 1000;
|
|
37
|
+
|
|
38
|
+
function sendingSince(root, id, now = Date.now()) {
|
|
39
|
+
try {
|
|
40
|
+
const at = statSync(sendingOf(root, id)).mtimeMs;
|
|
41
|
+
return now - at < SENDING_MS ? at : null;
|
|
42
|
+
} catch {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Claims the send of `id`, or says it's being sent already: one claim, whichever process asks first. */
|
|
48
|
+
function claimSend(root, id, now = Date.now()) {
|
|
49
|
+
const file = sendingOf(root, id);
|
|
50
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
51
|
+
for (let tries = 0; tries < 2; tries++) {
|
|
52
|
+
try {
|
|
53
|
+
closeSync(openSync(file, 'wx'));
|
|
54
|
+
return true;
|
|
55
|
+
} catch {
|
|
56
|
+
if (sendingSince(root, id, now) !== null) return false;
|
|
57
|
+
try {
|
|
58
|
+
unlinkSync(file);
|
|
59
|
+
} catch {
|
|
60
|
+
// taken by another send meanwhile
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const releaseSend = (root, id) => {
|
|
68
|
+
try {
|
|
69
|
+
unlinkSync(sendingOf(root, id));
|
|
70
|
+
} catch {
|
|
71
|
+
// gone already
|
|
72
|
+
}
|
|
73
|
+
};
|
|
24
74
|
|
|
25
75
|
function records(root) {
|
|
26
76
|
try {
|
|
@@ -86,8 +136,8 @@ function bodyOf(r) {
|
|
|
86
136
|
}
|
|
87
137
|
|
|
88
138
|
/**
|
|
89
|
-
* Every report, oldest first: { id, at, by, title, body, fingerprint, state: 'draft' | '
|
|
90
|
-
* sent: { at, url, comment } | null }.
|
|
139
|
+
* Every report, oldest first: { id, at, by, title, body, fingerprint, state: 'draft' | 'sending' | 'sent' |
|
|
140
|
+
* 'discarded', sent: { at, url, comment } | null }. `sending`: a Send is filing it now.
|
|
91
141
|
*/
|
|
92
142
|
export function readReports(root) {
|
|
93
143
|
const byId = new Map();
|
|
@@ -102,7 +152,9 @@ export function readReports(root) {
|
|
|
102
152
|
});
|
|
103
153
|
if (r.kind === 'discarded') d.state = 'discarded';
|
|
104
154
|
}
|
|
105
|
-
return [...byId.values()].map(({ kind, ...r }) =>
|
|
155
|
+
return [...byId.values()].map(({ kind, ...r }) =>
|
|
156
|
+
r.state === 'draft' && sendingSince(root, r.id) !== null ? { ...r, state: 'sending' } : r,
|
|
157
|
+
);
|
|
106
158
|
}
|
|
107
159
|
|
|
108
160
|
export const draftReports = (root) => readReports(root).filter((r) => r.state === 'draft');
|
|
@@ -175,9 +227,24 @@ const gh = (args) =>
|
|
|
175
227
|
* it already, otherwise a new issue; without a working `gh`, nothing is sent and the link is returned.
|
|
176
228
|
*/
|
|
177
229
|
export function sendReport(root, id, now = Date.now()) {
|
|
178
|
-
const
|
|
179
|
-
if (!
|
|
180
|
-
if (
|
|
230
|
+
const before = readReports(root).find((x) => x.id === id);
|
|
231
|
+
if (!before) return { ok: false, why: `There's no report ${id}.` };
|
|
232
|
+
if (before.state === 'sending') return { ok: false, why: `${id} is being sent already.` };
|
|
233
|
+
if (before.state !== 'draft') return { ok: false, why: `${id} was ${before.state} already.` };
|
|
234
|
+
if (!claimSend(root, id, now)) return { ok: false, why: `${id} is being sent already.` };
|
|
235
|
+
try {
|
|
236
|
+
// Another send may have finished between the read and the claim.
|
|
237
|
+
const r = readReports(root).find((x) => x.id === id);
|
|
238
|
+
if (r.sent || r.state === 'discarded')
|
|
239
|
+
return { ok: false, why: `${id} was ${r.sent ? 'sent' : 'discarded'} already.` };
|
|
240
|
+
return fileIssue(root, r, now);
|
|
241
|
+
} finally {
|
|
242
|
+
releaseSend(root, id);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function fileIssue(root, r, now) {
|
|
247
|
+
const { id } = r;
|
|
181
248
|
let url;
|
|
182
249
|
let comment = false;
|
|
183
250
|
try {
|
|
@@ -240,6 +307,8 @@ export function sendReport(root, id, now = Date.now()) {
|
|
|
240
307
|
export function discardReport(root, id, now = Date.now()) {
|
|
241
308
|
const r = readReports(root).find((x) => x.id === id);
|
|
242
309
|
if (!r) return { ok: false, why: `There's no report ${id}.` };
|
|
310
|
+
if (r.state === 'sending')
|
|
311
|
+
return { ok: false, why: `${id} is being sent, so it can't be discarded.` };
|
|
243
312
|
if (r.state !== 'draft') return { ok: false, why: `${id} was ${r.state} already.` };
|
|
244
313
|
append(root, { kind: 'discarded', id, at: new Date(now).toISOString() });
|
|
245
314
|
return { ok: true };
|
package/hooks/lib/rules.mjs
CHANGED
|
@@ -388,7 +388,11 @@ function requestRecords(root) {
|
|
|
388
388
|
export const readRequests = (root) => requestRecords(root).filter((r) => !r.drop);
|
|
389
389
|
|
|
390
390
|
/** CARD-7: whether a request was dropped (the person dismissed it, or the lead said it's no longer needed). */
|
|
391
|
-
|
|
391
|
+
// A drop written before drops carried the request's session (code-kit issue #78) matches it whatever its session.
|
|
392
|
+
const droppedIn = (drops, r) =>
|
|
393
|
+
drops.some(
|
|
394
|
+
(d) => d.of === r.at && sameRequest('session' in d ? d : { ...d, session: r.session }, r),
|
|
395
|
+
);
|
|
392
396
|
|
|
393
397
|
/**
|
|
394
398
|
* CARD-7: drops open requests: `which` is a request's number in `openRequests`' order (1 is the
|
|
@@ -409,7 +413,7 @@ export function dropRequests(root, which, { by, reason = null }, now = Date.now(
|
|
|
409
413
|
for (const r of picked)
|
|
410
414
|
appendFileSync(
|
|
411
415
|
file,
|
|
412
|
-
`${JSON.stringify({ drop: true, of: r.at, actor: r.actor, names: r.names, what: r.what, by, reason, at: new Date(now).toISOString() })}\n`,
|
|
416
|
+
`${JSON.stringify({ drop: true, of: r.at, actor: r.actor, session: r.session ?? null, names: r.names, what: r.what, by, reason, at: new Date(now).toISOString() })}\n`,
|
|
413
417
|
);
|
|
414
418
|
return { ok: true, dropped: picked };
|
|
415
419
|
}
|
|
@@ -849,8 +853,12 @@ function specCheckProblem(rel, root) {
|
|
|
849
853
|
return null; // not a git worktree: nothing to key the report on
|
|
850
854
|
}
|
|
851
855
|
if (rel === report) return null;
|
|
852
|
-
|
|
853
|
-
|
|
856
|
+
// In the worktree, or in the main checkout, where it's kept when a worktree goes (#55).
|
|
857
|
+
const read = (dir) => {
|
|
858
|
+
const file = join(dir, report);
|
|
859
|
+
return existsSync(file) && /\|\s*Requirement\s*\|/i.test(readFileSync(file, 'utf8'));
|
|
860
|
+
};
|
|
861
|
+
if (read(root) || read(projectWorktrees(root)[0] ?? root)) return null;
|
|
854
862
|
return `Run the spec-check skill before writing code on this branch. Save its report (the requirement table, questions and recommendation) to ${report}, then continue.`;
|
|
855
863
|
}
|
|
856
864
|
|
package/hooks/lib/schedule.mjs
CHANGED
|
@@ -84,3 +84,49 @@ export function pickPerLane(stories, { fixes = [], ready = [], busy = new Set(),
|
|
|
84
84
|
opened: startOrder,
|
|
85
85
|
};
|
|
86
86
|
}
|
|
87
|
+
|
|
88
|
+
/** SCHED-3: the models a lane agent steps up through, smallest first. */
|
|
89
|
+
export const STORY_MODELS = ['haiku', 'sonnet', 'opus'];
|
|
90
|
+
/** SCHED-3: the sizes a story's `**Size:**` may give, and the model each starts on. */
|
|
91
|
+
export const SIZE_MODELS = { small: 'haiku', medium: 'sonnet', large: 'opus' };
|
|
92
|
+
|
|
93
|
+
/** SET-4: the `model:` an agent file's frontmatter names, or null. */
|
|
94
|
+
export function agentFileModel(text) {
|
|
95
|
+
const front = /^---\r?\n([\s\S]*?)\r?\n---/.exec(String(text ?? ''))?.[1] ?? '';
|
|
96
|
+
return /^model:\s*['"]?([^'"\s]+)['"]?\s*$/m.exec(front)?.[1] ?? null;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const times = (n) => (n === 1 ? 'once' : n === 2 ? 'twice' : `${n} times`);
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* SCHED-3: the model a story's lane agent runs on, and why, as { model, why }. The lane's agent file
|
|
103
|
+
* keeps its own model (other than `inherit`). Otherwise the story's size picks it (Sonnet without one),
|
|
104
|
+
* a security requirement raises it to Opus, a fix to Sonnet at least, and each send-back of its branch
|
|
105
|
+
* one step more, to Opus at most.
|
|
106
|
+
*/
|
|
107
|
+
export function storyModel({
|
|
108
|
+
size = null,
|
|
109
|
+
security = false,
|
|
110
|
+
fix = false,
|
|
111
|
+
sentBack = 0,
|
|
112
|
+
fileModel = null,
|
|
113
|
+
} = {}) {
|
|
114
|
+
if (fileModel && fileModel !== 'inherit')
|
|
115
|
+
return { model: fileModel, why: `its lane's agent file names ${fileModel}` };
|
|
116
|
+
const rank = (m) => STORY_MODELS.indexOf(m);
|
|
117
|
+
let model = SIZE_MODELS[size] ?? 'sonnet';
|
|
118
|
+
const why = [SIZE_MODELS[size] ? `a ${size} story` : 'no size in the plan'];
|
|
119
|
+
const raise = (to, reason) => {
|
|
120
|
+
if (rank(to) <= rank(model)) return;
|
|
121
|
+
model = to;
|
|
122
|
+
why.push(reason);
|
|
123
|
+
};
|
|
124
|
+
if (security) raise('opus', 'it cites a security requirement');
|
|
125
|
+
if (fix) raise('sonnet', 'a fix proves its bug with a test');
|
|
126
|
+
if (sentBack > 0)
|
|
127
|
+
raise(
|
|
128
|
+
STORY_MODELS[Math.min(STORY_MODELS.length - 1, rank(model) + sentBack)],
|
|
129
|
+
`sent back ${times(sentBack)}`,
|
|
130
|
+
);
|
|
131
|
+
return { model, why: why.join(', ') };
|
|
132
|
+
}
|
package/hooks/lib/verify.mjs
CHANGED
|
@@ -164,6 +164,27 @@ function currentBranchOf(root) {
|
|
|
164
164
|
}
|
|
165
165
|
}
|
|
166
166
|
|
|
167
|
+
// The runtime's own noise, which says nothing about whether the check passed (#57).
|
|
168
|
+
const NOISE = [
|
|
169
|
+
/^\(node:\d+\) \[?\w*\]? ?(DeprecationWarning|ExperimentalWarning|Warning)\b/,
|
|
170
|
+
/^\(Use `node --trace-(deprecation|warnings) /,
|
|
171
|
+
/^\s*$/,
|
|
172
|
+
];
|
|
173
|
+
const FAILING = /\b(fail(ed|ing|s)?|error|✗|✘|×|expected|received|assert|panic|traceback)\b/i;
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* What a failed check printed, as the lead needs it (#57): the runtime's warnings left out, the lines
|
|
177
|
+
* that name a failure first (up to 20), then the last 20 lines.
|
|
178
|
+
*/
|
|
179
|
+
export function failureOutput(output) {
|
|
180
|
+
const lines = String(output ?? '')
|
|
181
|
+
.split('\n')
|
|
182
|
+
.filter((l) => !NOISE.some((re) => re.test(l)));
|
|
183
|
+
const tail = lines.slice(-20);
|
|
184
|
+
const named = lines.filter((l) => FAILING.test(l) && !tail.includes(l)).slice(0, 20);
|
|
185
|
+
return [...named, ...(named.length ? ['…'] : []), ...tail].join('\n');
|
|
186
|
+
}
|
|
187
|
+
|
|
167
188
|
/**
|
|
168
189
|
* The files changed, every problem with the branch, grouped as { ownership, protected, layers,
|
|
169
190
|
* baseline, design, tests, regression, standards, checks }, and the checks `skipped` because a tool isn't
|
|
@@ -301,6 +322,7 @@ export function verifyBranch({
|
|
|
301
322
|
if (fix) found.regression.push(...proveFix({ root, from, base, changed, config, fix }));
|
|
302
323
|
|
|
303
324
|
let skipped = [];
|
|
325
|
+
let unfinished = false;
|
|
304
326
|
if (checks) {
|
|
305
327
|
const actor = lane
|
|
306
328
|
? { kind: 'lane', lane, label: `${lane} lane branch` }
|
|
@@ -308,13 +330,10 @@ export function verifyBranch({
|
|
|
308
330
|
const ran = runChecks(config, changed, root, actor);
|
|
309
331
|
skipped = ran.skipped;
|
|
310
332
|
const { failure } = ran;
|
|
311
|
-
if (failure)
|
|
312
|
-
found.checks.push(
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
.slice(-40)
|
|
316
|
-
.join('\n')}`.trim(),
|
|
317
|
-
);
|
|
333
|
+
if (failure) {
|
|
334
|
+
found.checks.push(`${failure.title}\n${failureOutput(failure.output)}`.trim());
|
|
335
|
+
unfinished = Boolean(failure.timedOut);
|
|
336
|
+
}
|
|
318
337
|
}
|
|
319
|
-
return { changed, found, skipped };
|
|
338
|
+
return { changed, found, skipped, unfinished };
|
|
320
339
|
}
|
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
// The project's worktrees, and taking away the ones that are done (docs/specs/20-lean-lead.md, LEAN-6 and
|
|
2
|
+
// LEAN-8). Every lane agent works in a worktree of its own, each with its own install, so a project that
|
|
3
|
+
// merges a few stories a day gains a gigabyte or more of checkouts a day unless they go as their work
|
|
4
|
+
// merges. A worktree goes once its branch's own commits are merged and it holds nothing uncommitted, and
|
|
5
|
+
// no agent is still at work in it; one that's merged but still holds changes is the person's to decide,
|
|
6
|
+
// and what it held is kept as a patch. code-kit's own leftovers go too: a temporary merge checkout an
|
|
7
|
+
// interrupted merge left, a worktree whose folder is gone, and folders under .claude/worktrees git no
|
|
8
|
+
// longer knows.
|
|
9
|
+
import { spawnSync } from 'node:child_process';
|
|
10
|
+
import {
|
|
11
|
+
copyFileSync,
|
|
12
|
+
existsSync,
|
|
13
|
+
mkdirSync,
|
|
14
|
+
readdirSync,
|
|
15
|
+
realpathSync,
|
|
16
|
+
rmSync,
|
|
17
|
+
statSync,
|
|
18
|
+
writeFileSync,
|
|
19
|
+
} from 'node:fs';
|
|
20
|
+
import { tmpdir } from 'node:os';
|
|
21
|
+
import { basename, dirname, join } from 'node:path';
|
|
22
|
+
import { laneClaims } from './laneclaims.mjs';
|
|
23
|
+
import { storyOfBranch } from './teamfacts.mjs';
|
|
24
|
+
|
|
25
|
+
export const WORKTREES_DIR = '.claude/worktrees';
|
|
26
|
+
export const DISCARDED_DIR = '.claude/state/discarded';
|
|
27
|
+
/** A temporary merge checkout this old belongs to a merge that didn't finish. */
|
|
28
|
+
export const TEMP_MERGE_MS = 30 * 60_000;
|
|
29
|
+
const TEMP_MERGE = /^code-kit-merge-/;
|
|
30
|
+
|
|
31
|
+
const git = (cwd, ...args) => spawnSync('git', ['-C', cwd, ...args], { encoding: 'utf8' });
|
|
32
|
+
const real = (p) => {
|
|
33
|
+
try {
|
|
34
|
+
return realpathSync(p);
|
|
35
|
+
} catch {
|
|
36
|
+
return p;
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
const alive = (pid) => {
|
|
40
|
+
try {
|
|
41
|
+
process.kill(pid, 0);
|
|
42
|
+
return true;
|
|
43
|
+
} catch (e) {
|
|
44
|
+
return e.code === 'EPERM';
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
/** The base branch's ref a worktree's branch is merged into: the first protected branch, or its remote. */
|
|
49
|
+
export function baseRef(root, config) {
|
|
50
|
+
const name = config.branches?.protected?.[0];
|
|
51
|
+
if (!name) return null;
|
|
52
|
+
return (
|
|
53
|
+
[name, `origin/${name}`].find(
|
|
54
|
+
(r) => git(root, 'rev-parse', '--verify', '--quiet', r).status === 0,
|
|
55
|
+
) ?? null
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Whether the branch has commits of its own: a branch made from the base for an agent just dispatched
|
|
61
|
+
* is contained in the base too, but its work hasn't started, let alone merged (code-kit issue #61).
|
|
62
|
+
*/
|
|
63
|
+
function hasOwnCommits(root, branch) {
|
|
64
|
+
const log = git(root, 'reflog', 'show', '--format=%gs', `refs/heads/${branch}`);
|
|
65
|
+
if (log.status !== 0 || !log.stdout.trim()) return true; // no reflog: judged by the base alone
|
|
66
|
+
return log.stdout
|
|
67
|
+
.trim()
|
|
68
|
+
.split('\n')
|
|
69
|
+
.some((l) => !/^branch: Created from /.test(l));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* LEAN-6: each worktree but the main checkout: { path, branch, story, merged, clean, changes, report,
|
|
74
|
+
* kind, missing, locked: { reason, pid, live } | null, agentAtWork }. `kind` is `agent` (under
|
|
75
|
+
* .claude/worktrees), `merge` (a temporary merge checkout) or `other` (one the person made). `clean` and
|
|
76
|
+
* `changes` are null where they weren't read: an unmerged worktree stays whatever it holds (cleanOf reads it).
|
|
77
|
+
*/
|
|
78
|
+
export function worktrees(root, config, now = Date.now()) {
|
|
79
|
+
const list = git(root, 'worktree', 'list', '--porcelain');
|
|
80
|
+
if (list.status !== 0) return [];
|
|
81
|
+
const main = list.stdout.split('\n\n')[0];
|
|
82
|
+
const mainPath = /^worktree (.+)$/m.exec(main)?.[1] ?? root;
|
|
83
|
+
const from = baseRef(root, config);
|
|
84
|
+
const claims = laneClaims(mainPath, now).filter((c) => !c.stale);
|
|
85
|
+
const agents = real(join(mainPath, WORKTREES_DIR));
|
|
86
|
+
const temp = real(tmpdir());
|
|
87
|
+
return list.stdout
|
|
88
|
+
.split('\n\n')
|
|
89
|
+
.filter(Boolean)
|
|
90
|
+
.slice(1)
|
|
91
|
+
.map((block) => {
|
|
92
|
+
const path = /^worktree (.+)$/m.exec(block)?.[1];
|
|
93
|
+
const branch = /^branch refs\/heads\/(.+)$/m.exec(block)?.[1] ?? null;
|
|
94
|
+
const lockLine = /^locked(?: (.*))?$/m.exec(block);
|
|
95
|
+
const pid = Number(/\bpid (\d+)/.exec(lockLine?.[1] ?? '')?.[1]) || null;
|
|
96
|
+
const missing = !existsSync(path);
|
|
97
|
+
const where = real(path);
|
|
98
|
+
const kind = where.startsWith(`${agents}/`)
|
|
99
|
+
? 'agent'
|
|
100
|
+
: where.startsWith(`${temp}/`) && TEMP_MERGE.test(basename(path))
|
|
101
|
+
? 'merge'
|
|
102
|
+
: 'other';
|
|
103
|
+
const story = branch ? storyOfBranch(branch) : null;
|
|
104
|
+
const merged = Boolean(
|
|
105
|
+
branch &&
|
|
106
|
+
from &&
|
|
107
|
+
spawnSync('git', ['merge-base', '--is-ancestor', branch, from], { cwd: root }).status ===
|
|
108
|
+
0 &&
|
|
109
|
+
hasOwnCommits(root, branch),
|
|
110
|
+
);
|
|
111
|
+
// Read only where it decides anything: an unmerged worktree stays whatever it holds.
|
|
112
|
+
const status =
|
|
113
|
+
missing || (!merged && kind !== 'other') ? null : git(path, 'status', '--porcelain');
|
|
114
|
+
const changes =
|
|
115
|
+
status?.status === 0 ? status.stdout.split('\n').filter(Boolean).length : null;
|
|
116
|
+
const lane = branch?.includes('/') ? branch.split('/')[0] : null;
|
|
117
|
+
const report = branch ? `.claude/state/reports/${branch.replace(/[^\w.-]+/g, '_')}.md` : null;
|
|
118
|
+
return {
|
|
119
|
+
path,
|
|
120
|
+
branch,
|
|
121
|
+
story,
|
|
122
|
+
kind,
|
|
123
|
+
missing,
|
|
124
|
+
merged,
|
|
125
|
+
clean: changes === null ? null : changes === 0,
|
|
126
|
+
changes,
|
|
127
|
+
// What it holds, as git status words it: the first ten.
|
|
128
|
+
files: status?.status === 0 ? status.stdout.split('\n').filter(Boolean).slice(0, 10) : [],
|
|
129
|
+
report: report && !missing && existsSync(join(path, report)) ? report : null,
|
|
130
|
+
locked: lockLine
|
|
131
|
+
? { reason: lockLine[1] ?? null, pid, live: pid ? alive(pid) : true }
|
|
132
|
+
: null,
|
|
133
|
+
// A lane's agent still holds its claim on this story: it may yet commit here.
|
|
134
|
+
agentAtWork: Boolean(
|
|
135
|
+
lane && claims.some((c) => c.lane === lane && (c.story ?? null) === (story ?? c.story)),
|
|
136
|
+
),
|
|
137
|
+
age: missing ? null : now - statSync(path).mtimeMs,
|
|
138
|
+
};
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Whether a worktree holds nothing uncommitted, read now where worktrees() didn't. */
|
|
143
|
+
export function cleanOf(w) {
|
|
144
|
+
if (w.clean !== null) return w.clean;
|
|
145
|
+
if (w.missing) return true;
|
|
146
|
+
const status = git(w.path, 'status', '--porcelain');
|
|
147
|
+
return status.status === 0 && !status.stdout.trim();
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Why a worktree stays, in words, or null when it's done with and can go. */
|
|
151
|
+
export function keptBecause(w) {
|
|
152
|
+
if (w.missing) return null;
|
|
153
|
+
if (w.kind === 'merge') return w.age < TEMP_MERGE_MS ? 'a merge may be using it now' : null;
|
|
154
|
+
if (w.kind === 'other') return "it isn't one code-kit made; release it by name if it's done";
|
|
155
|
+
if (w.locked && !w.locked.pid)
|
|
156
|
+
return `it's locked${w.locked.reason ? ` (${w.locked.reason})` : ''}`;
|
|
157
|
+
if (!w.branch) return 'it has no branch checked out';
|
|
158
|
+
if (!w.merged) return "its branch isn't merged";
|
|
159
|
+
if (w.agentAtWork) return "its lane's agent is still at work on it";
|
|
160
|
+
if (!w.clean)
|
|
161
|
+
return `it's merged, but holds ${w.changes} uncommitted change${w.changes === 1 ? '' : 's'}`;
|
|
162
|
+
return null;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Folders under .claude/worktrees that no worktree is registered at: what a removal left behind. */
|
|
166
|
+
export function strayFolders(root, list) {
|
|
167
|
+
const dir = join(root, WORKTREES_DIR);
|
|
168
|
+
let names = [];
|
|
169
|
+
try {
|
|
170
|
+
names = readdirSync(dir, { withFileTypes: true })
|
|
171
|
+
.filter((d) => d.isDirectory())
|
|
172
|
+
.map((d) => d.name);
|
|
173
|
+
} catch {
|
|
174
|
+
return [];
|
|
175
|
+
}
|
|
176
|
+
const known = new Set(list.map((w) => real(w.path)));
|
|
177
|
+
return names
|
|
178
|
+
.map((n) => join(dir, n))
|
|
179
|
+
.filter((p) => !known.has(real(p)) && !existsSync(join(p, '.git')));
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* A worktree's report moved to the main checkout, so the next agent on its story still reads it, and its
|
|
184
|
+
* spec-check report, so that agent can carry on writing code on the branch (#55).
|
|
185
|
+
*/
|
|
186
|
+
function keepReport(root, w) {
|
|
187
|
+
const keep = (rel) => {
|
|
188
|
+
if (!rel || !existsSync(join(w.path, rel))) return;
|
|
189
|
+
mkdirSync(dirname(join(root, rel)), { recursive: true });
|
|
190
|
+
copyFileSync(join(w.path, rel), join(root, rel));
|
|
191
|
+
};
|
|
192
|
+
keep(w.report);
|
|
193
|
+
if (w.branch) keep(`.claude/state/spec-check/${w.branch.replace(/[^\w.-]+/g, '_')}.md`);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Removes one worktree, its report kept and its branch left. A lock held by Claude Code for an agent
|
|
198
|
+
* that has finished (its lane's claim on the story ended) doesn't keep it: `force` removes it anyway.
|
|
199
|
+
*/
|
|
200
|
+
export function removeWorktree(root, w, { force = false } = {}) {
|
|
201
|
+
if (w.missing) return { ok: true };
|
|
202
|
+
keepReport(root, w);
|
|
203
|
+
const locked = Boolean(w.locked);
|
|
204
|
+
const args = [
|
|
205
|
+
'worktree',
|
|
206
|
+
'remove',
|
|
207
|
+
...(force || locked ? ['--force'] : []),
|
|
208
|
+
...(locked ? ['--force'] : []),
|
|
209
|
+
w.path,
|
|
210
|
+
];
|
|
211
|
+
const removed = git(root, ...args);
|
|
212
|
+
return removed.status === 0 ? { ok: true } : { ok: false, why: removed.stderr.trim() };
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* LEAN-8: takes away every worktree that's done with (keptBecause is null), git's records of worktrees
|
|
217
|
+
* whose folders are gone, and the stray folders. Returns { removed: [label], kept: [{ label, why }] }.
|
|
218
|
+
*/
|
|
219
|
+
export function pruneWorktrees(root, config, now = Date.now()) {
|
|
220
|
+
const list = worktrees(root, config, now);
|
|
221
|
+
const removed = [];
|
|
222
|
+
const kept = [];
|
|
223
|
+
for (const w of list) {
|
|
224
|
+
const label = w.branch ?? w.path;
|
|
225
|
+
const why = keptBecause(w);
|
|
226
|
+
if (why) {
|
|
227
|
+
kept.push({ label, why, branch: w.branch, changes: w.changes, kind: w.kind });
|
|
228
|
+
continue;
|
|
229
|
+
}
|
|
230
|
+
if (w.missing) continue;
|
|
231
|
+
const r = removeWorktree(root, w, { force: w.kind === 'merge' });
|
|
232
|
+
if (r.ok) removed.push(`${label}${w.report ? ` (its report kept at ${w.report})` : ''}`);
|
|
233
|
+
else
|
|
234
|
+
kept.push({
|
|
235
|
+
label,
|
|
236
|
+
why: `git wouldn't remove it: ${r.why.split('\n')[0]}`,
|
|
237
|
+
branch: w.branch,
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
if (list.some((w) => w.missing)) {
|
|
241
|
+
git(root, 'worktree', 'prune');
|
|
242
|
+
for (const w of list.filter((x) => x.missing))
|
|
243
|
+
removed.push(`${w.branch ?? w.path} (its folder was gone)`);
|
|
244
|
+
}
|
|
245
|
+
for (const p of strayFolders(root, list)) {
|
|
246
|
+
rmSync(p, { recursive: true, force: true });
|
|
247
|
+
removed.push(`${p.slice(root.length + 1)} (left behind, not a worktree)`);
|
|
248
|
+
}
|
|
249
|
+
return { removed, kept };
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* LEAN-8: the person discards a merged worktree that still holds changes. What it held is kept first,
|
|
254
|
+
* as a patch under .claude/state/discarded, with the files nobody had added; then it goes.
|
|
255
|
+
*/
|
|
256
|
+
export function discardWorktree(root, config, branch, now = Date.now()) {
|
|
257
|
+
const w = worktrees(root, config, now).find((x) => x.branch === branch || x.path === branch);
|
|
258
|
+
if (!w) return { ok: false, why: `No worktree has ${branch} checked out.` };
|
|
259
|
+
if (!w.merged)
|
|
260
|
+
return {
|
|
261
|
+
ok: false,
|
|
262
|
+
why: `${branch} isn't merged, so its worktree is work in progress: release it once it's committed.`,
|
|
263
|
+
};
|
|
264
|
+
if (w.agentAtWork)
|
|
265
|
+
return {
|
|
266
|
+
ok: false,
|
|
267
|
+
why: `The ${branch.split('/')[0]} lane's agent is still at work on ${branch}.`,
|
|
268
|
+
};
|
|
269
|
+
let patch = null;
|
|
270
|
+
if (!w.clean) {
|
|
271
|
+
git(w.path, 'add', '-A');
|
|
272
|
+
const diff = spawnSync('git', ['-C', w.path, 'diff', '--cached', '--binary', 'HEAD'], {
|
|
273
|
+
encoding: 'utf8',
|
|
274
|
+
maxBuffer: 256 * 1024 * 1024,
|
|
275
|
+
});
|
|
276
|
+
patch = join(
|
|
277
|
+
DISCARDED_DIR,
|
|
278
|
+
`${branch.replace(/[^\w.-]+/g, '_')}-${new Date(now).toISOString().replace(/[:.]/g, '-')}.patch`,
|
|
279
|
+
);
|
|
280
|
+
mkdirSync(join(root, DISCARDED_DIR), { recursive: true });
|
|
281
|
+
writeFileSync(join(root, patch), diff.stdout ?? '');
|
|
282
|
+
}
|
|
283
|
+
const r = removeWorktree(root, w, { force: true });
|
|
284
|
+
if (!r.ok) return { ok: false, why: `git wouldn't remove it: ${r.why.split('\n')[0]}` };
|
|
285
|
+
return { ok: true, patch, report: w.report };
|
|
286
|
+
}
|
package/hooks/mod/decisions.mjs
CHANGED
|
@@ -20,6 +20,7 @@ export const DECISION_KINDS = new Set([
|
|
|
20
20
|
'question',
|
|
21
21
|
'brief',
|
|
22
22
|
'report',
|
|
23
|
+
'worktree',
|
|
23
24
|
'waiting',
|
|
24
25
|
]);
|
|
25
26
|
|
|
@@ -56,6 +57,9 @@ const EFFECT = {
|
|
|
56
57
|
sendReport:
|
|
57
58
|
"Files it on code-kit's GitHub under your account (a comment instead, if it's filed already).",
|
|
58
59
|
discardReport: "It's not sent, and goes.",
|
|
60
|
+
keepWorktree: 'It stays as it is, and comes back next session.',
|
|
61
|
+
discardWorktree:
|
|
62
|
+
'The worktree goes. What it held is kept as a patch under .claude/state/discarded, to apply again if you need it.',
|
|
59
63
|
};
|
|
60
64
|
|
|
61
65
|
/**
|
|
@@ -89,6 +93,12 @@ function eachDecision(line) {
|
|
|
89
93
|
}));
|
|
90
94
|
if (line.kind === 'report')
|
|
91
95
|
return (line.reports ?? [line.report]).map((r) => ({ ...line, text: r.title, report: r }));
|
|
96
|
+
if (line.kind === 'worktree')
|
|
97
|
+
return (line.worktrees ?? [line.worktree]).map((w) => ({
|
|
98
|
+
...line,
|
|
99
|
+
text: `${w.branch} is merged, and its worktree holds uncommitted changes`,
|
|
100
|
+
worktree: w,
|
|
101
|
+
}));
|
|
92
102
|
return [line];
|
|
93
103
|
}
|
|
94
104
|
|
|
@@ -121,6 +131,11 @@ function optionsOf(line) {
|
|
|
121
131
|
{ id: 'sendReport', label: 'Send' },
|
|
122
132
|
{ id: 'discardReport', label: 'Discard' },
|
|
123
133
|
];
|
|
134
|
+
if (line.kind === 'worktree')
|
|
135
|
+
return [
|
|
136
|
+
{ id: 'discardWorktree', label: 'Discard' },
|
|
137
|
+
{ id: 'keepWorktree', label: 'Keep' },
|
|
138
|
+
];
|
|
124
139
|
// LOOP-11: what the lead waits on, read from its reply: its answers, or the person's own words.
|
|
125
140
|
if (line.kind === 'waiting' && line.waiting.kind === 'person' && line.waiting.question)
|
|
126
141
|
return [
|
|
@@ -148,6 +163,7 @@ const TAG = {
|
|
|
148
163
|
question: 'question',
|
|
149
164
|
brief: 'your brief',
|
|
150
165
|
report: 'bug report',
|
|
166
|
+
worktree: 'worktree',
|
|
151
167
|
waiting: 'the lead',
|
|
152
168
|
};
|
|
153
169
|
|
|
@@ -195,6 +211,11 @@ function headlineOf(line, story) {
|
|
|
195
211
|
};
|
|
196
212
|
if (line.kind === 'report')
|
|
197
213
|
return { headline: line.report.title, sub: "drafted by an agent, for code-kit's GitHub" };
|
|
214
|
+
if (line.kind === 'worktree')
|
|
215
|
+
return {
|
|
216
|
+
headline: `${line.worktree.branch}'s worktree still holds ${line.worktree.changes} uncommitted change${line.worktree.changes === 1 ? '' : 's'}`,
|
|
217
|
+
sub: 'its branch is merged',
|
|
218
|
+
};
|
|
198
219
|
if (line.kind === 'waiting' && line.waiting.question)
|
|
199
220
|
return { headline: line.waiting.question, sub: 'from the lead, which waits on it' };
|
|
200
221
|
return { headline: line.text, sub: story ? `${story.id} ${story.title ?? ''}` : '' };
|
|
@@ -244,6 +265,8 @@ function whyOf(line, check) {
|
|
|
244
265
|
return 'You stopped the lead mid-turn, so the loop leaves the lead to you until you say.';
|
|
245
266
|
if (line.kind === 'waiting' && line.waiting.kind === 'blocked')
|
|
246
267
|
return "The lead was asked to take this step and didn't, so the loop won't ask again until you say.";
|
|
268
|
+
if (line.kind === 'worktree')
|
|
269
|
+
return "Its branch is merged, but something in its worktree was changed and never committed. Only you can tell whether that's work or leftovers, and the worktree holds a full install, so it takes disk space until it goes.";
|
|
247
270
|
if (line.kind === 'report')
|
|
248
271
|
return "code-kit got in an agent's way. It's sent under your GitHub account to a public repository, so read what it says first.";
|
|
249
272
|
return null;
|
|
@@ -347,7 +370,10 @@ export function decisionCards(lines, context = {}) {
|
|
|
347
370
|
(line.question?.blocks ? `${line.question.story} waits on your answer.` : null) ??
|
|
348
371
|
(line.waiting?.label ? `The loop's last step: ${line.waiting.label}` : null) ??
|
|
349
372
|
(line.denial ? clip(line.denial.command ?? line.denial.what, 400) : null) ??
|
|
350
|
-
(line.report ? line.report.body : null)
|
|
373
|
+
(line.report ? line.report.body : null) ??
|
|
374
|
+
(line.worktree?.files?.length
|
|
375
|
+
? `${line.worktree.files.join('\n')}${line.worktree.changes > line.worktree.files.length ? `\n… and ${line.worktree.changes - line.worktree.files.length} more` : ''}`
|
|
376
|
+
: null),
|
|
351
377
|
settled,
|
|
352
378
|
why: whyOf(line, check),
|
|
353
379
|
options: optionsOf(line).map((a) => ({
|
package/hooks/mod/loop.mjs
CHANGED
|
@@ -315,21 +315,25 @@ export const answeredPrompt = (question, answer) => {
|
|
|
315
315
|
: `The person says: ${said} Carry on with it.`;
|
|
316
316
|
};
|
|
317
317
|
|
|
318
|
-
|
|
319
|
-
export function agentFileModel(text) {
|
|
320
|
-
const front = /^---\r?\n([\s\S]*?)\r?\n---/.exec(String(text ?? ''))?.[1] ?? '';
|
|
321
|
-
return /^model:\s*['"]?([^'"\s]+)['"]?\s*$/m.exec(front)?.[1] ?? null;
|
|
322
|
-
}
|
|
318
|
+
export { agentFileModel } from '../lib/schedule.mjs';
|
|
323
319
|
|
|
324
320
|
/**
|
|
325
321
|
* SET-4: the model to start a lane agent on, or null to leave the spawn as it is: a model the lead's
|
|
326
322
|
* call names wins, then the lane agent file's own (other than `inherit`), then `harness.agents.lanes.model`.
|
|
323
|
+
* Set to `story` (SCHED-3), it's the model `next` gave the story, `story`, or null where it gave none.
|
|
327
324
|
*/
|
|
328
|
-
export function laneModel({
|
|
325
|
+
export function laneModel({
|
|
326
|
+
type,
|
|
327
|
+
model = null,
|
|
328
|
+
lanes = {},
|
|
329
|
+
setting = null,
|
|
330
|
+
fileModel = null,
|
|
331
|
+
story = null,
|
|
332
|
+
}) {
|
|
329
333
|
if (model || !setting) return null;
|
|
330
334
|
if (!Object.values(lanes).some((l) => l.agent === type)) return null;
|
|
331
335
|
if (fileModel && fileModel !== 'inherit') return null;
|
|
332
|
-
return setting;
|
|
336
|
+
return setting === 'story' ? story : setting;
|
|
333
337
|
}
|
|
334
338
|
|
|
335
339
|
/** LEAN-3: compacting a context below this share of its window isn't worth the summary it costs. */
|