@skitterbyte/skitterspec-linear 18.3.0 → 19.0.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.
@@ -58,12 +58,12 @@ function specIssueHash(p) {
58
58
 
59
59
  // Per-field hashes of the same two values.
60
60
  //
61
- // They are hashed SEPARATELY because they have different owners once a spec is
62
- // finished. The repo owns the description forever, but the workflow state is
63
- // handed off: a deploy pipeline (see `release.stages`) moves the issue past
64
- // `complete`, and welding the two meant any prose edit re-emitted the state and
65
- // dragged the issue back. Diffing them apart is what lets a push touch the
66
- // description without re-asserting a state someone else now owns.
61
+ // They are hashed SEPARATELY because skitterspec tells the tracker about its
62
+ // own transitions and nothing else. The description is resent whenever it
63
+ // changes; the state only when the spec itself moves. Welding the two meant any
64
+ // prose edit re-emitted the state and dragged back an issue someone had moved
65
+ // on the tracker — which is theirs to do. Diffing them apart is what lets a
66
+ // push touch the description without re-asserting a state.
67
67
  function specIssueFieldHashes(p, config) {
68
68
  const hashes = {
69
69
  description: hashField(p.description ?? null),
@@ -751,39 +751,27 @@ function phasesWithheld(snapshotDir, config) {
751
751
 
752
752
  // --- remote projection ------------------------------------------------------
753
753
 
754
- // The lifecycle bucket a deployment ladder descends FROM. A spec is handed over
755
- // to the deploy pipeline once it is finished, so every rung sits downstream of
756
- // `complete` — a ticket on "On Test" is a completed spec that has been deployed,
757
- // not a spec that moved somewhere else.
758
- const LADDER_ORIGIN_BUCKET = 'complete'
759
-
760
- // The declared ladder rung with this state name, or null.
761
- function stageForState(state, config) {
762
- if (state == null) return null
763
- const want = String(state).toLowerCase().trim()
764
- const stages = (config && config.release && config.release.stages) || []
765
- if (!Array.isArray(stages)) return null
766
- return stages.find((s) => s && typeof s.state === 'string' && s.state.toLowerCase().trim() === want) || null
754
+ // Every tracker state NAME that means this bucket: the one push writes
755
+ // (`states[bucket]`) first, then its read-only aliases (`stateAliases[bucket]`,
756
+ // from the array form of `states`). Readers use the whole list; writers only
757
+ // ever use `states[bucket]`, so an alias can never be written.
758
+ function stateNamesFor(bucket, config) {
759
+ const primary = config && config.states && config.states[bucket]
760
+ const aliases = (config && config.stateAliases && config.stateAliases[bucket]) || []
761
+ return [primary, ...(Array.isArray(aliases) ? aliases : [])].filter((n) => typeof n === 'string' && n)
767
762
  }
768
763
 
769
764
  // Map a remote workflow-state name back to the local lifecycle bucket (the
770
765
  // vocabulary `spec_status` uses) via config.states, so local and remote
771
766
  // workflowState hash equal when semantically equal. Falls back to a lowercased
772
767
  // raw value when the state isn't one of the configured names.
773
- //
774
- // A DECLARED DEPLOYMENT STAGE reads as `complete`, deliberately. Without this
775
- // the fallback lowercases it — "On Test" becomes "on test", which equals no
776
- // bucket — and every deployed spec reports as drifted forever, for the whole
777
- // time it sits in the pipeline. The project told us these states are downstream
778
- // of a finished spec, so they are not a disagreement about where the spec is.
779
768
  function bucketForState(state, config) {
780
769
  if (state == null) return null
781
770
  const states = (config && config.states) || {}
782
771
  const want = String(state).toLowerCase().trim()
783
- for (const [bucket, name] of Object.entries(states)) {
784
- if (typeof name === 'string' && name.toLowerCase().trim() === want) return bucket
772
+ for (const bucket of Object.keys(states)) {
773
+ if (stateNamesFor(bucket, config).some((name) => name.toLowerCase().trim() === want)) return bucket
785
774
  }
786
- if (stageForState(state, config)) return LADDER_ORIGIN_BUCKET
787
775
  return want
788
776
  }
789
777
 
@@ -818,11 +806,20 @@ function remoteWorkflowState(issue, config) {
818
806
  return name != null ? bucketForState(name, config) : null
819
807
  }
820
808
 
821
- // The declared ladder rung a remote issue is currently sitting on, or null.
822
- // Pairs with `remoteWorkflowState`: that says which bucket the issue maps to,
823
- // this says whether it got there by being deployed. Read-only.
824
- function remoteStage(issue, config) {
825
- return stageForState(remoteStateName(issue || {}, config), config)
809
+ // What the drift report needs to know about a remote issue's state: its name,
810
+ // the bucket it maps to, and whether it maps to one at all. Null when the
811
+ // payload carried no state — a cannot-tell, never an answer.
812
+ //
813
+ // AN UNMAPPED STATE IS NOT A DISAGREEMENT. A tracker grows states skitterspec
814
+ // never names ("Blocked", "Next Sprint"), and a ticket a person moved into one
815
+ // is not wrong about the spec — it is somewhere push does not manage, and push
816
+ // will not move it until the spec itself moves. `mapped` is what lets a report
817
+ // say that rather than accuse it.
818
+ function remoteStateReading(issue, config) {
819
+ const name = remoteStateName(issue || {}, config)
820
+ if (name == null) return null
821
+ const bucket = bucketForState(name, config)
822
+ return { name: String(name), bucket, mapped: LIFECYCLE_BUCKETS.includes(bucket) }
826
823
  }
827
824
 
828
825
  // A Linear issue title is plain text, so markdown emphasis is noise there — and
@@ -897,24 +894,16 @@ function titleFromText(text, max = 100) {
897
894
  return stripTitleMarkup(title)
898
895
  }
899
896
 
900
- // Every state NAME the config points at: the lifecycle bucket map, plus the
901
- // project's deployment ladder when it declares one. Both reach Linear the same
902
- // way and fail the same way, so both are checked by the same lookup.
897
+ // Every state NAME the config points at: the lifecycle bucket map.
903
898
  function configuredStateNames(config) {
904
- const names = Object.values((config && config.states) || {}).filter((v) => typeof v === 'string')
905
- const stages = (config && config.release && config.release.stages) || []
906
- for (const stage of Array.isArray(stages) ? stages : []) {
907
- if (stage && typeof stage.state === 'string') names.push(stage.state)
908
- }
909
- return names
899
+ // The WRITTEN names only. An alias is never written, so one the workspace
900
+ // lacks cannot strand a push; `stateSuggestions` still names it in reports.
901
+ return Object.values((config && config.states) || {}).filter((v) => typeof v === 'string')
910
902
  }
911
903
 
912
904
  // Which configured state NAMES are absent from the live workspace. The skill
913
905
  // fetches the workspace's project-status names over MCP and passes them here;
914
906
  // a non-empty result means a typo/rename that Linear would silently no-op.
915
- //
916
- // A project with no `release.stages` contributes nothing here, so the ladder
917
- // cannot make this accuse a config that was fine before it existed.
918
907
  function validateStates(config, workspaceStates) {
919
908
  const configured = configuredStateNames(config)
920
909
  const have = new Set((workspaceStates || []).map((s) => String(s).toLowerCase().trim()))
@@ -953,21 +942,6 @@ function stateSuggestions(config, workspaceStates) {
953
942
  const suggestion = names.find((n) => words.includes(n.toLowerCase().trim())) || null
954
943
  out.push({ bucket, configured, suggestion, label: `states.${bucket}` })
955
944
  }
956
- // Deployment-ladder rungs, reported the same way. No suggestion is offered:
957
- // BUCKET_WORDS describes lifecycle vocabulary, and a stage name is the
958
- // project's own — guessing "On Test" meant "In Progress" would be worse than
959
- // saying nothing.
960
- const stages = (config && config.release && config.release.stages) || []
961
- for (const stage of Array.isArray(stages) ? stages : []) {
962
- if (!stage || typeof stage.state !== 'string') continue
963
- if (have.has(stage.state.toLowerCase().trim())) continue
964
- out.push({
965
- bucket: null,
966
- configured: stage.state,
967
- suggestion: null,
968
- label: `release.stages[${stage.key}]`,
969
- })
970
- }
971
945
  return out
972
946
  }
973
947
 
@@ -991,8 +965,7 @@ module.exports = {
991
965
  canonicalRemoteStatus,
992
966
  bucketForState,
993
967
  LIFECYCLE_BUCKETS,
994
- stageForState,
995
- remoteStage,
996
968
  remoteWorkflowState,
997
- LADDER_ORIGIN_BUCKET,
969
+ remoteStateReading,
970
+ stateNamesFor,
998
971
  }
@@ -1,110 +0,0 @@
1
- # Wiring a deploy pipeline to Linear
2
-
3
- How a CI/CD pipeline moves a release's tickets along the ladder declared in
4
- `linear.config.json` → `release.stages`. Read `linear.config.md` → "The
5
- deployment ladder" first for the config itself; this page is the pipeline half.
6
-
7
- Nothing here applies until a ladder is declared. Without one, `spec-sync stage`
8
- refuses and every other command behaves as it always has.
9
-
10
- ## The model
11
-
12
- A spec's lifecycle ends at `complete`. Everything after that is a fact about an
13
- **environment**, which no folder under `specs/` can derive — so the repo hands
14
- off. The handoff point is one-way and automatic:
15
-
16
- ```
17
- /spec-complete → states.complete (the repo's last word on state)
18
- CI: spec-sync stage test → release.stages test (the pipeline's, from here on)
19
- CI: spec-sync stage prod → release.stages prod
20
- ```
21
-
22
- Once a spec is complete, pushes stop re-asserting its workflow state, so the
23
- pipeline is the only writer. Editing a finished spec's prose still updates the
24
- mirror's description; it will not drag the ticket back out of the pipeline.
25
-
26
- ## What a stage step runs
27
-
28
- ```sh
29
- skitterspec spec-sync stage <key> <previous-tag>..<this-tag> --apply
30
- ```
31
-
32
- - **Pass the range explicitly.** With no range it defaults to
33
- `git describe --tags --abbrev=0`..HEAD, which is a developer convenience — a
34
- pipeline knows exactly which tag it is deploying, and should say so. The
35
- resolved range is printed on every run either way.
36
- - **Drop `--apply` to dry-run.** Same output, no writes. Worth running in a
37
- pre-deploy job.
38
- - **`--json`** for a machine-readable result: the moves, the skips by category,
39
- and the commit counts.
40
- - **Exit code is 0 unless a write failed**, so a failed move fails the stage.
41
- A range with nothing to move is a success, not a failure.
42
-
43
- The tickets come from `Refs:` trailers on the commits in the range (see the
44
- `commit-trailers` rule). A commit with no trailer is counted and reported, never
45
- guessed at.
46
-
47
- ## Setup
48
-
49
- 1. **A ladder in `linear.config.json`** — via `/spec-linear-setup`, or
50
- `spec-sync init-config --stage test="On Test" --stage prod="Done"`.
51
- 2. **An API key as a pipeline secret**, exposed as the env var named by
52
- `auth.keyEnv` (default `LINEAR_API_KEY`). The config names the *variable*,
53
- never the key. `--apply` needs the API transport and refuses over MCP.
54
- 3. **Full history for the range** (CI: `fetch-depth: 0`). Fetching tags is not
55
- enough on its own: it makes the tag *resolve* without deepening the history,
56
- so `git log <tag>..HEAD` would return only the commits the clone happens to
57
- hold. `stage` and `released` check this and **refuse** rather than report a
58
- partial range, so a shallow checkout fails the step loudly instead of
59
- deploying a release that quietly leaves tickets behind.
60
- 4. **Run `spec-sync doctor --check-remote` once** after setup. It reports the
61
- ladder's rungs against the workspace and warns if the last rung never closes
62
- an issue.
63
-
64
- ### Azure Pipelines
65
-
66
- ```yaml
67
- - task: Bash@3
68
- displayName: Mark tickets as deployed to test
69
- env:
70
- LINEAR_API_KEY: $(LinearApiKey) # a secret variable, not inline
71
- inputs:
72
- targetType: inline
73
- script: |
74
- set -euo pipefail
75
- npx skitterspec spec-sync stage test "$(PreviousTag)..$(Build.SourceBranchName)" --apply
76
- ```
77
-
78
- Repeat per environment with a different `<key>`: a post-deploy step on the test
79
- stage runs `stage test`, the demo approval gate runs `stage demo`, the production
80
- deploy runs `stage prod`.
81
-
82
- ## Why not call the API directly
83
-
84
- A hand-rolled `curl` to Linear's GraphQL endpoint loses three things this command
85
- has, and the loss is silent in all three cases:
86
-
87
- - **State-name validation.** Linear **silently ignores** an unknown workflow
88
- state: the mutation succeeds, and the issue never moves. `stage` resolves the
89
- target state before its first write and refuses if the workspace lacks it.
90
- - **The skip rules.** A range carries refs that must not be moved — another
91
- team's, ones no spec claims, and specs that have not finished. A blanket loop
92
- over every ref in the log moves all of them.
93
- - **Retries and error classification.** The adapter retries transient failures;
94
- a bare `curl` reports a 500 as success if you forget to check.
95
-
96
- ## What it will not move, and why
97
-
98
- Every skipped ref is named in the output with its reason — a silent exclusion and
99
- a successful move look identical in a pipeline log.
100
-
101
- | Skipped | Reason |
102
- |---|---|
103
- | another team's ref | not `linear.teamKey`; writing to an unconfigured team is the worst failure available here |
104
- | no spec claims it | tracker-only work, or a typo in a trailer — nothing here can tell which |
105
- | spec not complete | it landed via `/spec-to-main`; push still owns its state and would bounce it back |
106
- | unreadable | Linear did not return the issue; dropped rather than guessed at |
107
-
108
- A move that runs against the declared order — backwards, or skipping a rung —
109
- **warns and proceeds**. A rollback from test and a hotfix going straight to prod
110
- are both legitimate, and refusing either would be wrong on healthy input.
@@ -1,380 +0,0 @@
1
- 'use strict'
2
-
3
- /**
4
- * The release seam — `spec-sync release create | deployed | complete`.
5
- *
6
- * A release today is a git tag and nothing more, while `released` already
7
- * knows exactly which tickets a tag contains. These verbs write that down where
8
- * people look: a release object on the tracker holding its tickets, which the
9
- * host project's CI moves through its deploy stages.
10
- *
11
- * SKITTERSPEC DECIDES A RELEASE'S CONTENTS, never the tracker. The ticket set
12
- * is `ticketsInRange` + `partitionStageMoves` over previous-tag → this-tag:
13
- * the `Refs:` trailers, bookkeeping commits ignored, foreign refs excluded.
14
- * That is one definition of "what shipped", shared with `released`.
15
- *
16
- * EVERY VERB IS A DRY RUN UNLESS `--apply`. CI passes it; a person reading the
17
- * plan does not have to.
18
- *
19
- * IDEMPOTENT BY LOOKUP, not by memory. `create` finds the release for the tag
20
- * first and updates it; a retry on the same tag never mints a duplicate. A
21
- * lookup that FAILED is a cannot-tell, and refuses rather than creating
22
- * (`.claude/rules/negative-checks.md` rule 4) — creating on "I could not see
23
- * one" is exactly how duplicates are made.
24
- *
25
- * Tracker calls arrive as OPTIONAL adapter ops, feature-detected: a provider
26
- * without them makes every verb refuse in one line. The ops:
27
- *
28
- * - `releaseFind(tag)` → release | null (throws = cannot tell)
29
- * - `releaseCreate({ tag, name, body, prerelease })` → release
30
- * - `releaseUpdate(release, { name, body })`
31
- * - `releaseAttach(release, tickets)` → `{ attached, already }`
32
- * - `releaseStage(release, optionName, tickets)` → `{ set }`
33
- * - `releaseComplete(release)`
34
- * - `releaseTagExists(tag)` OPTIONAL → true | false (throws = cannot tell)
35
- *
36
- * A release object carries at least `{ id, url, body }`.
37
- */
38
-
39
- const { execFileSync } = require('node:child_process')
40
-
41
- const { ticketsInRange, partitionStageMoves, stageOrderWarning } = require('./released.js')
42
-
43
- const REQUIRED_OPS = ['releaseFind', 'releaseCreate', 'releaseUpdate', 'releaseAttach', 'releaseStage', 'releaseComplete']
44
-
45
- // The line a release body carries so the next verb can read where the release
46
- // is without asking anything else. An HTML comment: invisible where the body is
47
- // rendered as markdown, and never confused with prose a person wrote.
48
- const MARKER_RE = /<!--\s*skitterspec:release\s+v1\s+stage=([A-Za-z0-9_.-]*)\s*-->/
49
-
50
- function stageOf(body) {
51
- const m = MARKER_RE.exec(String(body || ''))
52
- return m ? m[1] || null : null
53
- }
54
-
55
- function withStage(body, key) {
56
- const line = `<!-- skitterspec:release v1 stage=${key || ''} -->`
57
- const text = String(body || '')
58
- return MARKER_RE.test(text) ? text.replace(MARKER_RE, line) : `${text.replace(/\s+$/, '')}\n\n${line}\n`
59
- }
60
-
61
- function gitReader(dir) {
62
- return (argv) => {
63
- try {
64
- return execFileSync('git', ['-C', dir, ...argv], { stdio: ['ignore', 'pipe', 'ignore'], encoding: 'utf-8' }).trim()
65
- } catch {
66
- return null
67
- }
68
- }
69
- }
70
-
71
- /**
72
- * The series a tag belongs to: the configured `tagPrefix` it starts with,
73
- * longest first so `skitterspec-github@` is not read as `skitterspec`.
74
- */
75
- function seriesFor(series, tag) {
76
- return (
77
- [...(series || [])]
78
- .filter((s) => s && s.tagPrefix)
79
- .sort((a, b) => b.tagPrefix.length - a.tagPrefix.length)
80
- .find((s) => String(tag).startsWith(s.tagPrefix)) || null
81
- )
82
- }
83
-
84
- /**
85
- * Previous tag in the same series → this tag.
86
- *
87
- * `git describe --match '<prefix>*' <tag>^` walks back from the commit BEFORE
88
- * this tag, so a hotfix tag cut from a release tag ranges from that base, and
89
- * a tag never ranges from itself.
90
- *
91
- * WHAT WOULD FOOL THIS: a shallow clone. `describe` there finds no previous tag
92
- * and the range silently becomes "everything" — every ticket in history landing
93
- * on one release. So shallowness is asked about first, as a positive signal,
94
- * and refused with the fix (CI checkout `fetch-depth: 0`).
95
- */
96
- function resolveRange(dir, tag, prefix, git = gitReader(dir)) {
97
- if (git(['rev-parse', '--is-shallow-repository']) === 'true') {
98
- return {
99
- ok: false,
100
- error: 'this clone is shallow, so the previous tag cannot be found — check out with fetch-depth: 0',
101
- }
102
- }
103
- if (!git(['rev-parse', '--verify', '--quiet', `refs/tags/${tag}`])) {
104
- return { ok: false, error: `no tag ${tag} in this repo` }
105
- }
106
- const previous = git(['describe', '--tags', '--abbrev=0', '--match', `${prefix}*`, `${tag}^`])
107
- if (previous) return { ok: true, range: `${previous}..${tag}`, previous }
108
- return { ok: true, range: tag, previous: null, first: true }
109
- }
110
-
111
- /**
112
- * Compose the release body: the notes, then the issues, then the marker. Pure,
113
- * so a re-run on unchanged inputs produces the same text — which is what lets
114
- * `create` say "no change" rather than rewrite a release on every CI retry.
115
- */
116
- function composeBody({ notes, tickets, links, stage, describe }) {
117
- const parts = []
118
- if (notes && String(notes).trim()) parts.push(String(notes).trim())
119
- if (tickets.length) {
120
- parts.push(['## Issues', '', ...tickets.map((t) => `- ${describe ? describe(t) : t.ref}`)].join('\n'))
121
- }
122
- if (links && links.length) {
123
- parts.push(['## Links', '', ...links.map((l) => `- [${l.label || l.url}](${l.url})`)].join('\n'))
124
- }
125
- return withStage(parts.join('\n\n'), stage)
126
- }
127
-
128
- // `--link <url>[=label]`, repeatable. http(s) only: this lands in a body a
129
- // tracker renders as a link, and a `javascript:` url there is script.
130
- function parseLinks(raw) {
131
- const out = []
132
- const bad = []
133
- for (const item of raw || []) {
134
- const s = String(item)
135
- const eq = s.indexOf('=', s.indexOf('://') + 3)
136
- const url = eq > 0 ? s.slice(0, eq) : s
137
- const label = eq > 0 ? s.slice(eq + 1) : null
138
- if (/^https?:\/\//i.test(url)) out.push({ url, label })
139
- else bad.push(s)
140
- }
141
- return { links: out, bad }
142
- }
143
-
144
- /**
145
- * @param {object} p
146
- * - `tracker` the tracker's name in messages
147
- * - `program` 'spec-sync'
148
- * - `readCommits(dir, range)` → `{ ok, commits | error }` (the provider's `released` reader)
149
- * - `ticketOptions(config)` → the `ticketsInRange` options (ignorePaths, refPattern, …)
150
- * - `teamKey(config)` → the foreign-ref key for `partitionStageMoves` ('' for none)
151
- * - `listSpecs(dir, config)` → `[{ identifier, bucket, spec }]`
152
- * - `series(config)` → `[{ tagPrefix, envs: { key: optionName } }]`
153
- * - `adapterFor(config, flags)` → `{ ok, adapter | error }`
154
- * - `describe(ticket)` OPTIONAL → the issue line in the body
155
- * - `impossibleOverMcp` OPTIONAL — the transport answer for a provider whose
156
- * MCP server cannot write releases; `(config, flags) → string | null`
157
- */
158
- function makeReleaseCommands(p) {
159
- const prog = `${p.program || 'spec-sync'} release`
160
-
161
- function refuse(out, msg) {
162
- out.write(`${prog}: ${msg}\n`)
163
- return 1
164
- }
165
-
166
- // Everything a verb needs before touching the tracker, refused in one line
167
- // each so CI logs say exactly what was missing.
168
- function prepare(dir, config, tagArg, flags, out) {
169
- if (!tagArg) return { code: refuse(out, 'pass the tag, e.g. skitterspec@1.4.0') }
170
- const series = p.series(config)
171
- if (!series.length) return { code: refuse(out, `no releases.series configured — add one to the ${p.tracker} config`) }
172
- let tag = String(tagArg)
173
- // A bare version is accepted when exactly one series is configured — the
174
- // common single-package repo — and refused otherwise rather than guessed.
175
- if (!seriesFor(series, tag)) {
176
- if (series.length === 1 && /^v?\d/.test(tag)) tag = `${series[0].tagPrefix}${tag}`
177
- else return { code: refuse(out, `${tag} matches no releases.series tagPrefix (${series.map((s) => s.tagPrefix).join(', ')})`) }
178
- }
179
- const s = seriesFor(series, tag)
180
- if (p.impossibleOverMcp) {
181
- const why = p.impossibleOverMcp(config, flags)
182
- if (why) return { code: refuse(out, why) }
183
- }
184
- const got = p.adapterFor(config, flags)
185
- if (!got.ok) return { code: refuse(out, got.error) }
186
- const missing = REQUIRED_OPS.filter((op) => typeof got.adapter[op] !== 'function')
187
- if (missing.length) return { code: refuse(out, `the ${p.tracker} provider has no release support (${missing.join(', ')})`) }
188
- return { tag, series: s, adapter: got.adapter }
189
- }
190
-
191
- // The tickets a tag's range contains, split into what the release holds and
192
- // what it reports. Recomputed by every verb — stateless, so `deployed` and
193
- // `complete` act on the same set `create` attached without storing it.
194
- function ticketsOf(dir, config, tag, s) {
195
- const range = resolveRange(dir, tag, s.tagPrefix)
196
- if (!range.ok) return range
197
- const read = p.readCommits(dir, range.range)
198
- if (!read.ok) return { ok: false, error: read.error }
199
- const report = ticketsInRange(read.commits, p.ticketOptions(config))
200
- const parts = partitionStageMoves({ tickets: report.tickets, teamKey: p.teamKey(config), specs: p.listSpecs(dir, config) })
201
- // Movable AND unfinished: code that landed via /spec-to-main really is in
202
- // this release. Attaching never touches workflow state — push owns that.
203
- const attach = [...parts.movable, ...parts.unfinished]
204
- return { ok: true, range, report, parts, attach }
205
- }
206
-
207
- function planLines(t, tag) {
208
- const lines = [
209
- ` range: ${t.range.range}${t.range.first ? ' (no previous release in this series — everything up to the tag)' : ''}`,
210
- ` attach: ${t.attach.map((x) => x.ref).join(', ') || 'none'}`,
211
- ]
212
- if (t.parts.unfinished.length) lines.push(` (in flight: ${t.parts.unfinished.map((x) => x.ref).join(', ')} — attached, state left to push)`)
213
- if (t.parts.foreign.length) lines.push(` foreign: ${t.parts.foreign.map((x) => x.ref).join(', ')} — not attached`)
214
- if (t.parts.unlinked.length) lines.push(` unlinked: ${t.parts.unlinked.map((x) => x.ref).join(', ')} — no spec claims them, not attached`)
215
- lines.push(` ${t.report.unreferenced} commit(s) carry no Refs: trailer${t.report.ignored ? `, ${t.report.ignored} bookkeeping ignored` : ''}`)
216
- // Without this line a range from before a tracker move reads as mostly
217
- // missing: those commits are neither unreferenced nor attached.
218
- if (t.report.historical) lines.push(` ${t.report.historical} commit(s) reference an earlier tracker — not attached`)
219
- return lines
220
- }
221
-
222
- async function find(adapter, tag, out) {
223
- try {
224
- return { ok: true, release: await adapter.releaseFind(tag) }
225
- } catch (error) {
226
- refuse(out, `could not look up the release for ${tag} (${String(error.message).split('\n')[0]}) — refusing rather than risk a duplicate`)
227
- return { ok: false }
228
- }
229
- }
230
-
231
- async function create(dir, config, tagArg, flags, out) {
232
- const prep = prepare(dir, config, tagArg, flags, out)
233
- if (prep.code != null) return prep.code
234
- const { tag, series: s, adapter } = prep
235
- const t = ticketsOf(dir, config, tag, s)
236
- if (!t.ok) return refuse(out, t.error)
237
- const { links, bad } = parseLinks(flags.links)
238
- if (bad.length) return refuse(out, `--link must be http(s): ${bad.join(', ')}`)
239
- let notes = null
240
- if (flags.notes) {
241
- try {
242
- notes = require('node:fs').readFileSync(flags.notes, 'utf-8')
243
- } catch (error) {
244
- return refuse(out, `cannot read --notes: ${error.message}`)
245
- }
246
- }
247
- const envKeys = Object.keys(s.envs || {})
248
- const stage = flags.stage || envKeys[0] || null
249
- if (stage && envKeys.length && !envKeys.includes(stage)) {
250
- return refuse(out, `--stage ${stage} is not an env of ${s.tagPrefix} (${envKeys.join(', ')})`)
251
- }
252
-
253
- // A tracker that would CREATE a missing tag from the default branch must
254
- // not be handed one it has not got — the release would point at the wrong
255
- // commit. Positive signals only: `false` refuses, a throw is a cannot-tell
256
- // and the create goes ahead exactly as it would have.
257
- if (adapter.releaseTagExists) {
258
- let exists = null
259
- try {
260
- exists = await adapter.releaseTagExists(tag)
261
- } catch {
262
- exists = null
263
- }
264
- if (exists === false) return refuse(out, `${tag} is not on the ${p.tracker} remote yet — push the tag first`)
265
- }
266
-
267
- const found = await find(adapter, tag, out)
268
- if (!found.ok) return 1
269
- const existing = found.release
270
- // A release already past its first stage keeps the stage it is at: a CI
271
- // retry of `create` must not drag a deployed release back.
272
- const keep = existing ? stageOf(existing.body) : null
273
- const body = composeBody({ notes, tickets: await describeAll(adapter, t.attach), links, stage: keep || stage, describe: p.describe })
274
-
275
- const header = [`${prog} create: ${tag}${flags.apply ? '' : ' (dry run — pass --apply to write)'}`, ...planLines(t, tag)]
276
- if (!flags.apply) {
277
- header.push(` would ${existing ? (existing.body === body ? 'leave the release unchanged' : 'update the release') : 'create the release'}${existing && existing.url ? ` (${existing.url})` : ''}`)
278
- return emit(out, flags, header, { tag, range: t.range.range, attach: t.attach.map((x) => x.ref), apply: false, existing: !!existing })
279
- }
280
- let release = existing
281
- if (!release) {
282
- release = await adapter.releaseCreate({ tag, name: tag, body, prerelease: true })
283
- header.push(` created: ${release.url || release.id}`)
284
- } else if (release.body !== body) {
285
- await adapter.releaseUpdate(release, { name: tag, body })
286
- header.push(` updated: ${release.url || release.id}`)
287
- } else {
288
- header.push(` unchanged: ${release.url || release.id}`)
289
- }
290
- const attached = await adapter.releaseAttach(release, t.attach)
291
- header.push(` issues: ${attached.attached} noted, ${attached.already} already noted`)
292
- return emit(out, flags, header, { tag, range: t.range.range, attach: t.attach.map((x) => x.ref), apply: true, url: release.url || null })
293
- }
294
-
295
- async function deployed(dir, config, tagArg, envKey, flags, out) {
296
- const prep = prepare(dir, config, tagArg, flags, out)
297
- if (prep.code != null) return prep.code
298
- const { tag, series: s, adapter } = prep
299
- const envs = s.envs || {}
300
- if (!envKey || !(envKey in envs)) {
301
- return refuse(out, `pass an env of ${s.tagPrefix}: ${Object.keys(envs).join(', ') || '(none configured)'}`)
302
- }
303
- const found = await find(adapter, tag, out)
304
- if (!found.ok) return 1
305
- if (!found.release) return refuse(out, `no release for ${tag} yet — run \`release create ${tag}\` first`)
306
- const t = ticketsOf(dir, config, tag, s)
307
- if (!t.ok) return refuse(out, t.error)
308
- const lines = [`${prog} deployed: ${tag} → ${envKey}${flags.apply ? '' : ' (dry run — pass --apply to write)'}`]
309
- // WARNS, NEVER REFUSES: a rollback and a hotfix straight to prod are both
310
- // legitimate. The order is the series' own env order.
311
- const ladder = Object.keys(envs).map((key) => ({ key, state: key }))
312
- const from = stageOf(found.release.body)
313
- const warn = from ? stageOrderWarning(ladder, from, envKey) : null
314
- if (warn) lines.push(` !! ${warn}`)
315
- lines.push(` issues: ${t.attach.map((x) => x.ref).join(', ') || 'none'} → "${envs[envKey]}"`)
316
- if (!flags.apply) return emit(out, flags, lines, { tag, env: envKey, apply: false, warn })
317
- const staged = await adapter.releaseStage(found.release, envs[envKey], t.attach)
318
- await adapter.releaseUpdate(found.release, { name: tag, body: withStage(found.release.body, envKey) })
319
- lines.push(` set: ${staged.set} issue(s)`)
320
- return emit(out, flags, lines, { tag, env: envKey, apply: true, warn, set: staged.set })
321
- }
322
-
323
- async function complete(dir, config, tagArg, flags, out) {
324
- const prep = prepare(dir, config, tagArg, flags, out)
325
- if (prep.code != null) return prep.code
326
- const { tag, adapter } = prep
327
- const found = await find(adapter, tag, out)
328
- if (!found.ok) return 1
329
- if (!found.release) return refuse(out, `no release for ${tag} yet — run \`release create ${tag}\` first`)
330
- const lines = [`${prog} complete: ${tag}${flags.apply ? '' : ' (dry run — pass --apply to write)'}`]
331
- if (!flags.apply) {
332
- lines.push(` would mark ${found.release.url || found.release.id} complete`)
333
- return emit(out, flags, lines, { tag, apply: false })
334
- }
335
- await adapter.releaseComplete(found.release)
336
- lines.push(` completed: ${found.release.url || found.release.id}`)
337
- return emit(out, flags, lines, { tag, apply: true })
338
- }
339
-
340
- // Titles for the body, best-effort: a ticket the tracker cannot read is
341
- // still listed, by ref. The body is information, not a gate.
342
- async function describeAll(adapter, tickets) {
343
- const out = []
344
- for (const t of tickets) {
345
- let title = null
346
- if (adapter.readIssue) {
347
- try {
348
- const issue = await adapter.readIssue(t.ref)
349
- title = issue && issue.title ? issue.title : null
350
- } catch {
351
- title = null
352
- }
353
- }
354
- out.push({ ...t, title })
355
- }
356
- return out
357
- }
358
-
359
- function emit(out, flags, lines, json) {
360
- out.write(flags.json ? JSON.stringify(json, null, 2) + '\n' : lines.join('\n') + '\n')
361
- return 0
362
- }
363
-
364
- async function run(dir, config, args, flags, out) {
365
- const [verb, tag, env] = args
366
- if (verb === 'create') return create(dir, config, tag, flags, out)
367
- if (verb === 'deployed') return deployed(dir, config, tag, env, flags, out)
368
- if (verb === 'complete') return complete(dir, config, tag, flags, out)
369
- out.write(
370
- `Usage: ${prog} create <tag> [--notes <f>] [--link <url>[=label]] [--stage <env>] [--apply] [--json]\n` +
371
- ` ${prog} deployed <tag> <env> [--apply] [--json]\n` +
372
- ` ${prog} complete <tag> [--apply] [--json]\n`,
373
- )
374
- return verb ? 1 : 0
375
- }
376
-
377
- return { run, create, deployed, complete }
378
- }
379
-
380
- module.exports = { makeReleaseCommands, resolveRange, seriesFor, composeBody, stageOf, withStage, parseLinks, REQUIRED_OPS }