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,45 @@
1
+ // Which files are tests (D-46, REQ-4.3) and the REQ IDs their lines name. The kit never knows the
2
+ // language (D-11): a test file is a path that matches a pattern, and only its lines are read.
3
+ import { execFileSync } from 'node:child_process';
4
+ import { cmp } from './schema.js';
5
+
6
+ // A name with test or spec after a dot, underscore or dash before its extension (a.test.js,
7
+ // a_test.go, a-spec.ts); a name starting test_ (test_a.py); a name ending Test or Tests before its
8
+ // extension (BillingTest.java, BillingTests.cs).
9
+ export const DEFAULT_TEST_FILES = Object.freeze([
10
+ '(^|/)[^/]*[._-](test|spec)\.[^/.]+$',
11
+ '(^|/)test_[^/]*$',
12
+ '(^|/)[^/]*Tests?\.[^/.]+$',
13
+ ]);
14
+
15
+ const compiled = new Map();
16
+ function patterns(cfg) {
17
+ const list = cfg?.testFiles ?? DEFAULT_TEST_FILES;
18
+ const key = JSON.stringify(list);
19
+ if (!compiled.has(key)) compiled.set(key, list.map((s) => new RegExp(s)));
20
+ return compiled.get(key);
21
+ }
22
+
23
+ export const isTestFile = (rel, cfg) => patterns(cfg).some((r) => r.test(rel));
24
+
25
+ const REQ = /REQ-\d+\.\d+/g;
26
+
27
+ // Every REQ ID on each line, 1-based lines counted on \n (a CRLF file numbers the same).
28
+ export function reqMentions(text) {
29
+ const out = [];
30
+ String(text).split('\n').forEach((line, i) => {
31
+ for (const m of line.matchAll(REQ)) out.push({ req: m[0], line: i + 1 });
32
+ });
33
+ return out;
34
+ }
35
+
36
+ // The tracked files that match testFiles, repository-relative POSIX paths, sorted.
37
+ export function testFiles(repoRoot, cfg) {
38
+ const out = execFileSync('git', ['-c', 'core.quotePath=false', 'ls-files', '-z'], {
39
+ cwd: repoRoot,
40
+ encoding: 'utf8',
41
+ stdio: ['ignore', 'pipe', 'pipe'],
42
+ maxBuffer: 256 * 1024 * 1024,
43
+ });
44
+ return out.split('\0').filter((p) => p !== '' && isTestFile(p, cfg)).sort(cmp);
45
+ }
@@ -0,0 +1,83 @@
1
+ // trace (REQ-4.5): the tree under a requirement (its slices with their pull requests, commits and
2
+ // files, then the tests that cover it) and the tree above a file (the slices whose commits touched
3
+ // it, with the requirements and decisions above each). Reads the index only; no git, no host.
4
+ import { nodeLine } from './render.js';
5
+ import { GraphError, cmp, keyOf, kindOf } from './schema.js';
6
+
7
+ const byId = (a, b) => cmp(a.id, b.id);
8
+ // Commit dates keep each committer's time-zone offset, so they are compared as instants, not text.
9
+ export const timeOf = (d) => (d ? Date.parse(d) : Number.NEGATIVE_INFINITY);
10
+ const byTime = (a, b) => (a === b ? 0 : a < b ? -1 : 1);
11
+ export const newestFirst = (a, b) => byTime(timeOf(b.date), timeOf(a.date)) || cmp(a.id, b.id);
12
+
13
+ // The distinct nodes of `kind` at the `side` end of `edges`, in id order.
14
+ function ends(index, edges, side, kind) {
15
+ const seen = new Map();
16
+ for (const e of edges) {
17
+ const id = e[side];
18
+ if (kindOf(id) !== kind || seen.has(id)) continue;
19
+ const n = index.node(id);
20
+ if (n) seen.set(id, n);
21
+ }
22
+ return [...seen.values()].sort(byId);
23
+ }
24
+
25
+ const leaf = (node, children = []) => ({ node, children });
26
+ const byNumber = (a, b) => (a.number ?? 0) - (b.number ?? 0) || byId(a, b);
27
+
28
+ function sliceUnderRequirement(index, slice) {
29
+ const ins = index.in(slice.id, 'in');
30
+ const prs = ends(index, ins, 'from', 'pull-request').sort(byNumber);
31
+ const commits = ends(index, ins, 'from', 'commit').sort(newestFirst);
32
+ return leaf(slice, [
33
+ ...prs.map((p) => leaf(p)),
34
+ ...commits.map((c) => leaf(c, ends(index, index.out(c.id, 'touched'), 'to', 'file').map((f) => leaf(f)))),
35
+ ]);
36
+ }
37
+
38
+ const lineOf = (at) => Number(/:(\d+)$/.exec(at ?? '')?.[1] ?? 0);
39
+
40
+ export function traceRequirement(index, id) {
41
+ const rid = index.find(id);
42
+ if (!rid || kindOf(rid) !== 'requirement') throw new GraphError(2, `${id} is not in the graph`);
43
+ const slices = ends(index, index.in(rid, 'implements'), 'from', 'slice').map((s) => sliceUnderRequirement(index, s));
44
+ const tests = index
45
+ .in(rid, 'covers')
46
+ .filter((e) => kindOf(e.from) === 'test' && index.node(e.from))
47
+ .sort((a, b) => cmp(a.from, b.from) || lineOf(a.at) - lineOf(b.at))
48
+ .map((e) => ({ node: index.node(e.from), at: e.at, text: `test ${e.at}`, children: [] }));
49
+ return { node: index.node(rid), children: [...slices, ...tests] };
50
+ }
51
+
52
+ const decisionsCited = (index, id) => ends(index, index.out(id, 'cites'), 'to', 'decision').map((d) => leaf(d));
53
+
54
+ export function traceFile(index, path) {
55
+ const fid = index.find(path);
56
+ if (!fid || kindOf(fid) !== 'file') throw new GraphError(2, `${path} is not in the graph`);
57
+ const sliceEdges = index.in(fid, 'touched').flatMap((e) => index.out(e.from, 'in'));
58
+ const slices = ends(index, sliceEdges, 'to', 'slice').map((s) => {
59
+ const reqs = ends(index, index.out(s.id, 'implements'), 'to', 'requirement').map((r) => leaf(r, decisionsCited(index, r.id)));
60
+ return leaf(s, [...reqs, ...decisionsCited(index, s.id)]);
61
+ });
62
+ return { node: index.node(fid), children: slices };
63
+ }
64
+
65
+ // Two spaces per level; a child with its own text (a test at its line) prints that text.
66
+ export function renderLines(tree, depth = 0) {
67
+ const out = [`${' '.repeat(depth)}${tree.text ?? nodeLine(tree.node)}`];
68
+ for (const c of tree.children ?? []) out.push(...renderLines(c, depth + 1));
69
+ return out;
70
+ }
71
+
72
+ // {id, kind, label, from, at?, children}
73
+ export function treeJson(tree) {
74
+ const n = tree.node;
75
+ return {
76
+ id: n.id,
77
+ kind: n.kind,
78
+ label: n.label ?? keyOf(n.id),
79
+ from: n.from,
80
+ ...(tree.at ? { at: tree.at } : {}),
81
+ children: (tree.children ?? []).map(treeJson),
82
+ };
83
+ }
@@ -0,0 +1,16 @@
1
+ // uncovered (REQ-4.5, REQ-4.3): requirements no test covers, test files naming no requirement, and
2
+ // commits on the default branch with no slice trailer (merge commits left out). Reads the index only.
3
+ import { cmp, kindOf } from './schema.js';
4
+ import { newestFirst } from './trace.js';
5
+
6
+ const byId = (a, b) => cmp(a.id, b.id);
7
+
8
+ export function uncovered(index) {
9
+ const requirements = index.byKind('requirement').filter((r) => index.in(r.id, 'covers').length === 0).sort(byId);
10
+ const tests = index.byKind('test').filter((t) => index.out(t.id, 'covers').length === 0).sort(byId);
11
+ const commits = index
12
+ .byKind('commit')
13
+ .filter((c) => c.default === true && c.merge === false && !index.out(c.id, 'in').some((e) => kindOf(e.to) === 'slice'))
14
+ .sort(newestFirst);
15
+ return { requirements, tests, commits };
16
+ }
@@ -0,0 +1,188 @@
1
+ // The workspace of a program repository (REQ-4.6, D-15, D-47): the file that lists the repositories
2
+ // a program spans, and which of them are on disk to be walked. The workspace file is the only list;
3
+ // config's repos is accepted and never read here.
4
+ import { execFileSync } from 'node:child_process';
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { getHost } from '../adapters/githost/index.js';
8
+ import { GitHostError } from '../adapters/githost/errors.js';
9
+ import { kitPaths } from '../paths.js';
10
+ import { defaultRef } from './git-walk.js';
11
+ import { GraphError } from './schema.js';
12
+
13
+ const posix = (p) => p.split(path.sep).join('/');
14
+ const NAME = /^[A-Za-z0-9._-]+$/;
15
+ const BRANCH = /^(?!-)(?!.*\.\.)(?!.*\/\/)[^\s~^:?*[\\\0]+(?<![/.])$/;
16
+ const isText = (v) => typeof v === 'string' && v.trim() !== '';
17
+ const fold = (p) => (process.platform === 'win32' || process.platform === 'darwin' ? p.toLowerCase() : p);
18
+
19
+ // The first segment of every tracked path of the program repository that holds a slash, lower-cased:
20
+ // a workspace name that is one of them would share its file nodes (S-20 review H-1). A top-level file,
21
+ // or a git submodule (one gitlink, the node file:<name>), shares none (P3/S-34, issue #62), the rule
22
+ // historyCollision keeps. Untracked paths make no file node, so a workspace repository cloned inside
23
+ // the program and not ignored is not one (H-7); a folder only in the program's history is caught
24
+ // after the walk, by historyCollision (H-5).
25
+ function topLevel(root) {
26
+ try {
27
+ const out = execFileSync('git', ['-c', 'core.quotePath=false', 'ls-files', '-z'], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 1024 * 1024 * 1024 });
28
+ return new Set(out.split('\0').filter((p) => p.includes('/')).map((p) => p.split('/')[0].toLowerCase()));
29
+ } catch {
30
+ return new Set();
31
+ }
32
+ }
33
+
34
+ export const workspaceRel = (root, cfg) => posix(path.relative(root, kitPaths(root, cfg).workspace));
35
+
36
+ // readWorkspace(root, cfg) -> {repos: [{name, path, url, defaultBranch}]}, or null when there is no
37
+ // workspace file. A file that cannot be read as one throws GraphError(1, `<rel>: <problem>`).
38
+ export function readWorkspace(root, cfg) {
39
+ const file = kitPaths(root, cfg).workspace;
40
+ const rel = workspaceRel(root, cfg);
41
+ const fail = (problem) => {
42
+ throw new GraphError(1, `${rel}: ${problem}`);
43
+ };
44
+ let text;
45
+ try {
46
+ text = fs.readFileSync(file, 'utf8');
47
+ } catch (e) {
48
+ if (e.code === 'ENOENT') return null;
49
+ fail(`cannot be read: ${e.code ?? e.message}`);
50
+ }
51
+ let data;
52
+ try {
53
+ data = JSON.parse(text.replace(/^/, ''));
54
+ } catch (e) {
55
+ fail(`not valid JSON: ${e.message}`);
56
+ }
57
+ if (!data || typeof data !== 'object' || !Array.isArray(data.repos)) fail('repos must be an array');
58
+ // Names are compared ignoring case: the cache files of Orders and orders would be one file on
59
+ // Windows and macOS.
60
+ const seen = new Set();
61
+ const top = topLevel(root);
62
+ const repos = data.repos.map((r, i) => {
63
+ const at = `repos[${i}]`;
64
+ if (!r || typeof r !== 'object' || Array.isArray(r)) fail(`${at} must be an object`);
65
+ if (typeof r.name !== 'string' || !NAME.test(r.name) || r.name === '.' || r.name === '..') {
66
+ fail(`${at}.name must be a name of letters, digits, . _ or -, and not .`);
67
+ }
68
+ if (seen.has(r.name.toLowerCase())) fail(`${at}.name ${r.name} is listed twice`);
69
+ seen.add(r.name.toLowerCase());
70
+ // Tracked paths only: a nested clone the program tracks nothing under is no collision (H-7, H-9).
71
+ if (top.has(r.name.toLowerCase())) fail(`${at}.name ${r.name} is also a top-level path of the program repository`);
72
+ if (!isText(r.path) && !isText(r.url)) fail(`${at} gives neither path nor url`);
73
+ if (typeof r.defaultBranch !== 'string' || !BRANCH.test(r.defaultBranch)) fail(`${at}.defaultBranch must be a branch name`);
74
+ return { name: r.name, path: isText(r.path) ? r.path : null, url: isText(r.url) ? r.url : null, defaultBranch: r.defaultBranch };
75
+ });
76
+ return { repos };
77
+ }
78
+
79
+ // The real path of a repository's common git directory: one for a repository and all its worktrees
80
+ // (S-20 review H-6).
81
+ function commonDir(dir) {
82
+ const out = execFileSync('git', ['rev-parse', '--git-common-dir'], { cwd: dir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
83
+ return fold(fs.realpathSync.native(path.resolve(dir, out)));
84
+ }
85
+
86
+ // True when dir is the top of a git work tree (not a folder inside one).
87
+ function isRepoTop(dir) {
88
+ try {
89
+ const prefix = execFileSync('git', ['rev-parse', '--show-prefix'], { cwd: dir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
90
+ return prefix.trim() === '';
91
+ } catch {
92
+ return false;
93
+ }
94
+ }
95
+
96
+ // A host whose every call fails: a workspace repository with no fixture of its own. The graph asks
97
+ // a host for getPullRequest only.
98
+ const failingHost = (message) => ({
99
+ kind: 'fixture',
100
+ getPullRequest() {
101
+ throw new GitHostError(message);
102
+ },
103
+ });
104
+
105
+ // The git host of one workspace repository: getHost for its own root, so gh reads that repository.
106
+ // With SLICEKIT_GITHOST_FIXTURE set it is the fixture <fixture>/<name>, when that directory exists.
107
+ function hostFor(cfg, env, name, repoRoot) {
108
+ const fixture = env.SLICEKIT_GITHOST_FIXTURE;
109
+ try {
110
+ if (fixture) {
111
+ const dir = path.join(fixture, name);
112
+ if (!fs.existsSync(dir)) return { host: failingHost(`no fixture for ${name}`), skipped: null };
113
+ return { host: getHost(cfg, { ...env, SLICEKIT_GITHOST_FIXTURE: dir }, repoRoot), skipped: null };
114
+ }
115
+ return { host: getHost(cfg, env, repoRoot), skipped: null };
116
+ } catch (e) {
117
+ if (!(e instanceof GitHostError)) throw e;
118
+ return { host: null, skipped: `pull requests of ${name} skipped: ${e.message}` };
119
+ }
120
+ }
121
+
122
+ // reachRepos(root, cfg, workspace, env) -> {reached: [{name, index, root, defaultBranch, host, skipped}],
123
+ // unreached: [{name, reason}]}, both in the workspace file's order. `path` resolves against the
124
+ // program root; an entry with only a url is never cloned.
125
+ //
126
+ // Two entries on one repository, or an entry on the program repository (a worktree of it included),
127
+ // throw GraphError(1, `<rel>: <problem>`): they would walk the same commits twice (S-20 review H-1, H-6).
128
+ export function reachRepos(root, cfg, workspace, env = process.env) {
129
+ const reached = [];
130
+ const unreached = [];
131
+ if (!workspace || workspace.repos.length === 0) return { reached, unreached };
132
+ const rel = workspaceRel(root, cfg);
133
+ let program;
134
+ try {
135
+ program = commonDir(root);
136
+ } catch {
137
+ throw new GraphError(2, 'graph: not a git repository');
138
+ }
139
+ const tops = new Map([[program, null]]);
140
+ for (const [i, r] of (workspace?.repos ?? []).entries()) {
141
+ if (r.path === null) {
142
+ unreached.push({ name: r.name, reason: `no path; ${r.url} is not on disk` });
143
+ continue;
144
+ }
145
+ const abs = path.resolve(root, r.path);
146
+ if (!fs.existsSync(abs)) {
147
+ unreached.push({ name: r.name, reason: `${r.path} does not exist` });
148
+ continue;
149
+ }
150
+ if (!fs.statSync(abs).isDirectory() || !isRepoTop(abs)) {
151
+ unreached.push({ name: r.name, reason: `${r.path} is not a git repository` });
152
+ continue;
153
+ }
154
+ const top = commonDir(abs);
155
+ if (tops.has(top)) {
156
+ const j = tops.get(top);
157
+ throw new GraphError(1, `${rel}: repos[${i}].path ${r.path} is ${j === null ? 'the program repository' : `the repository of repos[${j}]`}`);
158
+ }
159
+ tops.set(top, i);
160
+ try {
161
+ defaultRef(abs, r.defaultBranch);
162
+ } catch (e) {
163
+ if (!(e instanceof GraphError)) throw e;
164
+ unreached.push({ name: r.name, reason: `the default branch ${r.defaultBranch} is not present` });
165
+ continue;
166
+ }
167
+ reached.push({ name: r.name, index: i, root: abs, defaultBranch: r.defaultBranch, ...hostFor(cfg, env, r.name, abs) });
168
+ }
169
+ return { reached, unreached };
170
+ }
171
+
172
+ // After the walk: a reached workspace name that is the first segment of a program file or test node
173
+ // (one only in the program's history included) throws GraphError(1, `<rel>: <problem>`), since the two
174
+ // repositories' nodes would be merged (S-20 review H-5).
175
+ export function historyCollision(root, cfg, graph, reached) {
176
+ if (reached.length === 0) return;
177
+ const segments = new Set();
178
+ for (const e of graph.edges) {
179
+ if (e.kind !== 'in' || e.to !== 'repo:.') continue;
180
+ const m = /^(?:file|test):([^/]+)\//.exec(e.from);
181
+ if (m) segments.add(m[1].toLowerCase());
182
+ }
183
+ for (const r of reached) {
184
+ if (segments.has(r.name.toLowerCase())) {
185
+ throw new GraphError(1, `${workspaceRel(root, cfg)}: repos[${r.index}].name ${r.name} is also a top-level path of the program repository`);
186
+ }
187
+ }
188
+ }
package/src/hook-cli.js CHANGED
@@ -13,7 +13,7 @@ export function onPath(name, env) {
13
13
 
14
14
  // The install advice of D-30: the kit is on npm from 0.1.1 (D-41).
15
15
  export const NOT_INSTALLED =
16
- 'slicekit is not installed locally or on PATH; hooks will fail until it is (npm i -D slicekit, or set cli in .slicekit/config.json)';
16
+ 'slicekit is not installed locally or on PATH; hooks will fail until it is (npm install --save-dev slicekit, or set cli in .slicekit/config.json)';
17
17
 
18
18
  // The command the hooks call, D-30: a local install, else slicekit on PATH, else the PATH form with
19
19
  // NOT_INSTALLED. Never a registry fetch: a hook that installs would run whatever the registry serves
package/src/init.js CHANGED
@@ -19,6 +19,8 @@ const GITHOOKS_DIR = fileURLToPath(new URL('../templates/githooks/', import.meta
19
19
  const IGNORE_RULES = [
20
20
  { rule: '.slicekit/graph/', forms: new Set(['.slicekit/graph/', '/.slicekit/graph/', '.slicekit/graph', '/.slicekit/graph']) },
21
21
  { rule: '.slicekit/.subagent-*', forms: new Set(['.slicekit/.subagent-*', '/.slicekit/.subagent-*']) },
22
+ // The machine's own settings (D-43), such as a local test command: never part of the project.
23
+ { rule: '.slicekit/local.json', forms: new Set(['.slicekit/local.json', '/.slicekit/local.json']) },
22
24
  { rule: '!.slicekit/journal/', forms: new Set(['!.slicekit/journal/', '!/.slicekit/journal/']) },
23
25
  { rule: '!.slicekit/journal/*.log', forms: new Set(['!.slicekit/journal/*.log', '!/.slicekit/journal/*.log']) },
24
26
  { rule: '.slicekit/journal/*.lock', forms: new Set(['.slicekit/journal/*.lock', '/.slicekit/journal/*.lock']) },
@@ -5,6 +5,7 @@
5
5
  import fs from 'node:fs';
6
6
  import path from 'node:path';
7
7
  import { fileURLToPath } from 'node:url';
8
+ import { loadConfig } from './config.js';
8
9
  import { readDecisions } from './decisions.js';
9
10
  import { exists, readText } from './fs.js';
10
11
  import { GitError, currentBranch, isRepo } from './git.js';
@@ -165,11 +166,26 @@ export function checkRole(cfg, role) {
165
166
  if (role === 'designer' && cfg.shape !== 'fullstack') throw new InstructionsError(2, `designer is not installed for shape ${cfg.shape}`);
166
167
  }
167
168
 
168
- // The slice file of `sliceId` (null: none) and the role's template with `{{cli}}` filled in, after
169
- // the role and the slice are checked.
170
- function briefHead(root, cfg, role, sliceId, templatesDir, fromBranch) {
169
+ // Where a brief reads the slice file, the requirements and the decisions, as { dir, cfg }: the
170
+ // worktree it is given, through that worktree's own config, when the worktree holds the slice's file,
171
+ // so a reviewer is briefed on the text under review (issue #56); else the session root.
172
+ function briefSource(root, cfg, sliceId, worktree) {
173
+ if (!sliceId || typeof worktree !== 'string' || worktree === '') return { dir: root, cfg };
174
+ const dir = path.resolve(root, worktree);
175
+ try {
176
+ const own = loadConfig(dir);
177
+ if (sliceFile(dir, own, sliceId)) return { dir, cfg: own };
178
+ } catch {
179
+ // No config there, or no slice files it can read: the session root's text, as before.
180
+ }
181
+ return { dir: root, cfg };
182
+ }
183
+
184
+ // The slice file of `sliceId` (null: none), read from `src` (default: the session root), and the
185
+ // role's template with `{{cli}}` filled in, after the role and the slice are checked.
186
+ function briefHead(root, cfg, role, sliceId, templatesDir, fromBranch, src = { dir: root, cfg }) {
171
187
  checkRole(cfg, role);
172
- const slice = sliceId ? sliceFile(root, cfg, sliceId) : null;
188
+ const slice = sliceId ? sliceFile(src.dir, src.cfg, sliceId) : null;
173
189
  if (sliceId && !slice && !fromBranch) throw new InstructionsError(2, `unknown slice ${sliceId}`);
174
190
  const file = path.join(templatesDir, 'agents', `${role}.md`);
175
191
  const head = fill(template(file, `the ${role} brief is not built in this version: ${posix(file)} is missing`), { cli: cfg.cli });
@@ -178,14 +194,16 @@ function briefHead(root, cfg, role, sliceId, templatesDir, fromBranch) {
178
194
 
179
195
  // The whole brief of `role` for `sliceId` (null: no active slice). The essentials come first and the
180
196
  // slice's Tasks section last, so a reader that cuts the text from its end loses the least. With
181
- // `worktree` it names where the agent works, so the brief is the agent's whole prompt (REQ-2.6 step 2).
197
+ // `worktree` it names where the agent works, so the brief is the agent's whole prompt (REQ-2.6 step 2),
198
+ // and reads the slice from there when the worktree holds its file (briefSource).
182
199
  // `fromBranch`: the id came from the branch, so a missing slice file is no active slice, not an error.
183
200
  export function renderBrief(root, cfg, role, sliceId, { templatesDir = TEMPLATES, worktree, fromBranch = false } = {}) {
184
- const { slice, head } = briefHead(root, cfg, role, sliceId, templatesDir, fromBranch);
201
+ const src = briefSource(root, cfg, sliceId, worktree);
202
+ const { slice, head } = briefHead(root, cfg, role, sliceId, templatesDir, fromBranch, src);
185
203
  const none = sliceId && !slice ? `No active slice. (branch names ${sliceId}, which has no slice file)` : 'No active slice.';
186
204
  const parts = [head.trim(), `## Writing rules\n\n${writingRules(root)}`.trim()];
187
- parts.push(`## Requirements\n\n${slice ? requirements(root, cfg, asList(slice.data.requirements)) : none}`);
188
- parts.push(`## Decisions\n\n${slice ? decisions(root, cfg, asList(slice.data.decisions)) : none}`);
205
+ parts.push(`## Requirements\n\n${slice ? requirements(src.dir, src.cfg, asList(slice.data.requirements)) : none}`);
206
+ parts.push(`## Decisions\n\n${slice ? decisions(src.dir, src.cfg, asList(slice.data.decisions)) : none}`);
189
207
  parts.push(slice ? `## Slice ${sliceId}\n\n${sliceSummary(slice)}` : `## Slice\n\n${none}`);
190
208
  parts.push(`## Team commands\n\n${TEAM_COMMANDS.map((k) => `- ${k}: ${cfg.commands?.[k] || 'not declared'}`).join('\n')}`);
191
209
  // The reviewer's verdict goes in the session root, where `build verdict` and the stop hook read it.
@@ -133,13 +133,20 @@ export function setState(root, cfg, id, to, evidence = {}) {
133
133
  // Backfill adopts a slice built outside the loop: an open pull request or a merge. A review,
134
134
  // CI or ready state is recorded only by the build commands, whose checks backfill would skip.
135
135
  if (!BACKFILL_TO.includes(to)) throw new TransitionError('backfill records only draft-pr or merged; later states come from the build commands');
136
- if (current.state !== 'todo') throw new TransitionError('backfill is only allowed from todo');
136
+ // A merge is a fact the git host reports (D-43): recorded from any state before merged, and only
137
+ // on the host's report (the state CLI asks the host and supplies it). An open pull request is
138
+ // adopted only into a slice the loop has not started.
139
+ if (to === 'draft-pr' && current.state !== 'todo') throw new TransitionError('backfill to draft-pr is only allowed from todo');
137
140
  const missing = rule.required.filter((k) => ev[k] === undefined);
138
141
  if (missing.length > 0) throw new TransitionError(`backfill to ${to} needs ${missing.join(', ')}`);
139
142
  const pr = ev.pr;
140
143
  if (!pr || !Number.isInteger(pr.number) || typeof pr.headSha !== 'string' || pr.headSha === '') {
141
144
  throw new TransitionError(`backfill to ${to} needs pr.number and pr.headSha`);
142
145
  }
146
+ if (to === 'merged') {
147
+ if (['merged', 'released'].includes(current.state)) throw new TransitionError(`${id} is already ${current.state}`);
148
+ if (ev.source !== 'host') throw new TransitionError('backfill to merged needs the git host to report the pull request merged');
149
+ }
143
150
  } else {
144
151
  if (!allowedMove(current.state, to, ev)) {
145
152
  throw new TransitionError(`${current.state} cannot move to ${to}`);
@@ -160,18 +167,42 @@ export function setState(root, cfg, id, to, evidence = {}) {
160
167
  });
161
168
  }
162
169
 
170
+ // A slice at draft-pr whose head moved since build pr recorded it (a merge of the default branch,
171
+ // any commit): the new head is recorded as a draft-pr entry, not a move, so the next verdict is taken
172
+ // on it (D-43). `pr` is { number, url, headSha }; only build pr calls this.
173
+ export function recordHead(root, cfg, id, pr) {
174
+ return withLock(root, cfg, id, () => {
175
+ const current = readSlice(root, cfg, id);
176
+ if (current.state !== 'draft-pr') throw new TransitionError(`${id} is ${current.state}; a moved head is recorded only at draft-pr`);
177
+ const typeError = validateEvidence({ pr });
178
+ if (typeError) throw new TransitionError(typeError);
179
+ const ev = resolveShas(root, { pr });
180
+ const next = {
181
+ ...current,
182
+ pr: { ...(current.pr ?? {}), ...ev.pr },
183
+ history: [...current.history, entry('draft-pr', 'draft-pr', 'cli', { head: ev.pr.headSha })],
184
+ };
185
+ writeSlice(root, cfg, next);
186
+ return next;
187
+ });
188
+ }
189
+
163
190
  // Only a test frozen at tests-red can be unfrozen; any other path has nothing to release. `extra`
164
- // joins the history entry's evidence (build amend gives the amendment commit and the reason).
165
- export function unfreeze(root, cfg, id, file, extra = {}) {
191
+ // joins the history entry's evidence (build amend gives the amendment commit and the reason). `to`
192
+ // moves the slice in the same write: build amend during review takes it back to building (D-43).
193
+ export function unfreeze(root, cfg, id, file, extra = {}, { to } = {}) {
166
194
  return withLock(root, cfg, id, () => {
167
195
  const current = readSlice(root, cfg, id);
168
196
  if (!current.frozenTests.includes(file)) {
169
197
  throw new TransitionError(`${file} is not a frozen test of ${id}`);
170
198
  }
199
+ const state = to ?? current.state;
171
200
  const next = {
172
201
  ...current,
202
+ state,
203
+ ...(state === current.state ? {} : { handoff: null }),
173
204
  unfrozen: [...current.unfrozen, file],
174
- history: [...current.history, entry(current.state, current.state, 'cli', { unfreeze: file, ...extra })],
205
+ history: [...current.history, entry(current.state, state, 'cli', { unfreeze: file, ...extra })],
175
206
  };
176
207
  writeSlice(root, cfg, next);
177
208
  return next;
package/src/verdict.js CHANGED
@@ -1,10 +1,14 @@
1
1
  // The reviewer's verdict file (REQ-2.11): parsed into a record, and checked for the shape problems
2
- // that make a hook refuse the reviewer. The head SHA is not read from the file: the state layer
3
- // stamps a verdict with the pull request head it holds when the verdict is recorded (REQ-1.8).
2
+ // that make a hook refuse the reviewer. The file names the head it reviewed on a `Head: <sha>` line
3
+ // (D-43); `build verdict` takes it only for the recorded head, and the state layer still stamps the
4
+ // verdict with the pull request head it holds when the verdict is recorded (REQ-1.8).
4
5
  import { lines, prose, headings } from './markdown.js';
5
6
 
6
7
  const VERDICT = /^Verdict: (BLOCK|CHANGES|APPROVE)\s*$/;
7
8
  const ANY_VERDICT = /^\s*Verdict:/;
9
+ const HEAD = /^\s*Head:\s*(.*?)\s*$/;
10
+ // The full commit id: a shorter one can be shadowed by a ref of that name.
11
+ const SHA = /^[0-9a-f]{40}$/;
8
12
  // The state layer's `--independent` flag decides independence (REQ-2.8), not this field alone.
9
13
  const INDEPENDENT = /^\s*Independent:\s*yes\s*$/i;
10
14
  const KINDS = { B: 'blocker', H: 'should-have' };
@@ -136,6 +140,8 @@ const unreadable = (path) => ({
136
140
  notChecked: [],
137
141
  hasNotChecked: false,
138
142
  independent: false,
143
+ head: null,
144
+ headLines: 0,
139
145
  unreadable: true,
140
146
  });
141
147
 
@@ -166,6 +172,9 @@ export function parseVerdict(input, path) {
166
172
  notChecked: notChecked ?? [],
167
173
  hasNotChecked: notChecked !== null,
168
174
  independent: proseLines.some((l) => INDEPENDENT.test(l)),
175
+ // The reviewed head as written on its `Head:` line (null when there is none), and how many such lines.
176
+ head: proseLines.map((l) => HEAD.exec(l)?.[1]).find((h) => h !== undefined) ?? null,
177
+ headLines: proseLines.filter((l) => HEAD.test(l)).length,
169
178
  };
170
179
  }
171
180
 
@@ -177,6 +186,9 @@ export function verdictProblems(v) {
177
186
  const out = [];
178
187
  if (!v.verdict) out.push('no verdict line');
179
188
  if (v.verdictLines > 1) out.push('more than one verdict line');
189
+ if (v.head === null) out.push('no "Head:" line naming the head reviewed');
190
+ else if (!SHA.test(v.head)) out.push(`Head "${v.head}" is not a full commit id (40 lowercase hex)`);
191
+ if (v.headLines > 1) out.push('more than one "Head:" line');
180
192
  for (const c of v.columns) out.push(`findings table has no "${c}" column`);
181
193
  const seen = new Set();
182
194
  v.findings.forEach((f, i) => {