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.
@@ -0,0 +1,95 @@
1
+ import { existsSync, renameSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { attachmentsRoot, list, set, str, fileName, normalizeId, repoPath, ticketId, UserError, } from '@knitmd/core';
4
+ import { save } from '../tracker.js';
5
+ import { refExists, showFile, tryGit } from '../git.js';
6
+ import { nextNumber } from '../publish.js';
7
+ import { open } from './basic.js';
8
+ function mainRef(t) {
9
+ const remote = `refs/remotes/${t.config.git.remote}/${t.config.git.main}`;
10
+ if (refExists(t.root, remote))
11
+ return remote;
12
+ return refExists(t.root, `refs/heads/${t.config.git.main}`) ? t.config.git.main : undefined;
13
+ }
14
+ /**
15
+ * Gives a ticket a new number. With duplicates, the ticket that is not on the main branch is the
16
+ * one renumbered, and only tickets that are not on the main branch have their references updated.
17
+ */
18
+ export function renumber(t, oldId, newNum) {
19
+ const same = t.tickets.filter((d) => ticketId(d) === oldId);
20
+ if (same.length === 0)
21
+ throw new UserError(`no ticket ${oldId}`, 1);
22
+ const main = mainRef(t);
23
+ const onMain = (d) => (main ? showFile(t.root, main, repoPath(t, d.path)) !== undefined : false);
24
+ const candidates = same.filter((d) => !onMain(d));
25
+ if (same.length > 1 && candidates.length !== 1) {
26
+ throw new UserError(`${oldId} is used by ${same.length} tickets and it is unclear which one is new; rename one by hand`, 1);
27
+ }
28
+ const doc = candidates[0] ?? same[0];
29
+ const num = newNum ?? nextNumber(t);
30
+ const newId = `${t.config.key}-${num}`;
31
+ if (t.tickets.some((d) => ticketId(d) === newId))
32
+ throw new UserError(`${newId} already exists`, 1);
33
+ const changed = [];
34
+ const oldPath = doc.path;
35
+ const newPath = join(oldPath, '..', fileName(doc).replace(oldId, newId));
36
+ const tracked = tryGit(t.root, ['ls-files', '--error-unmatch', repoPath(t, oldPath)]) !== undefined;
37
+ if (tracked)
38
+ tryGit(t.root, ['mv', repoPath(t, oldPath), repoPath(t, newPath)]);
39
+ else
40
+ renameSync(oldPath, newPath);
41
+ doc.path = newPath;
42
+ const oldDir = join(attachmentsRoot(t), oldId);
43
+ if (existsSync(oldDir)) {
44
+ const newDir = join(attachmentsRoot(t), newId);
45
+ const dirTracked = tryGit(t.root, ['ls-files', '--', repoPath(t, oldDir)]);
46
+ if (dirTracked)
47
+ tryGit(t.root, ['mv', repoPath(t, oldDir), repoPath(t, newDir)]);
48
+ if (existsSync(oldDir))
49
+ renameSync(oldDir, newDir);
50
+ changed.push(repoPath(t, newDir));
51
+ doc.body = doc.body.map((l) => l.split(`attachments/${oldId}/`).join(`attachments/${newId}/`));
52
+ }
53
+ set(doc, 'id', newId);
54
+ set(doc, 'x-former-id', [...list(doc, 'x-former-id'), oldId]);
55
+ doc.original = '';
56
+ save(doc);
57
+ changed.push(repoPath(t, newPath));
58
+ const re = new RegExp(`\\b${oldId}\\b`, 'g');
59
+ for (const other of t.tickets) {
60
+ if (other === doc || ticketId(other) === oldId || (same.length > 1 && onMain(other)))
61
+ continue;
62
+ let touched = false;
63
+ if (str(other, 'parent') === oldId) {
64
+ set(other, 'parent', newId);
65
+ touched = true;
66
+ }
67
+ const deps = list(other, 'depends_on');
68
+ if (deps.includes(oldId)) {
69
+ set(other, 'depends_on', deps.map((x) => (x === oldId ? newId : x)));
70
+ touched = true;
71
+ }
72
+ const body = other.body.map((l) => l.replace(re, newId));
73
+ if (body.some((l, i) => l !== other.body[i])) {
74
+ other.body = body;
75
+ touched = true;
76
+ }
77
+ if (touched && save(other))
78
+ changed.push(repoPath(t, other.path));
79
+ }
80
+ return { from: oldId, to: newId, changed };
81
+ }
82
+ export function cmdRenumber(ctx, o, id) {
83
+ if (!id)
84
+ throw new UserError('usage: nit renumber <ID> [--to <n>]');
85
+ const t = open(ctx, o);
86
+ const r = renumber(t, normalizeId(t.config, id), o.to ? Number(o.to) : undefined);
87
+ if (o.json)
88
+ ctx.out(JSON.stringify(r, null, 2));
89
+ else {
90
+ ctx.out(`${r.from} → ${r.to}`);
91
+ for (const f of r.changed)
92
+ ctx.out(` ${f}`);
93
+ }
94
+ return 0;
95
+ }
@@ -0,0 +1,187 @@
1
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { join, relative, resolve, sep } from 'node:path';
3
+ import { isClosed, isStarted, criteria, list, parseDoc, serialize, str, ATTACHMENTS_DIR, renderReports, fileName, repoPath, ticketId, UserError, isDate, inboxItems, } from '@knitmd/core';
4
+ import { waitingSince } from '../inbox.js';
5
+ import { linkedCommits } from '../linked.js';
6
+ import { git, GitError, hasRemote, refExists, showFile, tryGit } from '../git.js';
7
+ import { today } from '../ctx.js';
8
+ import { open } from './basic.js';
9
+ import { listClaims } from './flow.js';
10
+ import { closedIn } from './sync.js';
11
+ /** The tickets as the reports show them: the main branch, with each claim branch's version laid over it. */
12
+ export function overlayClaims(t, claims) {
13
+ if (t.code || t.config.mode === 'central')
14
+ return t.tickets;
15
+ const root = t.root;
16
+ const remote = t.config.git.remote;
17
+ return t.tickets.map((doc) => {
18
+ const claim = claims.find((c) => c.id === ticketId(doc));
19
+ if (!claim)
20
+ return doc;
21
+ const text = showFile(root, `refs/remotes/${remote}/${claim.branch}`, repoPath(t, doc.path));
22
+ return text ? parseDoc('ticket', doc.path, text) : doc;
23
+ });
24
+ }
25
+ function waiting(t, docs) {
26
+ const awaitingCriteria = [];
27
+ const waitingForRepos = [];
28
+ for (const d of docs) {
29
+ if (isClosed(t, str(d, 'status')))
30
+ continue;
31
+ const closed = closedIn(d);
32
+ if (closed.size === 0)
33
+ continue;
34
+ const missing = list(d, 'repos').filter((r) => !closed.has(r));
35
+ if (missing.length > 0)
36
+ waitingForRepos.push({ id: ticketId(d), repos: missing });
37
+ else if (criteria(d).some((c) => !c.checked) || criteria(d).length === 0)
38
+ awaitingCriteria.push(ticketId(d));
39
+ }
40
+ return { awaitingCriteria, waitingForRepos };
41
+ }
42
+ export function buildInput(t, ctx, opts) {
43
+ const claims = listClaims(t, ctx, { fetch: opts.fetch });
44
+ const tickets = overlayClaims(t, claims);
45
+ const commit = tryGit(t.root, ['rev-parse', '--short', 'HEAD']);
46
+ const commits = new Map(tickets.filter((d) => isStarted(t, str(d, 'status'))).map((d) => [ticketId(d), linkedCommits(t, d)]));
47
+ const queue = inboxItems(t, tickets, waitingSince(t));
48
+ return {
49
+ tracker: t,
50
+ tickets,
51
+ claims,
52
+ commits,
53
+ waiting: queue,
54
+ date: opts.date,
55
+ ...(commit ? { commit } : {}),
56
+ ticketsLink: opts.ticketsLink,
57
+ ...waiting(t, tickets),
58
+ };
59
+ }
60
+ export function cmdReport(ctx, o) {
61
+ const t = open(ctx, o);
62
+ const date = o.date ?? today(ctx);
63
+ if (!isDate(date))
64
+ throw new UserError(`--date '${date}' is not a date (YYYY-MM-DD)`);
65
+ const fetch = o.fetch !== false;
66
+ if (o.commit)
67
+ return commitReports(ctx, t, o, date, fetch);
68
+ if (o.out) {
69
+ const out = resolve(ctx.cwd, o.out);
70
+ mkdirSync(out, { recursive: true });
71
+ const link = relative(out, join(t.dir, 'tickets')).split(sep).join('/');
72
+ const input = buildInput(t, ctx, { date, fetch, ticketsLink: link });
73
+ for (const r of renderReports(input)) {
74
+ writeFileSync(join(out, r.name), r.text);
75
+ ctx.out(join(o.out, r.name));
76
+ }
77
+ return 0;
78
+ }
79
+ const input = buildInput(t, ctx, { date, fetch, ticketsLink: '../tickets' });
80
+ const name = o.name ?? 'README.md';
81
+ const r = renderReports(input).find((x) => x.name === name);
82
+ if (!r)
83
+ throw new UserError(`no report '${name}'; reports are README.md, board.md, gantt.md`);
84
+ ctx.out(r.text.replace(/\n$/, ''));
85
+ return 0;
86
+ }
87
+ /**
88
+ * Commits a snapshot of the tracker (with claimed tickets as on their claim branches) and the
89
+ * reports to the reports branch, without touching the working tree or the current branch.
90
+ */
91
+ function commitReports(ctx, t, o, date, fetch) {
92
+ const branch = t.config.reports.branch;
93
+ const remote = t.config.git.remote;
94
+ const push = (o.push ?? t.config.git.push) && hasRemote(t.root, remote);
95
+ if (branch === t.config.git.main) {
96
+ throw new UserError('reports.branch is the main branch: use `nit report --out <tracker>/reports` and commit it in CI');
97
+ }
98
+ for (let attempt = 0; attempt < 3; attempt++) {
99
+ if (push)
100
+ tryGit(t.root, ['fetch', '--quiet', remote, `+refs/heads/${branch}:refs/remotes/${remote}/${branch}`]);
101
+ const input = buildInput(t, ctx, { date, fetch: fetch && attempt === 0, ticketsLink: '../tickets' });
102
+ const files = new Map();
103
+ const base = t.rel ? `${t.rel}/` : '';
104
+ for (const d of input.tickets)
105
+ files.set(`${base}tickets/${fileName(d)}`, serialize(d));
106
+ for (const m of t.milestones)
107
+ files.set(`${base}milestones/${fileName(m)}`, serialize(m));
108
+ files.set(`${base}proj.yml`, readFileSync(join(t.dir, 'proj.yml'), 'utf8'));
109
+ for (const r of renderReports(input))
110
+ files.set(`${base}reports/${r.name}`, r.text);
111
+ files.set('README.md', reportsReadme(t, base));
112
+ const blobs = attachmentBlobs(t, input.claims);
113
+ const parent = refExists(t.root, `refs/remotes/${remote}/${branch}`)
114
+ ? git(t.root, ['rev-parse', `refs/remotes/${remote}/${branch}`])
115
+ : refExists(t.root, `refs/heads/${branch}`)
116
+ ? git(t.root, ['rev-parse', `refs/heads/${branch}`])
117
+ : undefined;
118
+ const gitDir = git(t.root, ['rev-parse', '--absolute-git-dir']);
119
+ const env = { GIT_INDEX_FILE: join(gitDir, `nit-reports-index-${process.pid}`) };
120
+ git(t.root, ['read-tree', '--empty'], { env });
121
+ for (const [path, text] of files) {
122
+ const blob = git(t.root, ['hash-object', '-w', '--stdin'], { input: text });
123
+ git(t.root, ['update-index', '--add', '--cacheinfo', `100644,${blob},${path}`], { env });
124
+ }
125
+ for (const [path, b] of blobs) {
126
+ if (!files.has(path))
127
+ git(t.root, ['update-index', '--add', '--cacheinfo', `${b.mode},${b.sha},${path}`], { env });
128
+ }
129
+ const tree = git(t.root, ['write-tree'], { env });
130
+ rmSync(env.GIT_INDEX_FILE, { force: true });
131
+ if (parent && git(t.root, ['rev-parse', `${parent}^{tree}`]) === tree) {
132
+ ctx.out(`reports on ${branch} are up to date`);
133
+ return 0;
134
+ }
135
+ const msg = `Update project reports for ${date}${input.commit ? ` from ${input.commit}` : ''}`;
136
+ const commit = git(t.root, ['commit-tree', tree, ...(parent ? ['-p', parent] : []), '-m', msg]);
137
+ git(t.root, ['update-ref', `refs/heads/${branch}`, commit]);
138
+ ctx.out(`committed reports to ${branch} (${commit.slice(0, 7)})`);
139
+ if (!push)
140
+ return 0;
141
+ try {
142
+ git(t.root, ['push', '--quiet', remote, `${commit}:refs/heads/${branch}`]);
143
+ ctx.out(`pushed ${branch} to ${remote}`);
144
+ return 0;
145
+ }
146
+ catch (e) {
147
+ if (!(e instanceof GitError))
148
+ throw e;
149
+ ctx.err(`push of ${branch} was rejected; retrying on top of the new state`);
150
+ }
151
+ }
152
+ throw new UserError(`could not push ${branch} after 3 attempts`, 1);
153
+ }
154
+ /**
155
+ * The attachment files of the main branch and of the claim branches (for their own tickets), as
156
+ * existing blobs: the snapshot refers to them without storing anything new.
157
+ */
158
+ function attachmentBlobs(t, claims) {
159
+ const out = new Map();
160
+ const base = `${t.rel ? `${t.rel}/` : ''}${ATTACHMENTS_DIR}`;
161
+ const read = (ref, dir) => {
162
+ for (const line of (tryGit(t.root, ['ls-tree', '-r', ref, '--', dir]) ?? '').split('\n').filter(Boolean)) {
163
+ const m = /^(\d+) blob ([0-9a-f]+)\t(.*)$/.exec(line);
164
+ if (m)
165
+ out.set(m[3], { mode: m[1], sha: m[2] });
166
+ }
167
+ };
168
+ read('HEAD', base);
169
+ if (!t.code && t.config.mode !== 'central') {
170
+ for (const c of claims)
171
+ read(`refs/remotes/${t.config.git.remote}/${c.branch}`, `${base}/${c.id}`);
172
+ }
173
+ return out;
174
+ }
175
+ function reportsReadme(t, base) {
176
+ return [
177
+ `# ${t.config.key} project reports`,
178
+ '',
179
+ 'This branch is written by the nit report job. It holds a snapshot of the tracker and the reports,',
180
+ 'one commit per update, so its history is the history of the project state.',
181
+ '',
182
+ `* [Status overview](${base}reports/README.md)`,
183
+ `* [Board](${base}reports/board.md)`,
184
+ `* [Schedule](${base}reports/gantt.md)`,
185
+ '',
186
+ ].join('\n');
187
+ }
@@ -0,0 +1,232 @@
1
+ import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, writeFileSync } from 'node:fs';
2
+ import { basename, dirname, join, relative, resolve, sep } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { POINTER_FILE, TRACKER_DIR, UserError, buildTracker, withWorkflowGuide } from '@knitmd/core';
5
+ import { fsFiles, loadConfig } from '../tracker.js';
6
+ import { currentBranch, repoRoot, tryGit } from '../git.js';
7
+ import { personKey } from '../person.js';
8
+ import { CODE_HOOKS, TRACKER_HOOKS, installHooks } from './hooks.js';
9
+ const TEMPLATES = fileURLToPath(new URL('../../templates/', import.meta.url));
10
+ export const INSTALL_COMMAND = 'npm install --global knitmd';
11
+ function fill(text, vars) {
12
+ return text.replace(/\{\{(\w+)\}\}/g, (m, k) => vars[k] ?? m);
13
+ }
14
+ function template(path, vars) {
15
+ return fill(readFileSync(join(TEMPLATES, path), 'utf8'), vars);
16
+ }
17
+ function defaultMain(root) {
18
+ const head = tryGit(root, ['symbolic-ref', '--quiet', '--short', 'refs/remotes/origin/HEAD']);
19
+ if (head)
20
+ return head.replace(/^origin\//, '');
21
+ return currentBranch(root) ?? 'main';
22
+ }
23
+ function deriveKey(root) {
24
+ const letters = basename(root)
25
+ .toUpperCase()
26
+ .replace(/[^A-Z0-9]/g, '');
27
+ return (/^[A-Z]/.test(letters) ? letters : `P${letters}`).slice(0, 4) || 'PROJ';
28
+ }
29
+ /** Adds a section to an agent instructions file (CLAUDE.md, else AGENTS.md). */
30
+ function addAgentPointer(ctx, root, guide) {
31
+ const candidates = ['CLAUDE.md', 'AGENTS.md'].map((f) => join(root, f));
32
+ const target = candidates.find(existsSync) ?? join(root, 'AGENTS.md');
33
+ const text = existsSync(target) ? readFileSync(target, 'utf8') : '';
34
+ if (text.includes(guide))
35
+ return;
36
+ const section = [
37
+ '## Tickets',
38
+ '',
39
+ `Work is tracked with Knit. Read \`${guide}\` before starting a task, and use`,
40
+ '`nit next`, `nit start <ID>` and `nit finish`.',
41
+ '',
42
+ ].join('\n');
43
+ writeFileSync(target, text === '' ? `# Agent instructions\n\n${section}` : `${text.replace(/\n*$/, '\n\n')}${section}`);
44
+ ctx.out(`${relative(ctx.cwd, target) || target}: added the ticket guide pointer`);
45
+ }
46
+ function addReadmeLink(ctx, root, dir, branch) {
47
+ const readme = ['README.md', 'readme.md'].map((f) => join(root, f)).find(existsSync);
48
+ if (!readme)
49
+ return;
50
+ const text = readFileSync(readme, 'utf8');
51
+ const link = `../../blob/${branch}/${dir}/reports/README.md`;
52
+ if (text.includes(link))
53
+ return;
54
+ const section = [
55
+ '## Project status',
56
+ '',
57
+ `[Status, board and schedule](${link}), updated by CI from the tickets in \`${dir}/\`.`,
58
+ '',
59
+ ].join('\n');
60
+ writeFileSync(readme, `${text.replace(/\n*$/, '\n\n')}${section}`);
61
+ ctx.out(`${relative(ctx.cwd, readme)}: added the project status link`);
62
+ }
63
+ export function cmdInit(ctx, o) {
64
+ const root = repoRoot(ctx.cwd) ?? resolve(ctx.cwd);
65
+ const dir = join(root, TRACKER_DIR);
66
+ const exists = existsSync(join(dir, 'proj.yml'));
67
+ if (exists && !o.force && !o.ci) {
68
+ throw new UserError(`${dir}/proj.yml already exists (use --ci to add only the CI workflows)`);
69
+ }
70
+ const ciOnly = exists && !o.force;
71
+ const key = (o.key ?? deriveKey(root)).toUpperCase();
72
+ if (!/^[A-Z][A-Z0-9]*$/.test(key))
73
+ throw new UserError(`--key '${key}' must be upper-case letters and digits`);
74
+ const main = defaultMain(root);
75
+ const userName = tryGit(root, ['config', 'user.name']);
76
+ const people = [
77
+ ...(userName
78
+ ? [` ${personKey(userName)}: { name: ${JSON.stringify(userName)} } # rename the key to your hosting user name`]
79
+ : []),
80
+ ' agent:claude: { name: Claude, agent: true }',
81
+ ].join('\n');
82
+ const repos = o.central
83
+ ? [
84
+ '',
85
+ 'repos: # the code repositories that refer to this tracker',
86
+ ' # auth-service: { url: "git@github.com:acme/auth-service.git", branch: main, path: ../auth-service }',
87
+ '',
88
+ 'sync:',
89
+ ' # since: 2026-12-01 # ignore older commits',
90
+ ].join('\n')
91
+ : '';
92
+ const vars = {
93
+ key,
94
+ mode: o.central ? 'central' : 'embedded',
95
+ main,
96
+ people,
97
+ repos,
98
+ dir: TRACKER_DIR,
99
+ branch: `${key.toLowerCase()}-12`,
100
+ reportsBranch: 'project-reports',
101
+ branchGlob: `${key.toLowerCase()}-*`,
102
+ install: INSTALL_COMMAND,
103
+ };
104
+ const written = [];
105
+ const write = (path, text) => {
106
+ if (existsSync(path) && !o.force)
107
+ return;
108
+ mkdirSync(dirname(path), { recursive: true });
109
+ writeFileSync(path, text);
110
+ written.push(path);
111
+ };
112
+ if (ciOnly) {
113
+ const cfg = loadConfig(join(dir, 'proj.yml'));
114
+ const ciVars = { ...vars, key: cfg.key, main: cfg.git.main, branchGlob: `${cfg.key.toLowerCase()}-*` };
115
+ write(join(root, '.github', 'workflows', 'project.yml'), template('ci/tracker.yml', ciVars));
116
+ if (cfg.mode === 'central')
117
+ write(join(root, '.github', 'workflows', 'project-sync.yml'), template('ci/tracker-sync.yml', ciVars));
118
+ for (const p of written)
119
+ ctx.out(relative(ctx.cwd, p) || p);
120
+ return 0;
121
+ }
122
+ mkdirSync(join(dir, 'tickets'), { recursive: true });
123
+ mkdirSync(join(dir, 'milestones'), { recursive: true });
124
+ mkdirSync(join(dir, 'templates'), { recursive: true });
125
+ write(join(dir, 'proj.yml'), template('tracker/proj.yml', vars).replace(/\n{3,}/g, '\n\n'));
126
+ write(join(dir, 'GUIDE.md'), template('tracker/GUIDE.md', vars));
127
+ for (const f of readdirSync(join(TEMPLATES, 'tracker', 'templates'))) {
128
+ write(join(dir, 'templates', f), template(`tracker/templates/${f}`, vars));
129
+ }
130
+ for (const d of ['tickets', 'milestones'])
131
+ write(join(dir, d, '.gitkeep'), '');
132
+ // Validate what we wrote, and generate the workflow section of the guide.
133
+ loadConfig(join(dir, 'proj.yml'));
134
+ const guidePath = join(dir, 'GUIDE.md');
135
+ if (written.includes(guidePath)) {
136
+ const real = realpathSync(dir);
137
+ const t = buildTracker({ dir: real, root: repoRoot(real) ?? real, files: fsFiles(repoRoot(real) ?? real) });
138
+ writeFileSync(guidePath, withWorkflowGuide(t, readFileSync(guidePath, 'utf8')));
139
+ }
140
+ for (const p of written)
141
+ ctx.out(relative(ctx.cwd, p) || p);
142
+ if (o.mcp)
143
+ writeMcpConfigs(ctx, root);
144
+ if (o.pointers !== false) {
145
+ addAgentPointer(ctx, root, `${TRACKER_DIR}/GUIDE.md`);
146
+ addReadmeLink(ctx, root, TRACKER_DIR, 'project-reports');
147
+ }
148
+ if (o.ci) {
149
+ write(join(root, '.github', 'workflows', 'project.yml'), template('ci/tracker.yml', vars));
150
+ if (o.central)
151
+ write(join(root, '.github', 'workflows', 'project-sync.yml'), template('ci/tracker-sync.yml', vars));
152
+ ctx.out('wrote the CI workflows to .github/workflows/');
153
+ }
154
+ if (o.hooks !== false && repoRoot(ctx.cwd))
155
+ installHooks(ctx, root, TRACKER_HOOKS);
156
+ ctx.out('');
157
+ ctx.out(`tracker ${key} ready. Next: \`nit new feature "<title>"\`${o.ci ? '' : '; `nit init --ci` adds the CI workflows'}`);
158
+ return 0;
159
+ }
160
+ /** `link <tracker>`: connects a code repository to a central tracker. */
161
+ export function cmdLink(ctx, o, trackerArg) {
162
+ if (!trackerArg)
163
+ throw new UserError('usage: nit link <path to the tracker repository> [--repo <name>]');
164
+ const root = repoRoot(ctx.cwd);
165
+ if (!root)
166
+ throw new UserError('run `nit link` inside the code repository');
167
+ const given = resolve(ctx.cwd, trackerArg);
168
+ const trackerRoot = existsSync(given) ? realpathSync(given) : given;
169
+ const projYml = [join(trackerRoot, TRACKER_DIR, 'proj.yml'), join(trackerRoot, 'proj.yml')].find(existsSync);
170
+ if (!projYml)
171
+ throw new UserError(`no tracker at ${trackerRoot} (no ${TRACKER_DIR}/proj.yml)`);
172
+ const cfg = loadConfig(projYml);
173
+ const repo = o.repo ?? basename(root);
174
+ const rel = relative(root, trackerRoot).split(sep).join('/') || '.';
175
+ writeFileSync(join(root, POINTER_FILE), `# Knit: where the tickets of this repository are\ntracker: ${rel}\nrepo: ${repo}\n`);
176
+ ctx.out(`${POINTER_FILE}: tracker ${rel}, repo ${repo}`);
177
+ if (!cfg.repos[repo]) {
178
+ const url = tryGit(root, ['remote', 'get-url', 'origin']);
179
+ ctx.err(`warning: '${repo}' is not in repos of ${relative(ctx.cwd, projYml)}; add:\n ${repo}: { ${url ? `url: "${url}", ` : ''}branch: ${defaultMain(root)}, path: ${relative(trackerRoot, root).split(sep).join('/')} }`);
180
+ }
181
+ if (o.mcp)
182
+ writeMcpConfigs(ctx, root);
183
+ if (o.pointers !== false) {
184
+ const guide = `${rel}/${relative(trackerRoot, dirname(projYml)).split(sep).join('/') || '.'}/GUIDE.md`.replace('/./', '/');
185
+ addAgentPointer(ctx, root, guide);
186
+ }
187
+ if (o.ci) {
188
+ const url = tryGit(trackerRoot, ['remote', 'get-url', 'origin']) ?? '';
189
+ const m = /github\.com[:/]([^/]+\/[^/]+?)(\.git)?$/.exec(url);
190
+ const path = join(root, '.github', 'workflows', 'tickets.yml');
191
+ mkdirSync(dirname(path), { recursive: true });
192
+ writeFileSync(path, template('ci/code.yml', {
193
+ main: defaultMain(root),
194
+ trackerRepo: m?.[1] ?? 'OWNER/TRACKER',
195
+ install: INSTALL_COMMAND,
196
+ }));
197
+ ctx.out(relative(ctx.cwd, path));
198
+ }
199
+ if (o.hooks !== false)
200
+ installHooks(ctx, root, CODE_HOOKS);
201
+ return 0;
202
+ }
203
+ /**
204
+ * Registers `nit mcp` for Claude Code (`.mcp.json`) and VS Code with GitHub Copilot
205
+ * (`.vscode/mcp.json`), keeping other servers in existing files.
206
+ */
207
+ function writeMcpConfigs(ctx, root) {
208
+ const server = (agent) => ({ command: 'nit', args: ['mcp'], env: { NIT_USER: agent } });
209
+ const targets = [
210
+ ['.mcp.json', 'mcpServers', server('agent:claude')],
211
+ [join('.vscode', 'mcp.json'), 'servers', { type: 'stdio', ...server('agent:copilot') }],
212
+ ];
213
+ for (const [file, key, entry] of targets) {
214
+ const path = join(root, file);
215
+ let config = {};
216
+ if (existsSync(path)) {
217
+ try {
218
+ config = JSON.parse(readFileSync(path, 'utf8'));
219
+ }
220
+ catch {
221
+ throw new UserError(`${file} is not valid JSON; fix it or add the knit server by hand`);
222
+ }
223
+ }
224
+ if (config[key]?.knit)
225
+ continue;
226
+ const { mdproj: _, ...servers } = config[key] ?? {}; // the entry of earlier versions
227
+ config[key] = { ...servers, knit: entry };
228
+ mkdirSync(dirname(path), { recursive: true });
229
+ writeFileSync(path, `${JSON.stringify(config, null, 2)}\n`);
230
+ ctx.out(`${relative(ctx.cwd, path) || path}: registered the knit MCP server`);
231
+ }
232
+ }
@@ -0,0 +1,146 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, mkdirSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { join, resolve } from 'node:path';
5
+ import { isClosed, LOG_FORMAT, parseLog, parseReferences, appendLog, criteria, list, logLines, set, str, repoPath, ticketId, UserError, } from '@knitmd/core';
6
+ import { save } from '../tracker.js';
7
+ import { git, refExists, tryGit } from '../git.js';
8
+ import { publish } from '../publish.js';
9
+ import { open } from './basic.js';
10
+ import { lookup } from './hooks.js';
11
+ const SYNC_LINE = /\bsync: ([\w.-]+)@([0-9a-f]{7,40}) (Refs|Closes)\b/;
12
+ function cacheDir(ctx, url) {
13
+ const base = ctx.env.XDG_CACHE_HOME || join(ctx.env.HOME || homedir(), '.cache');
14
+ const hash = createHash('sha256').update(url).digest('hex').slice(0, 16);
15
+ return join(base, 'nit', 'repos', hash);
16
+ }
17
+ /** Fetches a code repository and returns where and which ref to read. */
18
+ function openRepo(ctx, t, name) {
19
+ const r = t.config.repos[name];
20
+ if (r.path && existsSync(resolve(t.root, r.path))) {
21
+ const root = resolve(t.root, r.path);
22
+ const remote = 'origin';
23
+ if (tryGit(root, ['remote']) === undefined)
24
+ return undefined;
25
+ if ((tryGit(root, ['remote']) ?? '').split('\n').includes(remote)) {
26
+ if (tryGit(root, ['fetch', '--quiet', remote, r.branch]) === undefined)
27
+ ctx.err(`warning: could not fetch ${name}`);
28
+ if (refExists(root, `refs/remotes/${remote}/${r.branch}`))
29
+ return { root, ref: `${remote}/${r.branch}` };
30
+ }
31
+ return refExists(root, r.branch) ? { root, ref: r.branch } : undefined;
32
+ }
33
+ if (r.url) {
34
+ const dir = cacheDir(ctx, r.url);
35
+ if (!existsSync(dir)) {
36
+ mkdirSync(dir, { recursive: true });
37
+ git(dir, ['clone', '--quiet', '--bare', r.url, '.']);
38
+ }
39
+ else {
40
+ git(dir, ['fetch', '--quiet', 'origin', '+refs/heads/*:refs/heads/*']);
41
+ }
42
+ return { root: dir, ref: r.branch };
43
+ }
44
+ ctx.err(`warning: repository ${name} has neither a local path nor a url`);
45
+ return undefined;
46
+ }
47
+ /** Repositories that have closed a ticket, from the sync lines of its log. */
48
+ export function closedIn(doc) {
49
+ const out = new Map();
50
+ for (const l of logLines(doc)) {
51
+ const m = SYNC_LINE.exec(l);
52
+ if (m && m[3] === 'Closes')
53
+ out.set(m[1], /(\d{4}-\d{2}-\d{2})/.exec(l)?.[1] ?? '');
54
+ }
55
+ return out;
56
+ }
57
+ export function syncTracker(ctx, t, only) {
58
+ const names = Object.keys(t.config.repos).filter((n) => !only || n === only);
59
+ if (names.length === 0) {
60
+ throw new UserError(only ? `repository '${only}' is not in repos of proj.yml` : 'no repos in proj.yml: sync is for the central mode');
61
+ }
62
+ const result = { recorded: 0, closed: [], awaitingCriteria: [], waitingForRepos: [], unknown: [] };
63
+ const touched = new Set();
64
+ for (const name of names) {
65
+ const repo = openRepo(ctx, t, name);
66
+ if (!repo)
67
+ continue;
68
+ const args = ['log', LOG_FORMAT, repo.ref];
69
+ if (t.config.sync.since)
70
+ args.push(`--since=${t.config.sync.since}`);
71
+ const commits = parseLog(git(repo.root, args)).reverse();
72
+ for (const c of commits) {
73
+ const refs = parseReferences(c.message, t.config.key);
74
+ const kinds = [
75
+ ...refs.refs.map((id) => [id, 'Refs']),
76
+ ...refs.closes.map((id) => [id, 'Closes']),
77
+ ];
78
+ for (const [id, kind] of kinds) {
79
+ const doc = lookup(t, id);
80
+ if (!doc) {
81
+ if (!result.unknown.includes(id))
82
+ result.unknown.push(id);
83
+ continue;
84
+ }
85
+ const key = `${name}@${c.hash.slice(0, 7)}`;
86
+ if (logLines(doc).some((l) => l.includes(`sync: ${key} `)))
87
+ continue;
88
+ appendLog(doc, `- ${c.date} sync: ${key} ${kind} "${c.subject.replace(/"/g, "'")}"`);
89
+ touched.add(doc);
90
+ result.recorded++;
91
+ }
92
+ }
93
+ }
94
+ for (const doc of t.tickets) {
95
+ const closed = closedIn(doc);
96
+ if (closed.size === 0 || isClosed(t, str(doc, 'status')))
97
+ continue;
98
+ const required = list(doc, 'repos');
99
+ const missing = required.filter((r) => !closed.has(r));
100
+ const id = ticketId(doc);
101
+ if (missing.length > 0) {
102
+ result.waitingForRepos.push({ id, repos: missing });
103
+ continue;
104
+ }
105
+ if (criteria(doc).length === 0 || criteria(doc).some((c) => !c.checked)) {
106
+ result.awaitingCriteria.push(id);
107
+ continue;
108
+ }
109
+ const closedOn = [...closed.values()].sort().at(-1);
110
+ const started = str(doc, 'started');
111
+ const date = started && started > closedOn ? started : closedOn;
112
+ set(doc, 'status', t.config.workflow.done);
113
+ if (!started)
114
+ set(doc, 'started', date);
115
+ set(doc, 'done', date);
116
+ touched.add(doc);
117
+ result.closed.push(id);
118
+ }
119
+ for (const doc of touched)
120
+ save(doc);
121
+ return result;
122
+ }
123
+ export function cmdSync(ctx, o) {
124
+ const t = open(ctx, o, { fresh: true });
125
+ const before = new Map(t.tickets.map((d) => [d, d.original]));
126
+ const r = syncTracker(ctx, t, o.repo);
127
+ const changedPaths = t.tickets.filter((d) => before.get(d) !== d.original).map((d) => repoPath(t, d.path));
128
+ if (changedPaths.length > 0) {
129
+ const subject = `Sync ${r.recorded} commit reference(s)${r.closed.length ? `, close ${r.closed.join(', ')}` : ''}`;
130
+ publish(t, ctx, changedPaths, subject, o);
131
+ }
132
+ if (o.json) {
133
+ ctx.out(JSON.stringify(r, null, 2));
134
+ return 0;
135
+ }
136
+ ctx.out(`recorded ${r.recorded} commit reference(s)`);
137
+ if (r.closed.length)
138
+ ctx.out(`closed: ${r.closed.join(', ')}`);
139
+ if (r.awaitingCriteria.length)
140
+ ctx.out(`closed in code, awaiting criteria: ${r.awaitingCriteria.join(', ')}`);
141
+ for (const w of r.waitingForRepos)
142
+ ctx.out(`${w.id}: waiting for ${w.repos.join(', ')}`);
143
+ if (r.unknown.length)
144
+ ctx.err(`warning: unknown tickets referenced: ${r.unknown.join(', ')}`);
145
+ return 0;
146
+ }
package/dist/ctx.js ADDED
@@ -0,0 +1,8 @@
1
+ /** Today as YYYY-MM-DD in local time, or `$NIT_TODAY`. */
2
+ export function today(ctx) {
3
+ const fixed = ctx.env.NIT_TODAY;
4
+ if (fixed)
5
+ return fixed;
6
+ const d = new Date();
7
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
8
+ }