@skitterbyte/skitterspec-azure-boards 2.3.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.
Files changed (58) hide show
  1. package/assets/claude-md-section.md +20 -1
  2. package/assets/core/azure-boards.config.md +4 -2
  3. package/assets/core/env.config.json.example +1 -0
  4. package/assets/core/env.config.md +90 -6
  5. package/assets/hooks/main-guard.cjs +18 -2
  6. package/assets/hooks/review-gate.cjs +19 -2
  7. package/assets/rules/commit-trailers.md +24 -1
  8. package/assets/rules/spec-planning.md +81 -18
  9. package/assets/rules/spec-reports.md +1 -1
  10. package/assets/skills/spec/SKILL.md +55 -2
  11. package/assets/skills/spec-azure-setup/SKILL.md +23 -1
  12. package/assets/skills/spec-bug/SKILL.md +36 -3
  13. package/assets/skills/spec-cancel/SKILL.md +35 -0
  14. package/assets/skills/spec-claim/SKILL.md +41 -2
  15. package/assets/skills/spec-complete/SKILL.md +113 -0
  16. package/assets/skills/spec-hotfix/SKILL.md +51 -4
  17. package/assets/skills/spec-incident/SKILL.md +22 -0
  18. package/assets/skills/spec-next/SKILL.md +12 -5
  19. package/assets/skills/spec-push/SKILL.md +22 -0
  20. package/assets/skills/spec-review/SKILL.md +32 -0
  21. package/assets/skills/spec-start/SKILL.md +50 -3
  22. package/assets/skills/spec-status/SKILL.md +18 -3
  23. package/assets/skills/spec-sync/SKILL.md +1 -0
  24. package/assets/skills/spec-to-main/SKILL.md +47 -1
  25. package/package.json +1 -1
  26. package/src/cli.js +1091 -39
  27. package/src/env/base.js +104 -0
  28. package/src/env/config.js +75 -3
  29. package/src/env/disposition.js +62 -0
  30. package/src/env/handoff.js +80 -0
  31. package/src/env/host.js +262 -0
  32. package/src/env/hotfix.js +225 -0
  33. package/src/env/hotfixland.js +103 -9
  34. package/src/env/inflight.js +95 -0
  35. package/src/env/integrate.js +130 -4
  36. package/src/env/mainguard.js +6 -0
  37. package/src/env/phases.js +28 -0
  38. package/src/env/provision.js +18 -6
  39. package/src/env/resolve.js +108 -9
  40. package/src/env/serve.js +6 -1
  41. package/src/env/specstate.js +101 -0
  42. package/src/env/teardown.js +42 -0
  43. package/src/vendor/azure-boards/cli-sync.js +234 -22
  44. package/src/vendor/azure-boards/config.js +54 -6
  45. package/src/vendor/provider-kit/index.js +4 -0
  46. package/src/vendor/provider-kit/src/apply.js +55 -5
  47. package/src/vendor/provider-kit/src/assignment.js +78 -1
  48. package/src/vendor/provider-kit/src/config.js +34 -1
  49. package/src/vendor/provider-kit/src/list-rows.js +35 -11
  50. package/src/vendor/provider-kit/src/released.js +14 -1
  51. package/src/vendor/provider-kit/src/specs.js +4 -2
  52. package/src/vendor/provider-kit/src/splice.js +64 -0
  53. package/src/vendor/provider-kit/src/status.js +137 -0
  54. package/src/vendor/sync-core/index.js +14 -1
  55. package/src/vendor/sync-core/src/compare.js +81 -6
  56. package/src/vendor/sync-core/src/normalize.js +50 -7
  57. package/src/vendor/sync-core/src/push.js +65 -5
  58. package/src/vendor/sync-core/src/summary.js +257 -0
@@ -24,6 +24,7 @@ const { createHash } = require('node:crypto')
24
24
  // two reductions that disagree would be two different answers to one question.
25
25
  // Dialect-parameterised: the provider's `config.dialect` names the transforms.
26
26
  const { stream } = require('./verify.js')
27
+ const { comparableDescription } = require('./summary.js')
27
28
 
28
29
  // Deterministic JSON: object keys sorted recursively; array order preserved.
29
30
  // undefined normalises to null.
@@ -132,7 +133,10 @@ function remoteDescriptionEdited(snapshot, remote, config) {
132
133
  if (!remote || typeof remote !== 'object') return null
133
134
  // A provider whose remote shape differs supplies `config.remote.description`.
134
135
  const hook = config && config.remote && config.remote.description
135
- const text = typeof hook === 'function' ? hook(remote) : 'description' in remote ? remote.description : undefined
136
+ const raw = typeof hook === 'function' ? hook(remote) : 'description' in remote ? remote.description : undefined
137
+ // In summary mode only the block is the repo's: text around it is the team's
138
+ // and is never drift. A block that is missing or damaged is cannot-tell.
139
+ const text = comparableDescription(raw, config)
136
140
  if (typeof text !== 'string') return null
137
141
 
138
142
  return hashField(stream(text, config)) !== recorded
@@ -194,6 +198,49 @@ function snapshotOf(projection, config) {
194
198
  }
195
199
  }
196
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
+
197
244
  /**
198
245
  * Diff the local projection against the last-pushed snapshot.
199
246
  * @returns {{ issue?: object, subIssues: {create,update} }}
@@ -205,10 +252,13 @@ function snapshotOf(projection, config) {
205
252
  * `plan.issue` (when present) is the spec issue's description + state; the push
206
253
  * skill applies its provider's project/grouping choice on top of it.
207
254
  */
208
- function planChanges(projection, snapshot) {
255
+ function planChanges(projection, snapshot, { linked = false } = {}) {
209
256
  const p = projection || {}
210
257
  const snap = snapshot || {}
211
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
212
262
 
213
263
  // Ids the last push minted that no phase claims any more. A phase file's stamp
214
264
  // is the only link back to its sub-issue, and it lives in frontmatter — so a
@@ -235,13 +285,21 @@ function planChanges(projection, snapshot) {
235
285
  subIssues.create.push({ ref: s.ref, name: s.name, goal: s.goal, state: s.state })
236
286
  }
237
287
  } else if (snapS[String(s.id)] !== subIssueHash(s)) {
238
- 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' })
239
297
  }
240
298
  }
241
299
 
242
300
  const plan = { subIssues }
243
301
  if (unstamped.length) plan.unstamped = unstamped
244
- const issue = issueChanges(p, snap)
302
+ const issue = issueChanges(p, snap, { linked })
245
303
  if (issue) plan.issue = issue
246
304
  return plan
247
305
  }
@@ -259,11 +317,22 @@ function planChanges(projection, snapshot) {
259
317
  * that is the failure worth avoiding. The push rewrites the snapshot in the new
260
318
  * shape, so a spec passes through `unknown` exactly once.
261
319
  */
262
- function issueChanges(projection, snapshot) {
320
+ function issueChanges(projection, snapshot, { linked = false } = {}) {
263
321
  const p = projection || {}
264
322
  const snap = snapshot || {}
265
323
  const both = () => {
266
- const out = { description: p.description ?? null, state: p.status ?? null }
324
+ const out = { description: p.description ?? null }
325
+ // UNDER `pull`, THE UNKNOWN PATH SENDS NO STATE. Without split hashes there
326
+ // is no positive signal that the spec moved, and the tracker owns the state
327
+ // — so the harmless reading of "cannot tell" flips: re-asserting would drag
328
+ // back a ticket someone moved on the board. Only a CREATE still sends it,
329
+ // because an issue with no state yet gets its first one from the repo.
330
+ // `linked` is what tells the two apart: an adopted issue has no snapshot
331
+ // either, and its board status is a person's, not ours.
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'
267
336
  // ASSERT, NEVER CLEAR, on this path. There are no split hashes here, so
268
337
  // whether an assignee was ever pushed is unknown — and the harmless reading
269
338
  // of "unknown" is to send one we have and stay silent about one we don't.
@@ -290,6 +359,11 @@ function issueChanges(projection, snapshot) {
290
359
  const changed = {}
291
360
  if (fields.description !== want.description) changed.description = p.description ?? null
292
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
+ }
293
367
 
294
368
  // ASSIGNEE — AN ABSENT SNAPSHOT KEY MEANS "NEVER PUSHED", NOT "WAS NULL".
295
369
  //
@@ -330,6 +404,7 @@ module.exports = {
330
404
  issueChanges,
331
405
  specIssueFieldHashes,
332
406
  snapshotOf,
407
+ stateNamesRecord,
333
408
  isEmptyPlan,
334
409
  hashField,
335
410
  stableStringify,
@@ -17,6 +17,7 @@
17
17
  const fs = require('node:fs')
18
18
  const path = require('node:path')
19
19
  const { dialectOf } = require('./dialect.js')
20
+ const { descriptionMode, wrapBlock, specBlockInner, phaseBlockInner } = require('./summary.js')
20
21
  const { fieldsOf } = require('./fields.js')
21
22
  const { fenceMask, findTaskBlocks, collapse, collapseHyphenAware } = require('./task-block.js')
22
23
 
@@ -374,17 +375,46 @@ function ownsField(config, field) {
374
375
  return !!owned && field in owned && owned[field] !== 'none'
375
376
  }
376
377
 
378
+ /**
379
+ * WHO owns `field`: `push` (the repo), `pull` (the tracker), or `none` (it is
380
+ * not in play). `both` reads as `push` — it was accepted long before `pull`
381
+ * meant anything, and every config that wrote it meant the repo's behaviour.
382
+ *
383
+ * `pull` means the TRACKER is the record. The repo reads it live for display
384
+ * and sends it only as a transition it made itself (a spec changing bucket).
385
+ *
386
+ * WHAT WOULD MAKE `pull` LIE: reading the tracker's value and writing it into a
387
+ * spec file. Nothing that pulls ever writes a repo file — the moment one does,
388
+ * the repo holds a copy again, and the copy is the manual sync this exists to
389
+ * remove. `ownsField` stays "in play at all", so a pulled field still answers
390
+ * true there and no existing caller changes meaning.
391
+ */
392
+ function ownershipOf(config, field) {
393
+ if (!ownsField(config, field)) return 'none'
394
+ return config.sync.fieldOwnership[field] === 'pull' ? 'pull' : 'push'
395
+ }
396
+
397
+ // The pulled fields the repo still has something to say about. A spec changing
398
+ // bucket is a transition the repo made, so `workflowState` stays projected (its
399
+ // hash is what tells a transition from a routine push). The assignee has no such
400
+ // moment — the board assigns people — so under `pull` the repo projects none.
401
+ const TRANSITION_FIELDS = ['workflowState']
402
+
377
403
  // Reduce an `extracted` map to exactly the configured field keys, defaulting a
378
404
  // missing field to `null` so local and remote always share an identical set.
379
405
  //
380
406
  // A declined field is OMITTED, not set null. The two are not interchangeable
381
407
  // here: `null` is a value this projection asserts — it is how a finished spec
382
408
  // 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.
409
+ // clear in Linear exactly what declining ownership promised not to touch. A
410
+ // pulled field with no transition is omitted for the same reason: the tracker
411
+ // owns it, so the repo asserts nothing about it, not even `null`.
384
412
  function toFieldSet(extracted, config) {
385
413
  const out = {}
386
414
  for (const field of Object.keys(config.sync.fieldOwnership)) {
387
- if (!ownsField(config, field)) continue
415
+ const owner = ownershipOf(config, field)
416
+ if (owner === 'none') continue
417
+ if (owner === 'pull' && !TRANSITION_FIELDS.includes(field)) continue
388
418
  out[field] = field in extracted ? extracted[field] : null
389
419
  }
390
420
  return out
@@ -735,7 +765,9 @@ function phaseProjection(phases, workflowState, config) {
735
765
  // They differ only in where an unlinked phase goes — nowhere yet, or into the
736
766
  // spec issue's own description.
737
767
  const deferring = mode === 'deferred' && UNSTARTED_BUCKETS.includes(workflowState)
738
- const projected = deferring || mode === 'inline' ? named.filter((p) => p.id != null) : named
768
+ // `none` holds every unlinked phase back for good — the ticket is one ticket.
769
+ // A phase already linked keeps projecting, for the same no-delete reason.
770
+ const projected = deferring || mode === 'inline' || mode === 'none' ? named.filter((p) => p.id != null) : named
739
771
  const unlinked = named.filter((p) => p.id == null)
740
772
  return {
741
773
  projected,
@@ -751,8 +783,11 @@ function phaseProjection(phases, workflowState, config) {
751
783
 
752
784
  function normalizeLocal(snapshotDir, config) {
753
785
  const dialect = dialectOf(config)
754
- const { frontmatter, title, sections, phases } = readSnapshot(snapshotDir, config)
786
+ const { frontmatter, title, sections, phases, body } = readSnapshot(snapshotDir, config)
755
787
  const tasksMode = (config.mapping && config.mapping.tasks) || 'checklist'
788
+ // `summary` replaces both bodies with a delimited block (src/summary.js);
789
+ // `spec`, the default, is everything below exactly as it was.
790
+ const summaryMode = descriptionMode(config) === 'summary'
756
791
  // Status is the spec's lifecycle bucket. The folder is the source of truth; an
757
792
  // explicit `spec_status` frontmatter key overrides it if present. Resolved
758
793
  // BEFORE the sub-issue projection because deferral withholds phases by this
@@ -777,8 +812,13 @@ function normalizeLocal(snapshotDir, config) {
777
812
  const phasesCarriedBySubIssues =
778
813
  syncsSubIssues && phaseModeFor(workflowState, config) !== 'inline' && withheld === 0
779
814
  const extracted = {
780
- description:
781
- withInlinePhases(
815
+ description: summaryMode
816
+ ? wrapBlock(
817
+ dialect.flattenTables(dialect.canonicalize(specBlockInner({ snapshotDir, sections, body, phases }))) +
818
+ relatedIncidentLine(snapshotDir, config),
819
+ config,
820
+ )
821
+ : withInlinePhases(
782
822
  buildDescription(
783
823
  title,
784
824
  sections,
@@ -805,7 +845,9 @@ function normalizeLocal(snapshotDir, config) {
805
845
  id: p.id,
806
846
  ref: p.phase,
807
847
  name: p.name,
808
- goal: subIssueBody(p, tasksMode, config.sync.localOnlySections, dialect),
848
+ goal: summaryMode
849
+ ? wrapBlock(dialect.flattenTables(phaseBlockInner(p)), config)
850
+ : subIssueBody(p, tasksMode, config.sync.localOnlySections, dialect),
809
851
  state: phaseStateUnder(workflowState, p.state),
810
852
  })),
811
853
  workflowState,
@@ -1065,6 +1107,7 @@ function stateSuggestions(config, workspaceStates) {
1065
1107
 
1066
1108
  module.exports = {
1067
1109
  ownsField,
1110
+ ownershipOf,
1068
1111
  stateSuggestions,
1069
1112
  configuredStateNames,
1070
1113
  effectiveStates,
@@ -15,8 +15,10 @@
15
15
  * Date.now(). `recordPush` writes the snapshot sidecar.
16
16
  */
17
17
 
18
- const { normalizeLocal, phasesWithheld, phaseModeFor } = require('./normalize.js')
19
- const { planChanges, snapshotOf, isEmptyPlan } = require('./compare.js')
18
+ const { normalizeLocal, phasesWithheld, phaseModeFor, ownershipOf, readSnapshot } = require('./normalize.js')
19
+ const { descriptionMode } = require('./summary.js')
20
+ const { fieldsOf } = require('./fields.js')
21
+ const { planChanges, snapshotOf, stateNamesRecord, isEmptyPlan } = require('./compare.js')
20
22
  const { readBase, writeBase } = require('./base.js')
21
23
  const { detectLegacyMirror } = require('./legacy.js')
22
24
 
@@ -49,13 +51,58 @@ function projectionOf(snapshotDir, config) {
49
51
  // push. `normalizeLocal` omits the key entirely when `sync.fieldOwnership`
50
52
  // does not list it.
51
53
  if ('assignee' in local) projection.assignee = local.assignee ?? null
54
+ // The tracker owns the state (`sync.fieldOwnership.workflowState: "pull"`), so
55
+ // a push sends it only as a transition — see `issueChanges`. Set only when
56
+ // pulled, and read by name, so it can never reach a hash.
57
+ if (ownershipOf(config, 'workflowState') === 'pull') projection.statePulled = true
58
+ attachStateNames(projection, snapshotDir, config)
52
59
  return projection
53
60
  }
54
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
+
88
+ // Does the spec carry its issue stamp? NOT `identifier`: callers fall back to the
89
+ // folder name for an unlinked spec, so a truthy identifier proves nothing. The
90
+ // stamp is the positive signal — it tells a create (no issue yet, so the spec's
91
+ // first state IS a transition) from a linked spec whose snapshot cannot say what
92
+ // was last sent.
93
+ function isLinked(snapshotDir, config) {
94
+ try {
95
+ const { frontmatter } = readSnapshot(snapshotDir, config)
96
+ return !!(frontmatter && frontmatter[fieldsOf(config).identifier])
97
+ } catch {
98
+ return false
99
+ }
100
+ }
101
+
55
102
  function push({ dir, snapshotDir, identifier, config }) {
56
103
  const projection = projectionOf(snapshotDir, config)
57
104
  const snapshot = readBase(dir, identifier, config)
58
- const plan = planChanges(projection, snapshot)
105
+ const plan = planChanges(projection, snapshot, { linked: isLinked(snapshotDir, config) })
59
106
  // A spec still linked under the pre-9.0 model reads as unlinked here, so the
60
107
  // plan above is all-creates and would abandon a live mirror. Carry the finding
61
108
  // ON THE PLAN, not as a warning: `--json` routes warnings to stderr, and the
@@ -70,6 +117,10 @@ function push({ dir, snapshotDir, identifier, config }) {
70
117
  // know that an absent field means `subissue`. `isEmptyPlan` and `snapshotOf`
71
118
  // both read named fields, so an extra key cannot make a spec look edited.
72
119
  plan.phaseMode = projection.phaseMode
120
+ // Always set too: under `summary` the planned bodies are BLOCKS, and an
121
+ // apply that writes one over the whole description deletes the team's text.
122
+ // The MCP path reads this to know it must splice (`spec-sync splice`).
123
+ plan.descriptionMode = descriptionMode(config)
73
124
  return { ok: true, empty: isEmptyPlan(plan), plan, projection }
74
125
  }
75
126
 
@@ -77,9 +128,18 @@ function push({ dir, snapshotDir, identifier, config }) {
77
128
  * Record the last-pushed snapshot from the CURRENT files — call after the skill
78
129
  * has applied the plan and stamped new ids. Returns the snapshot path.
79
130
  */
80
- 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 }) {
81
138
  const projection = projectionOf(snapshotDir, config)
82
- 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)
83
143
  }
84
144
 
85
145
  module.exports = { push, recordPush, projectionOf }
@@ -0,0 +1,257 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * The SUMMARY BLOCK — what a ticket carries under `mapping.description:
5
+ * "summary"`. The spec stays in git; the ticket gets a short, delimited block
6
+ * (what the work is, what done looks like, what it touches) and the repo owns
7
+ * that block and nothing else in the description. Text a team writes around it
8
+ * survives every push.
9
+ *
10
+ * Writing it is a SPLICE, not a pull: the live description is read so the
11
+ * block can be replaced in place, and nothing outside the block is parsed,
12
+ * merged, hashed or written back to the spec.
13
+ *
14
+ * Pure: no I/O, no clock, no randomness.
15
+ */
16
+
17
+ const path = require('node:path')
18
+
19
+ // The two delimiter styles. `comment` is invisible where the tracker keeps
20
+ // HTML comments verbatim (GitHub, measured 2026-11-08); `heading` is the
21
+ // fallback where it may not. Which a provider uses is its config's call
22
+ // (`summary.delimiter`), never guessed from the text.
23
+ const DELIMITERS = Object.freeze({
24
+ comment: Object.freeze({ begin: '<!-- skitterspec:begin -->', end: '<!-- skitterspec:end -->' }),
25
+ heading: Object.freeze({ begin: '## Skitterspec summary', end: '_— end of skitterspec summary —_' }),
26
+ })
27
+
28
+ // `spec` (the whole overview, as before) unless the config says `summary`.
29
+ // ABSENT MEANS `spec`, deliberately: a config written before this key existed
30
+ // must push exactly what it always pushed, so an upgrade rewrites no ticket.
31
+ function descriptionMode(config) {
32
+ const mode = config && config.mapping && config.mapping.description
33
+ return mode === 'summary' ? 'summary' : 'spec'
34
+ }
35
+
36
+ function delimitersFor(config) {
37
+ const style = config && config.summary && config.summary.delimiter
38
+ return DELIMITERS[style] || DELIMITERS.heading
39
+ }
40
+
41
+ const countOf = (text, needle) => text.split(needle).length - 1
42
+
43
+ /**
44
+ * Where the block sits in a description.
45
+ *
46
+ * THREE STATES, and the third is why this returns more than a boolean:
47
+ *
48
+ * - `present` — exactly one begin, then exactly one end after it;
49
+ * - `absent` — neither delimiter appears;
50
+ * - `damaged` — anything else: a begin with no end, an end with no begin,
51
+ * two of either. Someone has edited a delimiter line, and the edges of the
52
+ * block cannot be told apart from the team's text around it.
53
+ *
54
+ * `damaged` is cannot-tell and every caller routes it to the harmless branch:
55
+ * the description is not written, and no edit is reported. Splicing into it
56
+ * could eat a paragraph that was never the repo's; prepending a second block
57
+ * would leave two (`.claude/rules/negative-checks.md` rule 4).
58
+ */
59
+ function blockOf(text, config) {
60
+ const t = typeof text === 'string' ? text : ''
61
+ const { begin, end } = delimitersFor(config)
62
+ const begins = countOf(t, begin)
63
+ const ends = countOf(t, end)
64
+ if (begins === 0 && ends === 0) return { state: 'absent' }
65
+ if (begins !== 1 || ends !== 1) return { state: 'damaged' }
66
+ const start = t.indexOf(begin)
67
+ const close = t.indexOf(end)
68
+ if (close < start) return { state: 'damaged' }
69
+ const stop = close + end.length
70
+ return { state: 'present', start, end: stop, block: t.slice(start, stop) }
71
+ }
72
+
73
+ function wrapBlock(inner, config) {
74
+ const { begin, end } = delimitersFor(config)
75
+ return `${begin}\n${String(inner || '').trim()}\n${end}`
76
+ }
77
+
78
+ /**
79
+ * Put `block` (a whole wrapped block) into `live`, leaving every other byte of
80
+ * `live` as it was. An absent block goes first, above the team's text. Returns
81
+ * null when the existing block is damaged — the caller must not write.
82
+ */
83
+ function spliceBlock(live, block, config) {
84
+ const text = typeof live === 'string' ? live : ''
85
+ const at = blockOf(text, config)
86
+ if (at.state === 'damaged') return null
87
+ if (at.state === 'present') return text.slice(0, at.start) + block + text.slice(at.end)
88
+ return text.trim() ? `${block}\n\n${text}` : block
89
+ }
90
+
91
+ /**
92
+ * The part of a tracker description that is the repo's to compare: the whole
93
+ * text in `spec` mode, the block alone in `summary` mode. Null when summary mode
94
+ * finds no intact block — cannot-tell for drift, and the caller decides whether
95
+ * an absent block is a loss (right after a write it is).
96
+ */
97
+ function comparableDescription(text, config) {
98
+ if (typeof text !== 'string') return null
99
+ if (descriptionMode(config) !== 'summary') return text
100
+ const at = blockOf(text, config)
101
+ return at.state === 'present' ? at.block : null
102
+ }
103
+
104
+ // --- the block's parts ------------------------------------------------------
105
+
106
+ function firstParagraph(text) {
107
+ const t = String(text || '').trim()
108
+ if (!t) return ''
109
+ return t.split(/\n\s*\n/)[0].trim()
110
+ }
111
+
112
+ // A markdown table's rows as `{ header: cell }` objects. Header and separator
113
+ // rows are consumed; a line that is not a table row ends the table.
114
+ function tableRows(text) {
115
+ const lines = String(text || '')
116
+ .split('\n')
117
+ .map((l) => l.trim())
118
+ .filter((l) => l.startsWith('|'))
119
+ if (lines.length < 2) return []
120
+ const cells = (l) =>
121
+ l
122
+ .replace(/^\|/, '')
123
+ .replace(/\|$/, '')
124
+ .split('|')
125
+ .map((c) => c.trim())
126
+ const header = cells(lines[0]).map((h) => h.toLowerCase())
127
+ return lines
128
+ .slice(2)
129
+ .map(cells)
130
+ .map((row) => Object.fromEntries(header.map((h, i) => [h, row[i] || ''])))
131
+ }
132
+
133
+ // The Impact table as one line: each row's Detail, else its Surface. Detail is
134
+ // what names the thing (`POST /orders`); Surface alone is its category
135
+ // (`Endpoint`), which tells a ticket reader nothing.
136
+ function touches(sections) {
137
+ const impact = sections.Impact
138
+ if (!impact) return ''
139
+ const named = tableRows(impact)
140
+ .map((r) => r.detail || r.surface || '')
141
+ .map((s) => s.trim())
142
+ .filter(Boolean)
143
+ return [...new Set(named)].join(' · ')
144
+ }
145
+
146
+ // The value of a `> **Field:** value` header line, or ''.
147
+ function headerValue(body, field) {
148
+ const m = String(body || '').match(new RegExp(`^>\\s*\\*\\*${field}:\\*\\*\\s*(.+)$`, 'm'))
149
+ return m ? m[1].trim() : ''
150
+ }
151
+
152
+ // The acceptance criteria as a checklist: every list item becomes `- [ ]`,
153
+ // keeping a `[x]` the author ticked. Prose between items is kept as written.
154
+ function criteria(sections) {
155
+ const text = sections['Acceptance criteria']
156
+ if (!text) return ''
157
+ return String(text)
158
+ .trim()
159
+ .split('\n')
160
+ .map((line) => {
161
+ const m = line.match(/^(\s*)[-*+]\s+(\[[ xX]\]\s+)?(.*)$/)
162
+ if (!m) return line
163
+ const box = m[2] && /x/i.test(m[2]) ? '[x]' : '[ ]'
164
+ return `${m[1]}- ${box} ${m[3]}`
165
+ })
166
+ .join('\n')
167
+ }
168
+
169
+ // `specs/<bucket>/<name>` — where the spec lives, for a reader who wants more.
170
+ function specPath(snapshotDir) {
171
+ const dir = String(snapshotDir || '')
172
+ return ['specs', path.basename(path.dirname(dir)), path.basename(dir)].join('/')
173
+ }
174
+
175
+ /**
176
+ * The spec ticket's block content (unwrapped). Every part is skipped, never
177
+ * invented, when its source is absent — a spec with no Summary, criteria,
178
+ * Impact table or Gating header still gets a block: its Problem and its path.
179
+ */
180
+ function specBlockInner({ snapshotDir, sections, body, phases }) {
181
+ const summary =
182
+ String(sections.Summary || '').trim() || firstParagraph(sections.Problem) || firstParagraph(sections.Symptom)
183
+ const parts = []
184
+ if (summary) parts.push(summary)
185
+ const ac = criteria(sections)
186
+ if (ac) parts.push(`**Acceptance criteria**\n\n${ac}`)
187
+ const t = touches(sections)
188
+ if (t) parts.push(`**Touches** ${t}`)
189
+ const gating = headerValue(body, 'Gating')
190
+ if (gating) parts.push(`**Gating** ${gating}`)
191
+ const progress = progressLine(phases)
192
+ if (progress) parts.push(progress)
193
+ parts.push(`**Spec** \`${specPath(snapshotDir)}\``)
194
+ return parts.join('\n\n')
195
+ }
196
+
197
+ // --- progress -----------------------------------------------------------------
198
+
199
+ // A phase's checkboxes: every task bullet, nested ones included, each counted
200
+ // once. Only `x` is done — `[~]`, `[>]`, `[-]` are not (task-block.js).
201
+ function taskCounts(phase) {
202
+ const boxes = ((phase && phase.blocks) || []).filter((b) => b && b.checkbox)
203
+ return { ticked: boxes.filter((b) => b.mark === 'x').length, total: boxes.length }
204
+ }
205
+
206
+ /**
207
+ * How far along a spec is, from its phase files' own checkboxes.
208
+ *
209
+ * `null` when there is not a single checkbox anywhere: that is cannot-tell, not
210
+ * 0%. A spec written without task lists has not "made no progress", and a
211
+ * ticket reading 0% for its whole life would say exactly that.
212
+ *
213
+ * `phase` is the one being worked: the first in progress, else the first not
214
+ * done, else the last (everything is done).
215
+ */
216
+ function progressOf(phases) {
217
+ const list = (phases || []).filter((p) => p && p.name)
218
+ let ticked = 0
219
+ let total = 0
220
+ for (const p of list) {
221
+ const c = taskCounts(p)
222
+ ticked += c.ticked
223
+ total += c.total
224
+ }
225
+ if (!total) return null
226
+ let at = list.findIndex((p) => p.state === 'in-progress')
227
+ if (at === -1) at = list.findIndex((p) => p.state !== 'complete')
228
+ if (at === -1) at = list.length - 1
229
+ return { ticked, total, percent: Math.floor((ticked / total) * 100), phase: at + 1, phases: list.length }
230
+ }
231
+
232
+ function progressLine(phases) {
233
+ const p = progressOf(phases)
234
+ return p ? `**Progress** ${p.percent}% · phase ${p.phase} of ${p.phases}` : ''
235
+ }
236
+
237
+ // A phase sub-issue's block content: its goal, and its task count when it has
238
+ // any checkboxes (a phase with none says nothing rather than `0 of 0`).
239
+ function phaseBlockInner(phase) {
240
+ const goal = String((phase && phase.goal) || '').trim() || String((phase && phase.name) || '').trim()
241
+ const { ticked, total } = taskCounts(phase)
242
+ return total ? `${goal}\n\n**Progress** ${ticked} of ${total} tasks` : goal
243
+ }
244
+
245
+ module.exports = {
246
+ DELIMITERS,
247
+ descriptionMode,
248
+ delimitersFor,
249
+ blockOf,
250
+ wrapBlock,
251
+ spliceBlock,
252
+ comparableDescription,
253
+ specBlockInner,
254
+ phaseBlockInner,
255
+ progressOf,
256
+ tableRows,
257
+ }