@skitterbyte/skitterspec-jira 0.0.0-stage → 1.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.
Files changed (109) hide show
  1. package/MIGRATION.md +1089 -0
  2. package/README.md +42 -2
  3. package/assets/claude-md-section.md +85 -0
  4. package/assets/commands/allow-main.md +33 -0
  5. package/assets/commands/spec-connect.md +13 -0
  6. package/assets/commands/spec-live.md +14 -0
  7. package/assets/commands/spec-remote-review.md +37 -0
  8. package/assets/commands/spec-skip.md +24 -0
  9. package/assets/core/SETUP.md +192 -0
  10. package/assets/core/env.config.json.example +56 -0
  11. package/assets/core/env.config.md +554 -0
  12. package/assets/core/gating.config.json.example +4 -0
  13. package/assets/core/gating.config.md +81 -0
  14. package/assets/core/jira.config.json.example +18 -0
  15. package/assets/core/jira.config.md +61 -0
  16. package/assets/hooks/main-guard.cjs +162 -0
  17. package/assets/hooks/review-gate.cjs +146 -0
  18. package/assets/review/page.html +3384 -0
  19. package/assets/rules/commit-trailers.md +96 -0
  20. package/assets/rules/negative-checks.md +69 -0
  21. package/assets/rules/offered-unblocks.md +100 -0
  22. package/assets/rules/spec-planning.md +692 -0
  23. package/assets/rules/spec-reports.md +557 -0
  24. package/assets/skills/no-spec/SKILL.md +246 -0
  25. package/assets/skills/spec/SKILL.md +714 -0
  26. package/assets/skills/spec-bug/SKILL.md +583 -0
  27. package/assets/skills/spec-cancel/SKILL.md +261 -0
  28. package/assets/skills/spec-complete/SKILL.md +448 -0
  29. package/assets/skills/spec-diff/SKILL.md +870 -0
  30. package/assets/skills/spec-hotfix/SKILL.md +605 -0
  31. package/assets/skills/spec-init/SKILL.md +178 -0
  32. package/assets/skills/spec-jira-setup/SKILL.md +220 -0
  33. package/assets/skills/spec-list/SKILL.md +173 -0
  34. package/assets/skills/spec-next/SKILL.md +676 -0
  35. package/assets/skills/spec-push/SKILL.md +306 -0
  36. package/assets/skills/spec-review/SKILL.md +256 -0
  37. package/assets/skills/spec-reviewed/SKILL.md +284 -0
  38. package/assets/skills/spec-start/SKILL.md +496 -0
  39. package/assets/skills/spec-status/SKILL.md +112 -0
  40. package/assets/skills/spec-sync/SKILL.md +218 -0
  41. package/assets/skills/spec-to-main/SKILL.md +139 -0
  42. package/bin/skitterspec-jira.js +61 -0
  43. package/package.json +40 -4
  44. package/src/cli.js +5901 -0
  45. package/src/deprecate.js +138 -0
  46. package/src/env/bootstrap.js +188 -0
  47. package/src/env/building.js +143 -0
  48. package/src/env/classify.js +176 -0
  49. package/src/env/commitcmd.js +108 -0
  50. package/src/env/config.js +753 -0
  51. package/src/env/dev.js +63 -0
  52. package/src/env/hooks.js +226 -0
  53. package/src/env/hotfix.js +385 -0
  54. package/src/env/hotfixland.js +302 -0
  55. package/src/env/integrate.js +126 -0
  56. package/src/env/live.js +504 -0
  57. package/src/env/mainguard.js +299 -0
  58. package/src/env/provision.js +466 -0
  59. package/src/env/proxy.js +192 -0
  60. package/src/env/prune.js +119 -0
  61. package/src/env/registry.js +159 -0
  62. package/src/env/render.js +17 -0
  63. package/src/env/resolve.js +716 -0
  64. package/src/env/review.js +2577 -0
  65. package/src/env/reviewers/coderabbit.js +228 -0
  66. package/src/env/reviewers.js +517 -0
  67. package/src/env/serve.js +1044 -0
  68. package/src/env/supervise.js +157 -0
  69. package/src/env/teardown.js +248 -0
  70. package/src/env/trust.js +87 -0
  71. package/src/gating.js +155 -0
  72. package/src/init.js +1150 -0
  73. package/src/lines-diff.js +114 -0
  74. package/src/prompts.js +129 -0
  75. package/src/vendor/jira/adf.js +414 -0
  76. package/src/vendor/jira/api.js +295 -0
  77. package/src/vendor/jira/cli-sync.js +1256 -0
  78. package/src/vendor/jira/commands.js +44 -0
  79. package/src/vendor/jira/config.js +296 -0
  80. package/src/vendor/jira/credentials.js +108 -0
  81. package/src/vendor/jira/dialect.js +45 -0
  82. package/src/vendor/jira/mcp.js +129 -0
  83. package/src/vendor/provider-kit/index.js +41 -0
  84. package/src/vendor/provider-kit/src/adapter.js +23 -0
  85. package/src/vendor/provider-kit/src/apply.js +197 -0
  86. package/src/vendor/provider-kit/src/args.js +68 -0
  87. package/src/vendor/provider-kit/src/config.js +198 -0
  88. package/src/vendor/provider-kit/src/credentials.js +404 -0
  89. package/src/vendor/provider-kit/src/doctor.js +35 -0
  90. package/src/vendor/provider-kit/src/http.js +44 -0
  91. package/src/vendor/provider-kit/src/identity.js +93 -0
  92. package/src/vendor/provider-kit/src/md-compare.js +39 -0
  93. package/src/vendor/provider-kit/src/md-tables.js +94 -0
  94. package/src/vendor/provider-kit/src/prompt.js +50 -0
  95. package/src/vendor/provider-kit/src/released.js +226 -0
  96. package/src/vendor/provider-kit/src/specs.js +166 -0
  97. package/src/vendor/provider-kit/src/transport.js +22 -0
  98. package/src/vendor/sync-core/index.js +92 -0
  99. package/src/vendor/sync-core/src/base.js +81 -0
  100. package/src/vendor/sync-core/src/compare.js +306 -0
  101. package/src/vendor/sync-core/src/dialect.js +51 -0
  102. package/src/vendor/sync-core/src/fields.js +36 -0
  103. package/src/vendor/sync-core/src/legacy.js +100 -0
  104. package/src/vendor/sync-core/src/normalize.js +989 -0
  105. package/src/vendor/sync-core/src/push.js +85 -0
  106. package/src/vendor/sync-core/src/retarget.js +278 -0
  107. package/src/vendor/sync-core/src/task-block.js +308 -0
  108. package/src/vendor/sync-core/src/verify.js +67 -0
  109. package/src/vendor/sync-core/src/write.js +191 -0
@@ -0,0 +1,989 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * Normalize a remote Project projection and a local spec snapshot into the SAME
5
+ * field set, so the three-way compare (compare.js) can diff them field by field.
6
+ *
7
+ * Both `normalizeLocal(snapshotDir, config)` and `normalizeRemote(project, config)`
8
+ * return an object whose keys are exactly `config.sync.fieldOwnership`'s keys —
9
+ * identical field sets by construction. A field a given side can't supply is
10
+ * `null` (scalars) or `[]` (collections), never absent, so the sets stay equal.
11
+ *
12
+ * Pure: `normalizeLocal` reads files under `snapshotDir` but makes no other side
13
+ * effects and no Date.now()/Math.random(). `localOnlySections` are stripped from
14
+ * the local `description` so they're never pushed to remote.
15
+ */
16
+
17
+ const fs = require('node:fs')
18
+ const path = require('node:path')
19
+ const { dialectOf } = require('./dialect.js')
20
+ const { fieldsOf } = require('./fields.js')
21
+ const { fenceMask, findTaskBlocks, collapse, collapseHyphenAware } = require('./task-block.js')
22
+
23
+ // --- markdown / frontmatter parsing -----------------------------------------
24
+
25
+ // Split `---\n…\n---` frontmatter off the top. Returns { data, body }.
26
+ function parseFrontmatter(raw) {
27
+ const m = /^---\n([\s\S]*?)\n---\n?/.exec(raw)
28
+ if (!m) return { data: {}, body: raw }
29
+ const data = {}
30
+ for (const line of m[1].split('\n')) {
31
+ const kv = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line)
32
+ if (!kv) continue
33
+ data[kv[1]] = parseScalar(kv[2].trim())
34
+ }
35
+ return { data, body: raw.slice(m[0].length) }
36
+ }
37
+
38
+ // Parse a frontmatter scalar: quoted string, JSON array, number, or bare string.
39
+ function parseScalar(v) {
40
+ if (v === '') return null
41
+ const unq = /^["'](.*)["']$/.exec(v)
42
+ if (unq) return unq[1]
43
+ if (v.startsWith('[')) {
44
+ try {
45
+ return JSON.parse(v)
46
+ } catch {
47
+ return v
48
+ .replace(/^\[|\]$/g, '')
49
+ .split(',')
50
+ .map((s) => s.trim().replace(/^["']|["']$/g, ''))
51
+ .filter(Boolean)
52
+ }
53
+ }
54
+ if (/^-?\d+(\.\d+)?$/.test(v)) return Number(v)
55
+ return v
56
+ }
57
+
58
+ // Split a markdown body into { title, sections } where sections maps a `## `
59
+ // heading text → its content (until the next `## `). The H1 `# ` is the title.
60
+ function parseSections(body) {
61
+ const lines = body.split('\n')
62
+ const inFence = fenceMask(lines)
63
+ let title = null
64
+ const sections = {}
65
+ let current = null
66
+ let buf = []
67
+ const flush = () => {
68
+ if (current !== null) sections[current] = buf.join('\n').trim()
69
+ }
70
+ for (let i = 0; i < lines.length; i++) {
71
+ const line = lines[i]
72
+ // A `#`/`##` inside a fenced code block is example text, not a real heading —
73
+ // treat it as body content so it can't start a phantom section.
74
+ const h1 = inFence[i] ? null : /^#\s+(.*)$/.exec(line)
75
+ const h2 = inFence[i] ? null : /^##\s+(.*)$/.exec(line)
76
+ if (h1 && title === null) {
77
+ title = h1[1].trim()
78
+ continue
79
+ }
80
+ if (h2) {
81
+ flush()
82
+ current = h2[1].trim()
83
+ buf = []
84
+ continue
85
+ }
86
+ if (current !== null) buf.push(line)
87
+ }
88
+ flush()
89
+ return { title, sections }
90
+ }
91
+
92
+ // Canonical milestone status from the phase-index emoji.
93
+ const EMOJI_STATUS = { '⬜': 'not-started', '🔄': 'in-progress', '✅': 'done' }
94
+
95
+ // Parse the "## Phases" index table into [{ name, status }] rows.
96
+ function parsePhaseIndex(phasesSection) {
97
+ if (!phasesSection) return []
98
+ const rows = []
99
+ for (const line of phasesSection.split('\n')) {
100
+ // | 1 | Phase name | ✅ | [01-…](01-…) |
101
+ const cells = line.split('|').map((c) => c.trim())
102
+ if (cells.length < 5) continue
103
+ const n = cells[1]
104
+ if (!/^\d+$/.test(n)) continue // skip header + separator rows
105
+ const name = cells[2]
106
+ const emoji = (cells[3].match(/[⬜🔄✅]/u) || [])[0]
107
+ // `stated` separates "the row says not-started" from "the row said nothing
108
+ // we recognise". A cell holding the word `Done`, an em dash, or a legacy
109
+ // spec's freeform text expresses no status in this vocabulary, and reading
110
+ // its absence as `not-started` let lintPhases quote the overview as saying
111
+ // something it never said.
112
+ rows.push({ name, status: EMOJI_STATUS[emoji] || 'not-started', stated: Boolean(emoji) })
113
+ }
114
+ return rows
115
+ }
116
+
117
+ // The phase's descriptive title: the h1 with the "Phase N — " prefix and any
118
+ // trailing status emoji stripped (so it matches its Linear Milestone name).
119
+ function phaseTitle(body) {
120
+ const h1 = /^#\s+(.*)$/m.exec(body)
121
+ if (!h1) return null
122
+ const t = h1[1]
123
+ .replace(/\s*[⬜🔄✅]\s*$/u, '')
124
+ .replace(/^Phase\s+\d+\s*[—–-]\s*/i, '')
125
+ .trim()
126
+ return t || null
127
+ }
128
+
129
+ // The raw ⬜/🔄/✅ on a phase file's h1, or undefined when it carries none.
130
+ // Kept separate from `phaseStateBucket` because the LINT has to tell "absent"
131
+ // apart from "not-started" — the projection deliberately cannot (see below).
132
+ function headingEmoji(body) {
133
+ const h1 = /^#\s+(.*)$/m.exec(body)
134
+ return h1 ? (h1[1].match(/[⬜🔄✅]/u) || [])[0] : undefined
135
+ }
136
+
137
+ // The `> **Status:** …` line's value, or null when the file has none. This is
138
+ // the human mirror of the heading emoji, not a source of truth — `lintPhases`
139
+ // cross-checks it, and nothing else reads it.
140
+ function phaseStatusLine(body) {
141
+ const m = /^>.*\*\*Status:\*\*\s*(.+?)\s*$/m.exec(body)
142
+ return m ? m[1] : null
143
+ }
144
+
145
+ // Read a `> **Status:**` value leniently into the canonical vocabulary: an emoji
146
+ // if it carries one, else a word we recognise. Returns null for anything else —
147
+ // the line is free prose, and warning on an unrecognised phrasing would train
148
+ // the warning away.
149
+ // `pending` is deliberately NOT here: "pending review" matches as not-started
150
+ // but means roughly the opposite, and a false positive is worse than a missed
151
+ // check — it teaches the reader to ignore the warning.
152
+ const STATUS_WORDS = [
153
+ [/\b(not[\s-]?started|todo|to[\s-]do|planned)\b/i, 'not-started'],
154
+ [/\b(in[\s-]?progress|started|doing|wip)\b/i, 'in-progress'],
155
+ [/\b(done|complete[d]?|finished|shipped)\b/i, 'done'],
156
+ ]
157
+ function statusLineValue(line) {
158
+ if (!line) return null
159
+ const emoji = (line.match(/[⬜🔄✅]/u) || [])[0]
160
+ if (emoji) return EMOJI_STATUS[emoji]
161
+ for (const [re, status] of STATUS_WORDS) if (re.test(line)) return status
162
+ return null
163
+ }
164
+
165
+ // A phase's status (from its heading emoji ⬜/🔄/✅) mapped to a state bucket the
166
+ // `states` table understands, so a sub-issue lands in the matching Linear issue
167
+ // state. Unknown/absent → backlog.
168
+ //
169
+ // That fallback conflates "author marked it not-started" with "author used a
170
+ // format we don't parse", which is silent corruption: the wrong state pushes
171
+ // cleanly and `record` then commits it as the INTENDED value. The fix is not
172
+ // leniency here — one convention beats two — it is `lintPhases`, which warns.
173
+ const PHASE_STATE_BUCKET = { 'not-started': 'backlog', 'in-progress': 'in-progress', done: 'complete' }
174
+ function phaseStateBucket(body) {
175
+ return PHASE_STATE_BUCKET[EMOJI_STATUS[headingEmoji(body)]] || 'backlog'
176
+ }
177
+
178
+ // Parse a task line (already stripped of its leading "- ") into a keyed item:
179
+ // its checkbox state, its text, and the inline Linear issue identifier if present
180
+ // (`… (SKI-123)`). Returns null for a non-task line.
181
+ function parseTaskLine(line) {
182
+ // Any single-character mark, matching the parser (`TASK_START_RE`). Only
183
+ // `x`/`X` is done — every other mark (`~`, `>`, `-` …) is a project's own
184
+ // vocabulary, carried through verbatim rather than coerced to unchecked.
185
+ const m = /^\[([^\]])\]\s*(.*)$/.exec(line)
186
+ if (!m) return null
187
+ const done = m[1].toLowerCase() === 'x'
188
+ let text = m[2].trim()
189
+ let id = null
190
+ const idm = /\s*\(([A-Za-z][A-Za-z0-9]*-\d+)\)\s*$/.exec(text)
191
+ if (idm) {
192
+ id = idm[1]
193
+ text = text.slice(0, idm.index).trim()
194
+ }
195
+ return { id, text, done }
196
+ }
197
+
198
+ // Tasks used to be grouped onto their source headings here, because the body was
199
+ // rebuilt from harvested task lines and the headings had to be put back. The
200
+ // projection now emits the phase file itself, so the headings never leave in the
201
+ // first place (bug-phase-content-dropped) and the grouping is gone with them.
202
+
203
+ // The phase's stated purpose, in either shape people actually write it: an
204
+ // inline `**Goal:** …` paragraph, or a `## Goal` section. Only the inline form
205
+ // was recognised — so the phase files written the other way (4 of the 96 in this
206
+ // repo, all of them recent) projected an empty goal.
207
+ function phaseGoal(body) {
208
+ const inline = /\*\*Goal:\*\*\s*([\s\S]*?)(?:\n\n|$)/.exec(body)
209
+ if (inline) return inline[1]
210
+ return parseSections(body).sections.Goal || ''
211
+ }
212
+
213
+ // One task block back to a single markdown line. `findTaskBlocks` also returns
214
+ // the plain sub-bullets written underneath a task; they carry no checkbox, so
215
+ // they render as the bullet their author used — emitting `- [ ]` here would
216
+ // invent a task that does not exist in the repo. Any inline `(KEY-123)` stamped
217
+ // on a legacy task line is stripped: those ids were per-task issues we no longer
218
+ // create, and they read as noise in the mirror.
219
+ function renderTaskBlockLine(b) {
220
+ const parsed = parseTaskLine(`[${b.checkbox ? b.mark : ' '}] ${b.text}`)
221
+ const text = parsed ? parsed.text : b.text
222
+ return b.checkbox ? `${b.indent}- [${b.mark}] ${text}` : `${b.indent}${b.marker} ${text}`
223
+ }
224
+
225
+ // Read the phase files (01-*.md, 02-*.md …) in execution order. Each yields its
226
+ // linked milestone id (from optional frontmatter), title, goal and tasks.
227
+ function readPhaseFiles(snapshotDir, config) {
228
+ let entries
229
+ try {
230
+ entries = fs.readdirSync(snapshotDir)
231
+ } catch {
232
+ return []
233
+ }
234
+ return entries
235
+ .filter((f) => /^\d\d-.*\.md$/.test(f) && !f.startsWith('00-'))
236
+ .sort()
237
+ .map((file) => {
238
+ const raw = fs.readFileSync(path.join(snapshotDir, file), 'utf-8')
239
+ const { data, body } = parseFrontmatter(raw)
240
+ // No /m on either: under /m, `$` matches end-of-LINE, so a non-greedy
241
+ // scan stops at the first newline and a hand-wrapped bullet or goal loses
242
+ // every continuation line. Tasks come from findTaskBlocks, which reads a
243
+ // wrapped bullet as one logical task.
244
+ // Collapsed, not just captured: the goal becomes a milestone description,
245
+ // and Linear may canonicalize a soft line break away on save. Collapsing
246
+ // both sides keeps a wrapped goal from diffing forever.
247
+ const goal = collapseHyphenAware(phaseGoal(body))
248
+ // Rendered as markdown checklist lines, ready to drop into a sub-issue
249
+ // description: indentation kept so nesting survives, each bullet keeping
250
+ // the marker its author wrote.
251
+ const lines = body.split('\n')
252
+ const blocks = findTaskBlocks(lines)
253
+ const tasks = blocks.map(renderTaskBlockLine)
254
+ return {
255
+ phase: file.replace(/\.md$/, ''),
256
+ file,
257
+ // The sub-issue id, stamped back into the phase file on first push.
258
+ id: data[fieldsOf(config).issueId] != null ? String(data[fieldsOf(config).issueId]) : null,
259
+ name: phaseTitle(body),
260
+ goal: goal.trim(),
261
+ state: phaseStateBucket(body),
262
+ // Lint-only signals. `emoji` is undefined when the heading carries none
263
+ // — the distinction `state` throws away; `statusLine` is the raw
264
+ // `> **Status:**` value. Neither affects the projection.
265
+ emoji: headingEmoji(body),
266
+ statusLine: phaseStatusLine(body),
267
+ tasks,
268
+ // The raw body and the parsed blocks, so `subIssueBody` can project the
269
+ // file rather than rebuild it from fragments. Not part of the pushed
270
+ // field set — `toFieldSet` picks the projection's keys explicitly.
271
+ lines,
272
+ blocks,
273
+ }
274
+ })
275
+ }
276
+
277
+ // --- phase-status lint ------------------------------------------------------
278
+
279
+ /**
280
+ * Warn where a phase's status signals are absent or disagree.
281
+ *
282
+ * A spec carries the same status in three places — the phase file's h1 emoji,
283
+ * its `> **Status:**` line, and the `00-overview.md` phase-index row — and only
284
+ * the h1 is load-bearing. Writing the other two correctly while leaving the h1
285
+ * bare projects a finished phase as `backlog`, pushes cleanly, and records the
286
+ * wrong value as intended. Nothing looks wrong anywhere.
287
+ *
288
+ * Returns `[{ file, code, message }]`, `code` being `missing-status-emoji` or
289
+ * `status-disagreement`. Pure aside from reads; callers decide how loud to be
290
+ * (today: printed, never fatal).
291
+ */
292
+ function lintPhases(snapshotDir, config) {
293
+ const phases = readPhaseFiles(snapshotDir, config)
294
+ // BLIND SPOT: `readPhaseFiles` only sees `NN-*.md`, so a legacy bare
295
+ // `<name>.md` spec yields no phases at all. Silence is the right answer —
296
+ // there is no phase file to carry an emoji — but it is silence from having
297
+ // looked nowhere, not from having looked and found everything in order.
298
+ if (!phases.length) return []
299
+
300
+ // The overview may be absent (a legacy bare `<name>.md` spec) — that is not
301
+ // itself a lint failure, it just removes one of the three cross-checks.
302
+ let indexRows = []
303
+ try {
304
+ const overviewFile = (config && config.snapshot && config.snapshot.overviewFile) || '00-overview.md'
305
+ const raw = fs.readFileSync(path.join(snapshotDir, overviewFile), 'utf-8')
306
+ const { sections } = parseSections(parseFrontmatter(raw).body)
307
+ indexRows = parsePhaseIndex(sections.Phases)
308
+ } catch {
309
+ indexRows = []
310
+ }
311
+
312
+ const warnings = []
313
+ phases.forEach((phase, i) => {
314
+ if (!phase.emoji) {
315
+ warnings.push({
316
+ file: phase.file,
317
+ code: 'missing-status-emoji',
318
+ message: `no ⬜/🔄/✅ in the heading — projecting as not-started`,
319
+ })
320
+ // Without a heading emoji there is nothing to disagree WITH: the other two
321
+ // signals can't be checked against a value that was never expressed.
322
+ return
323
+ }
324
+
325
+ const heading = EMOJI_STATUS[phase.emoji]
326
+
327
+ const fromLine = statusLineValue(phase.statusLine)
328
+ if (fromLine && fromLine !== heading) {
329
+ warnings.push({
330
+ file: phase.file,
331
+ code: 'status-disagreement',
332
+ message: `heading says ${heading} but its Status line says ${fromLine}`,
333
+ })
334
+ }
335
+
336
+ // Match the index row by phase title, falling back to position — a renamed
337
+ // phase shouldn't silently drop the check.
338
+ //
339
+ // BLIND SPOT: the index is only evidence where it used the emoji vocabulary.
340
+ // A row whose Status cell holds prose (or nothing) parses as `not-started`,
341
+ // which is a default, not a statement — cross-checking against it accused a
342
+ // healthy spec of a disagreement with a value nobody wrote. `stated` is the
343
+ // positive signal: compare only against a status the row actually expressed.
344
+ const row = indexRows.find((r) => r.name === phase.name) || indexRows[i]
345
+ if (row && row.stated && row.status !== heading) {
346
+ warnings.push({
347
+ file: phase.file,
348
+ code: 'status-disagreement',
349
+ message: `heading says ${heading} but the overview phase-index row says ${row.status}`,
350
+ })
351
+ }
352
+ })
353
+ return warnings
354
+ }
355
+
356
+ // --- ownership-driven field set ---------------------------------------------
357
+
358
+ /**
359
+ * Does this repo own `field` — i.e. does the projection carry it at all?
360
+ *
361
+ * THE VALUE DECIDES, NEVER THE KEY'S PRESENCE. A field configured `none` is
362
+ * declared not-ours, and it must be indistinguishable from one the config never
363
+ * listed: both produce a projection with no such key, which is the single
364
+ * vocabulary every downstream reader already speaks for "not in play"
365
+ * (`compare.js` hashes it only when defined; the status report prints an
366
+ * assignee line only when defined).
367
+ *
368
+ * Asked in one place so the two cannot drift. Testing `field in fieldOwnership`
369
+ * at a call site reads correct and is not: once a field is owned by DEFAULT the
370
+ * key is always present, and the test silently becomes "always true".
371
+ */
372
+ function ownsField(config, field) {
373
+ const owned = config && config.sync && config.sync.fieldOwnership
374
+ return !!owned && field in owned && owned[field] !== 'none'
375
+ }
376
+
377
+ // Reduce an `extracted` map to exactly the configured field keys, defaulting a
378
+ // missing field to `null` so local and remote always share an identical set.
379
+ //
380
+ // A declined field is OMITTED, not set null. The two are not interchangeable
381
+ // here: `null` is a value this projection asserts — it is how a finished spec
382
+ // hands its issue back — so writing it for a field the repo does not own would
383
+ // clear in Linear exactly what declining ownership promised not to touch.
384
+ function toFieldSet(extracted, config) {
385
+ const out = {}
386
+ for (const field of Object.keys(config.sync.fieldOwnership)) {
387
+ if (!ownsField(config, field)) continue
388
+ out[field] = field in extracted ? extracted[field] : null
389
+ }
390
+ return out
391
+ }
392
+
393
+ // --- local snapshot ---------------------------------------------------------
394
+
395
+ /**
396
+ * Read a spec snapshot (its 00-overview.md + phase files) into the raw pieces the
397
+ * extractors and callers need. Pure aside from reads under `snapshotDir`.
398
+ */
399
+ function readSnapshot(snapshotDir, config) {
400
+ const overviewFile = (config && config.snapshot && config.snapshot.overviewFile) || '00-overview.md'
401
+ const raw = fs.readFileSync(path.join(snapshotDir, overviewFile), 'utf-8')
402
+ const { data, body } = parseFrontmatter(raw)
403
+ const { title, sections } = parseSections(body)
404
+ const phases = readPhaseFiles(snapshotDir, config)
405
+ return { frontmatter: data, title, sections, phases, body }
406
+ }
407
+
408
+ // Build the pushed description: the overview prose with local-only sections
409
+ // removed. Keeps the title line for context. `extraSkip` drops additional
410
+ // sections (e.g. "Phases" once milestones sync as first-class Linear objects, so
411
+ // the phase list isn't duplicated in the description — Decision 5).
412
+ function buildDescription(title, sections, localOnlySections, extraSkip = [], dialect) {
413
+ const skip = new Set([...(localOnlySections || []), ...extraSkip])
414
+ const parts = []
415
+ if (title) parts.push(`# ${title}`)
416
+ for (const [heading, content] of Object.entries(sections)) {
417
+ if (skip.has(heading)) continue
418
+ parts.push(`## ${heading}\n\n${content}`.trim())
419
+ }
420
+ return dialect.flattenTables(dialect.canonicalize(parts.join('\n\n'))) || null
421
+ }
422
+
423
+ // A phase sub-issue's description: its `**Goal:**` line, plus the phase's task
424
+ // list as a markdown checklist when `mapping.tasks` is `checklist`.
425
+ //
426
+ // The checklist is a READ-ONLY mirror like everything else here — the repo is
427
+ // the source of truth, so a box ticked in the tracker is overwritten on the next
428
+ // push. Without it a sub-issue is a title and one sentence, which is too thin to
429
+ // act on; with it the phase is legible to someone working in the tracker without
430
+ // tasks becoming individually-synced objects again.
431
+ function subIssueBody(phase, tasksMode, localOnlySections, dialect) {
432
+ if (tasksMode !== 'checklist') return dialect.flattenTables(phase.goal)
433
+ return dialect.flattenTables(projectPhaseBody(phase, localOnlySections))
434
+ }
435
+
436
+ /**
437
+ * Project a phase file into its sub-issue body: the file as written, with each
438
+ * task bullet replaced by its rendered single-line form.
439
+ *
440
+ * This used to REBUILD the body from two harvested fragments — the `**Goal:**`
441
+ * paragraph and the task lines `findTaskBlocks` claimed — and silently dropped
442
+ * everything neither covered: prose, whole `##` sections, and any table or
443
+ * fenced block nested under a task. `buildDescription` never had that problem
444
+ * because it projects the overview section by section, so the fix is to make the
445
+ * phase body work the same way — lossless by construction rather than by
446
+ * enumerating the shapes we remembered.
447
+ *
448
+ * Only two things are deliberately left out, and both are pushed as their own
449
+ * field, so keeping them would duplicate:
450
+ *
451
+ * - the `#` h1, projected as the sub-issue's `name`;
452
+ * - the `> **Status:**` line, projected as its `state`.
453
+ *
454
+ * Local-only sections are stripped exactly as they are from the description.
455
+ */
456
+ function projectPhaseBody(phase, localOnlySections) {
457
+ const skip = new Set(localOnlySections || [])
458
+ const lines = phase.lines || []
459
+ const inFence = fenceMask(lines)
460
+ // Where each task block starts, so the walk can emit its rendered form and
461
+ // jump the lines it claims. Line-indexed splicing is what `task-block.js` is
462
+ // built for; everything it does NOT claim is content, and passes through.
463
+ const blockAt = new Map()
464
+ for (const b of phase.blocks || []) blockAt.set(b.start, b)
465
+
466
+ const out = []
467
+ let dropping = false // inside a local-only section
468
+ let seenTitle = false
469
+ for (let i = 0; i < lines.length; i++) {
470
+ const block = blockAt.get(i)
471
+ if (block) {
472
+ if (!dropping) out.push(renderTaskBlockLine(block))
473
+ i = block.end - 1
474
+ continue
475
+ }
476
+ const line = lines[i]
477
+ if (!inFence[i]) {
478
+ const h2 = /^##\s+(.*\S)\s*$/.exec(line)
479
+ if (h2) dropping = skip.has(h2[1].trim())
480
+ if (!seenTitle && /^#\s+/.test(line)) {
481
+ seenTitle = true
482
+ continue
483
+ }
484
+ if (/^>\s*\*\*Status:\*\*/.test(line)) continue
485
+ }
486
+ if (!dropping) out.push(line)
487
+ }
488
+ // Collapse the blank runs the removals leave behind, and trim the ends.
489
+ return out
490
+ .join('\n')
491
+ .replace(/\n{3,}/g, '\n\n')
492
+ .trim()
493
+ }
494
+
495
+ // Phases inline as `###`, hanging under the `## Phases` index that lists them.
496
+ // The body they carry is a whole document in its own right and starts at `##`,
497
+ // so it demotes to sit under that heading rather than break out of it.
498
+ const INLINE_PHASE_LEVEL = 3
499
+ const MAX_HEADING_LEVEL = 6
500
+
501
+ /**
502
+ * Shift every heading in a projected phase body `by` levels, so an inlined phase
503
+ * nests under the `###` that introduces it.
504
+ *
505
+ * Projected for a sub-issue the body is the whole description and its `## Tasks`
506
+ * is correctly top-level. Inlined it is a subsection, and an undemoted `## Tasks`
507
+ * would read as a sibling of `## Problem` — pulling every following phase under
508
+ * it in the outline. Only the `#` run length changes; the content is the same
509
+ * bytes either way, which is the point of sharing one composer.
510
+ */
511
+ function demoteHeadings(body, by) {
512
+ const lines = body.split('\n')
513
+ const inFence = fenceMask(lines)
514
+ return lines
515
+ .map((line, i) => {
516
+ if (inFence[i]) return line
517
+ const h = /^(#{1,6})(\s)/.exec(line)
518
+ if (!h) return line
519
+ return '#'.repeat(Math.min(h[1].length + by, MAX_HEADING_LEVEL)) + line.slice(h[1].length)
520
+ })
521
+ .join('\n')
522
+ }
523
+
524
+ // The phase file's h1 exactly as written — `Phase 2 — The inline projection 🔄`.
525
+ // `projectPhaseBody` drops it because a sub-issue projects the title as `name`
526
+ // and the emoji as `state`; inlined there are no such fields, so this heading is
527
+ // the only place either can live, and the raw line is where both still are.
528
+ function phaseHeading(phase) {
529
+ for (const line of phase.lines || []) {
530
+ const h1 = /^#\s+(.*\S)\s*$/.exec(line)
531
+ if (h1) return h1[1]
532
+ }
533
+ return phase.name
534
+ }
535
+
536
+ /**
537
+ * Append the inlined phases to the spec issue's description as `###` sections.
538
+ *
539
+ * The body is `subIssueBody`'s — the SAME composer the sub-issue form uses, so
540
+ * `inline` inherits its fidelity guarantee instead of growing a second extractor
541
+ * that drops content, which is exactly what the reporting project had to
542
+ * hand-roll before this existed.
543
+ */
544
+ function withInlinePhases(description, inlined, tasksMode, localOnlySections, dialect) {
545
+ if (!inlined.length) return description
546
+ const sections = inlined.map((phase) => {
547
+ const body = demoteHeadings(subIssueBody(phase, tasksMode, localOnlySections, dialect) || '', INLINE_PHASE_LEVEL - 1)
548
+ const heading = '#'.repeat(INLINE_PHASE_LEVEL) + ` ${phaseHeading(phase)}`
549
+ return body ? `${heading}\n\n${body}` : heading
550
+ })
551
+ return [description, ...sections].filter(Boolean).join('\n\n') || null
552
+ }
553
+
554
+ /**
555
+ * Normalize a local spec snapshot into the configured field set.
556
+ */
557
+ // The spec's lifecycle bucket from its folder — the source of truth for status
558
+ // (specs live in specs/<bucket>/<name>/). Maps directly to a `states` key.
559
+ const LIFECYCLE_BUCKETS = ['backlog', 'in-progress', 'complete', 'cancelled']
560
+ function bucketFromPath(snapshotDir) {
561
+ const parent = path.basename(path.dirname(snapshotDir))
562
+ return LIFECYCLE_BUCKETS.includes(parent) ? parent : null
563
+ }
564
+
565
+ // Lifecycle buckets in which a spec's work has not begun: never started, or
566
+ // abandoned without ever starting. Under `mapping.phases: 'deferred'` these are
567
+ // the states in which phases are not yet worth minting as sub-issues.
568
+ const UNSTARTED_BUCKETS = ['backlog', 'cancelled']
569
+
570
+ // Buckets where a spec is FINISHED, and so has nobody working on it.
571
+ const TERMINAL_BUCKETS = ['complete', 'cancelled']
572
+
573
+ /**
574
+ * The Linear user this spec is assigned to, AS PROJECTED — which is not simply
575
+ * what the frontmatter records.
576
+ *
577
+ * The BUCKET decides, not the stamp's presence. A spec that is live (`backlog`,
578
+ * `in-progress`) projects whoever the repo recorded; a finished one projects
579
+ * `null`, so completing a spec hands the issue back with no unassign step for
580
+ * anyone to remember. The stamp itself is deliberately left in the spec file:
581
+ * `> **Developer:**` and the frontmatter are the durable record of who actioned
582
+ * the work, and that outlives the assignment.
583
+ *
584
+ * `null` here does NOT mean "clear it in Linear" on its own — see
585
+ * `issueChanges`, where an assignee that was never pushed is left alone rather
586
+ * than retracted. That is what stops this wiping a PM's triage.
587
+ */
588
+ function assigneeFor(workflowState, frontmatter, config) {
589
+ if (TERMINAL_BUCKETS.includes(String(workflowState))) return null
590
+ const id = frontmatter && frontmatter[fieldsOf(config).assigneeId]
591
+ return typeof id === 'string' && id.trim() ? id.trim() : null
592
+ }
593
+
594
+ // The mode a bucket gets when a per-bucket `mapping.phases` map omits it. Adding
595
+ // a bucket to the map is therefore an EXCEPTION for that bucket, not a switch
596
+ // that silently suppresses phases everywhere the map is silent. Matches the
597
+ // scalar default in the provider's config so both forms start from one place.
598
+ const DEFAULT_PHASE_MODE = 'subissue'
599
+
600
+ /**
601
+ * The phase mode configured for one lifecycle bucket.
602
+ *
603
+ * `mapping.phases` is EITHER a scalar — one mode for the whole repo, which is
604
+ * what every config was before per-bucket mapping — or a map keyed by lifecycle
605
+ * bucket (`{ backlog: 'subissue', complete: 'inline' }`), because a repo can
606
+ * legitimately want assignable sub-issues for work in flight and none at all for
607
+ * 250 finished specs. A scalar resolves to itself for every bucket, so existing
608
+ * configs are unchanged.
609
+ *
610
+ * The SINGLE place a mode is decided: the projection and the description's
611
+ * `## Phases` index both read it, so they cannot disagree about one spec.
612
+ */
613
+ function phaseModeFor(bucket, config) {
614
+ const configured = config && config.mapping && config.mapping.phases
615
+ if (typeof configured === 'string') return configured
616
+ if (configured && typeof configured === 'object' && !Array.isArray(configured)) {
617
+ const mode = configured[bucket]
618
+ return typeof mode === 'string' ? mode : DEFAULT_PHASE_MODE
619
+ }
620
+ return DEFAULT_PHASE_MODE
621
+ }
622
+
623
+ /**
624
+ * Which phases the projection sends, and how many the `deferred` mapping is
625
+ * holding back. Pure — split out so both the projection and the CLI's "N phases
626
+ * deferred" line read the SAME predicate rather than two copies of it.
627
+ *
628
+ * Only UNLINKED phases are withheld. A phase that already carries an id keeps
629
+ * projecting whatever the mode: one-way sync has no delete op, so withholding a
630
+ * live sub-issue would not remove it from the tracker — it would freeze it there,
631
+ * never updated again. That makes switching a project to `deferred` safe.
632
+ */
633
+ // The spec's lifecycle status as projected: its folder bucket, unless the
634
+ // overview frontmatter pins `spec_status`. Shared by the projection and by
635
+ // `phasesWithheld` so the two can never disagree about whether work has started.
636
+ function specStatus(snapshotDir, frontmatter) {
637
+ return frontmatter && frontmatter.spec_status != null
638
+ ? String(frontmatter.spec_status)
639
+ : bucketFromPath(snapshotDir)
640
+ }
641
+
642
+ function phaseProjection(phases, workflowState, config) {
643
+ const named = phases.filter((p) => p.name)
644
+ const mode = phaseModeFor(workflowState, config)
645
+ // `deferred` and `inline` both send only phases that ALREADY carry an id, and
646
+ // for the same reason: one-way sync has no delete op, so withholding a live
647
+ // sub-issue would freeze it in the tracker rather than remove it (Decision 4).
648
+ // They differ only in where an unlinked phase goes — nowhere yet, or into the
649
+ // spec issue's own description.
650
+ const deferring = mode === 'deferred' && UNSTARTED_BUCKETS.includes(workflowState)
651
+ const projected = deferring || mode === 'inline' ? named.filter((p) => p.id != null) : named
652
+ const unlinked = named.filter((p) => p.id == null)
653
+ return {
654
+ projected,
655
+ // Held back until the work starts. Nothing carries them meanwhile, which is
656
+ // why the `## Phases` index stays and the CLI says how many.
657
+ withheld: deferring ? unlinked.length : 0,
658
+ // Rendered into the description instead. Deliberately NOT counted as
659
+ // withheld: nothing is missing from the mirror, so a report that said "N
660
+ // phases deferred" would be describing the opposite of what happened.
661
+ inlined: mode === 'inline' ? unlinked : [],
662
+ }
663
+ }
664
+
665
+ function normalizeLocal(snapshotDir, config) {
666
+ const dialect = dialectOf(config)
667
+ const { frontmatter, title, sections, phases } = readSnapshot(snapshotDir, config)
668
+ const tasksMode = (config.mapping && config.mapping.tasks) || 'checklist'
669
+ // Status is the spec's lifecycle bucket. The folder is the source of truth; an
670
+ // explicit `spec_status` frontmatter key overrides it if present. Resolved
671
+ // BEFORE the sub-issue projection because deferral withholds phases by this
672
+ // status — so the issue's state and its sub-issues always agree on whether the
673
+ // work has started, however that status was arrived at.
674
+ const workflowState = specStatus(snapshotDir, frontmatter)
675
+ const { projected, withheld, inlined } = phaseProjection(phases, workflowState, config)
676
+
677
+ // Strip the `## Phases` index only when the SUB-ISSUES replace it: they carry
678
+ // every phase, so keeping the index would duplicate the list as prose AND as
679
+ // objects. It stays whenever they do not — while deferral holds a phase back
680
+ // the index is the only place that phase appears, and under `inline` there are
681
+ // no new sub-issues at all, so it is the issue's only table of contents
682
+ // (Decision 3).
683
+ //
684
+ // Keyed on the resolved MODE rather than on `subIssues` being an owned field:
685
+ // ownership says WHICH fields sync, which is a different question from how
686
+ // phases are shaped, and `inline` answers the second one per spec (Decision 5).
687
+ // Ownership still gets a say — an unowned `subIssues` pushes no sub-issues at
688
+ // all, so the index has to stay there too.
689
+ const syncsSubIssues = !!(config.sync.fieldOwnership && 'subIssues' in config.sync.fieldOwnership)
690
+ const phasesCarriedBySubIssues =
691
+ syncsSubIssues && phaseModeFor(workflowState, config) !== 'inline' && withheld === 0
692
+ const extracted = {
693
+ description: withInlinePhases(
694
+ buildDescription(
695
+ title,
696
+ sections,
697
+ config.sync.localOnlySections,
698
+ phasesCarriedBySubIssues ? ['Phases'] : [],
699
+ dialect,
700
+ ),
701
+ inlined,
702
+ tasksMode,
703
+ config.sync.localOnlySections,
704
+ dialect,
705
+ ),
706
+ // Sub-issue projection: one per phase. `ref` is the phase-file basename — the
707
+ // local handle the push skill stamps a newly-created sub-issue id back into.
708
+ // `state` is the phase's status bucket (from its heading emoji), mapped to a
709
+ // Linear issue state via `config.states` at push time. Tasks ride along in
710
+ // the description as a read-only checklist (`mapping.tasks`), never as
711
+ // individually-synced objects.
712
+ subIssues: projected.map((p) => ({
713
+ id: p.id,
714
+ ref: p.phase,
715
+ name: p.name,
716
+ goal: subIssueBody(p, tasksMode, config.sync.localOnlySections, dialect),
717
+ state: p.state,
718
+ })),
719
+ workflowState,
720
+ // Who is building this. `toFieldSet` drops it unless the repo listed
721
+ // `assignee` in `sync.fieldOwnership`, so the opt-in costs no extra check
722
+ // here — an un-opted-in repo simply has no such key on its projection, and
723
+ // every downstream reader treats that as "the field is not in play".
724
+ assignee: assigneeFor(workflowState, frontmatter, config),
725
+ }
726
+ return toFieldSet(extracted, config)
727
+ }
728
+
729
+ /**
730
+ * How many phases `mapping.phases: 'deferred'` is currently holding back for
731
+ * this spec — 0 in every other mode.
732
+ *
733
+ * Deliberately NOT a key on `normalizeLocal`'s return: that is the configured
734
+ * field set and nothing else, so a reporting-only value cannot drift into the
735
+ * synced shape (or a hash). Callers that want to SAY "N phases deferred" ask for
736
+ * it, at the cost of a second read of a handful of small files.
737
+ */
738
+ function phasesWithheld(snapshotDir, config) {
739
+ const { frontmatter, phases } = readSnapshot(snapshotDir, config)
740
+ return phaseProjection(phases, specStatus(snapshotDir, frontmatter), config).withheld
741
+ }
742
+
743
+ // --- remote projection ------------------------------------------------------
744
+
745
+ // The lifecycle bucket a deployment ladder descends FROM. A spec is handed over
746
+ // to the deploy pipeline once it is finished, so every rung sits downstream of
747
+ // `complete` — a ticket on "On Test" is a completed spec that has been deployed,
748
+ // not a spec that moved somewhere else.
749
+ const LADDER_ORIGIN_BUCKET = 'complete'
750
+
751
+ // The declared ladder rung with this state name, or null.
752
+ function stageForState(state, config) {
753
+ if (state == null) return null
754
+ const want = String(state).toLowerCase().trim()
755
+ const stages = (config && config.release && config.release.stages) || []
756
+ if (!Array.isArray(stages)) return null
757
+ return stages.find((s) => s && typeof s.state === 'string' && s.state.toLowerCase().trim() === want) || null
758
+ }
759
+
760
+ // Map a remote workflow-state name back to the local lifecycle bucket (the
761
+ // vocabulary `spec_status` uses) via config.states, so local and remote
762
+ // workflowState hash equal when semantically equal. Falls back to a lowercased
763
+ // raw value when the state isn't one of the configured names.
764
+ //
765
+ // A DECLARED DEPLOYMENT STAGE reads as `complete`, deliberately. Without this
766
+ // the fallback lowercases it — "On Test" becomes "on test", which equals no
767
+ // bucket — and every deployed spec reports as drifted forever, for the whole
768
+ // time it sits in the pipeline. The project told us these states are downstream
769
+ // of a finished spec, so they are not a disagreement about where the spec is.
770
+ function bucketForState(state, config) {
771
+ if (state == null) return null
772
+ const states = (config && config.states) || {}
773
+ const want = String(state).toLowerCase().trim()
774
+ for (const [bucket, name] of Object.entries(states)) {
775
+ if (typeof name === 'string' && name.toLowerCase().trim() === want) return bucket
776
+ }
777
+ if (stageForState(state, config)) return LADDER_ORIGIN_BUCKET
778
+ return want
779
+ }
780
+
781
+ // Canonicalise a remote workflow-state name into the same vocabulary the local
782
+ // milestone emojis use, so equal states hash equal.
783
+ function canonicalRemoteStatus(state) {
784
+ const s = String(state || '').toLowerCase().trim()
785
+ if (!s) return 'not-started'
786
+ if (/(done|complete|completed|merged)/.test(s)) return 'done'
787
+ if (/(progress|started|doing|review)/.test(s)) return 'in-progress'
788
+ if (/(backlog|todo|planned|triage)/.test(s)) return 'not-started'
789
+ return s
790
+ }
791
+
792
+ // A tracker issue usually carries its workflow state in `state` (an object
793
+ // `{ name, type }`); accept `status` / a bare string too for robustness. A
794
+ // provider whose remote shape differs supplies `config.remote.stateName`.
795
+ function remoteStateName(issue, config) {
796
+ const hook = config && config.remote && config.remote.stateName
797
+ if (typeof hook === 'function') return hook(issue)
798
+ const st = issue.state != null ? issue.state : issue.status
799
+ if (st == null) return null
800
+ if (typeof st === 'object') return st.name != null ? st.name : st.type != null ? st.type : null
801
+ return st
802
+ }
803
+
804
+ // The ONE thing one-way sync reads back: the mirror issue's current workflow
805
+ // state, mapped to the local lifecycle bucket, so `/spec-status` can report a
806
+ // drift ("the tracker says Done, your spec says In Progress"). Read-only — never writes.
807
+ function remoteWorkflowState(issue, config) {
808
+ const name = remoteStateName(issue || {}, config)
809
+ return name != null ? bucketForState(name, config) : null
810
+ }
811
+
812
+ // The declared ladder rung a remote issue is currently sitting on, or null.
813
+ // Pairs with `remoteWorkflowState`: that says which bucket the issue maps to,
814
+ // this says whether it got there by being deployed. Read-only.
815
+ function remoteStage(issue, config) {
816
+ return stageForState(remoteStateName(issue || {}, config), config)
817
+ }
818
+
819
+ // A Linear issue title is plain text, so markdown emphasis is noise there — and
820
+ // worse, an emphasis run cut mid-title (or a bold LABEL like `**1. Foo**`) can
821
+ // leave a dangling `**`. Strip `*` emphasis markers and unwrap `[text](url)` to
822
+ // `text`. Backticks and `_` are KEPT: task labels lean on inline code
823
+ // (`` `DbFoo` ``) and identifiers use snake_case, and neither breaks a title.
824
+ function stripTitleMarkup(t) {
825
+ return t
826
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1') // [text](url) -> text
827
+ .replace(/\*/g, '') // bold/italic markers (incl. a dangling ** from a cut)
828
+ .replace(/\s+/g, ' ')
829
+ .trim()
830
+ }
831
+
832
+ // Trim a trailing parenthetical whose opener has no matching close — so a cut
833
+ // title never ends on a dangling `(`/`[`.
834
+ function dropUnclosedBracket(t) {
835
+ for (const [open, close] of [
836
+ ['(', ')'],
837
+ ['[', ']'],
838
+ ]) {
839
+ const o = t.lastIndexOf(open)
840
+ if (o !== -1 && t.indexOf(close, o) === -1) t = t.slice(0, o)
841
+ }
842
+ return t
843
+ }
844
+
845
+ // Derive a short Linear issue title from a task's full text: the first sentence,
846
+ // falling back to the first `max` chars at a word boundary. A paragraph-length
847
+ // task keeps its full text as the issue *description* (see the projection); this
848
+ // is only the title, so it must read as a one-liner. Guards decimals/versions
849
+ // (`7.0.2`) and common abbreviations (`e.g.`, `i.e.`, `etc.`) so it doesn't cut
850
+ // mid-number or mid-abbreviation.
851
+ function titleFromText(text, max = 100) {
852
+ const s = collapse(text)
853
+ if (!s) return s
854
+ let title = s
855
+ const re = /[.!?]/g
856
+ let m
857
+ while ((m = re.exec(s)) !== null) {
858
+ const i = m.index
859
+ const after = s[i + 1]
860
+ if (after !== undefined && !/\s/.test(after)) continue // not a sentence end
861
+ if (/\d/.test(s[i - 1] || '') && /\d/.test(after || '')) continue // 7.0.2, 3.14
862
+ if (/(?:^|[^\w])\d+$/.test(s.slice(0, i))) continue // list ordinal "1." "2."
863
+ if (/(^|\s)(e\.g|i\.e|etc|vs|no|fig|cf)$/i.test(s.slice(0, i))) continue // abbrev
864
+ title = s.slice(0, i) // drop the terminator
865
+ break
866
+ }
867
+ title = title.trim()
868
+ if (title.length > max) {
869
+ const cut = title.slice(0, max)
870
+ // Prefer the last clause boundary before the limit — a terminator/separator
871
+ // to cut AFTER (`.`/`;`/`:`…) or a dash to cut BEFORE — over a bare word break.
872
+ const minCut = Math.floor(max * 0.4)
873
+ let boundary = -1
874
+ let mm
875
+ const after = /[.!?;:](?=\s|$)/g
876
+ while ((mm = after.exec(cut)) !== null) boundary = Math.max(boundary, mm.index + 1)
877
+ const before = /\s[—–]/g
878
+ while ((mm = before.exec(cut)) !== null) boundary = Math.max(boundary, mm.index)
879
+ let t
880
+ if (boundary > minCut) {
881
+ t = cut.slice(0, boundary)
882
+ } else {
883
+ const sp = cut.lastIndexOf(' ')
884
+ t = sp > 40 ? cut.slice(0, sp) : cut
885
+ }
886
+ title = dropUnclosedBracket(t).replace(/[\s.,:;—–([]+$/, '').trim()
887
+ }
888
+ return stripTitleMarkup(title)
889
+ }
890
+
891
+ // Every state NAME the config points at: the lifecycle bucket map, plus the
892
+ // project's deployment ladder when it declares one. Both reach Linear the same
893
+ // way and fail the same way, so both are checked by the same lookup.
894
+ function configuredStateNames(config) {
895
+ const names = Object.values((config && config.states) || {}).filter((v) => typeof v === 'string')
896
+ const stages = (config && config.release && config.release.stages) || []
897
+ for (const stage of Array.isArray(stages) ? stages : []) {
898
+ if (stage && typeof stage.state === 'string') names.push(stage.state)
899
+ }
900
+ return names
901
+ }
902
+
903
+ // Which configured state NAMES are absent from the live workspace. The skill
904
+ // fetches the workspace's project-status names over MCP and passes them here;
905
+ // a non-empty result means a typo/rename that Linear would silently no-op.
906
+ //
907
+ // A project with no `release.stages` contributes nothing here, so the ladder
908
+ // cannot make this accuse a config that was fine before it existed.
909
+ function validateStates(config, workspaceStates) {
910
+ const configured = configuredStateNames(config)
911
+ const have = new Set((workspaceStates || []).map((s) => String(s).toLowerCase().trim()))
912
+ return configured.filter((name) => !have.has(name.toLowerCase().trim()))
913
+ }
914
+
915
+ // Words that identify a workspace state as belonging to a lifecycle bucket.
916
+ // Used only to SUGGEST a replacement for a configured name the workspace does
917
+ // not have — never to pick one silently. The 8→9 case this exists for is
918
+ // `complete`, where the correct value inverts: the project status `Completed`
919
+ // became the issue state `Done`, and no string-distance measure gets you from
920
+ // one to the other.
921
+ const BUCKET_WORDS = {
922
+ backlog: ['backlog', 'triage', 'todo', 'to do'],
923
+ 'in-progress': ['in progress', 'in-progress', 'doing', 'started', 'in review'],
924
+ complete: ['done', 'complete', 'completed', 'shipped', 'merged', 'released'],
925
+ cancelled: ['canceled', 'cancelled', 'abandoned', "won't do", 'wont do', 'duplicate'],
926
+ }
927
+
928
+ /**
929
+ * For each configured state name the workspace lacks, what to use instead.
930
+ *
931
+ * `validateStates` says a name is wrong; this says what is right, which is the
932
+ * difference between an error you can act on and one you have to go look up.
933
+ *
934
+ * @returns {Array<{bucket:string, configured:string, suggestion:string|null}>}
935
+ */
936
+ function stateSuggestions(config, workspaceStates) {
937
+ const names = (workspaceStates || []).map((s) => String(s)).filter(Boolean)
938
+ const have = new Set(names.map((n) => n.toLowerCase().trim()))
939
+ const out = []
940
+ for (const [bucket, configured] of Object.entries((config && config.states) || {})) {
941
+ if (typeof configured !== 'string') continue
942
+ if (have.has(configured.toLowerCase().trim())) continue
943
+ const words = BUCKET_WORDS[bucket] || []
944
+ const suggestion = names.find((n) => words.includes(n.toLowerCase().trim())) || null
945
+ out.push({ bucket, configured, suggestion, label: `states.${bucket}` })
946
+ }
947
+ // Deployment-ladder rungs, reported the same way. No suggestion is offered:
948
+ // BUCKET_WORDS describes lifecycle vocabulary, and a stage name is the
949
+ // project's own — guessing "On Test" meant "In Progress" would be worse than
950
+ // saying nothing.
951
+ const stages = (config && config.release && config.release.stages) || []
952
+ for (const stage of Array.isArray(stages) ? stages : []) {
953
+ if (!stage || typeof stage.state !== 'string') continue
954
+ if (have.has(stage.state.toLowerCase().trim())) continue
955
+ out.push({
956
+ bucket: null,
957
+ configured: stage.state,
958
+ suggestion: null,
959
+ label: `release.stages[${stage.key}]`,
960
+ })
961
+ }
962
+ return out
963
+ }
964
+
965
+ module.exports = {
966
+ ownsField,
967
+ stateSuggestions,
968
+ configuredStateNames,
969
+ normalizeLocal,
970
+ assigneeFor,
971
+ phaseProjection,
972
+ phaseModeFor,
973
+ phasesWithheld,
974
+ lintPhases,
975
+ readSnapshot,
976
+ parseFrontmatter,
977
+ parseSections,
978
+ parsePhaseIndex,
979
+ parseTaskLine,
980
+ titleFromText,
981
+ validateStates,
982
+ canonicalRemoteStatus,
983
+ bucketForState,
984
+ LIFECYCLE_BUCKETS,
985
+ stageForState,
986
+ remoteStage,
987
+ remoteWorkflowState,
988
+ LADDER_ORIGIN_BUCKET,
989
+ }