slicekit 0.1.2 → 0.2.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.
Files changed (65) hide show
  1. package/README.md +15 -13
  2. package/package.json +3 -2
  3. package/src/adapters/githost/fixture.js +24 -1
  4. package/src/adapters/githost/gh-json.js +69 -2
  5. package/src/adapters/githost/github.js +16 -1
  6. package/src/build/commit.js +152 -26
  7. package/src/build/config.js +50 -0
  8. package/src/build/pr.js +30 -15
  9. package/src/build/record.js +8 -2
  10. package/src/build/red.js +4 -3
  11. package/src/build/render.js +155 -0
  12. package/src/build/verdict.js +29 -0
  13. package/src/build/worktree.js +26 -5
  14. package/src/check/ci-event.js +17 -0
  15. package/src/check/rules/citations.js +53 -2
  16. package/src/check/rules/commands.js +32 -4
  17. package/src/check/rules/trailer.js +5 -16
  18. package/src/check/rules/workspace.js +86 -0
  19. package/src/cli/build.js +34 -8
  20. package/src/cli/ci.js +150 -0
  21. package/src/cli/decide.js +4 -3
  22. package/src/cli/gaps.js +6 -5
  23. package/src/cli/graph.js +79 -0
  24. package/src/cli/history.js +17 -0
  25. package/src/cli/hook.js +1 -1
  26. package/src/cli/impact.js +17 -0
  27. package/src/cli/index.js +28 -3
  28. package/src/cli/instructions.js +1 -1
  29. package/src/cli/intake.js +3 -3
  30. package/src/cli/query.js +39 -0
  31. package/src/cli/shipped.js +32 -0
  32. package/src/cli/state.js +42 -2
  33. package/src/cli/trace.js +21 -0
  34. package/src/cli/uncovered.js +32 -0
  35. package/src/cli/visualize.js +88 -0
  36. package/src/cli/workflow.js +6 -2
  37. package/src/config.js +85 -0
  38. package/src/graph/build.js +312 -0
  39. package/src/graph/docs.js +241 -0
  40. package/src/graph/git-walk.js +91 -0
  41. package/src/graph/history.js +60 -0
  42. package/src/graph/impact.js +143 -0
  43. package/src/graph/kitfiles.js +60 -0
  44. package/src/graph/load.js +93 -0
  45. package/src/graph/prs.js +136 -0
  46. package/src/graph/render.js +28 -0
  47. package/src/graph/schema.js +108 -0
  48. package/src/graph/shipped.js +32 -0
  49. package/src/graph/tests.js +45 -0
  50. package/src/graph/trace.js +83 -0
  51. package/src/graph/uncovered.js +16 -0
  52. package/src/graph/workspace.js +188 -0
  53. package/src/hook-cli.js +1 -1
  54. package/src/init.js +2 -0
  55. package/src/instructions.js +26 -8
  56. package/src/state/index.js +35 -4
  57. package/src/verdict.js +14 -2
  58. package/src/visualize/client.js +489 -0
  59. package/src/visualize/page.js +100 -0
  60. package/src/visualize/server.js +46 -0
  61. package/src/workflow.js +87 -9
  62. package/templates/instructions/agents/reviewer.md +7 -7
  63. package/templates/instructions/commands/build.md +34 -4
  64. package/templates/workflow/pins.json +2 -1
  65. package/templates/workflow/slicekit.yml +32 -1
@@ -0,0 +1,312 @@
1
+ // The graph builder (REQ-4.1 to REQ-4.4, D-13, D-23, D-44): reads the docs, the kit's files, the
2
+ // test files' REQ lines and git; keeps one fragment per source in the index so a second run walks
3
+ // only new commits and reads only changed files; assembles, validates and writes graph.json.
4
+ // Deterministic: no clock, locale, absolute path or environment value reaches the graph.
5
+ import crypto from 'node:crypto';
6
+ import { execFileSync } from 'node:child_process';
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { kitPaths } from '../paths.js';
10
+ import { docFragment, docsPrefix, intakeFragment, intakeKey, readsDoc } from './docs.js';
11
+ import { existing, reachable, refTips, walkCommits, webUrl } from './git-walk.js';
12
+ import { journalFragment, stateFragment, verdictFragment } from './kitfiles.js';
13
+ import { prNumbers, pullRequestNodes } from './prs.js';
14
+ import { GraphError, SCHEMA_VERSION, cmp, keyOf, nodeId, serializeGraph, validateGraph } from './schema.js';
15
+ import { reqMentions, testFiles } from './tests.js';
16
+
17
+ const INDEX_VERSION = 1;
18
+ const posix = (p) => p.split(path.sep).join('/');
19
+ const sha256 = (buf) => crypto.createHash('sha256').update(buf).digest('hex');
20
+
21
+ export const graphDir = (root, cfg) => kitPaths(root, cfg).graph;
22
+ const indexFile = (root, cfg) => path.join(graphDir(root, cfg), 'index.json');
23
+ const cacheDir = (root, cfg) => path.join(graphDir(root, cfg), 'cache');
24
+
25
+ function readIndex(root, cfg) {
26
+ try {
27
+ const idx = JSON.parse(fs.readFileSync(indexFile(root, cfg), 'utf8'));
28
+ if (idx?.version === INDEX_VERSION && idx.repos && idx.files) return idx;
29
+ } catch {
30
+ // absent or unreadable: a full build
31
+ }
32
+ return null;
33
+ }
34
+
35
+ function isRepoRoot(root) {
36
+ try {
37
+ execFileSync('git', ['rev-parse', '--git-dir'], { cwd: root, stdio: ['ignore', 'pipe', 'pipe'] });
38
+ return true;
39
+ } catch {
40
+ return false;
41
+ }
42
+ }
43
+
44
+ // Tracked and untracked, not ignored: repository-relative POSIX paths.
45
+ function listedFiles(root) {
46
+ const out = execFileSync('git', ['-c', 'core.quotePath=false', 'ls-files', '-co', '--exclude-standard', '-z'], {
47
+ cwd: root,
48
+ encoding: 'utf8',
49
+ stdio: ['ignore', 'pipe', 'pipe'],
50
+ maxBuffer: 1024 * 1024 * 1024,
51
+ });
52
+ return [...new Set(out.split('\0').filter((p) => p !== ''))].sort(cmp);
53
+ }
54
+
55
+ // Every source file of the program repository: {rel, kind}, kind doc, intake, state, verdict,
56
+ // journal or test. Only these are ever opened, and an intake file is only named.
57
+ function sources(root, cfg) {
58
+ const kp = kitPaths(root, cfg);
59
+ const rel = (abs) => posix(path.relative(root, abs));
60
+ const state = `${rel(kp.state)}/`;
61
+ const reviews = `${rel(kp.kit)}/reviews/`;
62
+ const journal = `${rel(kp.journalDir)}/`;
63
+ const docs = docsPrefix(cfg);
64
+ const out = new Map();
65
+ for (const p of listedFiles(root)) {
66
+ if (!fs.existsSync(path.join(root, ...p.split('/')))) continue;
67
+ if (p.startsWith(state) && /^[^/]+\.json$/.test(p.slice(state.length))) out.set(p, 'state');
68
+ else if (p.startsWith(reviews) && /^[^/]+\.md$/.test(p.slice(reviews.length))) out.set(p, 'verdict');
69
+ else if (p.startsWith(journal) && /^[^/]+\.log$/.test(p.slice(journal.length))) out.set(p, 'journal');
70
+ else if (p.startsWith(docs) && intakeKey(cfg, p) !== null) out.set(p, 'intake');
71
+ else if (p.startsWith(docs) && readsDoc(cfg, p)) out.set(p, 'doc');
72
+ }
73
+ for (const p of testFiles(root, cfg)) if (!out.has(p) && fs.existsSync(path.join(root, ...p.split('/')))) out.set(p, 'test');
74
+ return [...out].map(([rel, kind]) => ({ rel, kind })).sort((a, b) => cmp(a.rel, b.rel));
75
+ }
76
+
77
+ function testFragment(rel, text, prefix = '') {
78
+ const p = `${prefix}${rel}`;
79
+ const id = nodeId('test', p);
80
+ const repo = nodeId('repo', prefix === '' ? '.' : prefix.slice(0, -1));
81
+ const edges = [{ kind: 'in', from: id, to: repo, at: `${p}:1` }];
82
+ for (const { req, line } of reqMentions(text)) edges.push({ kind: 'covers', from: id, to: nodeId('requirement', req), at: `${p}:${line}` });
83
+ return { nodes: [{ id, kind: 'test', label: p, from: `${p}:1` }], edges };
84
+ }
85
+
86
+ function fragmentOf(root, cfg, { rel, kind }, text) {
87
+ switch (kind) {
88
+ case 'doc': return docFragment(root, cfg, rel, text);
89
+ case 'intake': return intakeFragment(cfg, rel);
90
+ case 'state': return stateFragment(rel, text);
91
+ case 'verdict': return verdictFragment(rel, text);
92
+ case 'journal': return journalFragment(rel, text);
93
+ case 'test': return testFragment(rel, text);
94
+ default: return { nodes: [], edges: [] };
95
+ }
96
+ }
97
+
98
+ // The file fragments, reusing the index's for every file whose bytes hash the same.
99
+ function fileFragments(root, cfg, list, old, prefix = '') {
100
+ const files = {};
101
+ let read = 0;
102
+ for (const s of list) {
103
+ const key = `${prefix}${s.rel}`;
104
+ let hash;
105
+ let text;
106
+ if (s.kind === 'intake') {
107
+ hash = 'named';
108
+ } else {
109
+ const buf = fs.readFileSync(path.join(root, ...s.rel.split('/')));
110
+ hash = sha256(buf);
111
+ text = buf.toString('utf8');
112
+ }
113
+ const prev = old?.[key];
114
+ if (prev && prev.hash === hash && prev.kind === s.kind) {
115
+ files[key] = prev;
116
+ continue;
117
+ }
118
+ read++;
119
+ const fragment = s.kind === 'test' ? testFragment(s.rel, text, prefix) : fragmentOf(root, cfg, s, text);
120
+ files[key] = { kind: s.kind, hash, fragment };
121
+ }
122
+ return { files, read };
123
+ }
124
+
125
+ // The commits of one repository, walked from its recorded tips on.
126
+ function repoCommits(repoRoot, defaultBranch, old, full) {
127
+ const tips = refTips(repoRoot, defaultBranch);
128
+ const recorded = full || !old ? [] : existing(repoRoot, [...new Set(old.tips.map((t) => t.sha))]);
129
+ const known = full || !old ? {} : old.commits;
130
+ const tipShas = [...new Set(tips.map((t) => t.sha))];
131
+ const walked = walkCommits(repoRoot, { include: tipShas, exclude: recorded });
132
+ const all = { ...known };
133
+ for (const c of walked) all[c.sha] = c;
134
+ const reach = reachable(repoRoot, tipShas);
135
+ const fromDefault = reachable(repoRoot, [tips[0].sha]);
136
+ const commits = {};
137
+ for (const sha of Object.keys(all).sort(cmp)) if (reach.has(sha)) commits[sha] = all[sha];
138
+ return { tips, commits, walked: walked.length, fromDefault, defaultSha: tips[0].sha };
139
+ }
140
+
141
+ const time = (c) => Date.parse(c.date);
142
+
143
+ // Commit, file and touched/in edges from the commits of one repository.
144
+ function commitPart(commits, fromDefault, prefix, repoId) {
145
+ const nodes = [];
146
+ const edges = [];
147
+ const firstTouch = new Map();
148
+ const ordered = Object.values(commits).sort((a, b) => time(a) - time(b) || cmp(a.sha, b.sha));
149
+ for (const c of ordered) {
150
+ const id = nodeId('commit', c.sha);
151
+ nodes.push({ id, kind: 'commit', label: c.subject, from: c.sha, date: c.date, subject: c.subject, parents: c.parents, merge: c.parents.length > 1, default: fromDefault.has(c.sha) });
152
+ for (const f of c.files) {
153
+ const p = `${prefix}${f}`;
154
+ if (!firstTouch.has(p)) firstTouch.set(p, c.sha);
155
+ edges.push({ kind: 'touched', from: id, to: nodeId('file', p), at: c.sha });
156
+ }
157
+ for (const s of c.slices) edges.push({ kind: 'in', from: id, to: nodeId('slice', s), at: c.sha });
158
+ }
159
+ for (const [p, sha] of firstTouch) {
160
+ nodes.push({ id: nodeId('file', p), kind: 'file', label: p, from: sha });
161
+ edges.push({ kind: 'in', from: nodeId('file', p), to: repoId, at: sha });
162
+ }
163
+ return { nodes, edges };
164
+ }
165
+
166
+ // buildGraph(root, cfg, {host, full, repos, skipped}) -> {graph, report, index}. `host` null with
167
+ // `skipped` a note means no host could be made; `repos` (S-20) are the reached workspace
168
+ // repositories, [{name, root, defaultBranch, host?, skipped?}]: each is walked as the program
169
+ // repository is, its file and test nodes prefixed `<name>/`, its pull requests read from its own merge
170
+ // commit subjects and from the state files of the slices whose `repo` names it, keyed `<name>#<n>`.
171
+ export function buildGraph(root, cfg, { host = null, full = false, repos = [], skipped = null } = {}) {
172
+ if (!isRepoRoot(root)) throw new GraphError(2, 'graph: not a git repository');
173
+ const old = full ? null : readIndex(root, cfg);
174
+ const warnings = [];
175
+
176
+ const main = repoCommits(root, cfg.defaultBranch, old?.repos?.['.'], full);
177
+ const list = sources(root, cfg);
178
+ const { files, read: readMain } = fileFragments(root, cfg, list, old?.files);
179
+ let read = readMain;
180
+ let fileCount = list.length;
181
+ let walked = main.walked;
182
+ const indexRepos = { '.': { tips: main.tips, commits: main.commits } };
183
+ const repoNodes = [{ id: nodeId('repo', '.'), kind: 'repo', label: '.', from: '.', ...(webUrl(root) ? { web: webUrl(root) } : {}) }];
184
+ const parts = [commitPart(main.commits, main.fromDefault, '', nodeId('repo', '.'))];
185
+ const repoShas = [{ name: '.', sha: main.defaultSha }];
186
+ let allCommits = Object.values(main.commits);
187
+ const reached = [];
188
+
189
+ for (const r of [...repos].sort((a, b) => cmp(a.name, b.name))) {
190
+ const prefix = `${r.name}/`;
191
+ const w = repoCommits(r.root, r.defaultBranch, old?.repos?.[r.name], full);
192
+ walked += w.walked;
193
+ indexRepos[r.name] = { tips: w.tips, commits: w.commits };
194
+ const tl = testFiles(r.root, cfg).map((rel) => ({ rel, kind: 'test' }));
195
+ const f = fileFragments(r.root, cfg, tl, old?.files, prefix);
196
+ Object.assign(files, f.files);
197
+ read += f.read;
198
+ fileCount += tl.length;
199
+ repoNodes.push({ id: nodeId('repo', r.name), kind: 'repo', label: r.name, from: r.name, ...(webUrl(r.root) ? { web: webUrl(r.root) } : {}) });
200
+ parts.push(commitPart(w.commits, w.fromDefault, prefix, nodeId('repo', r.name)));
201
+ repoShas.push({ name: r.name, sha: w.defaultSha });
202
+ reached.push({ repo: r, commits: Object.values(w.commits) });
203
+ }
204
+
205
+ const fragments = Object.keys(files).sort(cmp).map((k) => files[k].fragment);
206
+ for (const f of fragments) warnings.push(...(f.warnings ?? []));
207
+
208
+ // Nodes: whole nodes first (the first by `from` wins a duplicate), then patches merged in.
209
+ const byId = new Map();
210
+ const whole = fragments.flatMap((f) => f.nodes).filter((n) => !n.patch);
211
+ for (const n of [...whole, ...parts.flatMap((p) => p.nodes), ...repoNodes]) {
212
+ if (byId.has(n.id)) {
213
+ warnings.push(`graph: ${n.from} defines ${keyOf(n.id)} again`);
214
+ continue;
215
+ }
216
+ byId.set(n.id, { ...n });
217
+ }
218
+ for (const p of fragments.flatMap((f) => f.nodes).filter((n) => n.patch)) {
219
+ const target = byId.get(p.id);
220
+ if (!target) continue;
221
+ const { id: _id, patch: _patch, ...attrs } = p;
222
+ Object.assign(target, attrs);
223
+ }
224
+
225
+ // Pull requests, with reviewed-by edges to the verdicts of their slice.
226
+ const verdicts = new Map();
227
+ for (const n of [...byId.values()].filter((x) => x.kind === 'verdict').sort((a, b) => cmp(a.id, b.id))) {
228
+ const slice = fragments.flatMap((f) => f.edges).find((e) => e.kind === 'in' && e.from === n.id)?.to;
229
+ if (!slice) continue;
230
+ if (!verdicts.has(slice)) verdicts.set(slice, []);
231
+ verdicts.get(slice).push(n);
232
+ }
233
+ // A state file's pull request is its slice's, in the repository the slice names (S-20 B-1); a release
234
+ // file's refs are the program's. A ref of a slice in a repository that was not reached is dropped.
235
+ const repoOfSlice = new Map([...byId.values()].filter((n) => n.kind === 'slice').map((n) => [n.id, n.repo ?? '.']));
236
+ const owner = (ref) => (ref.slice ? (repoOfSlice.get(ref.slice) ?? '.') : '.');
237
+ const allRefs = fragments.flatMap((f) => f.prRefs ?? []);
238
+ const refsOf = (name) => [{ prRefs: allRefs.filter((ref) => owner(ref) === name) }];
239
+ const prs = pullRequestNodes(prNumbers(refsOf('.'), allCommits), { host, cacheDir: cacheDir(root, cfg), verdicts, skipped });
240
+ for (const { repo: r, commits } of reached) {
241
+ const sub = pullRequestNodes(prNumbers(refsOf(r.name), commits), { host: r.host ?? null, cacheDir: cacheDir(root, cfg), verdicts, skipped: r.skipped ?? null, repo: r.name });
242
+ prs.nodes.push(...sub.nodes);
243
+ prs.edges.push(...sub.edges);
244
+ prs.notes.push(...sub.notes);
245
+ prs.fetched += sub.fetched;
246
+ prs.cached += sub.cached;
247
+ allCommits = allCommits.concat(commits);
248
+ }
249
+ for (const n of prs.nodes) if (!byId.has(n.id)) byId.set(n.id, n);
250
+
251
+ // Edges: deduplicated; one whose endpoint is not a node is dropped with a warning.
252
+ const seen = new Set();
253
+ const edges = [];
254
+ for (const e of [...fragments.flatMap((f) => f.edges), ...parts.flatMap((p) => p.edges), ...prs.edges]) {
255
+ const k = `${e.kind}\0${e.from}\0${e.to}\0${e.at}`;
256
+ if (seen.has(k)) continue;
257
+ seen.add(k);
258
+ const missing = !byId.has(e.to) ? e.to : !byId.has(e.from) ? e.from : null;
259
+ if (missing) {
260
+ warnings.push(`graph: ${e.at} names ${keyOf(missing)}, which is not in the graph`);
261
+ continue;
262
+ }
263
+ edges.push(e);
264
+ }
265
+
266
+ const head = main.commits[main.defaultSha];
267
+ const graph = {
268
+ schemaVersion: SCHEMA_VERSION,
269
+ builtAt: head?.date ?? null,
270
+ defaultBranch: cfg.defaultBranch,
271
+ sha: main.defaultSha,
272
+ repos: repoShas,
273
+ nodes: [...byId.values()].sort((a, b) => cmp(a.id, b.id)),
274
+ edges,
275
+ };
276
+ const index = { version: INDEX_VERSION, repos: indexRepos, files };
277
+ const report = {
278
+ walked,
279
+ commits: allCommits.length,
280
+ read,
281
+ files: fileCount,
282
+ fetched: prs.fetched,
283
+ cached: prs.cached,
284
+ notes: [...new Set(prs.notes)],
285
+ warnings: [...new Set(warnings)].sort(cmp),
286
+ };
287
+ return { graph, report, index };
288
+ }
289
+
290
+ function writeAtomic(file, text) {
291
+ const tmp = `${file}.${process.pid}.tmp`;
292
+ try {
293
+ fs.writeFileSync(tmp, text);
294
+ fs.renameSync(tmp, file);
295
+ } catch (e) {
296
+ fs.rmSync(tmp, { force: true });
297
+ throw e;
298
+ }
299
+ }
300
+
301
+ // Refuses a graph with problems (nothing written); else writes graph.json and index.json through a
302
+ // temporary name and a rename -> the graph file's repository-relative path.
303
+ export function writeGraph(root, cfg, { graph, index }) {
304
+ const problems = validateGraph(graph);
305
+ if (problems.length > 0) throw new GraphError(1, `graph: schema: ${problems[0]}`);
306
+ const dir = graphDir(root, cfg);
307
+ fs.mkdirSync(dir, { recursive: true });
308
+ const file = path.join(dir, 'graph.json');
309
+ writeAtomic(file, serializeGraph(graph));
310
+ if (index) writeAtomic(indexFile(root, cfg), `${JSON.stringify(index)}\n`);
311
+ return posix(path.relative(root, file));
312
+ }
@@ -0,0 +1,241 @@
1
+ // Nodes and edges from one markdown file under the docs root (REQ-4.1, REQ-4.2): which kind of file
2
+ // it is follows from where it sits. Only IDs and the kit's own shapes are read; nothing is inferred.
3
+ import path from 'node:path';
4
+ import { citedRefs } from '../check/rules/citations.js';
5
+ import { readDecisions } from '../decisions.js';
6
+ import { readGaps } from '../gaps.js';
7
+ import { re } from '../ids.js';
8
+ import { headings, prose } from '../markdown.js';
9
+ import { SliceFileError, parsePhaseFile, parseSliceFile, phaseOfDir } from '../slicefile.js';
10
+ import { nodeId } from './schema.js';
11
+
12
+ const empty = () => ({ nodes: [], edges: [] });
13
+ const all = (name, text) => [...String(text).matchAll(re(name, 'g'))].map((m) => m[0]);
14
+ const uniq = (list) => [...new Set(list)];
15
+
16
+ // GitHub's heading anchor: lower case, punctuation dropped, spaces to dashes.
17
+ export const slug = (text) => text.trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, '').replace(/\s/g, '-');
18
+
19
+ // The docs root as a POSIX prefix: '' for '.', else '<docsRoot>/'.
20
+ export function docsPrefix(cfg) {
21
+ const d = path.posix.normalize(String(cfg.docsRoot).replace(/\\/g, '/')).replace(/\/$/, '');
22
+ return d === '.' || d === '' ? '' : `${d}/`;
23
+ }
24
+
25
+ // Where rel sits under the docs root -> {kind, ...} or null.
26
+ function classify(cfg, rel) {
27
+ const prefix = docsPrefix(cfg);
28
+ if (!rel.startsWith(prefix)) return null;
29
+ const sub = rel.slice(prefix.length);
30
+ if (/^intake\//.test(sub)) return { kind: 'intake' };
31
+ if (!rel.endsWith('.md')) return null;
32
+ if (sub === 'decisions.md') return { kind: 'decisions' };
33
+ if (sub === 'runbook.md') return { kind: 'runbook' };
34
+ if (sub === 'spec/gaps.md') return { kind: 'gaps' };
35
+ let m = /^spec\/contracts\/C-(\d+)-[^/]*\.md$/.exec(sub);
36
+ if (m) return { kind: 'contract', id: `C-${Number(m[1])}` };
37
+ if (/^spec\/[^/]+\.md$/.test(sub)) return { kind: 'spec' };
38
+ m = /^phases\/([^/]+)\/([^/]+)$/.exec(sub);
39
+ if (m) {
40
+ const phase = phaseOfDir(m[1]);
41
+ if (!phase) return null;
42
+ if (/^S-\d+.*\.md$/.test(m[2])) return { kind: 'slice' };
43
+ if (new RegExp(`^P0*${phase.n}\\.md$`).test(m[2])) return { kind: 'phase', phase };
44
+ return null;
45
+ }
46
+ m = /^releases\/P(\d+)\.md$/.exec(sub);
47
+ if (m) return { kind: 'release', id: `P${Number(m[1])}` };
48
+ return null;
49
+ }
50
+
51
+ // The intake key of a file under the intake folder, or null for a sidecar or a placeholder.
52
+ export function intakeKey(cfg, rel) {
53
+ const prefix = `${docsPrefix(cfg)}intake/`;
54
+ if (!rel.startsWith(prefix)) return null;
55
+ const name = rel.slice(prefix.length);
56
+ if (name === '' || name.endsWith('.meta.json') || path.posix.basename(name) === '.keep') return null;
57
+ return name;
58
+ }
59
+
60
+ // An intake file is named, never opened: its node comes from its path alone.
61
+ export function intakeFragment(cfg, rel) {
62
+ const name = intakeKey(cfg, rel);
63
+ if (name === null) return empty();
64
+ return { nodes: [{ id: nodeId('intake', name), kind: 'intake', label: name, from: `${rel}:1` }], edges: [] };
65
+ }
66
+
67
+ function decisions(rel, text) {
68
+ const out = empty();
69
+ for (const r of readDecisions(text).rows) {
70
+ const id = nodeId('decision', r.id);
71
+ const at = `${rel}:${r.line}`;
72
+ out.nodes.push({ id, kind: 'decision', label: r.question, from: at, type: r.type, open: r.table === 'open' });
73
+ const cells = [r.type, r.question, r.answer, r.who, r.why, r.recommendation].filter((c) => c != null).join(' ');
74
+ for (const d of uniq(all('decision', cells))) if (d !== r.id) out.edges.push({ kind: 'cites', from: id, to: nodeId('decision', d), at });
75
+ }
76
+ return out;
77
+ }
78
+
79
+ const citeTarget = (ref) => (ref.kind === 'decision' ? nodeId('decision', ref.name) : nodeId('intake', ref.name));
80
+ const REQ_HEADING = new RegExp(`^(${re('req').source})\\b\\s*(.*)$`);
81
+
82
+ function spec(rel, text) {
83
+ const out = empty();
84
+ const hs = headings(text);
85
+ const body = [...prose(text)];
86
+ hs.forEach((h, i) => {
87
+ if (h.level < 2 || h.level > 3) return;
88
+ const m = REQ_HEADING.exec(h.text);
89
+ if (!m) return;
90
+ const next = hs.slice(i + 1).find((x) => x.level <= h.level || (x.level <= 3 && REQ_HEADING.test(x.text)));
91
+ const end = next ? next.line : Infinity;
92
+ const id = nodeId('requirement', m[1]);
93
+ out.nodes.push({ id, kind: 'requirement', label: m[2].trim(), from: `${rel}:${h.line}` });
94
+ const lines = body.filter(([, n]) => n > h.line && n < end);
95
+ for (const ref of citedRefs(lines)) out.edges.push({ kind: 'cites', from: id, to: citeTarget(ref), at: `${rel}:${ref.line}` });
96
+ });
97
+ return out;
98
+ }
99
+
100
+ function gaps(rel, text) {
101
+ const out = empty();
102
+ for (const r of readGaps(text).rows) {
103
+ const id = nodeId('gap', r.id);
104
+ const at = `${rel}:${r.line}`;
105
+ out.nodes.push({ id, kind: 'gap', label: r.what, from: at, class: r.cls, closedBy: r.closedBy });
106
+ const cells = [r.cls, r.where, r.what, r.closedBy].join(' ');
107
+ for (const d of uniq(all('decision', cells))) out.edges.push({ kind: 'cites', from: id, to: nodeId('decision', d), at });
108
+ for (const q of uniq(all('req', cells))) out.edges.push({ kind: 'cites', from: id, to: nodeId('requirement', q), at });
109
+ }
110
+ return out;
111
+ }
112
+
113
+ const KEY = /\*\*([A-Z][A-Za-z ]*):\*\*/g;
114
+ const PARTY = { Producer: 'produces', Producers: 'produces', Consumer: 'consumes', Consumers: 'consumes' };
115
+
116
+ // The text under each **Key:** of a contract's prose, as [{key, text, line}] in file order: a key's
117
+ // text runs to the next key or a blank line, over as many lines as it takes (S-17, S-20).
118
+ export function keyedText(text) {
119
+ const out = [];
120
+ let open = null;
121
+ for (const [line, n] of prose(text)) {
122
+ if (line.trim() === '') {
123
+ open = null;
124
+ continue;
125
+ }
126
+ let cursor = 0;
127
+ for (const m of line.matchAll(KEY)) {
128
+ if (open !== null) out.push({ key: open, text: line.slice(cursor, m.index), line: n });
129
+ open = m[1].trim();
130
+ cursor = m.index + m[0].length;
131
+ }
132
+ if (open !== null) out.push({ key: open, text: line.slice(cursor), line: n });
133
+ }
134
+ return out;
135
+ }
136
+
137
+ // 'produces' for a Producer or Producers key, 'consumes' for a Consumer or Consumers key, else null.
138
+ export const partyOf = (key) => PARTY[key] ?? null;
139
+
140
+ function contract(rel, text, contractId) {
141
+ const id = nodeId('contract', contractId);
142
+ const first = headings(text)[0];
143
+ const label = first ? first.text.replace(new RegExp(`^${contractId}\\b[\\s:—-]*`), '').trim() : contractId;
144
+ const out = { nodes: [{ id, kind: 'contract', label, from: `${rel}:${first?.line ?? 1}` }], edges: [] };
145
+ for (const seg of keyedText(text)) {
146
+ const kind = partyOf(seg.key);
147
+ if (!kind) continue;
148
+ for (const s of uniq(all('sliceAddr', seg.text))) out.edges.push({ kind, from: nodeId('slice', s), to: id, at: `${rel}:${seg.line}` });
149
+ }
150
+ return out;
151
+ }
152
+
153
+ function phase(rel, text, ph) {
154
+ const parsed = parsePhaseFile(text);
155
+ const h = headings(text).find((x) => x.level === 1);
156
+ return { nodes: [{ id: nodeId('phase', ph.id), kind: 'phase', label: parsed?.name ?? ph.name, from: `${rel}:${h?.line ?? 1}` }], edges: [] };
157
+ }
158
+
159
+ // The 1-based line of each front-matter key.
160
+ function keyLines(text) {
161
+ const out = {};
162
+ const ls = String(text).replace(/^/, '').replace(/\r\n/g, '\n').split('\n');
163
+ if (ls[0] !== '---') return out;
164
+ for (let i = 1; i < ls.length && ls[i] !== '---'; i++) {
165
+ const m = /^([^:\s][^:]*):/.exec(ls[i]);
166
+ if (m && !(m[1] in out)) out[m[1]] = i + 1;
167
+ }
168
+ return out;
169
+ }
170
+
171
+ function slice(rel, text) {
172
+ let s;
173
+ try {
174
+ s = parseSliceFile(text, rel);
175
+ } catch (e) {
176
+ if (e instanceof SliceFileError) return { nodes: [], edges: [], warnings: [`graph: ${e.message}`] };
177
+ throw e;
178
+ }
179
+ const lines = keyLines(text);
180
+ const at = (key) => `${rel}:${lines[key] ?? 1}`;
181
+ const id = nodeId('slice', s.id);
182
+ const phaseN = Number(s.id.split('/')[0].slice(1));
183
+ const out = { nodes: [{ id, kind: 'slice', label: s.name, from: at('slice'), name: s.name, group: s.group, repo: s.repo }], edges: [] };
184
+ out.edges.push({ kind: 'in', from: id, to: nodeId('phase', `P${phaseN}`), at: at('slice') });
185
+ for (const r of uniq(s.requirements)) out.edges.push({ kind: 'implements', from: id, to: nodeId('requirement', r), at: at('requirements') });
186
+ for (const d of uniq(s.decisions)) out.edges.push({ kind: 'cites', from: id, to: nodeId('decision', d), at: at('decisions') });
187
+ return out;
188
+ }
189
+
190
+ function release(rel, text, releaseId) {
191
+ const id = nodeId('release', releaseId);
192
+ const out = { nodes: [{ id, kind: 'release', label: releaseId, from: `${rel}:1` }], edges: [], prRefs: [] };
193
+ for (const [line, n] of prose(text)) {
194
+ for (const m of line.matchAll(/(?<![\w&/#])#(\d+)\b/g)) out.prRefs.push({ number: Number(m[1]), at: `${rel}:${n}`, release: id });
195
+ }
196
+ return out;
197
+ }
198
+
199
+ function runbook(rel, text) {
200
+ const out = empty();
201
+ const hs = headings(text).filter((h) => h.level === 2);
202
+ const body = [...prose(text)];
203
+ hs.forEach((h, i) => {
204
+ const id = nodeId('runbook-section', `${rel}#${slug(h.text)}`);
205
+ out.nodes.push({ id, kind: 'runbook-section', label: h.text, from: `${rel}:${h.line}` });
206
+ const end = hs[i + 1]?.line ?? Infinity;
207
+ for (const [line, n] of body) {
208
+ if (n <= h.line || n >= end) continue;
209
+ const at = `${rel}:${n}`;
210
+ for (const s of uniq(all('sliceAddr', line))) out.edges.push({ kind: 'cites', from: id, to: nodeId('slice', s), at });
211
+ for (const q of uniq(all('req', line))) out.edges.push({ kind: 'cites', from: id, to: nodeId('requirement', q), at });
212
+ for (const d of uniq(all('decision', line))) out.edges.push({ kind: 'cites', from: id, to: nodeId('decision', d), at });
213
+ }
214
+ });
215
+ return out;
216
+ }
217
+
218
+ // True for a markdown file docFragment reads (an intake file is named, not read).
219
+ export const readsDoc = (cfg, rel) => {
220
+ const c = classify(cfg, rel);
221
+ return c !== null && c.kind !== 'intake';
222
+ };
223
+
224
+ // One file under the docs root -> {nodes, edges[, prRefs][, warnings]}. `root` is the repository;
225
+ // the shapes read here need only the text.
226
+ export function docFragment(root, cfg, rel, text) {
227
+ const c = classify(cfg, rel);
228
+ if (!c) return empty();
229
+ switch (c.kind) {
230
+ case 'decisions': return decisions(rel, text);
231
+ case 'spec': return spec(rel, text);
232
+ case 'gaps': return gaps(rel, text);
233
+ case 'contract': return contract(rel, text, c.id);
234
+ case 'phase': return phase(rel, text, c.phase);
235
+ case 'slice': return slice(rel, text);
236
+ case 'release': return release(rel, text, c.id);
237
+ case 'runbook': return runbook(rel, text);
238
+ case 'intake': return intakeFragment(cfg, rel);
239
+ default: return empty();
240
+ }
241
+ }
@@ -0,0 +1,91 @@
1
+ // What the graph reads from git (REQ-4.2): the default branch and every slice/* branch, each
2
+ // commit's parents, committer date, subject, Slice trailers and touched paths. Never file contents.
3
+ import { execFileSync } from 'node:child_process';
4
+ import { GraphError, cmp } from './schema.js';
5
+
6
+ const MAX = 1024 * 1024 * 1024;
7
+
8
+ function run(root, args, input) {
9
+ return execFileSync('git', args, {
10
+ cwd: root,
11
+ encoding: 'utf8',
12
+ input,
13
+ stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'],
14
+ maxBuffer: MAX,
15
+ });
16
+ }
17
+
18
+ function tryRun(root, args) {
19
+ try {
20
+ return run(root, args).trim();
21
+ } catch {
22
+ return null;
23
+ }
24
+ }
25
+
26
+ const verify = (root, ref) => tryRun(root, ['rev-parse', '--verify', '--quiet', '--end-of-options', `${ref}^{commit}`]);
27
+
28
+ export function defaultRef(repoRoot, branch) {
29
+ for (const ref of [`refs/heads/${branch}`, `refs/remotes/origin/${branch}`]) {
30
+ const sha = verify(repoRoot, ref);
31
+ if (sha) return { ref, sha };
32
+ }
33
+ throw new GraphError(1, `the default branch ${branch} is not present here; fetch it`);
34
+ }
35
+
36
+ // The default branch first, then every local and origin slice/* branch, sorted by ref name.
37
+ export function refTips(repoRoot, branch) {
38
+ const tips = [defaultRef(repoRoot, branch)];
39
+ const out = run(repoRoot, ['for-each-ref', '--format=%(refname)%00%(objectname)%00%(objecttype)', 'refs/heads/slice/', 'refs/remotes/origin/slice/']);
40
+ const rest = out
41
+ .split('\n')
42
+ .filter((l) => l !== '')
43
+ .map((l) => l.split('\0'))
44
+ .filter(([, , type]) => type === 'commit')
45
+ .map(([ref, sha]) => ({ ref, sha }))
46
+ .sort((a, b) => cmp(a.ref, b.ref));
47
+ return [...tips, ...rest];
48
+ }
49
+
50
+ const FORMAT = '--format=%x1e%H%x1f%P%x1f%cI%x1f%s%x1f%(trailers:key=Slice,valueonly,unfold,separator=%x1d)%x1f';
51
+
52
+ // The commits reachable from `include` and not from `exclude`, one `git log`; a merge lists no files.
53
+ export function walkCommits(repoRoot, { include = [], exclude = [] } = {}) {
54
+ if (include.length === 0) return [];
55
+ const args = ['-c', 'core.quotePath=false', 'log', '--no-renames', '--name-only', '-z', FORMAT, ...include];
56
+ if (exclude.length > 0) args.push('--not', ...exclude);
57
+ args.push('--');
58
+ const out = run(repoRoot, args);
59
+ const commits = [];
60
+ for (const rec of out.split('\x1e')) {
61
+ if (rec === '') continue;
62
+ const cut = rec.lastIndexOf('\x1f');
63
+ const [sha, parents, date, subject, trailers] = rec.slice(0, cut).split('\x1f');
64
+ const files = rec.slice(cut + 1).split('\0').map((f) => f.replace(/^\n/, '')).filter((f) => f !== '');
65
+ const slices = [...new Set((trailers ?? '').split('\x1d').map((s) => s.trim()).filter((s) => /^P\d+\/S-\d{2}$/.test(s)))].sort(cmp);
66
+ commits.push({ sha, parents: parents === '' ? [] : parents.split(' '), date, subject, slices, files: parents.includes(' ') ? [] : [...new Set(files)].sort(cmp) });
67
+ }
68
+ return commits;
69
+ }
70
+
71
+ // Every commit reachable from shas.
72
+ export function reachable(repoRoot, shas) {
73
+ if (shas.length === 0) return new Set();
74
+ const out = run(repoRoot, ['rev-list', '--stdin'], `${shas.join('\n')}\n`);
75
+ return new Set(out.split('\n').filter((l) => l !== ''));
76
+ }
77
+
78
+ // The shas among `shas` that name a commit here (a recorded tip may have been collected since).
79
+ export function existing(repoRoot, shas) {
80
+ if (shas.length === 0) return [];
81
+ const out = run(repoRoot, ['cat-file', '--batch-check=%(objectname) %(objecttype)'], `${shas.join('\n')}\n`);
82
+ return out.split('\n').map((l) => l.split(' ')).filter(([, type]) => type === 'commit').map(([sha]) => sha);
83
+ }
84
+
85
+ // The https form of an origin on GitHub, or null.
86
+ export function webUrl(repoRoot) {
87
+ const url = tryRun(repoRoot, ['remote', 'get-url', 'origin']);
88
+ if (!url) return null;
89
+ const m = /^(?:git@github\.com:|ssh:\/\/git@github\.com\/|https:\/\/(?:[^@/]+@)?github\.com\/)([^/]+)\/([^/]+?)(?:\.git)?\/?$/.exec(url);
90
+ return m ? `https://github.com/${m[1]}/${m[2]}` : null;
91
+ }