@skitterbyte/skitterspec-github 0.0.0-stage → 1.0.1

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 +1126 -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 +5907 -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 +225 -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 +800 -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,380 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * The release seam — `spec-sync release create | deployed | complete`.
5
+ *
6
+ * A release today is a git tag and nothing more, while `released` already
7
+ * knows exactly which tickets a tag contains. These verbs write that down where
8
+ * people look: a release object on the tracker holding its tickets, which the
9
+ * host project's CI moves through its deploy stages.
10
+ *
11
+ * SKITTERSPEC DECIDES A RELEASE'S CONTENTS, never the tracker. The ticket set
12
+ * is `ticketsInRange` + `partitionStageMoves` over previous-tag → this-tag:
13
+ * the `Refs:` trailers, bookkeeping commits ignored, foreign refs excluded.
14
+ * That is one definition of "what shipped", shared with `released`.
15
+ *
16
+ * EVERY VERB IS A DRY RUN UNLESS `--apply`. CI passes it; a person reading the
17
+ * plan does not have to.
18
+ *
19
+ * IDEMPOTENT BY LOOKUP, not by memory. `create` finds the release for the tag
20
+ * first and updates it; a retry on the same tag never mints a duplicate. A
21
+ * lookup that FAILED is a cannot-tell, and refuses rather than creating
22
+ * (`.claude/rules/negative-checks.md` rule 4) — creating on "I could not see
23
+ * one" is exactly how duplicates are made.
24
+ *
25
+ * Tracker calls arrive as OPTIONAL adapter ops, feature-detected: a provider
26
+ * without them makes every verb refuse in one line. The ops:
27
+ *
28
+ * - `releaseFind(tag)` → release | null (throws = cannot tell)
29
+ * - `releaseCreate({ tag, name, body, prerelease })` → release
30
+ * - `releaseUpdate(release, { name, body })`
31
+ * - `releaseAttach(release, tickets)` → `{ attached, already }`
32
+ * - `releaseStage(release, optionName, tickets)` → `{ set }`
33
+ * - `releaseComplete(release)`
34
+ * - `releaseTagExists(tag)` OPTIONAL → true | false (throws = cannot tell)
35
+ *
36
+ * A release object carries at least `{ id, url, body }`.
37
+ */
38
+
39
+ const { execFileSync } = require('node:child_process')
40
+
41
+ const { ticketsInRange, partitionStageMoves, stageOrderWarning } = require('./released.js')
42
+
43
+ const REQUIRED_OPS = ['releaseFind', 'releaseCreate', 'releaseUpdate', 'releaseAttach', 'releaseStage', 'releaseComplete']
44
+
45
+ // The line a release body carries so the next verb can read where the release
46
+ // is without asking anything else. An HTML comment: invisible where the body is
47
+ // rendered as markdown, and never confused with prose a person wrote.
48
+ const MARKER_RE = /<!--\s*skitterspec:release\s+v1\s+stage=([A-Za-z0-9_.-]*)\s*-->/
49
+
50
+ function stageOf(body) {
51
+ const m = MARKER_RE.exec(String(body || ''))
52
+ return m ? m[1] || null : null
53
+ }
54
+
55
+ function withStage(body, key) {
56
+ const line = `<!-- skitterspec:release v1 stage=${key || ''} -->`
57
+ const text = String(body || '')
58
+ return MARKER_RE.test(text) ? text.replace(MARKER_RE, line) : `${text.replace(/\s+$/, '')}\n\n${line}\n`
59
+ }
60
+
61
+ function gitReader(dir) {
62
+ return (argv) => {
63
+ try {
64
+ return execFileSync('git', ['-C', dir, ...argv], { stdio: ['ignore', 'pipe', 'ignore'], encoding: 'utf-8' }).trim()
65
+ } catch {
66
+ return null
67
+ }
68
+ }
69
+ }
70
+
71
+ /**
72
+ * The series a tag belongs to: the configured `tagPrefix` it starts with,
73
+ * longest first so `skitterspec-github@` is not read as `skitterspec`.
74
+ */
75
+ function seriesFor(series, tag) {
76
+ return (
77
+ [...(series || [])]
78
+ .filter((s) => s && s.tagPrefix)
79
+ .sort((a, b) => b.tagPrefix.length - a.tagPrefix.length)
80
+ .find((s) => String(tag).startsWith(s.tagPrefix)) || null
81
+ )
82
+ }
83
+
84
+ /**
85
+ * Previous tag in the same series → this tag.
86
+ *
87
+ * `git describe --match '<prefix>*' <tag>^` walks back from the commit BEFORE
88
+ * this tag, so a hotfix tag cut from a release tag ranges from that base, and
89
+ * a tag never ranges from itself.
90
+ *
91
+ * WHAT WOULD FOOL THIS: a shallow clone. `describe` there finds no previous tag
92
+ * and the range silently becomes "everything" — every ticket in history landing
93
+ * on one release. So shallowness is asked about first, as a positive signal,
94
+ * and refused with the fix (CI checkout `fetch-depth: 0`).
95
+ */
96
+ function resolveRange(dir, tag, prefix, git = gitReader(dir)) {
97
+ if (git(['rev-parse', '--is-shallow-repository']) === 'true') {
98
+ return {
99
+ ok: false,
100
+ error: 'this clone is shallow, so the previous tag cannot be found — check out with fetch-depth: 0',
101
+ }
102
+ }
103
+ if (!git(['rev-parse', '--verify', '--quiet', `refs/tags/${tag}`])) {
104
+ return { ok: false, error: `no tag ${tag} in this repo` }
105
+ }
106
+ const previous = git(['describe', '--tags', '--abbrev=0', '--match', `${prefix}*`, `${tag}^`])
107
+ if (previous) return { ok: true, range: `${previous}..${tag}`, previous }
108
+ return { ok: true, range: tag, previous: null, first: true }
109
+ }
110
+
111
+ /**
112
+ * Compose the release body: the notes, then the issues, then the marker. Pure,
113
+ * so a re-run on unchanged inputs produces the same text — which is what lets
114
+ * `create` say "no change" rather than rewrite a release on every CI retry.
115
+ */
116
+ function composeBody({ notes, tickets, links, stage, describe }) {
117
+ const parts = []
118
+ if (notes && String(notes).trim()) parts.push(String(notes).trim())
119
+ if (tickets.length) {
120
+ parts.push(['## Issues', '', ...tickets.map((t) => `- ${describe ? describe(t) : t.ref}`)].join('\n'))
121
+ }
122
+ if (links && links.length) {
123
+ parts.push(['## Links', '', ...links.map((l) => `- [${l.label || l.url}](${l.url})`)].join('\n'))
124
+ }
125
+ return withStage(parts.join('\n\n'), stage)
126
+ }
127
+
128
+ // `--link <url>[=label]`, repeatable. http(s) only: this lands in a body a
129
+ // tracker renders as a link, and a `javascript:` url there is script.
130
+ function parseLinks(raw) {
131
+ const out = []
132
+ const bad = []
133
+ for (const item of raw || []) {
134
+ const s = String(item)
135
+ const eq = s.indexOf('=', s.indexOf('://') + 3)
136
+ const url = eq > 0 ? s.slice(0, eq) : s
137
+ const label = eq > 0 ? s.slice(eq + 1) : null
138
+ if (/^https?:\/\//i.test(url)) out.push({ url, label })
139
+ else bad.push(s)
140
+ }
141
+ return { links: out, bad }
142
+ }
143
+
144
+ /**
145
+ * @param {object} p
146
+ * - `tracker` the tracker's name in messages
147
+ * - `program` 'spec-sync'
148
+ * - `readCommits(dir, range)` → `{ ok, commits | error }` (the provider's `released` reader)
149
+ * - `ticketOptions(config)` → the `ticketsInRange` options (ignorePaths, refPattern, …)
150
+ * - `teamKey(config)` → the foreign-ref key for `partitionStageMoves` ('' for none)
151
+ * - `listSpecs(dir, config)` → `[{ identifier, bucket, spec }]`
152
+ * - `series(config)` → `[{ tagPrefix, envs: { key: optionName } }]`
153
+ * - `adapterFor(config, flags)` → `{ ok, adapter | error }`
154
+ * - `describe(ticket)` OPTIONAL → the issue line in the body
155
+ * - `impossibleOverMcp` OPTIONAL — the transport answer for a provider whose
156
+ * MCP server cannot write releases; `(config, flags) → string | null`
157
+ */
158
+ function makeReleaseCommands(p) {
159
+ const prog = `${p.program || 'spec-sync'} release`
160
+
161
+ function refuse(out, msg) {
162
+ out.write(`${prog}: ${msg}\n`)
163
+ return 1
164
+ }
165
+
166
+ // Everything a verb needs before touching the tracker, refused in one line
167
+ // each so CI logs say exactly what was missing.
168
+ function prepare(dir, config, tagArg, flags, out) {
169
+ if (!tagArg) return { code: refuse(out, 'pass the tag, e.g. skitterspec@1.4.0') }
170
+ const series = p.series(config)
171
+ if (!series.length) return { code: refuse(out, `no releases.series configured — add one to the ${p.tracker} config`) }
172
+ let tag = String(tagArg)
173
+ // A bare version is accepted when exactly one series is configured — the
174
+ // common single-package repo — and refused otherwise rather than guessed.
175
+ if (!seriesFor(series, tag)) {
176
+ if (series.length === 1 && /^v?\d/.test(tag)) tag = `${series[0].tagPrefix}${tag}`
177
+ else return { code: refuse(out, `${tag} matches no releases.series tagPrefix (${series.map((s) => s.tagPrefix).join(', ')})`) }
178
+ }
179
+ const s = seriesFor(series, tag)
180
+ if (p.impossibleOverMcp) {
181
+ const why = p.impossibleOverMcp(config, flags)
182
+ if (why) return { code: refuse(out, why) }
183
+ }
184
+ const got = p.adapterFor(config, flags)
185
+ if (!got.ok) return { code: refuse(out, got.error) }
186
+ const missing = REQUIRED_OPS.filter((op) => typeof got.adapter[op] !== 'function')
187
+ if (missing.length) return { code: refuse(out, `the ${p.tracker} provider has no release support (${missing.join(', ')})`) }
188
+ return { tag, series: s, adapter: got.adapter }
189
+ }
190
+
191
+ // The tickets a tag's range contains, split into what the release holds and
192
+ // what it reports. Recomputed by every verb — stateless, so `deployed` and
193
+ // `complete` act on the same set `create` attached without storing it.
194
+ function ticketsOf(dir, config, tag, s) {
195
+ const range = resolveRange(dir, tag, s.tagPrefix)
196
+ if (!range.ok) return range
197
+ const read = p.readCommits(dir, range.range)
198
+ if (!read.ok) return { ok: false, error: read.error }
199
+ const report = ticketsInRange(read.commits, p.ticketOptions(config))
200
+ const parts = partitionStageMoves({ tickets: report.tickets, teamKey: p.teamKey(config), specs: p.listSpecs(dir, config) })
201
+ // Movable AND unfinished: code that landed via /spec-to-main really is in
202
+ // this release. Attaching never touches workflow state — push owns that.
203
+ const attach = [...parts.movable, ...parts.unfinished]
204
+ return { ok: true, range, report, parts, attach }
205
+ }
206
+
207
+ function planLines(t, tag) {
208
+ const lines = [
209
+ ` range: ${t.range.range}${t.range.first ? ' (no previous release in this series — everything up to the tag)' : ''}`,
210
+ ` attach: ${t.attach.map((x) => x.ref).join(', ') || 'none'}`,
211
+ ]
212
+ if (t.parts.unfinished.length) lines.push(` (in flight: ${t.parts.unfinished.map((x) => x.ref).join(', ')} — attached, state left to push)`)
213
+ if (t.parts.foreign.length) lines.push(` foreign: ${t.parts.foreign.map((x) => x.ref).join(', ')} — not attached`)
214
+ if (t.parts.unlinked.length) lines.push(` unlinked: ${t.parts.unlinked.map((x) => x.ref).join(', ')} — no spec claims them, not attached`)
215
+ lines.push(` ${t.report.unreferenced} commit(s) carry no Refs: trailer${t.report.ignored ? `, ${t.report.ignored} bookkeeping ignored` : ''}`)
216
+ // Without this line a range from before a tracker move reads as mostly
217
+ // missing: those commits are neither unreferenced nor attached.
218
+ if (t.report.historical) lines.push(` ${t.report.historical} commit(s) reference an earlier tracker — not attached`)
219
+ return lines
220
+ }
221
+
222
+ async function find(adapter, tag, out) {
223
+ try {
224
+ return { ok: true, release: await adapter.releaseFind(tag) }
225
+ } catch (error) {
226
+ refuse(out, `could not look up the release for ${tag} (${String(error.message).split('\n')[0]}) — refusing rather than risk a duplicate`)
227
+ return { ok: false }
228
+ }
229
+ }
230
+
231
+ async function create(dir, config, tagArg, flags, out) {
232
+ const prep = prepare(dir, config, tagArg, flags, out)
233
+ if (prep.code != null) return prep.code
234
+ const { tag, series: s, adapter } = prep
235
+ const t = ticketsOf(dir, config, tag, s)
236
+ if (!t.ok) return refuse(out, t.error)
237
+ const { links, bad } = parseLinks(flags.links)
238
+ if (bad.length) return refuse(out, `--link must be http(s): ${bad.join(', ')}`)
239
+ let notes = null
240
+ if (flags.notes) {
241
+ try {
242
+ notes = require('node:fs').readFileSync(flags.notes, 'utf-8')
243
+ } catch (error) {
244
+ return refuse(out, `cannot read --notes: ${error.message}`)
245
+ }
246
+ }
247
+ const envKeys = Object.keys(s.envs || {})
248
+ const stage = flags.stage || envKeys[0] || null
249
+ if (stage && envKeys.length && !envKeys.includes(stage)) {
250
+ return refuse(out, `--stage ${stage} is not an env of ${s.tagPrefix} (${envKeys.join(', ')})`)
251
+ }
252
+
253
+ // A tracker that would CREATE a missing tag from the default branch must
254
+ // not be handed one it has not got — the release would point at the wrong
255
+ // commit. Positive signals only: `false` refuses, a throw is a cannot-tell
256
+ // and the create goes ahead exactly as it would have.
257
+ if (adapter.releaseTagExists) {
258
+ let exists = null
259
+ try {
260
+ exists = await adapter.releaseTagExists(tag)
261
+ } catch {
262
+ exists = null
263
+ }
264
+ if (exists === false) return refuse(out, `${tag} is not on the ${p.tracker} remote yet — push the tag first`)
265
+ }
266
+
267
+ const found = await find(adapter, tag, out)
268
+ if (!found.ok) return 1
269
+ const existing = found.release
270
+ // A release already past its first stage keeps the stage it is at: a CI
271
+ // retry of `create` must not drag a deployed release back.
272
+ const keep = existing ? stageOf(existing.body) : null
273
+ const body = composeBody({ notes, tickets: await describeAll(adapter, t.attach), links, stage: keep || stage, describe: p.describe })
274
+
275
+ const header = [`${prog} create: ${tag}${flags.apply ? '' : ' (dry run — pass --apply to write)'}`, ...planLines(t, tag)]
276
+ if (!flags.apply) {
277
+ header.push(` would ${existing ? (existing.body === body ? 'leave the release unchanged' : 'update the release') : 'create the release'}${existing && existing.url ? ` (${existing.url})` : ''}`)
278
+ return emit(out, flags, header, { tag, range: t.range.range, attach: t.attach.map((x) => x.ref), apply: false, existing: !!existing })
279
+ }
280
+ let release = existing
281
+ if (!release) {
282
+ release = await adapter.releaseCreate({ tag, name: tag, body, prerelease: true })
283
+ header.push(` created: ${release.url || release.id}`)
284
+ } else if (release.body !== body) {
285
+ await adapter.releaseUpdate(release, { name: tag, body })
286
+ header.push(` updated: ${release.url || release.id}`)
287
+ } else {
288
+ header.push(` unchanged: ${release.url || release.id}`)
289
+ }
290
+ const attached = await adapter.releaseAttach(release, t.attach)
291
+ header.push(` issues: ${attached.attached} noted, ${attached.already} already noted`)
292
+ return emit(out, flags, header, { tag, range: t.range.range, attach: t.attach.map((x) => x.ref), apply: true, url: release.url || null })
293
+ }
294
+
295
+ async function deployed(dir, config, tagArg, envKey, flags, out) {
296
+ const prep = prepare(dir, config, tagArg, flags, out)
297
+ if (prep.code != null) return prep.code
298
+ const { tag, series: s, adapter } = prep
299
+ const envs = s.envs || {}
300
+ if (!envKey || !(envKey in envs)) {
301
+ return refuse(out, `pass an env of ${s.tagPrefix}: ${Object.keys(envs).join(', ') || '(none configured)'}`)
302
+ }
303
+ const found = await find(adapter, tag, out)
304
+ if (!found.ok) return 1
305
+ if (!found.release) return refuse(out, `no release for ${tag} yet — run \`release create ${tag}\` first`)
306
+ const t = ticketsOf(dir, config, tag, s)
307
+ if (!t.ok) return refuse(out, t.error)
308
+ const lines = [`${prog} deployed: ${tag} → ${envKey}${flags.apply ? '' : ' (dry run — pass --apply to write)'}`]
309
+ // WARNS, NEVER REFUSES: a rollback and a hotfix straight to prod are both
310
+ // legitimate. The order is the series' own env order.
311
+ const ladder = Object.keys(envs).map((key) => ({ key, state: key }))
312
+ const from = stageOf(found.release.body)
313
+ const warn = from ? stageOrderWarning(ladder, from, envKey) : null
314
+ if (warn) lines.push(` !! ${warn}`)
315
+ lines.push(` issues: ${t.attach.map((x) => x.ref).join(', ') || 'none'} → "${envs[envKey]}"`)
316
+ if (!flags.apply) return emit(out, flags, lines, { tag, env: envKey, apply: false, warn })
317
+ const staged = await adapter.releaseStage(found.release, envs[envKey], t.attach)
318
+ await adapter.releaseUpdate(found.release, { name: tag, body: withStage(found.release.body, envKey) })
319
+ lines.push(` set: ${staged.set} issue(s)`)
320
+ return emit(out, flags, lines, { tag, env: envKey, apply: true, warn, set: staged.set })
321
+ }
322
+
323
+ async function complete(dir, config, tagArg, flags, out) {
324
+ const prep = prepare(dir, config, tagArg, flags, out)
325
+ if (prep.code != null) return prep.code
326
+ const { tag, adapter } = prep
327
+ const found = await find(adapter, tag, out)
328
+ if (!found.ok) return 1
329
+ if (!found.release) return refuse(out, `no release for ${tag} yet — run \`release create ${tag}\` first`)
330
+ const lines = [`${prog} complete: ${tag}${flags.apply ? '' : ' (dry run — pass --apply to write)'}`]
331
+ if (!flags.apply) {
332
+ lines.push(` would mark ${found.release.url || found.release.id} complete`)
333
+ return emit(out, flags, lines, { tag, apply: false })
334
+ }
335
+ await adapter.releaseComplete(found.release)
336
+ lines.push(` completed: ${found.release.url || found.release.id}`)
337
+ return emit(out, flags, lines, { tag, apply: true })
338
+ }
339
+
340
+ // Titles for the body, best-effort: a ticket the tracker cannot read is
341
+ // still listed, by ref. The body is information, not a gate.
342
+ async function describeAll(adapter, tickets) {
343
+ const out = []
344
+ for (const t of tickets) {
345
+ let title = null
346
+ if (adapter.readIssue) {
347
+ try {
348
+ const issue = await adapter.readIssue(t.ref)
349
+ title = issue && issue.title ? issue.title : null
350
+ } catch {
351
+ title = null
352
+ }
353
+ }
354
+ out.push({ ...t, title })
355
+ }
356
+ return out
357
+ }
358
+
359
+ function emit(out, flags, lines, json) {
360
+ out.write(flags.json ? JSON.stringify(json, null, 2) + '\n' : lines.join('\n') + '\n')
361
+ return 0
362
+ }
363
+
364
+ async function run(dir, config, args, flags, out) {
365
+ const [verb, tag, env] = args
366
+ if (verb === 'create') return create(dir, config, tag, flags, out)
367
+ if (verb === 'deployed') return deployed(dir, config, tag, env, flags, out)
368
+ if (verb === 'complete') return complete(dir, config, tag, flags, out)
369
+ out.write(
370
+ `Usage: ${prog} create <tag> [--notes <f>] [--link <url>[=label]] [--stage <env>] [--apply] [--json]\n` +
371
+ ` ${prog} deployed <tag> <env> [--apply] [--json]\n` +
372
+ ` ${prog} complete <tag> [--apply] [--json]\n`,
373
+ )
374
+ return verb ? 1 : 0
375
+ }
376
+
377
+ return { run, create, deployed, complete }
378
+ }
379
+
380
+ module.exports = { makeReleaseCommands, resolveRange, seriesFor, composeBody, stageOf, withStage, parseLinks, REQUIRED_OPS }
@@ -0,0 +1,166 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * Spec resolution and listing for a provider CLI — how a spec argument becomes
5
+ * a snapshot directory, how a spec names its snapshot sidecar, and which specs
6
+ * a repo holds with which tracker links.
7
+ *
8
+ * The frontmatter key that links a spec is the provider's
9
+ * (`config.fields.identifier` — sync-core `src/fields.js`); everything else
10
+ * here is filesystem shape shared by every provider. `program` prefixes the
11
+ * user-facing refusals (`spec-sync: spec not found: …`).
12
+ */
13
+
14
+ const fs = require('node:fs')
15
+ const path = require('node:path')
16
+
17
+ const { BUCKETS, findSpecFolder } = require('../../../env/resolve.js')
18
+ const { readSnapshot, parseFrontmatter, lintPhases, fieldsOf, projectionOf, compareStored } = require('../../sync-core')
19
+
20
+ function makeSpecHelpers({ program = 'spec-sync' } = {}) {
21
+ // Resolve a spec argument to its snapshot dir. Accepts a spec name/folder
22
+ // found under specs/** (preferred) or a literal path to a snapshot directory.
23
+ function resolveSnapshotDir(specArg, dir) {
24
+ const found = findSpecFolder(specArg, dir)
25
+ if (found) return found.path
26
+ const literal = path.resolve(dir, specArg)
27
+ if (fs.existsSync(literal) && fs.statSync(literal).isDirectory()) return literal
28
+ return null
29
+ }
30
+
31
+ // The identifier keying the snapshot sidecar: the spec's stamped identifier
32
+ // if set, else its folder name (so the engine is usable before a spec is
33
+ // linked).
34
+ function specIdentifier(snapshotDir, config) {
35
+ const field = fieldsOf(config).identifier
36
+ try {
37
+ const { frontmatter } = readSnapshot(snapshotDir, config)
38
+ if (frontmatter[field]) return String(frontmatter[field])
39
+ } catch {
40
+ /* fall through to folder name */
41
+ }
42
+ return path.basename(snapshotDir)
43
+ }
44
+
45
+ // Read a spec's stamped identifier without throwing: an unlinked spec, an
46
+ // unreadable file and a spec with no frontmatter all read as `null`.
47
+ function linkedIdentifier(overviewPath, config) {
48
+ const field = fieldsOf(config).identifier
49
+ let raw
50
+ try {
51
+ raw = fs.readFileSync(overviewPath, 'utf-8')
52
+ } catch {
53
+ return null
54
+ }
55
+ const { data } = parseFrontmatter(raw)
56
+ return data[field] ? String(data[field]) : null
57
+ }
58
+
59
+ // Every spec under specs/<bucket>/, paired with the tracker issue it is
60
+ // linked to (`null` when it has never been pushed). Folder specs read
61
+ // `snapshot.overviewFile`; legacy bare `<name>.md` specs read the file
62
+ // itself. Sorted for stable output.
63
+ function listSpecs(dir, config) {
64
+ const overviewFile = (config.snapshot && config.snapshot.overviewFile) || '00-overview.md'
65
+ const specs = []
66
+ for (const bucket of BUCKETS) {
67
+ const root = path.join(dir, 'specs', bucket)
68
+ let entries
69
+ try {
70
+ entries = fs.readdirSync(root, { withFileTypes: true })
71
+ } catch {
72
+ continue
73
+ }
74
+ for (const entry of entries) {
75
+ let name
76
+ let overviewPath
77
+ if (entry.isDirectory()) {
78
+ name = entry.name
79
+ overviewPath = path.join(root, name, overviewFile)
80
+ } else if (entry.isFile() && entry.name.endsWith('.md')) {
81
+ name = entry.name.slice(0, -3)
82
+ overviewPath = path.join(root, entry.name)
83
+ } else {
84
+ continue
85
+ }
86
+ specs.push({ spec: name, bucket, identifier: linkedIdentifier(overviewPath, config) })
87
+ }
88
+ }
89
+ return specs.sort((a, b) => a.spec.localeCompare(b.spec))
90
+ }
91
+
92
+ // Resolve a spec argument to its folder, or null with a message on stdout.
93
+ // EVERY failure path here must print and EVERY caller must return a non-zero
94
+ // code: a push skill checks $? before it applies a plan, so a resolve failure
95
+ // that exits 0 reads as "nothing to do" rather than "I could not find the
96
+ // spec".
97
+ function resolveOrExit(specArg, dir, out) {
98
+ if (!specArg) {
99
+ out.write(`${program}: no spec given\n`)
100
+ return null
101
+ }
102
+ const snapshotDir = resolveSnapshotDir(specArg, dir)
103
+ if (!snapshotDir) {
104
+ out.write(`${program}: spec not found: ${specArg}\n`)
105
+ return null
106
+ }
107
+ return snapshotDir
108
+ }
109
+
110
+ // Phase-status warnings for a spec, one formatted line each. A spec states
111
+ // each phase's status three times and only the h1 emoji is read — get it
112
+ // wrong and the phase projects as `backlog`, pushes cleanly, and is recorded
113
+ // as intended: invisible. Reported by every subcommand that reads a
114
+ // projection, fatal in none — a legacy spec must still push.
115
+ function warningLines(snapshotDir, config) {
116
+ return lintPhases(snapshotDir, config).map((w) => ` warning ${w.file}: ${w.message}`)
117
+ }
118
+
119
+ // Emit warnings on stderr, keeping stdout pure for a machine-readable payload.
120
+ function warnToErr(snapshotDir, config, err) {
121
+ const lines = warningLines(snapshotDir, config)
122
+ if (lines.length) err.write(lines.join('\n') + '\n')
123
+ }
124
+
125
+ // Render the read-back comparison — the same check `verify` and `apply`
126
+ // both report through, so the two cannot disagree about what "intact" means.
127
+ function verifyLines(snapshotDir, config, stored, identifier) {
128
+ const projection = projectionOf(snapshotDir, config)
129
+ const checks = []
130
+ if (typeof stored.issue === 'string') checks.push(['issue', projection.description, stored.issue])
131
+ for (const [ref, text] of Object.entries(stored.subIssues || {})) {
132
+ const sub = projection.subIssues.find((s) => s.ref === ref)
133
+ if (!sub) {
134
+ checks.push([`sub-issue ${ref}`, null, text])
135
+ continue
136
+ }
137
+ checks.push([`sub-issue ${ref}`, sub.goal, text])
138
+ }
139
+
140
+ const lines = [`${program} verify: ${identifier}`]
141
+ let bad = 0
142
+ for (const [label, sent, got] of checks) {
143
+ if (sent == null) {
144
+ lines.push(` ?? ${label}: read back, but the projection has no such phase — stale ref?`)
145
+ bad++
146
+ continue
147
+ }
148
+ const r = compareStored(sent, got, config)
149
+ if (r.ok) continue
150
+ bad++
151
+ lines.push(
152
+ ` !! ${label}: the tracker stored different text — ${Math.abs(r.lost)} character(s) ` +
153
+ `${r.lost > 0 ? 'lost' : 'added'}, first difference at ${r.at}`,
154
+ ` sent: …${r.sentContext}…`,
155
+ ` stored: …${r.storedContext}…`,
156
+ )
157
+ }
158
+ if (!bad) lines.push(` ${checks.length} description(s) round-tripped intact`)
159
+ else lines.push(' the repo is unchanged and still correct; re-push to overwrite the mirror')
160
+ return lines
161
+ }
162
+
163
+ return { resolveSnapshotDir, specIdentifier, linkedIdentifier, listSpecs, resolveOrExit, warningLines, warnToErr, verifyLines }
164
+ }
165
+
166
+ module.exports = { makeSpecHelpers }
@@ -0,0 +1,22 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * Which transport a command runs over: `--via` wins, else the config's
5
+ * declared default, else "api when a credential resolved, mcp when it didn't".
6
+ *
7
+ * This expression was repeated verbatim nine times in the first provider —
8
+ * hoisted so the precedence is decided once. Per-command DEGRADATION stays with
9
+ * the command: which operations are impossible over mcp (exit 1, say so) and
10
+ * which hand the skill instructions (exit 0) is a per-command judgment, not a
11
+ * transport fact.
12
+ */
13
+
14
+ function resolveTransport(flags, config, credentialOk) {
15
+ return (
16
+ (flags && flags.via) ||
17
+ (config && config.apply && config.apply.transport) ||
18
+ (credentialOk ? 'api' : 'mcp')
19
+ )
20
+ }
21
+
22
+ module.exports = { resolveTransport }
@@ -0,0 +1,93 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * Provider-neutral one-way sync engine (repo → tracker).
5
+ *
6
+ * Every function is parameterised by a plain `config` object — it knows nothing
7
+ * about any specific tracker. The repo is the source of truth: the engine builds
8
+ * a local projection, diffs it against a committed last-pushed snapshot
9
+ * (`planChanges`), and returns a create/update plan the provider skill applies
10
+ * over its API. No remote content is read for CONTENT: nothing the tracker holds
11
+ * ever feeds the projection, the snapshot, or a repo file. `compareStored` is the
12
+ * one function that looks at a tracker value, and it only checks that what was
13
+ * stored matches what was sent — it merges nothing (see `src/verify.js`).
14
+ */
15
+
16
+ const { ownsField, normalizeLocal, LIFECYCLE_BUCKETS, lintPhases, readSnapshot, parseFrontmatter, remoteWorkflowState, titleFromText, validateStates, stateSuggestions, stageForState, remoteStage, phaseModeFor, LADDER_ORIGIN_BUCKET } = require('./src/normalize.js')
17
+ const { planChanges, snapshotOf, isEmptyPlan, hashField, stableStringify, remoteDescriptionEdited, remoteSubIssueEdited } = require('./src/compare.js')
18
+ const { readBase, writeBase } = require('./src/base.js')
19
+ const { push, recordPush, projectionOf } = require('./src/push.js')
20
+ const { writeFrontmatter, deleteFrontmatter, stampSubIssueId, stampIssueId, findPhaseFileByTitle, listPhaseFiles } = require('./src/write.js')
21
+ const { detectLegacyMirror } = require('./src/legacy.js')
22
+ const { compareStored, stream } = require('./src/verify.js')
23
+ const { identityDialect, dialectOf } = require('./src/dialect.js')
24
+ const { fieldsOf } = require('./src/fields.js')
25
+ const { renderTaskBlock, findTaskBlocks, wrapEmphasisAware, collapseHyphenAware, inferWidth, fenceMask, DEFAULT_WIDTH } = require('./src/task-block.js')
26
+ const { planRetarget, applyRetarget, deriveRecordedKey, isEmptyRetarget, dirtyPaths } = require('./src/retarget.js')
27
+
28
+ module.exports = {
29
+ ownsField,
30
+ normalizeLocal,
31
+ // Exported for `spec-sync list`: an `inline`-mode spec has no phase sub-issues
32
+ // to read, so the listing must resolve the mode rather than assume `subissue`.
33
+ phaseModeFor,
34
+ lintPhases,
35
+ readSnapshot,
36
+ parseFrontmatter,
37
+ projectionOf,
38
+ planChanges,
39
+ snapshotOf,
40
+ isEmptyPlan,
41
+ push,
42
+ recordPush,
43
+ remoteWorkflowState,
44
+ titleFromText,
45
+ validateStates,
46
+ stateSuggestions,
47
+ stageForState,
48
+ remoteStage,
49
+ LADDER_ORIGIN_BUCKET,
50
+ hashField,
51
+ stableStringify,
52
+ readBase,
53
+ writeBase,
54
+ writeFrontmatter,
55
+ deleteFrontmatter,
56
+ stampSubIssueId,
57
+ stampIssueId,
58
+ findPhaseFileByTitle,
59
+ listPhaseFiles,
60
+ detectLegacyMirror,
61
+ compareStored,
62
+ // The tolerant reduction behind both `compareStored` and the snapshot's
63
+ // `descriptionStream` hash — exported so a provider can reduce a read-back the
64
+ // same way rather than writing a second one that disagrees.
65
+ stream,
66
+ // Did someone else edit the tracker's description since the last push?
67
+ // Three-valued; `null` is cannot-tell and must never be reported as drift.
68
+ remoteDescriptionEdited,
69
+ remoteSubIssueEdited,
70
+ // Provider seams: the frontmatter field vocabulary and the markdown dialect
71
+ // a provider's config supplies (`config.fields` / `config.dialect`).
72
+ fieldsOf,
73
+ identityDialect,
74
+ dialectOf,
75
+ // The lifecycle buckets, exported once so providers and tests stop growing
76
+ // private copies (the tracker-free common package keeps its own — it cannot
77
+ // depend on this package).
78
+ LIFECYCLE_BUCKETS,
79
+ // Task-block helpers a provider's own text tooling builds on (the Linear
80
+ // sanitiser reflows emphasis-aware with these).
81
+ renderTaskBlock,
82
+ findTaskBlocks,
83
+ wrapEmphasisAware,
84
+ collapseHyphenAware,
85
+ inferWidth,
86
+ fenceMask,
87
+ DEFAULT_WIDTH,
88
+ planRetarget,
89
+ applyRetarget,
90
+ deriveRecordedKey,
91
+ isEmptyRetarget,
92
+ dirtyPaths,
93
+ }