@skitterbyte/skitterspec-linear 18.0.1 → 18.1.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 (50) hide show
  1. package/MIGRATION.md +81 -0
  2. package/assets/core/env.config.md +36 -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/spec-complete/SKILL.md +67 -25
  7. package/assets/skills/spec-hotfix/SKILL.md +21 -11
  8. package/assets/skills/spec-sync/SKILL.md +10 -1
  9. package/package.json +1 -1
  10. package/src/cli.js +289 -34
  11. package/src/env/config.js +14 -2
  12. package/src/env/hotfix.js +288 -16
  13. package/src/env/hotfixland.js +302 -0
  14. package/src/env/resolve.js +22 -8
  15. package/src/init.js +36 -4
  16. package/src/vendor/linear/api.js +43 -56
  17. package/src/vendor/linear/cli-sanitise.js +2 -2
  18. package/src/vendor/linear/cli-sync.js +87 -390
  19. package/src/vendor/linear/config.js +46 -171
  20. package/src/vendor/linear/credentials.js +40 -370
  21. package/src/vendor/linear/dialect.js +177 -0
  22. package/src/vendor/linear/doctor.js +7 -15
  23. package/src/vendor/linear/identity.js +20 -70
  24. package/src/vendor/linear/released.js +4 -222
  25. package/src/vendor/{sync-core/src → linear}/sanitise.js +4 -3
  26. package/src/vendor/provider-kit/index.js +41 -0
  27. package/src/vendor/provider-kit/src/adapter.js +23 -0
  28. package/src/vendor/provider-kit/src/apply.js +197 -0
  29. package/src/vendor/provider-kit/src/args.js +68 -0
  30. package/src/vendor/provider-kit/src/config.js +198 -0
  31. package/src/vendor/provider-kit/src/credentials.js +404 -0
  32. package/src/vendor/provider-kit/src/doctor.js +35 -0
  33. package/src/vendor/provider-kit/src/http.js +44 -0
  34. package/src/vendor/provider-kit/src/identity.js +93 -0
  35. package/src/vendor/provider-kit/src/md-compare.js +39 -0
  36. package/src/vendor/{sync-core/src/tables.js → provider-kit/src/md-tables.js} +10 -18
  37. package/src/vendor/provider-kit/src/prompt.js +50 -0
  38. package/src/vendor/provider-kit/src/released.js +226 -0
  39. package/src/vendor/provider-kit/src/specs.js +166 -0
  40. package/src/vendor/provider-kit/src/transport.js +22 -0
  41. package/src/vendor/sync-core/index.js +22 -5
  42. package/src/vendor/sync-core/src/compare.js +14 -12
  43. package/src/vendor/sync-core/src/dialect.js +51 -0
  44. package/src/vendor/sync-core/src/fields.js +36 -0
  45. package/src/vendor/sync-core/src/legacy.js +19 -9
  46. package/src/vendor/sync-core/src/normalize.js +30 -158
  47. package/src/vendor/sync-core/src/push.js +1 -1
  48. package/src/vendor/sync-core/src/retarget.js +21 -17
  49. package/src/vendor/sync-core/src/verify.js +24 -45
  50. package/src/vendor/sync-core/src/write.js +7 -5
package/src/env/hotfix.js CHANGED
@@ -39,6 +39,113 @@ 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
+ //
118
+ // Under `patch`, a base that is ITSELF a `-hotfix.N` tag continues that line.
119
+ // Bumping its patch takes X.Y.(Z+1), a number the mainline owns: refused when
120
+ // the mainline already cut it, and minted silently when it had not. Only a
121
+ // parsed hotfix suffix routes here; an rc or any other suffix keeps the patch
122
+ // bump, so a base we cannot read as a hotfix line is never treated as one.
123
+ function nextTag(baseTag, existingTags, bump = 'patch') {
124
+ if (bump === 'patch') {
125
+ const base = parseTag(baseTag)
126
+ if (base && base.hotfix !== null) return nextHotfixTag(baseTag, existingTags)
127
+ return bumpPatch(baseTag)
128
+ }
129
+ if (bump === 'hotfix-suffix') return nextHotfixTag(baseTag, existingTags)
130
+ throw new Error(`unknown hotfix.bump "${bump}" — use one of: ${BUMPS.join(', ')}`)
131
+ }
132
+
133
+ // What a collision refusal offers: the free tag on the same base's hotfix
134
+ // line, which is never taken by a mainline release. Never a deletion and never
135
+ // another base — the first destroys a released tag, the second forks from a
136
+ // version prod is not running. Empty where the suffix line cannot be derived
137
+ // (an rc base) or is already the strategy, so the refusal just names the tag.
138
+ function freeTagHint(baseTag, existingTags, bump) {
139
+ if (bump !== 'patch') return ''
140
+ let free
141
+ try {
142
+ free = nextHotfixTag(baseTag, existingTags)
143
+ } catch {
144
+ return ''
145
+ }
146
+ return ` — set hotfix.bump "hotfix-suffix" in env.config.json to cut ${free} instead`
147
+ }
148
+
42
149
  // A filesystem/branch-safe slug derived from a tag (`v30.2.1` → `v30-2-1`).
43
150
  function tagSlug(tag) {
44
151
  return String(tag)
@@ -50,7 +157,11 @@ function tagSlug(tag) {
50
157
  * @param {object} spec resolved hotfix spec: { slug, branch, worktreePath, baseRef, ... }
51
158
  * @param {object} config normalised env config (reads `config.hotfix`).
52
159
  * @param {object} ctx { worktreeState:{dirty}, aheadOfBase, fixRange, mainRepoPath,
53
- * base, extraTargets: string[], existingTags: string[] }
160
+ * base, extraTargets: string[], existingTags: string[],
161
+ * released?, push?: boolean, pushed?: boolean, remote?,
162
+ * fixCommits?: string[],
163
+ * carry?: { strategy: 'inplace'|'worktree'|'dirty', path,
164
+ * tmpPath?, commits: string[] } }
54
165
  * @returns {object} { blocked, noop, reason, commands, afterLand, prodTag, targets, branch, base }
55
166
  */
56
167
  function planHotfixLand(spec, config, ctx) {
@@ -63,6 +174,7 @@ function planHotfixLand(spec, config, ctx) {
63
174
  noop: false,
64
175
  reason: null,
65
176
  commands: [],
177
+ steps: [],
66
178
  afterLand: afterLandFor(null),
67
179
  prodTag: null,
68
180
  targets: [],
@@ -88,26 +200,81 @@ function planHotfixLand(spec, config, ctx) {
88
200
  // between the prod tag and a target tag).
89
201
  const taken = new Set(c.existingTags || [])
90
202
  const fixRange = c.fixRange
203
+ // What a target cherry-picks: the fix commits by sha when the caller listed
204
+ // them (the version commit already left out), else the bare range. The
205
+ // range form is what this planner always emitted and what pure callers that
206
+ // list nothing still get.
207
+ const fixPick = Array.isArray(c.fixCommits) && c.fixCommits.length ? c.fixCommits : [fixRange]
91
208
  const commands = []
92
209
  const targets = []
210
+ // What the engine runs (hotfixland.js). `commands` stays beside it as the
211
+ // human-readable spelling of the same thing, for `--plan` and the tests.
212
+ const steps = []
213
+ const bump = hotfixCfg.bump || 'patch'
214
+ const releaseWith = String(hotfixCfg.releaseWith || '').trim()
93
215
 
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`)
216
+ // 1. Prod line: release the hotfix branch head (already baseRef + fix). No push.
217
+ // Three ways, decided here so the runner never has to: a release already
218
+ // cut on an earlier run and still at HEAD is reused, never re-cut; a
219
+ // project's `releaseWith` command cuts it and says which tag it made; or
220
+ // the built-in tagger tags HEAD with the `hotfix.bump` strategy's tag.
221
+ let prodTag = null
222
+ if (c.released && c.released.tag) {
223
+ prodTag = c.released.tag
224
+ taken.add(prodTag)
225
+ steps.push({ kind: 'release', via: 'recorded', tag: prodTag, release: c.released })
226
+ } else if (releaseWith) {
227
+ // The tag is the command's to choose and is unknown until it has run, so
228
+ // there is nothing to check a collision against here — the command refuses
229
+ // a tag that exists, and the runner refuses one a target also planned.
230
+ commands.push(`(cd ${spec.worktreePath} && ${releaseWith})`)
231
+ steps.push({ kind: 'release', via: 'command', command: releaseWith, cwd: spec.worktreePath })
232
+ } else {
233
+ prodTag = nextTag(baseRef, c.existingTags, bump)
234
+ if (taken.has(prodTag)) {
235
+ return block(`tag ${prodTag} already exists${freeTagHint(baseRef, c.existingTags, bump)}`)
236
+ }
237
+ taken.add(prodTag)
238
+ commands.push(`git -C ${spec.worktreePath} tag ${prodTag}`)
239
+ steps.push({
240
+ kind: 'release',
241
+ via: 'tag',
242
+ tag: prodTag,
243
+ cwd: spec.worktreePath,
244
+ baseTag: baseRef,
245
+ branch,
246
+ })
98
247
  }
99
- taken.add(prodTag)
100
- commands.push(`git -C ${spec.worktreePath} tag ${prodTag}`)
101
248
  targets.push({ kind: 'prod', base: baseRef, tag: prodTag })
102
249
 
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
250
+ // 2. Publish the prod line: the branch first, then the tag, because the tag
251
+ // push is what starts the deploy. BEFORE anything is carried to main, so a
252
+ // declined or failed push never leaves main carrying a fix whose tag was
253
+ // never published. Three cases: the tag is already on the remote (a
254
+ // hand-run push, honoured on its positive signal); the operator consented
255
+ // (`--push`); or neither, and the run holds here with the commands printed.
256
+ const remote = c.remote || 'origin'
257
+ if (c.pushed) {
258
+ steps.push({ kind: 'push', via: 'remote', remote, branch, cwd: spec.worktreePath })
259
+ } else if (c.push) {
260
+ steps.push({ kind: 'push', via: 'push', remote, branch, cwd: spec.worktreePath })
261
+ } else {
262
+ steps.push({ kind: 'push', via: 'hold', remote, branch, cwd: spec.worktreePath })
263
+ }
264
+
265
+ // 3. Extra targets: cherry-pick the fix onto a throwaway worktree at each tag,
266
+ // re-tag with its own bump, then remove the worktree + temp branch (the
105
267
  // commits survive under the new tag, so `-D` is safe for the throwaway branch).
268
+ // TAG-ONLY, deliberately: `releaseWith` is the prod line's. Running a
269
+ // project's release per target would need a hotfix/ branch and a clean
270
+ // tree for each one, and one failing half-way leaves a line half-released.
106
271
  const wtRoot = path.dirname(spec.worktreePath)
107
272
  for (const t of c.extraTargets || []) {
108
- const tag = bumpPatch(t)
273
+ // Counted against `taken`, so two targets on one root get successive
274
+ // hotfix numbers rather than colliding on the same one.
275
+ const tag = nextTag(t, [...taken], bump)
109
276
  if (taken.has(tag)) {
110
- return block(`tag ${tag} (for target ${t}) already exists — resolve it before landing`)
277
+ return block(`tag ${tag} (for target ${t}) already exists${freeTagHint(t, [...taken], bump)}`)
111
278
  }
112
279
  taken.add(tag)
113
280
  const slug = `${spec.slug}-onto-${tagSlug(t)}`
@@ -115,25 +282,130 @@ function planHotfixLand(spec, config, ctx) {
115
282
  const tmpPath = path.join(wtRoot, slug)
116
283
  commands.push(
117
284
  `git worktree add ${tmpPath} -b ${tmpBranch} ${t}`,
118
- `git -C ${tmpPath} cherry-pick ${fixRange}`,
285
+ `git -C ${tmpPath} cherry-pick ${fixPick.join(' ')}`,
119
286
  `git -C ${tmpPath} tag ${tag}`,
120
287
  `git worktree remove ${tmpPath}`,
121
288
  `git branch -D ${tmpBranch}`,
122
289
  )
290
+ const root = c.mainRepoPath
291
+ steps.push({
292
+ kind: 'target',
293
+ base: t,
294
+ tag,
295
+ worktreePath: tmpPath,
296
+ argvs: [
297
+ ['-C', root, 'worktree', 'add', tmpPath, '-b', tmpBranch, t],
298
+ ['-C', tmpPath, 'cherry-pick', ...fixPick],
299
+ ['-C', tmpPath, 'tag', tag],
300
+ ['-C', root, 'worktree', 'remove', tmpPath],
301
+ ['-C', root, 'branch', '-D', tmpBranch],
302
+ ],
303
+ })
123
304
  targets.push({ kind: 'extra', base: t, tag, worktreePath: tmpPath })
124
305
  }
125
306
 
126
- // 3. Cherry-pick the fix onto the base branch (main) for the next release.
307
+ // 4. Cherry-pick the fix onto the base branch (main) for the next release.
127
308
  // Only then does the primary checkout gain anything, so only then do the
128
309
  // after-land commands apply — a prod-only land leaves main untouched.
129
310
  let afterLand = result.afterLand
130
311
  if (hotfixCfg.cherryPickMain !== false) {
131
- commands.push(`git -C ${c.mainRepoPath} cherry-pick ${fixRange}`)
312
+ // THE CARRY IS A LIST OF COMMITS, NOT A RANGE. A releasing command leaves
313
+ // a version commit on the branch (package.json, CHANGELOG, RELEASES), and
314
+ // main's version line never moves on a hotfix — so the caller hands over
315
+ // `baseRef..branch` minus that commit and minus what `git cherry` says main
316
+ // already has. The spec's own completion commits stay in it: that is how
317
+ // the completed spec reaches main. Without a list (pure callers), the old
318
+ // range form, run in place.
319
+ const carry = c.carry || { strategy: 'inplace', path: c.mainRepoPath, commits: null }
320
+ const picks = carry.commits || [fixRange]
321
+ commands.push(
322
+ carry.strategy === 'worktree'
323
+ ? `git worktree add ${carry.tmpPath} ${c.base} && git -C ${carry.tmpPath} cherry-pick ${picks.join(' ')}`
324
+ : `git -C ${carry.path} cherry-pick ${picks.join(' ')}`,
325
+ )
326
+ steps.push({
327
+ kind: 'carry',
328
+ base: c.base,
329
+ strategy: carry.strategy,
330
+ cwd: carry.path || c.mainRepoPath,
331
+ root: c.mainRepoPath,
332
+ tmpPath: carry.tmpPath || null,
333
+ commits: picks,
334
+ })
132
335
  targets.push({ kind: 'main', base: c.base })
133
336
  afterLand = afterLandFor(config, c.mainRepoPath)
134
337
  }
135
338
 
136
- return { ...result, commands, afterLand, prodTag, targets, fixRange }
339
+ return { ...result, commands, steps, afterLand, prodTag, targets, fixRange }
137
340
  }
138
341
 
139
- module.exports = { bumpPatch, tagSlug, planHotfixLand }
342
+ /**
343
+ * Plan `spec-env hotfix finish`: the teardown a hotfix waits for until its
344
+ * deploy is out.
345
+ *
346
+ * A hotfix branch is needed until the release it cut is confirmed — a failed
347
+ * deploy cuts the next `-hotfix.N` from the same branch — so `/spec-complete`
348
+ * lands and keeps the worktree, and this is the later step that removes it.
349
+ *
350
+ * THREE GUARDS, every one a positive signal, and every failing one named:
351
+ * - a clean tree — anything uncommitted would go with the worktree;
352
+ * - a release tag at HEAD — the land actually released what is here;
353
+ * - the branch on the remote at HEAD — a copy exists after `branch -D`.
354
+ * A remote that cannot be asked is "cannot tell", which refuses: deleting
355
+ * the only copy of a deployed fix is not the safe way to be wrong.
356
+ *
357
+ * DELIBERATELY NO "MERGED INTO MAIN" GUARD: the version commit never reaches
358
+ * main, so the branch is never an ancestor of it and `-d` would always refuse.
359
+ * And DELIBERATELY NO `--force` — the guards are the point of the verb, and
360
+ * `spec-env down --force` already exists for anyone who means to override them.
361
+ *
362
+ * state: { dirty, tagsAtHead: string[], head, remoteHead: string|null|undefined,
363
+ * remote, mainRepoPath, hasSlot }
364
+ * remoteHead: the branch's sha on the remote; null = not there;
365
+ * undefined = the remote could not be asked.
366
+ */
367
+ function planHotfixFinish(spec, state) {
368
+ const s = state || {}
369
+ const remote = s.remote || 'origin'
370
+ const reasons = []
371
+ if (s.dirty) reasons.push('the worktree has uncommitted changes')
372
+ const releaseTag = (s.tagsAtHead || []).find((t) => parseTag(t) !== null) || null
373
+ if (!releaseTag) {
374
+ reasons.push('no release tag at HEAD — run `spec-env hotfix land` first')
375
+ }
376
+ if (s.remoteHead === undefined) {
377
+ reasons.push(`cannot tell whether ${spec.branch} is on ${remote} — the remote did not answer`)
378
+ } else if (s.remoteHead === null) {
379
+ reasons.push(`${spec.branch} is not on ${remote} — push it (\`hotfix land --push\`)`)
380
+ } else if (s.head && s.remoteHead !== s.head) {
381
+ reasons.push(`${remote}/${spec.branch} is not at HEAD — push the branch first`)
382
+ }
383
+ // A Docker stack has volumes and a slot that only `down` knows how to free.
384
+ if (s.hasSlot) {
385
+ reasons.push(`${spec.folder} holds a Docker stack — tear it down with \`spec-env down\``)
386
+ }
387
+ if (reasons.length) return { blocked: true, reasons, releaseTag, argvs: [] }
388
+ const root = s.mainRepoPath
389
+ return {
390
+ blocked: false,
391
+ reasons: [],
392
+ releaseTag,
393
+ argvs: [
394
+ ['-C', root, 'worktree', 'remove', spec.worktreePath],
395
+ // -D, not -d: the branch is never merged into main (see above), and its
396
+ // commits are on the remote and under the release tag.
397
+ ['-C', root, 'branch', '-D', spec.branch],
398
+ ],
399
+ }
400
+ }
401
+
402
+ module.exports = {
403
+ bumpPatch,
404
+ compareTags,
405
+ nextHotfixTag,
406
+ nextTag,
407
+ BUMPS,
408
+ tagSlug,
409
+ planHotfixLand,
410
+ planHotfixFinish,
411
+ }
@@ -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 }