@skitterbyte/skitterspec-jira 2.0.0 → 2.2.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.
@@ -26,6 +26,9 @@ const {
26
26
  isEmptyPlan,
27
27
  validateStates,
28
28
  stateSuggestions,
29
+ effectiveStates,
30
+ specHeaders,
31
+ linkedIncident,
29
32
  remoteDescriptionEdited,
30
33
  writeFrontmatter,
31
34
  stampSubIssueId,
@@ -72,6 +75,41 @@ function stateCheckFailure(config, flags) {
72
75
  } catch (error) {
73
76
  return [`${PROGRAM} plan: refusing — --workspace-states is not valid JSON: ${error.message}`]
74
77
  }
78
+ // The keyed shape (`{ "<issue type>": [names] }`, what `states --json`
79
+ // prints) is checked PER TYPE: each configured type's effective statuses —
80
+ // statesByType over states, nulls skipped — against that type's own
81
+ // workflow, so a status one type's workflow lacks refuses before the first
82
+ // write even when another type can reach it.
83
+ if (names && typeof names === 'object' && !Array.isArray(names)) {
84
+ const lc = (s) => String(s).toLowerCase().trim()
85
+ const types = [
86
+ ...new Set(
87
+ [config.jira.issueType, config.jira.subtaskType, ...Object.values(config.jira.issueTypeByKind || {})].filter(Boolean),
88
+ ),
89
+ ]
90
+ const problems = []
91
+ for (const type of types) {
92
+ const have = names[type]
93
+ // A TYPE THE FILE LACKS IS A CANNOT-TELL, not a refusal: an absence
94
+ // here is an older file or a type the fetch could not read, and neither
95
+ // is evidence the config is wrong (negative-checks.md rule 4).
96
+ if (!Array.isArray(have)) continue
97
+ const haveSet = new Set(have.map(lc))
98
+ const effective = effectiveStates(config, config.statesByType, type)
99
+ for (const [bucket, name] of Object.entries(effective)) {
100
+ if (typeof name !== 'string') continue // null = send no status
101
+ if (!haveSet.has(lc(name))) problems.push({ type, bucket, name, available: have })
102
+ }
103
+ }
104
+ if (!problems.length) return null
105
+ const lines = [`${PROGRAM} plan: refusing — configured status name(s) missing from the type that would receive them`, '']
106
+ for (const p of problems) {
107
+ lines.push(` ${p.type}: "${p.name}" (states.${p.bucket}) is not a status this type's workflow has`)
108
+ lines.push(` ${p.type} has: ${p.available.join(', ') || '(none reported)'}`)
109
+ }
110
+ lines.push('', ` Fix ${CONFIG_FILE} -> states / statesByType.`)
111
+ return lines
112
+ }
75
113
  const list = Array.isArray(names) ? names : []
76
114
  const missing = validateStates(config, list)
77
115
  if (missing.length) {
@@ -90,21 +128,68 @@ function stateCheckFailure(config, flags) {
90
128
  // Apply ops: the kit orchestration with Jira's tracker calls. Status is moved
91
129
  // by TRANSITION after the create/update — Jira has no "set status" field — and
92
130
  // `transitionTo` is idempotent when the issue already sits on the target.
93
- function applyOps({ adapter, config }) {
94
- const statusFor = (bucket) => {
95
- const name = config.states && config.states[bucket]
131
+ // A spec's KIND, read off its folder prefix — the same convention the
132
+ // lifecycle skills stamp into `> **Type:**`, but greppable with no file read.
133
+ function specKindOf(snapshotDir) {
134
+ const name = path.basename(String(snapshotDir || ''))
135
+ if (name.startsWith('bug-')) return 'bug'
136
+ if (name.startsWith('hotfix-')) return 'hotfix'
137
+ if (name.startsWith('chore-')) return 'chore'
138
+ if (name.startsWith('issue-')) return 'issue'
139
+ if (name.startsWith('incident-')) return 'incident'
140
+ return 'feature'
141
+ }
142
+
143
+ function applyOps({ adapter, config, kind = 'feature', snapshotDir = null, out = null }) {
144
+ // The mint type for THIS spec's kind (jira.issueTypeByKind), falling back to
145
+ // the one configured type — unmapped kinds mint exactly as before.
146
+ const mintType = (config.jira.issueTypeByKind && config.jira.issueTypeByKind[kind]) || config.jira.issueType
147
+ // Push-time extras off the spec's own headers: `Severity:` lands in the
148
+ // site's own field (`jira.severityField`, opt-in — unset, the header stays
149
+ // repo-only), `Incident:` as a "Relates" issue link. Neither is a synced
150
+ // field, so neither touches the stored-base hashes.
151
+ const severity = snapshotDir ? specHeaders(snapshotDir, config).severity : null
152
+ const severityFields =
153
+ severity != null && config.jira.severityField ? { [config.jira.severityField]: severity } : undefined
154
+ const incident = snapshotDir ? linkedIncident(snapshotDir, config) : null
155
+ const relateToIncident = async (keyOrId) => {
156
+ if (!incident) return
157
+ if (!incident.identifier) {
158
+ if (out) out.write(` !! related incident ${incident.name} is not linked yet — link skipped\n`)
159
+ return
160
+ }
161
+ if (typeof adapter.createRelatedLink !== 'function') return
162
+ // Jira stacks duplicate links, and a push runs per phase — so an existing
163
+ // link to the incident is the skip condition, not an error to swallow.
164
+ if (typeof adapter.listRelatedLinks === 'function') {
165
+ const linked = await adapter.listRelatedLinks(keyOrId)
166
+ if (linked.includes(incident.identifier)) return
167
+ }
168
+ await adapter.createRelatedLink(keyOrId, incident.identifier)
169
+ if (out) out.write(` related link added: ${incident.identifier}\n`)
170
+ }
171
+ // Per-type resolution: statesByType[issue type] overlays states, and null
172
+ // means "send no status for this bucket" — a deliberate skip, not a gap.
173
+ const statusFor = (bucket, type) => {
174
+ const name = effectiveStates(config, config.statesByType, type)[bucket]
175
+ if (name === null) return null
96
176
  if (!name) {
97
177
  throw new Error(`no status configured for the "${bucket}" bucket — fix ${CONFIG_FILE} -> states`)
98
178
  }
99
179
  return name
100
180
  }
101
- const settle = async (keyOrId, bucket) => {
181
+ const settle = async (keyOrId, bucket, type) => {
102
182
  if (!bucket) return
103
- await adapter.transitionTo(keyOrId, statusFor(bucket))
183
+ const name = statusFor(bucket, type)
184
+ if (name === null) return
185
+ await adapter.transitionTo(keyOrId, name)
104
186
  }
105
187
  return {
106
188
  prevalidateStates: (buckets) => {
107
- for (const bucket of buckets) statusFor(bucket)
189
+ for (const bucket of buckets) {
190
+ statusFor(bucket, mintType)
191
+ statusFor(bucket, config.jira.subtaskType)
192
+ }
108
193
  },
109
194
  searchTwin: (title) => adapter.searchIssues({ query: title, projectKey: config.jira.projectKey }),
110
195
  twinAdvice: (twin, wanted, specName) =>
@@ -120,9 +205,11 @@ function applyOps({ adapter, config }) {
120
205
  description: issue && issue.description != null ? issue.description : undefined,
121
206
  assigneeId: issue && issue.assignee ? issue.assignee : undefined,
122
207
  projectKey: config.jira.projectKey,
123
- issueTypeName: config.jira.issueType,
208
+ issueTypeName: mintType,
209
+ extraFields: severityFields,
124
210
  })
125
- await settle(created.identifier, issue && issue.state)
211
+ await settle(created.identifier, issue && issue.state, mintType)
212
+ await relateToIncident(created.identifier)
126
213
  return created
127
214
  },
128
215
  updateIssue: async (existing, issue) => {
@@ -131,8 +218,10 @@ function applyOps({ adapter, config }) {
131
218
  // Null is meaningful here — it is how Jira unassigns — so the key is
132
219
  // forwarded whenever the plan carries it, never truthiness-tested.
133
220
  if ('assignee' in issue) updates.assigneeId = issue.assignee ?? null
221
+ if (severityFields) updates.extraFields = severityFields
134
222
  if (Object.keys(updates).length) await adapter.updateIssue(existing.identifier, updates)
135
- await settle(existing.identifier, issue.state)
223
+ await settle(existing.identifier, issue.state, mintType)
224
+ await relateToIncident(existing.identifier)
136
225
  },
137
226
  mintSubIssue: async (parentId, sub) => {
138
227
  const created = await adapter.createSubIssue(parentId, {
@@ -141,7 +230,7 @@ function applyOps({ adapter, config }) {
141
230
  projectKey: config.jira.projectKey,
142
231
  subtaskTypeName: config.jira.subtaskType,
143
232
  })
144
- await settle(created.identifier, sub.state)
233
+ await settle(created.identifier, sub.state, config.jira.subtaskType)
145
234
  return created
146
235
  },
147
236
  updateSubIssue: async (sub) => {
@@ -149,7 +238,7 @@ function applyOps({ adapter, config }) {
149
238
  if (sub.name != null) updates.title = sub.name
150
239
  if (sub.goal != null) updates.description = sub.goal
151
240
  if (Object.keys(updates).length) await adapter.updateIssue(sub.id, updates)
152
- await settle(sub.id, sub.state)
241
+ await settle(sub.id, sub.state, config.jira.subtaskType)
153
242
  },
154
243
  }
155
244
  }
@@ -241,7 +330,7 @@ async function specSyncApply(dir, config, specArg, flags, out, err) {
241
330
  snapshotDir,
242
331
  plan,
243
332
  adapter: cred.adapter,
244
- ops: applyOps({ adapter: cred.adapter, config }),
333
+ ops: applyOps({ adapter: cred.adapter, config, kind: specKindOf(snapshotDir), snapshotDir, out }),
245
334
  forceNew: !!flags.forceNew,
246
335
  program: PROGRAM,
247
336
  })
@@ -491,15 +580,31 @@ async function specSyncStates(dir, config, flags, out) {
491
580
  return 1
492
581
  }
493
582
  let states
583
+ let byType = null
494
584
  try {
495
- states = await cred.adapter.listIssueStates(config.jira.projectKey)
585
+ if (typeof cred.adapter.listIssueStatesByType === 'function') {
586
+ byType = await cred.adapter.listIssueStatesByType(config.jira.projectKey)
587
+ const byName = new Map()
588
+ for (const list of Object.values(byType)) for (const s of list) if (!byName.has(s.name)) byName.set(s.name, s)
589
+ states = [...byName.values()]
590
+ } else {
591
+ states = await cred.adapter.listIssueStates(config.jira.projectKey)
592
+ }
496
593
  } catch (error) {
497
594
  out.write(`${PROGRAM} states: ${error.message}\n`)
498
595
  return 1
499
596
  }
500
597
  const names = states.map((s) => s.name)
501
598
  if (flags.json) {
502
- // The bare array --workspace-states consumes.
599
+ if (byType) {
600
+ // The keyed shape --workspace-states consumes: `{ "<type>": [names] }`,
601
+ // so the pre-write check can validate each type against its own
602
+ // workflow. (A bare array from an older engine is still accepted there.)
603
+ const keyed = {}
604
+ for (const [type, list] of Object.entries(byType)) keyed[type] = list.map((s) => s.name)
605
+ out.write(JSON.stringify(keyed, null, 2) + '\n')
606
+ return 0
607
+ }
503
608
  out.write(JSON.stringify(names, null, 2) + '\n')
504
609
  return 0
505
610
  }
@@ -526,6 +631,29 @@ async function specSyncStates(dir, config, flags, out) {
526
631
  lines.push(` ${bucket.padEnd(bw)} -> ${String(name).padEnd(nw)} ${tail}`)
527
632
  }
528
633
  if (missing.length) lines.push(` remap: ${PROGRAM} init-config --force --state <bucket>="<status>"`)
634
+ // Per-type overrides, each checked against ITS issue type's own workflow —
635
+ // the union above cannot see a status one type lacks. Absent entirely when
636
+ // no statesByType is configured; "not checked" when the adapter could not
637
+ // list statuses per type.
638
+ const overrideTypes = Object.keys(config.statesByType || {})
639
+ if (overrideTypes.length) {
640
+ lines.push('', ' statesByType overrides, checked per issue type:')
641
+ const lc = (s) => String(s).toLowerCase().trim()
642
+ for (const type of overrideTypes) {
643
+ const have = byType && type in byType ? new Set(byType[type].map((s) => lc(s.name))) : null
644
+ for (const [bucket, name] of Object.entries(config.statesByType[type])) {
645
+ const tail =
646
+ name === null
647
+ ? 'sends no status'
648
+ : have === null
649
+ ? 'not checked — statuses not listed per type'
650
+ : have.has(lc(name))
651
+ ? 'ok'
652
+ : "MISSING from this type's workflow"
653
+ lines.push(` ${type}.${bucket} -> ${name === null ? '(none)' : name} ${tail}`)
654
+ }
655
+ }
656
+ }
529
657
  out.write(lines.join('\n') + '\n')
530
658
  return 0
531
659
  }
@@ -685,6 +813,50 @@ function specSyncReleased(dir, config, rangeArg, flags, out) {
685
813
  }
686
814
 
687
815
  // ---------------------------------------------------------------------------
816
+
817
+ // `comment <spec> --file <f>` — post a file's markdown onto the spec's issue
818
+ // as a comment: the one surface one-way sync never touches, so no later push
819
+ // can clobber it. `/spec-complete` posts an incident's log through this.
820
+ // Misuse (no readable file) exits 1; every cannot-tell exits 0 and says so.
821
+ async function specSyncComment(dir, config, specArg, flags, out) {
822
+ const snapshotDir = resolveOrExit(specArg, dir, out)
823
+ if (!snapshotDir) return 1
824
+ const done = (msg) => {
825
+ out.write(`${PROGRAM} comment: ${msg}\n`)
826
+ return 0
827
+ }
828
+ if (!flags.file) {
829
+ out.write(`${PROGRAM} comment: pass --file <markdown file to post>\n`)
830
+ return 1
831
+ }
832
+ let body
833
+ try {
834
+ body = fs.readFileSync(flags.file, 'utf-8')
835
+ } catch (error) {
836
+ out.write(`${PROGRAM} comment: cannot read --file: ${error.message}\n`)
837
+ return 1
838
+ }
839
+ if (!body.trim()) {
840
+ out.write(`${PROGRAM} comment: --file is empty — nothing to post\n`)
841
+ return 1
842
+ }
843
+ const overviewFile = (config.snapshot && config.snapshot.overviewFile) || '00-overview.md'
844
+ const identifier = specHelpers.linkedIdentifier(path.join(snapshotDir, overviewFile), config)
845
+ if (!identifier) return done(`${path.basename(snapshotDir)} is not linked — nothing posted`)
846
+ const cred = apiAdapterFor(config, flags)
847
+ const transport = kit.resolveTransport(flags, config, cred.ok)
848
+ if (transport === 'mcp') {
849
+ return done(`transport = mcp — post the file's contents onto ${identifier} with the Atlassian comment tool yourself`)
850
+ }
851
+ if (!cred.ok) return done(`no credentials — ${cred.error.split('\n')[0]}; nothing posted`)
852
+ try {
853
+ await cred.adapter.createComment(identifier, body)
854
+ return done(`${identifier} — comment posted (${body.length} characters)`)
855
+ } catch (error) {
856
+ return done(`could not reach Jira (${String(error.message).split('\n')[0]}); nothing posted`)
857
+ }
858
+ }
859
+
688
860
  // `preserve <spec>` — post the issue's current description back onto the issue
689
861
  // as a comment BEFORE the linking push replaces it. Every cannot-tell exits 0:
690
862
  // a missing link, an unreachable Jira, an issue with no description, and an
@@ -1100,6 +1272,7 @@ const USAGE = `Usage: skitterspec-jira spec-sync <subcommand>
1100
1272
  ref [<spec>] the Refs: trailer value for this branch
1101
1273
  released [<range>] tickets a commit range contains
1102
1274
  preserve <spec> [--text <f>] keep an adopted issue's original report
1275
+ comment <spec> --file <f> post a file onto the issue as a comment
1103
1276
  credentials <status|set|unset> the email + API-token pair (user-level)
1104
1277
  init-config --site-url … --project-key … write the config
1105
1278
  doctor [--check-remote] [--json] readiness report
@@ -1178,6 +1351,8 @@ async function specSync(rest, io = {}) {
1178
1351
  return specSyncReleased(dir, config, positional[0], flags, out)
1179
1352
  case 'preserve':
1180
1353
  return specSyncPreserve(dir, config, positional[0], flags, out)
1354
+ case 'comment':
1355
+ return specSyncComment(dir, config, positional[0], flags, out)
1181
1356
  case 'credentials':
1182
1357
  return specSyncCredentials(dir, config, positional[0], flags, out)
1183
1358
  default:
@@ -1206,6 +1381,7 @@ function parseArgs(args, sub) {
1206
1381
  '--stored': { kind: 'path' },
1207
1382
  '--remote': { kind: 'path' },
1208
1383
  '--text': { kind: 'path' },
1384
+ '--file': { kind: 'path' },
1209
1385
  '--workspace-states': { kind: 'path', name: 'workspaceStates' },
1210
1386
  '--skip-state-check': { kind: 'boolean', name: 'skipStateCheck' },
1211
1387
  '--via': { kind: 'string' },
@@ -35,7 +35,11 @@ const DEFAULT_CONFIG = Object.freeze({
35
35
  // here, once. `issueType`/`subtaskType` name the types this site uses for a
36
36
  // spec and its phases; workflows and type names vary per site, which is why
37
37
  // both are config rather than constants.
38
- jira: Object.freeze({ siteUrl: '', projectKey: '', issueType: 'Task', subtaskType: 'Subtask' }),
38
+ // `issueTypeByKind` picks the mint type per SPEC KIND
39
+ // (`feature`/`bug`/`hotfix`/`chore`, from the spec folder's prefix), falling
40
+ // back to `issueType` — `{ "bug": "Bug" }` files bug specs as Jira Bugs.
41
+ // Empty means one type for everything, as before.
42
+ jira: Object.freeze({ siteUrl: '', projectKey: '', issueType: 'Task', subtaskType: 'Subtask', issueTypeByKind: Object.freeze({}), severityField: '' }),
39
43
  // A spec is a Jira ISSUE; each phase a SUBTASK of it. `tasks` selects how the
40
44
  // phase's checkboxes reach that subtask's description (as an ADF task list —
41
45
  // live checkboxes, still a read-only mirror).
@@ -99,9 +103,10 @@ const LIFECYCLE_BUCKETS = Object.freeze(Object.keys(DEFAULT_CONFIG.states))
99
103
  // A fresh, deeply-mutable copy of the defaults to merge onto.
100
104
  function defaults() {
101
105
  return {
102
- jira: { ...DEFAULT_CONFIG.jira },
106
+ jira: { ...DEFAULT_CONFIG.jira, issueTypeByKind: { ...DEFAULT_CONFIG.jira.issueTypeByKind } },
103
107
  mapping: { ...DEFAULT_CONFIG.mapping },
104
108
  states: { ...DEFAULT_CONFIG.states },
109
+ statesByType: {},
105
110
  stateAliases: {},
106
111
  snapshot: { ...DEFAULT_CONFIG.snapshot },
107
112
  fields: { ...DEFAULT_CONFIG.fields },
@@ -122,7 +127,7 @@ function defaults() {
122
127
  }
123
128
 
124
129
  const { isObject, stringList, assign } = kitConfig
125
- const { mergeStates, mergeFieldOwnership, mergePhaseMapping, mergeReleaseIgnorePaths, mergeKeyedFields } =
130
+ const { mergeStates, mergeStateOverrides, mergeFieldOwnership, mergePhaseMapping, mergeReleaseIgnorePaths, mergeKeyedFields } =
126
131
  kitConfig.makeMergeHelpers({
127
132
  configFile: CONFIG_FILE,
128
133
  ownership: OWNERSHIP,
@@ -142,6 +147,17 @@ function mergeConfig(base, parsed) {
142
147
  assign(base.jira, parsed.jira, 'projectKey', 'string?')
143
148
  assign(base.jira, parsed.jira, 'issueType', 'string')
144
149
  assign(base.jira, parsed.jira, 'subtaskType', 'string')
150
+ assign(base.jira, parsed.jira, 'severityField', 'string?')
151
+ if (isObject(parsed.jira.issueTypeByKind)) {
152
+ // Only the kinds a spec folder can actually be — an unknown key is
153
+ // dropped, matching the other providers' by-kind validation.
154
+ const byKind = {}
155
+ for (const kind of ['feature', 'bug', 'hotfix', 'chore', 'issue', 'incident']) {
156
+ const value = parsed.jira.issueTypeByKind[kind]
157
+ if (typeof value === 'string' && value.trim()) byKind[kind] = value.trim()
158
+ }
159
+ base.jira.issueTypeByKind = byKind
160
+ }
145
161
  // A trailing slash on the site would double up in every composed URL.
146
162
  if (base.jira.siteUrl) base.jira.siteUrl = base.jira.siteUrl.replace(/\/+$/, '')
147
163
  }
@@ -159,6 +175,7 @@ function mergeConfig(base, parsed) {
159
175
  }
160
176
 
161
177
  mergeStates(base, parsed)
178
+ mergeStateOverrides(base, parsed, 'statesByType')
162
179
 
163
180
  if (isObject(parsed.snapshot)) {
164
181
  assign(base.snapshot, parsed.snapshot, 'overviewFile', 'string')
@@ -193,8 +193,52 @@ function makeMergeHelpers({ configFile, ownership, lifecycleBuckets, phaseMappin
193
193
  base.stateAliases = aliases
194
194
  }
195
195
 
196
+ // Merge (and validate) a per-type/kind state override table — `statesByType`
197
+ // keyed by work item / issue type (Azure, Jira), `statesByKind` keyed by spec
198
+ // kind (GitHub, Linear). Each entry is a PARTIAL bucket map laid over
199
+ // `states` for that type/kind: a bucket set to null means "send no state for
200
+ // this bucket", and a bucket the entry lacks falls through to `states`.
201
+ // An unknown bucket is refused — a typo'd bucket would silently change
202
+ // nothing at push time. Call after mergeStates, so buckets are final.
203
+ function mergeStateOverrides(base, parsed, key) {
204
+ const value = parsed[key]
205
+ if (!isObject(value)) return
206
+ const table = {}
207
+ for (const [name, entry] of Object.entries(value)) {
208
+ if (!isObject(entry)) {
209
+ throw new Error(
210
+ `Invalid ${configFile}: ${key}.${JSON.stringify(name)} = ${JSON.stringify(entry)} ` +
211
+ '(expected an object mapping lifecycle buckets to a state name, or null to send no state)',
212
+ )
213
+ }
214
+ const row = {}
215
+ for (const [bucket, state] of Object.entries(entry)) {
216
+ if (!(bucket in base.states)) {
217
+ throw new Error(
218
+ `Invalid ${configFile}: ${key}.${JSON.stringify(name)}.${bucket} — not a lifecycle bucket ` +
219
+ `(${Object.keys(base.states).join(', ')})`,
220
+ )
221
+ }
222
+ if (state === null) {
223
+ row[bucket] = null
224
+ continue
225
+ }
226
+ if (typeof state !== 'string' || !state.trim()) {
227
+ throw new Error(
228
+ `Invalid ${configFile}: ${key}.${JSON.stringify(name)}.${bucket} = ${JSON.stringify(state)} ` +
229
+ '(expected a state name, or null to send no state)',
230
+ )
231
+ }
232
+ row[bucket] = state.trim()
233
+ }
234
+ if (Object.keys(row).length) table[name] = row
235
+ }
236
+ base[key] = table
237
+ }
238
+
196
239
  return {
197
240
  mergeStates,
241
+ mergeStateOverrides,
198
242
  mergeFieldOwnership,
199
243
  mergePhaseMapping,
200
244
  mergeReleaseIgnorePaths,
@@ -13,7 +13,7 @@
13
13
  * stored matches what was sent — it merges nothing (see `src/verify.js`).
14
14
  */
15
15
 
16
- const { ownsField, normalizeLocal, LIFECYCLE_BUCKETS, lintPhases, readSnapshot, parseFrontmatter, remoteWorkflowState, remoteStateReading, stateNamesFor, titleFromText, validateStates, stateSuggestions, phaseModeFor } = require('./src/normalize.js')
16
+ const { ownsField, normalizeLocal, LIFECYCLE_BUCKETS, lintPhases, readSnapshot, parseFrontmatter, remoteWorkflowState, remoteStateReading, stateNamesFor, titleFromText, validateStates, stateSuggestions, effectiveStates, specHeaders, linkedIncident, phaseModeFor } = require('./src/normalize.js')
17
17
  const { planChanges, snapshotOf, isEmptyPlan, hashField, stableStringify, remoteDescriptionEdited, remoteSubIssueEdited } = require('./src/compare.js')
18
18
  const { readBase, writeBase } = require('./src/base.js')
19
19
  const { push, recordPush, projectionOf } = require('./src/push.js')
@@ -46,6 +46,9 @@ module.exports = {
46
46
  titleFromText,
47
47
  validateStates,
48
48
  stateSuggestions,
49
+ effectiveStates,
50
+ specHeaders,
51
+ linkedIncident,
49
52
  hashField,
50
53
  stableStringify,
51
54
  readBase,
@@ -405,15 +405,93 @@ function readSnapshot(snapshotDir, config) {
405
405
  return { frontmatter: data, title, sections, phases, body }
406
406
  }
407
407
 
408
+ // The spec's own `> **Severity:**` and `> **Incident:**` headers, off the
409
+ // overview's blockquote block. They are PUSH-TIME EXTRAS, deliberately not
410
+ // keys on `normalizeLocal`'s field set: severity lands in a provider-specific
411
+ // home (a field, a label) and the incident link as a typed relation, so
412
+ // neither belongs in the synced-field hashes a stored base compares.
413
+ function specHeaders(snapshotDir, config) {
414
+ const overviewFile = (config && config.snapshot && config.snapshot.overviewFile) || '00-overview.md'
415
+ let raw
416
+ try {
417
+ raw = fs.readFileSync(path.join(snapshotDir, overviewFile), 'utf-8')
418
+ } catch {
419
+ return { severity: null, incident: null }
420
+ }
421
+ const read = (name) => {
422
+ const m = new RegExp(`^>\\s*\\*\\*${name}:\\*\\*\\s*(.+)$`, 'm').exec(raw)
423
+ return m ? m[1].trim() : null
424
+ }
425
+ return { severity: read('Severity'), incident: read('Incident') }
426
+ }
427
+
428
+ // Resolve a fix spec's `> **Incident:**` header to the incident spec it names:
429
+ // its folder in any lifecycle bucket, and the tracker identifier stamped on it
430
+ // (via the provider's own `fields.identifier`). `identifier: null` means the
431
+ // incident exists but is not linked yet — report and carry on, never fail the
432
+ // push over it. No header at all returns null.
433
+ function linkedIncident(snapshotDir, config) {
434
+ const { incident } = specHeaders(snapshotDir, config)
435
+ if (!incident) return null
436
+ const root = path.resolve(snapshotDir, '..', '..', '..')
437
+ const overviewFile = (config && config.snapshot && config.snapshot.overviewFile) || '00-overview.md'
438
+ for (const bucket of ['in-progress', 'backlog', 'complete', 'cancelled']) {
439
+ const file = path.join(root, 'specs', bucket, incident, overviewFile)
440
+ if (!fs.existsSync(file)) continue
441
+ const { data } = parseFrontmatter(fs.readFileSync(file, 'utf-8'))
442
+ const idField = config && config.fields && config.fields.identifier
443
+ const identifier = idField && data[idField] != null ? String(data[idField]) : null
444
+ return { name: incident, identifier, found: true }
445
+ }
446
+ // A FOLDER NOT ON DISK IS NOT PROOF THE INCIDENT DOES NOT EXIST — buckets
447
+ // are branch-local truth, so an incident on its own unlanded branch is
448
+ // invisible here. The caller reports "not linked yet" and carries on.
449
+ return { name: incident, identifier: null, found: false }
450
+ }
451
+
452
+ // The one-line cross-reference a fix spec's body carries to its incident. Part
453
+ // of the PROJECTION (not appended at send time), so the stored base, the plan
454
+ // and what the tracker holds all hash the same bytes — and on GitHub the
455
+ // `#N` identifier backlinks on the incident's own timeline.
456
+ function relatedIncidentLine(snapshotDir, config) {
457
+ const incident = linkedIncident(snapshotDir, config)
458
+ if (!incident) return ''
459
+ return `\n\nRelated incident: ${incident.identifier || incident.name}`
460
+ }
461
+
462
+ // The headings a bug-shaped spec's ticket leads with, in this order, when the
463
+ // spec has them. A Bug ticket is read for its repro before anything else, and
464
+ // the feature overview order buries it. Sections a spec does not have are
465
+ // skipped, never invented — a legacy bug spec with feature-shaped sections
466
+ // renders exactly as it always did.
467
+ const BUG_LEAD_SECTIONS = ['Symptom', 'Repro', 'Expected', 'Actual', 'Root cause', 'Failing test (red)', 'Fix']
468
+
469
+ // A spec's kind off its folder prefix — the same convention the providers'
470
+ // `specKindOf` reads, kept local because sync-core depends on no other package.
471
+ function bugShaped(snapshotDir) {
472
+ const name = path.basename(String(snapshotDir || ''))
473
+ return name.startsWith('bug-') || name.startsWith('hotfix-')
474
+ }
475
+
408
476
  // Build the pushed description: the overview prose with local-only sections
409
477
  // removed. Keeps the title line for context. `extraSkip` drops additional
410
478
  // sections (e.g. "Phases" once milestones sync as first-class Linear objects, so
411
479
  // the phase list isn't duplicated in the description — Decision 5).
412
- function buildDescription(title, sections, localOnlySections, extraSkip = [], dialect) {
480
+ // `leadSections` names headings to emit FIRST, in its order, matched
481
+ // case-insensitively; the rest follow in document order. Empty means document
482
+ // order throughout — byte-identical to before the parameter existed.
483
+ function buildDescription(title, sections, localOnlySections, extraSkip = [], dialect, leadSections = []) {
413
484
  const skip = new Set([...(localOnlySections || []), ...extraSkip])
414
485
  const parts = []
415
486
  if (title) parts.push(`# ${title}`)
416
- for (const [heading, content] of Object.entries(sections)) {
487
+ const entries = Object.entries(sections)
488
+ const lead = []
489
+ for (const want of leadSections) {
490
+ const hit = entries.find(([heading]) => heading.toLowerCase() === want.toLowerCase())
491
+ if (hit) lead.push(hit)
492
+ }
493
+ const ordered = [...lead, ...entries.filter((e) => !lead.includes(e))]
494
+ for (const [heading, content] of ordered) {
417
495
  if (skip.has(heading)) continue
418
496
  parts.push(`## ${heading}\n\n${content}`.trim())
419
497
  }
@@ -699,19 +777,24 @@ function normalizeLocal(snapshotDir, config) {
699
777
  const phasesCarriedBySubIssues =
700
778
  syncsSubIssues && phaseModeFor(workflowState, config) !== 'inline' && withheld === 0
701
779
  const extracted = {
702
- description: withInlinePhases(
703
- buildDescription(
704
- title,
705
- sections,
780
+ description:
781
+ withInlinePhases(
782
+ buildDescription(
783
+ title,
784
+ sections,
785
+ config.sync.localOnlySections,
786
+ phasesCarriedBySubIssues ? ['Phases'] : [],
787
+ dialect,
788
+ // A bug or hotfix spec's ticket leads with the bug sections — a
789
+ // different render of the same overview, so the Bug form opens on the
790
+ // repro rather than the feature-shaped prose.
791
+ bugShaped(snapshotDir) ? BUG_LEAD_SECTIONS : [],
792
+ ),
793
+ inlined,
794
+ tasksMode,
706
795
  config.sync.localOnlySections,
707
- phasesCarriedBySubIssues ? ['Phases'] : [],
708
796
  dialect,
709
- ),
710
- inlined,
711
- tasksMode,
712
- config.sync.localOnlySections,
713
- dialect,
714
- ),
797
+ ) + relatedIncidentLine(snapshotDir, config),
715
798
  // Sub-issue projection: one per phase. `ref` is the phase-file basename — the
716
799
  // local handle the push skill stamps a newly-created sub-issue id back into.
717
800
  // `state` is the phase's status bucket (from its heading emoji), mapped to a
@@ -758,7 +841,14 @@ function phasesWithheld(snapshotDir, config) {
758
841
  function stateNamesFor(bucket, config) {
759
842
  const primary = config && config.states && config.states[bucket]
760
843
  const aliases = (config && config.stateAliases && config.stateAliases[bucket]) || []
761
- return [primary, ...(Array.isArray(aliases) ? aliases : [])].filter((n) => typeof n === 'string' && n)
844
+ // Override values read as the bucket they override — so a `/spec-status`
845
+ // against a type completed to "Closed" still reads as `complete`.
846
+ const overrides = stateOverrideTables(config).flatMap((table) =>
847
+ Object.values(table).map((entry) => entry && entry[bucket]),
848
+ )
849
+ return [...new Set([primary, ...(Array.isArray(aliases) ? aliases : []), ...overrides])].filter(
850
+ (n) => typeof n === 'string' && n,
851
+ )
762
852
  }
763
853
 
764
854
  // Map a remote workflow-state name back to the local lifecycle bucket (the
@@ -894,11 +984,39 @@ function titleFromText(text, max = 100) {
894
984
  return stripTitleMarkup(title)
895
985
  }
896
986
 
897
- // Every state NAME the config points at: the lifecycle bucket map.
987
+ // Per-type/kind state OVERRIDES: `table` maps a work item type (Azure, Jira)
988
+ // or a spec kind (GitHub, Linear) to a partial bucket map laid over
989
+ // `config.states`. A bucket mapped to null means "send no state for this
990
+ // bucket"; a bucket the entry lacks falls through to the base map. With no
991
+ // table, or no entry for `key`, this is exactly `config.states`.
992
+ function effectiveStates(config, table, key) {
993
+ const out = { ...((config && config.states) || {}) }
994
+ const over = (table && key && table[key]) || null
995
+ if (over) for (const [bucket, value] of Object.entries(over)) out[bucket] = value
996
+ return out
997
+ }
998
+
999
+ // The per-type/kind override tables a provider config may carry. Readers that
1000
+ // scan "every configured state name" scan these too, so an override value is
1001
+ // validated and recognised exactly like a base one.
1002
+ function stateOverrideTables(config) {
1003
+ return [config && config.statesByType, config && config.statesByKind].filter(Boolean)
1004
+ }
1005
+
1006
+ // Every state NAME the config points at: the lifecycle bucket map, plus any
1007
+ // per-type/kind override values (null entries carry no name).
898
1008
  function configuredStateNames(config) {
899
1009
  // The WRITTEN names only. An alias is never written, so one the workspace
900
1010
  // lacks cannot strand a push; `stateSuggestions` still names it in reports.
901
- return Object.values((config && config.states) || {}).filter((v) => typeof v === 'string')
1011
+ const names = Object.values((config && config.states) || {}).filter((v) => typeof v === 'string')
1012
+ for (const table of stateOverrideTables(config)) {
1013
+ for (const entry of Object.values(table)) {
1014
+ for (const value of Object.values(entry || {})) {
1015
+ if (typeof value === 'string') names.push(value)
1016
+ }
1017
+ }
1018
+ }
1019
+ return [...new Set(names)]
902
1020
  }
903
1021
 
904
1022
  // Which configured state NAMES are absent from the live workspace. The skill
@@ -949,6 +1067,7 @@ module.exports = {
949
1067
  ownsField,
950
1068
  stateSuggestions,
951
1069
  configuredStateNames,
1070
+ effectiveStates,
952
1071
  normalizeLocal,
953
1072
  assigneeFor,
954
1073
  phaseProjection,
@@ -968,4 +1087,6 @@ module.exports = {
968
1087
  remoteWorkflowState,
969
1088
  remoteStateReading,
970
1089
  stateNamesFor,
1090
+ specHeaders,
1091
+ linkedIncident,
971
1092
  }