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
@@ -7,7 +7,8 @@
7
7
  // under any root, or a `slicekit/subagent-*` marker, `slicekit/retry-*` retry state or `slicekit/agents-*`
8
8
  // started-agents record in a git directory (`.git` or `*.git`), or the `slicekit/interview.json` intake
9
9
  // session in one (a linked worktree's included)
10
- // — always; then, only while
10
+ // — always; (4) a path that matches a pattern of the root's `agents.denyPaths` (REQ-3.13) — always;
11
+ // then, only while
11
12
  // the file's own root has an active slice (a `slice/*` branch with a state file) in `tests-red` or
12
13
  // `building`: (1) a frozen test of that slice, unless `unfrozen` lists it; (2) a file under the docs root
13
14
  // that does not exist yet (only a create can name a missing file), except the runbook and anything in
@@ -28,7 +29,7 @@ import { parseSliceAddr } from '../ids.js';
28
29
  import { kitPaths } from '../paths.js';
29
30
  import { phaseOfDir } from '../slicefile.js';
30
31
  import { allow, deny } from './io.js';
31
- import { activeSlice, existingAncestor, fromGitBash, real, toPosix } from './paths.js';
32
+ import { activeSlice, denyPaths, existingAncestor, fromGitBash, matchesDeny, real, toPosix } from './paths.js';
32
33
 
33
34
  const WIN = process.platform === 'win32';
34
35
  const GUARDED_STATES = new Set(['tests-red', 'building']);
@@ -47,12 +48,18 @@ function relInside(root, abs) {
47
48
  // -> the canonical absolute path. Accepts absolute Windows paths with either slash, Git Bash `/c/...`
48
49
  // on win32, and relative paths (against cwd, else root). Throws on a win32 stream name.
49
50
  function absolute(filePath, root, cwd) {
51
+ return real(written(filePath, root, cwd));
52
+ }
53
+
54
+ // -> the absolute path as named, its symlinks not followed: the directory it is named from is
55
+ // canonical, the rest is the text (`data/link.txt` stays under data even when it points outside).
56
+ function written(filePath, root, cwd) {
50
57
  const p = fromGitBash(String(filePath).replace(/\\/g, '/'));
51
58
  if (WIN && p.replace(/^[A-Za-z]:/, '').includes(':')) {
52
59
  throw new Error(`${filePath}: a stream name is not a file path`);
53
60
  }
54
61
  const base = typeof cwd === 'string' && cwd !== '' ? path.resolve(root, fromGitBash(cwd.replace(/\\/g, '/'))) : root;
55
- return real(path.resolve(base, p));
62
+ return path.isAbsolute(p) ? path.resolve(p) : path.resolve(real(base), p);
56
63
  }
57
64
 
58
65
  // -> the POSIX path relative to root, or null when it is outside root.
@@ -126,8 +133,21 @@ function judge(filePath, input, hookRoot, hookCfg) {
126
133
 
127
134
  // (3)
128
135
  if (kitOwned(abs)) return deny(`${rel ?? toPosix(abs)} is written only by the slicekit CLI`);
136
+
137
+ // (4), the path as named: a symlink under a listed directory that points out of the repository
138
+ // resolves outside it, and its listed name must still count.
139
+ const lex = written(filePath, hookRoot, input.cwd);
140
+ for (const [r, c] of [[hookCanon, hookCfg], [root, cfg]]) {
141
+ const named = relInside(r, lex);
142
+ const hit = named === null ? null : matchesDeny(named, denyPaths(c));
143
+ if (hit !== null) return deny(`${named} matches agents.denyPaths pattern ${hit}; agents may not read or change it (REQ-3.13)`);
144
+ }
129
145
  if (rel === null) return allow();
130
146
 
147
+ // (4)
148
+ const pattern = matchesDeny(rel, denyPaths(cfg));
149
+ if (pattern !== null) return deny(`${rel} matches agents.denyPaths pattern ${pattern}; agents may not read or change it (REQ-3.13)`);
150
+
131
151
  const active = activeSlice(root, cfg);
132
152
  if (active?.error) throw new Error(active.error);
133
153
  if (active) {
package/src/init.js CHANGED
@@ -1,15 +1,17 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
- import { CONFIG_PATH, ConfigError, defaultConfig, loadConfig, validateConfig } from './config.js';
4
+ import { CONFIG_PATH, ConfigError, defaultConfig, isBranchName, loadConfig, validateConfig } from './config.js';
5
5
  import { exists, listFiles, readText, writeText } from './fs.js';
6
- import { currentBranch, git, GitError, hasCommits, isRepo } from './git.js';
6
+ import { currentBranch, detectDefaultBranch, git, GitError, hasCommits, isRepo } from './git.js';
7
7
  import { GITHOOKS, HOOKS_PATH, hooksPathValue, isInstalledHooksPath } from './githooks.js';
8
8
  import { probeCli } from './hook-cli.js';
9
9
  import { kitPaths } from './paths.js';
10
10
  import { kitVersion, renderAll } from './render/index.js';
11
11
  import { readSettings } from './render/settings.js';
12
12
  import { WORKFLOW_DRIFT, WORKFLOW_PATH, workflowState } from './workflow.js';
13
+ import { getHost } from './adapters/githost/index.js';
14
+ import { actionsPullRequestSetting, hasSyncJob, missingRules, requiredChecks } from './check/rules/host-rules.js';
13
15
 
14
16
  const TEMPLATES_DIR = fileURLToPath(new URL('../templates/docs/', import.meta.url));
15
17
  const GITHOOKS_DIR = fileURLToPath(new URL('../templates/githooks/', import.meta.url));
@@ -24,6 +26,8 @@ const IGNORE_RULES = [
24
26
  { rule: '!.slicekit/journal/', forms: new Set(['!.slicekit/journal/', '!/.slicekit/journal/']) },
25
27
  { rule: '!.slicekit/journal/*.log', forms: new Set(['!.slicekit/journal/*.log', '!/.slicekit/journal/*.log']) },
26
28
  { rule: '.slicekit/journal/*.lock', forms: new Set(['.slicekit/journal/*.lock', '/.slicekit/journal/*.lock']) },
29
+ // The heads log (REQ-3.8, D-89) is committed by the sync job; a `*.log` rule would make its `git add` refuse it.
30
+ { rule: '!.slicekit/journal-heads.log', forms: new Set(['!.slicekit/journal-heads.log', '!/.slicekit/journal-heads.log']) },
27
31
  // Slice worktrees (REQ-2.6 step 1) live under the root and are never part of the checkout.
28
32
  { rule: '.worktrees/', forms: new Set(['.worktrees/', '/.worktrees/', '.worktrees', '/.worktrees']) },
29
33
  // The README's path is an npm install (S-28): what it installs is never part of the project. A file
@@ -31,6 +35,65 @@ const IGNORE_RULES = [
31
35
  // `!node_modules/local-pkg/` would cancel it (P2/S-28 review H-1).
32
36
  { rule: 'node_modules/', forms: new Set(['node_modules/', '/node_modules/', 'node_modules', '/node_modules']), mentions: 'node_modules' },
33
37
  ];
38
+ // The rules that keep journal files and the heads log committed, re-appended in this order when git
39
+ // still ignores either path after init: a present rule counts only when a later rule does not override it.
40
+ const UNIGNORE_RULES = ['!.slicekit/journal/', '!.slicekit/journal/*.log', '.slicekit/journal/*.lock', '!.slicekit/journal-heads.log'];
41
+ const UNIGNORE_PROBES = ['.slicekit/journal-heads.log', '.slicekit/journal/main--00000000.log'];
42
+
43
+ function ignoredByGit(root, rel) {
44
+ try {
45
+ git(root, ['check-ignore', '--quiet', '--no-index', rel]);
46
+ return true;
47
+ } catch {
48
+ return false;
49
+ }
50
+ }
51
+
52
+ // The ignore-file line git matches for `rel`, as `<source>:<line>:<pattern>`.
53
+ function ignoringLine(root, rel) {
54
+ try {
55
+ return git(root, ['check-ignore', '-v', '--no-index', rel]).split('\t')[0];
56
+ } catch {
57
+ return null;
58
+ }
59
+ }
60
+
61
+ function endsWithUnignores(raw) {
62
+ const lines = raw.split(/\r?\n/).map((l) => l.trim());
63
+ while (lines.length > 0 && lines[lines.length - 1] === '') lines.pop();
64
+ const tail = lines.slice(-UNIGNORE_RULES.length);
65
+ return tail.length === UNIGNORE_RULES.length && tail.every((l, i) => l === UNIGNORE_RULES[i]);
66
+ }
67
+
68
+ // Appends the un-ignores again when git still ignores a probe and the file does not already end with
69
+ // them. When git still ignores a probe after that, as under an excluded parent such as `.slicekit/`,
70
+ // the note names the line that ignores it and nothing more is appended (P4/S-47 review H-1).
71
+ // Returns { appended, note }.
72
+ function reassertUnignores(root, file) {
73
+ const none = { appended: false, note: null };
74
+ if (!isRepo(root) || !exists(file)) return none;
75
+ const before = UNIGNORE_PROBES.filter((rel) => ignoredByGit(root, rel));
76
+ if (before.length === 0) return none;
77
+ const raw = fs.readFileSync(file, 'utf8');
78
+ let appended = false;
79
+ if (!endsWithUnignores(raw)) {
80
+ const eol = raw.includes('\r\n') ? '\r\n' : '\n';
81
+ const sep = raw === '' || raw.endsWith('\n') ? '' : eol;
82
+ fs.appendFileSync(file, `${sep}${UNIGNORE_RULES.map((rule) => `${rule}${eol}`).join('')}`);
83
+ appended = true;
84
+ }
85
+ const still = UNIGNORE_PROBES.filter((rel) => ignoredByGit(root, rel));
86
+ if (still.length === 0) return { appended, note: null };
87
+ // The copy just appended changed nothing git decides: take it back out, byte for byte.
88
+ if (appended && still.length === before.length) {
89
+ fs.writeFileSync(file, raw);
90
+ appended = false;
91
+ }
92
+ const lines = [...new Set(still.map((rel) => ignoringLine(root, rel)).filter(Boolean))];
93
+ const note = `${still.join(' and ')} still ignored by git (${lines.join(', ')}); the un-ignores at the end of .gitignore cannot override that rule, so init does not append them again`;
94
+ return { appended, note };
95
+ }
96
+
34
97
  // Hooks checked out with CRLF break sh (REQ-3.9).
35
98
  // Intake snapshots (S-10) are stored byte for byte, so git must not convert their line endings. The
36
99
  // pattern comes from kitPaths as S-10 builds it, so `./docs` and `docs` write the same line.
@@ -174,7 +237,7 @@ function setHooksPath(root, warnings) {
174
237
  // A new config takes cli from --cli, else from the probe (D-30); the probe's warning comes back with it.
175
238
  // One exception: a config with no cli key at all (an example project ships one, so that it names no
176
239
  // one's install) takes cli from --cli, else from the probe, and is written back with it.
177
- function resolveConfig(root, { name, shape, docsRoot, commands, cli, env }) {
240
+ function resolveConfig(root, { name, shape, docsRoot, commands, cli, defaultBranch, env }) {
178
241
  const file = path.join(root, CONFIG_PATH);
179
242
  if (exists(file)) {
180
243
  const raw = configWithoutCli(file);
@@ -184,7 +247,7 @@ function resolveConfig(root, { name, shape, docsRoot, commands, cli, env }) {
184
247
  raw.cli = probed.cli;
185
248
  }
186
249
  const cfg = raw ?? loadConfig(root);
187
- for (const [field, value] of [['shape', shape], ['docsRoot', docsRoot], ['cli', cli]]) {
250
+ for (const [field, value] of [['shape', shape], ['docsRoot', docsRoot], ['cli', cli], ['defaultBranch', defaultBranch]]) {
188
251
  if (value !== undefined && value !== cfg[field]) {
189
252
  throw new ConfigError([`config.json already sets ${field} = ${cfg[field]}; remove the flag or edit the config`]);
190
253
  }
@@ -202,12 +265,53 @@ function resolveConfig(root, { name, shape, docsRoot, commands, cli, env }) {
202
265
  docsRoot: docsRoot ?? 'docs',
203
266
  commands,
204
267
  cli: probed.cli,
268
+ defaultBranch: defaultBranch ?? detectDefaultBranch(root, { accept: isBranchName }),
205
269
  });
206
270
  const errors = validateConfig(cfg);
207
271
  if (errors.length > 0) throw new ConfigError(errors);
208
272
  return { cfg, cliWarning: probed.warning, cliFilled: false };
209
273
  }
210
274
 
275
+ // The default branch a new config names, when the repository tells it: origin names it, it is a
276
+ // local branch, or an empty repository's HEAD is on it. Otherwise detectDefaultBranch's `main` is a
277
+ // guess, and a guess on a feature branch or a detached HEAD would protect the wrong branch, so the
278
+ // init command refuses and asks for the name (issue #87). Outside a repository the guess is `main`.
279
+ // It throws a ConfigError; init() itself still takes detectDefaultBranch's answer when given none.
280
+ // The refusal names init.defaultBranch as it is: absent, or set to a branch this repository lacks.
281
+ function noDefaultBranch(configured) {
282
+ const setting = configured === '' ? 'no init.defaultBranch' : `init.defaultBranch names ${configured}, which is not a branch here`;
283
+ return `cannot tell the default branch: there is no origin, ${setting}, and HEAD is not on main or master; run init again with --default-branch <name>`;
284
+ }
285
+ export function knownDefaultBranch(root) {
286
+ const branch = detectDefaultBranch(root, { accept: isBranchName });
287
+ if (!isRepo(root)) return branch;
288
+ const has = (ref) => {
289
+ try {
290
+ git(root, ['rev-parse', '--verify', '-q', ref]);
291
+ return true;
292
+ } catch (e) {
293
+ if (e instanceof GitError) return false;
294
+ throw e;
295
+ }
296
+ };
297
+ if (has(`refs/heads/${branch}`) || has(`refs/remotes/origin/${branch}`)) return branch;
298
+ let origin = '';
299
+ try {
300
+ origin = git(root, ['symbolic-ref', '-q', 'refs/remotes/origin/HEAD']);
301
+ } catch (e) {
302
+ if (!(e instanceof GitError)) throw e;
303
+ }
304
+ if (origin === `refs/remotes/origin/${branch}`) return branch;
305
+ if (!hasCommits(root) && currentBranch(root) === branch) return branch;
306
+ let configured = '';
307
+ try {
308
+ configured = git(root, ['config', '--get', 'init.defaultBranch']);
309
+ } catch (e) {
310
+ if (!(e instanceof GitError)) throw e;
311
+ }
312
+ throw new ConfigError([noDefaultBranch(configured)]);
313
+ }
314
+
211
315
  // The parsed config when it is a JSON object with no cli key; null otherwise (loadConfig then reads,
212
316
  // and reports, the file as it is).
213
317
  function configWithoutCli(file) {
@@ -227,8 +331,30 @@ export function bareCliWarning(cli) {
227
331
  return `cli is "${cli}", a bare command, and CI has no global install, so ${WORKFLOW_PATH} cannot run it; set cli in .slicekit/config.json to a repository path or add an install step`;
228
332
  }
229
333
 
230
- export function init(root, { name, shape, docsRoot, commands = {}, cli, env = process.env }) {
231
- const { cfg, cliWarning, cliFilled } = resolveConfig(root, { name, shape, docsRoot, commands, cli, env });
334
+ // `slicekit init --protect` (REQ-3.14, D-77, D-88): the rules of REQ-3.14 the default branch lacks,
335
+ // set as the one repository ruleset named slicekit. A human with admin rights runs it from their own
336
+ // terminal; this is the kit's one call of a host write of a rule. A required check of the slicekit
337
+ // ruleset that is not gate or checks is taken out of that ruleset; a check
338
+ // another ruleset requires is the team's and stays. Returns the branch, what each rule set reads as,
339
+ // and the checks removed: both empty when nothing changed. A GitHostError (no token, no admin rights)
340
+ // is the caller's to print. `actionsPullRequests` is 'off' when the workflow has a sync job and the
341
+ // Actions setting it needs is off: init --protect never changes that setting, a human does (REQ-3.11).
342
+ export function protect(root, { env = process.env } = {}) {
343
+ const cfg = loadConfig(root);
344
+ const branch = cfg.defaultBranch;
345
+ const host = getHost(cfg, env, root);
346
+ const rules = host.readBranchRules(branch);
347
+ const missing = missingRules(cfg, rules, host.readCodeowners());
348
+ const kitChecks = requiredChecks(cfg);
349
+ const unknown = (rules.requiredChecks ?? []).filter((c) => !kitChecks.includes(c));
350
+ const actionsPullRequests = hasSyncJob(cfg) ? actionsPullRequestSetting(cfg, env, root) : 'unknown';
351
+ if (missing.length === 0 && unknown.length === 0) return { branch, set: [], removed: [], actionsPullRequests };
352
+ const done = host.applyBranchRules(branch, { ...Object.fromEntries(missing.map((m) => [m.key, m.value])), kitChecks });
353
+ return { branch, set: missing.map((m) => m.set), removed: done?.removedChecks ?? [], actionsPullRequests };
354
+ }
355
+
356
+ export function init(root, { name, shape, docsRoot, commands = {}, cli, defaultBranch, env = process.env }) {
357
+ const { cfg, cliWarning, cliFilled } = resolveConfig(root, { name, shape, docsRoot, commands, cli, defaultBranch, env });
232
358
  readSettings(root); // a corrupt .claude/settings.json stops init before anything is written
233
359
 
234
360
  const paths = kitPaths(root, cfg);
@@ -243,12 +369,15 @@ export function init(root, { name, shape, docsRoot, commands = {}, cli, env = pr
243
369
  lists.created.push(rel(abs));
244
370
  }
245
371
  }
246
- lists[ensureLines(paths.gitignore, IGNORE_RULES)].push(rel(paths.gitignore));
372
+ const ignoreState = ensureLines(paths.gitignore, IGNORE_RULES);
373
+ const unignores = reassertUnignores(root, paths.gitignore);
374
+ lists[unignores.appended && ignoreState === 'skipped' ? 'updated' : ignoreState].push(rel(paths.gitignore));
247
375
  const attributes = path.join(root, '.gitattributes');
248
376
  lists[ensureLines(attributes, attributeRules(root, cfg))].push(rel(attributes));
249
377
 
250
378
  const repo = isRepo(root);
251
379
  const warnings = repo ? [] : [NOT_A_REPO];
380
+ if (unignores.note) warnings.push(unignores.note);
252
381
  if (cliWarning) warnings.push(cliWarning);
253
382
  const hooks = installHooks(paths, rel, lists, warnings);
254
383
  if (repo) {
package/src/journal.js CHANGED
@@ -11,6 +11,15 @@
11
11
  // What is protected: a mid-chain edit is caught by the chain (verifyJournal); shortening or removing a
12
12
  // committed file is caught against the default branch (appendOnlyProblems); lines not yet committed are
13
13
  // not protected. Nothing here repairs a journal.
14
+ //
15
+ // The chain carries no key: anyone who rewrites a file can recompute every hash, so the chain shows an
16
+ // edit only against what the default branch already holds. The `actor` field is what the session
17
+ // reports and proves nothing about who ran it. What binds a journal to a person is the commit that
18
+ // carries it (D-71): under `check --ci` every commit of the pull request that changes a journal file
19
+ // must be signed and verified by the git host (C-1 getCommit). The sync pull request records each
20
+ // merged journal's last hash in `.slicekit/journal-heads.log` (headsLines), with the CI run that wrote
21
+ // it, and `check --ci` recomputes every line that file gains from git and C-1 getRun rather than trust
22
+ // its writer (D-89). The kit manages no keys.
14
23
  import { execFileSync } from 'node:child_process';
15
24
  import crypto from 'node:crypto';
16
25
  import fs from 'node:fs';
@@ -215,6 +224,21 @@ function resolves(root, ref) {
215
224
  }
216
225
  }
217
226
 
227
+ // The merge base of `tip` and `against` (default: the default branch, local, else origin's), as
228
+ // { ref, base }, or null when neither ref nor a merge base exists.
229
+ export function mergeBaseWith(root, cfg, { against, tip = 'HEAD' } = {}) {
230
+ const def = cfg?.defaultBranch ?? 'main';
231
+ const candidates = against != null ? [against] : [def, `origin/${def}`];
232
+ const ref = candidates.find((r) => resolves(root, r));
233
+ if (ref === undefined) return null;
234
+ try {
235
+ return { ref, base: git(root, ['merge-base', assertRef(tip), ref]) };
236
+ } catch (e) {
237
+ if (e instanceof GitError) return null;
238
+ throw e;
239
+ }
240
+ }
241
+
218
242
  // Append-only against git: every journal file at the merge base of HEAD and `against` (default: the
219
243
  // default branch, local, else origin's) must still exist in the working tree and start with the base
220
244
  // copy's bytes (CRLF read as LF). [] outside a repo. When the ref or the merge base does not exist: []
@@ -224,18 +248,9 @@ function resolves(root, ref) {
224
248
  export function appendOnlyProblems(root, cfg, { against, ci = false } = {}) {
225
249
  if (!isRepo(root)) return [];
226
250
  const relDir = toPosix(path.relative(root, dirOf(root, cfg)));
227
- const noBase = () => (ci ? [{ file: relDir, line: 0, message: NO_BASE }] : []);
228
- const def = cfg?.defaultBranch ?? 'main';
229
- const candidates = against != null ? [against] : [def, `origin/${def}`];
230
- const ref = candidates.find((r) => resolves(root, r));
231
- if (ref === undefined) return noBase();
232
- let base;
233
- try {
234
- base = git(root, ['merge-base', 'HEAD', ref]);
235
- } catch (e) {
236
- if (e instanceof GitError) return noBase();
237
- throw e;
238
- }
251
+ const found = mergeBaseWith(root, cfg, { against });
252
+ if (found === null) return ci ? [{ file: relDir, line: 0, message: NO_BASE }] : [];
253
+ const { ref, base } = found;
239
254
  // --full-name lists paths from the top level, as `git show <base>:<path>` takes them; the prefix
240
255
  // (root's place below the top level) maps each back to root.
241
256
  const prefix = git(root, ['rev-parse', '--show-prefix']);
@@ -324,3 +339,129 @@ export function appendJournal(root, fields, { branch = journalBranch(root), now
324
339
  return line;
325
340
  }, budgetMs);
326
341
  }
342
+
343
+ // ---- signed commits and the journal-heads file (03 REQ-3.8, D-71, D-89) ----
344
+
345
+ export const HEADS_FILE = 'journal-heads.log';
346
+ export const SIGNED_MESSAGE = 'journal commits must be signed';
347
+ const HEADS_LINE = /^(\S+) hash=(\S+) merge=([0-9a-f]{40}) run=(\S+) workflow=(\S+) actor=(\S+)$/;
348
+
349
+ // Where the sync pull request records each merged journal's last hash: `.slicekit/journal-heads.log`.
350
+ export const headsPath = (root, cfg) => path.join(kitPaths(root, cfg ?? { docsRoot: 'docs' }).kit, HEADS_FILE);
351
+
352
+ // One line of the journal-heads file (no newline):
353
+ // <journal file> hash=<its last hash> merge=<merge sha> run=<run id> workflow=<name> actor=<login>
354
+ // Every value goes through the journal's own masking, so none carries a space or `=`.
355
+ export function headsLine({ file, hash, merge, run, workflow, actor }) {
356
+ return `${value(file)} hash=${value(hash)} merge=${value(merge)} run=${value(run)} workflow=${value(workflow)} actor=${value(actor)}`;
357
+ }
358
+
359
+ // -> {file, hash, merge, run, workflow, actor}, or null.
360
+ export function parseHeadsLine(text) {
361
+ const m = HEADS_LINE.exec(String(text).replace(/\r$/, ''));
362
+ if (!m) return null;
363
+ const [, file, hash, merge, run, workflow, actor] = m;
364
+ return { file, hash, merge, run, workflow, actor };
365
+ }
366
+
367
+ const gitOr = (root, args, fallback) => {
368
+ try {
369
+ return git(root, args);
370
+ } catch (e) {
371
+ if (e instanceof GitError) return fallback;
372
+ throw e;
373
+ }
374
+ };
375
+
376
+ // The bytes of `rel` (relative to root) at commit `rev` (CRLF read as LF), or null when it has none.
377
+ function bytesAt(root, rev, rel) {
378
+ try {
379
+ return lf(gitBytes(root, ['show', `${rev}:./${rel}`]));
380
+ } catch (e) {
381
+ if (e instanceof GitError) return null;
382
+ throw e;
383
+ }
384
+ }
385
+
386
+ // The journal files a heads line is owed for at merge commit `merge` (REQ-3.8), sorted by file, each
387
+ // as {file, hash} with its last hash at the merge ('-' when it has none). A file is owed a line when its
388
+ // last hash at the merge differs from the last hash the heads log `recorded` gives for it. A file the log
389
+ // does not name is owed one when its last hash differs from its last hash at the newest merge the log
390
+ // names (absent there counts as different). While the log names no merge yet, a merge commit with two
391
+ // or more parents compares against its first parent, the default branch before the merge; any other
392
+ // commit (a fast-forward, rebase or squash push, or a root commit) owes a line for every journal file it
393
+ // holds, because git alone cannot say where its push began and check --ci must compute the same set.
394
+ // So a push of several commits and a merge whose sync pull request was superseded before it merged both
395
+ // get their lines from the next sync. `recorded`
396
+ // is the heads log text the lines will be appended to; it defaults to the log at the merge commit.
397
+ // Computed from git alone. Throws GitError when `merge` is not a commit of this clone.
398
+ export function headsFiles(root, cfg, merge, { recorded } = {}) {
399
+ const sha = git(root, ['rev-parse', '--verify', '--quiet', '--end-of-options', `${assertRef(merge)}^{commit}`]);
400
+ const relDir = toPosix(path.relative(root, dirOf(root, cfg)));
401
+ const log = recorded ?? (bytesAt(root, sha, toPosix(path.relative(root, headsPath(root, cfg)))) ?? Buffer.alloc(0)).toString('utf8');
402
+ const named = new Map();
403
+ let lastMerge = null;
404
+ for (const text of log.split('\n')) {
405
+ const p = parseHeadsLine(text);
406
+ if (p === null) continue;
407
+ named.set(p.file, p.hash);
408
+ lastMerge = p.merge;
409
+ }
410
+ const base = lastMerge !== null
411
+ ? gitOr(root, ['rev-parse', '--verify', '--quiet', '--end-of-options', `${lastMerge}^{commit}`], '')
412
+ : gitOr(root, ['rev-parse', '--verify', '--quiet', '--end-of-options', `${sha}^2`], '') === ''
413
+ ? ''
414
+ : gitOr(root, ['rev-parse', '--verify', '--quiet', '--end-of-options', `${sha}^1`], '');
415
+ const inDir = (listed) => (listed === '' ? [] : listed.split('\n'))
416
+ .map((f) => f.replace(/\r$/, ''))
417
+ .filter((f) => f.startsWith(`${relDir}/`) && f.endsWith('.log') && !f.slice(relDir.length + 1).includes('/'));
418
+ const lastHashAt = (rev, file) => {
419
+ const bytes = bytesAt(root, rev, file);
420
+ if (bytes === null) return null;
421
+ const text = bytes.toString('utf8');
422
+ const last = text.endsWith('\n') ? lastLine(text) : null;
423
+ return (last === null ? null : parseLine(last)?.hash) ?? '-';
424
+ };
425
+ const out = [];
426
+ for (const file of inDir(git(root, ['ls-tree', '-r', '--name-only', sha, '--', `${relDir}/`])).sort()) {
427
+ const hash = lastHashAt(sha, file);
428
+ const was = named.has(file) ? named.get(file) : base === '' ? null : lastHashAt(base, file);
429
+ if (hash !== was) out.push({ file, hash });
430
+ }
431
+ return out;
432
+ }
433
+
434
+ // The lines the sync job adds to the journal-heads file for merge commit `merge` (REQ-3.8): one per
435
+ // file headsFiles names, with the run's id, workflow and actor. The sync job writes with it (`slicekit
436
+ // journal heads`, values from the run's environment, against the log at the merge), and `check --ci`
437
+ // recomputes with it (values from C-1 getRun, against the log at the merge base), so the two cannot
438
+ // drift. Throws GitError when `merge` is not a commit of this clone.
439
+ export function headsLines(root, cfg, merge, { run, workflow, actor }, { recorded } = {}) {
440
+ const sha = git(root, ['rev-parse', '--verify', '--quiet', '--end-of-options', `${assertRef(merge)}^{commit}`]);
441
+ return headsFiles(root, cfg, sha, { recorded }).map(({ file, hash }) => headsLine({ file, hash, merge: sha, run, workflow, actor }));
442
+ }
443
+
444
+ // Appends lines to the journal-heads file and returns them. The file is written only here.
445
+ export function appendHeads(root, cfg, lines) {
446
+ if (lines.length === 0) return [];
447
+ const file = headsPath(root, cfg);
448
+ fs.mkdirSync(path.dirname(file), { recursive: true });
449
+ const text = readIfAny(file);
450
+ const sep = text !== '' && !text.endsWith('\n') ? '\n' : '';
451
+ fs.appendFileSync(file, `${sep}${lines.join('\n')}\n`);
452
+ return lines;
453
+ }
454
+
455
+ // The commits after `base` up to `tip` that change a file under .slicekit/journal/, newest first.
456
+ // The journal-heads file sits beside that directory, not in it, so a sync commit is not one of them.
457
+ export function journalCommits(root, cfg, base, tip) {
458
+ const relDir = toPosix(path.relative(root, dirOf(root, cfg)));
459
+ const out = git(root, ['log', '--format=%H', `${assertRef(base)}..${assertRef(tip)}`, '--', `${relDir}/`]);
460
+ return out === '' ? [] : out.split('\n').map((s) => s.trim()).filter(Boolean);
461
+ }
462
+
463
+ // The journal-heads file at `base` and at `tip`: { rel, was, now } (bytes, LF; empty when absent).
464
+ export function headsAt(root, cfg, base, tip) {
465
+ const rel = toPosix(path.relative(root, headsPath(root, cfg)));
466
+ return { rel, was: bytesAt(root, base, rel) ?? Buffer.alloc(0), now: bytesAt(root, tip, rel) ?? Buffer.alloc(0) };
467
+ }
package/src/pr.js CHANGED
@@ -19,7 +19,7 @@ export class PrError extends Error {
19
19
  }
20
20
 
21
21
  // A slice pull request opens as a draft (the build loop marks it ready once review clears it); a
22
- // `[spec] ` or `[plan] ` pull request opens ready for review. `draft: true` forces a draft.
22
+ // `[spec] `, `[plan] ` or `[sync] ` pull request opens ready for review. `draft: true` forces a draft.
23
23
  export const opensAsDraft = (title) => !EXEMPT_TITLE.test(title);
24
24
 
25
25
  const NOT_INSIDE = '--paths must name files or folders inside the repository, not the root';
package/src/prbody.js CHANGED
@@ -3,7 +3,7 @@
3
3
  // A section is `**<name>:**` at the start of a line (indent allowed); its text is what follows the
4
4
  // colon on that line, or the next non-blank line when that is not itself a required section or a
5
5
  // heading. Anything inside a fenced code block (CommonMark fences) or an HTML comment is never a
6
- // section or a heading, and a comment is never section text. A `[spec] ` / `[plan] ` title needs
6
+ // section or a heading, and a comment is never section text. A `[spec] ` / `[plan] ` / `[sync] ` title needs
7
7
  // only the first three sections and no slice heading; a title with no slice id leaves the heading to
8
8
  // ci-title. The configured filler list (style.banned) is matched over the body, one finding per
9
9
  // phrase (REQ-3.10).