slicekit 0.2.0 → 0.3.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 (44) hide show
  1. package/README.md +7 -2
  2. package/bin/slicekit.js +0 -0
  3. package/package.json +1 -1
  4. package/src/adapters/githost/fixture.js +106 -0
  5. package/src/adapters/githost/gh-json.js +201 -0
  6. package/src/adapters/githost/github.js +141 -0
  7. package/src/adapters/tracker/index.js +5 -1
  8. package/src/adapters/tracker/jira.js +133 -0
  9. package/src/build/commit.js +85 -7
  10. package/src/build/decline.js +17 -8
  11. package/src/build/record.js +11 -1
  12. package/src/check/ci-event.js +38 -6
  13. package/src/check/index.js +6 -1
  14. package/src/check/rules/ci-body.js +1 -1
  15. package/src/check/rules/ci-title.js +10 -4
  16. package/src/check/rules/frozen.js +127 -0
  17. package/src/check/rules/host-rules.js +149 -0
  18. package/src/check/rules/journal.js +130 -3
  19. package/src/check/rules/references.js +31 -0
  20. package/src/check/rules/sync-release.js +94 -0
  21. package/src/cli/build.js +8 -7
  22. package/src/cli/index.js +13 -0
  23. package/src/cli/init.js +29 -2
  24. package/src/cli/journal.js +44 -2
  25. package/src/cli/status.js +14 -2
  26. package/src/cli/sync.js +52 -0
  27. package/src/config.js +77 -3
  28. package/src/git.js +65 -1
  29. package/src/hooks/paths.js +103 -0
  30. package/src/hooks/pre-bash.js +642 -43
  31. package/src/hooks/pre-edit.js +23 -3
  32. package/src/init.js +136 -7
  33. package/src/journal.js +153 -12
  34. package/src/pr.js +1 -1
  35. package/src/prbody.js +1 -1
  36. package/src/release-version.js +196 -0
  37. package/src/render/settings.js +26 -2
  38. package/src/render/update.js +1 -1
  39. package/src/state/index.js +11 -0
  40. package/src/state/sync.js +182 -0
  41. package/src/workflow.js +141 -29
  42. package/templates/instructions/commands/build.md +12 -2
  43. package/templates/workflow/pins.json +2 -1
  44. package/templates/workflow/slicekit.yml +46 -11
@@ -0,0 +1,149 @@
1
+ // host-rules (03 REQ-3.14, D-77, D-81, D-84): the repository rulesets that apply to the default
2
+ // branch, read through C-1, hold every rule the kit relies on: a pull request before merge, at least
3
+ // one approving review (from a code owner when the repository has a CODEOWNERS file), the kit's CI
4
+ // checks required, and force push refused. Each rule missing is one finding. Rulesets only: a branch
5
+ // on classic branch protection alone is told to move to a ruleset (D-84).
6
+ //
7
+ // When the host cannot be read (no network, no token, a token that may not read the rules), the rule
8
+ // fails under --ci and otherwise reports a note, "host rules not checked", that does not block (D-81).
9
+ // When the generated workflow has a sync job, the rule also reads the repository's Actions workflow
10
+ // permissions through C-1: the sync job opens its [sync] pull request with the workflow's own token
11
+ // (REQ-3.11), which GitHub refuses while "Allow GitHub Actions to create and approve pull requests" is
12
+ // off. Off fails under --ci and is a note otherwise. The workflow's own token cannot read that setting
13
+ // (it needs administration read), so a read the host refuses is a note in both, never a failure: under
14
+ // D-81 it would fail every CI run, which no setting a human can change would fix.
15
+ // A repository with no origin remote names no host: nothing to judge. The rule never writes a host
16
+ // setting; `slicekit init --protect` is the one place that does, and shares missingRules.
17
+ import { getHost } from '../../adapters/githost/index.js';
18
+ import { GitHostError } from '../../adapters/githost/errors.js';
19
+ import { hasRemote } from '../../git.js';
20
+ import { renderWorkflow } from '../../workflow.js';
21
+
22
+ export const id = 'host-rules';
23
+ export const blocking = true;
24
+ export const ratchet = false;
25
+
26
+ const PROTECT = 'run slicekit init --protect as an admin';
27
+
28
+ // Where a human turns on the setting the sync job needs; slicekit never changes it (D-77).
29
+ export const ACTIONS_PR_SETTING = 'Settings, Actions, General, Workflow permissions, "Allow GitHub Actions to create and approve pull requests"';
30
+ export const ACTIONS_PR_OFF = `GitHub Actions may not create pull requests, so the sync job cannot open its [sync] pull request; a human turns on ${ACTIONS_PR_SETTING} (approvals still need a human under the ruleset)`;
31
+
32
+ // Whether the workflow renderWorkflow writes for `cfg` has a sync job.
33
+ export const hasSyncJob = (cfg) => /^jobs:\s*$[\s\S]*^ {2}sync:\s*$/m.test(renderWorkflow(cfg).replace(/\r\n/g, '\n'));
34
+
35
+ // The sync job's Actions setting: 'on', 'off', 'unknown' (the host does not say) or { error } when
36
+ // the host refused the read.
37
+ export function actionsPullRequestSetting(cfg, env, root) {
38
+ try {
39
+ const got = getHost(cfg, env, root).readWorkflowPermissions();
40
+ if (got === null) return 'unknown';
41
+ return got.canCreatePullRequests ? 'on' : 'off';
42
+ } catch (e) {
43
+ if (!(e instanceof GitHostError)) throw e;
44
+ return { error: e.message };
45
+ }
46
+ }
47
+ // The jobs of the generated workflow a merge waits on: the gate, and the checks job, which needs every
48
+ // command and observability job and passes when each passed or was skipped for bookkeeping. A command
49
+ // job's matrix names are never required: a job skipped by its own if reports one check under its id
50
+ // and none of them (D-49), so a bookkeeping head would never satisfy them.
51
+ const CHECK_JOB = /^(gate|checks)$/;
52
+
53
+ const unquote = (v) => (v.startsWith("'") && v.endsWith("'") && v.length >= 2 ? v.slice(1, -1).replace(/''/g, "'") : v);
54
+
55
+ // The check names GitHub gives the gate and checks jobs of a rendered workflow: each job's `name:` or
56
+ // its id. Neither job has a matrix.
57
+ export function workflowCheckNames(text) {
58
+ const jobs = [];
59
+ let inJobs = false;
60
+ for (const line of text.replace(/\r\n/g, '\n').split('\n')) {
61
+ if (/^jobs:\s*$/.test(line)) {
62
+ inJobs = true;
63
+ continue;
64
+ }
65
+ if (!inJobs) continue;
66
+ if (/^\S/.test(line)) {
67
+ inJobs = false;
68
+ continue;
69
+ }
70
+ let m = /^ {2}([A-Za-z0-9_-]+):\s*$/.exec(line);
71
+ if (m) jobs.push({ id: m[1], name: null });
72
+ else if ((m = /^ {4}name: (.+)$/.exec(line)) && jobs.length > 0) jobs.at(-1).name = unquote(m[1].trim());
73
+ }
74
+ return jobs.filter((j) => CHECK_JOB.test(j.id)).map((j) => j.name ?? j.id);
75
+ }
76
+
77
+ // The checks a merge into the default branch must wait on: the gate and checks jobs renderWorkflow writes.
78
+ export const requiredChecks = (cfg) => workflowCheckNames(renderWorkflow(cfg));
79
+
80
+ // Each rule `rules` (C-1 readBranchRules) lacks, as { key, value, missing, set }: `value` is what the
81
+ // ruleset write takes for `key`, `missing` the finding's text and `set` what init --protect prints.
82
+ export function missingRules(cfg, rules, codeowners) {
83
+ const out = [];
84
+ if (!rules.pullRequest) {
85
+ out.push({ key: 'pullRequest', value: true, missing: 'a pull request is not required before merge', set: 'a pull request is required before merge' });
86
+ }
87
+ if (!(rules.approvals >= 1)) {
88
+ out.push({ key: 'approvals', value: 1, missing: 'no approving review is required', set: 'one approving review is required' });
89
+ }
90
+ if (codeowners && !rules.codeOwnerReview) {
91
+ out.push({
92
+ key: 'codeOwnerReview',
93
+ value: true,
94
+ missing: `the approving review is not required to come from a code owner (${codeowners.path})`,
95
+ set: `the approving review must come from a code owner (${codeowners.path})`,
96
+ });
97
+ }
98
+ const have = new Set(rules.requiredChecks ?? []);
99
+ const lacking = requiredChecks(cfg).filter((c) => !have.has(c));
100
+ if (lacking.length > 0) {
101
+ out.push({
102
+ key: 'requiredChecks',
103
+ value: lacking,
104
+ missing: `the kit's CI checks are not required: ${lacking.join(', ')}`,
105
+ set: `the kit's CI checks are required: ${lacking.join(', ')}`,
106
+ });
107
+ }
108
+ if (!rules.refuseForcePush) {
109
+ out.push({ key: 'refuseForcePush', value: true, missing: 'force push is not refused', set: 'force push is refused' });
110
+ }
111
+ return out;
112
+ }
113
+
114
+ // What the host says about the default branch: { rules, codeowners }. Throws GitHostError when it
115
+ // cannot say.
116
+ export function readHostRules(cfg, env, root) {
117
+ const host = getHost(cfg, env, root);
118
+ const rules = host.readBranchRules(cfg.defaultBranch);
119
+ return { rules, codeowners: host.readCodeowners() };
120
+ }
121
+
122
+ export function run(ctx) {
123
+ const { root, cfg, env = process.env, ci } = ctx;
124
+ if (!ctx.git?.isRepo || typeof cfg?.defaultBranch !== 'string') return [];
125
+ if (!env.SLICEKIT_GITHOST_FIXTURE && !hasRemote(root)) return [];
126
+ const branch = cfg.defaultBranch;
127
+ let read;
128
+ try {
129
+ read = readHostRules(cfg, env, root);
130
+ } catch (e) {
131
+ if (!(e instanceof GitHostError)) throw e;
132
+ if (ci) return [{ file: '-', line: 0, message: `${branch}: host rules not checked: ${e.message}` }];
133
+ return [{ file: '-', line: 0, message: `host rules not checked: ${e.message}`, note: true }];
134
+ }
135
+ const found = [];
136
+ if (read.rules.classic && read.rules.ruleCount === 0) {
137
+ found.push(`${branch}: protected by classic branch protection only; move to a repository ruleset, the protection slicekit reads (D-84), or ${PROTECT}`);
138
+ }
139
+ for (const m of missingRules(cfg, read.rules, read.codeowners)) found.push(`${branch}: ${m.missing}; ${PROTECT}`);
140
+ const out = found.map((message) => ({ file: '-', line: 0, message }));
141
+ if (hasSyncJob(cfg)) {
142
+ const setting = actionsPullRequestSetting(cfg, env, root);
143
+ if (setting === 'off') out.push({ file: '-', line: 0, message: ACTIONS_PR_OFF, ...(ci ? {} : { note: true }) });
144
+ else if (typeof setting === 'object') out.push({ file: '-', line: 0, message: `the Actions pull request setting not checked: ${setting.error}`, note: true });
145
+ }
146
+ return out;
147
+ }
148
+
149
+ export default { id, blocking, ratchet, run };
@@ -1,17 +1,144 @@
1
- // journal (03 REQ-3.7, REQ-3.8, D-34, D-36): every file under .slicekit/journal/ must verify as an unbroken
1
+ // journal (03 REQ-3.7, REQ-3.8, D-34, D-36, D-71, D-89): every file under .slicekit/journal/ must verify as an unbroken
2
2
  // hash chain from genesis (one finding per broken file, at its first broken line); nothing else may sit
3
3
  // in that directory but `*.log` files and their `*.lock`; and every journal file committed at the merge
4
4
  // base with the default branch must still be there and only have grown. Silent when there is no journal
5
5
  // and, for the git part, outside a repository; without a base, silent locally and one finding under
6
6
  // --ci. Never repairs.
7
- import { appendOnlyProblems, verifyJournal } from '../../journal.js';
7
+ //
8
+ // Under --ci only, on the branch the run judges (branchTip: the pull request's head, or the branch of a
9
+ // dispatched run) against its merge base with the default branch:
10
+ // - each commit that changes a file under .slicekit/journal/ must be signed and verified by the git
11
+ // host (C-1 getCommit); one finding per commit that is not, naming it (D-71). The journal-heads file
12
+ // sits outside that directory, so the sync job's unsigned commits are not asked about;
13
+ // - when .slicekit/journal-heads.log changed, the branch must be a sync branch (`sync/<short sha>`),
14
+ // the file at the base must be a byte prefix of the file at the tip, and each line it gains must equal
15
+ // the line headsLines computes for that line's merge commit from git and C-1 getRun (D-89). A line
16
+ // that differs is a finding at its line number. Each line is recomputed against the heads file at the
17
+ // base plus the lines added before it, as the sync job computed it against the file at its merge;
18
+ // - on a sync branch whose short sha names a commit of this clone, the file must gain a line for each
19
+ // journal file headsFiles owes a line at that merge, whether or not the file changed; one finding per
20
+ // line it lacks (REQ-3.8).
21
+ // Outside CI no signature or run is read.
22
+ import path from 'node:path';
23
+ import { getHost } from '../../adapters/githost/index.js';
24
+ import { GitHostError } from '../../adapters/githost/errors.js';
25
+ import { GitError, resolveCommit } from '../../git.js';
26
+ import { appendOnlyProblems, headsAt, headsFiles, headsLines, journalCommits, mergeBaseWith, parseHeadsLine, SIGNED_MESSAGE, verifyJournal } from '../../journal.js';
27
+ import { kitPaths } from '../../paths.js';
28
+ import { SYNC_BRANCH, branchTip } from '../ci-event.js';
8
29
 
9
30
  export const id = 'journal';
10
31
  export const blocking = true;
11
32
  export const ratchet = false;
12
33
 
34
+ const short = (sha) => sha.slice(0, 7);
35
+ const toPosix = (p) => p.split(path.sep).join('/');
36
+
13
37
  export function run(ctx) {
14
- return [...verifyJournal(ctx.root, ctx.cfg).problems, ...appendOnlyProblems(ctx.root, ctx.cfg, { ci: Boolean(ctx.ci) })];
38
+ const found = [...verifyJournal(ctx.root, ctx.cfg).problems, ...appendOnlyProblems(ctx.root, ctx.cfg, { ci: Boolean(ctx.ci) })];
39
+ if (!ctx.ci) return found;
40
+ return [...found, ...ciProblems(ctx)];
41
+ }
42
+
43
+ function ciProblems(ctx) {
44
+ const { root, cfg } = ctx;
45
+ const at = branchTip(ctx);
46
+ if (at === null) return [];
47
+ const mb = mergeBaseWith(root, cfg, { tip: at.tip });
48
+ if (mb === null) return []; // appendOnlyProblems already reports the missing base under --ci
49
+ let host;
50
+ const theHost = () => (host ??= getHost(cfg, ctx.env ?? process.env, root));
51
+ return [...signedProblems(ctx, theHost, mb.base, at.tip), ...headsProblems(ctx, theHost, mb, at)];
52
+ }
53
+
54
+ function signedProblems(ctx, theHost, base, tip) {
55
+ const relDir = toPosix(path.relative(ctx.root, kitPaths(ctx.root, ctx.cfg).journalDir));
56
+ const out = [];
57
+ for (const sha of journalCommits(ctx.root, ctx.cfg, base, tip)) {
58
+ let got;
59
+ try {
60
+ got = theHost().getCommit(sha);
61
+ } catch (e) {
62
+ if (!(e instanceof GitHostError)) throw e;
63
+ out.push({ file: relDir, line: 0, message: `commit ${short(sha)} changes a journal file and the host could not say whether it is signed (${e.message}); ${SIGNED_MESSAGE}` });
64
+ continue;
65
+ }
66
+ if (!got.verified) out.push({ file: relDir, line: 0, message: `commit ${short(sha)} changes a journal file and its signature is not verified by the host; ${SIGNED_MESSAGE}` });
67
+ }
68
+ return out;
69
+ }
70
+
71
+ function headsProblems(ctx, theHost, mb, at) {
72
+ const { root, cfg } = ctx;
73
+ const { rel, was, now } = headsAt(root, cfg, mb.base, at.tip);
74
+ const sync = SYNC_BRANCH.test(at.branch);
75
+ const syncMerge = sync ? resolveCommit(root, at.branch.slice('sync/'.length)) : null;
76
+ // A sync branch whose merge this checkout cannot resolve fails closed: no omitted-line check could run.
77
+ if (sync && syncMerge === null) return [{ file: rel, line: 0, message: `${at.branch} names a merge this checkout cannot resolve; a sync pull request records a commit of ${mb.ref}` }];
78
+ if (was.equals(now)) return syncMerge === null ? [] : omitted(root, cfg, rel, syncMerge, was.toString('utf8'));
79
+ const at0 = (message) => [{ file: rel, line: 0, message }];
80
+ if (!sync) return at0(`${rel} changed on ${at.branch}; only a sync pull request (a sync/<short sha> branch) may change it`);
81
+ if (now.length < was.length || !now.subarray(0, was.length).equals(was)) return at0(`${rel} is not append-only against ${mb.ref}`);
82
+ const before = was.toString('utf8');
83
+ const first = (before.match(/\n/g)?.length ?? 0) + (before !== '' && !before.endsWith('\n') ? 1 : 0) + 1;
84
+ const added = now.subarray(was.length).toString('utf8');
85
+ const parts = added.split('\n');
86
+ const torn = parts.at(-1) !== '';
87
+ const lines = torn ? parts : parts.slice(0, -1);
88
+ const out = [];
89
+ const expected = new Map();
90
+ const used = new Map();
91
+ lines.forEach((text, i) => {
92
+ const n = first + i;
93
+ const differs = (want) => out.push({ file: rel, line: n, message: `${rel} line ${n} differs from the line CI computes: ${want}` });
94
+ const p = parseHeadsLine(text);
95
+ if (p === null || (torn && i === lines.length - 1)) return differs('a line that does not parse');
96
+ const key = `${p.merge} ${p.run}`;
97
+ if (!expected.has(key)) expected.set(key, recompute(root, cfg, theHost, p, before + lines.slice(0, i).map((l) => `${l}\n`).join('')));
98
+ const want = expected.get(key);
99
+ if (typeof want === 'string') return differs(want);
100
+ const j = used.get(key) ?? 0;
101
+ used.set(key, j + 1);
102
+ if (want[j] !== text) differs(want[j] ?? `no line (the merge ${short(p.merge)} changed ${want.length} journal file${want.length === 1 ? '' : 's'})`);
103
+ });
104
+ for (const [key, want] of expected) {
105
+ if (typeof want === 'string') continue;
106
+ const j = used.get(key) ?? 0;
107
+ for (const missing of want.slice(j)) out.push({ file: rel, line: 0, message: `${rel} lacks the line CI computes: ${missing}` });
108
+ }
109
+ if (syncMerge !== null && ![...expected.keys()].some((key) => key.startsWith(`${syncMerge} `))) out.push(...omitted(root, cfg, rel, syncMerge, before));
110
+ return out;
111
+ }
112
+
113
+ // One finding per journal file the sync pull request for `merge` owes a heads line and does not add one
114
+ // for, computed against the heads file at the base (`recorded`); the run is not read, since no line names it.
115
+ function omitted(root, cfg, rel, merge, recorded) {
116
+ let owed;
117
+ try {
118
+ owed = headsFiles(root, cfg, merge, { recorded });
119
+ } catch (e) {
120
+ if (!(e instanceof GitError)) throw e;
121
+ return [];
122
+ }
123
+ return owed.map(({ file, hash }) => ({ file: rel, line: 0, message: `${rel} lacks a line for ${file} hash=${hash} at merge ${short(merge)}; the sync pull request adds one per journal file the merge changed` }));
124
+ }
125
+
126
+ // The lines headsLines computes for p's merge commit and run, or a string saying why there are none.
127
+ function recompute(root, cfg, theHost, p, recorded) {
128
+ let r;
129
+ try {
130
+ r = theHost().getRun(p.run);
131
+ } catch (e) {
132
+ if (!(e instanceof GitHostError) && !/run id must be/.test(String(e?.message))) throw e;
133
+ return `none (run ${p.run} could not be read: ${e.message})`;
134
+ }
135
+ if (r.headSha !== p.merge) return `none (run ${p.run} ran on ${short(String(r.headSha))}, not ${short(p.merge)})`;
136
+ try {
137
+ return headsLines(root, cfg, p.merge, { run: p.run, workflow: r.workflow, actor: r.actor }, { recorded });
138
+ } catch (e) {
139
+ if (!(e instanceof GitError)) throw e;
140
+ return `none (merge ${short(p.merge)} is not a commit of this clone)`;
141
+ }
15
142
  }
16
143
 
17
144
  export default { id, blocking, ratchet, run };
@@ -6,6 +6,7 @@ import { findSliceFiles } from '../../slicefile.js';
6
6
  import { readSlice } from '../../state/index.js';
7
7
  import { MARKER as BUILD_MARKER } from '../../state/build.js';
8
8
  import { intakeStatus } from '../context.js';
9
+ import { git, GitError } from '../../git.js';
9
10
 
10
11
  export const id = 'references';
11
12
  export const blocking = true;
@@ -120,6 +121,34 @@ function sliceAddresses(ctx) {
120
121
  return out;
121
122
  }
122
123
 
124
+ // A verdict file already on the default branch, at origin's copy or the local one, is history: it
125
+ // was reviewed and merged. A version bump renames `.slicekit/rendered/<version>/`, so the old
126
+ // version's paths it names are gone; those are not findings (issue #75). A verdict that is on
127
+ // neither, such as the current slice's, is checked in full.
128
+ const REVIEWS = '.slicekit/reviews/';
129
+ const RENDERED = '.slicekit/rendered/';
130
+ // Whether a target names a path under the rendered folder, read from the root or from the verdict's
131
+ // own directory.
132
+ const inRendered = (rel, value) => {
133
+ const v = toSlashes(value);
134
+ const fromRoot = path.posix.normalize(v.replace(/^\/+/, ''));
135
+ const fromDoc = path.posix.normalize(path.posix.join(path.posix.dirname(rel), v));
136
+ return fromRoot.startsWith(RENDERED) || (!v.startsWith('/') && fromDoc.startsWith(RENDERED));
137
+ };
138
+ function onDefaultBranch(ctx, rel) {
139
+ const branch = ctx.cfg?.defaultBranch;
140
+ if (!branch || !rel.startsWith(REVIEWS)) return false;
141
+ for (const ref of [`refs/remotes/origin/${branch}`, `refs/heads/${branch}`]) {
142
+ try {
143
+ git(ctx.root, ['cat-file', '-e', `${ref}:${rel}`]);
144
+ return true;
145
+ } catch (e) {
146
+ if (!(e instanceof GitError)) throw e;
147
+ }
148
+ }
149
+ return false;
150
+ }
151
+
123
152
  export function run(ctx) {
124
153
  const findings = [];
125
154
  const slugCache = new Map();
@@ -203,6 +232,7 @@ export function run(ctx) {
203
232
  // like any doc and is itself a finding (REQ-1.2).
204
233
  if (intake === 'unpinned') add(0, 'intake file has no valid sidecar');
205
234
  const promises = promiseLines(ctx, doc, sliceIds, (message) => add(0, message));
235
+ const merged = onDefaultBranch(ctx, doc.rel);
206
236
 
207
237
  // A pending marker defers its line's paths while the slice it names is not merged or
208
238
  // released; once it is, the paths are checked and the marker is stale. Its own address is not
@@ -226,6 +256,7 @@ export function run(ctx) {
226
256
  if (ref.kind === 'path') {
227
257
  if (ref.line <= viewEnd || deferred.has(ref.line)) continue;
228
258
  if (ref.via === 'code' && promises?.has(ref.line)) continue;
259
+ if (merged && inRendered(doc.rel, ref.value)) continue;
229
260
  if (isPathLike(ref.value) && !resolve(doc, ref.value, ref.via)) add(ref.line, `missing file ${ref.value}`);
230
261
  } else if (ref.kind === 'anchor') {
231
262
  if (!/\.md$/i.test(ref.file)) continue;
@@ -0,0 +1,94 @@
1
+ // sync-release (05 REQ-5.5, D-43, D-89, D-90): under --ci on a sync pull request (a `sync/<short sha>`
2
+ // branch), the files the release step writes (package.json, CHANGELOG.md and the rendered files) must
3
+ // equal what CI computes for the merge the branch names: a fresh checkout of that merge in a temporary
4
+ // worktree, synced from the git host and given the version, section and render the sync step would
5
+ // write there. So package.json may change only in its version field, CHANGELOG.md only by the one new
6
+ // section, and a rendered file only to its fresh render at that version. One finding per file that
7
+ // differs, naming it. A sync branch whose merge the checkout cannot resolve is the journal rule's
8
+ // finding. Silent outside CI and on any other branch, and when the config has no release.auto and the
9
+ // branch changes none of those files.
10
+ import { execFileSync } from 'node:child_process';
11
+ import fs from 'node:fs';
12
+ import os from 'node:os';
13
+ import path from 'node:path';
14
+ import { getHost } from '../../adapters/githost/index.js';
15
+ import { GitHostError } from '../../adapters/githost/errors.js';
16
+ import { ConfigError, loadConfig } from '../../config.js';
17
+ import { git, resolveCommit } from '../../git.js';
18
+ import { PACKAGE, ReleaseError, applyRelease, isKitRoot, isReleasePath } from '../../release-version.js';
19
+ import { syncFromHost } from '../../state/sync.js';
20
+ import { SYNC_BRANCH, branchTip } from '../ci-event.js';
21
+
22
+ export const id = 'sync-release';
23
+ export const blocking = true;
24
+ export const ratchet = false;
25
+
26
+ const nul = (out) => out.split('\0').filter((l) => l !== '');
27
+
28
+ export function run(ctx) {
29
+ if (!ctx.ci) return [];
30
+ const { root, cfg } = ctx;
31
+ const at = branchTip(ctx);
32
+ if (at === null || !SYNC_BRANCH.test(at.branch)) return [];
33
+ const merge = resolveCommit(root, at.branch.slice('sync/'.length));
34
+ if (merge === null) return [];
35
+ const owns = isReleasePath(cfg);
36
+ const changed = nul(git(root, ['diff', '--name-only', '--no-renames', '-z', merge, at.tip])).filter(owns);
37
+ if (cfg.release?.auto !== true && changed.length === 0) return [];
38
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'slicekit-sync-release-'));
39
+ const wt = path.join(tmp, 'merge');
40
+ try {
41
+ git(root, ['worktree', 'add', '--quiet', '--detach', wt, merge]);
42
+ let expected;
43
+ try {
44
+ expected = expectedFiles(root, ctx, wt, owns);
45
+ } catch (e) {
46
+ if (!(e instanceof GitHostError || e instanceof ConfigError || e instanceof ReleaseError)) throw e;
47
+ return [{ file: PACKAGE, line: 0, message: `the version for the merge ${merge.slice(0, 7)} could not be computed (${e.message}); a sync pull request carries only what CI computes` }];
48
+ }
49
+ const out = [];
50
+ for (const file of [...new Set([...changed, ...expected.keys()])].sort()) {
51
+ const want = expected.has(file) ? expected.get(file) : read(wt, file);
52
+ const got = blob(root, at.tip, file);
53
+ if (!same(want, got)) out.push({ file, line: 0, message: `${file} differs from what CI computes for the merge ${merge.slice(0, 7)}; a sync pull request changes it only as the sync step does (package.json's version, one new CHANGELOG.md section, the render at that version)` });
54
+ }
55
+ return out;
56
+ } finally {
57
+ try {
58
+ git(root, ['worktree', 'remove', '--force', wt]);
59
+ } catch {
60
+ // Left for git worktree prune.
61
+ }
62
+ fs.rmSync(tmp, { recursive: true, force: true });
63
+ }
64
+ }
65
+
66
+ const same = (a, b) => (a === null ? b === null : b !== null && a.equals(b));
67
+
68
+ function read(dir, file) {
69
+ const abs = path.join(dir, ...file.split('/'));
70
+ return fs.existsSync(abs) && fs.statSync(abs).isFile() ? fs.readFileSync(abs) : null;
71
+ }
72
+
73
+ // The file at `rev` as a Buffer, or null when the commit does not hold it.
74
+ function blob(root, rev, file) {
75
+ const listed = git(root, ['ls-tree', '--name-only', rev, '--', file]);
76
+ if (listed === '') return null;
77
+ return execFileSync('git', ['cat-file', 'blob', `${rev}:${file}`], { cwd: root, stdio: ['ignore', 'pipe', 'pipe'] });
78
+ }
79
+
80
+ // Runs the sync step in the merge's worktree and returns the release paths it changed, with their
81
+ // new content (null for a removed file).
82
+ function expectedFiles(root, ctx, wt, owns) {
83
+ const cfg = loadConfig(wt);
84
+ const host = getHost(cfg, ctx.env ?? process.env, root);
85
+ const { changes } = syncFromHost(wt, cfg, host);
86
+ applyRelease(wt, cfg, changes, { merge: 'HEAD', isKit: isKitRoot(root) });
87
+ const tracked = nul(git(wt, ['diff', '--name-only', '--no-renames', '-z', 'HEAD']));
88
+ const untracked = nul(git(wt, ['ls-files', '--others', '--exclude-standard', '-z']));
89
+ const out = new Map();
90
+ for (const f of [...new Set([...tracked, ...untracked])].filter(owns)) out.set(f, read(wt, f));
91
+ return out;
92
+ }
93
+
94
+ export default { id, blocking, ratchet, run };
package/src/cli/build.js CHANGED
@@ -28,7 +28,7 @@ import { INDEPENDENT_MISSING } from '../state/transitions.js';
28
28
 
29
29
  const SUBCOMMANDS = ['next', 'start', 'red', 'commit', 'render', 'config', 'amend', 'pr', 'verdict', 'decline', 'finish', 'sync', 'parallel'];
30
30
  const USAGE =
31
- 'build next | build start <id> [--descr <d>] | build parallel P<n> | build red <id> --tests <a,b> [--worktree <p>] | build commit <id> --message <m> [--require-green] [--worktree <p>] | build render <id> [--worktree <p>] | build config <id> [--worktree <p>] | build amend <id> --test <path> --reason <r> [--worktree <p>] | build pr <id> [--notes <file>] [--worktree <p>] | build verdict <id> <file> [--independent] [--worktree <p>] | build decline <id> <H-n> [--worktree <p>] | build finish <id> [--wait <s>, default 90] [--worktree <p>] | build sync <id> [--worktree <p>]';
31
+ 'build next | build start <id> [--descr <d>] | build parallel P<n> | build red <id> --tests <a,b> [--worktree <p>] | build commit <id> --message <m> [--require-green] [--worktree <p>] (commits the staged paths; with nothing staged, every changed path) | build render <id> [--worktree <p>] | build config <id> [--worktree <p>] | build amend <id> [--test <path>] --reason <r> [--worktree <p>] (no --test: the slice file alone, once every test it names is unfrozen) | build pr <id> [--notes <file>] [--worktree <p>] | build verdict <id> <file> [--independent] [--worktree <p>] | build decline <id> <H-n> [--worktree <p>] | build finish <id> [--wait <s>, default 90] [--worktree <p>] | build sync <id> [--worktree <p>]';
32
32
 
33
33
  const OPTIONS = {
34
34
  descr: { type: 'string' },
@@ -138,10 +138,10 @@ function configStep(root, io, positionals, values) {
138
138
  }
139
139
 
140
140
  function amendStep(root, io, positionals, values) {
141
- if (positionals.length !== 1 || values.test === undefined || values.reason === undefined) return usage(io);
141
+ if (positionals.length !== 1 || values.reason === undefined) return usage(io);
142
142
  const cfg = loadConfig(root);
143
- const { test } = amend(root, cfg, positionals[0], { test: values.test, reason: values.reason, worktree: values.worktree });
144
- io.stdout(`unfroze ${test}\n`);
143
+ const { sha, test } = amend(root, cfg, positionals[0], { test: values.test, reason: values.reason, worktree: values.worktree });
144
+ io.stdout(test === null ? `${sha.slice(0, 7)} amended the slice file\n` : `unfroze ${test}\n`);
145
145
  return 0;
146
146
  }
147
147
 
@@ -182,12 +182,12 @@ function verdictStep(root, io, positionals, values) {
182
182
 
183
183
  // Prints the issue's URL, and `(already filed)` (`, closed` for a closed one) when the finding's issue
184
184
  // was there before.
185
- function declineStep(root, io, positionals, values) {
185
+ async function declineStep(root, io, positionals, values) {
186
186
  if (positionals.length !== 2) return usage(io);
187
187
  const cfg = loadConfig(root);
188
188
  const env = io.env ?? process.env;
189
189
  const [id, finding] = positionals;
190
- const { url, created, state } = declineFinding(root, cfg, getHost(cfg, env, root), getTracker(cfg, env, root), id, finding, { worktree: values.worktree });
190
+ const { url, created, state } = await declineFinding(root, cfg, getHost(cfg, env, root), getTracker(cfg, env, root), id, finding, { worktree: values.worktree });
191
191
  const filed = state === 'closed' ? 'already filed, closed' : 'already filed';
192
192
  io.stdout(created ? `${url}\n` : `${url} (${filed})\n`);
193
193
  return 0;
@@ -240,7 +240,8 @@ async function run(args, io) {
240
240
  const handler = Object.hasOwn(HANDLERS, sub ?? '') ? HANDLERS[sub] : undefined;
241
241
  if (!handler) return usage(io);
242
242
  try {
243
- return handler(io.cwd, io, rest, values);
243
+ // Awaited, so a handler that rejects (decline on an asynchronous tracker) is caught below.
244
+ return await handler(io.cwd, io, rest, values);
244
245
  } catch (e) {
245
246
  if (e instanceof BuildError || e instanceof PrError) {
246
247
  io.stderr(`slicekit: ${e.message}\n`);
package/src/cli/index.js CHANGED
@@ -23,6 +23,7 @@ import { stageCommand } from './stage.js';
23
23
  import { shippedCommand } from './shipped.js';
24
24
  import { stateCommand } from './state.js';
25
25
  import { statusCommand } from './status.js';
26
+ import { syncCommand } from './sync.js';
26
27
  import { traceCommand } from './trace.js';
27
28
  import { uncoveredCommand } from './uncovered.js';
28
29
  import { updateCommand } from './update.js';
@@ -55,6 +56,7 @@ export const COMMANDS = {
55
56
  stage: stageCommand,
56
57
  state: stateCommand,
57
58
  status: statusCommand,
59
+ sync: syncCommand,
58
60
  trace: traceCommand,
59
61
  uncovered: uncoveredCommand,
60
62
  update: updateCommand,
@@ -104,5 +106,16 @@ export async function main(argv, io) {
104
106
  if (first !== undefined) io.stderr(`slicekit: unknown command '${first}'\n`);
105
107
  return 2;
106
108
  }
109
+ // `<command> --help` (P3/S-36, issue #77) answers like `--help`; one after `--` is the command's.
110
+ const end = rest.indexOf('--');
111
+ if ((end === -1 ? rest : rest.slice(0, end)).includes('--help')) {
112
+ io.stdout(commandUsage(command));
113
+ return 0;
114
+ }
107
115
  return command.run(rest, io);
108
116
  }
117
+
118
+ function commandUsage(command) {
119
+ const lines = command.usage.split('\n').map((line) => ` slicekit ${line.trim()}`);
120
+ return `usage:\n${lines.join('\n')}\n`;
121
+ }
package/src/cli/init.js CHANGED
@@ -5,21 +5,25 @@ import { CONFIG_PATH, ConfigError } from '../config.js';
5
5
  import { exists } from '../fs.js';
6
6
  import { git, GitError, isRepo } from '../git.js';
7
7
  import { checkCli } from '../hook-cli.js';
8
- import { init } from '../init.js';
8
+ import { GitHostError } from '../adapters/githost/errors.js';
9
+ import { init, knownDefaultBranch, protect } from '../init.js';
10
+ import { ACTIONS_PR_OFF } from '../check/rules/host-rules.js';
9
11
  import { kitVersion } from '../render/index.js';
10
12
 
11
13
  const USAGE =
12
- 'init --shape <backend|fullstack|data> [--name <n>] [--docs <dir>] [--cli <command>] [--test <cmd>] [--lint <cmd>] [--build <cmd>] [--e2e <cmd>]';
14
+ 'init --shape <backend|fullstack|data> [--name <n>] [--docs <dir>] [--cli <command>] [--default-branch <name>] [--test <cmd>] [--lint <cmd>] [--build <cmd>] [--e2e <cmd>] [--protect]';
13
15
 
14
16
  const OPTIONS = {
15
17
  shape: { type: 'string' },
16
18
  cli: { type: 'string' },
19
+ 'default-branch': { type: 'string' },
17
20
  name: { type: 'string' },
18
21
  docs: { type: 'string' },
19
22
  test: { type: 'string' },
20
23
  lint: { type: 'string' },
21
24
  build: { type: 'string' },
22
25
  e2e: { type: 'string' },
26
+ protect: { type: 'boolean' },
23
27
  };
24
28
 
25
29
  function samePath(a, b) {
@@ -66,12 +70,16 @@ async function run(args, io) {
66
70
  }
67
71
  let result;
68
72
  try {
73
+ // A new config needs a default branch the repository names, or the flag (issue #87).
74
+ const defaultBranch =
75
+ values['default-branch'] ?? (exists(path.join(root, CONFIG_PATH)) ? undefined : knownDefaultBranch(root));
69
76
  result = init(root, {
70
77
  name: values.name ?? path.basename(root),
71
78
  shape: values.shape,
72
79
  docsRoot: normaliseDocs(values.docs),
73
80
  commands,
74
81
  cli: values.cli,
82
+ defaultBranch,
75
83
  env: io.env ?? process.env,
76
84
  });
77
85
  } catch (e) {
@@ -90,6 +98,25 @@ async function run(args, io) {
90
98
  const unanswered = checkCli(result.cli, { version: kitVersion(), cwd: root });
91
99
  if (unanswered) io.stderr(`slicekit: ${unanswered}\n`);
92
100
  }
101
+ // Only with --protect does init change a host setting (REQ-3.14).
102
+ if (values.protect) {
103
+ let done;
104
+ try {
105
+ done = protect(root, { env: io.env ?? process.env });
106
+ } catch (e) {
107
+ if (!(e instanceof GitHostError || e instanceof ConfigError)) throw e;
108
+ io.stderr(`slicekit: init --protect: ${e.message}\n`);
109
+ return 1;
110
+ }
111
+ if (done.set.length === 0 && done.removed.length === 0) {
112
+ io.stdout(`host rules: ${done.branch} has every rule; nothing set\n`);
113
+ } else {
114
+ for (const line of done.set) io.stdout(`set ${done.branch}: ${line}\n`);
115
+ for (const check of done.removed) io.stdout(`removed ${done.branch}: required check ${check}, which is not gate or checks\n`);
116
+ io.stdout(`host rules: ruleset slicekit applied to ${done.branch}\n`);
117
+ }
118
+ if (done.actionsPullRequests === 'off') io.stdout(`not set: ${ACTIONS_PR_OFF}; init --protect does not change it\n`);
119
+ }
93
120
  return 0;
94
121
  }
95
122