slicekit 0.1.2 → 0.2.1

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 (66) 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 +39 -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 +90 -3
  38. package/src/git.js +35 -0
  39. package/src/graph/build.js +312 -0
  40. package/src/graph/docs.js +241 -0
  41. package/src/graph/git-walk.js +91 -0
  42. package/src/graph/history.js +60 -0
  43. package/src/graph/impact.js +143 -0
  44. package/src/graph/kitfiles.js +60 -0
  45. package/src/graph/load.js +93 -0
  46. package/src/graph/prs.js +136 -0
  47. package/src/graph/render.js +28 -0
  48. package/src/graph/schema.js +108 -0
  49. package/src/graph/shipped.js +32 -0
  50. package/src/graph/tests.js +45 -0
  51. package/src/graph/trace.js +83 -0
  52. package/src/graph/uncovered.js +16 -0
  53. package/src/graph/workspace.js +188 -0
  54. package/src/hook-cli.js +1 -1
  55. package/src/init.js +5 -2
  56. package/src/instructions.js +26 -8
  57. package/src/state/index.js +35 -4
  58. package/src/verdict.js +14 -2
  59. package/src/visualize/client.js +489 -0
  60. package/src/visualize/page.js +100 -0
  61. package/src/visualize/server.js +46 -0
  62. package/src/workflow.js +87 -9
  63. package/templates/instructions/agents/reviewer.md +7 -7
  64. package/templates/instructions/commands/build.md +34 -4
  65. package/templates/workflow/pins.json +2 -1
  66. package/templates/workflow/slicekit.yml +32 -1
package/README.md CHANGED
@@ -7,17 +7,18 @@ agent finishes a turn and again in CI, not because anyone remembers to update it
7
7
 
8
8
  ## Status: preview
9
9
 
10
- Phases 1 and 2 work: intake, specify, the gap scan, plan, the build from red tests to green, the
11
- review loop, the independent review and `/slicekit build --parallel`. Phase 3 will add the
12
- traceability graph, its queries and views, and workspaces that span several repositories. Phase 4
13
- will add release, ops and audit, and the other examples (`fullstack` and `data`). Phases 3 and 4
14
- are not built yet.
10
+ Phases 1 to 3 work. Phases 1 and 2 are intake, specify, the gap scan, plan, the build from red
11
+ tests to green, the review loop, the independent review and `/slicekit build --parallel`. Phase 3
12
+ is the traceability graph (`graph`), its queries (`trace`, `impact`, `history`, `uncovered` and
13
+ `shipped`), its views (`visualize`), and workspaces that span several repositories. Phase 4
14
+ (release, ops, audit and the other examples) is not built yet. [CHANGELOG.md](https://github.com/adityapandya1/agentic-slicekit/blob/main/CHANGELOG.md) lists what each
15
+ version changed.
15
16
 
16
17
  The kit is on npm as a preview from 0.1.1. It needs Node 22 or later and git, and it has no
17
18
  dependencies of its own. In your project:
18
19
 
19
20
  ```sh
20
- npm i -D slicekit
21
+ npm install --save-dev slicekit
21
22
  npx slicekit init --shape backend --name <your-project>
22
23
  ```
23
24
 
@@ -147,10 +148,11 @@ VERDICT="$(sed -n 's/^verdict //p' "$WORK/pr.txt")"
147
148
  ```
148
149
 
149
150
  In `/slicekit build` the reviewer agent writes the verdict now. The copy here is an `APPROVE` with
150
- no findings. `build verdict` checks it, commits it to the branch and prints the next step, `ci`.
151
+ no findings. Its `Head:` line names the commit it reviewed, here the worktree's head. `build verdict`
152
+ checks it, commits it to the branch and prints the next step, `ci`.
151
153
 
152
154
  ```sh
153
- cp "$KIT/examples/walkthrough/P1-S-01-r1.md" "$VERDICT"
155
+ sed "s/^Head: .*/Head: $(git -C "$WT" log -1 --format=%H)/" "$KIT/examples/walkthrough/P1-S-01-r1.md" > "$VERDICT"
154
156
  node "$KIT/bin/slicekit.js" build verdict P1/S-01 "$VERDICT" --worktree "$WT"
155
157
  ```
156
158
 
@@ -184,7 +186,7 @@ commits it in the review worktree and pushes it. CI reports on that new head. It
184
186
  review rounds inside `/slicekit build`, and the independent review uses neither of them.
185
187
 
186
188
  ```sh
187
- cp "$KIT/examples/walkthrough/P1-S-01i-r2.md" "$VERDICT"
189
+ sed "s/^Head: .*/Head: $(git -C .worktrees/review-P1-S-01 log -1 --format=%H)/" "$KIT/examples/walkthrough/P1-S-01i-r2.md" > "$VERDICT"
188
190
  node "$KIT/bin/slicekit.js" build verdict P1/S-01 "$VERDICT" --independent --worktree .worktrees/review-P1-S-01
189
191
  node "$KIT/examples/walkthrough/host.js" ci 1 success
190
192
  ```
@@ -226,9 +228,9 @@ rm -rf "$WORK"
226
228
 
227
229
  ## Scope
228
230
 
229
- The kit does not parse source code. Its graph, coming in Phase 3, will be built from its own IDs and
230
- from git: requirements, decisions, slices, tests, commits, pull requests and releases. It will infer
231
- no calls or imports. For a code graph,
231
+ The kit does not parse source code. Its graph is built from its own IDs and from git by
232
+ `slicekit graph`: requirements, decisions, slices, tests, commits, pull requests and releases. It is
233
+ not a code graph: it infers no calls or imports. For a code graph,
232
234
  [graphify](https://github.com/Graphify-Labs/graphify) or a similar tool sits alongside. This line
233
235
  installs graphify and its Claude Code skill:
234
236
 
@@ -245,7 +247,7 @@ repository has a local install, and `slicekit` otherwise, which needs slicekit o
245
247
  is found, init still writes `slicekit` and warns that the hooks will fail until it is installed; it
246
248
  never fetches slicekit from the registry. `cli` in `.slicekit/config.json` (or `init --cli <command>`)
247
249
  overrides that choice, and init and update warn when the command does not answer `--version`. The
248
- usual setup is a local install, `npm i -D slicekit`, before init. To run the kit from a clone
250
+ usual setup is a local install, `npm install --save-dev slicekit`, before init. To run the kit from a clone
249
251
  instead, pass `--cli` to init, as the walkthrough does:
250
252
  `--cli "node \"<path-to-kit>/bin/slicekit.js\""`. The
251
253
  hooks run from the session's working directory, so a worktree outside the repository tree needs an
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "slicekit",
3
- "version": "0.1.2",
3
+ "version": "0.2.1",
4
4
  "description": "Spec-driven agentic workflow kit",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -20,6 +20,7 @@
20
20
  "node": ">=22"
21
21
  },
22
22
  "scripts": {
23
- "test": "node --test \"test/**/*.test.js\""
23
+ "test": "node --test \"test/**/*.test.js\"",
24
+ "test:shard": "node scripts/test-shard.js"
24
25
  }
25
26
  }
@@ -3,12 +3,25 @@ import path from 'node:path';
3
3
  import { GitHostError, GitHostNotFound } from './errors.js';
4
4
  import { assertDate, assertSha } from '../../evidence.js';
5
5
  import { redact } from '../../redact.js';
6
- import { assertBranch, assertLabel, assertLabelColor, assertPrNumber, assertTitle, filterMergedSince, mapPullRequest, pickBranchPullRequest, reduceRuns } from './gh-json.js';
6
+ import {
7
+ assertBranch,
8
+ assertLabel,
9
+ assertLabelColor,
10
+ assertPrNumber,
11
+ assertTitle,
12
+ decidedSlicekitRun,
13
+ filterMergedSince,
14
+ mapJobs,
15
+ mapPullRequest,
16
+ pickBranchPullRequest,
17
+ reduceRuns,
18
+ } from './gh-json.js';
7
19
 
8
20
  // The test seam for C-1 (05 REQ-5.2): a directory of gh-shaped JSON files.
9
21
  // pr-<n>.json what `gh pr view <n> --json ...` prints
10
22
  // merged-since.json what `gh pr list --state merged --json ...` prints (an array)
11
23
  // ci-<sha>.json what `gh run list --commit <sha> --json ...` prints (an array)
24
+ // jobs-<id>.json what `gh run view <id> --json jobs` prints, for slicekitRun
12
25
  // label-error.txt, label-create-error.txt gh refusing `pr edit`, `label create`
13
26
  // label-calls.jsonl written: one line per label call, in order
14
27
  // pr-create-error.txt gh refusing `pr create`
@@ -79,6 +92,16 @@ export function fixtureHost(dir) {
79
92
  assertSha(sha);
80
93
  return reduceRuns(readJson(path.join(dir, `ci-${sha}.json`)) ?? []);
81
94
  },
95
+ // As the GitHub host (decidedSlicekitRun): ci-<sha>.json narrowed to the slicekit workflow's
96
+ // pull_request runs, each completed one's jobs read from jobs-<databaseId>.json (none when the file
97
+ // is missing), newest first until one is decided.
98
+ slicekitRun(sha) {
99
+ assertSha(sha);
100
+ return decidedSlicekitRun(readJson(path.join(dir, `ci-${sha}.json`)) ?? [], (run) => {
101
+ if (!Number.isInteger(run.databaseId)) throw new GitHostError('git host fixture: a slicekit run with no databaseId');
102
+ return mapJobs(readJson(path.join(dir, `jobs-${run.databaseId}.json`)));
103
+ });
104
+ },
82
105
  setLabel(n, name, present) {
83
106
  assertPrNumber(n);
84
107
  assertLabel(name);
@@ -89,11 +89,78 @@ export function filterMergedSince(list, since) {
89
89
 
90
90
  // gh lists runs newest first. Any run still going → pending; any completed run that did not
91
91
  // succeed (skipped and neutral count as success) → failure; all succeeded → success; none → unknown.
92
- export function reduceRuns(runs) {
93
- if (!Array.isArray(runs) || runs.length === 0) return { status: 'unknown', url: null };
92
+ // The newest run of each workflow and event (REQ-2.6 step 9, issue #33): a run that a newer run of the
93
+ // same workflow and event replaced, often cancelled by the workflow's concurrency, is not the
94
+ // commit's answer. A workflow is known by its workflowDatabaseId when every run carries one, so two
95
+ // workflow files that declare one name are judged apart (issue #41), else by its name. Runs with
96
+ // neither, or with no event, are judged together, as before.
97
+ const hasId = (r) => r.workflowDatabaseId !== undefined && r.workflowDatabaseId !== null && r.workflowDatabaseId !== '';
98
+
99
+ // When a run last started: a re-run moves startedAt and leaves createdAt alone, so an older run
100
+ // re-run after a newer one is the newer answer (issue #42). createdAt for a run with no startedAt.
101
+ const startOf = (r) => String(r.startedAt || r.createdAt || '');
102
+
103
+ function newestPerWorkflow(runs) {
104
+ const byId = runs.every(hasId);
105
+ if (!byId && !runs.every((r) => r.workflowName && r.event)) return runs;
106
+ const newest = new Map();
107
+ for (const r of runs) {
108
+ const key = JSON.stringify(byId ? ['id', r.workflowDatabaseId, r.event ?? null] : ['name', r.workflowName, r.event]);
109
+ const held = newest.get(key);
110
+ if (!held || startOf(r) > startOf(held)) newest.set(key, r);
111
+ }
112
+ return [...newest.values()];
113
+ }
114
+
115
+ export function reduceRuns(all) {
116
+ if (!Array.isArray(all) || all.length === 0) return { status: 'unknown', url: null };
117
+ const runs = newestPerWorkflow(all);
94
118
  const going = runs.find((r) => r.status !== 'completed');
95
119
  if (going) return { status: 'pending', url: going.url ?? null };
96
120
  const failed = runs.find((r) => !OK_CONCLUSIONS.has(r.conclusion));
97
121
  if (failed) return { status: 'failure', url: failed.url ?? null };
98
122
  return { status: 'success', url: runs[0].url ?? null };
99
123
  }
124
+
125
+ // D-49: the generated workflow, as `gh run list --workflow` names its file and as its runs name it.
126
+ export const SLICEKIT_WORKFLOW = Object.freeze({ file: 'slicekit.yml', name: 'slicekit' });
127
+ export const SLICEKIT_RUN_FIELDS = 'databaseId,status,conclusion,createdAt,startedAt,workflowName,workflowDatabaseId,event,url';
128
+
129
+ // The slicekit run of a commit, shared by the GitHub host and the fixture host (issue #52): of gh's
130
+ // runs, the pull_request runs of the slicekit workflow newest first by start, the first whose team
131
+ // command jobs were decided, `passed` or `failed` by commandJobsVerdict, as { run, jobs }; null when
132
+ // none was. A run still in progress (on an `edited` event, the current one) is passed over without
133
+ // asking for its jobs, and so is one whose command jobs were all skipped or cancelled. `jobsOf(run)`
134
+ // is the host's `gh run view <id> --json jobs`, mapped; it refuses a run with no databaseId. Runs of
135
+ // any other workflow or event are never the answer, whatever gh was asked for.
136
+ export function decidedSlicekitRun(runs, jobsOf) {
137
+ const mine = (Array.isArray(runs) ? runs : []).filter((r) => r && r.workflowName === SLICEKIT_WORKFLOW.name && r.event === 'pull_request');
138
+ const newestFirst = mine.map((r, i) => ({ r, i })).sort((a, b) => (startOf(b.r) > startOf(a.r) ? 1 : startOf(b.r) < startOf(a.r) ? -1 : a.i - b.i));
139
+ for (const { r: run } of newestFirst) {
140
+ if (run.status !== 'completed') continue;
141
+ const jobs = jobsOf(run);
142
+ const verdict = commandJobsVerdict(run, jobs);
143
+ if (verdict === 'passed' || verdict === 'failed') return { run, jobs };
144
+ }
145
+ return null;
146
+ }
147
+
148
+ // The jobs of `gh run view <id> --json jobs`, as { name, status, conclusion }.
149
+ export function mapJobs(view) {
150
+ const jobs = view?.jobs;
151
+ if (!Array.isArray(jobs)) return [];
152
+ return jobs.map((j) => ({ name: String(j?.name ?? ''), status: j?.status ?? null, conclusion: j?.conclusion ?? null }));
153
+ }
154
+
155
+ // What a slicekit run says about the team command jobs (`cmd-*`) on its commit: `passed` when it
156
+ // completed and at least one ran and every one concluded success (a skipped one, as on a bookkeeping
157
+ // push, is not a pass); `failed` when one concluded anything other than success, skipped or
158
+ // cancelled; `pending` while it runs; `other` otherwise (skipped, cancelled, no command jobs).
159
+ export function commandJobsVerdict(run, jobs) {
160
+ if (!run) return 'other';
161
+ if (run.status !== 'completed') return 'pending';
162
+ const commands = (jobs ?? []).filter((j) => j.name.startsWith('cmd-'));
163
+ if (commands.some((j) => !['success', 'skipped', 'cancelled'].includes(j.conclusion))) return 'failed';
164
+ if (commands.length > 0 && commands.every((j) => j.status === 'completed' && j.conclusion === 'success')) return 'passed';
165
+ return 'other';
166
+ }
@@ -14,6 +14,10 @@ import {
14
14
  parsePullRequestUrl,
15
15
  pickBranchPullRequest,
16
16
  reduceRuns,
17
+ mapJobs,
18
+ decidedSlicekitRun,
19
+ SLICEKIT_RUN_FIELDS,
20
+ SLICEKIT_WORKFLOW,
17
21
  } from './gh-json.js';
18
22
 
19
23
  // C-1 for GitHub through the `gh` CLI. This file owns only the spawn; the JSON mapping is gh-json.js.
@@ -22,7 +26,7 @@ export const GH_NOT_FOUND = 'gh not found; install GitHub CLI or set SLICEKIT_GI
22
26
 
23
27
  const PR_FIELDS = 'number,url,state,mergedAt,headRefOid,headRefName,isDraft,title,body,labels';
24
28
  const LIST_FIELDS = 'number,mergedAt,headRefOid,title';
25
- const RUN_FIELDS = 'status,conclusion,url,createdAt';
29
+ const RUN_FIELDS = 'status,conclusion,url,createdAt,startedAt,workflowName,workflowDatabaseId,event';
26
30
 
27
31
  // A non-zero gh exit, typed: "no such pull request" is a GitHostNotFound, anything else a GitHostError
28
32
  // whose message carries the first line of gh's stderr, with any token shape masked.
@@ -76,6 +80,17 @@ export function githubHost(env = process.env, root = process.cwd(), exec = execF
76
80
  assertSha(sha);
77
81
  return reduceRuns(ghJson(['run', 'list', '--commit', sha, '--limit', '20', '--json', RUN_FIELDS]));
78
82
  },
83
+ // D-49: the newest pull_request run of the slicekit workflow on a commit whose team command jobs
84
+ // were decided, and its jobs, or null (decidedSlicekitRun). One `gh run list`, then one `gh run
85
+ // view` per completed run, newest first, until one is decided.
86
+ slicekitRun(sha) {
87
+ assertSha(sha);
88
+ const args = ['run', 'list', '--commit', sha, '--workflow', SLICEKIT_WORKFLOW.file, '--event', 'pull_request', '--limit', '20', '--json', SLICEKIT_RUN_FIELDS];
89
+ return decidedSlicekitRun(ghJson(args), (run) => {
90
+ if (!Number.isInteger(run.databaseId)) throw new GitHostError('gh run list printed a run with no databaseId');
91
+ return mapJobs(ghJson(['run', 'view', String(run.databaseId), '--json', 'jobs']));
92
+ });
93
+ },
79
94
  // Adds the label when present is true, removes it otherwise. A label the repository does not
80
95
  // have is gh's error, reported as a GitHostError.
81
96
  setLabel(n, name, present) {
@@ -3,12 +3,15 @@
3
3
  // human has amended the slice file, and then only that one test.
4
4
  import fs from 'node:fs';
5
5
  import path from 'node:path';
6
- import { GitError, commitPaths, git, parseTrailers } from '../git.js';
6
+ import { buildTestCommand } from '../config.js';
7
+ import { GitError, assertRef, commitPaths, git, hasRemote, parseTrailers } from '../git.js';
8
+ import { configSubject, namesConfigAt } from './config.js';
9
+ import { freshAt, renderPathsOnly, renderSubject } from './render.js';
7
10
  import { stateFileName, verdictFilePattern } from '../ids.js';
8
11
  import { kitPaths } from '../paths.js';
9
12
  import { TransitionError, readSlice, unfreeze } from '../state/index.js';
10
13
  import { isKitFile, posixRel, runCommand, sliceIn, toWorktreePath, unusableRun } from './red.js';
11
- import { commitBookkeeping } from './record.js';
14
+ import { commitState } from './record.js';
12
15
  import { BuildError, findWorktree } from './worktree.js';
13
16
 
14
17
  const short = (sha) => sha.slice(0, 7);
@@ -87,30 +90,119 @@ function kitCommit(id, subject, trailers, changes, stateRel, buildRel, sliceRel)
87
90
  return false;
88
91
  }
89
92
 
93
+ // The default branch's tip the guard reads (D-53): origin's when there is an origin, else the
94
+ // local branch; null when neither resolves.
95
+ function defaultBranchTip(wt, cfg) {
96
+ let name;
97
+ try {
98
+ name = assertRef(cfg.defaultBranch);
99
+ } catch {
100
+ return null;
101
+ }
102
+ const ref = hasRemote(wt, 'origin') ? `refs/remotes/origin/${name}` : `refs/heads/${name}`;
103
+ try {
104
+ return git(wt, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]);
105
+ } catch (e) {
106
+ if (e instanceof GitError) return null;
107
+ throw e;
108
+ }
109
+ }
110
+
111
+ // The files merge `sha` changed against its first parent, the branch it was made on.
112
+ const mergeFiles = (wt, sha, first) =>
113
+ git(wt, ['diff-tree', '-r', '--name-only', '--no-commit-id', '--no-renames', '-z', first, sha]).split('\0').filter((f) => f !== '');
114
+
115
+ function isAncestor(wt, a, b) {
116
+ try {
117
+ git(wt, ['merge-base', '--is-ancestor', a, b]);
118
+ return true;
119
+ } catch (e) {
120
+ if (e instanceof GitError) return false;
121
+ throw e;
122
+ }
123
+ }
124
+
125
+ // `file` in merge `sha` is what one of its other parents holds, a parent the default branch's tip
126
+ // reaches: the merge took it from the default branch unchanged.
127
+ const fromDefault = (wt, sha, file, others, tip) =>
128
+ tip !== null && others.some((p) => isAncestor(wt, p, tip) && blobAt(wt, sha, file) === blobAt(wt, p, file));
129
+
90
130
  // A kit path changed since the red commit in a commit the kit did not make: a hand commit could
91
- // otherwise unfreeze a test or rewrite the evaluation set.
131
+ // otherwise unfreeze a test or rewrite the evaluation set (D-53, replacing D-50).
132
+ // - A commit the default branch's tip reaches was reviewed and merged there, so only this slice's
133
+ // own state file and verdicts are judged in it: the default branch never carries them while the
134
+ // slice is open, and its tip is a ref a clone can move or a fork's author can push to.
135
+ // - A merge is judged by its kit files against its first parent: each must equal what a parent on
136
+ // the default branch holds. This slice's own state file and verdicts must equal what another parent
137
+ // in the range holds, off the default branch: a line of the slice branch itself, as when the review
138
+ // worktree and the build worktree both pushed (review r2 H-1), whose commits are judged one by one
139
+ // here. So a hand edit made while merging, or a file taken whole from another branch, is caught.
140
+ // - A commit with no parent has every file it adds judged (--root).
92
141
  function forgedKitChange(wt, cfg, id, current, slice) {
93
142
  const paths = kitPaths(wt, cfg);
94
143
  const stateRel = posixRel(wt, path.join(paths.state, stateFileName(id)));
95
144
  const buildRel = posixRel(wt, paths.build);
96
145
  const sliceRel = posixRel(wt, slice.path);
97
- for (const sha of lines(git(wt, ['rev-list', '--no-merges', `${current.redCommit}..HEAD`]))) {
98
- const changes = lines(git(wt, ['diff-tree', '--no-commit-id', '--name-status', '--no-renames', '-r', sha])).map((l) => {
146
+ const configRel = posixRel(wt, paths.config);
147
+ // Kit files that are not this slice's business (D-43): another slice's state file or verdict, and
148
+ // BUILD.md, the view of every state. A commit whose kit changes are all of them is skipped, whoever
149
+ // made it and wherever it came from.
150
+ const stateDir = posixRel(wt, paths.state);
151
+ const mine = verdictFilePattern(id);
152
+ const othersOnly = (f) =>
153
+ f === buildRel ||
154
+ (f.startsWith(`${stateDir}/`) && f.endsWith('.json') && !f.slice(stateDir.length + 1).includes('/') && f !== stateRel) ||
155
+ (f.startsWith(REVIEWS) && !f.slice(REVIEWS.length).includes('/') && !mine.test(f.slice(REVIEWS.length)));
156
+ const own = (f) => f === stateRel || (f.startsWith(REVIEWS) && !f.slice(REVIEWS.length).includes('/') && mine.test(f.slice(REVIEWS.length)));
157
+ let rendered = false;
158
+ const tip = defaultBranchTip(wt, cfg);
159
+ const offDefault = tip === null ? null : new Set(lines(git(wt, ['rev-list', 'HEAD', `^${current.redCommit}`, `^${tip}`])));
160
+ const range = lines(git(wt, ['rev-list', '--parents', 'HEAD', `^${current.redCommit}`]));
161
+ // Commits whose own changes this loop judges: in the range, and off the default branch.
162
+ const judged = offDefault ?? new Set(range.map((l) => l.split(' ')[0]));
163
+ // `file` in merge `sha` is what another parent holds, a parent whose commits are judged here.
164
+ const fromSlice = (sha, file, others) => others.some((p) => judged.has(p) && blobAt(wt, sha, file) === blobAt(wt, p, file));
165
+ for (const line of range) {
166
+ const [sha, ...parents] = line.split(' ');
167
+ const onDefault = offDefault !== null && !offDefault.has(sha);
168
+ if (parents.length > 1) {
169
+ const kit = mergeFiles(wt, sha, parents[0]).filter((f) => isKitFile(wt, cfg, slice, f) && !othersOnly(f) && (!onDefault || own(f)));
170
+ const bad = kit.find((f) => (own(f) ? !fromSlice(sha, f, parents.slice(1)) : !fromDefault(wt, sha, f, parents.slice(1), tip)));
171
+ if (bad) return `${bad} was changed in ${short(sha)}, a merge, outside the kit; only build commands write it`;
172
+ continue;
173
+ }
174
+ const changes = lines(git(wt, ['diff-tree', '--root', '--no-commit-id', '--name-status', '--no-renames', '-r', sha])).map((l) => {
99
175
  const [status, ...rest] = l.split('\t');
100
176
  return { status, file: rest.join('\t') };
101
177
  });
102
- const kit = changes.map((c) => c.file).find((f) => isKitFile(wt, cfg, slice, f));
103
- if (!kit) continue;
178
+ const kitFiles = changes.map((c) => c.file).filter((f) => isKitFile(wt, cfg, slice, f) && (!onDefault || own(f)));
179
+ if (kitFiles.length === 0 || kitFiles.every(othersOnly)) continue;
180
+ const kit = kitFiles.find((f) => !othersOnly(f));
104
181
  const subject = git(wt, ['log', '-1', '--format=%s', sha]);
105
182
  const trailers = parseTrailers(git(wt, ['log', '-1', '--format=%B', sha]));
183
+ // build render's commits hold only the files update writes; what they wrote is judged at HEAD.
184
+ if (subject === renderSubject(id) && trailers.Slice === id) {
185
+ if (!renderPathsOnly(wt, sha)) return `${kit} was changed in ${short(sha)} outside the kit; a render commit holds only the files slicekit update writes`;
186
+ rendered = true;
187
+ continue;
188
+ }
189
+ // build config's commit: the config alone, under its subject, for a slice whose file at that
190
+ // commit names the config in its Expected changes.
191
+ if (subject === configSubject(id) && trailers.Slice === id && changes.length === 1 && changes[0].file === configRel && namesConfigAt(wt, sha, sliceRel)) continue;
106
192
  if (!kitCommit(id, subject, trailers, changes, stateRel, buildRel, sliceRel)) {
107
193
  return `${kit} was changed in ${short(sha)} outside the kit; only build commands write it`;
108
194
  }
109
195
  }
196
+ // With a render in the range, the files update writes must, at HEAD, be what a fresh render from
197
+ // this kit writes: an `update --check` of HEAD (D-43).
198
+ if (rendered) {
199
+ const stale = freshAt(wt, 'HEAD');
200
+ if (stale) return `${stale} at HEAD is not what slicekit update renders: changed outside the kit or by another kit; run slicekit build render ${id} again`;
201
+ }
110
202
  return null;
111
203
  }
112
204
 
113
- export function commitWork(root, cfg, id, { message, requireGreen = false, worktree } = {}) {
205
+ export function commitWork(root, cfg, id, { message, requireGreen = false, worktree, env = process.env } = {}) {
114
206
  if (typeof message !== 'string' || message.trim() === '') throw new BuildError('--message is required', 2);
115
207
  const wt = findWorktree(root, id, { worktree }).path;
116
208
  const current = building(wt, cfg, id, 'commit', COMMIT_FROM);
@@ -121,18 +213,22 @@ export function commitWork(root, cfg, id, { message, requireGreen = false, workt
121
213
  if (frozen) throw new BuildError(frozen);
122
214
  const paths = changedPaths(wt);
123
215
  const kit = paths.find((p) => isKitFile(wt, cfg, slice, p));
124
- if (kit) throw new BuildError(`${kit} is a kit file; build commit does not commit it`);
125
- const command = cfg.commands?.test ?? '';
216
+ if (kit) {
217
+ const config = kit === posixRel(wt, kitPaths(wt, cfg).config) ? `; run slicekit build config ${id}` : '';
218
+ throw new BuildError(`${kit} is a kit file; build commit does not commit it${config}`);
219
+ }
220
+ const { command, local } = buildTestCommand(root, cfg, env);
126
221
  if (command.trim() === '') throw new BuildError('commands.test is not declared in .slicekit/config.json');
222
+ const ranLocal = local ? command : null;
127
223
 
128
224
  const run = runCommand(wt, command);
129
225
  const unusable = unusableRun(command, run);
130
226
  if (unusable) throw unusable;
131
227
  if (requireGreen && run.exit !== 0) throw new BuildError(`tests fail (exit ${run.exit}): ${run.summary}`);
132
- if (paths.length === 0) return { sha: null, exit: run.exit };
228
+ if (paths.length === 0) return { sha: null, exit: run.exit, local: ranLocal };
133
229
  // Only the paths the status named: the developer's work, never the kit's files.
134
230
  const sha = commitPaths(wt, paths, `${message.trim()}\n\nran: ${command} → exit ${run.exit}\n\nSlice: ${id}`);
135
- return { sha, exit: run.exit };
231
+ return { sha, exit: run.exit, local: ranLocal };
136
232
  }
137
233
 
138
234
  // HEAD is this slice's amendment commit: the subject, the trailer, and the slice file alone.
@@ -143,24 +239,51 @@ function headIsAmendment(wt, id, sliceRel) {
143
239
  return subject === `docs(${id}): amend evaluation set` && trailers.Slice === id && files.length === 1 && files[0] === sliceRel;
144
240
  }
145
241
 
146
- // The state file on disk differs from HEAD's copy only by this unfreeze: its bookkeeping commit did
147
- // not land.
148
- function pendingUnfreeze(wt, stateRel, file) {
149
- let committed;
242
+ // A frozen test is amended while the slice is built or in review (D-43): a finding inside a frozen
243
+ // test is fixed during review. From review the amendment takes the slice back to building.
244
+ const AMEND_FROM = ['building', 'draft-pr', 'in-review', 'changes-requested'];
245
+
246
+ // The state file as HEAD holds it, or null: a hand edit of the file on disk never decides a step.
247
+ function committedState(wt, stateRel) {
150
248
  try {
151
- committed = JSON.parse(git(wt, ['show', `HEAD:${stateRel}`]));
249
+ return JSON.parse(git(wt, ['show', `HEAD:${stateRel}`]));
152
250
  } catch {
153
- return false;
251
+ return null;
154
252
  }
253
+ }
254
+
255
+ // `sha` is this slice's amendment commit, on HEAD's history: the subject, the trailer, the slice file alone.
256
+ function isAmendment(wt, id, sliceRel, sha) {
257
+ if (typeof sha !== 'string' || !/^[0-9a-f]{7,40}$/.test(sha)) return false;
258
+ try {
259
+ git(wt, ['merge-base', '--is-ancestor', sha, 'HEAD']);
260
+ } catch (e) {
261
+ if (e instanceof GitError) return false;
262
+ throw e;
263
+ }
264
+ const subject = git(wt, ['log', '-1', '--format=%s', sha]);
265
+ const trailers = parseTrailers(git(wt, ['log', '-1', '--format=%B', sha]));
266
+ const files = lines(git(wt, ['diff-tree', '--no-commit-id', '--name-only', '-r', sha]));
267
+ return subject === `docs(${id}): amend evaluation set` && trailers.Slice === id && files.length === 1 && files[0] === sliceRel;
268
+ }
269
+
270
+ // The state file on disk differs from HEAD's copy only by this unfreeze (and its move to building),
271
+ // its amendment commit is on HEAD's history, and HEAD's state is one amend runs from: its bookkeeping
272
+ // commit did not land.
273
+ function pendingUnfreeze(wt, id, stateRel, sliceRel, file) {
274
+ const committed = committedState(wt, stateRel);
275
+ if (!committed || !AMEND_FROM.includes(committed.state)) return false;
155
276
  const now = JSON.parse(fs.readFileSync(path.join(wt, ...stateRel.split('/')), 'utf8'));
156
277
  const added = now.history.at(-1);
157
- const strip = (s) => JSON.stringify({ ...s, unfrozen: null, history: null });
278
+ const strip = (s) => JSON.stringify({ ...s, unfrozen: null, history: null, state: null, handoff: null });
158
279
  return (
159
280
  strip(now) === strip(committed) &&
281
+ (now.state === committed.state || now.state === 'building') &&
160
282
  JSON.stringify(now.unfrozen) === JSON.stringify([...committed.unfrozen, file]) &&
161
283
  now.history.length === committed.history.length + 1 &&
162
284
  JSON.stringify(now.history.slice(0, -1)) === JSON.stringify(committed.history) &&
163
- added?.evidence?.unfreeze === file
285
+ added?.evidence?.unfreeze === file &&
286
+ isAmendment(wt, id, sliceRel, added?.evidence?.amendCommit)
164
287
  );
165
288
  }
166
289
 
@@ -170,16 +293,19 @@ export function amend(root, cfg, id, { test, reason, worktree } = {}) {
170
293
  if (typeof reason !== 'string' || reason.trim() === '') throw new BuildError('--reason is required', 2);
171
294
  if (typeof test !== 'string' || test.trim() === '') throw new BuildError('--test is required', 2);
172
295
  const wt = findWorktree(root, id, { worktree }).path;
173
- const current = building(wt, cfg, id, 'amend');
296
+ const current = readSlice(wt, cfg, id);
297
+ const stateRel = posixRel(wt, path.join(kitPaths(wt, cfg).state, stateFileName(id)));
298
+ // Where amend runs from is read from HEAD's state file, never the copy on disk.
299
+ const committed = committedState(wt, stateRel) ?? current;
300
+ if (!AMEND_FROM.includes(committed.state)) throw new BuildError(`${id} is ${committed.state}; amend runs from ${AMEND_FROM.join(', ')}`);
174
301
  const file = toWorktreePath(wt, test);
175
302
  // Checked before the slice file is committed; the words are unfreeze's own TransitionError reason.
176
303
  if (!current.frozenTests.includes(file)) throw new BuildError(`${file} is not a frozen test of ${id}`);
177
- const stateRel = posixRel(wt, path.join(kitPaths(wt, cfg).state, stateFileName(id)));
178
304
  const sliceRel = posixRel(wt, sliceIn(wt, cfg, id).path);
179
305
  const lastAmendment = () => git(wt, ['log', '-1', '--format=%H', `--grep=^docs(${id}): amend evaluation set$`, '--', sliceRel]);
180
306
  if (current.unfrozen.includes(file)) {
181
- if (!pendingUnfreeze(wt, stateRel, file)) throw new BuildError(`${file} is already unfrozen`);
182
- commitBookkeeping(wt, id, `unfreeze ${file}`, [stateRel]);
307
+ if (!pendingUnfreeze(wt, id, stateRel, sliceRel, file)) throw new BuildError(`${file} is already unfrozen`);
308
+ commitState(wt, cfg, id, `unfreeze ${file}`);
183
309
  return { sha: lastAmendment(), test: file };
184
310
  }
185
311
  let sha;
@@ -191,11 +317,11 @@ export function amend(root, cfg, id, { test, reason, worktree } = {}) {
191
317
  throw new BuildError('amend the slice file first; it has no change');
192
318
  }
193
319
  try {
194
- unfreeze(wt, cfg, id, file, { amendCommit: sha, reason: reason.trim() });
320
+ unfreeze(wt, cfg, id, file, { amendCommit: sha, reason: reason.trim() }, { to: 'building' });
195
321
  } catch (e) {
196
322
  if (e instanceof TransitionError) throw new BuildError(e.reason);
197
323
  throw e;
198
324
  }
199
- commitBookkeeping(wt, id, `unfreeze ${file}`, [stateRel]);
325
+ commitState(wt, cfg, id, `unfreeze ${file}`);
200
326
  return { sha, test: file };
201
327
  }
@@ -0,0 +1,50 @@
1
+ // `build config` (REQ-2.6, D-50): a slice that changes the kit's own config commits the worktree's
2
+ // changed `.slicekit/config.json` alone, as `chore(slicekit): <id> config`, as `build render` commits
3
+ // a render. `build commit` never commits a kit file; it accepts this commit when its subject, its
4
+ // trailer and its one file match and the slice file at that commit names the config (issue #51).
5
+ import { ConfigError, loadConfig } from '../config.js';
6
+ import { GitError, commitPaths, git } from '../git.js';
7
+ import { parseSliceFile } from '../slicefile.js';
8
+ import { readSlice } from '../state/index.js';
9
+ import { posixRel, sliceIn } from './red.js';
10
+ import { BuildError, findWorktree } from './worktree.js';
11
+
12
+ export const CONFIG = '.slicekit/config.json';
13
+ // The states `build render` runs from.
14
+ const CONFIG_FROM = ['building', 'draft-pr', 'in-review', 'changes-requested', 'ci-green', 'ready'];
15
+
16
+ export const configSubject = (id) => `chore(slicekit): ${id} config`;
17
+
18
+ // Whether the slice file at `rev` (POSIX `sliceRel`) lists the config in its Expected changes.
19
+ export function namesConfigAt(wt, rev, sliceRel) {
20
+ let text;
21
+ try {
22
+ text = git(wt, ['show', `${rev}:${sliceRel}`]);
23
+ } catch (e) {
24
+ if (e instanceof GitError) return false;
25
+ throw e;
26
+ }
27
+ try {
28
+ return parseSliceFile(text, sliceRel).expectedChanges.includes(CONFIG);
29
+ } catch {
30
+ return false;
31
+ }
32
+ }
33
+
34
+ // -> { sha }: the config commit, or sha null when the worktree's config has no change.
35
+ export function configSlice(root, rootCfg, id, { worktree } = {}) {
36
+ const wt = findWorktree(root, id, { worktree }).path;
37
+ const current = readSlice(wt, rootCfg, id);
38
+ if (!CONFIG_FROM.includes(current.state)) throw new BuildError(`${id} is ${current.state}; config runs from ${CONFIG_FROM.join(', ')}`);
39
+ const sliceRel = posixRel(wt, sliceIn(wt, rootCfg, id).path);
40
+ if (!namesConfigAt(wt, 'HEAD', sliceRel)) throw new BuildError(`slice ${id} does not name ${CONFIG} in its Expected changes`);
41
+ try {
42
+ loadConfig(wt);
43
+ } catch (e) {
44
+ if (e instanceof ConfigError) throw new BuildError(`${CONFIG}: ${e.message}`);
45
+ throw e;
46
+ }
47
+ if (git(wt, ['--literal-pathspecs', 'status', '--porcelain', '--', CONFIG]) === '') return { sha: null };
48
+ const sha = commitPaths(wt, [CONFIG], `${configSubject(id)}\n\nSlice: ${id}`);
49
+ return { sha };
50
+ }