slicekit 0.2.1 → 0.3.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 (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 +2 -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 +72 -0
  28. package/src/git.js +30 -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 +134 -6
  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,196 @@
1
+ // The version a sync pull request sets (05 REQ-5.5, D-90, P5/S-48). With `release.auto` true in
2
+ // config, the sync step after a merge sets package.json's version and adds CHANGELOG.md's newest
3
+ // section for it: the patch number up by one for the slice merges the sync records, or the minor
4
+ // number up by one (patch 0) when a merge it records leaves every slice of that slice's phase
5
+ // `merged` or `released`. One version per sync, however many merges it records; its section names
6
+ // every one of them. A merge that changes package.json's version itself, with that version's
7
+ // CHANGELOG.md section (the release slice's own, or a sync pull request's), a merge that records no
8
+ // slice merge (a [plan], [sync] or [release] merge), and a config without `release.auto` set none. The version counts from package.json at the merge commit, never from one
9
+ // an open sync pull request proposes. The rendered files follow the version (`update --yes`), as
10
+ // `build render` would commit them.
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+ import { fileURLToPath } from 'node:url';
14
+ import { ConfigError, releaseAutoError } from './config.js';
15
+ import { GitError, git } from './git.js';
16
+ import { readText, writeText } from './fs.js';
17
+ import { RENDERED, SETTINGS, kitVersion } from './render/index.js';
18
+ import { entriesForShape } from './render/manifest.js';
19
+ import { applyUpdate, planUpdate } from './render/update.js';
20
+ import { findSliceFiles, parsePhaseFile, parseSliceFile } from './slicefile.js';
21
+ import { readSlice } from './state/index.js';
22
+
23
+ export const PACKAGE = 'package.json';
24
+ export const CHANGELOG = 'CHANGELOG.md';
25
+ const DONE = ['merged', 'released'];
26
+ const SEMVER = /^(\d+)\.(\d+)\.(\d+)$/;
27
+
28
+ // The kit's own checkout: in it the rendered files name the version the sync sets.
29
+ const KIT_ROOT = fileURLToPath(new URL('../', import.meta.url));
30
+ const real = (p) => {
31
+ try {
32
+ return fs.realpathSync.native(p);
33
+ } catch {
34
+ return path.resolve(p);
35
+ }
36
+ };
37
+ export const isKitRoot = (root) => real(root).toLowerCase() === real(KIT_ROOT).toLowerCase();
38
+
39
+ export class ReleaseError extends Error {
40
+ constructor(message) {
41
+ super(message);
42
+ this.name = 'ReleaseError';
43
+ }
44
+ }
45
+
46
+ // The next version: null with no merge; else the minor up (patch 0) when a phase completed, else
47
+ // the patch up. `current` must be MAJOR.MINOR.PATCH.
48
+ export function nextVersion({ current, merges, phaseComplete }) {
49
+ if (!Array.isArray(merges) || merges.length === 0) return null;
50
+ const m = SEMVER.exec(String(current));
51
+ if (!m) throw new ReleaseError(`package.json's version '${current}' is not MAJOR.MINOR.PATCH`);
52
+ const [maj, min, pat] = m.slice(1).map(Number);
53
+ return phaseComplete ? `${maj}.${min + 1}.0` : `${maj}.${min}.${pat + 1}`;
54
+ }
55
+
56
+ const sliceLine = (s) => `- ${s.id} ${s.name}${Number.isInteger(s.pr) ? ` (#${s.pr})` : ''}`;
57
+
58
+ // CHANGELOG.md's section for `version`: each phase it completes with all of that phase's slices,
59
+ // then every other slice merge the sync records. merges and slices: [{ id, name, pr }];
60
+ // phases: [{ id, name, slices }].
61
+ export function changelogSection({ version, merges, phases = [] }) {
62
+ const out = [`## ${version}`, ''];
63
+ const named = new Set();
64
+ for (const p of phases) {
65
+ out.push(`Phase ${p.id.replace(/^P/, '')}${p.name ? `: ${p.name}` : ''}.`, '');
66
+ for (const s of p.slices) {
67
+ out.push(sliceLine(s));
68
+ named.add(s.id);
69
+ }
70
+ out.push('');
71
+ }
72
+ const rest = merges.filter((s) => !named.has(s.id));
73
+ if (rest.length > 0) {
74
+ for (const s of rest) out.push(sliceLine(s));
75
+ out.push('');
76
+ }
77
+ return `${out.join('\n').trimEnd()}\n`;
78
+ }
79
+
80
+ // The changelog with `section` on top, under the file's intro (everything before the first `## `).
81
+ export function prependSection(text, section) {
82
+ if (text === null || text === '') return `# Changelog\n\n${section}`;
83
+ const lines = text.split('\n');
84
+ const at = lines.findIndex((l) => /^## /.test(l));
85
+ if (at < 0) return `${text.replace(/\n*$/, '\n\n')}${section}`;
86
+ return [...lines.slice(0, at), ...`${section}\n`.split('\n').slice(0, -1), ...lines.slice(at)].join('\n');
87
+ }
88
+
89
+ // package.json's text with only its top-level version field changed.
90
+ export function setVersion(text, version) {
91
+ const next = text.replace(/("version"\s*:\s*)"[^"]*"/, `$1"${version}"`);
92
+ let parsed;
93
+ try {
94
+ parsed = JSON.parse(next);
95
+ } catch {
96
+ throw new ReleaseError('package.json is not valid JSON');
97
+ }
98
+ if (parsed.version !== version) throw new ReleaseError('package.json has no top-level "version" field to set');
99
+ return next;
100
+ }
101
+
102
+ // The version field of package.json at `rev`, or null when the commit holds none.
103
+ function versionAt(root, rev) {
104
+ let text;
105
+ try {
106
+ text = git(root, ['show', `${rev}:${PACKAGE}`]);
107
+ } catch (e) {
108
+ if (e instanceof GitError) return null;
109
+ throw e;
110
+ }
111
+ try {
112
+ const v = JSON.parse(text).version;
113
+ return typeof v === 'string' ? v : null;
114
+ } catch {
115
+ return null;
116
+ }
117
+ }
118
+
119
+ // The versions CHANGELOG.md's `## ` headings name at `rev`, newest first; [] when it holds none.
120
+ function changelogVersionsAt(root, rev) {
121
+ let text;
122
+ try {
123
+ text = git(root, ['show', `${rev}:${CHANGELOG}`]);
124
+ } catch (e) {
125
+ if (e instanceof GitError) return [];
126
+ throw e;
127
+ }
128
+ return text.split('\n').filter((l) => /^## /.test(l)).map((l) => l.replace(/^## /, '').split(/\s/)[0]);
129
+ }
130
+
131
+ // The paths the release step may write: package.json, CHANGELOG.md and the files `update` renders.
132
+ export function releasePaths(cfg) {
133
+ return [PACKAGE, CHANGELOG, ...new Set([...entriesForShape(cfg.shape).map((e) => e.dest), SETTINGS]), RENDERED];
134
+ }
135
+ export const isReleasePath = (cfg) => {
136
+ const dests = new Set(releasePaths(cfg));
137
+ return (f) => dests.has(f) || f.startsWith(`${RENDERED}/`);
138
+ };
139
+
140
+ function phaseName(phaseDir, phaseId) {
141
+ for (const f of fs.readdirSync(phaseDir).filter((n) => n.endsWith('.md') && !/^S-\d+/.test(n)).sort()) {
142
+ const p = parsePhaseFile(readText(path.join(phaseDir, f)));
143
+ if (p?.id === phaseId) return p.name;
144
+ }
145
+ return null;
146
+ }
147
+
148
+ // What the sync after `merge` sets, given the slice changes syncFromHost made: { version, section }
149
+ // or null (see the header). Reads the slice states on disk, so it runs after the sync.
150
+ export function releaseFor(root, cfg, changes, { merge = 'HEAD' } = {}) {
151
+ const bad = releaseAutoError(cfg);
152
+ if (bad) throw new ConfigError([bad]);
153
+ if (cfg.release?.auto !== true) return null;
154
+ if (!Array.isArray(changes) || changes.length === 0) return null;
155
+ if (!fs.existsSync(path.join(root, PACKAGE))) return null;
156
+ const current = versionAt(root, merge);
157
+ if (current === null) return null;
158
+ // A first commit, or a merge that sets the version itself: no version from the sync. A merge sets
159
+ // it itself when it changes package.json's version and CHANGELOG.md at the merge already holds
160
+ // that version's section (the release slice's merge, or a sync pull request's).
161
+ const before = versionAt(root, `${merge}^1`);
162
+ if (before === null) return null;
163
+ if (before !== current && changelogVersionsAt(root, merge).includes(current)) return null;
164
+ const all = findSliceFiles(root, cfg).map((f) => {
165
+ const s = parseSliceFile(readText(f.path), f.path);
166
+ const st = readSlice(root, cfg, s.id);
167
+ return { id: s.id, name: s.name, phase: f.phaseId, phaseDir: f.phaseDir, state: st.state, pr: st.pr?.number ?? null };
168
+ });
169
+ const byId = new Map(all.map((s) => [s.id, s]));
170
+ const merges = changes.map((c) => ({ id: c.id, name: byId.get(c.id)?.name ?? '', pr: c.pr, phase: byId.get(c.id)?.phase }));
171
+ const phases = [];
172
+ for (const id of [...new Set(merges.map((m) => m.phase).filter(Boolean))]) {
173
+ const slices = all.filter((s) => s.phase === id);
174
+ if (slices.length > 0 && slices.every((s) => DONE.includes(s.state))) {
175
+ phases.push({ id, name: phaseName(slices[0].phaseDir, id), slices });
176
+ }
177
+ }
178
+ const version = nextVersion({ current, merges, phaseComplete: phases.length > 0 });
179
+ if (version === null) return null;
180
+ return { version, section: changelogSection({ version, merges, phases }) };
181
+ }
182
+
183
+ // Writes what releaseFor computed: package.json's version, the changelog section, and the render at
184
+ // that version (the kit's own checkout) or at the running kit's version (any other). `isKit` says
185
+ // which; it defaults to whether `root` is the kit's checkout. Returns the release or null.
186
+ export function applyRelease(root, cfg, changes, { merge = 'HEAD', isKit = isKitRoot(root) } = {}) {
187
+ const release = releaseFor(root, cfg, changes, { merge });
188
+ if (release === null) return null;
189
+ const pkg = path.join(root, PACKAGE);
190
+ writeText(pkg, setVersion(readText(pkg), release.version));
191
+ const log = path.join(root, CHANGELOG);
192
+ writeText(log, prependSection(fs.existsSync(log) ? readText(log) : null, release.section));
193
+ const version = isKit ? release.version : kitVersion();
194
+ applyUpdate(root, cfg, planUpdate(root, cfg, { version }), { version });
195
+ return release;
196
+ }
@@ -62,7 +62,26 @@ export function ourEntries(settings, prefixes) {
62
62
  return out;
63
63
  }
64
64
 
65
- export function mergeSettings(existing, hooks, { version, cli } = {}) {
65
+ // REQ-3.13: each agents.denyPaths pattern as a Read and an Edit rule of permissions.deny. The rules
66
+ // slicekit wrote last time are recorded in `_slicekit.deny` and replaced; every other deny entry is
67
+ // the team's and stays, and a rule the team already holds is left the team's. -> {permissions, deny}:
68
+ // the permissions object to write (undefined when there is none) and the rules slicekit now owns.
69
+ function mergeDeny(base, denyPaths) {
70
+ const permissions = base.permissions && typeof base.permissions === 'object' && !Array.isArray(base.permissions) ? base.permissions : undefined;
71
+ const current = Array.isArray(permissions?.deny) ? permissions.deny : [];
72
+ const recorded = Array.isArray(base._slicekit?.deny) ? base._slicekit.deny : [];
73
+ const kept = current.filter((e) => !recorded.includes(e));
74
+ const rules = denyPaths.flatMap((p) => [`Read(${p})`, `Edit(${p})`]);
75
+ const ours = [...new Set(rules)].filter((e) => !kept.includes(e));
76
+ const deny = [...kept, ...ours];
77
+ if (deny.length === current.length && deny.every((e, i) => e === current[i])) return { permissions: base.permissions, deny: ours };
78
+ const next = { ...permissions };
79
+ if (deny.length > 0) next.deny = deny;
80
+ else delete next.deny;
81
+ return { permissions: Object.keys(next).length > 0 ? next : undefined, deny: ours };
82
+ }
83
+
84
+ export function mergeSettings(existing, hooks, { version, cli, denyPaths = [] } = {}) {
66
85
  const base = existing && typeof existing === 'object' && !Array.isArray(existing) ? existing : {};
67
86
  const prefixes = ourPrefixes(base, cli);
68
87
  const merged = { ...(base.hooks ?? {}) };
@@ -72,5 +91,10 @@ export function mergeSettings(existing, hooks, { version, cli } = {}) {
72
91
  }
73
92
  const meta = { managed: true, version };
74
93
  if (cli) meta.cli = cli;
75
- return { ...base, hooks: merged, _slicekit: meta };
94
+ const { permissions, deny } = mergeDeny(base, Array.isArray(denyPaths) ? denyPaths : []);
95
+ if (deny.length > 0) meta.deny = deny;
96
+ const out = { ...base, hooks: merged, _slicekit: meta };
97
+ if (permissions === undefined) delete out.permissions;
98
+ else out.permissions = permissions;
99
+ return out;
76
100
  }
@@ -72,7 +72,7 @@ function fileItem(root, cfg, entry, opts) {
72
72
  function settingsItem(root, cfg, { version, templates }) {
73
73
  const hooks = loadHooks(templates, varsFor(cfg, version));
74
74
  const existing = readSettings(root);
75
- const next = `${JSON.stringify(mergeSettings(existing, hooks, { version, cli: cfg.cli }), null, 2)}\n`;
75
+ const next = `${JSON.stringify(mergeSettings(existing, hooks, { version, cli: cfg.cli, denyPaths: cfg.agents?.denyPaths }), null, 2)}\n`;
76
76
  const file = path.join(root, SETTINGS);
77
77
  const current = exists(file) ? readText(file) : null;
78
78
  const refText = `${JSON.stringify({ hooks }, null, 2)}\n`;
@@ -209,6 +209,17 @@ export function unfreeze(root, cfg, id, file, extra = {}, { to } = {}) {
209
209
  });
210
210
  }
211
211
 
212
+ // One history entry that leaves the state where it is (build amend of the slice file alone), under
213
+ // the slice lock, re-reading the file inside it so a concurrent `slicekit state set` is never undone.
214
+ export function appendHistory(root, cfg, id, evidence) {
215
+ return withLock(root, cfg, id, () => {
216
+ const current = readSlice(root, cfg, id);
217
+ const added = entry(current.state, current.state, 'cli', evidence);
218
+ writeSlice(root, cfg, { ...current, history: [...current.history, added] });
219
+ return added;
220
+ });
221
+ }
222
+
212
223
  // Replaces only the slice's handoff, under the slice lock, re-reading the file inside it so a
213
224
  // concurrent `slicekit state set` is never undone. State and history are left as they are. A slice with
214
225
  // no state file yet is skipped (returns false): the handoff never creates one. Throws LockError when
package/src/state/sync.js CHANGED
@@ -1,7 +1,15 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import path from 'node:path';
1
3
  import { GitHostNotFound } from '../adapters/githost/errors.js';
4
+ import { SLICEKIT_WORKFLOW } from '../adapters/githost/gh-json.js';
5
+ import { SYNC_BRANCH, SYNC_TITLE } from '../check/ci-event.js';
6
+ import { GitError, currentBranch, git, switchBranch } from '../git.js';
7
+ import { kitPaths } from '../paths.js';
8
+ import { prBodyProblems } from '../prbody.js';
2
9
  import { listSlices, setState } from './index.js';
3
10
  import { isDate } from '../evidence.js';
4
11
  import { HOST_MERGE_FROM } from './transitions.js';
12
+ import { releasePaths } from '../release-version.js';
5
13
 
6
14
  // Before a pull request exists in the state machine: a merged pull request recorded here means the
7
15
  // record is wrong, and a human should look rather than the sync guess.
@@ -62,3 +70,177 @@ export function syncFromHost(root, cfg, host) {
62
70
  }
63
71
  return { changes, warnings };
64
72
  }
73
+
74
+ // `slicekit sync open` (03 REQ-3.11, D-78, D-80): after status --sync --write on the default branch's
75
+ // merge commit, the state change goes up for review instead of onto the default branch. The paths it
76
+ // may carry are the state directory, BUILD.md and the journal heads log, and with release.auto the
77
+ // files the release step writes (syncPaths, D-90); nothing else is staged. When
78
+ // none of them changed it opens nothing. Otherwise it commits them on `sync/<short sha>` (a new branch
79
+ // from the merge commit), pushes that branch alone, opens `[sync] state after <short sha>` into the
80
+ // default branch through C-1, and starts the kit's workflow on the branch with workflow_dispatch, since
81
+ // a pull request opened with the workflow's own token starts no run. An open pull request for that
82
+ // branch means a run already did this: nothing is opened a second time. The commit is made with
83
+ // ALLOW_PROTECTED_COMMIT removed from its environment, so the git hooks guard it as any other.
84
+ // Returns { outcome: 'unchanged' } | { outcome: 'open', branch, number, url } |
85
+ // { outcome: 'opened', branch, number, url, files } | { outcome: 'newer', branch, number, url, head } (a
86
+ // sync pull request cut from a later merge is open; nothing pushed or opened), each with `closed`, the
87
+ // older [sync] pull requests it closed as superseded. Throws SyncOpenError, GitError or GitHostError.
88
+ export class SyncOpenError extends Error {
89
+ constructor(message) {
90
+ super(message);
91
+ this.name = 'SyncOpenError';
92
+ }
93
+ }
94
+
95
+ export const SYNC_BRANCH_PREFIX = 'sync/';
96
+ export const syncTitle = (short) => `[sync] state after ${short}`;
97
+
98
+ const posix = (p) => p.split(path.sep).join('/');
99
+
100
+ // The paths a sync commit may carry, relative to the repository root. With release.auto, also the
101
+ // files the release step writes: package.json, CHANGELOG.md and the rendered files (D-90).
102
+ export function syncPaths(root, cfg) {
103
+ const p = kitPaths(root, cfg);
104
+ const state = [p.build, p.state, path.join(p.kit, 'journal-heads.log')].map((f) => posix(path.relative(root, f)));
105
+ return cfg.release?.auto === true ? [...state, ...releasePaths(cfg)] : state;
106
+ }
107
+
108
+ // git with ALLOW_PROTECTED_COMMIT taken out of the environment (REQ-3.11: the sync never sets it).
109
+ function gitGuarded(root, args) {
110
+ const env = { ...process.env };
111
+ for (const k of Object.keys(env)) if (k.toUpperCase() === 'ALLOW_PROTECTED_COMMIT') delete env[k];
112
+ try {
113
+ return execFileSync('git', args, { cwd: root, env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
114
+ } catch (e) {
115
+ throw new GitError(args, String(e.stderr ?? e.message).trim());
116
+ }
117
+ }
118
+
119
+ // The files under `paths` that differ from HEAD, untracked ones included, as POSIX paths.
120
+ function changedUnder(root, paths) {
121
+ const out = gitGuarded(root, ['--literal-pathspecs', 'status', '--porcelain=v1', '-z', '--no-renames', '--untracked-files=all', '--', ...paths]);
122
+ return out
123
+ .split('\0')
124
+ .filter((e) => e.length > 3)
125
+ .map((e) => e.slice(3))
126
+ .sort();
127
+ }
128
+
129
+ export function syncBody(short, defaultBranch, files) {
130
+ const list = files.map((f) => `\`${f}\``).join(', ');
131
+ return [
132
+ `**Done when:** the slice state that \`slicekit status --sync --write\` recorded after ${short} is on ${defaultBranch}: ${list}`,
133
+ `**Proof:** \`slicekit status --sync --write\` on ${short} changed ${files.length} file${files.length === 1 ? '' : 's'}; the checks run on this branch through workflow_dispatch`,
134
+ '**Decisions:** none',
135
+ '',
136
+ ].join('\n');
137
+ }
138
+
139
+ // Pushes the sync branch, and only a `sync/<short sha>` branch, with a lease on what origin holds
140
+ // for it now: none, or the commit a run that stopped before its pull request left there. A re-run
141
+ // makes a new commit (its committer time differs), so a plain push would be refused; the lease
142
+ // replaces only the ref read a moment before and never touches any other branch.
143
+ function pushSyncBranch(root, cfg, branch) {
144
+ if (!SYNC_BRANCH.test(branch) || branch === cfg.defaultBranch || (cfg.protectedBranches ?? []).includes(branch)) {
145
+ throw new SyncOpenError(`sync open pushes only a sync/<short sha> branch, not ${branch}`);
146
+ }
147
+ const ref = `refs/heads/${branch}`;
148
+ const listed = gitGuarded(root, ['ls-remote', '--heads', 'origin', ref]).trim();
149
+ const held = listed.split('\n').map((l) => l.split(/\s+/)).find(([, name]) => name === ref)?.[0] ?? '';
150
+ gitGuarded(root, ['push', '-q', `--force-with-lease=${ref}:${held}`, 'origin', `HEAD:${ref}`]);
151
+ }
152
+
153
+ // The commit a sync branch was cut from, the merge commit its name carries (`sync/<short sha>`), or null
154
+ // when the clone does not hold it.
155
+ function syncBase(root, branch) {
156
+ const sha = branch.slice(SYNC_BRANCH_PREFIX.length);
157
+ try {
158
+ return gitGuarded(root, ['rev-parse', '--verify', '--quiet', '--end-of-options', `${sha}^{commit}`]).trim() || null;
159
+ } catch (e) {
160
+ if (e instanceof GitError) return null;
161
+ throw e;
162
+ }
163
+ }
164
+
165
+ const isAncestor = (root, a, b) => {
166
+ try {
167
+ gitGuarded(root, ['merge-base', '--is-ancestor', a, b]);
168
+ return true;
169
+ } catch (e) {
170
+ if (e instanceof GitError) return false;
171
+ throw e;
172
+ }
173
+ };
174
+
175
+ // The other open `[sync]` pull requests on a `sync/<short sha>` branch into the default branch, sorted
176
+ // by where their branch was cut relative to this run's merge commit `head`: `older` when their commit
177
+ // is an ancestor of head (this run's state carries theirs), `newer` when head is an ancestor of theirs
178
+ // (theirs carries this run's). One whose commit the clone does not hold, or that is neither, is left.
179
+ function otherSyncPullRequests(root, cfg, host, head, branch) {
180
+ const older = [];
181
+ const newer = [];
182
+ for (const pr of host.listOpenPullRequests()) {
183
+ if (pr.head === branch) continue;
184
+ if (!SYNC_BRANCH.test(pr.head) || !SYNC_TITLE.test(pr.title) || (pr.base !== null && pr.base !== cfg.defaultBranch)) continue;
185
+ const base = syncBase(root, pr.head);
186
+ if (base === null || base === head) continue;
187
+ if (isAncestor(root, base, head)) older.push(pr);
188
+ else if (isAncestor(root, head, base)) newer.push(pr);
189
+ }
190
+ return { older, newer };
191
+ }
192
+
193
+ // Closes each older sync pull request with a comment naming the one that supersedes it: the sync state
194
+ // is cumulative from the default branch's tip, so a sync pull request cut from a later merge carries
195
+ // every change an earlier one did. Returns the numbers closed.
196
+ function closeSuperseded(host, cfg, older, keep) {
197
+ for (const pr of older) {
198
+ host.closePullRequest(pr.number, `Superseded by #${keep.number} (${keep.url}): the sync state is cumulative from ${cfg.defaultBranch}'s tip, so #${keep.number} carries every change this pull request did.`);
199
+ }
200
+ return older.map((pr) => pr.number);
201
+ }
202
+
203
+ export function openSyncPullRequest(root, cfg, host) {
204
+ const start = currentBranch(root);
205
+ if (start !== cfg.defaultBranch) {
206
+ throw new SyncOpenError(`sync open runs on ${cfg.defaultBranch}, at the merge commit; HEAD is ${start === null ? 'detached' : `on ${start}`}`);
207
+ }
208
+ const files = changedUnder(root, syncPaths(root, cfg));
209
+ if (files.length === 0) return { outcome: 'unchanged' };
210
+ const short = git(root, ['rev-parse', '--short', 'HEAD']);
211
+ const branch = `${SYNC_BRANCH_PREFIX}${short}`;
212
+ const head = git(root, ['rev-parse', 'HEAD']);
213
+ const others = otherSyncPullRequests(root, cfg, host, head, branch);
214
+ // A sync pull request cut from a later merge already carries this state (a re-run of an older
215
+ // merge's job): opening this one would only open a stale one.
216
+ const newest = others.newer.at(-1);
217
+ if (newest) return { outcome: 'newer', branch, number: newest.number, url: newest.url, head: newest.head, closed: [] };
218
+ const open = host.pullRequestForBranch(branch, { base: cfg.defaultBranch });
219
+ if (open) {
220
+ // A re-run of the job: the pull request is there, but the first run may have stopped before its
221
+ // dispatch, so start the workflow on the branch again; a second run of the checks is harmless.
222
+ const closed = closeSuperseded(host, cfg, others.older, { number: open.number, url: open.url });
223
+ host.dispatchWorkflow(SLICEKIT_WORKFLOW.file, branch);
224
+ return { outcome: 'open', branch, number: open.number, url: open.url, closed };
225
+ }
226
+
227
+ const title = syncTitle(short);
228
+ const body = syncBody(short, cfg.defaultBranch, files);
229
+ const problems = prBodyProblems(title, body, cfg);
230
+ if (problems.length > 0) throw new SyncOpenError(problems.join('\n'));
231
+
232
+ switchBranch(root, branch, { create: true });
233
+ try {
234
+ gitGuarded(root, ['--literal-pathspecs', 'add', '-A', '--', ...files]);
235
+ gitGuarded(root, ['--literal-pathspecs', 'commit', '-q', '-m', `chore(slicekit): sync state after ${short}`, '--', ...files]);
236
+ pushSyncBranch(root, cfg, branch);
237
+ } finally {
238
+ // Back to where it started; the change lives on the sync branch.
239
+ git(root, ['switch', '-q', start]);
240
+ }
241
+ const made = host.openPullRequest({ branch, base: cfg.defaultBranch, title, body, draft: false });
242
+ // Closed only once the new one is open, so a failed open leaves the older one standing.
243
+ const closed = closeSuperseded(host, cfg, others.older, { number: made.number, url: made.url });
244
+ host.dispatchWorkflow(SLICEKIT_WORKFLOW.file, branch);
245
+ return { outcome: 'opened', branch, number: made.number, url: made.url, files, closed };
246
+ }