@skitterbyte/skitterspec-azure-boards 2.4.0 → 2.6.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.
@@ -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
  }
@@ -415,6 +471,8 @@ function specSyncReleased(dir, config, rangeArg, flags, out) {
415
471
  }
416
472
  const report = kit.ticketsInRange(read.commits, {
417
473
  ignorePaths: (config.release && config.release.ignorePaths) || [],
474
+ // A nested project's commits carry its folder in every path (feat-subfolder-project).
475
+ prefix: kit.projectPrefixOf(dir),
418
476
  refPattern: AZURE_REF_RE,
419
477
  foreignPatterns: foreign.patterns,
420
478
  })
@@ -765,7 +823,7 @@ function specSyncRecord(dir, config, specArg, out) {
765
823
  const snapshotDir = resolveOrExit(specArg, dir, out)
766
824
  if (!snapshotDir) return 1
767
825
  const file = recordPush({ dir, snapshotDir, identifier: specIdentifier(snapshotDir, config), config })
768
- out.write(`${PROGRAM} record: snapshot written — ${path.relative(dir, file)}\n`)
826
+ out.write(`${PROGRAM} record: snapshot written — ${path.relative(dir, file).split(path.sep).join('/')}\n`)
769
827
  return 0
770
828
  }
771
829
 
@@ -1604,11 +1662,120 @@ async function specSyncDoctor(dir, flags, out) {
1604
1662
  }
1605
1663
 
1606
1664
  // ---------------------------------------------------------------------------
1665
+ // `restate <spec> | --all <bucket> [--parents] [--apply]` — bring the states of
1666
+ // already-pushed items up to today's config, read live.
1667
+ //
1668
+ // `plan` sees a state-map change only for items whose snapshot recorded the
1669
+ // name they were sent. Everything pushed before that record existed has
1670
+ // nothing to diff against, so this reads each item's live state instead and
1671
+ // settles it through the same resend guard an apply uses: an item in a state
1672
+ // this config does not map for its type, or in a later bucket, is left and
1673
+ // named. Children only by default — a host's release CI often owns the
1674
+ // parent's states past complete — and `--parents` opts the spec item in.
1675
+ // Dry-run unless `--apply`; on `--apply` the names are recorded into each
1676
+ // spec's existing snapshot, so the next state-map change shows up in `plan`.
1677
+ async function specSyncRestate(dir, config, specArg, flags, out) {
1678
+ const cred = apiAdapterFor(config, flags)
1679
+ if (kit.resolveTransport(flags, config, cred.ok) === 'mcp') {
1680
+ out.write(`${PROGRAM} restate: transport = mcp — this reads every item's live state, so it needs the API. Set credentials and re-run.\n`)
1681
+ return 0
1682
+ }
1683
+ if (!cred.ok) {
1684
+ out.write(`${PROGRAM} restate: ${String(cred.error).split('\n')[0]} — nothing read, nothing written\n`)
1685
+ return 0
1686
+ }
1687
+ let dirs
1688
+ if (flags.all !== undefined) {
1689
+ const bucket = String(flags.all)
1690
+ if (!BUCKETS.includes(bucket)) {
1691
+ out.write(`${PROGRAM} restate --all: not a lifecycle bucket: ${bucket}\n`)
1692
+ return 1
1693
+ }
1694
+ dirs = listSpecs(dir, config)
1695
+ .filter((sp) => sp.bucket === bucket)
1696
+ .map((sp) => resolveSnapshotDir(sp.spec, dir))
1697
+ } else {
1698
+ const snapshotDir = resolveOrExit(specArg, dir, out)
1699
+ if (!snapshotDir) return 1
1700
+ dirs = [snapshotDir]
1701
+ }
1702
+
1703
+ const apply = !!flags.apply
1704
+ const overviewFile = (config.snapshot && config.snapshot.overviewFile) || '00-overview.md'
1705
+ const pulled = ownershipOf(config, 'workflowState') === 'pull'
1706
+ const totals = { moved: 0, already: 0, kept: 0 }
1707
+ for (const snapshotDir of dirs) {
1708
+ const spec = path.basename(snapshotDir)
1709
+ const identifier = specHelpers.linkedIdentifier(path.join(snapshotDir, overviewFile), config)
1710
+ if (!identifier) {
1711
+ out.write(`${PROGRAM} restate: ${spec} — not linked, skipped\n`)
1712
+ continue
1713
+ }
1714
+ out.write(`${PROGRAM} restate: ${spec} (${identifier})\n`)
1715
+ const ops = applyOps({ adapter: cred.adapter, config, out: null, kind: specKindOf(snapshotDir), snapshotDir })
1716
+ const projection = projectionOf(snapshotDir, config)
1717
+ const items = []
1718
+ if (flags.parents) {
1719
+ if (pulled) out.write(` ${identifier} left — its state is the tracker's (sync.fieldOwnership.workflowState: pull)\n`)
1720
+ else items.push({ role: 'issue', id: identifier, bucket: projection.status, type: ops.mintType })
1721
+ }
1722
+ for (const sub of projection.subIssues || []) {
1723
+ if (sub && sub.id != null) items.push({ role: 'subIssue', id: sub.id, bucket: sub.state, type: config.azure.childType })
1724
+ }
1725
+ const settled = { subIssues: {} }
1726
+ for (const item of items) {
1727
+ if (!item.bucket) continue
1728
+ const label = asIdentifier(apiId(item.id))
1729
+ const d = await ops.stateDecision(item.id, item.bucket, item.type)
1730
+ if (d.name === null) {
1731
+ out.write(` ${label} — ${item.bucket} sends no state for ${item.type}\n`)
1732
+ continue
1733
+ }
1734
+ if (d.keep) {
1735
+ totals.kept++
1736
+ out.write(ops.keptLine(item.id, d.keep))
1737
+ } else if (d.already) {
1738
+ totals.already++
1739
+ out.write(` ${label} already "${d.name}"\n`)
1740
+ } else {
1741
+ totals.moved++
1742
+ if (apply) await cred.adapter.transitionTo(apiId(item.id), d.name)
1743
+ out.write(` ${label} "${d.at}" → "${d.name}"${apply ? '' : ' (dry run)'}\n`)
1744
+ }
1745
+ if (item.role === 'issue') settled.issue = d.name
1746
+ else settled.subIssues[String(item.id)] = d.name
1747
+ }
1748
+ if (apply) recordStateNames(dir, config, snapshotDir, settled, out)
1749
+ }
1750
+ const verb = apply ? 'moved' : 'would move'
1751
+ out.write(`${PROGRAM} restate: ${totals.moved} ${verb}, ${totals.already} already there, ${totals.kept} left alone\n`)
1752
+ if (!apply && totals.moved) out.write(' dry run — nothing written. Re-run with --apply to move them.\n')
1753
+ return 0
1754
+ }
1755
+
1756
+ // Merge the names `restate` settled into the spec's EXISTING snapshot. With no
1757
+ // snapshot nothing is written: a snapshot holding only names would read to
1758
+ // `plan` as every phase unrecorded, and resend all their bodies.
1759
+ function recordStateNames(dir, config, snapshotDir, settled, out) {
1760
+ const identifier = specIdentifier(snapshotDir, config)
1761
+ const base = readBase(dir, identifier, config)
1762
+ if (!base) {
1763
+ out.write(' no snapshot to record names in — the next push records them\n')
1764
+ return
1765
+ }
1766
+ const before = base.stateNames || {}
1767
+ const names = { ...before, subIssues: { ...(before.subIssues || {}), ...settled.subIssues } }
1768
+ if (settled.issue !== undefined) names.issue = settled.issue
1769
+ writeBase(dir, identifier, config, { ...base, stateNames: names })
1770
+ }
1771
+
1607
1772
  const USAGE = `Usage: skitterspec-azure-boards spec-sync <subcommand>
1608
1773
 
1609
1774
  normalize <spec> print the local projection as JSON
1610
1775
  plan <spec> --workspace-states <f> what a push would change (dry, JSON)
1611
1776
  apply <spec> --plan <f> | --all <b> apply a plan over the API
1777
+ restate <spec> | --all <b> resend child states to today's map (dry)
1778
+ [--parents] [--apply] include the spec item; write the moves
1612
1779
  stamp <spec> --issue AB#n [--sub r=n] write returned ids into the spec
1613
1780
  record <spec> write the last-pushed snapshot
1614
1781
  status <spec> [--remote <f>] read-only drift report
@@ -1683,6 +1850,8 @@ async function specSync(rest, io = {}) {
1683
1850
  return specSyncPlan(dir, config, positional[0], flags, out, err)
1684
1851
  case 'apply':
1685
1852
  return specSyncApply(dir, config, positional[0], flags, out, err)
1853
+ case 'restate':
1854
+ return specSyncRestate(dir, config, positional[0], flags, out)
1686
1855
  case 'stamp':
1687
1856
  return specSyncStamp(dir, config, positional[0], flags, out)
1688
1857
  case 'record':
@@ -1768,6 +1937,7 @@ function parseArgs(args, sub) {
1768
1937
  '--link': { kind: 'list', name: 'links' },
1769
1938
  '--stage': { kind: 'string' },
1770
1939
  '--apply': { kind: 'boolean' },
1940
+ '--parents': { kind: 'boolean' },
1771
1941
  '--to': { kind: 'string' },
1772
1942
  '--name': { kind: 'string' },
1773
1943
  '--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,8 +217,10 @@ 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 })
216
- 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('/')}`)
217
224
  return { result, lines, lost }
218
225
  }
219
226
 
@@ -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,
@@ -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,6 +169,7 @@ 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()
@@ -150,7 +180,7 @@ function ticketsInRange(commits, options = {}) {
150
180
  let sawMergeFlag = false
151
181
  for (const commit of commits || []) {
152
182
  if (commit && commit.isMerge !== undefined) sawMergeFlag = true
153
- if (onlyIgnoredPaths(commit && commit.paths, ignorePaths)) {
183
+ if (onlyIgnoredPaths(commit && commit.paths, ignorePaths, prefix)) {
154
184
  // Not counted as unreferenced either: that number exists to surface a
155
185
  // MISSED trailer, and a paperwork commit is not a gap someone should hunt.
156
186
  ignored++
@@ -222,6 +252,7 @@ function refuseRemovedVerb(out, program, verb) {
222
252
  }
223
253
 
224
254
  module.exports = {
255
+ projectPrefixOf,
225
256
  ticketsInRange,
226
257
  refuseRemovedVerb,
227
258
  nameTickets,
@@ -21,9 +21,9 @@ 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')
26
+ const { primaryAnchor, attachProject, projectIn } = require('../../../env/project.js')
27
27
  const { readSnapshot, parseFrontmatter, lintPhases, fieldsOf, projectionOf, compareStored, comparableDescription } = require('../../sync-core')
28
28
 
29
29
  function makeSpecHelpers({ program = 'spec-sync' } = {}) {
@@ -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)