@skitterbyte/skitterspec-linear 18.0.0 → 18.1.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 (51) hide show
  1. package/MIGRATION.md +81 -0
  2. package/assets/core/env.config.md +33 -9
  3. package/assets/hooks/main-guard.cjs +1 -1
  4. package/assets/hooks/review-gate.cjs +1 -1
  5. package/assets/rules/spec-planning.md +4 -2
  6. package/assets/skills/no-spec/SKILL.md +3 -2
  7. package/assets/skills/spec-complete/SKILL.md +67 -25
  8. package/assets/skills/spec-hotfix/SKILL.md +21 -11
  9. package/assets/skills/spec-sync/SKILL.md +10 -1
  10. package/package.json +1 -1
  11. package/src/cli.js +295 -37
  12. package/src/env/config.js +14 -2
  13. package/src/env/hotfix.js +261 -15
  14. package/src/env/hotfixland.js +302 -0
  15. package/src/env/resolve.js +22 -8
  16. package/src/init.js +36 -4
  17. package/src/vendor/linear/api.js +43 -56
  18. package/src/vendor/linear/cli-sanitise.js +2 -2
  19. package/src/vendor/linear/cli-sync.js +87 -390
  20. package/src/vendor/linear/config.js +46 -171
  21. package/src/vendor/linear/credentials.js +40 -370
  22. package/src/vendor/linear/dialect.js +177 -0
  23. package/src/vendor/linear/doctor.js +7 -15
  24. package/src/vendor/linear/identity.js +20 -70
  25. package/src/vendor/linear/released.js +4 -222
  26. package/src/vendor/{sync-core/src → linear}/sanitise.js +4 -3
  27. package/src/vendor/provider-kit/index.js +41 -0
  28. package/src/vendor/provider-kit/src/adapter.js +23 -0
  29. package/src/vendor/provider-kit/src/apply.js +197 -0
  30. package/src/vendor/provider-kit/src/args.js +68 -0
  31. package/src/vendor/provider-kit/src/config.js +198 -0
  32. package/src/vendor/provider-kit/src/credentials.js +404 -0
  33. package/src/vendor/provider-kit/src/doctor.js +35 -0
  34. package/src/vendor/provider-kit/src/http.js +44 -0
  35. package/src/vendor/provider-kit/src/identity.js +93 -0
  36. package/src/vendor/provider-kit/src/md-compare.js +39 -0
  37. package/src/vendor/{sync-core/src/tables.js → provider-kit/src/md-tables.js} +10 -18
  38. package/src/vendor/provider-kit/src/prompt.js +50 -0
  39. package/src/vendor/provider-kit/src/released.js +226 -0
  40. package/src/vendor/provider-kit/src/specs.js +166 -0
  41. package/src/vendor/provider-kit/src/transport.js +22 -0
  42. package/src/vendor/sync-core/index.js +22 -5
  43. package/src/vendor/sync-core/src/compare.js +14 -12
  44. package/src/vendor/sync-core/src/dialect.js +51 -0
  45. package/src/vendor/sync-core/src/fields.js +36 -0
  46. package/src/vendor/sync-core/src/legacy.js +19 -9
  47. package/src/vendor/sync-core/src/normalize.js +30 -158
  48. package/src/vendor/sync-core/src/push.js +1 -1
  49. package/src/vendor/sync-core/src/retarget.js +21 -17
  50. package/src/vendor/sync-core/src/verify.js +24 -45
  51. package/src/vendor/sync-core/src/write.js +7 -5
package/src/env/hotfix.js CHANGED
@@ -39,6 +39,87 @@ function bumpPatch(tag) {
39
39
  return `${prefix}${major}.${minor}.${Number(patch) + 1}`
40
40
  }
41
41
 
42
+ // A release tag's parts: `<prefix><major>.<minor>.<patch>[-<suffix>]`. A
43
+ // `hotfix.N` suffix is kept apart from every other one, because the two sort on
44
+ // opposite sides of their base (see compareTags). Null for anything else.
45
+ const TAG = /^(\D*)(\d+)\.(\d+)\.(\d+)(?:-(.+))?$/
46
+ function parseTag(tag) {
47
+ const m = TAG.exec(String(tag || '').trim())
48
+ if (!m) return null
49
+ const [, prefix, major, minor, patch, suffix = null] = m
50
+ const hotfix = suffix && /^hotfix\.(\d+)$/.exec(suffix)
51
+ return {
52
+ prefix,
53
+ core: [Number(major), Number(minor), Number(patch)],
54
+ root: `${prefix}${major}.${minor}.${patch}`,
55
+ hotfix: hotfix ? Number(hotfix[1]) : null,
56
+ suffix: hotfix ? null : suffix,
57
+ }
58
+ }
59
+
60
+ /**
61
+ * Order two release tags: X.Y.Z-rc.N < X.Y.Z < X.Y.Z-hotfix.N < X.Y.(Z+1).
62
+ *
63
+ * This is skittership's rule and git's `version:refname` with a hotfix suffix
64
+ * configured to sort after its base, so the two tools never disagree about
65
+ * which tag is newer. A hotfix is a later build OF X.Y.Z; every other suffix is
66
+ * a pre-release BEFORE it, as in semver. Hotfix numbers compare numerically
67
+ * (`-hotfix.10` after `-hotfix.9`); other suffixes compare as strings. An
68
+ * unparseable tag sorts first, so it can never be mistaken for the newest.
69
+ */
70
+ function compareTags(a, b) {
71
+ const x = parseTag(a)
72
+ const y = parseTag(b)
73
+ if (!x || !y) return (x ? 1 : 0) - (y ? 1 : 0)
74
+ for (let i = 0; i < 3; i++) {
75
+ if (x.core[i] !== y.core[i]) return x.core[i] - y.core[i]
76
+ }
77
+ // Rank within one core: pre-release (0) < the release itself (1) < hotfix (2).
78
+ const rank = (t) => (t.suffix ? 0 : t.hotfix === null ? 1 : 2)
79
+ if (rank(x) !== rank(y)) return rank(x) - rank(y)
80
+ if (x.hotfix !== null) return x.hotfix - y.hotfix
81
+ if (x.suffix) return x.suffix < y.suffix ? -1 : x.suffix > y.suffix ? 1 : 0
82
+ return 0
83
+ }
84
+
85
+ /**
86
+ * The next `<root>-hotfix.<N>` for a base tag: N is one above the highest
87
+ * `<root>-hotfix.*` among `existingTags`, else 1. The root is the base with any
88
+ * hotfix suffix stripped, so a hotfix on `v36.4.0-hotfix.2` continues that
89
+ * line. A later `X.Y.(Z+1)` is neither a collision nor counted — it is another
90
+ * release line entirely. Same rule as skittership's release-hotfix.
91
+ */
92
+ function nextHotfixTag(baseTag, existingTags) {
93
+ const base = parseTag(baseTag)
94
+ if (!base) {
95
+ throw new Error(
96
+ `hotfix: cannot derive a hotfix tag from "${baseTag}" — need <prefix>MAJOR.MINOR.PATCH`,
97
+ )
98
+ }
99
+ if (base.suffix) {
100
+ throw new Error(
101
+ `hotfix: base tag "${baseTag}" is a pre-release — a hotfix needs a released version`,
102
+ )
103
+ }
104
+ let n = base.hotfix || 0
105
+ for (const t of existingTags || []) {
106
+ const p = parseTag(t)
107
+ if (p && p.root === base.root && p.hotfix !== null && p.hotfix > n) n = p.hotfix
108
+ }
109
+ return `${base.root}-hotfix.${n + 1}`
110
+ }
111
+
112
+ const BUMPS = ['patch', 'hotfix-suffix']
113
+
114
+ // The tag `hotfix.bump` asks for. An unknown strategy throws rather than
115
+ // falling back to `patch`: a typo there would otherwise cut the wrong release
116
+ // line and say nothing.
117
+ function nextTag(baseTag, existingTags, bump = 'patch') {
118
+ if (bump === 'patch') return bumpPatch(baseTag)
119
+ if (bump === 'hotfix-suffix') return nextHotfixTag(baseTag, existingTags)
120
+ throw new Error(`unknown hotfix.bump "${bump}" — use one of: ${BUMPS.join(', ')}`)
121
+ }
122
+
42
123
  // A filesystem/branch-safe slug derived from a tag (`v30.2.1` → `v30-2-1`).
43
124
  function tagSlug(tag) {
44
125
  return String(tag)
@@ -50,7 +131,11 @@ function tagSlug(tag) {
50
131
  * @param {object} spec resolved hotfix spec: { slug, branch, worktreePath, baseRef, ... }
51
132
  * @param {object} config normalised env config (reads `config.hotfix`).
52
133
  * @param {object} ctx { worktreeState:{dirty}, aheadOfBase, fixRange, mainRepoPath,
53
- * base, extraTargets: string[], existingTags: string[] }
134
+ * base, extraTargets: string[], existingTags: string[],
135
+ * released?, push?: boolean, pushed?: boolean, remote?,
136
+ * fixCommits?: string[],
137
+ * carry?: { strategy: 'inplace'|'worktree'|'dirty', path,
138
+ * tmpPath?, commits: string[] } }
54
139
  * @returns {object} { blocked, noop, reason, commands, afterLand, prodTag, targets, branch, base }
55
140
  */
56
141
  function planHotfixLand(spec, config, ctx) {
@@ -63,6 +148,7 @@ function planHotfixLand(spec, config, ctx) {
63
148
  noop: false,
64
149
  reason: null,
65
150
  commands: [],
151
+ steps: [],
66
152
  afterLand: afterLandFor(null),
67
153
  prodTag: null,
68
154
  targets: [],
@@ -88,24 +174,79 @@ function planHotfixLand(spec, config, ctx) {
88
174
  // between the prod tag and a target tag).
89
175
  const taken = new Set(c.existingTags || [])
90
176
  const fixRange = c.fixRange
177
+ // What a target cherry-picks: the fix commits by sha when the caller listed
178
+ // them (the version commit already left out), else the bare range. The
179
+ // range form is what this planner always emitted and what pure callers that
180
+ // list nothing still get.
181
+ const fixPick = Array.isArray(c.fixCommits) && c.fixCommits.length ? c.fixCommits : [fixRange]
91
182
  const commands = []
92
183
  const targets = []
184
+ // What the engine runs (hotfixland.js). `commands` stays beside it as the
185
+ // human-readable spelling of the same thing, for `--plan` and the tests.
186
+ const steps = []
187
+ const bump = hotfixCfg.bump || 'patch'
188
+ const releaseWith = String(hotfixCfg.releaseWith || '').trim()
93
189
 
94
- // 1. Prod line: tag the hotfix branch head (already baseRef + fix). No push.
95
- const prodTag = bumpPatch(baseRef)
96
- if (taken.has(prodTag)) {
97
- return block(`tag ${prodTag} already exists — bump the base version or delete the stale tag`)
190
+ // 1. Prod line: release the hotfix branch head (already baseRef + fix). No push.
191
+ // Three ways, decided here so the runner never has to: a release already
192
+ // cut on an earlier run and still at HEAD is reused, never re-cut; a
193
+ // project's `releaseWith` command cuts it and says which tag it made; or
194
+ // the built-in tagger tags HEAD with the `hotfix.bump` strategy's tag.
195
+ let prodTag = null
196
+ if (c.released && c.released.tag) {
197
+ prodTag = c.released.tag
198
+ taken.add(prodTag)
199
+ steps.push({ kind: 'release', via: 'recorded', tag: prodTag, release: c.released })
200
+ } else if (releaseWith) {
201
+ // The tag is the command's to choose and is unknown until it has run, so
202
+ // there is nothing to check a collision against here — the command refuses
203
+ // a tag that exists, and the runner refuses one a target also planned.
204
+ commands.push(`(cd ${spec.worktreePath} && ${releaseWith})`)
205
+ steps.push({ kind: 'release', via: 'command', command: releaseWith, cwd: spec.worktreePath })
206
+ } else {
207
+ prodTag = nextTag(baseRef, c.existingTags, bump)
208
+ if (taken.has(prodTag)) {
209
+ return block(`tag ${prodTag} already exists — bump the base version or delete the stale tag`)
210
+ }
211
+ taken.add(prodTag)
212
+ commands.push(`git -C ${spec.worktreePath} tag ${prodTag}`)
213
+ steps.push({
214
+ kind: 'release',
215
+ via: 'tag',
216
+ tag: prodTag,
217
+ cwd: spec.worktreePath,
218
+ baseTag: baseRef,
219
+ branch,
220
+ })
98
221
  }
99
- taken.add(prodTag)
100
- commands.push(`git -C ${spec.worktreePath} tag ${prodTag}`)
101
222
  targets.push({ kind: 'prod', base: baseRef, tag: prodTag })
102
223
 
103
- // 2. Extra targets: cherry-pick the fix onto a throwaway worktree at each tag,
104
- // re-tag with its own patch bump, then remove the worktree + temp branch (the
224
+ // 2. Publish the prod line: the branch first, then the tag, because the tag
225
+ // push is what starts the deploy. BEFORE anything is carried to main, so a
226
+ // declined or failed push never leaves main carrying a fix whose tag was
227
+ // never published. Three cases: the tag is already on the remote (a
228
+ // hand-run push, honoured on its positive signal); the operator consented
229
+ // (`--push`); or neither, and the run holds here with the commands printed.
230
+ const remote = c.remote || 'origin'
231
+ if (c.pushed) {
232
+ steps.push({ kind: 'push', via: 'remote', remote, branch, cwd: spec.worktreePath })
233
+ } else if (c.push) {
234
+ steps.push({ kind: 'push', via: 'push', remote, branch, cwd: spec.worktreePath })
235
+ } else {
236
+ steps.push({ kind: 'push', via: 'hold', remote, branch, cwd: spec.worktreePath })
237
+ }
238
+
239
+ // 3. Extra targets: cherry-pick the fix onto a throwaway worktree at each tag,
240
+ // re-tag with its own bump, then remove the worktree + temp branch (the
105
241
  // commits survive under the new tag, so `-D` is safe for the throwaway branch).
242
+ // TAG-ONLY, deliberately: `releaseWith` is the prod line's. Running a
243
+ // project's release per target would need a hotfix/ branch and a clean
244
+ // tree for each one, and one failing half-way leaves a line half-released.
106
245
  const wtRoot = path.dirname(spec.worktreePath)
107
246
  for (const t of c.extraTargets || []) {
108
- const tag = bumpPatch(t)
247
+ // Counted against `taken`, so two targets on one root get successive
248
+ // hotfix numbers rather than colliding on the same one.
249
+ const tag = nextTag(t, [...taken], bump)
109
250
  if (taken.has(tag)) {
110
251
  return block(`tag ${tag} (for target ${t}) already exists — resolve it before landing`)
111
252
  }
@@ -115,25 +256,130 @@ function planHotfixLand(spec, config, ctx) {
115
256
  const tmpPath = path.join(wtRoot, slug)
116
257
  commands.push(
117
258
  `git worktree add ${tmpPath} -b ${tmpBranch} ${t}`,
118
- `git -C ${tmpPath} cherry-pick ${fixRange}`,
259
+ `git -C ${tmpPath} cherry-pick ${fixPick.join(' ')}`,
119
260
  `git -C ${tmpPath} tag ${tag}`,
120
261
  `git worktree remove ${tmpPath}`,
121
262
  `git branch -D ${tmpBranch}`,
122
263
  )
264
+ const root = c.mainRepoPath
265
+ steps.push({
266
+ kind: 'target',
267
+ base: t,
268
+ tag,
269
+ worktreePath: tmpPath,
270
+ argvs: [
271
+ ['-C', root, 'worktree', 'add', tmpPath, '-b', tmpBranch, t],
272
+ ['-C', tmpPath, 'cherry-pick', ...fixPick],
273
+ ['-C', tmpPath, 'tag', tag],
274
+ ['-C', root, 'worktree', 'remove', tmpPath],
275
+ ['-C', root, 'branch', '-D', tmpBranch],
276
+ ],
277
+ })
123
278
  targets.push({ kind: 'extra', base: t, tag, worktreePath: tmpPath })
124
279
  }
125
280
 
126
- // 3. Cherry-pick the fix onto the base branch (main) for the next release.
281
+ // 4. Cherry-pick the fix onto the base branch (main) for the next release.
127
282
  // Only then does the primary checkout gain anything, so only then do the
128
283
  // after-land commands apply — a prod-only land leaves main untouched.
129
284
  let afterLand = result.afterLand
130
285
  if (hotfixCfg.cherryPickMain !== false) {
131
- commands.push(`git -C ${c.mainRepoPath} cherry-pick ${fixRange}`)
286
+ // THE CARRY IS A LIST OF COMMITS, NOT A RANGE. A releasing command leaves
287
+ // a version commit on the branch (package.json, CHANGELOG, RELEASES), and
288
+ // main's version line never moves on a hotfix — so the caller hands over
289
+ // `baseRef..branch` minus that commit and minus what `git cherry` says main
290
+ // already has. The spec's own completion commits stay in it: that is how
291
+ // the completed spec reaches main. Without a list (pure callers), the old
292
+ // range form, run in place.
293
+ const carry = c.carry || { strategy: 'inplace', path: c.mainRepoPath, commits: null }
294
+ const picks = carry.commits || [fixRange]
295
+ commands.push(
296
+ carry.strategy === 'worktree'
297
+ ? `git worktree add ${carry.tmpPath} ${c.base} && git -C ${carry.tmpPath} cherry-pick ${picks.join(' ')}`
298
+ : `git -C ${carry.path} cherry-pick ${picks.join(' ')}`,
299
+ )
300
+ steps.push({
301
+ kind: 'carry',
302
+ base: c.base,
303
+ strategy: carry.strategy,
304
+ cwd: carry.path || c.mainRepoPath,
305
+ root: c.mainRepoPath,
306
+ tmpPath: carry.tmpPath || null,
307
+ commits: picks,
308
+ })
132
309
  targets.push({ kind: 'main', base: c.base })
133
310
  afterLand = afterLandFor(config, c.mainRepoPath)
134
311
  }
135
312
 
136
- return { ...result, commands, afterLand, prodTag, targets, fixRange }
313
+ return { ...result, commands, steps, afterLand, prodTag, targets, fixRange }
137
314
  }
138
315
 
139
- module.exports = { bumpPatch, tagSlug, planHotfixLand }
316
+ /**
317
+ * Plan `spec-env hotfix finish`: the teardown a hotfix waits for until its
318
+ * deploy is out.
319
+ *
320
+ * A hotfix branch is needed until the release it cut is confirmed — a failed
321
+ * deploy cuts the next `-hotfix.N` from the same branch — so `/spec-complete`
322
+ * lands and keeps the worktree, and this is the later step that removes it.
323
+ *
324
+ * THREE GUARDS, every one a positive signal, and every failing one named:
325
+ * - a clean tree — anything uncommitted would go with the worktree;
326
+ * - a release tag at HEAD — the land actually released what is here;
327
+ * - the branch on the remote at HEAD — a copy exists after `branch -D`.
328
+ * A remote that cannot be asked is "cannot tell", which refuses: deleting
329
+ * the only copy of a deployed fix is not the safe way to be wrong.
330
+ *
331
+ * DELIBERATELY NO "MERGED INTO MAIN" GUARD: the version commit never reaches
332
+ * main, so the branch is never an ancestor of it and `-d` would always refuse.
333
+ * And DELIBERATELY NO `--force` — the guards are the point of the verb, and
334
+ * `spec-env down --force` already exists for anyone who means to override them.
335
+ *
336
+ * state: { dirty, tagsAtHead: string[], head, remoteHead: string|null|undefined,
337
+ * remote, mainRepoPath, hasSlot }
338
+ * remoteHead: the branch's sha on the remote; null = not there;
339
+ * undefined = the remote could not be asked.
340
+ */
341
+ function planHotfixFinish(spec, state) {
342
+ const s = state || {}
343
+ const remote = s.remote || 'origin'
344
+ const reasons = []
345
+ if (s.dirty) reasons.push('the worktree has uncommitted changes')
346
+ const releaseTag = (s.tagsAtHead || []).find((t) => parseTag(t) !== null) || null
347
+ if (!releaseTag) {
348
+ reasons.push('no release tag at HEAD — run `spec-env hotfix land` first')
349
+ }
350
+ if (s.remoteHead === undefined) {
351
+ reasons.push(`cannot tell whether ${spec.branch} is on ${remote} — the remote did not answer`)
352
+ } else if (s.remoteHead === null) {
353
+ reasons.push(`${spec.branch} is not on ${remote} — push it (\`hotfix land --push\`)`)
354
+ } else if (s.head && s.remoteHead !== s.head) {
355
+ reasons.push(`${remote}/${spec.branch} is not at HEAD — push the branch first`)
356
+ }
357
+ // A Docker stack has volumes and a slot that only `down` knows how to free.
358
+ if (s.hasSlot) {
359
+ reasons.push(`${spec.folder} holds a Docker stack — tear it down with \`spec-env down\``)
360
+ }
361
+ if (reasons.length) return { blocked: true, reasons, releaseTag, argvs: [] }
362
+ const root = s.mainRepoPath
363
+ return {
364
+ blocked: false,
365
+ reasons: [],
366
+ releaseTag,
367
+ argvs: [
368
+ ['-C', root, 'worktree', 'remove', spec.worktreePath],
369
+ // -D, not -d: the branch is never merged into main (see above), and its
370
+ // commits are on the remote and under the release tag.
371
+ ['-C', root, 'branch', '-D', spec.branch],
372
+ ],
373
+ }
374
+ }
375
+
376
+ module.exports = {
377
+ bumpPatch,
378
+ compareTags,
379
+ nextHotfixTag,
380
+ nextTag,
381
+ BUMPS,
382
+ tagSlug,
383
+ planHotfixLand,
384
+ planHotfixFinish,
385
+ }
@@ -0,0 +1,302 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * Run a hotfix land's steps — the engine half of `spec-env hotfix land`.
5
+ *
6
+ * `planHotfixLand` (hotfix.js) decides WHAT the land is; this module does it,
7
+ * the way `bootstrap.js` does a worktree's steps. It used to be a printed plan
8
+ * the skill ran by hand, and that stopped being possible the moment the release
9
+ * could be a project's own command: the prod tag is only known once that
10
+ * command has run and said what it cut, so no plan printed beforehand can name
11
+ * it.
12
+ *
13
+ * The run stops at the first step that fails, and the release is reported to
14
+ * `io.record` the moment it succeeds — so a land that stops later (a refused
15
+ * push, a conflicted cherry-pick) can be re-run without cutting a second
16
+ * release. skittership's own command refuses a second one anyway, since HEAD is
17
+ * then already tagged; the record is what lets the re-run carry on instead of
18
+ * stopping there.
19
+ *
20
+ * Every side effect goes through `io.spawn`, so tests drive it with a fake.
21
+ */
22
+
23
+ const { spawnSync } = require('node:child_process')
24
+
25
+ // The fields skittership's `release-hotfix.cjs --json` prints, and their types.
26
+ // `versionCommit` is null only on its `--dry-run`, which skitterspec never
27
+ // passes — so a null here is accepted, and means "no version commit to leave
28
+ // behind", exactly as the built-in tagger's.
29
+ const RELEASE_FIELDS = {
30
+ tag: 'string',
31
+ version: 'string',
32
+ baseTag: 'string',
33
+ branch: 'string',
34
+ versionCommit: 'string|null',
35
+ pushed: 'boolean',
36
+ }
37
+
38
+ /**
39
+ * Parse a release command's stdout STRICTLY: the whole of it, trimmed, must be
40
+ * one JSON object carrying every field above. Anything else — a package
41
+ * manager's run banner, a stray log line, a missing field — is a refusal rather
42
+ * than a best guess, because a guessed tag is a deploy of the wrong thing.
43
+ */
44
+ function parseRelease(stdout) {
45
+ const text = String(stdout || '').trim()
46
+ if (!text) return { ok: false, reason: 'printed nothing on stdout — expected one JSON line' }
47
+ let obj
48
+ try {
49
+ obj = JSON.parse(text)
50
+ } catch {
51
+ const first = text.split('\n')[0].slice(0, 120)
52
+ return { ok: false, reason: `stdout is not one JSON object (starts: ${first})` }
53
+ }
54
+ if (!obj || typeof obj !== 'object' || Array.isArray(obj)) {
55
+ return { ok: false, reason: 'stdout is JSON but not an object' }
56
+ }
57
+ for (const [key, type] of Object.entries(RELEASE_FIELDS)) {
58
+ const v = obj[key]
59
+ const fits = type
60
+ .split('|')
61
+ .some((t) => (t === 'null' ? v === null : typeof v === t && (t !== 'string' || v.length)))
62
+ if (!fits) return { ok: false, reason: `JSON field "${key}" is missing or not ${type}` }
63
+ }
64
+ return { ok: true, release: obj }
65
+ }
66
+
67
+ /** One line describing a step, for `--plan` and the failure report. */
68
+ function describeStep(step) {
69
+ switch (step.kind) {
70
+ case 'release':
71
+ if (step.via === 'command') return `release: ${step.command}`
72
+ if (step.via === 'recorded') return `release: ${step.tag} (cut earlier — not re-run)`
73
+ return `release: git tag ${step.tag}`
74
+ case 'push':
75
+ if (step.via === 'remote') return `push: ${step.tag || 'the tag'} is already on ${step.remote}`
76
+ if (step.via === 'hold') return `push: held — no consent to push to ${step.remote}`
77
+ return `push: ${step.branch}, then ${step.tag || 'the tag'}, to ${step.remote}`
78
+ case 'target':
79
+ return `target: ${step.base} -> ${step.tag} (cherry-pick, tag)`
80
+ case 'carry': {
81
+ const n = Array.isArray(step.commits) ? step.commits.length : 0
82
+ const what = n === 1 ? '1 commit' : `${n} commits`
83
+ if (step.strategy === 'worktree') return `carry: cherry-pick ${what} onto ${step.base} (throwaway worktree)`
84
+ return `carry: cherry-pick ${what} onto ${step.base}`
85
+ }
86
+ default:
87
+ return `unknown step ${step.kind}`
88
+ }
89
+ }
90
+
91
+ // The last non-blank line a command wrote to stderr — skittership's refusals
92
+ // are one `✖ release-hotfix: <reason>` line there, and that is what to relay.
93
+ function lastLine(text) {
94
+ const lines = String(text || '')
95
+ .split('\n')
96
+ .map((l) => l.trim())
97
+ .filter(Boolean)
98
+ return lines.length ? lines[lines.length - 1] : null
99
+ }
100
+
101
+ function why(res) {
102
+ if (res.error) return res.error.message
103
+ return res.status === null ? `killed by ${res.signal || 'a signal'}` : `exit ${res.status}`
104
+ }
105
+
106
+ function runRelease(step, ctx) {
107
+ if (step.via === 'recorded') {
108
+ return { outcome: 'skipped', line: describeStep(step), release: step.release }
109
+ }
110
+ if (step.via === 'tag') {
111
+ const res = ctx.spawn('git', ['-C', step.cwd, 'tag', step.tag], {
112
+ stdio: ['ignore', 'pipe', 'pipe'],
113
+ encoding: 'utf8',
114
+ })
115
+ if (res.error || res.status !== 0) {
116
+ return { outcome: 'failed', line: `${describeStep(step)} — ${lastLine(res.stderr) || why(res)}` }
117
+ }
118
+ const release = {
119
+ tag: step.tag,
120
+ version: step.tag.replace(/^\D*/, ''),
121
+ baseTag: step.baseTag,
122
+ branch: step.branch,
123
+ versionCommit: null,
124
+ pushed: false,
125
+ }
126
+ return { outcome: 'released', line: `tagged ${step.tag}`, release }
127
+ }
128
+ // A project's own command, through the shell. stdout is captured whole for
129
+ // the JSON; stderr is captured so a refusal can be relayed as its own line,
130
+ // and is passed on to ours so its progress output is not lost.
131
+ const res = ctx.spawn(step.command, {
132
+ cwd: step.cwd,
133
+ shell: true,
134
+ stdio: ['ignore', 'pipe', 'pipe'],
135
+ encoding: 'utf8',
136
+ })
137
+ if (res.stderr) ctx.childStderr(res.stderr)
138
+ if (res.error || res.status !== 0) {
139
+ return { outcome: 'refused', line: `release refused — ${lastLine(res.stderr) || why(res)}` }
140
+ }
141
+ const parsed = parseRelease(res.stdout)
142
+ if (!parsed.ok) return { outcome: 'refused', line: `release refused — ${parsed.reason}` }
143
+ return { outcome: 'released', line: `released ${parsed.release.tag}`, release: parsed.release }
144
+ }
145
+
146
+ // Publish the release. The tag is the release's, known only once it has run,
147
+ // so the argvs are built here rather than in the plan. `hold` is not a failure:
148
+ // it is the operator not having said yes, and it stops the run so nothing after
149
+ // it is carried before the deploy tag is public.
150
+ function runPush(step, release, ctx) {
151
+ const s = { ...step, tag: release ? release.tag : null }
152
+ if (s.via === 'remote') return { outcome: 'skipped', line: describeStep(s) }
153
+ if (s.via === 'hold') return { outcome: 'held', line: describeStep(s) }
154
+ if (!release) return { outcome: 'failed', line: `${describeStep(s)} — no release to push` }
155
+ for (const ref of [s.branch, s.tag]) {
156
+ const argv = ['-C', s.cwd, 'push', s.remote, ref]
157
+ const res = ctx.spawn('git', argv, { stdio: ['ignore', ctx.childStdout, 'pipe'], encoding: 'utf8' })
158
+ if (res.error || res.status !== 0) {
159
+ return { outcome: 'failed', line: `push ${ref} to ${s.remote} — ${lastLine(res.stderr) || why(res)}` }
160
+ }
161
+ }
162
+ return { outcome: 'pushed', line: `pushed ${s.branch}, then ${s.tag}, to ${s.remote}` }
163
+ }
164
+
165
+ /**
166
+ * Carry the fix onto the base branch, one commit at a time so a conflict can
167
+ * name the commit that caused it.
168
+ *
169
+ * Three strategies, chosen by the caller from where the base branch is:
170
+ * inplace — checked out and clean: cherry-pick there.
171
+ * worktree — not checked out anywhere: a throwaway worktree on it, removed
172
+ * afterwards, so the branch moves without anyone's checkout moving.
173
+ * dirty — checked out with uncommitted work: refuse, and print the command
174
+ * to run by hand once it is clean. Somebody's work is in that tree.
175
+ * On a conflict the cherry-pick is aborted, which leaves the base branch where
176
+ * it was before that commit, and the hotfix branch and its record untouched —
177
+ * so a re-run tries the carry again.
178
+ */
179
+ function runCarry(step, release, ctx) {
180
+ const version = release && release.versionCommit
181
+ // The version commit cannot be in a list made before the release cut it,
182
+ // but a re-run lists the branch after — so it is left out here as well.
183
+ const commits = (step.commits || []).filter((sha) => !version || sha !== version)
184
+ if (!commits.length) {
185
+ return { outcome: 'skipped', line: `carry: nothing to carry — ${step.base} already has the fix`, carried: 0 }
186
+ }
187
+ if (step.strategy === 'dirty') {
188
+ return {
189
+ outcome: 'refused',
190
+ line:
191
+ `carry: ${step.cwd} has uncommitted changes on ${step.base} — commit or stash them, ` +
192
+ `then run: git -C ${step.cwd} cherry-pick ${commits.join(' ')}`,
193
+ }
194
+ }
195
+ const git = (argv) =>
196
+ ctx.spawn('git', argv, { stdio: ['ignore', ctx.childStdout, 'pipe'], encoding: 'utf8' })
197
+ let cwd = step.cwd
198
+ if (step.strategy === 'worktree') {
199
+ cwd = step.tmpPath
200
+ const res = git(['-C', step.root, 'worktree', 'add', cwd, step.base])
201
+ if (res.error || res.status !== 0) {
202
+ return { outcome: 'failed', line: `carry: worktree add ${cwd} — ${lastLine(res.stderr) || why(res)}` }
203
+ }
204
+ }
205
+ const cleanup = () => {
206
+ if (step.strategy === 'worktree') git(['-C', step.root, 'worktree', 'remove', '--force', cwd])
207
+ }
208
+ for (const sha of commits) {
209
+ const res = git(['-C', cwd, 'cherry-pick', sha])
210
+ if (res.error || res.status !== 0) {
211
+ git(['-C', cwd, 'cherry-pick', '--abort'])
212
+ cleanup()
213
+ return {
214
+ outcome: 'failed',
215
+ line:
216
+ `carry: cherry-pick ${sha} onto ${step.base} conflicted — aborted; ` +
217
+ `${lastLine(res.stderr) || why(res)}`,
218
+ }
219
+ }
220
+ }
221
+ cleanup()
222
+ const what = commits.length === 1 ? '1 commit' : `${commits.length} commits`
223
+ return { outcome: 'ran', line: `carried ${what} onto ${step.base}`, carried: commits.length }
224
+ }
225
+
226
+ // A step that is a list of git argvs run in order — a target's worktree,
227
+ // cherry-pick, tag and cleanup, or the carry's cherry-pick.
228
+ function runArgvs(step, ctx) {
229
+ for (const argv of step.argvs) {
230
+ const res = ctx.spawn('git', argv, { stdio: ['ignore', ctx.childStdout, 'pipe'], encoding: 'utf8' })
231
+ if (res.error || res.status !== 0) {
232
+ return {
233
+ outcome: 'failed',
234
+ line: `${describeStep(step)} — git ${argv.join(' ')}: ${lastLine(res.stderr) || why(res)}`,
235
+ }
236
+ }
237
+ }
238
+ return { outcome: 'ran', line: describeStep(step) }
239
+ }
240
+
241
+ /**
242
+ * Run `steps` in order, stopping at the first that fails or refuses.
243
+ *
244
+ * io: { spawn?, write?, record?, childStdout?, childStderr? }
245
+ * - `write(line)` receives every report line as it happens
246
+ * - `record(release)` is called once, as soon as a release succeeds
247
+ *
248
+ * Returns { ok, held, results, failedAt, release } — `release` is what the
249
+ * release step cut (or found recorded), or null if it never got that far.
250
+ * `held` is a run that stopped at the push for want of consent: not a failure,
251
+ * and nothing after it ran.
252
+ */
253
+ function runHotfixLand(steps, io = {}) {
254
+ const ctx = {
255
+ spawn: io.spawn || spawnSync,
256
+ childStdout: io.childStdout || 'inherit',
257
+ childStderr: io.childStderr || ((t) => process.stderr.write(t)),
258
+ }
259
+ const write = io.write || (() => {})
260
+ const results = []
261
+ let release = null
262
+ let carried = null
263
+ for (let i = 0; i < steps.length; i++) {
264
+ const step = steps[i]
265
+ let r
266
+ try {
267
+ if (step.kind === 'release') r = runRelease(step, ctx)
268
+ else if (step.kind === 'push') r = runPush(step, release, ctx)
269
+ else if (step.kind === 'carry') r = runCarry(step, release, ctx)
270
+ else if (step.kind === 'target') {
271
+ // A project's release command can cut a tag the built-in tagger also
272
+ // planned for a target on the same root. Refuse rather than collide.
273
+ if (step.kind === 'target' && release && release.tag === step.tag) {
274
+ r = { outcome: 'refused', line: `${describeStep(step)} — the release already cut ${step.tag}` }
275
+ } else r = runArgvs(step, ctx)
276
+ } else r = { outcome: 'failed', line: describeStep(step) }
277
+ } catch (err) {
278
+ r = { outcome: 'failed', line: `${describeStep(step)} — ${err.message}` }
279
+ }
280
+ results.push({ step, outcome: r.outcome, line: r.line })
281
+ if (typeof r.carried === 'number') carried = r.carried
282
+ if (r.release) {
283
+ release = r.release
284
+ if (r.outcome === 'released' && io.record) io.record(release)
285
+ }
286
+ if (r.outcome === 'pushed' && release) {
287
+ release = { ...release, pushed: true }
288
+ if (io.record) io.record(release)
289
+ }
290
+ if (r.outcome === 'held') {
291
+ if (r.line) write(r.line)
292
+ return { ok: true, held: true, results, failedAt: null, release, carried }
293
+ }
294
+ if (r.outcome === 'failed' || r.outcome === 'refused') {
295
+ return { ok: false, results, failedAt: i + 1, release, carried }
296
+ }
297
+ if (r.line) write(r.line)
298
+ }
299
+ return { ok: true, held: false, results, failedAt: null, release, carried }
300
+ }
301
+
302
+ module.exports = { parseRelease, runHotfixLand, describeStep, RELEASE_FIELDS }