@skitterbyte/skitterspec-azure-boards 2.4.0 → 2.5.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skitterbyte/skitterspec-azure-boards",
3
- "version": "2.4.0",
3
+ "version": "2.5.0",
4
4
  "description": "Spec-driven development for Claude Code, with one-way Azure Boards sync — a superset of @skitterbyte/skitterspec: the base filesystem workflow plus /spec-status · /spec-push · /spec-claim and the spec-sync CLI, mirroring specs to Azure DevOps work items with parent/child hierarchy, assignment and a release work item per tag. The repo is canonical; Boards is a generated mirror. Install this OR the base OR one other superset — exactly one.",
5
5
  "keywords": [
6
6
  "claude",
@@ -44,6 +44,9 @@ const {
44
44
  listPhaseFiles,
45
45
  normalizeLocal,
46
46
  descriptionMode,
47
+ projectionOf,
48
+ ownershipOf,
49
+ writeBase,
47
50
  } = require('../sync-core')
48
51
  const kit = require('../provider-kit')
49
52
  const { BUCKETS, findSpecFolder, currentBranch } = require('../../env/resolve.js')
@@ -53,7 +56,16 @@ const { resolveListAssignee } = require('../provider-kit/src/list-assignee.js')
53
56
  const { expandStateArgs, specColumn, specCell } = require('../provider-kit/src/list-rows.js')
54
57
  const { IDENTIFIER_RE } = require('../provider-kit/src/released.js')
55
58
 
56
- const { loadAzureConfig, mergeConfig, defaults, CONFIG_FILE, LIFECYCLE_BUCKETS } = require('./config.js')
59
+ const {
60
+ loadAzureConfig,
61
+ mergeConfig,
62
+ defaults,
63
+ CONFIG_FILE,
64
+ LIFECYCLE_BUCKETS,
65
+ specKindOf,
66
+ mintTypeFor,
67
+ stateNameFor,
68
+ } = require('./config.js')
57
69
  const {
58
70
  resolveCredential,
59
71
  writeCredential,
@@ -185,24 +197,23 @@ function stateCheckFailure(config, flags) {
185
197
  // Apply ops: the kit orchestration with Azure's tracker calls. State is moved
186
198
  // by a direct `System.State` write after the create/update, and `transitionTo`
187
199
  // is idempotent when the item already sits on the target.
188
- // A spec's KIND, read off its folder prefix — the same convention the
189
- // lifecycle skills stamp into `> **Type:**`, but greppable with no file read.
190
- function specKindOf(snapshotDir) {
191
- const name = path.basename(String(snapshotDir || ''))
192
- if (name.startsWith('bug-')) return 'bug'
193
- if (name.startsWith('hotfix-')) return 'hotfix'
194
- if (name.startsWith('chore-')) return 'chore'
195
- if (name.startsWith('issue-')) return 'issue'
196
- if (name.startsWith('incident-')) return 'incident'
197
- return 'feature'
198
- }
199
-
200
+ //
201
+ // A RESEND IS NOT A MOVE. A plan marks a state `stateResend` when nothing says
202
+ // the spec moved — a state-map change, or a snapshot that was lost — and such a
203
+ // send never drags an item backwards: one sitting in a state this config does
204
+ // not map for its type, or in a later bucket than the target, is left where it
205
+ // is and named. A host's release CI moving finished items on (Resolved → On
206
+ // Prod) is the case this protects. A real bucket move is the repo's transition
207
+ // and is sent as before, backwards or not.
208
+
209
+ // How far through the lifecycle a bucket is. The two finished buckets rank
210
+ // alike: neither is behind the other.
211
+ const BUCKET_RANK = { backlog: 0, 'in-progress': 1, complete: 2, cancelled: 2 }
200
212
  function applyOps({ adapter, config, out, kind = 'feature', snapshotDir = null }) {
201
213
  // The mint type for THIS spec's kind (its folder prefix), falling back to
202
214
  // the one configured type. The twin search uses the same type, so a bug
203
215
  // never refuses over a feature that happens to share its title.
204
- const mintType =
205
- (config.azure.workItemTypeByKind && config.azure.workItemTypeByKind[kind]) || config.azure.workItemType
216
+ const mintType = mintTypeFor(config, kind)
206
217
  // Push-time extras off the spec's own headers: `Severity:` lands in the
207
218
  // built-in field, `Incident:` as a Related link. Neither is a synced field,
208
219
  // so neither touches the stored-base hashes.
@@ -221,17 +232,59 @@ function applyOps({ adapter, config, out, kind = 'feature', snapshotDir = null }
221
232
  // Per-type resolution: statesByType[type] overlays states, and null means
222
233
  // "send no state for this bucket" — a deliberate skip, not a gap.
223
234
  const stateFor = (bucket, type) => {
224
- const name = effectiveStates(config, config.statesByType, type)[bucket]
235
+ const name = stateNameFor(config, bucket, type)
225
236
  if (name === null) return null
226
237
  if (!name) {
227
238
  throw new Error(`no state configured for the "${bucket}" bucket — fix ${CONFIG_FILE} -> states`)
228
239
  }
229
240
  return name
230
241
  }
231
- const settle = async (idOrIdentifier, bucket, type) => {
242
+ // The bucket a live state means for one type: its own resolution first, then
243
+ // the shared map and its aliases — an item can still sit on the name an
244
+ // earlier map wrote. Null is a state this config does not map at all.
245
+ const bucketOfState = (name, type) => {
246
+ const want = String(name).toLowerCase().trim()
247
+ const same = (n) => typeof n === 'string' && n.toLowerCase().trim() === want
248
+ for (const bucket of LIFECYCLE_BUCKETS) if (same(stateNameFor(config, bucket, type))) return bucket
249
+ for (const bucket of LIFECYCLE_BUCKETS) if (same(config.states[bucket])) return bucket
250
+ for (const bucket of LIFECYCLE_BUCKETS) if (((config.stateAliases || {})[bucket] || []).some(same)) return bucket
251
+ return null
252
+ }
253
+ // Where a state send would take this item, read live: the name it would
254
+ // write, where it sits now, and — for a resend — why it should be left
255
+ // alone (`keep`), or null when it may move.
256
+ const stateDecision = async (idOrIdentifier, bucket, type) => {
257
+ const name = stateFor(bucket, type)
258
+ if (name === null) return { name: null, at: null, keep: null, already: false }
259
+ let item
260
+ try {
261
+ item = await adapter.readIssue(apiId(idOrIdentifier))
262
+ } catch (error) {
263
+ const why = String((error && error.message) || error).split('\n')[0]
264
+ return { name, at: null, keep: `could not read its state (${why})`, already: false }
265
+ }
266
+ const at = item && item.state && item.state.name
267
+ // Cannot tell where it is, so the harmless reading is to leave it.
268
+ if (!at) return { name, at: null, keep: 'could not read its state', already: false }
269
+ if (String(at).toLowerCase().trim() === String(name).toLowerCase().trim()) return { name, at, keep: null, already: true }
270
+ const current = bucketOfState(at, type)
271
+ if (current === null) return { name, at, keep: `at "${at}", a state this config does not map for ${type}`, already: false }
272
+ if (BUCKET_RANK[current] > BUCKET_RANK[bucket]) return { name, at, keep: `at "${at}", later than ${bucket}`, already: false }
273
+ return { name, at, keep: null, already: false }
274
+ }
275
+ const keptLine = (idOrIdentifier, reason) =>
276
+ ` state kept: ${asIdentifier(apiId(idOrIdentifier))} ${reason} — a resend leaves it\n`
277
+ const settle = async (idOrIdentifier, bucket, type, resend = null) => {
232
278
  if (!bucket) return
233
279
  const name = stateFor(bucket, type)
234
280
  if (name === null) return
281
+ if (resend) {
282
+ const decision = await stateDecision(idOrIdentifier, bucket, type)
283
+ if (decision.keep) {
284
+ if (out) out.write(keptLine(idOrIdentifier, decision.keep))
285
+ return
286
+ }
287
+ }
235
288
  await adapter.transitionTo(apiId(idOrIdentifier), name)
236
289
  }
237
290
  // Azure refuses the WHOLE patch over one bad `System.AssignedTo` value
@@ -268,6 +321,9 @@ function applyOps({ adapter, config, out, kind = 'feature', snapshotDir = null }
268
321
  }
269
322
  }
270
323
  return {
324
+ stateDecision,
325
+ keptLine,
326
+ mintType,
271
327
  prevalidateStates: (buckets) => {
272
328
  for (const bucket of buckets) {
273
329
  stateFor(bucket, mintType)
@@ -310,7 +366,7 @@ function applyOps({ adapter, config, out, kind = 'feature', snapshotDir = null }
310
366
  skippingRefusedSeverity(input, (i) => adapter.updateIssue(apiId(existing.identifier), i)),
311
367
  )
312
368
  }
313
- await settle(existing.identifier, issue.state, mintType)
369
+ await settle(existing.identifier, issue.state, mintType, issue.stateResend)
314
370
  await relateToIncident(existing.identifier)
315
371
  },
316
372
  mintSubIssue: async (parentId, sub) => {
@@ -328,7 +384,7 @@ function applyOps({ adapter, config, out, kind = 'feature', snapshotDir = null }
328
384
  if (sub.name != null) updates.title = sub.name
329
385
  if (sub.goal != null) updates.description = sub.goal
330
386
  if (Object.keys(updates).length) await adapter.updateIssue(apiId(sub.id), updates)
331
- await settle(sub.id, sub.state, config.azure.childType)
387
+ await settle(sub.id, sub.state, config.azure.childType, sub.stateResend)
332
388
  },
333
389
  }
334
390
  }
@@ -1604,11 +1660,120 @@ async function specSyncDoctor(dir, flags, out) {
1604
1660
  }
1605
1661
 
1606
1662
  // ---------------------------------------------------------------------------
1663
+ // `restate <spec> | --all <bucket> [--parents] [--apply]` — bring the states of
1664
+ // already-pushed items up to today's config, read live.
1665
+ //
1666
+ // `plan` sees a state-map change only for items whose snapshot recorded the
1667
+ // name they were sent. Everything pushed before that record existed has
1668
+ // nothing to diff against, so this reads each item's live state instead and
1669
+ // settles it through the same resend guard an apply uses: an item in a state
1670
+ // this config does not map for its type, or in a later bucket, is left and
1671
+ // named. Children only by default — a host's release CI often owns the
1672
+ // parent's states past complete — and `--parents` opts the spec item in.
1673
+ // Dry-run unless `--apply`; on `--apply` the names are recorded into each
1674
+ // spec's existing snapshot, so the next state-map change shows up in `plan`.
1675
+ async function specSyncRestate(dir, config, specArg, flags, out) {
1676
+ const cred = apiAdapterFor(config, flags)
1677
+ if (kit.resolveTransport(flags, config, cred.ok) === 'mcp') {
1678
+ out.write(`${PROGRAM} restate: transport = mcp — this reads every item's live state, so it needs the API. Set credentials and re-run.\n`)
1679
+ return 0
1680
+ }
1681
+ if (!cred.ok) {
1682
+ out.write(`${PROGRAM} restate: ${String(cred.error).split('\n')[0]} — nothing read, nothing written\n`)
1683
+ return 0
1684
+ }
1685
+ let dirs
1686
+ if (flags.all !== undefined) {
1687
+ const bucket = String(flags.all)
1688
+ if (!BUCKETS.includes(bucket)) {
1689
+ out.write(`${PROGRAM} restate --all: not a lifecycle bucket: ${bucket}\n`)
1690
+ return 1
1691
+ }
1692
+ dirs = listSpecs(dir, config)
1693
+ .filter((sp) => sp.bucket === bucket)
1694
+ .map((sp) => resolveSnapshotDir(sp.spec, dir))
1695
+ } else {
1696
+ const snapshotDir = resolveOrExit(specArg, dir, out)
1697
+ if (!snapshotDir) return 1
1698
+ dirs = [snapshotDir]
1699
+ }
1700
+
1701
+ const apply = !!flags.apply
1702
+ const overviewFile = (config.snapshot && config.snapshot.overviewFile) || '00-overview.md'
1703
+ const pulled = ownershipOf(config, 'workflowState') === 'pull'
1704
+ const totals = { moved: 0, already: 0, kept: 0 }
1705
+ for (const snapshotDir of dirs) {
1706
+ const spec = path.basename(snapshotDir)
1707
+ const identifier = specHelpers.linkedIdentifier(path.join(snapshotDir, overviewFile), config)
1708
+ if (!identifier) {
1709
+ out.write(`${PROGRAM} restate: ${spec} — not linked, skipped\n`)
1710
+ continue
1711
+ }
1712
+ out.write(`${PROGRAM} restate: ${spec} (${identifier})\n`)
1713
+ const ops = applyOps({ adapter: cred.adapter, config, out: null, kind: specKindOf(snapshotDir), snapshotDir })
1714
+ const projection = projectionOf(snapshotDir, config)
1715
+ const items = []
1716
+ if (flags.parents) {
1717
+ if (pulled) out.write(` ${identifier} left — its state is the tracker's (sync.fieldOwnership.workflowState: pull)\n`)
1718
+ else items.push({ role: 'issue', id: identifier, bucket: projection.status, type: ops.mintType })
1719
+ }
1720
+ for (const sub of projection.subIssues || []) {
1721
+ if (sub && sub.id != null) items.push({ role: 'subIssue', id: sub.id, bucket: sub.state, type: config.azure.childType })
1722
+ }
1723
+ const settled = { subIssues: {} }
1724
+ for (const item of items) {
1725
+ if (!item.bucket) continue
1726
+ const label = asIdentifier(apiId(item.id))
1727
+ const d = await ops.stateDecision(item.id, item.bucket, item.type)
1728
+ if (d.name === null) {
1729
+ out.write(` ${label} — ${item.bucket} sends no state for ${item.type}\n`)
1730
+ continue
1731
+ }
1732
+ if (d.keep) {
1733
+ totals.kept++
1734
+ out.write(ops.keptLine(item.id, d.keep))
1735
+ } else if (d.already) {
1736
+ totals.already++
1737
+ out.write(` ${label} already "${d.name}"\n`)
1738
+ } else {
1739
+ totals.moved++
1740
+ if (apply) await cred.adapter.transitionTo(apiId(item.id), d.name)
1741
+ out.write(` ${label} "${d.at}" → "${d.name}"${apply ? '' : ' (dry run)'}\n`)
1742
+ }
1743
+ if (item.role === 'issue') settled.issue = d.name
1744
+ else settled.subIssues[String(item.id)] = d.name
1745
+ }
1746
+ if (apply) recordStateNames(dir, config, snapshotDir, settled, out)
1747
+ }
1748
+ const verb = apply ? 'moved' : 'would move'
1749
+ out.write(`${PROGRAM} restate: ${totals.moved} ${verb}, ${totals.already} already there, ${totals.kept} left alone\n`)
1750
+ if (!apply && totals.moved) out.write(' dry run — nothing written. Re-run with --apply to move them.\n')
1751
+ return 0
1752
+ }
1753
+
1754
+ // Merge the names `restate` settled into the spec's EXISTING snapshot. With no
1755
+ // snapshot nothing is written: a snapshot holding only names would read to
1756
+ // `plan` as every phase unrecorded, and resend all their bodies.
1757
+ function recordStateNames(dir, config, snapshotDir, settled, out) {
1758
+ const identifier = specIdentifier(snapshotDir, config)
1759
+ const base = readBase(dir, identifier, config)
1760
+ if (!base) {
1761
+ out.write(' no snapshot to record names in — the next push records them\n')
1762
+ return
1763
+ }
1764
+ const before = base.stateNames || {}
1765
+ const names = { ...before, subIssues: { ...(before.subIssues || {}), ...settled.subIssues } }
1766
+ if (settled.issue !== undefined) names.issue = settled.issue
1767
+ writeBase(dir, identifier, config, { ...base, stateNames: names })
1768
+ }
1769
+
1607
1770
  const USAGE = `Usage: skitterspec-azure-boards spec-sync <subcommand>
1608
1771
 
1609
1772
  normalize <spec> print the local projection as JSON
1610
1773
  plan <spec> --workspace-states <f> what a push would change (dry, JSON)
1611
1774
  apply <spec> --plan <f> | --all <b> apply a plan over the API
1775
+ restate <spec> | --all <b> resend child states to today's map (dry)
1776
+ [--parents] [--apply] include the spec item; write the moves
1612
1777
  stamp <spec> --issue AB#n [--sub r=n] write returned ids into the spec
1613
1778
  record <spec> write the last-pushed snapshot
1614
1779
  status <spec> [--remote <f>] read-only drift report
@@ -1683,6 +1848,8 @@ async function specSync(rest, io = {}) {
1683
1848
  return specSyncPlan(dir, config, positional[0], flags, out, err)
1684
1849
  case 'apply':
1685
1850
  return specSyncApply(dir, config, positional[0], flags, out, err)
1851
+ case 'restate':
1852
+ return specSyncRestate(dir, config, positional[0], flags, out)
1686
1853
  case 'stamp':
1687
1854
  return specSyncStamp(dir, config, positional[0], flags, out)
1688
1855
  case 'record':
@@ -1768,6 +1935,7 @@ function parseArgs(args, sub) {
1768
1935
  '--link': { kind: 'list', name: 'links' },
1769
1936
  '--stage': { kind: 'string' },
1770
1937
  '--apply': { kind: 'boolean' },
1938
+ '--parents': { kind: 'boolean' },
1771
1939
  '--to': { kind: 'string' },
1772
1940
  '--name': { kind: 'string' },
1773
1941
  '--release': { kind: 'boolean' },
@@ -14,9 +14,10 @@
14
14
  */
15
15
 
16
16
  const { readFileSync } = require('node:fs')
17
- const { join } = require('node:path')
17
+ const { join, basename } = require('node:path')
18
18
 
19
19
  const kitConfig = require('../provider-kit/src/config.js')
20
+ const { effectiveStates } = require('../sync-core')
20
21
  const { dialect, htmlToText, looksLikeHtml } = require('./dialect.js')
21
22
 
22
23
  const CONFIG_FILE = 'specs/.core/azure-boards.config.json'
@@ -305,6 +306,30 @@ function mergeConfig(base, parsed) {
305
306
  return base
306
307
  }
307
308
 
309
+ // A spec's KIND, read off its folder prefix — the same convention the
310
+ // lifecycle skills stamp into `> **Type:**`, but greppable with no file read.
311
+ function specKindOf(snapshotDir) {
312
+ const name = basename(String(snapshotDir || ''))
313
+ if (name.startsWith('bug-')) return 'bug'
314
+ if (name.startsWith('hotfix-')) return 'hotfix'
315
+ if (name.startsWith('chore-')) return 'chore'
316
+ if (name.startsWith('issue-')) return 'issue'
317
+ if (name.startsWith('incident-')) return 'incident'
318
+ return 'feature'
319
+ }
320
+
321
+ // The work item type a spec of this kind mints, falling back to the one
322
+ // configured type.
323
+ function mintTypeFor(config, kind) {
324
+ return (config.azure.workItemTypeByKind && config.azure.workItemTypeByKind[kind]) || config.azure.workItemType
325
+ }
326
+
327
+ // The state a bucket writes for one work item type: statesByType[type] over
328
+ // states. `null` is a deliberate "send no state"; `undefined` is no mapping.
329
+ function stateNameFor(config, bucket, type) {
330
+ return effectiveStates(config, config.statesByType, type)[bucket]
331
+ }
332
+
308
333
  // Attach the parts of the provider contract that are code, not JSON: the
309
334
  // markdown dialect, and the `provider` block. Azure identifiers all share the
310
335
  // constant `AB` prefix (`AB#123`), so unlike Jira's project key there is
@@ -323,6 +348,14 @@ function withRuntime(config) {
323
348
  // as markdown or HTML depending on the item's era. Each hook falls back to
324
349
  // the flat Linear-like shape, so a pre-reduced payload keeps working.
325
350
  config.remote = {
351
+ // The state name a push writes for this bucket, recorded in the snapshot
352
+ // so a state-map change is visible to `plan` (sync-core `stateNames`).
353
+ // Resolved exactly as the apply resolves it: the spec item by its kind's
354
+ // mint type, a phase by `childType`.
355
+ writtenStateName(bucket, role, snapshotDir) {
356
+ const type = role === 'subIssue' ? config.azure.childType : mintTypeFor(config, specKindOf(snapshotDir))
357
+ return stateNameFor(config, bucket, type)
358
+ },
326
359
  stateName(item) {
327
360
  const st = item && item.fields && item.fields['System.State']
328
361
  if (st != null) return typeof st === 'object' ? (st.name != null ? st.name : null) : st
@@ -392,6 +425,9 @@ function loadAzureConfig(dir = process.cwd()) {
392
425
  const releaseIgnorePaths = (config) => (config.release && config.release.ignorePaths) || []
393
426
 
394
427
  module.exports = {
428
+ specKindOf,
429
+ mintTypeFor,
430
+ stateNameFor,
395
431
  loadAzureConfig,
396
432
  mergeConfig,
397
433
  defaults,
@@ -83,6 +83,9 @@ async function applyInner({ dir, config, snapshotDir, plan, adapter, ops, progre
83
83
  const identifier = helpers.linkedIdentifier(path.join(snapshotDir, overviewFile), config)
84
84
  const lines = []
85
85
  const result = { issue: null, subIssues: {} }
86
+ // Which items this apply carried a state for — the snapshot records today's
87
+ // state name for these and only these (`recordPush`).
88
+ const sent = { issue: !!(plan.issue && plan.issue.state != null), subIssues: new Set() }
86
89
  // Handed out immediately, so a throw from anywhere below still reports what
87
90
  // had been stamped by the time it happened.
88
91
  if (progress) progress.result = result
@@ -167,6 +170,7 @@ async function applyInner({ dir, config, snapshotDir, plan, adapter, ops, progre
167
170
  const file = resolvePhaseFileIn(snapshotDir, sub.ref)
168
171
  if (!file) throw new Error(`no phase file for ref ${sub.ref}`)
169
172
  stampSubIssueId(snapshotDir, file, created.identifier, config)
173
+ if (sub.state != null) sent.subIssues.add(String(created.identifier))
170
174
  result.subIssues[sub.ref] = created.identifier
171
175
  lines.push(` sub-issue created: ${sub.ref} → ${created.identifier}`)
172
176
  }
@@ -193,6 +197,7 @@ async function applyInner({ dir, config, snapshotDir, plan, adapter, ops, progre
193
197
  sub = spliced(sub, 'goal', before, config, sub.id, lines)
194
198
  }
195
199
  await ops.updateSubIssue(sub)
200
+ if (sub.state != null) sent.subIssues.add(String(sub.id))
196
201
  result.subIssues[sub.ref || refById.get(String(sub.id)) || sub.id] = sub.id
197
202
  lines.push(` sub-issue updated: ${sub.id}`)
198
203
  }
@@ -212,7 +217,7 @@ async function applyInner({ dir, config, snapshotDir, plan, adapter, ops, progre
212
217
  const lost = verify.some((l) => l.includes('!!') || l.includes('??'))
213
218
 
214
219
  // 7. Record the snapshot from the now-stamped files, so the next push is empty.
215
- const file = recordPush({ dir, snapshotDir, identifier: helpers.specIdentifier(snapshotDir, config), config })
220
+ const file = recordPush({ dir, snapshotDir, identifier: helpers.specIdentifier(snapshotDir, config), config, sent })
216
221
  lines.push(` snapshot: ${path.relative(dir, file)}`)
217
222
  return { result, lines, lost }
218
223
  }
@@ -198,6 +198,49 @@ function snapshotOf(projection, config) {
198
198
  }
199
199
  }
200
200
 
201
+ /**
202
+ * The `stateNames` record for a snapshot: the tracker state name each item was
203
+ * last SENT, `{ issue, subIssues: { <id>: name } }`, or null when there is
204
+ * nothing to record (no provider hook, nothing ever sent).
205
+ *
206
+ * An item this push sent a state for (`sent`) records today's resolution. Any
207
+ * other item keeps the name the previous snapshot had for it, or gets none —
208
+ * the absence `planChanges` reads as cannot-tell. Writing today's name for an
209
+ * item that was not sent would record a claim about the tracker nobody made.
210
+ *
211
+ * @param {object} projection the projection, carrying `stateName`s
212
+ * @param {object|null} previous the snapshot being replaced
213
+ * @param {{ issue?: boolean, subIssues?: Set<string> }|null} sent
214
+ */
215
+ function stateNamesRecord(projection, previous, sent) {
216
+ const p = projection || {}
217
+ const before = (previous && previous.stateNames) || {}
218
+ const beforeSubs = before.subIssues || {}
219
+ const sentSubs = (sent && sent.subIssues) || new Set()
220
+ const has = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key)
221
+ const out = { subIssues: {} }
222
+ if (sent && sent.issue && p.stateName !== undefined) out.issue = p.stateName
223
+ else if (has(before, 'issue')) out.issue = before.issue
224
+ for (const s of p.subIssues || []) {
225
+ if (!s || s.id == null) continue
226
+ const id = String(s.id)
227
+ if (sentSubs.has(id) && s.stateName !== undefined) out.subIssues[id] = s.stateName
228
+ else if (has(beforeSubs, id)) out.subIssues[id] = beforeSubs[id]
229
+ }
230
+ if (!has(out, 'issue') && !Object.keys(out.subIssues).length) return null
231
+ return out
232
+ }
233
+
234
+ // Has the state an unchanged item maps to moved under it — a state-map edit in
235
+ // the config rather than a move of the spec? Only a RECORDED name can say: an
236
+ // item with none is cannot-tell and plans nothing, so an upgrade or a config
237
+ // change never turns into a workspace-wide resend. A bucket that now sends no
238
+ // state (`null`) has nothing to resend.
239
+ function remapped(recorded, current) {
240
+ if (recorded === undefined || current === undefined || current === null) return false
241
+ return recorded !== current
242
+ }
243
+
201
244
  /**
202
245
  * Diff the local projection against the last-pushed snapshot.
203
246
  * @returns {{ issue?: object, subIssues: {create,update} }}
@@ -213,6 +256,9 @@ function planChanges(projection, snapshot, { linked = false } = {}) {
213
256
  const p = projection || {}
214
257
  const snap = snapshot || {}
215
258
  const snapS = snap.subIssues || {}
259
+ const names = snap.stateNames || {}
260
+ const recordedSub = (id) =>
261
+ names.subIssues && Object.prototype.hasOwnProperty.call(names.subIssues, id) ? names.subIssues[id] : undefined
216
262
 
217
263
  // Ids the last push minted that no phase claims any more. A phase file's stamp
218
264
  // is the only link back to its sub-issue, and it lives in frontmatter — so a
@@ -239,7 +285,15 @@ function planChanges(projection, snapshot, { linked = false } = {}) {
239
285
  subIssues.create.push({ ref: s.ref, name: s.name, goal: s.goal, state: s.state })
240
286
  }
241
287
  } else if (snapS[String(s.id)] !== subIssueHash(s)) {
242
- subIssues.update.push({ ref: s.ref, id: s.id, name: s.name, goal: s.goal, state: s.state })
288
+ const update = { ref: s.ref, id: s.id, name: s.name, goal: s.goal, state: s.state }
289
+ // No hash on record for an id the spec carries: the snapshot was lost or
290
+ // predates it, so this is a resend, not a move the spec made.
291
+ if (snapS[String(s.id)] === undefined) update.stateResend = 'unknown'
292
+ subIssues.update.push(update)
293
+ } else if (remapped(recordedSub(String(s.id)), s.stateName)) {
294
+ // STATE ONLY: the phase itself is unchanged, so its title and body stay
295
+ // as they are on the tracker.
296
+ subIssues.update.push({ ref: s.ref, id: s.id, state: s.state, stateResend: 'remap' })
243
297
  }
244
298
  }
245
299
 
@@ -276,6 +330,9 @@ function issueChanges(projection, snapshot, { linked = false } = {}) {
276
330
  // `linked` is what tells the two apart: an adopted issue has no snapshot
277
331
  // either, and its board status is a person's, not ours.
278
332
  if (!p.statePulled || !linked) out.state = p.status ?? null
333
+ // A linked issue with no split hashes is a resend: nothing says the spec
334
+ // moved, so the apply must not drag the issue out of a later state.
335
+ if (linked && out.state != null) out.stateResend = 'unknown'
279
336
  // ASSERT, NEVER CLEAR, on this path. There are no split hashes here, so
280
337
  // whether an assignee was ever pushed is unknown — and the harmless reading
281
338
  // of "unknown" is to send one we have and stay silent about one we don't.
@@ -302,6 +359,11 @@ function issueChanges(projection, snapshot, { linked = false } = {}) {
302
359
  const changed = {}
303
360
  if (fields.description !== want.description) changed.description = p.description ?? null
304
361
  if (fields.state !== want.state) changed.state = p.status ?? null
362
+ else if (!p.statePulled && remapped(snap.stateNames && snap.stateNames.issue, p.stateName)) {
363
+ // The tracker owns a pulled state, so a remap never re-asserts it there.
364
+ changed.state = p.status ?? null
365
+ changed.stateResend = 'remap'
366
+ }
305
367
 
306
368
  // ASSIGNEE — AN ABSENT SNAPSHOT KEY MEANS "NEVER PUSHED", NOT "WAS NULL".
307
369
  //
@@ -342,6 +404,7 @@ module.exports = {
342
404
  issueChanges,
343
405
  specIssueFieldHashes,
344
406
  snapshotOf,
407
+ stateNamesRecord,
345
408
  isEmptyPlan,
346
409
  hashField,
347
410
  stableStringify,
@@ -18,7 +18,7 @@
18
18
  const { normalizeLocal, phasesWithheld, phaseModeFor, ownershipOf, readSnapshot } = require('./normalize.js')
19
19
  const { descriptionMode } = require('./summary.js')
20
20
  const { fieldsOf } = require('./fields.js')
21
- const { planChanges, snapshotOf, isEmptyPlan } = require('./compare.js')
21
+ const { planChanges, snapshotOf, stateNamesRecord, isEmptyPlan } = require('./compare.js')
22
22
  const { readBase, writeBase } = require('./base.js')
23
23
  const { detectLegacyMirror } = require('./legacy.js')
24
24
 
@@ -55,9 +55,36 @@ function projectionOf(snapshotDir, config) {
55
55
  // a push sends it only as a transition — see `issueChanges`. Set only when
56
56
  // pulled, and read by name, so it can never reach a hash.
57
57
  if (ownershipOf(config, 'workflowState') === 'pull') projection.statePulled = true
58
+ attachStateNames(projection, snapshotDir, config)
58
59
  return projection
59
60
  }
60
61
 
62
+ // The tracker state NAME each bucket resolves to today, from the provider's
63
+ // `config.remote.writtenStateName(bucket, role, snapshotDir)` hook: a string,
64
+ // `null` for "this bucket sends no state", or `undefined` for cannot-tell — no
65
+ // hook, a hook that threw, or no bucket to resolve. Read by name, so it never
66
+ // reaches a hash: recorded beside them as `stateNames`, it is what lets a plan
67
+ // see a state-map change the bucket hashes are blind to.
68
+ function attachStateNames(projection, snapshotDir, config) {
69
+ const hook = config && config.remote && config.remote.writtenStateName
70
+ if (typeof hook !== 'function') return
71
+ const resolve = (bucket, role) => {
72
+ if (!bucket) return undefined
73
+ try {
74
+ const name = hook(bucket, role, snapshotDir)
75
+ return name === null || typeof name === 'string' ? name : undefined
76
+ } catch {
77
+ return undefined
78
+ }
79
+ }
80
+ const name = resolve(projection.status, 'issue')
81
+ if (name !== undefined) projection.stateName = name
82
+ projection.subIssues = projection.subIssues.map((s) => {
83
+ const sub = resolve(s && s.state, 'subIssue')
84
+ return sub === undefined ? s : { ...s, stateName: sub }
85
+ })
86
+ }
87
+
61
88
  // Does the spec carry its issue stamp? NOT `identifier`: callers fall back to the
62
89
  // folder name for an unlinked spec, so a truthy identifier proves nothing. The
63
90
  // stamp is the positive signal — it tells a create (no issue yet, so the spec's
@@ -101,9 +128,18 @@ function push({ dir, snapshotDir, identifier, config }) {
101
128
  * Record the last-pushed snapshot from the CURRENT files — call after the skill
102
129
  * has applied the plan and stamped new ids. Returns the snapshot path.
103
130
  */
104
- function recordPush({ dir, snapshotDir, identifier, config }) {
131
+ // `sent` says which items this push carried a state for — `{ issue, subIssues }`,
132
+ // the latter a set of ids. Only those get today's name recorded; anything else
133
+ // keeps the name it already had, or none. Recording today's name for an item
134
+ // that was NOT sent would claim the tracker holds it, and silence the very remap
135
+ // this record exists to catch. Without `sent` (a hand-applied MCP push) nothing
136
+ // new is recorded and what was there is kept.
137
+ function recordPush({ dir, snapshotDir, identifier, config, sent = null }) {
105
138
  const projection = projectionOf(snapshotDir, config)
106
- return writeBase(dir, identifier, config, snapshotOf(projection, config))
139
+ const snapshot = snapshotOf(projection, config)
140
+ const names = stateNamesRecord(projection, readBase(dir, identifier, config), sent)
141
+ if (names) snapshot.stateNames = names
142
+ return writeBase(dir, identifier, config, snapshot)
107
143
  }
108
144
 
109
145
  module.exports = { push, recordPush, projectionOf }