@skitterbyte/skitterspec-jira 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 (67) hide show
  1. package/assets/claude-md-section.md +20 -1
  2. package/assets/core/SETUP.md +5 -0
  3. package/assets/core/env.config.json.example +1 -0
  4. package/assets/core/env.config.md +143 -8
  5. package/assets/core/jira.config.md +4 -2
  6. package/assets/hooks/main-guard.cjs +40 -6
  7. package/assets/hooks/review-gate.cjs +42 -7
  8. package/assets/rules/commit-trailers.md +24 -1
  9. package/assets/rules/spec-planning.md +81 -18
  10. package/assets/rules/spec-reports.md +1 -1
  11. package/assets/skills/spec/SKILL.md +55 -2
  12. package/assets/skills/spec-bug/SKILL.md +25 -1
  13. package/assets/skills/spec-cancel/SKILL.md +35 -0
  14. package/assets/skills/spec-complete/SKILL.md +113 -0
  15. package/assets/skills/spec-hotfix/SKILL.md +40 -2
  16. package/assets/skills/spec-incident/SKILL.md +22 -0
  17. package/assets/skills/spec-jira-setup/SKILL.md +23 -1
  18. package/assets/skills/spec-next/SKILL.md +9 -4
  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 +39 -1
  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 +1188 -79
  27. package/src/env/base.js +104 -0
  28. package/src/env/bootstrap.js +22 -3
  29. package/src/env/classify.js +12 -4
  30. package/src/env/config.js +77 -5
  31. package/src/env/disposition.js +62 -0
  32. package/src/env/handoff.js +81 -0
  33. package/src/env/host.js +262 -0
  34. package/src/env/hotfix.js +237 -9
  35. package/src/env/hotfixland.js +105 -10
  36. package/src/env/inflight.js +98 -0
  37. package/src/env/integrate.js +136 -9
  38. package/src/env/live.js +8 -7
  39. package/src/env/mainguard.js +20 -5
  40. package/src/env/phases.js +28 -0
  41. package/src/env/project.js +223 -0
  42. package/src/env/provision.js +30 -8
  43. package/src/env/resolve.js +147 -25
  44. package/src/env/review.js +21 -7
  45. package/src/env/reviewers.js +7 -10
  46. package/src/env/serve.js +27 -11
  47. package/src/env/specstate.js +101 -0
  48. package/src/env/supervise.js +15 -2
  49. package/src/env/teardown.js +46 -3
  50. package/src/init.js +49 -9
  51. package/src/vendor/jira/cli-sync.js +48 -4
  52. package/src/vendor/jira/config.js +17 -5
  53. package/src/vendor/provider-kit/index.js +4 -0
  54. package/src/vendor/provider-kit/src/apply.js +58 -6
  55. package/src/vendor/provider-kit/src/assignment.js +78 -1
  56. package/src/vendor/provider-kit/src/config.js +34 -1
  57. package/src/vendor/provider-kit/src/credentials.js +7 -2
  58. package/src/vendor/provider-kit/src/list-rows.js +35 -11
  59. package/src/vendor/provider-kit/src/released.js +48 -4
  60. package/src/vendor/provider-kit/src/specs.js +18 -7
  61. package/src/vendor/provider-kit/src/splice.js +64 -0
  62. package/src/vendor/provider-kit/src/status.js +137 -0
  63. package/src/vendor/sync-core/index.js +14 -1
  64. package/src/vendor/sync-core/src/compare.js +81 -6
  65. package/src/vendor/sync-core/src/normalize.js +50 -7
  66. package/src/vendor/sync-core/src/push.js +65 -5
  67. package/src/vendor/sync-core/src/summary.js +257 -0
@@ -21,7 +21,7 @@ const CONFIG_FILE = 'specs/.core/jira.config.json'
21
21
 
22
22
  const OWNERSHIP = Object.freeze(['both', 'pull', 'push', 'none'])
23
23
  const TASK_MAPPINGS = Object.freeze(['checklist', 'none'])
24
- const PHASE_MAPPINGS = Object.freeze(['subissue', 'deferred', 'inline'])
24
+ const PHASE_MAPPINGS = Object.freeze(['subissue', 'deferred', 'inline', 'none'])
25
25
  const TRANSPORTS = Object.freeze(['api', 'mcp'])
26
26
  const DEFAULT_EMAIL_ENV = 'JIRA_EMAIL'
27
27
  const DEFAULT_TOKEN_ENV = 'JIRA_API_TOKEN'
@@ -43,7 +43,12 @@ const DEFAULT_CONFIG = Object.freeze({
43
43
  // A spec is a Jira ISSUE; each phase a SUBTASK of it. `tasks` selects how the
44
44
  // phase's checkboxes reach that subtask's description (as an ADF task list —
45
45
  // live checkboxes, still a read-only mirror).
46
- mapping: Object.freeze({ specFolder: 'issue', phases: DEFAULT_PHASE_MODE, tasks: 'checklist' }),
46
+ // `description`: what the ticket body carries — `spec` (the whole overview)
47
+ // or `summary` (a delimited block beside the team's own text). `spec` is the
48
+ // default so a config written before the key pushes what it always pushed.
49
+ mapping: Object.freeze({ specFolder: 'issue', phases: DEFAULT_PHASE_MODE, tasks: 'checklist', description: 'spec' }),
50
+ // The summary block's delimiters (provisional until chore-delimiter-spike-providers measures this tracker).
51
+ summary: Object.freeze({ delimiter: 'heading' }),
47
52
  // Jira STATUS names — the spec issue's status (from the folder bucket) and
48
53
  // each subtask's status (from the phase emoji) both map through this table.
49
54
  // They must match the project's workflow statuses exactly; `validateStates`
@@ -76,11 +81,16 @@ const DEFAULT_CONFIG = Object.freeze({
76
81
  sync: Object.freeze({
77
82
  baseDir: 'specs/.core/jira-base',
78
83
  backupDir: 'specs/.core/jira-backups',
84
+ // The repo owns the spec's CONTENT (`push`); the tracker owns its STATUS and
85
+ // ASSIGNEE (`pull`) — the board is where a team assigns and moves work, so a
86
+ // repo copy is one somebody has to keep in step by hand. Under `pull` the
87
+ // state is sent only as a transition the repo made (a bucket move), and the
88
+ // assignee not at all. Set either back to `"push"` for the repo-owned behaviour.
79
89
  fieldOwnership: Object.freeze({
80
90
  description: 'push',
81
91
  subIssues: 'push',
82
- workflowState: 'push',
83
- assignee: 'push',
92
+ workflowState: 'pull',
93
+ assignee: 'pull',
84
94
  }),
85
95
  localOnlySections: Object.freeze(['State log', 'Changelog', 'Open questions']),
86
96
  keyedFields: Object.freeze({}),
@@ -105,6 +115,7 @@ function defaults() {
105
115
  return {
106
116
  jira: { ...DEFAULT_CONFIG.jira, issueTypeByKind: { ...DEFAULT_CONFIG.jira.issueTypeByKind } },
107
117
  mapping: { ...DEFAULT_CONFIG.mapping },
118
+ summary: { ...DEFAULT_CONFIG.summary },
108
119
  states: { ...DEFAULT_CONFIG.states },
109
120
  statesByType: {},
110
121
  stateAliases: {},
@@ -127,7 +138,7 @@ function defaults() {
127
138
  }
128
139
 
129
140
  const { isObject, stringList, assign } = kitConfig
130
- const { mergeStates, mergeStateOverrides, mergeFieldOwnership, mergePhaseMapping, mergeReleaseIgnorePaths, mergeKeyedFields } =
141
+ const { mergeStates, mergeStateOverrides, mergeFieldOwnership, mergePhaseMapping, mergeReleaseIgnorePaths, mergeKeyedFields, mergeDescription } =
131
142
  kitConfig.makeMergeHelpers({
132
143
  configFile: CONFIG_FILE,
133
144
  ownership: OWNERSHIP,
@@ -173,6 +184,7 @@ function mergeConfig(base, parsed) {
173
184
  }
174
185
  mergePhaseMapping(base.mapping, parsed.mapping)
175
186
  }
187
+ mergeDescription(base, parsed)
176
188
 
177
189
  mergeStates(base, parsed)
178
190
  mergeStateOverrides(base, parsed, 'statesByType')
@@ -24,6 +24,8 @@ const prompt = require('./src/prompt.js')
24
24
  const args = require('./src/args.js')
25
25
  const adapter = require('./src/adapter.js')
26
26
  const apply = require('./src/apply.js')
27
+ const status = require('./src/status.js')
28
+ const splice = require('./src/splice.js')
27
29
 
28
30
  module.exports = {
29
31
  ...config,
@@ -38,4 +40,6 @@ module.exports = {
38
40
  ...args,
39
41
  ...adapter,
40
42
  ...apply,
43
+ ...status,
44
+ ...splice,
41
45
  }
@@ -36,6 +36,7 @@
36
36
  * - `updateSubIssue(sub)` apply a sub-issue update
37
37
  * - `remoteEditedLine(identifier)` the someone-else-edited warning
38
38
  * - `twinAdvice(twin, title, specName)` the refusal message for a twin
39
+ * - `afterIssue(issue)` optional; → a report line or null
39
40
  */
40
41
 
41
42
  const path = require('node:path')
@@ -51,6 +52,8 @@ const {
51
52
  remoteDescriptionEdited,
52
53
  remoteSubIssueEdited,
53
54
  listPhaseFiles,
55
+ descriptionMode,
56
+ spliceBlock,
54
57
  } = require('../../sync-core')
55
58
  const { makeSpecHelpers } = require('./specs.js')
56
59
 
@@ -80,6 +83,9 @@ async function applyInner({ dir, config, snapshotDir, plan, adapter, ops, progre
80
83
  const identifier = helpers.linkedIdentifier(path.join(snapshotDir, overviewFile), config)
81
84
  const lines = []
82
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() }
83
89
  // Handed out immediately, so a throw from anywhere below still reports what
84
90
  // had been stamped by the time it happened.
85
91
  if (progress) progress.result = result
@@ -140,11 +146,23 @@ async function applyInner({ dir, config, snapshotDir, plan, adapter, ops, progre
140
146
  lines.push(ops.remoteEditedLine(identifier))
141
147
  }
142
148
  if (plan.issue) {
143
- await ops.updateIssue(existing, plan.issue)
149
+ const issue = spliced(plan.issue, 'description', existing, config, identifier, lines)
150
+ await ops.updateIssue(existing, issue)
144
151
  lines.push(` issue updated: ${identifier}`)
145
152
  }
146
153
  }
147
154
 
155
+ // A provider's per-push extra on the spec issue (e.g. progress mirrored into
156
+ // a native field). Never fatal: the repo and the block already carry it.
157
+ if (ops.afterIssue && result.issue) {
158
+ try {
159
+ const line = await ops.afterIssue(result.issue)
160
+ if (line) lines.push(line)
161
+ } catch (error) {
162
+ lines.push(` ?? ${result.issue.identifier}: ${String((error && error.message) || error).split('\n')[0]}`)
163
+ }
164
+ }
165
+
148
166
  // 4. Sub-issue creates — each stamped as it lands, for the same reason.
149
167
  for (const sub of (plan.subIssues && plan.subIssues.create) || []) {
150
168
  const created = await ops.mintSubIssue(parentId, sub)
@@ -152,6 +170,7 @@ async function applyInner({ dir, config, snapshotDir, plan, adapter, ops, progre
152
170
  const file = resolvePhaseFileIn(snapshotDir, sub.ref)
153
171
  if (!file) throw new Error(`no phase file for ref ${sub.ref}`)
154
172
  stampSubIssueId(snapshotDir, file, created.identifier, config)
173
+ if (sub.state != null) sent.subIssues.add(String(created.identifier))
155
174
  result.subIssues[sub.ref] = created.identifier
156
175
  lines.push(` sub-issue created: ${sub.ref} → ${created.identifier}`)
157
176
  }
@@ -167,13 +186,18 @@ async function applyInner({ dir, config, snapshotDir, plan, adapter, ops, progre
167
186
  // issue. The read is spent only where the snapshot recorded something to
168
187
  // compare against, so an old snapshot costs no extra calls.
169
188
  const base = readBase(dir, identifier, config)
170
- for (const sub of (plan.subIssues && plan.subIssues.update) || []) {
189
+ const summary = descriptionMode(config) === 'summary'
190
+ for (let sub of (plan.subIssues && plan.subIssues.update) || []) {
171
191
  const streams = base && base.subIssueStreams
172
- if (sub.goal != null && streams && streams[String(sub.id)]) {
192
+ const compare = sub.goal != null && streams && streams[String(sub.id)]
193
+ // Summary mode always reads the live body: the block is spliced into it.
194
+ if (compare || (summary && sub.goal != null)) {
173
195
  const before = await adapter.readIssue(sub.id)
174
- if (remoteSubIssueEdited(base, sub.id, before, config) === true) lines.push(ops.remoteEditedLine(sub.id))
196
+ if (compare && remoteSubIssueEdited(base, sub.id, before, config) === true) lines.push(ops.remoteEditedLine(sub.id))
197
+ sub = spliced(sub, 'goal', before, config, sub.id, lines)
175
198
  }
176
199
  await ops.updateSubIssue(sub)
200
+ if (sub.state != null) sent.subIssues.add(String(sub.id))
177
201
  result.subIssues[sub.ref || refById.get(String(sub.id)) || sub.id] = sub.id
178
202
  lines.push(` sub-issue updated: ${sub.id}`)
179
203
  }
@@ -193,11 +217,39 @@ async function applyInner({ dir, config, snapshotDir, plan, adapter, ops, progre
193
217
  const lost = verify.some((l) => l.includes('!!') || l.includes('??'))
194
218
 
195
219
  // 7. Record the snapshot from the now-stamped files, so the next push is empty.
196
- const file = recordPush({ dir, snapshotDir, identifier: helpers.specIdentifier(snapshotDir, config), config })
197
- lines.push(` snapshot: ${path.relative(dir, file)}`)
220
+ const file = recordPush({ dir, snapshotDir, identifier: helpers.specIdentifier(snapshotDir, config), config, sent })
221
+ // A repo path, `/`-separated on every platform — the form every other
222
+ // spec path in this output takes.
223
+ lines.push(` snapshot: ${path.relative(dir, file).split(path.sep).join('/')}`)
198
224
  return { result, lines, lost }
199
225
  }
200
226
 
227
+ /**
228
+ * Under `mapping.description: "summary"` the planned body is the block alone,
229
+ * and the write must be the block SPLICED into what the tracker holds, so the
230
+ * team's text around it survives. `spec` mode returns the payload untouched.
231
+ *
232
+ * A damaged block (a delimiter someone edited) is cannot-tell: the body is
233
+ * left out of the write entirely and the run says so. Guessing the edges would
234
+ * eat the team's text, and prepending would leave two blocks.
235
+ */
236
+ function spliced(payload, key, live, config, label, lines) {
237
+ if (descriptionMode(config) !== 'summary' || payload[key] == null) return payload
238
+ const hook = config && config.remote && config.remote.description
239
+ const current = live && typeof hook === 'function' ? hook(live) : live ? live.description : undefined
240
+ // Nothing read back is not an empty body: write nothing rather than guess.
241
+ if (typeof current !== 'string') {
242
+ lines.push(` ?? ${label}: could not read its body — summary block not written`)
243
+ return { ...payload, [key]: undefined }
244
+ }
245
+ const next = spliceBlock(current, payload[key], config)
246
+ if (next == null) {
247
+ lines.push(` !! ${label}: its summary block's delimiters were edited — block not written; repair them and re-push`)
248
+ return { ...payload, [key]: undefined }
249
+ }
250
+ return { ...payload, [key]: next }
251
+ }
252
+
201
253
  // The phase file a sub-issue ref names — the ref is the phase-file basename.
202
254
  function resolvePhaseFileIn(snapshotDir, ref) {
203
255
  const want = String(ref).replace(/\.md$/, '')
@@ -13,6 +13,12 @@
13
13
  * the operator is in the tracker, which is the fact assignment rests on.
14
14
  * - `users [<query>]` finds a person to hand a spec to.
15
15
  *
16
+ * Under `sync.fieldOwnership.assignee: "pull"` the TRACKER owns the field, so
17
+ * `assign` writes the ticket directly and stamps nothing into the repo — there
18
+ * is no projection to carry it, and a stamp would be a copy someone has to
19
+ * keep in step. `--if-unassigned` is how `/spec-start` claims a ticket nobody
20
+ * holds without ever taking one from someone who does.
21
+ *
16
22
  * Everything tracker-shaped arrives as a hook (`makeAssignmentCommands`): the
17
23
  * tracker's name for messages, the frontmatter fields, the store scope, how a
18
24
  * credential resolves and how an adapter is made. The behaviour is the Linear
@@ -21,9 +27,10 @@
21
27
 
22
28
  const path = require('node:path')
23
29
 
24
- const { ownsField, writeFrontmatter, deleteFrontmatter, fieldsOf } = require('../../sync-core')
30
+ const { ownsField, ownershipOf, writeFrontmatter, deleteFrontmatter, fieldsOf, readSnapshot } = require('../../sync-core')
25
31
  const { resolveTransport } = require('./transport.js')
26
32
  const { makeSpecHelpers } = require('./specs.js')
33
+ const { readStatus } = require('./status.js')
27
34
 
28
35
  /**
29
36
  * @param {object} p
@@ -58,6 +65,7 @@ function makeAssignmentCommands(p) {
58
65
 
59
66
  const problems = []
60
67
  if (flags.release && flags.to) problems.push('--release and --to are opposites — pass one')
68
+ if (flags.release && flags.ifUnassigned) problems.push('--if-unassigned guards an assignment — it has nothing to say about --release')
61
69
  if (!flags.release && !flags.to) problems.push('nothing to do — pass --to <user-id> or --release')
62
70
  // An unlinked spec has no issue to assign. Refusing beats stamping a field
63
71
  // that would sit in the file doing nothing until someone noticed.
@@ -86,6 +94,19 @@ function makeAssignmentCommands(p) {
86
94
  return 1
87
95
  }
88
96
 
97
+ if (ownershipOf(config, 'assignee') === 'pull') return assignOnTracker(config, identifier, flags, out)
98
+
99
+ // Under `push` the repo's stamp IS the record, so that is what the guard asks.
100
+ if (flags.ifUnassigned) {
101
+ const { frontmatter } = readSnapshot(snapshotDir, config)
102
+ const recorded = frontmatter[fields.assigneeId]
103
+ if (recorded) {
104
+ const shown = (fields.assigneeName && frontmatter[fields.assigneeName]) || recorded
105
+ out.write(`spec-sync assign: ${rel} is already assigned to ${shown} — left alone\n`)
106
+ return 0
107
+ }
108
+ }
109
+
89
110
  if (flags.release) {
90
111
  const removed = deleteFrontmatter(snapshotDir, config, [fields.assigneeId, fields.assigneeName].filter(Boolean))
91
112
  if (flags.json) {
@@ -116,6 +137,62 @@ function makeAssignmentCommands(p) {
116
137
  return 0
117
138
  }
118
139
 
140
+ /**
141
+ * The `pull` half of `assign`: write the ticket, stamp nothing.
142
+ *
143
+ * `--if-unassigned` reads the ticket first and acts only on a POSITIVE
144
+ * "nobody holds it". A read that could not run is cannot-tell, and the
145
+ * harmless branch is to assign nobody: taking a ticket from a colleague is
146
+ * the one mistake here that costs someone else their afternoon.
147
+ *
148
+ * Exits 0 on every cannot-tell (MCP transport, no credential, an unreadable
149
+ * ticket) and 1 only when the tracker refused a write it was asked to make.
150
+ */
151
+ async function assignOnTracker(config, identifier, flags, out) {
152
+ const say = (line) => {
153
+ out.write(`spec-sync assign: ${line}\n`)
154
+ return 0
155
+ }
156
+ const report = (result) => {
157
+ if (flags.json) {
158
+ out.write(JSON.stringify({ issue: identifier, owner: 'tracker', ...result }, null, 2) + '\n')
159
+ return 0
160
+ }
161
+ return say(result.line)
162
+ }
163
+ const cred = flags.adapter ? { ok: true } : p.resolveCredential(config, flags.env || process.env)
164
+ const transport = resolveTransport(flags, config, cred.ok)
165
+ if (transport === 'mcp' || !cred.ok) {
166
+ const what = flags.release ? 'unassign it' : `assign it to ${flags.to}`
167
+ return report({
168
+ written: false,
169
+ line: `${p.tracker} owns the assignee here, and there is no API transport — ${what} on ${identifier} with the tracker's own tool; nothing was written`,
170
+ })
171
+ }
172
+ const adapter = flags.adapter || p.makeAdapter(config, cred, flags)
173
+
174
+ if (flags.ifUnassigned) {
175
+ const now = await readStatus({ adapter, ref: identifier, config })
176
+ if (!now.ok) {
177
+ return report({ written: false, line: `could not read ${identifier} (${now.reason}) — assigned nobody` })
178
+ }
179
+ if (now.assignee) {
180
+ const who = now.assignee.name || now.assignee.id
181
+ return report({ written: false, assignee: now.assignee, line: `${identifier} is already assigned to ${who} — left alone` })
182
+ }
183
+ }
184
+
185
+ try {
186
+ await adapter.updateIssue(identifier, { assigneeId: flags.release ? null : flags.to })
187
+ } catch (error) {
188
+ out.write(`spec-sync assign: ${p.tracker} refused — ${String(error.message).split('\n')[0]}\n`)
189
+ return 1
190
+ }
191
+ if (flags.release) return report({ written: true, released: true, line: `${identifier} unassigned on ${p.tracker}` })
192
+ const who = flags.name ? `${flags.name} (${flags.to})` : flags.to
193
+ return report({ written: true, id: flags.to, name: flags.name || null, line: `${identifier} assigned to ${who} on ${p.tracker}` })
194
+ }
195
+
119
196
  /**
120
197
  * Exit 0 even when the answer is "unknown": this answers a question, and
121
198
  * "nobody is identified here" is a valid answer — a shared key, an offline
@@ -236,6 +236,33 @@ function makeMergeHelpers({ configFile, ownership, lifecycleBuckets, phaseMappin
236
236
  base[key] = table
237
237
  }
238
238
 
239
+ // Merge (and validate) what a ticket's description carries —
240
+ // `mapping.description` (`spec` · `summary`) and the block's delimiter style
241
+ // (`summary.delimiter`: `comment` · `heading`). Loud on a bad value: a typo
242
+ // must not read as a choice to keep pushing the whole spec.
243
+ function mergeDescription(base, parsed) {
244
+ if (isObject(parsed.mapping) && parsed.mapping.description !== undefined) {
245
+ const mode = parsed.mapping.description
246
+ if (!DESCRIPTION_MODES.includes(mode)) {
247
+ throw new Error(
248
+ `Invalid ${configFile}: mapping.description = ${JSON.stringify(mode)} ` +
249
+ `(expected one of ${DESCRIPTION_MODES.join('|')})`,
250
+ )
251
+ }
252
+ base.mapping.description = mode
253
+ }
254
+ if (isObject(parsed.summary) && parsed.summary.delimiter !== undefined) {
255
+ const style = parsed.summary.delimiter
256
+ if (!DELIMITER_STYLES.includes(style)) {
257
+ throw new Error(
258
+ `Invalid ${configFile}: summary.delimiter = ${JSON.stringify(style)} ` +
259
+ `(expected one of ${DELIMITER_STYLES.join('|')})`,
260
+ )
261
+ }
262
+ base.summary = { ...(base.summary || {}), delimiter: style }
263
+ }
264
+ }
265
+
239
266
  return {
240
267
  mergeStates,
241
268
  mergeStateOverrides,
@@ -243,9 +270,15 @@ function makeMergeHelpers({ configFile, ownership, lifecycleBuckets, phaseMappin
243
270
  mergePhaseMapping,
244
271
  mergeReleaseIgnorePaths,
245
272
  mergeKeyedFields,
273
+ mergeDescription,
246
274
  }
247
275
  }
248
276
 
277
+ // What `mapping.description` may be. `spec` is the default and what a config
278
+ // that predates the key gets, so an upgrade rewrites no ticket.
279
+ const DESCRIPTION_MODES = Object.freeze(['spec', 'summary'])
280
+ const DELIMITER_STYLES = Object.freeze(['comment', 'heading'])
281
+
249
282
  // Keys no provider reads any more. The merge already ignores them, as it does
250
283
  // every unknown key — so a config still carrying one is a stale file, not a
251
284
  // broken one, and `doctor` says so as a `warn` without touching the exit code.
@@ -292,4 +325,4 @@ function retiredKeysRow(file, configFile, row) {
292
325
  )
293
326
  }
294
327
 
295
- module.exports = { isObject, stringList, assign, makeMergeHelpers, retiredKeys, retiredKeysRow, RETIRED_KEYS }
328
+ module.exports = { isObject, stringList, assign, makeMergeHelpers, retiredKeys, retiredKeysRow, RETIRED_KEYS, DESCRIPTION_MODES, DELIMITER_STYLES }
@@ -63,7 +63,7 @@ function storePath(env = process.env, homedir = os.homedir) {
63
63
  * `absent` (no file — the normal default, not a problem), `permissions`
64
64
  * (group/world readable), `unreadable`, `malformed`.
65
65
  */
66
- function readStore(file, { stat = fs.statSync, read = fs.readFileSync } = {}) {
66
+ function readStore(file, { stat = fs.statSync, read = fs.readFileSync, platform = process.platform } = {}) {
67
67
  let info
68
68
  try {
69
69
  info = stat(file)
@@ -74,7 +74,12 @@ function readStore(file, { stat = fs.statSync, read = fs.readFileSync } = {}) {
74
74
  return { ok: false, code: 'unreadable', path: file, reason: `cannot read ${file}: ${err.message}` }
75
75
  }
76
76
 
77
- if (info.mode & GROUP_OR_WORLD) {
77
+ // ON WINDOWS THE MODE BITS SAY NOTHING. Node reports every file there as
78
+ // 0o666, so this check refused every store on Windows and no stored
79
+ // credential could ever be read (chore-windows-ci). Access there is the
80
+ // profile directory's ACL, which these bits do not describe — cannot tell,
81
+ // and cannot-tell does not accuse (`.claude/rules/negative-checks.md`).
82
+ if (platform !== 'win32' && info.mode & GROUP_OR_WORLD) {
78
83
  const mode = (info.mode & 0o777).toString(8)
79
84
  return {
80
85
  ok: false,
@@ -14,22 +14,46 @@ function expandStateArgs(args, config) {
14
14
  return (args || []).flatMap((arg) => (LIFECYCLE_BUCKETS.includes(arg) ? stateNamesFor(arg, config) : [arg]))
15
15
  }
16
16
 
17
- // The spec's status beside the board's, and whether they disagree. A board
18
- // state that maps to no bucket never disagrees: it is somewhere push does not
19
- // manage, which is not a claim about the spec. Nor does a row whose spec is not
20
- // on this machine — there is nothing to disagree WITH.
17
+ // A spec's bucket is a CODE FACT — whether `/spec-start`, `/spec-complete` or
18
+ // `/spec-cancel` has run — and the board holds the planning status. So almost
19
+ // every difference between the two is the board doing its job: a backlog spec
20
+ // the board calls Ready or Blocked, an in-flight one it calls In Review. Neither
21
+ // is a claim about the repo, and flagging them would teach a reader to ignore
22
+ // the column.
23
+ //
24
+ // One difference IS worth a reader's time: the board says the work is finished
25
+ // (Done or Cancelled) and the repo has not done the matching cleanup. Only that
26
+ // pairing disagrees, and it carries the command that would close it.
27
+ const LIVE_BUCKETS = ['backlog', 'in-progress']
28
+ const FINISHED_BUCKETS = ['complete', 'cancelled']
29
+
30
+ // `{ board, cleanup }` when the board has finished what the repo has not, else
31
+ // null. Done against a spec in flight is `/spec-complete`; every other pairing
32
+ // (Cancelled, or Done on a spec that never started) is `/spec-cancel`, because
33
+ // there is no work here to complete.
34
+ function boardDisagreement(specBucket, boardBucket) {
35
+ if (!LIVE_BUCKETS.includes(specBucket) || !FINISHED_BUCKETS.includes(boardBucket)) return null
36
+ const cleanup = specBucket === 'in-progress' && boardBucket === 'complete' ? '/spec-complete' : '/spec-cancel'
37
+ return { board: boardBucket, cleanup }
38
+ }
39
+
40
+ // The spec's status beside the board's, and whether they disagree in the one
41
+ // way above. A board state that maps to no bucket never disagrees: it is
42
+ // somewhere push does not manage, which is not a claim about the spec. Nor does
43
+ // a row whose spec is not on this machine — there is nothing to disagree WITH.
21
44
  function specColumn(stateName, spec, config) {
22
45
  const specStatus = spec ? spec.bucket : null
23
46
  const seen = stateName == null ? null : remoteStateReading({ state: { name: stateName } }, config)
24
- const disagrees = Boolean(specStatus && seen && seen.mapped && seen.bucket !== specStatus)
25
- return { specStatus, disagrees }
47
+ const found = specStatus && seen && seen.mapped ? boardDisagreement(specStatus, seen.bucket) : null
48
+ return found ? { specStatus, disagrees: true, cleanup: found.cleanup } : { specStatus, disagrees: false }
26
49
  }
27
50
 
28
- // The cell itself: `in-progress`, `≠ backlog` when it disagrees, `—` when the
29
- // spec is not here.
30
- function specCell({ specStatus, disagrees }) {
51
+ // The cell itself: `in-progress`, `≠ in-progress → /spec-cancel` when the board
52
+ // finished it, `—` when the spec is not here.
53
+ function specCell({ specStatus, disagrees, cleanup }) {
31
54
  if (!specStatus) return '—'
32
- return disagrees ? `≠ ${specStatus}` : specStatus
55
+ if (!disagrees) return specStatus
56
+ return cleanup ? `≠ ${specStatus} → ${cleanup}` : `≠ ${specStatus}`
33
57
  }
34
58
 
35
- module.exports = { expandStateArgs, specColumn, specCell }
59
+ module.exports = { expandStateArgs, specColumn, specCell, boardDisagreement }
@@ -1,5 +1,25 @@
1
1
  'use strict'
2
2
 
3
+ const { execFileSync } = require('node:child_process')
4
+ const { primaryAnchor, fromRepoPath } = require('../../../env/project.js')
5
+
6
+ /**
7
+ * The project's prefix within its repo, read from `dir` — `''` at the root, and
8
+ * `''` whenever git cannot answer (today's behaviour). What `ticketsInRange`
9
+ * needs to read a commit's root-relative paths against the project's
10
+ * `ignorePaths`.
11
+ */
12
+ function projectPrefixOf(dir) {
13
+ const git = (args) => {
14
+ try {
15
+ return execFileSync('git', ['-C', dir, ...args], { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'] }).trim()
16
+ } catch {
17
+ return null
18
+ }
19
+ }
20
+ return primaryAnchor(dir, git).prefix
21
+ }
22
+
3
23
  /**
4
24
  * Which tickets a release contains.
5
25
  *
@@ -99,7 +119,14 @@ function asGlobal(pattern) {
99
119
  * @param {string[]|null|undefined} paths repo-relative paths the commit changed
100
120
  * @param {string[]} ignorePaths repo-relative prefixes that are bookkeeping
101
121
  */
102
- function onlyIgnoredPaths(paths, ignorePaths) {
122
+ //
123
+ // `paths` are what `git log --name-only` prints — from the REPO ROOT — while
124
+ // `ignorePaths` are the project's, like every path in its config. For a project
125
+ // in a subfolder of its repo (`prefix`, spec feat-subfolder-project) each path
126
+ // is made project-relative first, and a path OUTSIDE the project is never
127
+ // bookkeeping: a commit that touched `Sql/` did real work. Prefix '' compares
128
+ // exactly as before.
129
+ function onlyIgnoredPaths(paths, ignorePaths, prefix = '') {
103
130
  if (!Array.isArray(paths) || !paths.length) return false
104
131
  const prefixes = (Array.isArray(ignorePaths) ? ignorePaths : [])
105
132
  .filter((p) => typeof p === 'string' && p.trim())
@@ -113,7 +140,9 @@ function onlyIgnoredPaths(paths, ignorePaths) {
113
140
  // An unreadable entry is an unknown, not an ignored one — it makes the whole
114
141
  // commit count, per the bias above.
115
142
  if (!file) return false
116
- return prefixes.some((prefix) => file === prefix || file.startsWith(`${prefix}/`))
143
+ const rel = fromRepoPath(file, prefix)
144
+ if (rel === null) return false
145
+ return prefixes.some((p) => rel === p || rel.startsWith(`${p}/`))
117
146
  })
118
147
  }
119
148
 
@@ -140,14 +169,18 @@ function onlyIgnoredPaths(paths, ignorePaths) {
140
169
  */
141
170
  function ticketsInRange(commits, options = {}) {
142
171
  const ignorePaths = (options && options.ignorePaths) || []
172
+ const prefix = (options && options.prefix) || ''
143
173
  const refPattern = options && options.refPattern
144
174
  const foreign = ((options && options.foreignPatterns) || []).map(asGlobal).filter(Boolean)
145
175
  const seen = new Map()
146
176
  let unreferenced = 0
147
177
  let ignored = 0
148
178
  let historical = 0
179
+ let merges = 0
180
+ let sawMergeFlag = false
149
181
  for (const commit of commits || []) {
150
- if (onlyIgnoredPaths(commit && commit.paths, ignorePaths)) {
182
+ if (commit && commit.isMerge !== undefined) sawMergeFlag = true
183
+ if (onlyIgnoredPaths(commit && commit.paths, ignorePaths, prefix)) {
151
184
  // Not counted as unreferenced either: that number exists to surface a
152
185
  // MISSED trailer, and a paperwork commit is not a gap someone should hunt.
153
186
  ignored++
@@ -157,8 +190,15 @@ function ticketsInRange(commits, options = {}) {
157
190
  if (!refs.length) {
158
191
  // A POSITIVE signal, never an absence: only a trailer that actually
159
192
  // carries an older tracker's ref makes a commit historical. A commit with
160
- // no trailer at all is still the gap `unreferenced` is there to name.
193
+ // no trailer at all is still the gap `unreferenced` is there to name —
194
+ // unless it is a MERGE commit, which is transport: under PR landing the
195
+ // host writes one per merged PR, and counting each as a missed trailer
196
+ // buries the real gaps. A merge that CARRIES a trailer still counted
197
+ // above, deliberately — a hand merge is where a ticket's only trailer
198
+ // sometimes lives, which is why these are read rather than skipped
199
+ // (`--no-merges` was tried and dropped for exactly that loss).
161
200
  if (foreign.some((p) => refsInBody(commit && commit.body, p).length)) historical++
201
+ else if (commit && commit.isMerge) merges++
162
202
  else unreferenced++
163
203
  continue
164
204
  }
@@ -171,6 +211,9 @@ function ticketsInRange(commits, options = {}) {
171
211
  total: (commits || []).length,
172
212
  }
173
213
  if (foreign.length) report.historical = historical
214
+ // Present only when a caller supplied the flag at all, so a provider that
215
+ // passes no parent info sees exactly the report shape it always did.
216
+ if (sawMergeFlag) report.merges = merges
174
217
  return report
175
218
  }
176
219
 
@@ -209,6 +252,7 @@ function refuseRemovedVerb(out, program, verb) {
209
252
  }
210
253
 
211
254
  module.exports = {
255
+ projectPrefixOf,
212
256
  ticketsInRange,
213
257
  refuseRemovedVerb,
214
258
  nameTickets,
@@ -21,10 +21,10 @@ const {
21
21
  findSpecFolder,
22
22
  resolveSpec,
23
23
  liveWorktreePaths,
24
- resolvePrimaryCheckout,
25
24
  } = require('../../../env/resolve.js')
26
25
  const { loadEnvConfig } = require('../../../env/config.js')
27
- const { readSnapshot, parseFrontmatter, lintPhases, fieldsOf, projectionOf, compareStored } = require('../../sync-core')
26
+ const { primaryAnchor, attachProject, projectIn } = require('../../../env/project.js')
27
+ const { readSnapshot, parseFrontmatter, lintPhases, fieldsOf, projectionOf, compareStored, comparableDescription } = require('../../sync-core')
28
28
 
29
29
  function makeSpecHelpers({ program = 'spec-sync' } = {}) {
30
30
  // Resolve a spec argument to its snapshot dir. Accepts a spec name/folder
@@ -136,9 +136,16 @@ function makeSpecHelpers({ program = 'spec-sync' } = {}) {
136
136
  }
137
137
  let primary
138
138
  let env
139
+ let prefix = ''
139
140
  try {
140
- primary = resolvePrimaryCheckout(dir, git) || dir
141
+ // The project folder in the primary checkout, with where it sits in its
142
+ // repo attached — worktrees are laid out beside the REPO, and each holds
143
+ // the project at the same prefix (feat-subfolder-project).
144
+ const anchor = primaryAnchor(dir, git)
145
+ primary = anchor.dir || dir
146
+ prefix = anchor.prefix
141
147
  env = loadEnvConfig(primary)
148
+ attachProject(env.config, anchor)
142
149
  } catch {
143
150
  return here
144
151
  }
@@ -147,7 +154,7 @@ function makeSpecHelpers({ program = 'spec-sync' } = {}) {
147
154
  // symlinks (macOS /var → /private/var) where `resolveSpec` does not.
148
155
  const real = (p) => {
149
156
  try {
150
- return fs.realpathSync(p)
157
+ return fs.realpathSync.native(p)
151
158
  } catch {
152
159
  return path.resolve(p)
153
160
  }
@@ -156,8 +163,10 @@ function makeSpecHelpers({ program = 'spec-sync' } = {}) {
156
163
  const byName = new Map(here.map((s) => [s.spec, s]))
157
164
  for (const listed of liveWorktreePaths(git)) {
158
165
  const tree = real(listed)
159
- if (tree === self) continue
160
- for (const s of listSpecs(tree, config)) {
166
+ // The project folder inside this worktree — where its specs are.
167
+ const project = real(projectIn(listed, prefix))
168
+ if (project === self) continue
169
+ for (const s of listSpecs(project, config)) {
161
170
  let own = null
162
171
  try {
163
172
  own = real(resolveSpec(s.spec, primary, env.config, { searchDirs: [tree] }).worktreePath)
@@ -227,7 +236,9 @@ function makeSpecHelpers({ program = 'spec-sync' } = {}) {
227
236
  bad++
228
237
  continue
229
238
  }
230
- const r = compareStored(sent, got, config)
239
+ // Summary mode compares the block alone: the text around it is the
240
+ // team's. Right after a write a missing block IS a loss, so it reads as ''.
241
+ const r = compareStored(sent, comparableDescription(got, config) ?? '', config)
231
242
  if (r.ok) continue
232
243
  bad++
233
244
  lines.push(