@skitterbyte/skitterspec-azure-boards 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -146,7 +146,21 @@ function stateCheckFailure(config, flags) {
146
146
  // Apply ops: the kit orchestration with Azure's tracker calls. State is moved
147
147
  // by a direct `System.State` write after the create/update, and `transitionTo`
148
148
  // is idempotent when the item already sits on the target.
149
- function applyOps({ adapter, config }) {
149
+ // A spec's KIND, read off its folder prefix — the same convention the
150
+ // lifecycle skills stamp into `> **Type:**`, but greppable with no file read.
151
+ function specKindOf(snapshotDir) {
152
+ const name = path.basename(String(snapshotDir || ''))
153
+ if (name.startsWith('bug-')) return 'bug'
154
+ if (name.startsWith('hotfix-')) return 'hotfix'
155
+ return 'feature'
156
+ }
157
+
158
+ function applyOps({ adapter, config, out, kind = 'feature' }) {
159
+ // The mint type for THIS spec's kind (its folder prefix), falling back to
160
+ // the one configured type. The twin search uses the same type, so a bug
161
+ // never refuses over a feature that happens to share its title.
162
+ const mintType =
163
+ (config.azure.workItemTypeByKind && config.azure.workItemTypeByKind[kind]) || config.azure.workItemType
150
164
  const stateFor = (bucket) => {
151
165
  const name = config.states && config.states[bucket]
152
166
  if (!name) {
@@ -158,11 +172,29 @@ function applyOps({ adapter, config }) {
158
172
  if (!bucket) return
159
173
  await adapter.transitionTo(apiId(idOrIdentifier), stateFor(bucket))
160
174
  }
175
+ // Azure refuses the WHOLE patch over one bad `System.AssignedTo` value
176
+ // ("… is an unknown identity", live repro), which used to take the
177
+ // description and state down with it. A refused assignee is a cosmetic gap
178
+ // `/spec-claim` closes later; the rest of the push is not — so retry the
179
+ // same write once without the assignee and say so. Only that exact refusal
180
+ // is retried: any other error still fails the apply.
181
+ const skippingRefusedAssignee = async (input, send) => {
182
+ const assignee = 'assigneeId' in input ? input.assigneeId : undefined
183
+ try {
184
+ return await send(input)
185
+ } catch (error) {
186
+ if (assignee === undefined || !/unknown identity/i.test(String(error && error.message))) throw error
187
+ const { assigneeId, ...rest } = input
188
+ const result = await send(rest)
189
+ if (out) out.write(` !! assignee skipped: Azure refused '${assignee}' for Assigned To — the rest of the push landed\n`)
190
+ return result
191
+ }
192
+ }
161
193
  return {
162
194
  prevalidateStates: (buckets) => {
163
195
  for (const bucket of buckets) stateFor(bucket)
164
196
  },
165
- searchTwin: (title) => adapter.searchIssues({ query: title, workItemType: config.azure.workItemType }),
197
+ searchTwin: (title) => adapter.searchIssues({ query: title, workItemType: mintType }),
166
198
  twinAdvice: (twin, wanted, specName) =>
167
199
  `${twin.identifier} is already titled "${wanted}" and no spec claims it — ` +
168
200
  `stamp it onto the spec with \`spec-sync stamp ${specName} --issue ${twin.identifier}\`, ` +
@@ -171,13 +203,16 @@ function applyOps({ adapter, config }) {
171
203
  remoteEditedLine: (identifier) =>
172
204
  ` !! ${identifier}'s description was edited on Azure Boards since the last push — this replaces it`,
173
205
  mintIssue: async ({ title, issue }) => {
174
- const created = await adapter.createIssue({
175
- title,
176
- description: issue && issue.description != null ? issue.description : undefined,
177
- assigneeId: issue && issue.assignee ? issue.assignee : undefined,
178
- workItemType: config.azure.workItemType,
179
- areaPath: config.azure.areaPath || undefined,
180
- })
206
+ const created = await skippingRefusedAssignee(
207
+ {
208
+ title,
209
+ description: issue && issue.description != null ? issue.description : undefined,
210
+ assigneeId: issue && issue.assignee ? issue.assignee : undefined,
211
+ workItemType: mintType,
212
+ areaPath: config.azure.areaPath || undefined,
213
+ },
214
+ (input) => adapter.createIssue(input),
215
+ )
181
216
  await settle(created.id, issue && issue.state)
182
217
  return created
183
218
  },
@@ -187,7 +222,9 @@ function applyOps({ adapter, config }) {
187
222
  // Null is meaningful here — it is how Boards unassigns — so the key is
188
223
  // forwarded whenever the plan carries it, never truthiness-tested.
189
224
  if ('assignee' in issue) updates.assigneeId = issue.assignee ?? null
190
- if (Object.keys(updates).length) await adapter.updateIssue(apiId(existing.identifier), updates)
225
+ if (Object.keys(updates).length) {
226
+ await skippingRefusedAssignee(updates, (input) => adapter.updateIssue(apiId(existing.identifier), input))
227
+ }
191
228
  await settle(existing.identifier, issue.state)
192
229
  },
193
230
  mintSubIssue: async (parentId, sub) => {
@@ -356,11 +393,21 @@ const assignment = makeAssignmentCommands({
356
393
  usersOverMcp: 'search identities with core_get_identity_ids over MCP, or read them off the org\'s Users page',
357
394
  })
358
395
 
359
- // The state names BOTH configured types can hold, deduped — one map serves the
396
+ // The state names EVERY configured type can hold, deduped — one map serves the
360
397
  // spec item and its children, so a name only has to exist on one of them to be
361
- // writable somewhere, and validation checks against the union.
398
+ // writable somewhere, and validation checks against the union. The per-kind
399
+ // mint types are in the union too, so a `workItemTypeByKind` entry's states
400
+ // are validated before the first write, exactly like the base pair.
362
401
  async function unionStates(adapter, config) {
363
- const types = [...new Set([config.azure.workItemType, config.azure.childType].filter(Boolean))]
402
+ const types = [
403
+ ...new Set(
404
+ [
405
+ config.azure.workItemType,
406
+ config.azure.childType,
407
+ ...Object.values(config.azure.workItemTypeByKind || {}),
408
+ ].filter(Boolean),
409
+ ),
410
+ ]
364
411
  const byName = new Map()
365
412
  for (const type of types) {
366
413
  for (const s of await adapter.listIssueStates(type)) {
@@ -410,6 +457,52 @@ function specSyncPlan(dir, config, specArg, flags, out, err) {
410
457
  return 0
411
458
  }
412
459
 
460
+ // Does the project's OWN env.config.json claim the snapshot this apply just
461
+ // wrote? If not, `spec-env stage` classifies `<baseDir>/<id>.base.json` as
462
+ // another spec's and `/commit` leaves it behind — found live on a project that
463
+ // adopted this provider over a Linear-era isolation config. One line, after a
464
+ // successful apply, naming the exact keys to set.
465
+ //
466
+ // Fires only on POSITIVE signals: env.config.json present and parseable, the
467
+ // identifier stamped, and an explicit pattern set that provably misses the
468
+ // file. A key the project leaves unset is covered by the provider's runtime
469
+ // env defaults (common src/env/config.js), so absence stays silent — as does
470
+ // a project with no isolation at all (`.claude/rules/negative-checks.md`).
471
+ function companionCoverageNote(dir, config, snapshotDir, out) {
472
+ let parsed
473
+ try {
474
+ parsed = JSON.parse(fs.readFileSync(path.join(dir, 'specs', '.core', 'env.config.json'), 'utf-8'))
475
+ } catch {
476
+ return
477
+ }
478
+ if (!parsed || typeof parsed !== 'object') return
479
+ const overviewFile = (config.snapshot && config.snapshot.overviewFile) || '00-overview.md'
480
+ const identifier = specHelpers.linkedIdentifier(path.join(snapshotDir, overviewFile), config)
481
+ if (!identifier) return
482
+
483
+ const defaultPattern = `${config.sync.baseDir}/{identifier}.base.json`
484
+ const rawPatterns = parsed.spec && parsed.spec.companionPaths
485
+ const patterns = Array.isArray(rawPatterns) ? rawPatterns : [defaultPattern]
486
+ const rawField = parsed.branch && parsed.branch.identifierField
487
+ const field = typeof rawField === 'string' && rawField ? rawField : config.fields.identifier
488
+
489
+ const slug = path.basename(snapshotDir).replace(/^(feat|bug|hotfix)-/, '')
490
+ const basePath = `${config.sync.baseDir}/${identifier}.base.json`
491
+ const claimed = patterns.some((p) => {
492
+ if (typeof p !== 'string') return false
493
+ const expanded = p.split('{identifier}').join(identifier).split('{slug}').join(slug)
494
+ if (expanded !== basePath) return false
495
+ // Stage reads `{identifier}` through branch.identifierField, so a pattern
496
+ // that names the right file through the wrong field still claims nothing.
497
+ return !p.includes('{identifier}') || field === config.fields.identifier
498
+ })
499
+ if (claimed) return
500
+ out.write(
501
+ ` note: ${basePath} is not claimed by env.config.json — spec-env stage and /commit will treat it as another spec's.\n` +
502
+ ` set branch.identifierField: "${config.fields.identifier}" and add "${defaultPattern}" to spec.companionPaths\n`,
503
+ )
504
+ }
505
+
413
506
  async function specSyncApply(dir, config, specArg, flags, out, err) {
414
507
  if (!flags.plan && !flags.all) {
415
508
  out.write(`${PROGRAM} apply: pass --plan <file> (from \`plan --json\`), or --all <bucket>\n`)
@@ -442,7 +535,7 @@ async function specSyncApply(dir, config, specArg, flags, out, err) {
442
535
  snapshotDir,
443
536
  plan,
444
537
  adapter: cred.adapter,
445
- ops: applyOps({ adapter: cred.adapter, config }),
538
+ ops: applyOps({ adapter: cred.adapter, config, out, kind: specKindOf(snapshotDir) }),
446
539
  forceNew: !!flags.forceNew,
447
540
  program: PROGRAM,
448
541
  })
@@ -464,6 +557,7 @@ async function specSyncApply(dir, config, specArg, flags, out, err) {
464
557
  try {
465
558
  const applied = await applyOne(snapshotDir, r.plan)
466
559
  out.write(applied.lines.join('\n') + '\n')
560
+ companionCoverageNote(dir, config, snapshotDir, out)
467
561
  } catch (error) {
468
562
  failed++
469
563
  out.write(` !! ${error.message}\n`)
@@ -494,6 +588,7 @@ async function specSyncApply(dir, config, specArg, flags, out, err) {
494
588
  try {
495
589
  const applied = await applyOne(snapshotDir, plan)
496
590
  out.write(applied.lines.join('\n') + '\n')
591
+ companionCoverageNote(dir, config, snapshotDir, out)
497
592
  return 0
498
593
  } catch (error) {
499
594
  out.write(`${PROGRAM} apply: ${error.message}\n`)
@@ -814,7 +909,16 @@ function specSyncRef(dir, config, specArg, flags, out, err) {
814
909
  return 1
815
910
  }
816
911
  } else {
817
- const branch = currentBranch(dir)
912
+ // `currentBranch` takes a git READER bound to the checkout, not a path.
913
+ const { execFileSync } = require('node:child_process')
914
+ const git = (argv) => {
915
+ try {
916
+ return execFileSync('git', ['-C', dir, ...argv], { stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim()
917
+ } catch {
918
+ return null
919
+ }
920
+ }
921
+ const branch = currentBranch(git)
818
922
  if (!branch) {
819
923
  err.write(`${PROGRAM} ref: not on a branch\n`)
820
924
  return 1
@@ -1033,6 +1137,12 @@ async function specSyncInitConfig(dir, flags, out) {
1033
1137
  const parsed = { azure: { orgUrl: flags.orgUrl, project: flags.project } }
1034
1138
  if (flags.workItemType) parsed.azure.workItemType = flags.workItemType
1035
1139
  if (flags.childType) parsed.azure.childType = flags.childType
1140
+ if (flags.kindTypes && Object.keys(flags.kindTypes).length) parsed.azure.workItemTypeByKind = flags.kindTypes
1141
+ if (flags.bugTypes || flags.hotfixTypes) {
1142
+ parsed.intake = {}
1143
+ if (flags.bugTypes) parsed.intake.bugTypes = flags.bugTypes
1144
+ if (flags.hotfixTypes) parsed.intake.hotfixTypes = flags.hotfixTypes
1145
+ }
1036
1146
  if (flags.stateNames && Object.keys(flags.stateNames).length) {
1037
1147
  for (const bucket of Object.keys(flags.stateNames)) {
1038
1148
  if (!LIFECYCLE_BUCKETS.includes(bucket)) {
@@ -1398,6 +1508,19 @@ function parseArgs(args, sub) {
1398
1508
  '--project': { kind: 'string', name: 'project' },
1399
1509
  '--work-item-type': { kind: 'string', name: 'workItemType' },
1400
1510
  '--child-type': { kind: 'string', name: 'childType' },
1511
+ // `--kind-type bug=Bug`, repeatable — azure.workItemTypeByKind for init-config.
1512
+ '--kind-type': {
1513
+ kind: 'custom',
1514
+ handle: (flags, value) => {
1515
+ const raw = String(value || '').trim()
1516
+ const [kind, ...rest] = raw.split('=')
1517
+ if (rest.length) {
1518
+ flags.kindTypes = { ...(flags.kindTypes || {}), [kind.trim()]: rest.join('=').trim() }
1519
+ }
1520
+ },
1521
+ },
1522
+ '--bug-type': { kind: 'list', name: 'bugTypes' },
1523
+ '--hotfix-type': { kind: 'list', name: 'hotfixTypes' },
1401
1524
  '--state': {
1402
1525
  kind: 'custom',
1403
1526
  handle: (flags, value) => {
@@ -41,6 +41,12 @@ const DEFAULT_CONFIG = Object.freeze({
41
41
  workItemType: 'Issue',
42
42
  childType: 'Task',
43
43
  areaPath: '',
44
+ // The mint type per SPEC KIND (`feature`/`bug`/`hotfix`, from the spec
45
+ // folder's prefix), falling back to `workItemType`. In Agile, Scrum and
46
+ // CMMI a bug is a work item TYPE, so `/spec-bug` minting a User Story
47
+ // files it in the wrong backlog; `{ "bug": "Bug", "hotfix": "Bug" }` is
48
+ // the usual shape there. Empty means one type for everything, as before.
49
+ workItemTypeByKind: Object.freeze({}),
44
50
  }),
45
51
  // A spec is a WORK ITEM; each phase a CHILD work item under a hierarchy
46
52
  // link. `tasks` selects how the phase's checkboxes reach that child's
@@ -59,10 +65,19 @@ const DEFAULT_CONFIG = Object.freeze({
59
65
  complete: 'Done',
60
66
  cancelled: 'Done',
61
67
  }),
62
- // Intake routes an adopted work item by its TAGS (Boards has tags, not
63
- // labels): `tag` is the inbox filter, the other two route to /spec-bug and
64
- // /spec-hotfix. Empty lists route nothing.
65
- intake: Object.freeze({ tag: '', bugTags: Object.freeze(['bug']), hotfixTags: Object.freeze([]) }),
68
+ // Intake routes an adopted work item by its work item TYPE and its TAGS
69
+ // (Boards has tags, not labels): `tag` is the inbox filter, the type and tag
70
+ // lists route to /spec-bug and /spec-hotfix, and hotfix wins over bug.
71
+ // `bugTypes` defaults to Agile/Scrum/CMMI's literal `Bug` type because there
72
+ // a bug IS a type — an explicit empty list opts type routing out. Empty tag
73
+ // lists route nothing, as before.
74
+ intake: Object.freeze({
75
+ tag: '',
76
+ bugTags: Object.freeze(['bug']),
77
+ hotfixTags: Object.freeze([]),
78
+ bugTypes: Object.freeze(['Bug']),
79
+ hotfixTypes: Object.freeze([]),
80
+ }),
66
81
  snapshot: Object.freeze({ overviewFile: '00-overview.md' }),
67
82
  // The frontmatter FIELD VOCABULARY this provider stamps into spec files
68
83
  // (sync-core `src/fields.js`). No legacy keys: this provider has no pre-9.0
@@ -130,6 +145,8 @@ function defaults() {
130
145
  tag: DEFAULT_CONFIG.intake.tag,
131
146
  bugTags: [...DEFAULT_CONFIG.intake.bugTags],
132
147
  hotfixTags: [...DEFAULT_CONFIG.intake.hotfixTags],
148
+ bugTypes: [...DEFAULT_CONFIG.intake.bugTypes],
149
+ hotfixTypes: [...DEFAULT_CONFIG.intake.hotfixTypes],
133
150
  },
134
151
  snapshot: { ...DEFAULT_CONFIG.snapshot },
135
152
  fields: { ...DEFAULT_CONFIG.fields },
@@ -193,6 +210,16 @@ function mergeConfig(base, parsed) {
193
210
  assign(base.azure, parsed.azure, 'workItemType', 'string')
194
211
  assign(base.azure, parsed.azure, 'childType', 'string')
195
212
  assign(base.azure, parsed.azure, 'areaPath', 'string?')
213
+ if (isObject(parsed.azure.workItemTypeByKind)) {
214
+ // Only the kinds a spec folder can actually be — an unknown key is
215
+ // dropped rather than carried into `states` validation it can never pass.
216
+ const byKind = {}
217
+ for (const kind of ['feature', 'bug', 'hotfix']) {
218
+ const value = parsed.azure.workItemTypeByKind[kind]
219
+ if (typeof value === 'string' && value.trim()) byKind[kind] = value.trim()
220
+ }
221
+ base.azure.workItemTypeByKind = byKind
222
+ }
196
223
  // A trailing slash on the org would double up in every composed URL.
197
224
  if (base.azure.orgUrl) base.azure.orgUrl = base.azure.orgUrl.replace(/\/+$/, '')
198
225
  }
@@ -219,6 +246,8 @@ function mergeConfig(base, parsed) {
219
246
  assign(base.intake, parsed.intake, 'tag', 'string?')
220
247
  if (Array.isArray(parsed.intake.bugTags)) base.intake.bugTags = stringList(parsed.intake.bugTags)
221
248
  if (Array.isArray(parsed.intake.hotfixTags)) base.intake.hotfixTags = stringList(parsed.intake.hotfixTags)
249
+ if (Array.isArray(parsed.intake.bugTypes)) base.intake.bugTypes = stringList(parsed.intake.bugTypes)
250
+ if (Array.isArray(parsed.intake.hotfixTypes)) base.intake.hotfixTypes = stringList(parsed.intake.hotfixTypes)
222
251
  }
223
252
 
224
253
  if (isObject(parsed.snapshot)) {
@@ -89,12 +89,29 @@ function htmlToText(html) {
89
89
  .trim()
90
90
  }
91
91
 
92
+ // Azure's storage transform, observed live (phase: bug-azure-boards-adoption-
93
+ // fixes): a markdown description comes back with stray HTML specials
94
+ // entity-encoded, and TAG-SHAPED TOKENS STRIPPED ENTIRELY — `<bucket>` and
95
+ // `<name>` vanish from `specs/<bucket>/<name>/…` even inside a backtick code
96
+ // span. Both transforms are applied to BOTH sides here, so an intact mirror
97
+ // compares clean: decoding is symmetric noise on already-decoded text, and
98
+ // stripping the sent side's tokens matches the sanitiser's deletions.
99
+ //
100
+ // BLIND SPOT, named deliberately: a Boards-side edit that only adds or removes
101
+ // a tag-shaped token is invisible to the compare — the same trade the
102
+ // word-character stream already makes for punctuation, and the same safe
103
+ // direction (`.claude/rules/negative-checks.md` rule 4).
104
+ function azureCanonicalForCompare(text) {
105
+ const decoded = decodeEntities(String(text == null ? '' : text))
106
+ return markdownCanonicalForCompare(decoded.replace(/<\/?[a-zA-Z][a-zA-Z0-9-]*>/g, ''))
107
+ }
108
+
92
109
  const dialect = Object.freeze({
93
110
  canonicalize: canonicalizeMarkdown,
94
111
  // See the header: markdown is stored verbatim, so there is nothing to
95
112
  // reshape for. The hook stays so sync-core can call it unconditionally.
96
113
  flattenTables: (text) => text,
97
- canonicalForCompare: markdownCanonicalForCompare,
114
+ canonicalForCompare: azureCanonicalForCompare,
98
115
  })
99
116
 
100
- module.exports = { dialect, canonicalizeMarkdown, htmlToText, looksLikeHtml }
117
+ module.exports = { dialect, canonicalizeMarkdown, htmlToText, looksLikeHtml, decodeEntities }
@@ -7,9 +7,11 @@
7
7
  *
8
8
  * The answer is DERIVED from the PAT: a Personal Access Token belongs to a
9
9
  * person, and `connectionData` names them without any scope beyond the token
10
- * being valid (phase 1 spike). The id is the IDENTITY id (a GUID) —
11
- * `System.AssignedTo` also accepts the uniqueName/email, but the GUID is the
12
- * one value that survives a display-name change.
10
+ * being valid (phase 1 spike). The id is the uniqueName/email — the one form
11
+ * `System.AssignedTo` accepts. The identity GUID was cached here once, on the
12
+ * belief Azure took both; a live write refused it as an "unknown identity"
13
+ * (bug-azure-boards-adoption-fixes), so the GUID survives only for an
14
+ * identity with no account property at all.
13
15
  */
14
16
 
15
17
  const { resolveIdentity: kitResolveIdentity, defaultDisplayName } = require('../provider-kit/src/identity.js')