knitmd 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +2 -2
- package/dist/approval.js +37 -0
- package/dist/cli.js +359 -0
- package/dist/commands/attach.js +77 -0
- package/dist/commands/basic.js +503 -0
- package/dist/commands/flow.js +340 -0
- package/dist/commands/hooks.js +257 -0
- package/dist/commands/mcp.js +91 -0
- package/dist/commands/renumber.js +95 -0
- package/dist/commands/report.js +187 -0
- package/dist/commands/setup.js +232 -0
- package/dist/commands/sync.js +146 -0
- package/dist/ctx.js +8 -0
- package/dist/git.js +65 -0
- package/dist/inbox.js +15 -0
- package/dist/linked.js +58 -0
- package/dist/person.js +32 -0
- package/dist/publish.js +95 -0
- package/dist/tracker.js +146 -0
- package/package.json +37 -4
- package/templates/ci/code.yml +41 -0
- package/templates/ci/tracker-sync.yml +38 -0
- package/templates/ci/tracker.yml +50 -0
- package/templates/tracker/GUIDE.md +124 -0
- package/templates/tracker/proj.yml +60 -0
- package/templates/tracker/templates/bug.md +22 -0
- package/templates/tracker/templates/default.md +10 -0
- package/templates/tracker/templates/epic.md +10 -0
- package/templates/tracker/templates/feature.md +14 -0
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { basename, dirname, join } from 'node:path';
|
|
4
|
+
import { isDone, checkTicket, formatProblem, isClosed, isStarted, openDependencies, appendLog, criteria, parseDoc, serialize, set, str, branchFor, branchPattern, fileName, findTicket, repoPath, ticketId, workRoot, UserError, textTable, } from '@knitmd/core';
|
|
5
|
+
import { guardStatusChange } from '../approval.js';
|
|
6
|
+
import { displayPath, resolveTicketArg, save } from '../tracker.js';
|
|
7
|
+
import { currentBranch, git, hasRemote, refExists, showFile, tryGit } from '../git.js';
|
|
8
|
+
import { currentPerson } from '../person.js';
|
|
9
|
+
import { canPush, publish } from '../publish.js';
|
|
10
|
+
import { today } from '../ctx.js';
|
|
11
|
+
import { open } from './basic.js';
|
|
12
|
+
function fetchQuietly(ctx, root, remote) {
|
|
13
|
+
if (!hasRemote(root, remote))
|
|
14
|
+
return;
|
|
15
|
+
if (tryGit(root, ['fetch', '--quiet', '--prune', remote]) === undefined) {
|
|
16
|
+
ctx.err(`warning: could not fetch ${remote}; claims may be out of date`);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
/** Open claims: claim branches on the remote of the repository the developer works in. */
|
|
20
|
+
export function listClaims(t, ctx, opts = {}) {
|
|
21
|
+
const root = workRoot(t);
|
|
22
|
+
const remote = t.config.git.remote;
|
|
23
|
+
if (opts.fetch !== false)
|
|
24
|
+
fetchQuietly(ctx, root, remote);
|
|
25
|
+
const out = tryGit(root, [
|
|
26
|
+
'for-each-ref',
|
|
27
|
+
'--format=%(refname)%09%(committerdate:short)%09%(authorname)',
|
|
28
|
+
`refs/remotes/${remote}/`,
|
|
29
|
+
]);
|
|
30
|
+
const pattern = branchPattern(t.config);
|
|
31
|
+
const claims = [];
|
|
32
|
+
for (const line of (out ?? '').split('\n').filter(Boolean)) {
|
|
33
|
+
const [ref, last, author] = line.split('\t');
|
|
34
|
+
const branch = ref.slice(`refs/remotes/${remote}/`.length);
|
|
35
|
+
const m = pattern.exec(branch);
|
|
36
|
+
if (!m)
|
|
37
|
+
continue;
|
|
38
|
+
const id = m[1].toUpperCase();
|
|
39
|
+
let assignee;
|
|
40
|
+
if (!t.code) {
|
|
41
|
+
const doc = t.tickets.find((d) => ticketId(d) === id);
|
|
42
|
+
const text = doc ? showFile(root, ref, repoPath(t, doc.path)) : undefined;
|
|
43
|
+
if (text)
|
|
44
|
+
assignee = str(parseDoc('ticket', doc.path, text), 'assignee');
|
|
45
|
+
}
|
|
46
|
+
else {
|
|
47
|
+
const doc = t.tickets.find((d) => ticketId(d) === id);
|
|
48
|
+
if (doc)
|
|
49
|
+
assignee = str(doc, 'assignee');
|
|
50
|
+
}
|
|
51
|
+
claims.push({ id, branch, last, author, ...(assignee ? { assignee } : {}) });
|
|
52
|
+
}
|
|
53
|
+
return claims;
|
|
54
|
+
}
|
|
55
|
+
/** IDs that someone works on: started in the tracker, or with a claim branch. */
|
|
56
|
+
export function claimedIds(t, ctx, opts = {}) {
|
|
57
|
+
const ids = new Set(t.tickets.filter((d) => isStarted(t, str(d, 'status'))).map(ticketId));
|
|
58
|
+
for (const c of listClaims(t, ctx, opts))
|
|
59
|
+
ids.add(c.id);
|
|
60
|
+
return ids;
|
|
61
|
+
}
|
|
62
|
+
function message(subject, trailer, id) {
|
|
63
|
+
return `${subject}\n\n${trailer}: ${id}`;
|
|
64
|
+
}
|
|
65
|
+
function claimFields(t, ctx, doc, person) {
|
|
66
|
+
set(doc, 'status', t.config.workflow.start);
|
|
67
|
+
set(doc, 'assignee', person);
|
|
68
|
+
if (!str(doc, 'started'))
|
|
69
|
+
set(doc, 'started', today(ctx));
|
|
70
|
+
}
|
|
71
|
+
// ---------------------------------------------------------------- start
|
|
72
|
+
export function cmdStart(ctx, o, idArg) {
|
|
73
|
+
if (!idArg)
|
|
74
|
+
throw new UserError('usage: nit start <ID> [--worktree]');
|
|
75
|
+
const t = open(ctx, o, { fresh: true });
|
|
76
|
+
const doc = findTicket(t, idArg);
|
|
77
|
+
const id = ticketId(doc);
|
|
78
|
+
const cfg = t.config;
|
|
79
|
+
const status = str(doc, 'status');
|
|
80
|
+
if (isClosed(t, status))
|
|
81
|
+
throw new UserError(`${id} is already ${status}`, 1);
|
|
82
|
+
if (isStarted(t, status))
|
|
83
|
+
throw new UserError(`${id} is already ${status} (assignee: ${str(doc, 'assignee') ?? '?'})`, 1);
|
|
84
|
+
if (str(doc, 'type') === 'epic' && !o.force)
|
|
85
|
+
throw new UserError(`${id} is an epic: start one of its child tickets`, 1);
|
|
86
|
+
const blockers = openDependencies(t, doc);
|
|
87
|
+
if (blockers.length > 0 && !o.force)
|
|
88
|
+
throw new UserError(`${id} is blocked by ${blockers.join(', ')} (use --force to start anyway)`, 1);
|
|
89
|
+
const person = currentPerson(ctx, cfg, workRoot(t));
|
|
90
|
+
const after = parseDoc('ticket', doc.path, serialize(doc));
|
|
91
|
+
set(after, 'assignee', person);
|
|
92
|
+
set(after, 'status', cfg.workflow.start);
|
|
93
|
+
guardStatusChange(ctx, t, workRoot(t), after, status, cfg.workflow.start);
|
|
94
|
+
const work = workRoot(t);
|
|
95
|
+
const remote = cfg.git.remote;
|
|
96
|
+
const branch = branchFor(cfg, id);
|
|
97
|
+
const push = canPush(t, work, o);
|
|
98
|
+
if (hasRemote(work, remote))
|
|
99
|
+
fetchQuietly(ctx, work, remote);
|
|
100
|
+
if (push) {
|
|
101
|
+
const existing = tryGit(work, ['ls-remote', '--heads', remote, `refs/heads/${branch}`]);
|
|
102
|
+
if (existing)
|
|
103
|
+
throw new UserError(`${id} is already claimed: branch ${branch} exists on ${remote}${claimHolder(t, work, branch, doc)}`, 1);
|
|
104
|
+
}
|
|
105
|
+
if (refExists(work, `refs/heads/${branch}`)) {
|
|
106
|
+
throw new UserError(`branch ${branch} already exists locally: switch to it, or delete it to start over`, 1);
|
|
107
|
+
}
|
|
108
|
+
const base = refExists(work, `refs/remotes/${remote}/${cfg.git.main}`) ? `${remote}/${cfg.git.main}` : cfg.git.main;
|
|
109
|
+
const target = o.worktree
|
|
110
|
+
? (o.path ?? join(dirname(work), `${basename(work)}-${branch.replace(/[\\/]/g, '-')}`))
|
|
111
|
+
: work;
|
|
112
|
+
if (o.worktree && existsSync(target))
|
|
113
|
+
throw new UserError(`${target} already exists`);
|
|
114
|
+
// Central mode: the claim is committed to the tracker first; a concurrent claim fails there.
|
|
115
|
+
if (t.code || cfg.mode === 'central') {
|
|
116
|
+
claimFields(t, ctx, doc, person);
|
|
117
|
+
appendLog(doc, `- ${today(ctx)} ${person}: Started${t.code ? ` in ${t.code.repo}` : ''} on branch ${branch}.`);
|
|
118
|
+
const problems = checkTicket(t, doc).filter((p) => p.severity === 'error');
|
|
119
|
+
if (problems.length > 0) {
|
|
120
|
+
for (const p of problems)
|
|
121
|
+
ctx.err(formatProblem(p));
|
|
122
|
+
throw new UserError(`${id} cannot be started`, 1);
|
|
123
|
+
}
|
|
124
|
+
save(doc);
|
|
125
|
+
publish(t, ctx, [repoPath(t, doc.path)], message(`Start ${id}: ${str(doc, 'title')}`, 'Refs', id), {
|
|
126
|
+
...o,
|
|
127
|
+
commit: o.commit ?? true,
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
if (o.worktree)
|
|
131
|
+
git(work, ['worktree', 'add', '--quiet', '-b', branch, target, base]);
|
|
132
|
+
else
|
|
133
|
+
git(work, ['switch', '--quiet', '-c', branch, base]);
|
|
134
|
+
const rollback = () => {
|
|
135
|
+
if (o.worktree)
|
|
136
|
+
tryGit(work, ['worktree', 'remove', '--force', target]);
|
|
137
|
+
else
|
|
138
|
+
tryGit(work, ['switch', '--quiet', '-']);
|
|
139
|
+
tryGit(work, ['branch', '-D', branch]);
|
|
140
|
+
};
|
|
141
|
+
try {
|
|
142
|
+
if (!t.code && cfg.mode !== 'central') {
|
|
143
|
+
// Embedded mode: the claim is the first commit of the branch.
|
|
144
|
+
const path = join(target, t.rel, 'tickets', fileName(doc));
|
|
145
|
+
if (!existsSync(path)) {
|
|
146
|
+
throw new UserError(`${id} is not on ${base} yet: merge or push the commit that adds it, then start`, 1);
|
|
147
|
+
}
|
|
148
|
+
const branchDoc = parseDoc('ticket', path, readFileSync(path, 'utf8'));
|
|
149
|
+
claimFields(t, ctx, branchDoc, person);
|
|
150
|
+
const problems = checkTicket({ ...t, tickets: t.tickets.map((d) => (d === doc ? branchDoc : d)) }, branchDoc).filter((p) => p.severity === 'error');
|
|
151
|
+
if (problems.length > 0) {
|
|
152
|
+
for (const p of problems)
|
|
153
|
+
ctx.err(formatProblem(p));
|
|
154
|
+
throw new UserError(`${id} cannot be started`, 1);
|
|
155
|
+
}
|
|
156
|
+
writeFileSync(path, serialize(branchDoc));
|
|
157
|
+
const rel = join(t.rel, 'tickets', fileName(doc));
|
|
158
|
+
git(target, [
|
|
159
|
+
'commit',
|
|
160
|
+
'--quiet',
|
|
161
|
+
'--no-verify',
|
|
162
|
+
'-m',
|
|
163
|
+
message(`Start ${id}: ${str(doc, 'title')}`, 'Refs', id),
|
|
164
|
+
'--',
|
|
165
|
+
rel,
|
|
166
|
+
]);
|
|
167
|
+
}
|
|
168
|
+
if (push) {
|
|
169
|
+
try {
|
|
170
|
+
git(target, [
|
|
171
|
+
'push',
|
|
172
|
+
'--quiet',
|
|
173
|
+
'-u',
|
|
174
|
+
`--force-with-lease=refs/heads/${branch}:`,
|
|
175
|
+
remote,
|
|
176
|
+
`${branch}:${branch}`,
|
|
177
|
+
]);
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
throw new UserError(`${id} was claimed by someone else just now (branch ${branch} exists on ${remote})`, 1);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
catch (e) {
|
|
185
|
+
rollback();
|
|
186
|
+
throw e;
|
|
187
|
+
}
|
|
188
|
+
ctx.out(`${id} claimed on branch ${branch}${push ? ` (pushed to ${remote})` : ' (local only: not pushed)'}`);
|
|
189
|
+
if (o.worktree)
|
|
190
|
+
ctx.out(`worktree: ${displayPath(ctx, target)}`);
|
|
191
|
+
ctx.out(`next: write the ## Plan, do the work, then run \`nit finish\``);
|
|
192
|
+
if (o.json)
|
|
193
|
+
ctx.out(JSON.stringify({ id, branch, worktree: o.worktree ? target : null, pushed: push }));
|
|
194
|
+
return 0;
|
|
195
|
+
}
|
|
196
|
+
function claimHolder(t, work, branch, doc) {
|
|
197
|
+
if (t.code)
|
|
198
|
+
return str(doc, 'assignee') ? ` (assignee: ${str(doc, 'assignee')})` : '';
|
|
199
|
+
tryGit(work, ['fetch', '--quiet', t.config.git.remote, branch]);
|
|
200
|
+
const text = showFile(work, `${t.config.git.remote}/${branch}`, repoPath(t, doc.path));
|
|
201
|
+
const who = text ? str(parseDoc('ticket', doc.path, text), 'assignee') : undefined;
|
|
202
|
+
return who ? ` (assignee: ${who})` : '';
|
|
203
|
+
}
|
|
204
|
+
// ---------------------------------------------------------------- finish
|
|
205
|
+
export function cmdFinish(ctx, o, idArg) {
|
|
206
|
+
const t = open(ctx, o, { fresh: true });
|
|
207
|
+
const doc = resolveTicketArg(t, idArg);
|
|
208
|
+
const id = ticketId(doc);
|
|
209
|
+
const cfg = t.config;
|
|
210
|
+
const work = workRoot(t);
|
|
211
|
+
const branch = currentBranch(work);
|
|
212
|
+
if (branch !== branchFor(cfg, id)) {
|
|
213
|
+
throw new UserError(`finish ${id} on its branch ${branchFor(cfg, id)} (the current branch is ${branch ?? 'detached'})`);
|
|
214
|
+
}
|
|
215
|
+
const crit = criteria(doc);
|
|
216
|
+
if (crit.length === 0)
|
|
217
|
+
throw new UserError(`${id} has no acceptance criteria; add them before finishing`, 1);
|
|
218
|
+
const openCrit = crit.filter((c) => !c.checked);
|
|
219
|
+
if (openCrit.length > 0) {
|
|
220
|
+
ctx.err(`${id} has unchecked acceptance criteria:`);
|
|
221
|
+
for (const c of openCrit)
|
|
222
|
+
ctx.err(` ${repoPath(t, doc.path)}:${c.line}: [ ] ${c.text}`);
|
|
223
|
+
ctx.err('check them when they are met, or log what is left and keep the ticket in progress');
|
|
224
|
+
return 1;
|
|
225
|
+
}
|
|
226
|
+
const person = currentPerson(ctx, cfg, work);
|
|
227
|
+
const subject = `Finish ${id}: ${str(doc, 'title')}`;
|
|
228
|
+
if (t.code || cfg.mode === 'central') {
|
|
229
|
+
appendLog(doc, `- ${today(ctx)} ${person}: Finished${t.code ? ` in ${t.code.repo}` : ''}; closes when ${branch} is merged.`);
|
|
230
|
+
save(doc);
|
|
231
|
+
publish(t, ctx, [repoPath(t, doc.path)], message(`Log ${id}: finished on ${branch}`, 'Refs', id), {
|
|
232
|
+
...o,
|
|
233
|
+
commit: o.commit ?? true,
|
|
234
|
+
});
|
|
235
|
+
git(work, ['commit', '--quiet', '--no-verify', '--allow-empty', '-m', message(subject, 'Closes', id)]);
|
|
236
|
+
}
|
|
237
|
+
else {
|
|
238
|
+
const before = str(doc, 'status');
|
|
239
|
+
set(doc, 'status', cfg.workflow.finish);
|
|
240
|
+
if (!str(doc, 'assignee'))
|
|
241
|
+
set(doc, 'assignee', person);
|
|
242
|
+
if (!str(doc, 'started'))
|
|
243
|
+
set(doc, 'started', today(ctx));
|
|
244
|
+
if (isDone(t, cfg.workflow.finish))
|
|
245
|
+
set(doc, 'done', today(ctx));
|
|
246
|
+
guardStatusChange(ctx, t, work, doc, before, cfg.workflow.finish);
|
|
247
|
+
const problems = checkTicket(t, doc).filter((p) => p.severity === 'error');
|
|
248
|
+
if (problems.length > 0) {
|
|
249
|
+
for (const p of problems)
|
|
250
|
+
ctx.err(formatProblem(p));
|
|
251
|
+
throw new UserError(`${id} cannot be finished`, 1);
|
|
252
|
+
}
|
|
253
|
+
save(doc);
|
|
254
|
+
git(work, ['commit', '--quiet', '--no-verify', '-m', message(subject, 'Closes', id), '--', repoPath(t, doc.path)]);
|
|
255
|
+
}
|
|
256
|
+
ctx.out(`${id} finished on ${branch}`);
|
|
257
|
+
const parent = str(doc, 'parent');
|
|
258
|
+
if (parent) {
|
|
259
|
+
const siblings = t.tickets.filter((x) => str(x, 'parent') === parent && ticketId(x) !== id);
|
|
260
|
+
if (siblings.every((x) => isClosed(t, str(x, 'status')))) {
|
|
261
|
+
ctx.out(`${id} is the last open child of epic ${parent}: close the epic after the merge, once its own criteria are met (nit set ${parent} status=${cfg.workflow.done})`);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
if (canPush(t, work, o)) {
|
|
265
|
+
try {
|
|
266
|
+
git(work, ['push', '--quiet', '-u', cfg.git.remote, `${branch}:${branch}`]);
|
|
267
|
+
ctx.out(`pushed ${branch} to ${cfg.git.remote}`);
|
|
268
|
+
}
|
|
269
|
+
catch (e) {
|
|
270
|
+
ctx.err(`warning: push failed: ${e.message}`);
|
|
271
|
+
return 1;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
if (o.pr)
|
|
275
|
+
openPullRequest(ctx, work, branch);
|
|
276
|
+
else
|
|
277
|
+
ctx.out('next: open the pull request');
|
|
278
|
+
return 0;
|
|
279
|
+
}
|
|
280
|
+
function openPullRequest(ctx, cwd, branch) {
|
|
281
|
+
try {
|
|
282
|
+
const url = execFileSync('gh', ['pr', 'create', '--fill', '--head', branch], { cwd, encoding: 'utf8' });
|
|
283
|
+
ctx.out(url.trim());
|
|
284
|
+
}
|
|
285
|
+
catch {
|
|
286
|
+
ctx.err('could not open the pull request with `gh`; open it in the web UI');
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
// ---------------------------------------------------------------- claims / release
|
|
290
|
+
export function cmdClaims(ctx, o) {
|
|
291
|
+
const t = open(ctx, o);
|
|
292
|
+
const claims = listClaims(t, ctx, { fetch: o.fetch !== false });
|
|
293
|
+
if (o.json) {
|
|
294
|
+
ctx.out(JSON.stringify(claims, null, 2));
|
|
295
|
+
return 0;
|
|
296
|
+
}
|
|
297
|
+
if (claims.length === 0) {
|
|
298
|
+
ctx.out('no open claims');
|
|
299
|
+
return 0;
|
|
300
|
+
}
|
|
301
|
+
const rows = [['ID', 'BRANCH', 'ASSIGNEE', 'LAST COMMIT', 'TITLE']];
|
|
302
|
+
for (const c of claims) {
|
|
303
|
+
const doc = t.tickets.find((d) => ticketId(d) === c.id);
|
|
304
|
+
rows.push([c.id, c.branch, c.assignee ?? c.author, c.last, doc ? (str(doc, 'title') ?? '') : '(unknown ticket)']);
|
|
305
|
+
}
|
|
306
|
+
for (const line of textTable(rows))
|
|
307
|
+
ctx.out(line);
|
|
308
|
+
return 0;
|
|
309
|
+
}
|
|
310
|
+
export function cmdRelease(ctx, o, idArg) {
|
|
311
|
+
const t = open(ctx, o, { fresh: true });
|
|
312
|
+
const doc = resolveTicketArg(t, idArg);
|
|
313
|
+
const id = ticketId(doc);
|
|
314
|
+
const cfg = t.config;
|
|
315
|
+
const work = workRoot(t);
|
|
316
|
+
const remote = cfg.git.remote;
|
|
317
|
+
const branch = branchFor(cfg, id);
|
|
318
|
+
const central = Boolean(t.code) || cfg.mode === 'central';
|
|
319
|
+
if (hasRemote(work, remote) && tryGit(work, ['ls-remote', '--heads', remote, `refs/heads/${branch}`])) {
|
|
320
|
+
tryGit(work, ['fetch', '--quiet', remote, branch]);
|
|
321
|
+
const ahead = Number(tryGit(work, ['rev-list', '--count', `${remote}/${cfg.git.main}..${remote}/${branch}`]) ?? '0');
|
|
322
|
+
const claimOnly = central ? 0 : 1;
|
|
323
|
+
if (ahead > claimOnly && !o.force) {
|
|
324
|
+
throw new UserError(`${branch} on ${remote} has ${ahead - claimOnly} commit(s) of work; merge or hand them over first, or use --force`, 1);
|
|
325
|
+
}
|
|
326
|
+
git(work, ['push', '--quiet', remote, '--delete', branch]);
|
|
327
|
+
ctx.out(`deleted ${branch} on ${remote}`);
|
|
328
|
+
}
|
|
329
|
+
if (central) {
|
|
330
|
+
guardStatusChange(ctx, t, work, doc, str(doc, 'status'), cfg.workflow.ready);
|
|
331
|
+
set(doc, 'status', cfg.workflow.ready);
|
|
332
|
+
set(doc, 'assignee', undefined);
|
|
333
|
+
set(doc, 'started', undefined);
|
|
334
|
+
appendLog(doc, `- ${today(ctx)} ${currentPerson(ctx, cfg, work)}: Released the claim.`);
|
|
335
|
+
save(doc);
|
|
336
|
+
publish(t, ctx, [repoPath(t, doc.path)], message(`Release ${id}`, 'Refs', id), { ...o, commit: o.commit ?? true });
|
|
337
|
+
}
|
|
338
|
+
ctx.out(`${id} released${refExists(work, `refs/heads/${branch}`) ? `; the local branch ${branch} is kept` : ''}`);
|
|
339
|
+
return 0;
|
|
340
|
+
}
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { isAbsolute, join, resolve } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { approvalRefusal, isApproval, isDone, transitionError, authorPerson, checkTracker, formatProblem, criteria, list, str, LOG_FORMAT, allReferences, parseLog, parseReferences, formatDoc, idFromBranch, repoPath, ticketId, workRoot, UserError, } from '@knitmd/core';
|
|
5
|
+
import { guardStatusChange, stagedStatusChanges, statusChangesIn } from '../approval.js';
|
|
6
|
+
import { loadTracker } from '../tracker.js';
|
|
7
|
+
import { currentBranch, git, repoRoot, tryGit } from '../git.js';
|
|
8
|
+
import { today } from '../ctx.js';
|
|
9
|
+
/** Finds a ticket by its current or former ID. */
|
|
10
|
+
export function lookup(t, id) {
|
|
11
|
+
return t.tickets.find((d) => ticketId(d) === id) ?? t.tickets.find((d) => list(d, 'x-former-id').includes(id));
|
|
12
|
+
}
|
|
13
|
+
/** Checks the ticket references of one commit message. */
|
|
14
|
+
export function checkMessage(t, message) {
|
|
15
|
+
const refs = parseReferences(message, t.config.key);
|
|
16
|
+
const problems = [];
|
|
17
|
+
const ids = allReferences(refs);
|
|
18
|
+
if (ids.length === 0 && t.config.git.requireTicket) {
|
|
19
|
+
problems.push(`no ticket reference: add a 'Refs: ${t.config.key}-<n>' trailer (or work on a ticket branch)`);
|
|
20
|
+
}
|
|
21
|
+
for (const id of ids)
|
|
22
|
+
if (!lookup(t, id))
|
|
23
|
+
problems.push(`unknown ticket ${id}`);
|
|
24
|
+
return problems;
|
|
25
|
+
}
|
|
26
|
+
/** `check-commits <range>`: references exist, and every `Closes:` ticket is ready to close. */
|
|
27
|
+
export function cmdCheckCommits(ctx, o, range) {
|
|
28
|
+
if (!range)
|
|
29
|
+
throw new UserError('usage: nit check-commits <base>..<head>');
|
|
30
|
+
const t = loadTracker(ctx, o.dir);
|
|
31
|
+
const work = workRoot(t);
|
|
32
|
+
const commits = parseLog(git(work, ['log', '--no-merges', LOG_FORMAT, range]));
|
|
33
|
+
const problems = [];
|
|
34
|
+
const closes = new Set();
|
|
35
|
+
for (const c of commits) {
|
|
36
|
+
for (const m of checkMessage(t, c.message))
|
|
37
|
+
problems.push({ commit: c.hash.slice(0, 7), message: m });
|
|
38
|
+
for (const id of parseReferences(c.message, t.config.key).closes)
|
|
39
|
+
closes.add(id);
|
|
40
|
+
}
|
|
41
|
+
// Approvals: only the tracker's own repository holds the tickets.
|
|
42
|
+
if (!t.code) {
|
|
43
|
+
for (const c of commits) {
|
|
44
|
+
const changes = statusChangesIn(t, work, c.hash);
|
|
45
|
+
if (changes.length === 0)
|
|
46
|
+
continue;
|
|
47
|
+
const [name, email] = git(work, ['show', '-s', '--format=%an%x1f%ae', c.hash]).split('\x1f');
|
|
48
|
+
const person = authorPerson(t.config, name, email);
|
|
49
|
+
for (const ch of changes) {
|
|
50
|
+
const moved = `${name} moved ${ch.id} from ${ch.from ?? '(new)'} to ${ch.to}`;
|
|
51
|
+
const refusal = isApproval(t, ch.from, ch.to) ? approvalRefusal(t.config, person) : undefined;
|
|
52
|
+
if (refusal) {
|
|
53
|
+
problems.push({
|
|
54
|
+
commit: c.hash.slice(0, 7),
|
|
55
|
+
message: `${moved}, but ${refusal}; an approver makes this change`,
|
|
56
|
+
});
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
const why = transitionError(t, ch.doc, ch.from, ch.to, person);
|
|
60
|
+
if (why)
|
|
61
|
+
problems.push({ commit: c.hash.slice(0, 7), message: `${moved}: ${why}` });
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
const embedded = !t.code && t.config.mode !== 'central';
|
|
66
|
+
for (const id of closes) {
|
|
67
|
+
const doc = lookup(t, id);
|
|
68
|
+
if (!doc)
|
|
69
|
+
continue;
|
|
70
|
+
const open = criteria(doc).filter((c) => !c.checked);
|
|
71
|
+
const file = repoPath(t, doc.path);
|
|
72
|
+
if (criteria(doc).length === 0)
|
|
73
|
+
problems.push({ commit: '', message: `Closes: ${id}, but ${file} has no acceptance criteria` });
|
|
74
|
+
for (const c of open)
|
|
75
|
+
problems.push({ commit: '', message: `Closes: ${id}, but ${file}:${c.line} is unchecked: ${c.text}` });
|
|
76
|
+
const status = str(doc, 'status');
|
|
77
|
+
if (embedded && status !== t.config.workflow.finish && !isDone(t, status)) {
|
|
78
|
+
problems.push({
|
|
79
|
+
commit: '',
|
|
80
|
+
message: `Closes: ${id}, but its status is '${str(doc, 'status')}'; run \`nit finish\``,
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
if (o.json)
|
|
85
|
+
ctx.out(JSON.stringify({ commits: commits.length, closes: [...closes], problems }, null, 2));
|
|
86
|
+
else
|
|
87
|
+
for (const p of problems)
|
|
88
|
+
ctx.out(`${p.commit ? `${p.commit}: ` : ''}${p.message}`);
|
|
89
|
+
if (!o.json)
|
|
90
|
+
ctx.err(problems.length === 0 ? `${commits.length} commit(s): ok` : `${problems.length} problem(s)`);
|
|
91
|
+
return problems.length > 0 ? 1 : 0;
|
|
92
|
+
}
|
|
93
|
+
// ---------------------------------------------------------------- hook entry points
|
|
94
|
+
function tryTracker(ctx, o) {
|
|
95
|
+
try {
|
|
96
|
+
return loadTracker(ctx, o.dir);
|
|
97
|
+
}
|
|
98
|
+
catch (e) {
|
|
99
|
+
if (e instanceof UserError) {
|
|
100
|
+
ctx.err(`nit: ${e.message} (ticket references not checked)`);
|
|
101
|
+
return undefined;
|
|
102
|
+
}
|
|
103
|
+
throw e;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
function stripComments(text) {
|
|
107
|
+
return text
|
|
108
|
+
.split(/\r?\n/)
|
|
109
|
+
.filter((l) => !l.startsWith('#'))
|
|
110
|
+
.join('\n');
|
|
111
|
+
}
|
|
112
|
+
export function hookPrepareCommitMsg(ctx, o, file, source) {
|
|
113
|
+
if (!file || source === 'merge' || source === 'squash')
|
|
114
|
+
return 0;
|
|
115
|
+
const t = tryTracker(ctx, o);
|
|
116
|
+
if (!t)
|
|
117
|
+
return 0;
|
|
118
|
+
const id = idFromBranch(t.config, currentBranch(workRoot(t)) ?? currentBranch(ctx.cwd));
|
|
119
|
+
if (!id)
|
|
120
|
+
return 0;
|
|
121
|
+
const path = resolve(ctx.cwd, file);
|
|
122
|
+
const text = readFileSync(path, 'utf8');
|
|
123
|
+
if (allReferences(parseReferences(stripComments(text), t.config.key)).includes(id))
|
|
124
|
+
return 0;
|
|
125
|
+
git(ctx.cwd, ['interpret-trailers', '--in-place', '--if-exists', 'addIfDifferent', '--trailer', `Refs: ${id}`, path]);
|
|
126
|
+
return 0;
|
|
127
|
+
}
|
|
128
|
+
export function hookCommitMsg(ctx, o, file) {
|
|
129
|
+
if (!file)
|
|
130
|
+
return 0;
|
|
131
|
+
const t = tryTracker(ctx, o);
|
|
132
|
+
if (!t)
|
|
133
|
+
return 0;
|
|
134
|
+
const message = stripComments(readFileSync(resolve(ctx.cwd, file), 'utf8'));
|
|
135
|
+
const problems = checkMessage(t, message);
|
|
136
|
+
for (const p of problems)
|
|
137
|
+
ctx.err(`nit: ${p}`);
|
|
138
|
+
return problems.length > 0 ? 1 : 0;
|
|
139
|
+
}
|
|
140
|
+
export function hookPreCommit(ctx, o) {
|
|
141
|
+
let t;
|
|
142
|
+
try {
|
|
143
|
+
t = loadTracker(ctx, o.dir);
|
|
144
|
+
}
|
|
145
|
+
catch (e) {
|
|
146
|
+
if (!(e instanceof UserError))
|
|
147
|
+
throw e;
|
|
148
|
+
if (e.message.startsWith('no tracker found'))
|
|
149
|
+
return 0;
|
|
150
|
+
ctx.err(`nit: ${e.message}`);
|
|
151
|
+
return 1;
|
|
152
|
+
}
|
|
153
|
+
if (t.code)
|
|
154
|
+
return 0;
|
|
155
|
+
const staged = (tryGit(t.root, ['diff', '--cached', '--name-only', '--diff-filter=ACMR']) ?? '')
|
|
156
|
+
.split('\n')
|
|
157
|
+
.filter(Boolean);
|
|
158
|
+
const prefix = t.rel ? `${t.rel}/` : '';
|
|
159
|
+
const touched = staged.filter((f) => f.startsWith(prefix) && /\.(md|yml)$/.test(f));
|
|
160
|
+
if (touched.length === 0)
|
|
161
|
+
return 0;
|
|
162
|
+
const unstaged = new Set((tryGit(t.root, ['diff', '--name-only']) ?? '').split('\n').filter(Boolean));
|
|
163
|
+
const date = today(ctx);
|
|
164
|
+
for (const doc of [...t.tickets, ...t.milestones]) {
|
|
165
|
+
const rel = repoPath(t, doc.path);
|
|
166
|
+
if (!touched.includes(rel))
|
|
167
|
+
continue;
|
|
168
|
+
const before = doc.original;
|
|
169
|
+
const text = formatDoc(t, doc, date);
|
|
170
|
+
if (text === before)
|
|
171
|
+
continue;
|
|
172
|
+
if (unstaged.has(rel)) {
|
|
173
|
+
ctx.err(`nit: ${rel} is not formatted, and has unstaged changes; run \`nit fmt\` and stage it`);
|
|
174
|
+
return 1;
|
|
175
|
+
}
|
|
176
|
+
writeFileSync(doc.path, text);
|
|
177
|
+
doc.original = text;
|
|
178
|
+
git(t.root, ['add', '--', rel]);
|
|
179
|
+
ctx.err(`nit: formatted ${rel}`);
|
|
180
|
+
}
|
|
181
|
+
for (const ch of stagedStatusChanges(t, t.root)) {
|
|
182
|
+
try {
|
|
183
|
+
guardStatusChange(ctx, t, t.root, ch.doc, ch.from, ch.to);
|
|
184
|
+
}
|
|
185
|
+
catch (e) {
|
|
186
|
+
if (!(e instanceof UserError))
|
|
187
|
+
throw e;
|
|
188
|
+
ctx.err(`nit: ${ch.file}: ${e.message}`);
|
|
189
|
+
return 1;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
const problems = checkTracker(t);
|
|
193
|
+
const errors = problems.filter((p) => p.severity === 'error');
|
|
194
|
+
for (const p of problems)
|
|
195
|
+
ctx.err(formatProblem(p));
|
|
196
|
+
if (errors.length > 0) {
|
|
197
|
+
ctx.err(`nit: ${errors.length} error(s) in the tracker; fix them, or commit with --no-verify to skip the check`);
|
|
198
|
+
return 1;
|
|
199
|
+
}
|
|
200
|
+
return 0;
|
|
201
|
+
}
|
|
202
|
+
// ---------------------------------------------------------------- install
|
|
203
|
+
const MARKER = '# nit hook';
|
|
204
|
+
/** Hooks installed by earlier versions (markdown-proj) are ours too, and replaced. */
|
|
205
|
+
const LEGACY_MARKER = '# mdproj hook';
|
|
206
|
+
export const TRACKER_HOOKS = ['pre-commit', 'prepare-commit-msg', 'commit-msg'];
|
|
207
|
+
export const CODE_HOOKS = ['prepare-commit-msg', 'commit-msg'];
|
|
208
|
+
export function hooksDir(root) {
|
|
209
|
+
const configured = tryGit(root, ['config', 'core.hooksPath']);
|
|
210
|
+
if (configured)
|
|
211
|
+
return isAbsolute(configured) ? configured : join(root, configured);
|
|
212
|
+
const common = git(root, ['rev-parse', '--git-common-dir']);
|
|
213
|
+
return join(isAbsolute(common) ? common : join(root, common), 'hooks');
|
|
214
|
+
}
|
|
215
|
+
function cliPath() {
|
|
216
|
+
// cli.ts in development, cli.js in the published package.
|
|
217
|
+
const ext = import.meta.url.endsWith('.js') ? 'js' : 'ts';
|
|
218
|
+
return fileURLToPath(new URL(`../cli.${ext}`, import.meta.url));
|
|
219
|
+
}
|
|
220
|
+
export function installHooks(ctx, root, names, force = false) {
|
|
221
|
+
const dir = hooksDir(root);
|
|
222
|
+
mkdirSync(dir, { recursive: true });
|
|
223
|
+
let failed = 0;
|
|
224
|
+
for (const name of names) {
|
|
225
|
+
const path = join(dir, name);
|
|
226
|
+
const ours = (text) => text.includes(MARKER) || text.includes(LEGACY_MARKER);
|
|
227
|
+
if (existsSync(path) && !ours(readFileSync(path, 'utf8')) && !force) {
|
|
228
|
+
ctx.err(`${path} exists and is not a nit hook; add \`nit hook ${name} "$@"\` to it, or use --force`);
|
|
229
|
+
failed++;
|
|
230
|
+
continue;
|
|
231
|
+
}
|
|
232
|
+
const script = [
|
|
233
|
+
'#!/bin/sh',
|
|
234
|
+
`${MARKER} (installed by \`nit hooks install\`)`,
|
|
235
|
+
`exec "${process.execPath}" "${cliPath()}" hook ${name} "$@"`,
|
|
236
|
+
'',
|
|
237
|
+
].join('\n');
|
|
238
|
+
writeFileSync(path, script);
|
|
239
|
+
chmodSync(path, 0o755);
|
|
240
|
+
ctx.out(`installed ${name}`);
|
|
241
|
+
}
|
|
242
|
+
return failed > 0 ? 1 : 0;
|
|
243
|
+
}
|
|
244
|
+
export function cmdHooksInstall(ctx, o) {
|
|
245
|
+
const root = repoRoot(ctx.cwd);
|
|
246
|
+
if (!root)
|
|
247
|
+
throw new UserError('not in a Git repository');
|
|
248
|
+
let t;
|
|
249
|
+
try {
|
|
250
|
+
t = loadTracker(ctx, o.dir);
|
|
251
|
+
}
|
|
252
|
+
catch {
|
|
253
|
+
t = undefined;
|
|
254
|
+
}
|
|
255
|
+
const isTrackerRepo = t !== undefined && !t.code && resolve(t.root) === resolve(root);
|
|
256
|
+
return installHooks(ctx, root, isTrackerRepo ? TRACKER_HOOKS : CODE_HOOKS, o.force);
|
|
257
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { SKILL_DIR, skillFiles } from '@knitmd/core';
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { dirname, join, relative, resolve } from 'node:path';
|
|
4
|
+
import { repoRoot } from '../git.js';
|
|
5
|
+
import { loadTracker } from '../tracker.js';
|
|
6
|
+
const INSTRUCTIONS = [
|
|
7
|
+
'Knit tracks the work of this repository as Markdown tickets in Git.',
|
|
8
|
+
'Read the resource knit://guide before working on tickets: it holds the workflow, who owns each',
|
|
9
|
+
'status and what agents do in it. Use `next` or `inbox` to find work, `start` before changing code,',
|
|
10
|
+
'`log` for decisions, `tick` for acceptance criteria and `finish` when done.',
|
|
11
|
+
'Agents never approve tickets (move them to the ready status); leave them for a person and ask.',
|
|
12
|
+
].join(' ');
|
|
13
|
+
const REPORTS = [
|
|
14
|
+
['README.md', 'Overview: status counts, milestones, epics, waiting queue'],
|
|
15
|
+
['board.md', 'Board: tickets per status'],
|
|
16
|
+
['gantt.md', 'Schedule: milestones and planned dates'],
|
|
17
|
+
];
|
|
18
|
+
export const MCP_MISSING = '`nit mcp` needs the MCP server package: npm install --global @knitmd/mcp (or add it next to knitmd in your project)';
|
|
19
|
+
/** The MCP server of `nit mcp`: every tool runs a command line in-process. */
|
|
20
|
+
export function mcpServer(mcp, ctx, main, version, dir) {
|
|
21
|
+
const run = (argv) => {
|
|
22
|
+
const out = [];
|
|
23
|
+
const err = [];
|
|
24
|
+
const code = main([...argv, ...(dir ? ['--dir', dir] : [])], {
|
|
25
|
+
cwd: ctx.cwd,
|
|
26
|
+
env: ctx.env,
|
|
27
|
+
out: (l) => out.push(l),
|
|
28
|
+
err: (l) => err.push(l),
|
|
29
|
+
});
|
|
30
|
+
return { code, out: out.join('\n'), err: err.join('\n') };
|
|
31
|
+
};
|
|
32
|
+
const text = (r) => (r.code === 0 ? r.out : `${r.err}\n${r.out}`.trim());
|
|
33
|
+
const resources = [
|
|
34
|
+
{
|
|
35
|
+
uri: 'knit://guide',
|
|
36
|
+
name: 'GUIDE.md',
|
|
37
|
+
description: 'How this project works with tickets: the everyday flow, approval and the workflow',
|
|
38
|
+
mimeType: 'text/markdown',
|
|
39
|
+
read: () => {
|
|
40
|
+
const path = join(loadTracker(ctx, dir).dir, 'GUIDE.md');
|
|
41
|
+
return existsSync(path) ? readFileSync(path, 'utf8') : text(run(['guide']));
|
|
42
|
+
},
|
|
43
|
+
},
|
|
44
|
+
...REPORTS.map(([name, description]) => ({
|
|
45
|
+
uri: `knit://reports/${name}`,
|
|
46
|
+
name,
|
|
47
|
+
description,
|
|
48
|
+
mimeType: 'text/markdown',
|
|
49
|
+
read: () => text(run(['report', '--name', name, '--no-fetch'])),
|
|
50
|
+
})),
|
|
51
|
+
];
|
|
52
|
+
return new mcp.Server({ name: 'knit', version, run, resources, instructions: INSTRUCTIONS });
|
|
53
|
+
}
|
|
54
|
+
/** `mcp`: serves the MCP protocol on stdin/stdout until stdin closes. */
|
|
55
|
+
export function cmdMcp(ctx, v, main, version) {
|
|
56
|
+
import('@knitmd/mcp').then((mcp) => {
|
|
57
|
+
const server = mcpServer(mcp, ctx, main, version, v.dir);
|
|
58
|
+
void mcp.serve(server, process.stdin, (line) => process.stdout.write(line));
|
|
59
|
+
}, (e) => {
|
|
60
|
+
if (e.code !== 'ERR_MODULE_NOT_FOUND' || !String(e.message).includes('@knitmd/mcp'))
|
|
61
|
+
throw e;
|
|
62
|
+
ctx.err(`nit: ${MCP_MISSING}`);
|
|
63
|
+
process.exitCode = 1;
|
|
64
|
+
process.stdin.destroy();
|
|
65
|
+
});
|
|
66
|
+
return 0;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* `skill [--write] [--path DIR]`: the agent skill generated from the guide; `--write` installs it
|
|
70
|
+
* into the repository (default `.claude/skills/knit`).
|
|
71
|
+
*/
|
|
72
|
+
export function cmdSkill(ctx, v, commands) {
|
|
73
|
+
const t = loadTracker(ctx, v.dir);
|
|
74
|
+
const root = repoRoot(ctx.cwd) ?? ctx.cwd;
|
|
75
|
+
const guide = relative(root, join(t.dir, 'GUIDE.md')).split('\\').join('/');
|
|
76
|
+
const files = skillFiles(t, guide, commands);
|
|
77
|
+
if (!v.write) {
|
|
78
|
+
ctx.out(files['SKILL.md'] ?? '');
|
|
79
|
+
return 0;
|
|
80
|
+
}
|
|
81
|
+
const target = resolve(root, v.path ?? SKILL_DIR);
|
|
82
|
+
for (const [name, text] of Object.entries(files)) {
|
|
83
|
+
const path = join(target, name);
|
|
84
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
85
|
+
const changed = !existsSync(path) || readFileSync(path, 'utf8') !== text;
|
|
86
|
+
if (changed)
|
|
87
|
+
writeFileSync(path, text);
|
|
88
|
+
ctx.out(`${relative(ctx.cwd, path) || path}${changed ? '' : ': no change'}`);
|
|
89
|
+
}
|
|
90
|
+
return 0;
|
|
91
|
+
}
|