@skitterbyte/skitterspec-linear 18.0.1 → 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 (50) 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/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 +261 -15
  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
@@ -0,0 +1,35 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * The doctor REPORT FRAMEWORK — the states, the row shape, and the combining
5
+ * rule every provider's `doctor` shares. The checks themselves are the
6
+ * provider's: they name its config files, its states, its transports.
7
+ *
8
+ * Two distinctions carry the design:
9
+ *
10
+ * 1. **`missing` is not `broken`.** `missing` is an opt-in not taken, which is
11
+ * fine; `broken` is configured-but-wrong, which is not. `ok` is false only
12
+ * for `broken`, so declining an opt-in never reads as a failure.
13
+ * 2. **Every non-`ok` row names the command that fixes it**, so the output is
14
+ * actionable without reading docs.
15
+ *
16
+ * `warn` sits between `ok` and `broken`: worth a human's attention, but not a
17
+ * failure — said out loud, exit code left alone.
18
+ */
19
+
20
+ const DOCTOR_STATES = ['ok', 'missing', 'broken', 'skipped', 'warn']
21
+
22
+ // A row is a check. `fix` is the exact command to run, or null when there is
23
+ // nothing to fix.
24
+ function doctorRow(id, label, state, detail, fix = null) {
25
+ if (!DOCTOR_STATES.includes(state)) throw new Error(`doctor: unknown check state "${state}" for ${id}`)
26
+ return { id, label, state, detail, fix }
27
+ }
28
+
29
+ // `missing` is a declined opt-in, so it must not fail the run. Only a
30
+ // configured-but-wrong layer does.
31
+ function combineDoctorChecks(checks) {
32
+ return { ok: !checks.some((c) => c.state === 'broken'), checks }
33
+ }
34
+
35
+ module.exports = { DOCTOR_STATES, doctorRow, combineDoctorChecks }
@@ -0,0 +1,44 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * Rate-limit-aware HTTP retry — the transport discipline every provider's API
5
+ * client shares, with none of any tracker's protocol in it.
6
+ *
7
+ * A bulk backfill is exactly the workload that gets throttled, and failing the
8
+ * run would strand a half-mirrored bucket — so a 429 waits and retries rather
9
+ * than surfacing. The server says how long to wait (`Retry-After`, seconds);
10
+ * honour that over guessing, and fall back to exponential backoff (from 1s,
11
+ * capped) when it doesn't.
12
+ */
13
+
14
+ const MAX_RETRIES = 5
15
+ const MAX_BACKOFF_MS = 60_000
16
+
17
+ // How long to wait before retrying a 429.
18
+ function retryDelay(res, attempt, maxBackoffMs = MAX_BACKOFF_MS) {
19
+ const header = res.headers && typeof res.headers.get === 'function' ? res.headers.get('retry-after') : null
20
+ const seconds = header != null ? Number(header) : NaN
21
+ if (Number.isFinite(seconds) && seconds >= 0) return Math.min(seconds * 1000, maxBackoffMs)
22
+ return Math.min(1000 * 2 ** attempt, maxBackoffMs)
23
+ }
24
+
25
+ /**
26
+ * Run `attempt()` (→ a fetch Response) until it is not rate-limited or the
27
+ * retries run out. Returns `{ response, exhausted }` — `exhausted` true when
28
+ * the LAST response is still a 429, so the caller phrases its own refusal (and
29
+ * marks it retryable: rate limiting is the failure where waiting is the whole
30
+ * answer, and the one a refusal must stay distinguishable from).
31
+ */
32
+ async function withRateLimitRetry(attempt, { sleep, maxRetries = MAX_RETRIES, maxBackoffMs = MAX_BACKOFF_MS } = {}) {
33
+ const wait = sleep || ((ms) => new Promise((r) => setTimeout(r, ms)))
34
+ for (let n = 0; ; n++) {
35
+ const response = await attempt()
36
+ if (response.status === 429 && n < maxRetries) {
37
+ await wait(retryDelay(response, n, maxBackoffMs))
38
+ continue
39
+ }
40
+ return { response, exhausted: response.status === 429 }
41
+ }
42
+ }
43
+
44
+ module.exports = { withRateLimitRetry, retryDelay, MAX_RETRIES, MAX_BACKOFF_MS }
@@ -0,0 +1,93 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * "Who am I in this workspace?" — the resolution shape every provider's
5
+ * assignment rests on.
6
+ *
7
+ * Three tiers, first hit wins:
8
+ *
9
+ * 1. the user-level credentials store (`source: 'store'`) — no network
10
+ * 2. the credential itself, via the tracker's "who am I" call
11
+ * (`source: 'viewer'`)
12
+ * 3. nothing (`source: 'unknown'`)
13
+ *
14
+ * **Unknown is a normal state, not a failure.** A shared/bot key answers the
15
+ * viewer call with the bot; an offline machine answers with nothing; neither is
16
+ * a broken install. So this returns a structured result the caller branches on,
17
+ * never an exception — and it NEVER PROMPTS and NEVER WRITES. Prompting belongs
18
+ * to the skill with a human in front of it, and caching belongs to the command
19
+ * that decided the answer was worth keeping: a resolver that wrote to disk as a
20
+ * side effect would cache a bot's identity the first time CI ran.
21
+ *
22
+ * Everything tracker-shaped arrives as a hook: how a credential resolves, how
23
+ * the viewer is fetched, and how a user object yields a display name.
24
+ */
25
+
26
+ /**
27
+ * @param {object} hooks
28
+ * - `scopeId` the credentials-store scope (e.g. a team id) — '' skips tier 1
29
+ * - `file` the store path (carried through on every result)
30
+ * - `readStore(file)` kit credentials read
31
+ * - `userFor(store,id)` the provider store binding's identity read
32
+ * - `resolveCredential()` → `{ ok, error?, envVar?, … }` — the provider's key resolution
33
+ * - `readViewer(credential)` → the tracker's current user (may throw)
34
+ * - `nameOf(viewer)` display name of a user object
35
+ * @returns {Promise<object>} `{ ok: true, id, name, email?, source, path }` or
36
+ * `{ ok: false, source: 'unknown', reason, envVar?, path }`.
37
+ */
38
+ async function resolveIdentity({ scopeId, file, readStore, userFor, resolveCredential, readViewer, nameOf }) {
39
+ if (scopeId) {
40
+ const result = readStore(file)
41
+ if (result.ok) {
42
+ const cached = userFor(result.store, scopeId)
43
+ if (cached) return { ok: true, id: cached.id, name: cached.name, source: 'store', path: file }
44
+ }
45
+ // A store that is present but unusable (over-permissive, malformed) is NOT
46
+ // reported as an identity failure — credential resolution hits the same
47
+ // file and reports it properly. Duplicating it here would print the same
48
+ // permissions warning twice for one cause.
49
+ }
50
+
51
+ const credential = resolveCredential()
52
+ if (!credential.ok) {
53
+ return { ok: false, source: 'unknown', reason: credential.error, envVar: credential.envVar, path: file }
54
+ }
55
+
56
+ let viewer
57
+ try {
58
+ viewer = await readViewer(credential)
59
+ } catch (error) {
60
+ // Offline, revoked key, tracker down. All are "cannot tell", which routes
61
+ // to the harmless branch: the caller skips assignment rather than guessing.
62
+ return { ok: false, source: 'unknown', reason: error.message, path: file }
63
+ }
64
+
65
+ const id = viewer && typeof viewer.id === 'string' ? viewer.id.trim() : ''
66
+ if (!id) {
67
+ return { ok: false, source: 'unknown', reason: 'the tracker returned no viewer for this key', path: file }
68
+ }
69
+ return {
70
+ ok: true,
71
+ id,
72
+ name: (nameOf || defaultDisplayName)(viewer),
73
+ email: (viewer && viewer.email) || null,
74
+ source: 'viewer',
75
+ path: file,
76
+ }
77
+ }
78
+
79
+ /**
80
+ * The name to show for a tracker user. Falls back through `displayName` and
81
+ * `email` so a user with an odd profile still reads as a person rather than a
82
+ * UUID.
83
+ */
84
+ function defaultDisplayName(user) {
85
+ if (!user || typeof user !== 'object') return null
86
+ for (const field of ['name', 'displayName', 'email']) {
87
+ const value = user[field]
88
+ if (typeof value === 'string' && value.trim()) return value.trim()
89
+ }
90
+ return null
91
+ }
92
+
93
+ module.exports = { resolveIdentity, defaultDisplayName }
@@ -0,0 +1,39 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * The markdown-form reduction both dialects compare through. Every transform
5
+ * here is a benign difference between two spellings of the same markdown —
6
+ * a reserialising editor's (Linear rewrites bullets, renumbers lists,
7
+ * case-folds checkboxes, collapses separator rows on save) or a round-trip
8
+ * renderer's (the ADF reducer re-emits `-` bullets and `| -- |` separators
9
+ * whatever the source used). Normalised away BEFORE comparing, so an intact
10
+ * mirror never reports as data loss; digits stay significant everywhere else —
11
+ * a port, a version, a key length still count.
12
+ */
13
+
14
+ function canonicalForCompare(text) {
15
+ return String(text == null ? '' : text)
16
+ .replace(/\r\n/g, '\n')
17
+ .split('\n')
18
+ .map((line) =>
19
+ line
20
+ // Ordered-list markers → a placeholder. Linear renumbers lists, and the
21
+ // digits it rewrites are alphanumeric, so a naive alphanumeric compare
22
+ // would flag its own benign reformat as data loss. Normalising the
23
+ // marker keeps digits significant EVERYWHERE ELSE — a port, a version, a
24
+ // key length still count.
25
+ .replace(/^(\s*)\d+\.(\s)/, '$1#.$2')
26
+ // Unordered markers unify (`-`/`+` come back as `*`).
27
+ .replace(/^(\s*)[*+-](\s)/, '$1-$2')
28
+ // Checkbox marks case-fold. Targeted rather than lowercasing the whole
29
+ // text, so a genuine case corruption in prose is still caught.
30
+ .replace(/^(\s*-\s*\[)[xX](\])/, '$1x$2')
31
+ // Table separator rows collapse (`|-------|` → `| -- |`).
32
+ .replace(/^\s*\|[\s:|-]+\|\s*$/, '|--|')
33
+ .replace(/[ \t]+$/, ''),
34
+ )
35
+ .join('\n')
36
+ .replace(/\n{3,}/g, '\n\n')
37
+ .trim()
38
+ }
39
+ module.exports = { markdownCanonicalForCompare: canonicalForCompare }
@@ -1,31 +1,22 @@
1
1
  'use strict'
2
2
 
3
3
  /**
4
- * Flatten markdown tables that sit INSIDE a list item, because Linear corrupts
5
- * them.
4
+ * Flatten markdown tables that sit INSIDE a list item, because both tracker
5
+ * dialects need it: Linear's renderer corrupts nested-table data cells
6
+ * (measured on probe SKI-28, 2026-08-28 — every data cell loses its first N
7
+ * characters, N being the rendered list indent; the auth header
8
+ * `X-Extraction-Key` was stored as `Extraction-Key`), and ADF's `listItem`
9
+ * cannot contain a `table` node at all, so a Jira render would drop or mangle
10
+ * it. The re-emitted shapes are ones proven to survive nesting unchanged:
6
11
  *
7
- * Measured on probe SKI-28 (2026-08-28): when Linear renders a table nested in a
8
- * list item, every **data** cell loses its first N characters, where N is the
9
- * list-content indent Linear renders at — 3 per ordered-list level, 2 per bullet
10
- * level — regardless of the indent the source used. Source indents 3, 4 and 6
11
- * all lose exactly 3. The header row is never touched, column-0 tables never
12
- * corrupt, and the column count is irrelevant. Real damage from the field: the
13
- * auth header `X-Extraction-Key` was stored as `Extraction-Key`.
14
- *
15
- * The engine passes the table through byte-identically — this is Linear's
16
- * parser, not ours — but the projection is the only place that can stop the
17
- * markdown reaching it in a shape it mangles. So nested tables are re-emitted as
18
- * shapes SKI-28 proved survive nesting unchanged:
19
- *
20
- * - 2 columns → a bullet list (`- a — b`), the key/value case, and the shape
21
- * the reporter hand-repaired in production
12
+ * - 2 columns → a bullet list (`- a — b`), the key/value case
22
13
  * - otherwise → a fenced code block wrapping the original rows verbatim
23
14
  *
24
15
  * This shapes the PROJECTION only. Repo files are never rewritten: the source
25
16
  * markdown is valid and renders correctly in GitHub and every editor.
26
17
  */
27
18
 
28
- const { fenceMask } = require('./task-block.js')
19
+ const { fenceMask } = require('../../sync-core/src/task-block.js')
29
20
 
30
21
  // A table row: optional indent, then a `|`-delimited line. We only ever act on
31
22
  // indented ones — a column-0 table (the `## Phases` index, every Impact map) is
@@ -99,4 +90,5 @@ function flattenNestedTables(md) {
99
90
  return out.join('\n')
100
91
  }
101
92
 
93
+
102
94
  module.exports = { flattenNestedTables, splitCells }
@@ -0,0 +1,50 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * Terminal input helpers for a credentials CLI — reading a piped secret, and
5
+ * prompting for one with the echo off.
6
+ */
7
+
8
+ // Read stdin to completion (for `--stdin`).
9
+ function readAllStdin(input) {
10
+ return new Promise((resolve, reject) => {
11
+ let data = ''
12
+ input.setEncoding('utf-8')
13
+ input.on('data', (chunk) => (data += chunk))
14
+ input.on('end', () => resolve(data))
15
+ input.on('error', reject)
16
+ })
17
+ }
18
+
19
+ // Prompt on a TTY with the input hidden. `_writeToOutput` is readline's own echo
20
+ // hook — filtering it is what keeps the key off the screen (and out of a
21
+ // screen-shared terminal or a recorded session).
22
+ //
23
+ // READLINE OWNS THE PROMPT, deliberately. Writing it ourselves and then starting
24
+ // the interface loses it: readline clears from the cursor to the end of the
25
+ // screen (`ESC[0J`) before its first redraw, so the prompt was wiped the instant
26
+ // it appeared and the user was left staring at a blank line while the process
27
+ // waited for a key — indistinguishable from a hang.
28
+ //
29
+ // The hook is assigned BEFORE `question`, so the very first redraw goes through
30
+ // it. readline hands it `prompt + what has been typed`; re-writing only the
31
+ // prompt is what keeps the key hidden while the prompt survives every redraw.
32
+ function promptHidden(question, input, out) {
33
+ const readline = require('node:readline')
34
+ return new Promise((resolve) => {
35
+ // `out`, never `process.stdout`: they are the same stream in production, and
36
+ // hardcoding one half meant readline cleared a screen the prompt had not
37
+ // been written to under test — the split that hid this bug from the suite.
38
+ const rl = readline.createInterface({ input, output: out, terminal: true })
39
+ rl._writeToOutput = (s) => {
40
+ if (s.includes(question)) out.write(question)
41
+ }
42
+ rl.question(question, (answer) => {
43
+ out.write('\n')
44
+ rl.close()
45
+ resolve(answer)
46
+ })
47
+ })
48
+ }
49
+
50
+ module.exports = { readAllStdin, promptHidden }
@@ -0,0 +1,226 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * Which tickets a release contains.
5
+ *
6
+ * The repo lands specs with `merge --ff-only`, so history is linear and branch
7
+ * names never reach it. A commit's `Refs:` trailer is therefore the only place
8
+ * the ticket survives into the range a release scans — see the
9
+ * `commit-trailers` rule. Nothing here is tracker-specific: the identifier
10
+ * shape (`KEY-123`) and the team-key prefix are common to the trackers this
11
+ * scans for, which is why the module lives in the kit.
12
+ *
13
+ * The parsing half is pure and takes commits as data, so the rules below are
14
+ * testable without git. Reading the range, and enriching refs with issue titles,
15
+ * belong to the caller.
16
+ */
17
+
18
+ // An issue identifier: uppercase team key, dash, number.
19
+ const IDENTIFIER_RE = /\b[A-Z][A-Z0-9]*-\d+\b/g
20
+ // A `Refs:` trailer line. Anchored, so it is a line of its own — never prose
21
+ // that happens to mention the word.
22
+ const TRAILER_RE = /^Refs:[ \t]*(.+?)[ \t]*$/
23
+
24
+ /**
25
+ * The refs a single commit body claims.
26
+ *
27
+ * Deliberately blind to three things that LOOK like trailers and are not:
28
+ *
29
+ * - a line inside a ``` fence — a commit explaining the convention quotes it;
30
+ * - a quoted line (`> Refs: …`) — same reason, in review replies;
31
+ * - an indented line (4+ spaces) — markdown code, e.g. a sample message.
32
+ *
33
+ * Counting any of those would make a release claim work it does not contain,
34
+ * which is worse than missing a ticket: the missing one is noticed when someone
35
+ * looks for it, the invented one never is.
36
+ */
37
+ function refsInBody(body) {
38
+ const found = []
39
+ let fenced = false
40
+ for (const raw of String(body || '').split('\n')) {
41
+ const line = raw.replace(/\r$/, '')
42
+ if (/^\s*```/.test(line)) {
43
+ fenced = !fenced
44
+ continue
45
+ }
46
+ if (fenced) continue
47
+ if (/^\s*>/.test(line)) continue
48
+ if (/^ {4,}|\t/.test(line)) continue
49
+ const m = TRAILER_RE.exec(line.trim() === line ? line : line.trimStart())
50
+ if (!m) continue
51
+ for (const id of m[1].match(IDENTIFIER_RE) || []) found.push(id)
52
+ }
53
+ return found
54
+ }
55
+
56
+ /**
57
+ * Whether a commit's changed paths are ENTIRELY bookkeeping.
58
+ *
59
+ * The problem it solves: a spec's `chore(spec): complete <name>` commit carries
60
+ * the same `Refs:` trailer as the code it describes, but lands after the tag
61
+ * that shipped that code — so the ticket turns up in two consecutive release
62
+ * ranges, once for its code and once for its paperwork.
63
+ *
64
+ * Deliberately a POSITIVE signal: it says yes only when it actually saw paths
65
+ * and every one of them sits under an ignored prefix. It never reasons from an
66
+ * absence.
67
+ *
68
+ * WHAT WOULD FOOL THE OTHER PHRASING ("no unignored path was found"): git lists
69
+ * no files at all for a MERGE commit (without `-m`) — verified, not assumed —
70
+ * nor for a genuinely empty one, and a `git log` that failed outright yields no
71
+ * paths for anything. Under that phrasing every one of those becomes a release
72
+ * silently losing its tickets. Under this one they mean "nothing was seen, so
73
+ * nothing is known", which keeps the pre-filter behaviour: an over-claimed
74
+ * ticket is noticed when someone looks for it, whereas a ticket that quietly
75
+ * belongs to no release never is.
76
+ *
77
+ * Matching is path-prefix, not glob: `specs` and `specs/` both mean the
78
+ * directory, and a prefix only matches on a path SEGMENT boundary, so `specs/`
79
+ * never swallows `specs-archive/`.
80
+ *
81
+ * @param {string[]|null|undefined} paths repo-relative paths the commit changed
82
+ * @param {string[]} ignorePaths repo-relative prefixes that are bookkeeping
83
+ */
84
+ function onlyIgnoredPaths(paths, ignorePaths) {
85
+ if (!Array.isArray(paths) || !paths.length) return false
86
+ const prefixes = (Array.isArray(ignorePaths) ? ignorePaths : [])
87
+ .filter((p) => typeof p === 'string' && p.trim())
88
+ .map((p) => p.trim().replace(/^\.\//, '').replace(/\/+$/, ''))
89
+ .filter(Boolean)
90
+ if (!prefixes.length) return false
91
+ return paths.every((raw) => {
92
+ const file = String(raw == null ? '' : raw)
93
+ .trim()
94
+ .replace(/^\.\//, '')
95
+ // An unreadable entry is an unknown, not an ignored one — it makes the whole
96
+ // commit count, per the bias above.
97
+ if (!file) return false
98
+ return prefixes.some((prefix) => file === prefix || file.startsWith(`${prefix}/`))
99
+ })
100
+ }
101
+
102
+ /**
103
+ * Fold commits into the report a release needs.
104
+ *
105
+ * @param {Array<{sha?:string, subject?:string, body?:string, paths?:string[]}>} commits
106
+ * @param {{ignorePaths?:string[]}} [options] `ignorePaths` marks bookkeeping —
107
+ * see `onlyIgnoredPaths`. Omitted (or empty) means nothing is ignored, so the
108
+ * report is what it was before the filter existed.
109
+ * @returns {{tickets: Array<{ref:string, commits:number}>, unreferenced:number, ignored:number, total:number}}
110
+ * `tickets` is deduped in FIRST-SEEN order: a ticket touched by eight commits
111
+ * is listed once, where it first appears, not eight times. `ignored` is
112
+ * reported rather than merely subtracted — a filter that removes commits in
113
+ * silence reads as "there was nothing there".
114
+ */
115
+ function ticketsInRange(commits, options = {}) {
116
+ const ignorePaths = (options && options.ignorePaths) || []
117
+ const seen = new Map()
118
+ let unreferenced = 0
119
+ let ignored = 0
120
+ for (const commit of commits || []) {
121
+ if (onlyIgnoredPaths(commit && commit.paths, ignorePaths)) {
122
+ // Not counted as unreferenced either: that number exists to surface a
123
+ // MISSED trailer, and a paperwork commit is not a gap someone should hunt.
124
+ ignored++
125
+ continue
126
+ }
127
+ const refs = [...new Set(refsInBody(commit && commit.body))]
128
+ if (!refs.length) {
129
+ unreferenced++
130
+ continue
131
+ }
132
+ for (const ref of refs) seen.set(ref, (seen.get(ref) || 0) + 1)
133
+ }
134
+ return {
135
+ tickets: [...seen.entries()].map(([ref, count]) => ({ ref, commits: count })),
136
+ unreferenced,
137
+ ignored,
138
+ total: (commits || []).length,
139
+ }
140
+ }
141
+
142
+ /**
143
+ * Split a release's tickets into the ones a stage move may touch and the ones it
144
+ * must not, with a reason for every exclusion.
145
+ *
146
+ * Three reasons to leave a ticket alone, and each is a case where acting would
147
+ * be worse than not acting:
148
+ *
149
+ * - **foreign** — the ref is not this repo's team. A range can carry another
150
+ * team's ref (a shared dependency, a quoted ticket), and writing to a team
151
+ * this repo was never configured for is the worst failure available here.
152
+ * - **unlinked** — the ref is this team's, but no spec in the repo claims it.
153
+ * It may be tracker-only work, or a typo in a trailer. Either way nothing
154
+ * here knows what it is, so it is reported, not moved.
155
+ * - **unfinished** — a spec that has not reached the ceded bucket. Its code
156
+ * really is in the release (it landed via `/spec-to-main`), but push still
157
+ * owns its workflow state and would bounce it straight back. Exactly one
158
+ * writer per issue at any moment beats a visible flip-flop.
159
+ *
160
+ * Pure: it takes the spec list as data, so the rules are testable without a repo.
161
+ */
162
+ function partitionStageMoves({ tickets, teamKey, specs, cededBucket = 'complete' }) {
163
+ const bucketOf = new Map()
164
+ for (const spec of specs || []) {
165
+ if (spec && spec.identifier) bucketOf.set(spec.identifier, spec.bucket)
166
+ }
167
+ const key = String(teamKey || '').trim().toUpperCase()
168
+ const movable = []
169
+ const foreign = []
170
+ const unlinked = []
171
+ const unfinished = []
172
+ for (const ticket of tickets || []) {
173
+ const ref = ticket && ticket.ref
174
+ if (!ref) continue
175
+ if (key && !ref.toUpperCase().startsWith(`${key}-`)) {
176
+ foreign.push(ticket)
177
+ } else if (!bucketOf.has(ref)) {
178
+ unlinked.push(ticket)
179
+ } else if (bucketOf.get(ref) !== cededBucket) {
180
+ unfinished.push({ ...ticket, bucket: bucketOf.get(ref) })
181
+ } else {
182
+ movable.push(ticket)
183
+ }
184
+ }
185
+ return { movable, foreign, unlinked, unfinished }
186
+ }
187
+
188
+ /**
189
+ * Whether moving from `fromState` to the rung `toKey` runs against the declared
190
+ * order — and if so, how to say it.
191
+ *
192
+ * WARNS, never refuses. A rollback from test and a hotfix going straight to prod
193
+ * are both legitimate, and a check that blocked either would be wrong on healthy
194
+ * input. An issue that is on no rung yet is entering the ladder, which is the
195
+ * normal case and says nothing.
196
+ *
197
+ * `lifecycleStates` is the bucket map's own state names, and a state among them
198
+ * means the issue is at its LIFECYCLE position, not on a rung — even when the
199
+ * two names coincide. They routinely do: `states.complete` and a final `prod`
200
+ * rung are both naturally "Done", and without this a spec that had merely been
201
+ * completed would read as already deployed to prod, so its first real deploy
202
+ * would be warned about as a move backwards. Bucket wins over ladder here for
203
+ * the same reason it wins in `bucketForState`.
204
+ *
205
+ * @returns {string|null}
206
+ */
207
+ function stageOrderWarning(stages, fromState, toKey, lifecycleStates = []) {
208
+ const list = Array.isArray(stages) ? stages : []
209
+ const to = list.findIndex((s) => s && s.key === toKey)
210
+ if (to < 0) return null
211
+ const want = String(fromState || '').toLowerCase().trim()
212
+ if (!want) return null
213
+ const lifecycle = new Set(
214
+ (Array.isArray(lifecycleStates) ? lifecycleStates : [])
215
+ .filter((n) => typeof n === 'string')
216
+ .map((n) => n.toLowerCase().trim()),
217
+ )
218
+ if (lifecycle.has(want)) return null
219
+ const from = list.findIndex((s) => s && typeof s.state === 'string' && s.state.toLowerCase().trim() === want)
220
+ if (from < 0) return null
221
+ if (to < from) return `moves back from "${list[from].key}"`
222
+ if (to > from + 1) return `skips ${to - from - 1} rung(s) from "${list[from].key}"`
223
+ return null
224
+ }
225
+
226
+ module.exports = { ticketsInRange, refsInBody, onlyIgnoredPaths, partitionStageMoves, stageOrderWarning }