@skitterbyte/skitterspec-github 0.0.0-stage → 1.0.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 (112) hide show
  1. package/MIGRATION.md +1107 -0
  2. package/README.md +53 -2
  3. package/assets/claude-md-section.md +85 -0
  4. package/assets/commands/allow-main.md +33 -0
  5. package/assets/commands/spec-connect.md +13 -0
  6. package/assets/commands/spec-live.md +14 -0
  7. package/assets/commands/spec-remote-review.md +37 -0
  8. package/assets/commands/spec-skip.md +24 -0
  9. package/assets/core/SETUP.md +112 -0
  10. package/assets/core/env.config.json.example +56 -0
  11. package/assets/core/env.config.md +557 -0
  12. package/assets/core/gating.config.json.example +4 -0
  13. package/assets/core/gating.config.md +81 -0
  14. package/assets/core/github.config.json.example +18 -0
  15. package/assets/core/github.config.md +66 -0
  16. package/assets/hooks/main-guard.cjs +162 -0
  17. package/assets/hooks/review-gate.cjs +146 -0
  18. package/assets/review/page.html +3384 -0
  19. package/assets/rules/commit-trailers.md +103 -0
  20. package/assets/rules/negative-checks.md +69 -0
  21. package/assets/rules/offered-unblocks.md +100 -0
  22. package/assets/rules/spec-planning.md +692 -0
  23. package/assets/rules/spec-reports.md +557 -0
  24. package/assets/skills/no-spec/SKILL.md +246 -0
  25. package/assets/skills/spec/SKILL.md +718 -0
  26. package/assets/skills/spec-bug/SKILL.md +646 -0
  27. package/assets/skills/spec-cancel/SKILL.md +263 -0
  28. package/assets/skills/spec-claim/SKILL.md +122 -0
  29. package/assets/skills/spec-complete/SKILL.md +450 -0
  30. package/assets/skills/spec-diff/SKILL.md +870 -0
  31. package/assets/skills/spec-github-setup/SKILL.md +236 -0
  32. package/assets/skills/spec-hotfix/SKILL.md +668 -0
  33. package/assets/skills/spec-init/SKILL.md +178 -0
  34. package/assets/skills/spec-list/SKILL.md +172 -0
  35. package/assets/skills/spec-next/SKILL.md +685 -0
  36. package/assets/skills/spec-push/SKILL.md +307 -0
  37. package/assets/skills/spec-review/SKILL.md +258 -0
  38. package/assets/skills/spec-reviewed/SKILL.md +284 -0
  39. package/assets/skills/spec-start/SKILL.md +554 -0
  40. package/assets/skills/spec-status/SKILL.md +112 -0
  41. package/assets/skills/spec-sync/SKILL.md +226 -0
  42. package/assets/skills/spec-to-main/SKILL.md +139 -0
  43. package/bin/skitterspec-github.js +61 -0
  44. package/package.json +41 -4
  45. package/src/cli.js +5901 -0
  46. package/src/deprecate.js +138 -0
  47. package/src/env/bootstrap.js +188 -0
  48. package/src/env/building.js +143 -0
  49. package/src/env/classify.js +176 -0
  50. package/src/env/commitcmd.js +108 -0
  51. package/src/env/config.js +753 -0
  52. package/src/env/dev.js +63 -0
  53. package/src/env/hooks.js +226 -0
  54. package/src/env/hotfix.js +411 -0
  55. package/src/env/hotfixland.js +302 -0
  56. package/src/env/integrate.js +126 -0
  57. package/src/env/live.js +504 -0
  58. package/src/env/mainguard.js +299 -0
  59. package/src/env/provision.js +466 -0
  60. package/src/env/proxy.js +192 -0
  61. package/src/env/prune.js +119 -0
  62. package/src/env/registry.js +159 -0
  63. package/src/env/render.js +17 -0
  64. package/src/env/resolve.js +716 -0
  65. package/src/env/review.js +2577 -0
  66. package/src/env/reviewers/coderabbit.js +228 -0
  67. package/src/env/reviewers.js +517 -0
  68. package/src/env/serve.js +1044 -0
  69. package/src/env/supervise.js +157 -0
  70. package/src/env/teardown.js +248 -0
  71. package/src/env/trust.js +87 -0
  72. package/src/gating.js +155 -0
  73. package/src/init.js +1150 -0
  74. package/src/lines-diff.js +114 -0
  75. package/src/prompts.js +129 -0
  76. package/src/vendor/github/api.js +786 -0
  77. package/src/vendor/github/cli-sync.js +1530 -0
  78. package/src/vendor/github/commands.js +44 -0
  79. package/src/vendor/github/config.js +414 -0
  80. package/src/vendor/github/credentials.js +109 -0
  81. package/src/vendor/github/dialect.js +62 -0
  82. package/src/vendor/github/identity.js +38 -0
  83. package/src/vendor/github/mcp.js +85 -0
  84. package/src/vendor/provider-kit/index.js +41 -0
  85. package/src/vendor/provider-kit/src/adapter.js +23 -0
  86. package/src/vendor/provider-kit/src/apply.js +207 -0
  87. package/src/vendor/provider-kit/src/args.js +68 -0
  88. package/src/vendor/provider-kit/src/assignment.js +277 -0
  89. package/src/vendor/provider-kit/src/config.js +198 -0
  90. package/src/vendor/provider-kit/src/credentials.js +404 -0
  91. package/src/vendor/provider-kit/src/doctor.js +35 -0
  92. package/src/vendor/provider-kit/src/http.js +63 -0
  93. package/src/vendor/provider-kit/src/identity.js +93 -0
  94. package/src/vendor/provider-kit/src/md-compare.js +39 -0
  95. package/src/vendor/provider-kit/src/md-tables.js +94 -0
  96. package/src/vendor/provider-kit/src/prompt.js +50 -0
  97. package/src/vendor/provider-kit/src/released.js +269 -0
  98. package/src/vendor/provider-kit/src/releases.js +380 -0
  99. package/src/vendor/provider-kit/src/specs.js +166 -0
  100. package/src/vendor/provider-kit/src/transport.js +22 -0
  101. package/src/vendor/sync-core/index.js +93 -0
  102. package/src/vendor/sync-core/src/base.js +81 -0
  103. package/src/vendor/sync-core/src/compare.js +338 -0
  104. package/src/vendor/sync-core/src/dialect.js +51 -0
  105. package/src/vendor/sync-core/src/fields.js +36 -0
  106. package/src/vendor/sync-core/src/legacy.js +100 -0
  107. package/src/vendor/sync-core/src/normalize.js +998 -0
  108. package/src/vendor/sync-core/src/push.js +85 -0
  109. package/src/vendor/sync-core/src/retarget.js +278 -0
  110. package/src/vendor/sync-core/src/task-block.js +308 -0
  111. package/src/vendor/sync-core/src/verify.js +67 -0
  112. package/src/vendor/sync-core/src/write.js +191 -0
@@ -0,0 +1,1530 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * `skitterspec-github spec-sync <sub>` — the GitHub provider's engine CLI.
5
+ *
6
+ * Built on the provider kit: spec resolution, transport precedence, the flag
7
+ * parser with its unknown-flag refusal, the credentials prompts and the apply
8
+ * orchestration are all shared machinery; what this file owns is GitHub's —
9
+ * state applied as a board Status option plus the issue's own open/closed, the
10
+ * `#N` identifier shape, the config file it names in refusals, and which
11
+ * operations the MCP transport cannot express.
12
+ *
13
+ * Exit-code semantics mirror the other providers' table: `ref` prints the
14
+ * bare identifier on stdout ONLY on success (so `$(spec-sync ref)` cannot
15
+ * splice an error into a commit body); `verify` warns and never fails on
16
+ * losses; `preserve` exits 0 on every cannot-tell; dry-runs are the default
17
+ * wherever a write exists; an unknown `--flag` refuses before anything runs.
18
+ */
19
+
20
+ const fs = require('node:fs')
21
+ const path = require('node:path')
22
+
23
+ const {
24
+ push,
25
+ recordPush,
26
+ readBase,
27
+ isEmptyPlan,
28
+ validateStates,
29
+ stateSuggestions,
30
+ remoteWorkflowState,
31
+ remoteDescriptionEdited,
32
+ writeFrontmatter,
33
+ stampSubIssueId,
34
+ listPhaseFiles,
35
+ normalizeLocal,
36
+ } = require('../sync-core')
37
+ const kit = require('../provider-kit')
38
+ const { GITHUB_REF_RE, IDENTIFIER_RE } = require('../provider-kit/src/released.js')
39
+ const { BUCKETS, findSpecFolder, currentBranch } = require('../../env/resolve.js')
40
+
41
+ const {
42
+ loadGithubConfig,
43
+ mergeConfig,
44
+ defaults,
45
+ closeReasonForBucket,
46
+ markersFor,
47
+ CONFIG_FILE,
48
+ LIFECYCLE_BUCKETS,
49
+ } = require('./config.js')
50
+ const {
51
+ resolveCredential,
52
+ writeCredential,
53
+ removeCredential,
54
+ storePath,
55
+ storeMode,
56
+ fingerprint,
57
+ scopeOf,
58
+ writeUser,
59
+ removeUser,
60
+ } = require('./credentials.js')
61
+ const { makeApiAdapter } = require('./api.js')
62
+ const { APPLY_OVER_MCP } = require('./mcp.js')
63
+ const { resolveIdentity, displayNameOf } = require('./identity.js')
64
+ const { makeAssignmentCommands } = require('../provider-kit/src/assignment.js')
65
+ const { makeReleaseCommands } = require('../provider-kit/src/releases.js')
66
+
67
+ const PROGRAM = 'spec-sync'
68
+ const BIN = 'skitterspec-github'
69
+ const specHelpers = kit.makeSpecHelpers({ program: PROGRAM })
70
+ const { resolveSnapshotDir, specIdentifier, listSpecs, resolveOrExit, warnToErr, verifyLines } = specHelpers
71
+
72
+ // An issue reference as typed: `#123` or `123`. Stamped as `#123`.
73
+ const ID_RE = /^#?\d+$/
74
+ const asIdentifier = (ref) => `#${String(ref).replace(/^#/, '')}`
75
+
76
+ const repoLabel = (config) => `${config.github.owner}/${config.github.repo}`
77
+ const issueUrl = (config, identifier) =>
78
+ config.github.owner && config.github.repo
79
+ ? `https://github.com/${config.github.owner}/${config.github.repo}/issues/${String(identifier).replace(/^#/, '')}`
80
+ : null
81
+
82
+ // What a command needs before it can talk to GitHub at all. One message, so
83
+ // every command names the same three keys the same way.
84
+ function configGap(config, { board = true } = {}) {
85
+ const g = config.github || {}
86
+ const missing = []
87
+ if (!g.owner) missing.push('github.owner')
88
+ if (!g.repo) missing.push('github.repo')
89
+ if (board && !g.project) missing.push('github.project')
90
+ return missing.length ? `${missing.join(', ')} not set — fix ${CONFIG_FILE}` : null
91
+ }
92
+
93
+ // ---------------------------------------------------------------------------
94
+ // The state gate. GitHub refuses an unknown Status option only when the
95
+ // field write is attempted — after the body write has already landed — so a
96
+ // half-typed `states` table would mirror the prose and strand the state move.
97
+ // Same discipline as the other providers: validate against the board's real
98
+ // options first.
99
+ function stateCheckFailure(config, flags) {
100
+ if (flags.skipStateCheck) return null
101
+ if (!flags.workspaceStates) {
102
+ return [
103
+ `${PROGRAM} plan: refusing — the configured board states have not been validated`,
104
+ " pass --workspace-states <file> (a JSON array of the board's Status",
105
+ ' options — `spec-sync states --json` prints exactly that), or',
106
+ ' --skip-state-check to push anyway.',
107
+ ' An unknown Status option is refused only at the field write, after the',
108
+ ' body write has landed: the push would half-apply.',
109
+ ]
110
+ }
111
+ if (!fs.existsSync(flags.workspaceStates)) {
112
+ return [`${PROGRAM} plan: refusing — no such --workspace-states file: ${flags.workspaceStates}`]
113
+ }
114
+ let names
115
+ try {
116
+ names = JSON.parse(fs.readFileSync(flags.workspaceStates, 'utf-8'))
117
+ } catch (error) {
118
+ return [`${PROGRAM} plan: refusing — --workspace-states is not valid JSON: ${error.message}`]
119
+ }
120
+ const list = Array.isArray(names) ? names : []
121
+ const missing = validateStates(config, list)
122
+ if (missing.length) {
123
+ const lines = [`${PROGRAM} plan: refusing — configured state name(s) not on the board`, '']
124
+ for (const { label, configured, suggestion } of stateSuggestions(config, list)) {
125
+ lines.push(` ${label}: "${configured}" is not a Status option on the board`)
126
+ if (suggestion) lines.push(` use "${suggestion}" instead`)
127
+ }
128
+ lines.push('', ` available: ${list.join(', ') || '(the board reported none)'}`, ` Fix ${CONFIG_FILE} -> states.`)
129
+ return lines
130
+ }
131
+ return null
132
+ }
133
+
134
+ // ---------------------------------------------------------------------------
135
+ // Apply ops: the kit orchestration with GitHub's calls. State is applied
136
+ // AFTER the create/update, in two writes: the board Status option, then the
137
+ // issue's own open/closed where the bucket calls for it. Both are idempotent —
138
+ // a Status already set is left alone, and the issue is only opened or closed
139
+ // when it is not already.
140
+ function applyOps({ adapter, config }) {
141
+ const statusFor = (bucket) => {
142
+ const name = config.states && config.states[bucket]
143
+ if (!name) {
144
+ throw new Error(`no state configured for the "${bucket}" bucket — fix ${CONFIG_FILE} -> states`)
145
+ }
146
+ return name
147
+ }
148
+ const settle = async (issueOrRef, bucket) => {
149
+ if (!bucket) return
150
+ const issue = issueOrRef && issueOrRef.nodeId ? issueOrRef : await adapter.readIssue(issueOrRef)
151
+ if (!issue) throw new Error(`no GitHub issue found for ${issueOrRef}`)
152
+ const changed = await adapter.setStatus(issue, statusFor(bucket))
153
+ const reason = closeReasonForBucket(bucket)
154
+ const wantOpen = !reason
155
+ if (issue.open === wantOpen) return
156
+ // A BOARD MAY HAVE GOT THERE FIRST. Projects ship an "auto-close issue"
157
+ // workflow that closes an issue the moment its Status becomes Done, so the
158
+ // Status write above can itself close it — and GitHub then refuses our close
159
+ // as "closed by another request". Re-read after a Status change and act only
160
+ // on what is still wrong: the positive signal is the issue's own state.
161
+ let now = issue
162
+ if (changed && changed.changed !== false) now = (await adapter.readIssue(issue.id)) || issue
163
+ if (now.open === wantOpen) return
164
+ try {
165
+ await adapter.setIssueOpen(issue.id, { open: wantOpen, reason })
166
+ } catch (error) {
167
+ // The same race, lost later: re-read once, and accept the refusal only
168
+ // when the issue is now where we wanted it. Anything else is real.
169
+ const after = await adapter.readIssue(issue.id).catch(() => null)
170
+ if (!after || after.open !== wantOpen) throw error
171
+ }
172
+ }
173
+ // A create that lands and a settle that then fails leaves a real issue the
174
+ // kit has not stamped — it records a create only once the op returns. Name it
175
+ // on the error, as the adapter does for a failed sub-issue link, so the
176
+ // refusal says what to stamp before anyone re-runs and mints a twin.
177
+ const withOrphan = async (created, fn) => {
178
+ try {
179
+ await fn()
180
+ } catch (error) {
181
+ if (error && typeof error === 'object' && !error.orphan) error.orphan = created
182
+ throw error
183
+ }
184
+ }
185
+ const spec = markersFor(config, 'spec')
186
+ const phase = markersFor(config, 'phase')
187
+ return {
188
+ prevalidateStates: (buckets) => {
189
+ for (const bucket of buckets) statusFor(bucket)
190
+ },
191
+ searchTwin: (title) => adapter.searchIssues({ query: title }),
192
+ twinAdvice: (twin, wanted, specName) =>
193
+ `${twin.identifier} is already titled "${wanted}" and no spec claims it — ` +
194
+ `stamp it onto the spec with \`spec-sync stamp ${specName} --issue ${twin.identifier}\`, ` +
195
+ 'or pass --force-new to create a second',
196
+ missingIssueMessage: (identifier) => `no GitHub issue found for ${identifier} in ${repoLabel(config)}`,
197
+ remoteEditedLine: (identifier) =>
198
+ ` !! ${identifier}'s body was edited on GitHub since the last push — this replaces it`,
199
+ mintIssue: async ({ title, issue }) => {
200
+ const created = await adapter.createIssue({
201
+ title,
202
+ description: issue && issue.description != null ? issue.description : undefined,
203
+ assigneeId: issue && issue.assignee ? issue.assignee : undefined,
204
+ labels: spec.labels,
205
+ type: spec.type,
206
+ })
207
+ await withOrphan(created, () => settle(created.id, issue && issue.state))
208
+ return created
209
+ },
210
+ updateIssue: async (existing, issue) => {
211
+ const updates = {}
212
+ if (issue.description !== undefined) updates.description = issue.description
213
+ // Null is meaningful here — it is how an issue is unassigned — so the
214
+ // key is forwarded whenever the plan carries it, never truthiness-tested.
215
+ if ('assignee' in issue) updates.assigneeId = issue.assignee ?? null
216
+ // An ADOPTED issue was filed by a person and carries none of our markers,
217
+ // and `list` finds specs by the spec label. A PATCH replaces the whole
218
+ // label set, so the issue's own labels go along — and only when they were
219
+ // read: an unknown set is left alone rather than overwritten.
220
+ if (Array.isArray(existing.labels)) {
221
+ const have = new Set(existing.labels.map((l) => String(l).toLowerCase()))
222
+ const missing = spec.labels.filter((l) => !have.has(String(l).toLowerCase()))
223
+ if (missing.length) updates.labels = [...existing.labels, ...missing]
224
+ }
225
+ if (Object.keys(updates).length) await adapter.updateIssue(existing.id, updates)
226
+ await settle(existing, issue.state)
227
+ },
228
+ mintSubIssue: async (parentId, sub) => {
229
+ const created = await adapter.createSubIssue(parentId, {
230
+ title: sub.name,
231
+ description: sub.goal != null ? sub.goal : undefined,
232
+ labels: phase.labels,
233
+ type: phase.type,
234
+ })
235
+ await withOrphan(created, () => settle(created.id, sub.state))
236
+ return created
237
+ },
238
+ updateSubIssue: async (sub) => {
239
+ const updates = {}
240
+ if (sub.name != null) updates.title = sub.name
241
+ if (sub.goal != null) updates.description = sub.goal
242
+ if (Object.keys(updates).length) await adapter.updateIssue(sub.id, updates)
243
+ await settle(sub.id, sub.state)
244
+ },
245
+ }
246
+ }
247
+
248
+ function adapterOptions(config) {
249
+ const g = config.github || {}
250
+ const deployedField = (config.releases && config.releases.deployedField) || 'Deployed'
251
+ return { owner: g.owner, repo: g.repo, project: g.project, statusField: g.statusField, deployedField }
252
+ }
253
+
254
+ function apiAdapterFor(config, flags) {
255
+ if (flags.adapter) return { ok: true, adapter: flags.adapter }
256
+ const cred = resolveCredential(config, flags.env || process.env)
257
+ if (!cred.ok) return { ok: false, error: cred.error }
258
+ const gap = configGap(config, { board: false })
259
+ if (gap) return { ok: false, error: gap }
260
+ return { ok: true, adapter: makeApiAdapter({ ...adapterOptions(config), token: cred.token, fetch: flags.fetch }) }
261
+ }
262
+
263
+ // ---------------------------------------------------------------------------
264
+ // Assignment: `assign`, `whoami` and `users` are the kit's
265
+ // (`provider-kit/src/assignment.js`); this is GitHub's binding. The id is a
266
+ // LOGIN, the store scope the owner, and the user list the repo's assignees —
267
+ // the only people GitHub will let an issue be assigned to.
268
+ const assignment = makeAssignmentCommands({
269
+ tracker: 'GitHub',
270
+ configFile: CONFIG_FILE,
271
+ bin: BIN,
272
+ idHint: '<login>',
273
+ credentialNoun: 'token',
274
+ scopeJsonKey: 'owner',
275
+ scopeLineLabel: 'owner:',
276
+ scopeOf: (config) => {
277
+ const id = scopeOf(config)
278
+ return {
279
+ id,
280
+ label: id,
281
+ missing: `spec-sync whoami: no github.owner in ${CONFIG_FILE}.\n Identity is stored per owner — run \`spec-sync init-config\` first.`,
282
+ }
283
+ },
284
+ storePath: (env) => storePath(env),
285
+ writeUser: (file, scope, user, deps) => writeUser(file, scope, user, deps),
286
+ removeUser: (file, scope, deps) => removeUser(file, scope, deps),
287
+ resolveIdentity: (config, env, deps) => resolveIdentity(config, env, deps),
288
+ resolveCredential: (config, env) => resolveCredential(config, env),
289
+ makeAdapter: (config, cred, flags) => makeApiAdapter({ ...adapterOptions(config), token: cred.token, fetch: flags.fetch }),
290
+ displayNameOf: (u) => displayNameOf(u),
291
+ usersOverMcp: 'list the repo\'s assignees over MCP, or read them off the repo\'s settings',
292
+ // GitHub refuses to assign anyone who is not a collaborator, and refuses it
293
+ // at PUSH time, after the stamp has been committed. Checked here instead —
294
+ // but only on a positive answer: no token, or a check that could not run, is
295
+ // a cannot-tell and the stamp proceeds exactly as before (negative-checks).
296
+ validateAssignee: async (config, login, flags) => {
297
+ const cred = apiAdapterFor(config, flags)
298
+ if (!cred.ok || !cred.adapter.checkAssignable) return null
299
+ try {
300
+ const ok = await cred.adapter.checkAssignable(login)
301
+ return ok === false
302
+ ? `${login} cannot be assigned in ${repoLabel(config)} — only collaborators can (\`spec-sync users\` lists them)`
303
+ : null
304
+ } catch {
305
+ return null
306
+ }
307
+ },
308
+ })
309
+
310
+ // ---------------------------------------------------------------------------
311
+ // Subcommands. Each returns an exit code and writes only to the streams it is
312
+ // handed, so every branch is testable offline.
313
+
314
+ function specSyncNormalize(dir, config, specArg, out, err) {
315
+ const snapshotDir = resolveOrExit(specArg, dir, out)
316
+ if (!snapshotDir) return 1
317
+ warnToErr(snapshotDir, config, err)
318
+ out.write(JSON.stringify(normalizeLocal(snapshotDir, config), null, 2) + '\n')
319
+ return 0
320
+ }
321
+
322
+ function specSyncPlan(dir, config, specArg, flags, out, err) {
323
+ const snapshotDir = resolveOrExit(specArg, dir, out)
324
+ if (!snapshotDir) return 1
325
+ const refused = stateCheckFailure(config, flags)
326
+ if (refused) {
327
+ out.write(refused.join('\n') + '\n')
328
+ return 1
329
+ }
330
+ warnToErr(snapshotDir, config, err)
331
+ const identifier = specIdentifier(snapshotDir, config)
332
+ const r = push({ dir, snapshotDir, identifier, config })
333
+ if (flags.json || !out.isTTY) {
334
+ out.write(JSON.stringify(r.plan, null, 2) + '\n')
335
+ return 0
336
+ }
337
+ if (r.empty) {
338
+ out.write(`${PROGRAM} plan: ${identifier} — nothing to push\n`)
339
+ return 0
340
+ }
341
+ const c = r.plan.subIssues.create.length
342
+ const u = r.plan.subIssues.update.length
343
+ out.write(
344
+ `${PROGRAM} plan: ${identifier} — ${r.plan.issue ? 'issue update, ' : ''}${c} sub-issue create(s), ${u} update(s)\n` +
345
+ ' apply it: spec-sync plan <spec> --json > plan.json && spec-sync apply <spec> --plan plan.json\n',
346
+ )
347
+ return 0
348
+ }
349
+
350
+ async function specSyncApply(dir, config, specArg, flags, out, err) {
351
+ if (!flags.plan && !flags.all) {
352
+ out.write(`${PROGRAM} apply: pass --plan <file> (from \`plan --json\`), or --all <bucket>\n`)
353
+ return 1
354
+ }
355
+ const cred = apiAdapterFor(config, flags)
356
+ const transport = kit.resolveTransport(flags, config, cred.ok)
357
+ if (transport === 'mcp') {
358
+ if (flags.all) {
359
+ out.write(`${PROGRAM} apply --all: the MCP transport cannot bulk-apply — set a token and re-run\n`)
360
+ return 1
361
+ }
362
+ out.write(`${PROGRAM} apply: transport = mcp — nothing written by the engine.\n ${APPLY_OVER_MCP}\n`)
363
+ return 0
364
+ }
365
+ if (!cred.ok) {
366
+ out.write(`${PROGRAM} apply: ${cred.error}\n`)
367
+ return 1
368
+ }
369
+ const gap = flags.adapter ? null : configGap(config)
370
+ if (gap) {
371
+ out.write(`${PROGRAM} apply: ${gap}\n`)
372
+ return 1
373
+ }
374
+
375
+ const applyOne = (snapshotDir, plan) =>
376
+ kit.applySpecPlan({
377
+ dir,
378
+ config,
379
+ snapshotDir,
380
+ plan,
381
+ adapter: cred.adapter,
382
+ ops: applyOps({ adapter: cred.adapter, config }),
383
+ forceNew: !!flags.forceNew,
384
+ program: PROGRAM,
385
+ })
386
+
387
+ // A sub-issue created but not linkable is a real issue nobody stamped — the
388
+ // adapter hands it back on the refusal, and it is named alongside the
389
+ // orchestration's own orphans.
390
+ const orphansOf = (error) => [
391
+ ...((error && error.orphans) || []),
392
+ ...(error && error.orphan && error.orphan.identifier ? [error.orphan.identifier] : []),
393
+ ]
394
+
395
+ if (flags.all) {
396
+ const bucket = String(flags.all)
397
+ if (!BUCKETS.includes(bucket)) {
398
+ out.write(`${PROGRAM} apply --all: not a lifecycle bucket: ${bucket}\n`)
399
+ return 1
400
+ }
401
+ const specs = listSpecs(dir, config).filter((s) => s.bucket === bucket)
402
+ let failed = 0
403
+ for (const spec of specs) {
404
+ const snapshotDir = resolveSnapshotDir(spec.spec, dir)
405
+ const identifier = specIdentifier(snapshotDir, config)
406
+ const r = push({ dir, snapshotDir, identifier, config })
407
+ if (r.empty) continue
408
+ out.write(`${PROGRAM} apply: ${spec.spec}\n`)
409
+ try {
410
+ const applied = await applyOne(snapshotDir, r.plan)
411
+ out.write(applied.lines.join('\n') + '\n')
412
+ } catch (error) {
413
+ failed++
414
+ out.write(` !! ${error.message}\n`)
415
+ const orphans = orphansOf(error)
416
+ if (orphans.length) out.write(` created but not stamped: ${orphans.join(', ')} — stamp before re-running\n`)
417
+ }
418
+ }
419
+ out.write(`${PROGRAM} apply --all ${bucket}: ${specs.length} spec(s), ${failed} failed\n`)
420
+ return failed ? 1 : 0
421
+ }
422
+
423
+ const snapshotDir = resolveOrExit(specArg, dir, out)
424
+ if (!snapshotDir) return 1
425
+ let plan
426
+ try {
427
+ plan = JSON.parse(fs.readFileSync(flags.plan, 'utf-8'))
428
+ } catch (error) {
429
+ out.write(`${PROGRAM} apply: cannot read --plan: ${error.message}\n`)
430
+ return 1
431
+ }
432
+ if (isEmptyPlan(plan)) {
433
+ out.write(`${PROGRAM} apply: empty plan — nothing to do\n`)
434
+ return 0
435
+ }
436
+ out.write(`${PROGRAM} apply: transport = api\n`)
437
+ warnToErr(snapshotDir, config, err)
438
+ try {
439
+ const applied = await applyOne(snapshotDir, plan)
440
+ out.write(applied.lines.join('\n') + '\n')
441
+ return 0
442
+ } catch (error) {
443
+ out.write(`${PROGRAM} apply: ${error.message}\n`)
444
+ const orphans = orphansOf(error)
445
+ if (orphans.length) {
446
+ out.write(
447
+ ` created but not stamped: ${orphans.join(', ')} — stamp them with \`spec-sync stamp\` before re-running,\n` +
448
+ ' or the next apply mints duplicates\n',
449
+ )
450
+ }
451
+ return 1
452
+ }
453
+ }
454
+
455
+ async function specSyncStamp(dir, config, specArg, flags, out) {
456
+ const snapshotDir = resolveOrExit(specArg, dir, out)
457
+ if (!snapshotDir) return 1
458
+ // Validate EVERYTHING before writing ANYTHING: a half-stamped spec mints
459
+ // duplicates on the next push, which is worse than a refused stamp.
460
+ const problems = []
461
+ if (!flags.issue) problems.push('--issue <#n> is required')
462
+ else if (!ID_RE.test(flags.issue)) problems.push(`--issue ${flags.issue} is not an issue number (#123)`)
463
+ if (flags.url && !/^https?:\/\//i.test(flags.url)) problems.push(`--url must be http(s): ${flags.url}`)
464
+ const subs = []
465
+ for (const pair of flags.subs || []) {
466
+ const [ref, ...rest] = String(pair).split('=')
467
+ const id = rest.join('=').trim()
468
+ const file = listPhaseFiles(snapshotDir).find(
469
+ (f) => f.replace(/\.md$/, '') === String(ref).trim().replace(/\.md$/, ''),
470
+ )
471
+ if (!file) problems.push(`--sub ${pair}: no phase file named ${ref}`)
472
+ else if (!ID_RE.test(id)) problems.push(`--sub ${pair}: ${id || '(empty)'} is not an issue number`)
473
+ else subs.push({ file, id: asIdentifier(id) })
474
+ }
475
+ const issue = flags.issue && ID_RE.test(flags.issue) ? asIdentifier(flags.issue) : null
476
+ // The live half of the same promise: when a token resolves, a number GitHub
477
+ // positively answers "no such issue" to is refused — a wrong stamp's whole
478
+ // failure mode is a duplicate minted LATER, far from the typo. Offline use
479
+ // stays first-class: no token, or a GitHub that cannot be reached, is a
480
+ // cannot-tell and stamps exactly as before (negative-checks rule 4).
481
+ // WHAT WOULD FOOL THIS: GitHub reads a private repo the token cannot see as
482
+ // "no such issue" — so the refusal says to check the repo as well as the number.
483
+ let verified = false
484
+ if (!problems.length) {
485
+ const cred = apiAdapterFor(config, flags)
486
+ if (cred.ok) {
487
+ try {
488
+ const ids = [[issue, '--issue'], ...subs.map((sub) => [sub.id, `--sub ${path.basename(sub.file)}`])]
489
+ for (const [id, label] of ids) {
490
+ if ((await cred.adapter.readIssue(id)) == null) {
491
+ problems.push(`${label} ${id}: ${repoLabel(config)} has no such issue this token can see — check the number and the repo`)
492
+ }
493
+ }
494
+ verified = !problems.length
495
+ } catch {
496
+ out.write(`${PROGRAM} stamp: could not check the number(s) against GitHub — stamping anyway\n`)
497
+ }
498
+ }
499
+ }
500
+ if (problems.length) {
501
+ out.write([`${PROGRAM} stamp: refusing — nothing written`, ...problems.map((p) => ` ${p}`)].join('\n') + '\n')
502
+ return 1
503
+ }
504
+ const fields = config.fields
505
+ const url = flags.url || issueUrl(config, issue)
506
+ writeFrontmatter(snapshotDir, config, {
507
+ [fields.identifier]: issue,
508
+ ...(url ? { [fields.url]: url } : {}),
509
+ })
510
+ for (const { file, id } of subs) stampSubIssueId(snapshotDir, file, id, config)
511
+ out.write(
512
+ `${PROGRAM} stamp: ${issue} stamped onto ${path.basename(snapshotDir)} (+${subs.length} sub-issue stamp(s))` +
513
+ `${verified ? ' — verified against GitHub' : ''}\n`,
514
+ )
515
+ return 0
516
+ }
517
+
518
+ function specSyncRecord(dir, config, specArg, out) {
519
+ const snapshotDir = resolveOrExit(specArg, dir, out)
520
+ if (!snapshotDir) return 1
521
+ const file = recordPush({ dir, snapshotDir, identifier: specIdentifier(snapshotDir, config), config })
522
+ out.write(`${PROGRAM} record: snapshot written — ${path.relative(dir, file)}\n`)
523
+ return 0
524
+ }
525
+
526
+ function specSyncStatus(dir, config, specArg, flags, out, err) {
527
+ const snapshotDir = resolveOrExit(specArg, dir, out)
528
+ if (!snapshotDir) return 1
529
+ const identifier = specIdentifier(snapshotDir, config)
530
+ const lines = [`${PROGRAM} status: ${identifier}`]
531
+ warnToErr(snapshotDir, config, err)
532
+
533
+ if (flags.workspaceStates) {
534
+ const refused = stateCheckFailure(config, { workspaceStates: flags.workspaceStates })
535
+ if (refused) {
536
+ out.write(refused.join('\n') + '\n')
537
+ return 1
538
+ }
539
+ lines.push(' states: every configured state is a Status option on the board')
540
+ }
541
+
542
+ const r = push({ dir, snapshotDir, identifier, config })
543
+ if (r.empty) lines.push(' push: in sync — nothing would push')
544
+ else {
545
+ const c = r.plan.subIssues.create.length
546
+ const u = r.plan.subIssues.update.length
547
+ lines.push(` push: pending — ${r.plan.issue ? 'issue update, ' : ''}${c} sub-issue create(s), ${u} update(s)`)
548
+ }
549
+
550
+ if (flags.remote) {
551
+ let remote
552
+ try {
553
+ remote = JSON.parse(fs.readFileSync(flags.remote, 'utf-8'))
554
+ } catch (error) {
555
+ out.write(`${PROGRAM} status: cannot read --remote: ${error.message}\n`)
556
+ return 1
557
+ }
558
+ const bucket = remoteWorkflowState(remote, config)
559
+ const local = r.projection.status
560
+ if (bucket && local && bucket !== local) {
561
+ lines.push(` drift: the board says "${bucket}", the repo says "${local}" (repo wins on next push)`)
562
+ } else if (bucket) {
563
+ lines.push(' drift: none — the board agrees with the repo')
564
+ }
565
+ // SILENT ON EVERYTHING EXCEPT A POSITIVE ANSWER: `remoteDescriptionEdited`
566
+ // returns null for every cannot-tell, and none of those is evidence.
567
+ if (remoteDescriptionEdited(readBase(dir, identifier, config), remote, config) === true) {
568
+ lines.push(
569
+ ` drift: ${identifier}'s body was edited on GitHub since the last push`,
570
+ ' (repo wins on next push — read it before pushing)',
571
+ )
572
+ }
573
+ }
574
+ out.write(lines.join('\n') + '\n')
575
+ return 0
576
+ }
577
+
578
+ function specSyncVerify(dir, config, specArg, flags, out) {
579
+ const snapshotDir = resolveOrExit(specArg, dir, out)
580
+ if (!snapshotDir) return 1
581
+ if (!flags.stored) {
582
+ out.write(`${PROGRAM} verify: pass --stored <file> ({ issue, subIssues: { ref: text } })\n`)
583
+ return 1
584
+ }
585
+ let stored
586
+ try {
587
+ stored = JSON.parse(fs.readFileSync(flags.stored, 'utf-8'))
588
+ } catch (error) {
589
+ out.write(`${PROGRAM} verify: cannot read --stored: ${error.message}\n`)
590
+ return 1
591
+ }
592
+ // A snapshot passed as --stored compares hashes against text and reports
593
+ // total loss on a healthy mirror — refuse the shape explicitly.
594
+ if (stored && stored.issueFields) {
595
+ out.write(
596
+ `${PROGRAM} verify: that looks like a .base.json snapshot, not a read-back —\n` +
597
+ ' pass the BODIES GitHub returned ({ issue, subIssues: { ref: text } })\n',
598
+ )
599
+ return 1
600
+ }
601
+ out.write(verifyLines(snapshotDir, config, stored || {}, specIdentifier(snapshotDir, config)).join('\n') + '\n')
602
+ // Warn, never fail: losses are for a human to read, and failing the command
603
+ // would fail the push that just succeeded.
604
+ return 0
605
+ }
606
+
607
+ function specSyncLinked(dir, config, flags, out) {
608
+ const specs = listSpecs(dir, config)
609
+ if (flags.json) {
610
+ out.write(JSON.stringify(specs, null, 2) + '\n')
611
+ return 0
612
+ }
613
+ if (!specs.length) {
614
+ out.write(`${PROGRAM} linked: no specs found under specs/\n`)
615
+ return 0
616
+ }
617
+ const lines = [`${PROGRAM} linked:`]
618
+ for (const s of specs) lines.push(` ${s.identifier || '—'}\t${s.spec} (${s.bucket})`)
619
+ lines.push(` ${specs.filter((s) => s.identifier).length}/${specs.length} linked`)
620
+ out.write(lines.join('\n') + '\n')
621
+ return 0
622
+ }
623
+
624
+ async function specSyncStates(dir, config, flags, out) {
625
+ const cred = apiAdapterFor(config, flags)
626
+ const transport = kit.resolveTransport(flags, config, cred.ok)
627
+ if (transport === 'mcp') {
628
+ out.write(
629
+ `${PROGRAM} states: transport = mcp — read the board's "${config.github.statusField}" field\n` +
630
+ ' options with projects_get / projects_list and write the names to a JSON\n' +
631
+ ' array file for --workspace-states.\n',
632
+ )
633
+ return 0
634
+ }
635
+ if (!cred.ok) {
636
+ out.write(`${PROGRAM} states: ${cred.error}\n`)
637
+ return 1
638
+ }
639
+ const gap = flags.adapter ? null : configGap(config)
640
+ if (gap) {
641
+ out.write(`${PROGRAM} states: ${gap}\n`)
642
+ return 1
643
+ }
644
+ let states
645
+ try {
646
+ states = await cred.adapter.listIssueStates()
647
+ } catch (error) {
648
+ out.write(`${PROGRAM} states: ${error.message}\n`)
649
+ return 1
650
+ }
651
+ const names = states.map((s) => s.name)
652
+ if (flags.json) {
653
+ // The bare array --workspace-states consumes.
654
+ out.write(JSON.stringify(names, null, 2) + '\n')
655
+ return 0
656
+ }
657
+ const lines = [
658
+ `${PROGRAM} states: ${repoLabel(config)} · board ${config.github.project} · "${config.github.statusField}"`,
659
+ ...names.map((n) => ` ${n}`),
660
+ ]
661
+ // The bucket map — the one visual answer to "is skitterspec wired to what
662
+ // this board actually has?". Every bucket gets a row and a verdict, a
663
+ // missing option names its closest match, and the issue's own state is
664
+ // shown beside it so "Done" and "closed" are visibly the same move.
665
+ const suggestions = new Map(stateSuggestions(config, names).map((x) => [x.bucket, x.suggestion]))
666
+ const buckets = Object.entries(config.states)
667
+ const bw = Math.max(...buckets.map(([b]) => b.length))
668
+ const nw = Math.max(...buckets.map(([, n]) => String(n).length))
669
+ lines.push('', ' map: lifecycle bucket -> board Status · issue')
670
+ const missing = []
671
+ for (const [bucket, name] of buckets) {
672
+ const ok = names.includes(name)
673
+ if (!ok) missing.push(bucket)
674
+ const reason = closeReasonForBucket(bucket)
675
+ const issue = reason ? `closed (${reason})` : 'open'
676
+ const tail = ok
677
+ ? `ok · ${issue}`
678
+ : `MISSING from the board${suggestions.get(bucket) ? ` — closest: "${suggestions.get(bucket)}"` : ''}`
679
+ lines.push(` ${bucket.padEnd(bw)} -> ${String(name).padEnd(nw)} ${tail}`)
680
+ }
681
+ if (missing.length) {
682
+ lines.push(` remap: ${PROGRAM} init-config --force … --state <bucket>="<option>", or add the option on the board`)
683
+ }
684
+ out.write(lines.join('\n') + '\n')
685
+ return 0
686
+ }
687
+
688
+ async function specSyncList(dir, config, flags, out) {
689
+ const cred = apiAdapterFor(config, flags)
690
+ const transport = kit.resolveTransport(flags, config, cred.ok)
691
+ if (transport === 'mcp' || !cred.ok) {
692
+ // Degrades rather than refusing: a listing is a convenience, and with no
693
+ // token there is simply nothing to list from here.
694
+ out.write(`${PROGRAM} list: needs the API transport — ${cred.ok ? 'pass --via api' : cred.error.split('\n')[0]}\n`)
695
+ return 0
696
+ }
697
+ const gap = flags.adapter ? null : configGap(config)
698
+ if (gap) {
699
+ out.write(`${PROGRAM} list: ${gap}\n`)
700
+ return 1
701
+ }
702
+ let issues
703
+ try {
704
+ issues = await cred.adapter.listBoardItems({ label: markersFor(config, 'spec').labels[0] || '' })
705
+ const stateNames = flags.stateArgs || []
706
+ if (stateNames.length) {
707
+ const want = new Set(stateNames.map((s) => s.toLowerCase()))
708
+ issues = issues.filter((i) => i.state && want.has(String(i.state.name).toLowerCase()))
709
+ } else if (!flags.all) {
710
+ issues = issues.filter((i) => i.open)
711
+ }
712
+ } catch (error) {
713
+ out.write(`${PROGRAM} list: ${error.message}\n`)
714
+ return 1
715
+ }
716
+ const linked = new Map(listSpecs(dir, config).filter((s) => s.identifier).map((s) => [s.identifier, s]))
717
+ const rows = issues
718
+ .filter((i) => !i.parent)
719
+ .slice(0, flags.limit || Infinity)
720
+ .map((i) => ({
721
+ identifier: i.identifier,
722
+ title: i.title,
723
+ state: i.state ? i.state.name : null,
724
+ spec: linked.has(i.identifier) ? linked.get(i.identifier).spec : null,
725
+ }))
726
+ if (flags.json) {
727
+ out.write(JSON.stringify(rows, null, 2) + '\n')
728
+ return 0
729
+ }
730
+ if (!rows.length) {
731
+ out.write(`${PROGRAM} list: nothing matched\n`)
732
+ return 0
733
+ }
734
+ const lines = [`${PROGRAM} list: ${repoLabel(config)} · board ${config.github.project}`]
735
+ for (const r of rows) {
736
+ lines.push(` ${r.identifier}\t${r.state || '—'}\t${r.title || ''}${r.spec ? ` -> ${r.spec}` : ''}`)
737
+ }
738
+ out.write(lines.join('\n') + '\n')
739
+ return 0
740
+ }
741
+
742
+ // `intake [query]` — the inbox `/spec --from-issue` browses: open issues
743
+ // carrying `intake.label` that no spec has adopted yet, and that are not
744
+ // themselves spec or phase issues. Read-only, and never fatal: a listing is
745
+ // a convenience, so a missing token degrades to one line and exit 0.
746
+ async function specSyncIntake(dir, config, query, flags, out) {
747
+ const cred = apiAdapterFor(config, flags)
748
+ const transport = kit.resolveTransport(flags, config, cred.ok)
749
+ if (transport === 'mcp' || !cred.ok) {
750
+ out.write(
751
+ `${PROGRAM} intake: needs the API transport — ${cred.ok ? 'pass --via api' : cred.error.split('\n')[0]}\n` +
752
+ ` (over MCP: list_issues with label "${config.intake.label || '<any>'}", then drop the ones \`spec-sync linked\` names)\n`,
753
+ )
754
+ return 0
755
+ }
756
+ let issues
757
+ try {
758
+ issues = await cred.adapter.listIssues({ labels: config.intake.label ? [config.intake.label] : [] })
759
+ } catch (error) {
760
+ out.write(`${PROGRAM} intake: ${error.message}\n`)
761
+ return 1
762
+ }
763
+ const claimed = new Set(listSpecs(dir, config).map((s) => s.identifier).filter(Boolean))
764
+ const own = new Set(['spec', 'phase'].flatMap((k) => markersFor(config, k).labels).map((l) => l.toLowerCase()))
765
+ const want = String(query || '').toLowerCase().trim()
766
+ const bug = new Set((config.intake.bugLabels || []).map((l) => l.toLowerCase()))
767
+ const hot = new Set((config.intake.hotfixLabels || []).map((l) => l.toLowerCase()))
768
+ const rows = issues
769
+ .filter((i) => !claimed.has(i.identifier))
770
+ .filter((i) => !i.labels.some((l) => own.has(l.toLowerCase())))
771
+ .filter((i) => !want || String(i.title || '').toLowerCase().includes(want))
772
+ .map((i) => {
773
+ const lower = i.labels.map((l) => l.toLowerCase())
774
+ // Hotfix is checked first, as the intake seam does: production is the
775
+ // more specific destination.
776
+ const route = lower.some((l) => hot.has(l)) ? '/spec-hotfix' : lower.some((l) => bug.has(l)) ? '/spec-bug' : '/spec'
777
+ return { identifier: i.identifier, title: i.title, url: i.url, labels: i.labels, author: i.author, route }
778
+ })
779
+ if (flags.json) {
780
+ out.write(JSON.stringify(rows, null, 2) + '\n')
781
+ return 0
782
+ }
783
+ if (!rows.length) {
784
+ out.write(`${PROGRAM} intake: nothing waiting${config.intake.label ? ` under "${config.intake.label}"` : ''}\n`)
785
+ return 0
786
+ }
787
+ const lines = [`${PROGRAM} intake: ${repoLabel(config)}${config.intake.label ? ` · "${config.intake.label}"` : ''}`]
788
+ for (const r of rows) lines.push(` ${r.identifier}\t${r.route}\t${r.title || ''}${r.author ? ` (${r.author})` : ''}`)
789
+ out.write(lines.join('\n') + '\n')
790
+ return 0
791
+ }
792
+
793
+ // The `Refs:` trailer's source of truth: the ticket for the spec this branch
794
+ // (or the named spec) belongs to. Bare identifier on stdout ONLY on success —
795
+ // every no-ref case writes stderr and exits 1, so `$(spec-sync ref)` cannot
796
+ // splice an error into a commit body.
797
+ function specSyncRef(dir, config, specArg, flags, out, err) {
798
+ let snapshotDir = null
799
+ if (specArg) {
800
+ snapshotDir = resolveSnapshotDir(specArg, dir)
801
+ if (!snapshotDir) {
802
+ err.write(`${PROGRAM} ref: spec not found: ${specArg}\n`)
803
+ return 1
804
+ }
805
+ } else {
806
+ // `currentBranch` takes a git READER bound to the checkout, not a path.
807
+ const { execFileSync } = require('node:child_process')
808
+ const git = (argv) => {
809
+ try {
810
+ return execFileSync('git', ['-C', dir, ...argv], { stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim()
811
+ } catch {
812
+ return null
813
+ }
814
+ }
815
+ const branch = currentBranch(git)
816
+ if (!branch) {
817
+ err.write(`${PROGRAM} ref: not on a branch\n`)
818
+ return 1
819
+ }
820
+ const slug = branch.includes('/') ? branch.slice(branch.indexOf('/') + 1) : branch
821
+ const type = branch.includes('/') ? branch.slice(0, branch.indexOf('/')) : null
822
+ const name = type ? `${type}-${slug}` : slug
823
+ const found = findSpecFolder(name, dir)
824
+ if (!found) {
825
+ err.write(`${PROGRAM} ref: no spec matches branch ${branch}\n`)
826
+ return 1
827
+ }
828
+ snapshotDir = found.path
829
+ }
830
+ const overviewFile = (config.snapshot && config.snapshot.overviewFile) || '00-overview.md'
831
+ const id = specHelpers.linkedIdentifier(path.join(snapshotDir, overviewFile), config)
832
+ if (!id) {
833
+ err.write(`${PROGRAM} ref: ${path.basename(snapshotDir)} has no ${config.fields.identifier} — omit the trailer\n`)
834
+ return 1
835
+ }
836
+ if (flags.json) out.write(JSON.stringify({ identifier: id }) + '\n')
837
+ else out.write(id + '\n')
838
+ return 0
839
+ }
840
+
841
+ // ---------------------------------------------------------------------------
842
+ // `released [<range>]` — which tickets a commit range contains, off the
843
+ // `Refs:` trailers (kit `src/released.js` owns the parsing rules). Refs are
844
+ // `#N`; an older tracker's `KEY-N` trailer — a repo that moved here from
845
+ // Linear or Jira — counts as historical, never as a missed trailer.
846
+ function readCommitRange(dir, range) {
847
+ const { execFileSync } = require('node:child_process')
848
+ const SEP = '\0SKITTERSPEC\0'
849
+ let raw
850
+ try {
851
+ raw = execFileSync('git', ['-C', dir, 'log', `--format=%x00SKITTERSPEC%x00%H%n%B%x00END%x00`, '--name-only', range], {
852
+ encoding: 'utf-8',
853
+ stdio: ['ignore', 'pipe', 'pipe'],
854
+ maxBuffer: 64 * 1024 * 1024,
855
+ })
856
+ } catch (error) {
857
+ const detail = (error.stderr || '').toString().trim().split('\n')[0] || error.message
858
+ return { ok: false, error: detail }
859
+ }
860
+ const commits = []
861
+ for (const chunk of raw.split(SEP)) {
862
+ if (!chunk.trim()) continue
863
+ const endAt = chunk.indexOf('\0END\0')
864
+ if (endAt < 0) continue
865
+ const head = chunk.slice(0, endAt)
866
+ const paths = chunk
867
+ .slice(endAt + '\0END\0'.length)
868
+ .split('\n')
869
+ .map((l) => l.trim())
870
+ .filter(Boolean)
871
+ const nl = head.indexOf('\n')
872
+ const sha = head.slice(0, nl < 0 ? head.length : nl).trim()
873
+ const body = nl < 0 ? '' : head.slice(nl + 1)
874
+ commits.push({ sha, subject: body.split('\n')[0] || '', body, paths })
875
+ }
876
+ return { ok: true, commits }
877
+ }
878
+
879
+ function specSyncReleased(dir, config, rangeArg, flags, out) {
880
+ const range = rangeArg || 'HEAD'
881
+ const read = readCommitRange(dir, range)
882
+ if (!read.ok) {
883
+ out.write(`${PROGRAM} released: ${read.error}\n`)
884
+ return 1
885
+ }
886
+ const report = kit.ticketsInRange(read.commits, {
887
+ ignorePaths: (config.release && config.release.ignorePaths) || [],
888
+ refPattern: GITHUB_REF_RE,
889
+ foreignPatterns: [IDENTIFIER_RE],
890
+ })
891
+ if (flags.json) {
892
+ out.write(JSON.stringify(report, null, 2) + '\n')
893
+ return 0
894
+ }
895
+ const lines = [`${PROGRAM} released: ${range} — ${report.total} commit(s)`]
896
+ for (const t of report.tickets) lines.push(` ${t.ref} (${t.commits} commit(s))`)
897
+ if (!report.tickets.length) lines.push(' no referenced issues')
898
+ if (report.unreferenced) lines.push(` ${report.unreferenced} commit(s) carry no Refs: trailer`)
899
+ if (report.historical) lines.push(` ${report.historical} commit(s) reference an earlier tracker (KEY-N)`)
900
+ if (report.ignored) lines.push(` ${report.ignored} bookkeeping commit(s) ignored`)
901
+ out.write(lines.join('\n') + '\n')
902
+ return 0
903
+ }
904
+
905
+ // ---------------------------------------------------------------------------
906
+ // `release create | deployed | complete` — the kit's release seam
907
+ // (`provider-kit/src/releases.js`) on GitHub Releases plus the board's
908
+ // Deployed field. Run by CI on a tag push; dry unless `--apply`.
909
+ const releases = makeReleaseCommands({
910
+ tracker: 'GitHub',
911
+ program: PROGRAM,
912
+ readCommits: (dir, range) => readCommitRange(dir, range),
913
+ ticketOptions: (config) => ({
914
+ ignorePaths: (config.release && config.release.ignorePaths) || [],
915
+ refPattern: GITHUB_REF_RE,
916
+ foreignPatterns: [IDENTIFIER_RE],
917
+ }),
918
+ teamKey: () => '',
919
+ listSpecs: (dir, config) => listSpecs(dir, config),
920
+ series: (config) => (config.releases && config.releases.series) || [],
921
+ adapterFor: (config, flags) => {
922
+ const got = apiAdapterFor(config, flags)
923
+ if (!got.ok) return got
924
+ const gap = flags.adapter ? null : configGap(config)
925
+ return gap ? { ok: false, error: gap } : got
926
+ },
927
+ describe: (t) => `${t.ref}${t.title ? ` ${t.title}` : ''}`,
928
+ // GitHub's MCP server can READ releases and cannot write one — so over MCP
929
+ // this is impossible, not merely slower, and says so (exit 1).
930
+ impossibleOverMcp: (config, flags) =>
931
+ kit.resolveTransport(flags, config, true) === 'mcp'
932
+ ? "transport = mcp — GitHub's MCP server has no release write tool; set a token (CI: a repo secret) and re-run"
933
+ : null,
934
+ })
935
+
936
+ // ---------------------------------------------------------------------------
937
+ // `preserve <spec>` — post the issue's current body back onto the issue as a
938
+ // comment BEFORE the linking push replaces it. Every cannot-tell exits 0: a
939
+ // missing link, an unreachable GitHub, an issue with no body, and an
940
+ // already-preserved report are all states to report, not failures.
941
+ const PRESERVE_HEADING = '**Original report**'
942
+ const PRESERVE_MARKER = 'preserved by skitterspec before the spec replaced this description'
943
+
944
+ async function specSyncPreserve(dir, config, specArg, flags, out) {
945
+ const snapshotDir = resolveOrExit(specArg, dir, out)
946
+ if (!snapshotDir) return 1
947
+ const overviewFile = (config.snapshot && config.snapshot.overviewFile) || '00-overview.md'
948
+ const identifier = specHelpers.linkedIdentifier(path.join(snapshotDir, overviewFile), config)
949
+ const done = (msg) => {
950
+ out.write(`${PROGRAM} preserve: ${msg}\n`)
951
+ return 0
952
+ }
953
+ if (!identifier) return done(`${path.basename(snapshotDir)} is not linked — nothing to preserve`)
954
+
955
+ let original = null
956
+ if (flags.text) {
957
+ try {
958
+ original = fs.readFileSync(flags.text, 'utf-8')
959
+ } catch (error) {
960
+ out.write(`${PROGRAM} preserve: cannot read --text: ${error.message}\n`)
961
+ return 1
962
+ }
963
+ }
964
+
965
+ const cred = apiAdapterFor(config, flags)
966
+ const transport = kit.resolveTransport(flags, config, cred.ok)
967
+ if (transport === 'mcp' && original == null) {
968
+ return done(
969
+ 'transport = mcp — read the issue body with issue_read, save it to a file,\n' +
970
+ ' and re-run with --text <file>; the comment is then posted for you\n' +
971
+ ` (or post it yourself with add_issue_comment, headed "${PRESERVE_HEADING}")`,
972
+ )
973
+ }
974
+ if (!cred.ok) return done(`no token — ${cred.error.split('\n')[0]}; nothing preserved`)
975
+
976
+ try {
977
+ const comments = await cred.adapter.listComments(identifier)
978
+ if (comments.some((c) => c.body && c.body.includes(PRESERVE_MARKER))) {
979
+ return done(`${identifier} — already preserved, nothing to do`)
980
+ }
981
+ if (original == null) {
982
+ const issue = await cred.adapter.readIssue(identifier)
983
+ if (!issue) return done(`${identifier} not found in ${repoLabel(config)} — nothing preserved`)
984
+ original = issue.description
985
+ }
986
+ if (original == null || !String(original).trim()) {
987
+ return done(`${identifier} has no body — nothing to preserve`)
988
+ }
989
+ await cred.adapter.createComment(identifier, `${PRESERVE_HEADING}\n\n_${PRESERVE_MARKER}_\n\n${original}`)
990
+ return done(`${identifier} — original report preserved as a comment (${String(original).length} characters kept)`)
991
+ } catch (error) {
992
+ return done(`could not reach GitHub (${String(error.message).split('\n')[0]}); nothing preserved`)
993
+ }
994
+ }
995
+
996
+ // ---------------------------------------------------------------------------
997
+ // Credentials: `status` is a READINESS check (exit 1 with none); `set`
998
+ // prompts for the token hidden; `unset` removes the owner's entry.
999
+ async function specSyncCredentials(dir, config, action, flags, out) {
1000
+ // The store is USER-LEVEL — a machine credential must be storable before any
1001
+ // repo is configured — so the owner (the store's scope key) may come from the
1002
+ // flag as well as the config.
1003
+ const owner = flags.owner || (config.github && config.github.owner) || ''
1004
+ const scoped = { ...config, github: { ...(config.github || {}), owner } }
1005
+ const scope = scopeOf(scoped)
1006
+ if (!scope) {
1007
+ out.write(
1008
+ `${PROGRAM} credentials: no owner to key the entry by — pass --owner <account>,\n` +
1009
+ ` or configure ${CONFIG_FILE} first (/spec-github-setup, or spec-sync init-config).\n`,
1010
+ )
1011
+ return 1
1012
+ }
1013
+ const env = flags.env || process.env
1014
+ const file = storePath(env)
1015
+
1016
+ if (action === 'status') {
1017
+ const resolved = resolveCredential(scoped, env)
1018
+ const mode = storeMode(file)
1019
+ const payload = {
1020
+ store: file,
1021
+ mode,
1022
+ scope,
1023
+ credentials: resolved.ok ? { present: true, source: resolved.source, token: fingerprint(resolved.token) } : { present: false },
1024
+ }
1025
+ if (flags.json) {
1026
+ out.write(JSON.stringify(payload, null, 2) + '\n')
1027
+ return resolved.ok ? 0 : 1
1028
+ }
1029
+ const lines = [`${PROGRAM} credentials:`]
1030
+ lines.push(` store: ${file}${mode ? ` (${mode})` : ' (not created yet)'}`)
1031
+ lines.push(` owner: ${scope}`)
1032
+ if (resolved.ok) {
1033
+ const where = resolved.source === 'env' ? `environment (${resolved.envVar})` : resolved.source
1034
+ lines.push(` token: set — ${fingerprint(resolved.token)} from the ${where}`)
1035
+ } else {
1036
+ lines.push(' token: not set')
1037
+ lines.push('')
1038
+ lines.push(' Run this yourself, in your own terminal — not through an assistant:')
1039
+ lines.push(` ${BIN} spec-sync credentials set`)
1040
+ }
1041
+ out.write(lines.join('\n') + '\n')
1042
+ return resolved.ok ? 0 : 1
1043
+ }
1044
+
1045
+ if (action === 'set') {
1046
+ if (flags.keyArgGiven) {
1047
+ out.write(
1048
+ `${PROGRAM} credentials: --key is not supported, on purpose.\n` +
1049
+ ' A secret in the command line is visible in shell history and to `ps`.\n' +
1050
+ ' Run `credentials set` with no arguments and paste at the prompt (input\n' +
1051
+ ' is hidden), or pipe it: `… | credentials set --stdin`.\n',
1052
+ )
1053
+ return 1
1054
+ }
1055
+ let token = ''
1056
+ const input = flags.input || process.stdin
1057
+ if (flags.stdin) {
1058
+ // A TTY on stdin is positive evidence that nothing was piped: `--stdin`
1059
+ // then waits for an EOF a terminal never sends. Refuse and name the two
1060
+ // working forms rather than blocking forever.
1061
+ if (input.isTTY) {
1062
+ out.write(
1063
+ `${PROGRAM} credentials: --stdin expects a pipe, but stdin is a terminal.\n` +
1064
+ ' Run it without --stdin to be prompted, or pipe the token:\n' +
1065
+ ` <command that prints the token> | ${BIN} spec-sync credentials set --stdin\n`,
1066
+ )
1067
+ return 1
1068
+ }
1069
+ token = (await kit.readAllStdin(input)).trim()
1070
+ } else {
1071
+ if (!input.isTTY) {
1072
+ out.write(
1073
+ `${PROGRAM} credentials: not a terminal — cannot prompt.\n` +
1074
+ ' Run it in your own terminal, or pipe the token with --stdin.\n',
1075
+ )
1076
+ return 1
1077
+ }
1078
+ token = (await kit.promptHidden(`GitHub token for ${scope} (classic, repo + project; hidden): `, input, out)).trim()
1079
+ }
1080
+ if (!token) {
1081
+ out.write(`${PROGRAM} credentials: empty token — nothing stored.\n`)
1082
+ return 1
1083
+ }
1084
+ const r = writeCredential(file, scope, token)
1085
+ if (!r.ok) {
1086
+ out.write(`${PROGRAM} credentials: ${r.reason}\n`)
1087
+ return 1
1088
+ }
1089
+ out.write(`${PROGRAM} credentials: stored for ${scope} in ${r.path} (600)\n`)
1090
+ return 0
1091
+ }
1092
+
1093
+ if (action === 'unset') {
1094
+ const r = removeCredential(file, scope)
1095
+ if (!r.ok) {
1096
+ out.write(`${PROGRAM} credentials: ${r.reason}\n`)
1097
+ return 1
1098
+ }
1099
+ out.write(
1100
+ r.removed
1101
+ ? `${PROGRAM} credentials: removed the entry for ${scope} from ${r.path}\n`
1102
+ : `${PROGRAM} credentials: nothing stored for ${scope} — nothing to remove\n`,
1103
+ )
1104
+ return 0
1105
+ }
1106
+
1107
+ out.write(`Usage: ${BIN} spec-sync credentials <status|set|unset> [--owner <account>] [--stdin] [--json]\n`)
1108
+ return 1
1109
+ }
1110
+
1111
+ // ---------------------------------------------------------------------------
1112
+ async function specSyncInitConfig(dir, flags, out) {
1113
+ const file = path.join(dir, CONFIG_FILE)
1114
+ if (fs.existsSync(file) && !flags.force) {
1115
+ out.write(`${PROGRAM} init-config: ${CONFIG_FILE} already exists — pass --force to overwrite\n`)
1116
+ return 1
1117
+ }
1118
+ if (!flags.owner || !flags.repo || !flags.project) {
1119
+ out.write(`${PROGRAM} init-config: --owner, --repo and --project (the board number) are required\n`)
1120
+ return 1
1121
+ }
1122
+ // Only the keys the operator set are written; everything else stays a
1123
+ // loader default, validated through the loader's own merge so a bad value
1124
+ // fails HERE rather than on the first push.
1125
+ const parsed = { github: { owner: flags.owner, repo: flags.repo, project: flags.project } }
1126
+ if (flags.statusField) parsed.github.statusField = flags.statusField
1127
+ if (flags.stateNames && Object.keys(flags.stateNames).length) {
1128
+ for (const bucket of Object.keys(flags.stateNames)) {
1129
+ if (!LIFECYCLE_BUCKETS.includes(bucket)) {
1130
+ out.write(
1131
+ `${PROGRAM} init-config: --state ${bucket}=… is not a lifecycle bucket (${LIFECYCLE_BUCKETS.join('|')})\n`,
1132
+ )
1133
+ return 1
1134
+ }
1135
+ }
1136
+ parsed.states = flags.stateNames
1137
+ }
1138
+ let merged
1139
+ try {
1140
+ merged = mergeConfig(defaults(), parsed)
1141
+ } catch (error) {
1142
+ out.write(`${PROGRAM} init-config: ${error.message}\n`)
1143
+ return 1
1144
+ }
1145
+
1146
+ // Validate the states map against the board's REAL options whenever a token
1147
+ // can reach it — a map this command could have checked must not sail
1148
+ // through to fail at doctor or, worse, at the first half-applied push.
1149
+ // Refuses with per-bucket suggestions and writes NOTHING; it never picks a
1150
+ // mapping itself, because that is a judgment only the operator can make
1151
+ // (`/spec-github-setup` is the surface that asks). Unreachable or
1152
+ // token-less is a cannot-tell: the config is still written, with one line
1153
+ // saying what was not checked.
1154
+ const cred = flags.adapter ? { ok: true } : resolveCredential(merged, flags.env || process.env)
1155
+ if (cred.ok) {
1156
+ const adapter = flags.adapter || makeApiAdapter({ ...adapterOptions(merged), token: cred.token, fetch: flags.fetch })
1157
+ let names = null
1158
+ try {
1159
+ names = (await adapter.listIssueStates()).map((st) => st.name)
1160
+ } catch (error) {
1161
+ out.write(`${PROGRAM} init-config: could not check the board's options (${String(error.message).split('\n')[0]}) — doctor --check-remote will\n`)
1162
+ }
1163
+ if (names) {
1164
+ const missing = [...new Set(validateStates(merged, names))]
1165
+ if (missing.length) {
1166
+ const lines = [`${PROGRAM} init-config: refusing — nothing written`, '']
1167
+ for (const { label, configured, suggestion } of stateSuggestions(merged, names)) {
1168
+ lines.push(` ${label}: "${configured}" is not a "${merged.github.statusField}" option on board ${merged.github.project}`)
1169
+ if (suggestion) lines.push(` try --state ${label}="${suggestion}"`)
1170
+ }
1171
+ lines.push(
1172
+ '',
1173
+ ` available: ${names.join(', ')}`,
1174
+ ' Map every lifecycle bucket to one of those with --state <bucket>=<name>,',
1175
+ ' add the missing option on the board, or run /spec-github-setup.',
1176
+ )
1177
+ out.write(lines.join('\n') + '\n')
1178
+ return 1
1179
+ }
1180
+ }
1181
+ } else {
1182
+ out.write(`${PROGRAM} init-config: states not checked against the board (no token) — doctor --check-remote will\n`)
1183
+ }
1184
+
1185
+ fs.mkdirSync(path.dirname(file), { recursive: true })
1186
+ fs.writeFileSync(file, JSON.stringify(parsed, null, 2) + '\n')
1187
+ out.write(`${PROGRAM} init-config: wrote ${CONFIG_FILE}\n`)
1188
+ // A worktree forks from a COMMIT, so an uncommitted config is invisible in
1189
+ // every spec worktree — where the sync skills actually run. Say so here,
1190
+ // once, rather than letting each worktree report "GitHub sync is off".
1191
+ out.write(` commit it — spec worktrees fork from commits, and sync is off wherever this file is absent\n`)
1192
+ return 0
1193
+ }
1194
+
1195
+ // ---------------------------------------------------------------------------
1196
+ // Doctor: readiness across the layers this provider owns. The row framework
1197
+ // and the missing-is-not-broken discipline are the kit's.
1198
+ async function specSyncDoctor(dir, flags, out) {
1199
+ const { doctorRow: row, combineDoctorChecks } = kit
1200
+ const checks = []
1201
+ let loaded = null
1202
+ try {
1203
+ loaded = loadGithubConfig(dir)
1204
+ } catch (error) {
1205
+ checks.push(row('tracker', 'GitHub config', 'broken', error.message, `fix ${CONFIG_FILE}`))
1206
+ }
1207
+ if (loaded) {
1208
+ if (!loaded.present) {
1209
+ checks.push(
1210
+ row(
1211
+ 'tracker',
1212
+ 'GitHub config',
1213
+ 'missing',
1214
+ `${CONFIG_FILE} not present — GitHub sync is off`,
1215
+ `${BIN} spec-sync init-config --owner … --repo … --project …`,
1216
+ ),
1217
+ )
1218
+ } else if (configGap(loaded.config)) {
1219
+ checks.push(row('tracker', 'GitHub config', 'broken', configGap(loaded.config), `fix ${CONFIG_FILE}`))
1220
+ } else {
1221
+ checks.push(row('tracker', 'GitHub config', 'ok', `${repoLabel(loaded.config)} · board ${loaded.config.github.project}`))
1222
+ // A worktree forks from a COMMIT, so a config that exists only in the
1223
+ // working tree is invisible in every spec worktree — where the sync
1224
+ // skills actually run. The positive signal is git tracking the file;
1225
+ // every cannot-tell (no git repo, no git binary, a crashed call) stays
1226
+ // silent rather than accusing a healthy setup (negative-checks rule 4).
1227
+ // WHAT WOULD FOOL THIS: tracked-but-modified — worktrees then see the
1228
+ // last committed mapping, not this one. Lesser and not warned on.
1229
+ try {
1230
+ const { execFileSync } = require('node:child_process')
1231
+ const tracked = execFileSync('git', ['-C', dir, 'ls-files', '--', CONFIG_FILE], {
1232
+ encoding: 'utf-8',
1233
+ stdio: ['ignore', 'pipe', 'ignore'],
1234
+ }).trim()
1235
+ const inRepo = execFileSync('git', ['-C', dir, 'rev-parse', '--is-inside-work-tree'], {
1236
+ encoding: 'utf-8',
1237
+ stdio: ['ignore', 'pipe', 'ignore'],
1238
+ }).trim()
1239
+ if (inRepo === 'true' && !tracked) {
1240
+ checks.push(
1241
+ row(
1242
+ 'tracker',
1243
+ 'Config committed',
1244
+ 'warn',
1245
+ `${CONFIG_FILE} is untracked — invisible in spec worktrees, sync is off there`,
1246
+ `git add -- ${CONFIG_FILE} && git commit`,
1247
+ ),
1248
+ )
1249
+ }
1250
+ } catch {
1251
+ // cannot tell — say nothing
1252
+ }
1253
+ }
1254
+ }
1255
+ const config = loaded && loaded.present && !configGap(loaded.config) ? loaded.config : null
1256
+ if (config) {
1257
+ const cred = resolveCredential(config, flags.env || process.env)
1258
+ checks.push(
1259
+ cred.ok
1260
+ ? row('credentials', 'Token', 'ok', `${fingerprint(cred.token)} (${cred.source === 'env' ? cred.envVar : cred.source})`)
1261
+ : row('credentials', 'Token', 'missing', cred.error.split('\n')[0], `${BIN} spec-sync credentials set`),
1262
+ )
1263
+ if (flags.remoteCheck && (cred.ok || flags.adapter)) {
1264
+ const adapter = flags.adapter || makeApiAdapter({ ...adapterOptions(config), token: cred.token, fetch: flags.fetch })
1265
+ try {
1266
+ const viewer = await adapter.readViewer()
1267
+ checks.push(row('remote', 'GitHub reachable', 'ok', viewer ? `as ${viewer.login || viewer.id}` : 'yes'))
1268
+ // Scopes are a POSITIVE signal only for a classic token, which reports
1269
+ // them; a fine-grained token reports none (`null`) — a cannot-tell,
1270
+ // never "no scopes".
1271
+ if (viewer && Array.isArray(viewer.scopes)) {
1272
+ const need = ['repo', 'project'].filter((s) => !viewer.scopes.includes(s))
1273
+ checks.push(
1274
+ need.length
1275
+ ? row('remote', 'Token scopes', 'broken', `missing: ${need.join(', ')}`, 'create a classic token with repo + project, then credentials set')
1276
+ : row('remote', 'Token scopes', 'ok', 'repo, project'),
1277
+ )
1278
+ }
1279
+ const states = await adapter.listIssueStates()
1280
+ // Deduped: two buckets may share one option, and a stutter reads as noise.
1281
+ const missing = [...new Set(validateStates(config, states.map((s) => s.name)))]
1282
+ checks.push(
1283
+ missing.length
1284
+ ? row(
1285
+ 'states',
1286
+ 'Board states',
1287
+ 'broken',
1288
+ `not "${config.github.statusField}" options: ${missing.join(', ')}`,
1289
+ `add them on the board, or fix ${CONFIG_FILE} -> states (see spec-sync states)`,
1290
+ )
1291
+ : row('states', 'Board states', 'ok', `every configured state is a "${config.github.statusField}" option`),
1292
+ )
1293
+ // Releases: the Deployed field and every env option a series names. Only
1294
+ // when a series is configured — a repo that never adopted releases has
1295
+ // nothing to be told about here.
1296
+ const series = (config.releases && config.releases.series) || []
1297
+ if (series.length && adapter.resolveBoard) {
1298
+ const field = config.releases.deployedField
1299
+ const board = await adapter.resolveBoard()
1300
+ const f = board.fields.find((x) => String(x.name).toLowerCase() === String(field).toLowerCase() && x.options)
1301
+ if (!f) {
1302
+ checks.push(row('releases', 'Deployed field', 'broken', `the board has no single-select "${field}"`, `add it on the board, or set releases.deployedField`))
1303
+ } else {
1304
+ const have = new Set(f.options.map((o) => o.name.toLowerCase()))
1305
+ const absent = series.flatMap((s) => Object.values(s.envs || {})).filter((o) => !have.has(o.toLowerCase()))
1306
+ checks.push(
1307
+ absent.length
1308
+ ? row('releases', 'Deployed field', 'broken', `"${field}" lacks: ${[...new Set(absent)].join(', ')}`, 'add the options on the board, or fix releases.series envs')
1309
+ : row('releases', 'Deployed field', 'ok', `"${field}" has every env option`),
1310
+ )
1311
+ }
1312
+ }
1313
+ if (adapter.listLabels) {
1314
+ const have = new Set((await adapter.listLabels()).map((l) => String(l.name).toLowerCase()))
1315
+ const want = ['spec', 'phase'].flatMap((k) => markersFor(config, k).labels)
1316
+ const absent = want.filter((l) => !have.has(l.toLowerCase()))
1317
+ checks.push(
1318
+ absent.length
1319
+ ? row('labels', 'Labels', 'warn', `not in the repo: ${absent.join(', ')} — GitHub creates them on first use`, '/spec-github-setup offers to create them')
1320
+ : row('labels', 'Labels', 'ok', want.join(', ') || 'none configured'),
1321
+ )
1322
+ }
1323
+ } catch (error) {
1324
+ checks.push(row('remote', 'GitHub reachable', 'broken', String(error.message).split('\n')[0], 'check the token, github.owner/repo and github.project'))
1325
+ }
1326
+ } else if (flags.remoteCheck) {
1327
+ checks.push(row('remote', 'GitHub reachable', 'skipped', 'no token to check with'))
1328
+ }
1329
+ }
1330
+ const report = combineDoctorChecks(checks)
1331
+ if (flags.json) {
1332
+ out.write(JSON.stringify(report, null, 2) + '\n')
1333
+ return report.ok ? 0 : 1
1334
+ }
1335
+ const mark = { ok: 'ok', missing: '--', broken: 'XX', skipped: '..', warn: '!!' }
1336
+ const lines = [`${PROGRAM} doctor:`]
1337
+ for (const c of report.checks) {
1338
+ lines.push(` ${mark[c.state] || '??'} ${c.label}: ${c.detail}`)
1339
+ if (c.fix && c.state !== 'ok') lines.push(` fix: ${c.fix}`)
1340
+ }
1341
+ out.write(lines.join('\n') + '\n')
1342
+ return report.ok ? 0 : 1
1343
+ }
1344
+
1345
+ // ---------------------------------------------------------------------------
1346
+ const USAGE = `Usage: ${BIN} spec-sync <subcommand>
1347
+
1348
+ normalize <spec> print the local projection as JSON
1349
+ plan <spec> --workspace-states <f> what a push would change (dry, JSON)
1350
+ apply <spec> --plan <f> | --all <b> apply a plan over the API
1351
+ stamp <spec> --issue #N [--sub r=#N] write returned numbers into the spec
1352
+ record <spec> write the last-pushed snapshot
1353
+ status <spec> [--remote <f>] read-only drift report
1354
+ verify <spec> --stored <f> compare a read-back against the repo
1355
+ states [--json] the board's Status options + bucket map
1356
+ list [--all | --state NAME] the board's issues for this repo
1357
+ intake [query] [--json] issues waiting to become specs
1358
+ linked [--json] specs and their linked issues (offline)
1359
+ ref [<spec>] the Refs: trailer value for this branch
1360
+ released [<range>] issues a commit range contains
1361
+ release create|deployed|complete <tag> GitHub Release + Deployed field (CI; --apply)
1362
+ preserve <spec> [--text <f>] keep an adopted issue's original report
1363
+ assign <spec> --to <login> | --release stamp who is building it
1364
+ whoami [--set <login>] [--unset] who you are on GitHub (cached)
1365
+ users [<query>] the repo's assignable people
1366
+ credentials <status|set|unset> the GitHub token (user-level)
1367
+ init-config --owner … --repo … --project N write the config
1368
+ doctor [--check-remote] [--json] readiness report
1369
+
1370
+ Not yet shipped for GitHub: retarget, reattach, sanitise.
1371
+ `
1372
+
1373
+ async function specSync(rest, io = {}) {
1374
+ const out = io.out || process.stdout
1375
+ const err = io.err || process.stderr
1376
+ const [sub, ...args] = rest
1377
+ let dir = io.cwd || process.cwd()
1378
+
1379
+ const { flags, positional, unknown } = parseArgs(args, sub)
1380
+ if (unknown.length) {
1381
+ out.write(kit.unknownFlagLines(PROGRAM, unknown).join('\n') + '\n')
1382
+ return 1
1383
+ }
1384
+ if (flags.dirOverride) dir = flags.dirOverride
1385
+ dir = path.resolve(dir)
1386
+ // Injection seam, alongside cwd/out/err: `env` supplies the credential
1387
+ // lookup and `adapter`/`fetch` stand in for the network, so every command is
1388
+ // exercised end to end offline. Production passes none and gets the real thing.
1389
+ flags.env = io.env || process.env
1390
+ if (io.adapter) flags.adapter = io.adapter
1391
+ if (io.fetch) flags.fetch = io.fetch
1392
+ if (io.input) flags.input = io.input
1393
+ if (io.tty !== undefined) out.isTTY = io.tty
1394
+
1395
+ if (sub === 'init-config') return specSyncInitConfig(dir, flags, out)
1396
+ if (sub === 'doctor') return specSyncDoctor(dir, flags, out)
1397
+
1398
+ let loaded
1399
+ try {
1400
+ loaded = loadGithubConfig(dir)
1401
+ } catch (error) {
1402
+ out.write(`${PROGRAM}: ${error.message}\n`)
1403
+ return 1
1404
+ }
1405
+ // Credentials are user-level, not repo-level: storing or checking them must
1406
+ // work before the repo opts in, or setup has a circular order.
1407
+ if (sub === 'credentials') return specSyncCredentials(dir, loaded.config, positional[0], flags, out)
1408
+ if (!loaded.present) {
1409
+ // Opt-out, not an error: a repo with no github config has nothing to sync.
1410
+ out.write(`${PROGRAM}: ${CONFIG_FILE} not present — GitHub sync is off for this repo\n`)
1411
+ return 0
1412
+ }
1413
+ const config = loaded.config
1414
+
1415
+ switch (sub) {
1416
+ case 'normalize':
1417
+ return specSyncNormalize(dir, config, positional[0], out, err)
1418
+ case 'plan':
1419
+ return specSyncPlan(dir, config, positional[0], flags, out, err)
1420
+ case 'apply':
1421
+ return specSyncApply(dir, config, positional[0], flags, out, err)
1422
+ case 'stamp':
1423
+ return specSyncStamp(dir, config, positional[0], flags, out)
1424
+ case 'record':
1425
+ return specSyncRecord(dir, config, positional[0], out)
1426
+ case 'status':
1427
+ return specSyncStatus(dir, config, positional[0], flags, out, err)
1428
+ case 'verify':
1429
+ return specSyncVerify(dir, config, positional[0], flags, out)
1430
+ case 'linked':
1431
+ return specSyncLinked(dir, config, flags, out)
1432
+ case 'states':
1433
+ return specSyncStates(dir, config, flags, out)
1434
+ case 'list':
1435
+ return specSyncList(dir, config, flags, out)
1436
+ case 'intake':
1437
+ return specSyncIntake(dir, config, positional[0], flags, out)
1438
+ case 'ref':
1439
+ return specSyncRef(dir, config, positional[0], flags, out, err)
1440
+ case 'released':
1441
+ return specSyncReleased(dir, config, positional[0], flags, out)
1442
+ case 'preserve':
1443
+ return specSyncPreserve(dir, config, positional[0], flags, out)
1444
+ case 'release':
1445
+ return releases.run(dir, config, positional, flags, out)
1446
+ case 'assign':
1447
+ return assignment.assign(dir, config, positional[0], flags, out)
1448
+ case 'whoami':
1449
+ return assignment.whoami(dir, config, flags, out)
1450
+ case 'users':
1451
+ return assignment.users(dir, config, positional[0], flags, out)
1452
+ default:
1453
+ out.write(USAGE)
1454
+ return sub ? 1 : 0
1455
+ }
1456
+ }
1457
+
1458
+ // The kit's table parser, plus the one flag it cannot express portably:
1459
+ // `apply --all <bucket>` takes a value while `list --all` is bare, so `--all`
1460
+ // is resolved in a pre-pass keyed on the subcommand.
1461
+ function parseArgs(args, sub) {
1462
+ const pre = []
1463
+ let all
1464
+ for (let i = 0; i < args.length; i++) {
1465
+ if (args[i] === '--all') {
1466
+ all = sub === 'list' ? true : args[++i]
1467
+ continue
1468
+ }
1469
+ pre.push(args[i])
1470
+ }
1471
+ const table = {
1472
+ '--json': { kind: 'boolean' },
1473
+ '--dir': { kind: 'path', name: 'dirOverride' },
1474
+ '--plan': { kind: 'path' },
1475
+ '--stored': { kind: 'path' },
1476
+ '--remote': { kind: 'path' },
1477
+ '--text': { kind: 'path' },
1478
+ '--workspace-states': { kind: 'path', name: 'workspaceStates' },
1479
+ '--skip-state-check': { kind: 'boolean', name: 'skipStateCheck' },
1480
+ '--via': { kind: 'string' },
1481
+ '--force': { kind: 'boolean' },
1482
+ '--force-new': { kind: 'boolean', name: 'forceNew' },
1483
+ '--issue': { kind: 'string' },
1484
+ '--url': { kind: 'value' },
1485
+ '--sub': { kind: 'list', name: 'subs' },
1486
+ '--limit': { kind: 'number' },
1487
+ '--stdin': { kind: 'boolean' },
1488
+ '--check-remote': { kind: 'boolean', name: 'remoteCheck' },
1489
+ '--owner': { kind: 'string' },
1490
+ '--repo': { kind: 'string' },
1491
+ '--project': { kind: 'string' },
1492
+ '--status-field': { kind: 'string', name: 'statusField' },
1493
+ '--to': { kind: 'string' },
1494
+ '--name': { kind: 'value' },
1495
+ '--release': { kind: 'boolean' },
1496
+ '--set': { kind: 'string' },
1497
+ '--unset': { kind: 'boolean' },
1498
+ '--cursor': { kind: 'string' },
1499
+ '--notes': { kind: 'path' },
1500
+ '--link': { kind: 'list', name: 'links' },
1501
+ '--stage': { kind: 'string' },
1502
+ '--apply': { kind: 'boolean' },
1503
+ '--state': {
1504
+ kind: 'custom',
1505
+ handle: (flags, value) => {
1506
+ // Two readings, kept apart: `init-config --state complete=Shipped` is
1507
+ // a bucket=name PAIR; `list --state "In Progress"` a bare option name.
1508
+ const raw = String(value || '').trim()
1509
+ const [bucket, ...rest] = raw.split('=')
1510
+ if (rest.length) {
1511
+ flags.stateNames = { ...(flags.stateNames || {}), [bucket.trim()]: rest.join('=').trim() }
1512
+ }
1513
+ if (raw) (flags.stateArgs = flags.stateArgs || []).push(rest.length ? rest.join('=').trim() : raw)
1514
+ },
1515
+ },
1516
+ '--key': {
1517
+ kind: 'custom',
1518
+ handle: (flags) => {
1519
+ // Consumed and DELIBERATELY DISCARDED — a secret in argv is refused,
1520
+ // but it must still be swallowed or it would print back in usage.
1521
+ flags.keyArgGiven = true
1522
+ },
1523
+ },
1524
+ }
1525
+ const parsed = kit.parseFlags(pre, table)
1526
+ if (all !== undefined) parsed.flags.all = all
1527
+ return parsed
1528
+ }
1529
+
1530
+ module.exports = { specSync, USAGE, stateCheckFailure, applyOps, PRESERVE_HEADING, PRESERVE_MARKER }