@skitterbyte/skitterspec-linear 18.0.1 → 18.1.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 (50) hide show
  1. package/MIGRATION.md +81 -0
  2. package/assets/core/env.config.md +33 -9
  3. package/assets/hooks/main-guard.cjs +1 -1
  4. package/assets/hooks/review-gate.cjs +1 -1
  5. package/assets/rules/spec-planning.md +4 -2
  6. package/assets/skills/spec-complete/SKILL.md +67 -25
  7. package/assets/skills/spec-hotfix/SKILL.md +21 -11
  8. package/assets/skills/spec-sync/SKILL.md +10 -1
  9. package/package.json +1 -1
  10. package/src/cli.js +289 -34
  11. package/src/env/config.js +14 -2
  12. package/src/env/hotfix.js +261 -15
  13. package/src/env/hotfixland.js +302 -0
  14. package/src/env/resolve.js +22 -8
  15. package/src/init.js +36 -4
  16. package/src/vendor/linear/api.js +43 -56
  17. package/src/vendor/linear/cli-sanitise.js +2 -2
  18. package/src/vendor/linear/cli-sync.js +87 -390
  19. package/src/vendor/linear/config.js +46 -171
  20. package/src/vendor/linear/credentials.js +40 -370
  21. package/src/vendor/linear/dialect.js +177 -0
  22. package/src/vendor/linear/doctor.js +7 -15
  23. package/src/vendor/linear/identity.js +20 -70
  24. package/src/vendor/linear/released.js +4 -222
  25. package/src/vendor/{sync-core/src → linear}/sanitise.js +4 -3
  26. package/src/vendor/provider-kit/index.js +41 -0
  27. package/src/vendor/provider-kit/src/adapter.js +23 -0
  28. package/src/vendor/provider-kit/src/apply.js +197 -0
  29. package/src/vendor/provider-kit/src/args.js +68 -0
  30. package/src/vendor/provider-kit/src/config.js +198 -0
  31. package/src/vendor/provider-kit/src/credentials.js +404 -0
  32. package/src/vendor/provider-kit/src/doctor.js +35 -0
  33. package/src/vendor/provider-kit/src/http.js +44 -0
  34. package/src/vendor/provider-kit/src/identity.js +93 -0
  35. package/src/vendor/provider-kit/src/md-compare.js +39 -0
  36. package/src/vendor/{sync-core/src/tables.js → provider-kit/src/md-tables.js} +10 -18
  37. package/src/vendor/provider-kit/src/prompt.js +50 -0
  38. package/src/vendor/provider-kit/src/released.js +226 -0
  39. package/src/vendor/provider-kit/src/specs.js +166 -0
  40. package/src/vendor/provider-kit/src/transport.js +22 -0
  41. package/src/vendor/sync-core/index.js +22 -5
  42. package/src/vendor/sync-core/src/compare.js +14 -12
  43. package/src/vendor/sync-core/src/dialect.js +51 -0
  44. package/src/vendor/sync-core/src/fields.js +36 -0
  45. package/src/vendor/sync-core/src/legacy.js +19 -9
  46. package/src/vendor/sync-core/src/normalize.js +30 -158
  47. package/src/vendor/sync-core/src/push.js +1 -1
  48. package/src/vendor/sync-core/src/retarget.js +21 -17
  49. package/src/vendor/sync-core/src/verify.js +24 -45
  50. package/src/vendor/sync-core/src/write.js +7 -5
@@ -1,7 +1,9 @@
1
1
  'use strict'
2
2
 
3
3
  /**
4
- * "Who am I in this Linear workspace?" — the question assignment rests on.
4
+ * "Who am I in this Linear workspace?" — the Linear binding of the kit's
5
+ * identity resolver (`provider-kit/src/identity.js`, which carries the
6
+ * three-tier contract: store → viewer → unknown, unknown being a normal state).
5
7
  *
6
8
  * The answer is DERIVED, not configured. A Linear personal API key is issued to
7
9
  * a person, so the workspace can be asked directly (`viewer` on the API path,
@@ -9,97 +11,45 @@
9
11
  * common case, and why there is no `linear.userId`: `specs/.core/linear.config.json`
10
12
  * is committed, so an id written there would follow the repo to every teammate
11
13
  * who clones it and assign their specs to whoever set it up.
12
- *
13
- * Resolution order, first hit wins:
14
- *
15
- * 1. the user-level credentials store (`source: 'store'`) — no network
16
- * 2. the credential itself, via `viewer` (`source: 'viewer'`)
17
- * 3. nothing (`source: 'unknown'`)
18
- *
19
- * **Unknown is a normal state, not a failure** — the same contract
20
- * `resolveApiKey` holds for a missing key. A shared/bot key answers `viewer`
21
- * with the bot; an offline machine answers with nothing; neither is a broken
22
- * install, and both are why `spec-sync whoami --set` exists. So this returns a
23
- * structured result the caller branches on, never an exception.
24
- *
25
- * It also NEVER PROMPTS and NEVER WRITES. Prompting belongs to the skill that
26
- * has a human in front of it, and caching belongs to the command that decided
27
- * the answer was worth keeping — a resolver that wrote to disk as a side effect
28
- * of being asked a question would cache a bot's identity the first time CI ran.
29
14
  */
30
15
 
16
+ const { resolveIdentity: kitResolveIdentity, defaultDisplayName } = require('../provider-kit/src/identity.js')
31
17
  const { resolveApiKey, makeApiAdapter } = require('./api.js')
32
18
  const { storePath, readStore, userForTeam } = require('./credentials.js')
33
19
 
34
20
  /**
35
21
  * Resolve the current user's Linear identity.
36
22
  *
37
- * @returns {Promise<object>} `{ ok: true, id, name, source }` where `source` is
23
+ * @returns {Promise<object>} `{ ok: true, id, name, source }` with `source`
38
24
  * `'store'` or `'viewer'`; otherwise `{ ok: false, source: 'unknown', reason }`.
39
25
  * `reason` explains what was tried, so "no key" and "Linear rejected the key"
40
26
  * stay distinguishable — an unexplained "unknown" is what makes people
41
27
  * re-enter a name that was never the problem.
42
28
  */
43
29
  async function resolveIdentity(config, env = process.env, deps = {}) {
44
- const teamId = (config && config.linear && config.linear.teamId) || ''
45
30
  // The store is keyed by team, so with no teamId there is nothing to look up.
46
31
  // Fall through rather than fail: `viewer` does not need a team, and a repo
47
32
  // mid-setup should still be able to answer who you are.
33
+ const teamId = (config && config.linear && config.linear.teamId) || ''
48
34
  const file = (deps.storePath || storePath)(env)
49
-
50
- if (teamId) {
51
- const result = (deps.readStore || readStore)(file)
52
- if (result.ok) {
53
- const cached = (deps.userForTeam || userForTeam)(result.store, teamId)
54
- if (cached) return { ok: true, id: cached.id, name: cached.name, source: 'store', path: file }
55
- }
56
- // A store that is present but unusable (over-permissive, malformed) is NOT
57
- // reported as an identity failure — the key resolution below hits the same
58
- // file and reports it properly. Duplicating it here would print the same
59
- // permissions warning twice for one cause.
60
- }
61
-
62
- const key = (deps.resolveApiKey || resolveApiKey)(config, env)
63
- if (!key.ok) {
64
- return { ok: false, source: 'unknown', reason: key.error, envVar: key.envVar, path: file }
65
- }
66
-
67
- const adapter = deps.adapter || makeApiAdapter({ apiKey: key.key, fetch: deps.fetch })
68
- let viewer
69
- try {
70
- viewer = await adapter.readViewer()
71
- } catch (error) {
72
- // Offline, revoked key, Linear down. All are "cannot tell", which routes to
73
- // the harmless branch: the caller skips assignment rather than guessing.
74
- return { ok: false, source: 'unknown', reason: error.message, path: file }
75
- }
76
-
77
- const id = viewer && typeof viewer.id === 'string' ? viewer.id.trim() : ''
78
- if (!id) {
79
- return { ok: false, source: 'unknown', reason: 'Linear returned no viewer for this key', path: file }
80
- }
81
- return {
82
- ok: true,
83
- id,
84
- name: displayNameOf(viewer),
85
- email: (viewer && viewer.email) || null,
86
- source: 'viewer',
87
- path: file,
88
- }
35
+ return kitResolveIdentity({
36
+ scopeId: teamId,
37
+ file,
38
+ readStore: (f) => (deps.readStore || readStore)(f),
39
+ userFor: (store, id) => (deps.userForTeam || userForTeam)(store, id),
40
+ resolveCredential: () => (deps.resolveApiKey || resolveApiKey)(config, env),
41
+ readViewer: (key) => {
42
+ const adapter = deps.adapter || makeApiAdapter({ apiKey: key.key, fetch: deps.fetch })
43
+ return adapter.readViewer()
44
+ },
45
+ nameOf: displayNameOf,
46
+ })
89
47
  }
90
48
 
91
49
  /**
92
50
  * The name to show for a Linear user, preferring the one Linear itself puts on
93
- * an issue. Falls back through `displayName` and `email` so a user with an odd
94
- * profile still reads as a person rather than a UUID.
51
+ * an issue.
95
52
  */
96
- function displayNameOf(user) {
97
- if (!user || typeof user !== 'object') return null
98
- for (const field of ['name', 'displayName', 'email']) {
99
- const value = user[field]
100
- if (typeof value === 'string' && value.trim()) return value.trim()
101
- }
102
- return null
103
- }
53
+ const displayNameOf = defaultDisplayName
104
54
 
105
55
  module.exports = { resolveIdentity, displayNameOf }
@@ -1,224 +1,6 @@
1
1
  'use strict'
2
2
 
3
- /**
4
- * Which tickets a release contains.
5
- *
6
- * The repo lands specs with `merge --ff-only`, so history is linear and branch
7
- * names never reach it. A commit's `Refs:` trailer is therefore the only place
8
- * the ticket survives into the range a release scans — see the
9
- * `commit-trailers` rule.
10
- *
11
- * The parsing half is pure and takes commits as data, so the rules below are
12
- * testable without git. Reading the range, and enriching refs with issue titles,
13
- * belong to the caller.
14
- */
15
-
16
- // An issue identifier: uppercase team key, dash, number.
17
- const IDENTIFIER_RE = /\b[A-Z][A-Z0-9]*-\d+\b/g
18
- // A `Refs:` trailer line. Anchored, so it is a line of its own — never prose
19
- // that happens to mention the word.
20
- const TRAILER_RE = /^Refs:[ \t]*(.+?)[ \t]*$/
21
-
22
- /**
23
- * The refs a single commit body claims.
24
- *
25
- * Deliberately blind to three things that LOOK like trailers and are not:
26
- *
27
- * - a line inside a ``` fence — a commit explaining the convention quotes it;
28
- * - a quoted line (`> Refs: …`) — same reason, in review replies;
29
- * - an indented line (4+ spaces) — markdown code, e.g. a sample message.
30
- *
31
- * Counting any of those would make a release claim work it does not contain,
32
- * which is worse than missing a ticket: the missing one is noticed when someone
33
- * looks for it, the invented one never is.
34
- */
35
- function refsInBody(body) {
36
- const found = []
37
- let fenced = false
38
- for (const raw of String(body || '').split('\n')) {
39
- const line = raw.replace(/\r$/, '')
40
- if (/^\s*```/.test(line)) {
41
- fenced = !fenced
42
- continue
43
- }
44
- if (fenced) continue
45
- if (/^\s*>/.test(line)) continue
46
- if (/^ {4,}|\t/.test(line)) continue
47
- const m = TRAILER_RE.exec(line.trim() === line ? line : line.trimStart())
48
- if (!m) continue
49
- for (const id of m[1].match(IDENTIFIER_RE) || []) found.push(id)
50
- }
51
- return found
52
- }
53
-
54
- /**
55
- * Whether a commit's changed paths are ENTIRELY bookkeeping.
56
- *
57
- * The problem it solves: a spec's `chore(spec): complete <name>` commit carries
58
- * the same `Refs:` trailer as the code it describes, but lands after the tag
59
- * that shipped that code — so the ticket turns up in two consecutive release
60
- * ranges, once for its code and once for its paperwork.
61
- *
62
- * Deliberately a POSITIVE signal: it says yes only when it actually saw paths
63
- * and every one of them sits under an ignored prefix. It never reasons from an
64
- * absence.
65
- *
66
- * WHAT WOULD FOOL THE OTHER PHRASING ("no unignored path was found"): git lists
67
- * no files at all for a MERGE commit (without `-m`) — verified, not assumed —
68
- * nor for a genuinely empty one, and a `git log` that failed outright yields no
69
- * paths for anything. Under that phrasing every one of those becomes a release
70
- * silently losing its tickets. Under this one they mean "nothing was seen, so
71
- * nothing is known", which keeps the pre-filter behaviour: an over-claimed
72
- * ticket is noticed when someone looks for it, whereas a ticket that quietly
73
- * belongs to no release never is.
74
- *
75
- * Matching is path-prefix, not glob: `specs` and `specs/` both mean the
76
- * directory, and a prefix only matches on a path SEGMENT boundary, so `specs/`
77
- * never swallows `specs-archive/`.
78
- *
79
- * @param {string[]|null|undefined} paths repo-relative paths the commit changed
80
- * @param {string[]} ignorePaths repo-relative prefixes that are bookkeeping
81
- */
82
- function onlyIgnoredPaths(paths, ignorePaths) {
83
- if (!Array.isArray(paths) || !paths.length) return false
84
- const prefixes = (Array.isArray(ignorePaths) ? ignorePaths : [])
85
- .filter((p) => typeof p === 'string' && p.trim())
86
- .map((p) => p.trim().replace(/^\.\//, '').replace(/\/+$/, ''))
87
- .filter(Boolean)
88
- if (!prefixes.length) return false
89
- return paths.every((raw) => {
90
- const file = String(raw == null ? '' : raw)
91
- .trim()
92
- .replace(/^\.\//, '')
93
- // An unreadable entry is an unknown, not an ignored one — it makes the whole
94
- // commit count, per the bias above.
95
- if (!file) return false
96
- return prefixes.some((prefix) => file === prefix || file.startsWith(`${prefix}/`))
97
- })
98
- }
99
-
100
- /**
101
- * Fold commits into the report a release needs.
102
- *
103
- * @param {Array<{sha?:string, subject?:string, body?:string, paths?:string[]}>} commits
104
- * @param {{ignorePaths?:string[]}} [options] `ignorePaths` marks bookkeeping —
105
- * see `onlyIgnoredPaths`. Omitted (or empty) means nothing is ignored, so the
106
- * report is what it was before the filter existed.
107
- * @returns {{tickets: Array<{ref:string, commits:number}>, unreferenced:number, ignored:number, total:number}}
108
- * `tickets` is deduped in FIRST-SEEN order: a ticket touched by eight commits
109
- * is listed once, where it first appears, not eight times. `ignored` is
110
- * reported rather than merely subtracted — a filter that removes commits in
111
- * silence reads as "there was nothing there".
112
- */
113
- function ticketsInRange(commits, options = {}) {
114
- const ignorePaths = (options && options.ignorePaths) || []
115
- const seen = new Map()
116
- let unreferenced = 0
117
- let ignored = 0
118
- for (const commit of commits || []) {
119
- if (onlyIgnoredPaths(commit && commit.paths, ignorePaths)) {
120
- // Not counted as unreferenced either: that number exists to surface a
121
- // MISSED trailer, and a paperwork commit is not a gap someone should hunt.
122
- ignored++
123
- continue
124
- }
125
- const refs = [...new Set(refsInBody(commit && commit.body))]
126
- if (!refs.length) {
127
- unreferenced++
128
- continue
129
- }
130
- for (const ref of refs) seen.set(ref, (seen.get(ref) || 0) + 1)
131
- }
132
- return {
133
- tickets: [...seen.entries()].map(([ref, count]) => ({ ref, commits: count })),
134
- unreferenced,
135
- ignored,
136
- total: (commits || []).length,
137
- }
138
- }
139
-
140
- /**
141
- * Split a release's tickets into the ones a stage move may touch and the ones it
142
- * must not, with a reason for every exclusion.
143
- *
144
- * Three reasons to leave a ticket alone, and each is a case where acting would
145
- * be worse than not acting:
146
- *
147
- * - **foreign** — the ref is not this repo's team. A range can carry another
148
- * team's ref (a shared dependency, a quoted ticket), and writing to a team
149
- * this repo was never configured for is the worst failure available here.
150
- * - **unlinked** — the ref is this team's, but no spec in the repo claims it.
151
- * It may be tracker-only work, or a typo in a trailer. Either way nothing
152
- * here knows what it is, so it is reported, not moved.
153
- * - **unfinished** — a spec that has not reached the ceded bucket. Its code
154
- * really is in the release (it landed via `/spec-to-main`), but push still
155
- * owns its workflow state and would bounce it straight back. Exactly one
156
- * writer per issue at any moment beats a visible flip-flop.
157
- *
158
- * Pure: it takes the spec list as data, so the rules are testable without a repo.
159
- */
160
- function partitionStageMoves({ tickets, teamKey, specs, cededBucket = 'complete' }) {
161
- const bucketOf = new Map()
162
- for (const spec of specs || []) {
163
- if (spec && spec.identifier) bucketOf.set(spec.identifier, spec.bucket)
164
- }
165
- const key = String(teamKey || '').trim().toUpperCase()
166
- const movable = []
167
- const foreign = []
168
- const unlinked = []
169
- const unfinished = []
170
- for (const ticket of tickets || []) {
171
- const ref = ticket && ticket.ref
172
- if (!ref) continue
173
- if (key && !ref.toUpperCase().startsWith(`${key}-`)) {
174
- foreign.push(ticket)
175
- } else if (!bucketOf.has(ref)) {
176
- unlinked.push(ticket)
177
- } else if (bucketOf.get(ref) !== cededBucket) {
178
- unfinished.push({ ...ticket, bucket: bucketOf.get(ref) })
179
- } else {
180
- movable.push(ticket)
181
- }
182
- }
183
- return { movable, foreign, unlinked, unfinished }
184
- }
185
-
186
- /**
187
- * Whether moving from `fromState` to the rung `toKey` runs against the declared
188
- * order — and if so, how to say it.
189
- *
190
- * WARNS, never refuses. A rollback from test and a hotfix going straight to prod
191
- * are both legitimate, and a check that blocked either would be wrong on healthy
192
- * input. An issue that is on no rung yet is entering the ladder, which is the
193
- * normal case and says nothing.
194
- *
195
- * `lifecycleStates` is the bucket map's own state names, and a state among them
196
- * means the issue is at its LIFECYCLE position, not on a rung — even when the
197
- * two names coincide. They routinely do: `states.complete` and a final `prod`
198
- * rung are both naturally "Done", and without this a spec that had merely been
199
- * completed would read as already deployed to prod, so its first real deploy
200
- * would be warned about as a move backwards. Bucket wins over ladder here for
201
- * the same reason it wins in `bucketForState`.
202
- *
203
- * @returns {string|null}
204
- */
205
- function stageOrderWarning(stages, fromState, toKey, lifecycleStates = []) {
206
- const list = Array.isArray(stages) ? stages : []
207
- const to = list.findIndex((s) => s && s.key === toKey)
208
- if (to < 0) return null
209
- const want = String(fromState || '').toLowerCase().trim()
210
- if (!want) return null
211
- const lifecycle = new Set(
212
- (Array.isArray(lifecycleStates) ? lifecycleStates : [])
213
- .filter((n) => typeof n === 'string')
214
- .map((n) => n.toLowerCase().trim()),
215
- )
216
- if (lifecycle.has(want)) return null
217
- const from = list.findIndex((s) => s && typeof s.state === 'string' && s.state.toLowerCase().trim() === want)
218
- if (from < 0) return null
219
- if (to < from) return `moves back from "${list[from].key}"`
220
- if (to > from + 1) return `skips ${to - from - 1} rung(s) from "${list[from].key}"`
221
- return null
222
- }
223
-
224
- module.exports = { ticketsInRange, refsInBody, onlyIgnoredPaths, partitionStageMoves, stageOrderWarning }
3
+ // Which tickets a release contains — entirely provider-neutral, so the
4
+ // implementation lives in the kit. Re-exported here so the provider's own
5
+ // modules and tests keep one import path.
6
+ module.exports = require('../provider-kit/src/released.js')
@@ -4,7 +4,8 @@
4
4
  * One-time sanitiser: rewrite spec markdown so no inline emphasis or link span
5
5
  * straddles a hard line break, and repair any Linear-mangled `****` artifacts
6
6
  * already committed. This brings hand-wrapped spec files "inline" so they round-
7
- * trip through Linear cleanly (Linear mangles a straddling `**`/`*`/link on save).
7
+ * trip through Linear cleanly (Linear mangles a straddling `**`/`*`/link on
8
+ * save) — which is why this lives in the Linear provider, beside its dialect.
8
9
  *
9
10
  * Deliberately minimal-diff: only a block that actually contains a straddle or a
10
11
  * mangle is reflowed — every other paragraph, table, code fence, and heading is
@@ -15,8 +16,8 @@
15
16
  * Pure string→string (`sanitizeSpecMarkdown`); the CLI wraps it with fs walking.
16
17
  */
17
18
 
18
- const { wrapEmphasisAware, collapseHyphenAware, inferWidth, DEFAULT_WIDTH } = require('./task-block.js')
19
- const { joinEmphasisAcrossBreaks } = require('./normalize.js')
19
+ const { wrapEmphasisAware, collapseHyphenAware, inferWidth, DEFAULT_WIDTH } = require('../sync-core/src/task-block.js')
20
+ const { joinEmphasisAcrossBreaks } = require('./dialect.js')
20
21
 
21
22
  // A run of non-blank lines contains an emphasis straddle / mangle iff joining
22
23
  // spans across breaks changes it.
@@ -0,0 +1,41 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * Provider-neutral CLI plumbing shared by skitterspec ticketing providers.
5
+ *
6
+ * sync-core is the projection/plan/snapshot ENGINE — pure, no CLI, no network.
7
+ * This package is everything a provider\'s CLI builds around that engine and
8
+ * that a second provider would otherwise duplicate: config merging, the
9
+ * namespaced credentials store, identity resolution, the doctor report
10
+ * framework, released-range scanning, transport resolution, rate-limit-aware
11
+ * HTTP retry, spec resolution/listing, terminal secret input, and a flag
12
+ * parser with the unknown-flag refusal. Nothing in here names a tracker.
13
+ */
14
+
15
+ const config = require('./src/config.js')
16
+ const credentials = require('./src/credentials.js')
17
+ const identity = require('./src/identity.js')
18
+ const doctor = require('./src/doctor.js')
19
+ const released = require('./src/released.js')
20
+ const transport = require('./src/transport.js')
21
+ const http = require('./src/http.js')
22
+ const specs = require('./src/specs.js')
23
+ const prompt = require('./src/prompt.js')
24
+ const args = require('./src/args.js')
25
+ const adapter = require('./src/adapter.js')
26
+ const apply = require('./src/apply.js')
27
+
28
+ module.exports = {
29
+ ...config,
30
+ ...credentials,
31
+ ...identity,
32
+ ...doctor,
33
+ ...released,
34
+ ...transport,
35
+ ...http,
36
+ ...specs,
37
+ ...prompt,
38
+ ...args,
39
+ ...adapter,
40
+ ...apply,
41
+ }
@@ -0,0 +1,23 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * The transport op-contract check: a provider's API adapter may ADD ops beyond
5
+ * its MCP adapter, but must never be missing one — consumers feature-detect the
6
+ * extras and assume the base set. Run it in the provider's own tests against
7
+ * both adapters, so the two transports cannot drift apart silently.
8
+ */
9
+
10
+ // The function-valued op names an adapter exposes.
11
+ function adapterOps(adapter) {
12
+ return Object.keys(adapter || {})
13
+ .filter((k) => typeof adapter[k] === 'function')
14
+ .sort()
15
+ }
16
+
17
+ // Which of `required` are absent from `adapter` — [] is the passing answer.
18
+ function missingOps(required, adapter) {
19
+ const have = new Set(adapterOps(adapter))
20
+ return [].concat(required).filter((op) => !have.has(op))
21
+ }
22
+
23
+ module.exports = { adapterOps, missingOps }
@@ -0,0 +1,197 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * The apply ORCHESTRATION — the ordering, stamping and accounting shared by
5
+ * every provider's `spec-sync apply`, with the tracker calls themselves left
6
+ * to provider `ops` (deferred to this shape until two providers existed to
7
+ * validate it: one folds workflow state into its create/update payloads, the
8
+ * other must move status by a separate transition call — so state application
9
+ * lives inside the ops, and the skeleton owns only what is identical).
10
+ *
11
+ * What the skeleton owns, in order:
12
+ *
13
+ * 1. resolve every workflow state BEFORE the first write, so a bad
14
+ * `config.states` value cannot strand the spec mid-apply;
15
+ * 2. the twin-mint guard: an EXACT-title issue held by no spec is a positive
16
+ * signal the issue already exists — refuse to mint a second (a fuzzy
17
+ * match must never count: being wrong here blocks a legitimate push);
18
+ * 3. mint-or-update the spec issue, stamping the identifier the moment the
19
+ * create lands — an interrupt after that point must not mint a twin;
20
+ * 4. sub-issue creates, each STAMPED AS IT LANDS, then updates (keyed by
21
+ * ref, never by id — the read-back matches by ref);
22
+ * 5. read back what the tracker stored and run the same check `verify` runs;
23
+ * 6. record the snapshot from the now-stamped files, so the next push is
24
+ * empty.
25
+ *
26
+ * Orphan accounting rides the whole way: `created` is what the tracker holds,
27
+ * `stamped` what the repo recorded, and the one case a re-run makes WORSE is a
28
+ * create whose stamp could not be written — the identifiers travel out on the
29
+ * error so the caller can name them.
30
+ *
31
+ * @param {object} ops the provider's tracker calls:
32
+ * - `prevalidateStates(buckets)` throw early on a bad state name
33
+ * - `mintIssue({ title, issue })` → `{ id, identifier, url }`
34
+ * - `updateIssue(existing, issue)` apply `plan.issue` to a live issue
35
+ * - `mintSubIssue(parentId, sub)` → `{ id, identifier }`
36
+ * - `updateSubIssue(sub)` apply a sub-issue update
37
+ * - `remoteEditedLine(identifier)` the someone-else-edited warning
38
+ * - `twinAdvice(twin, title, specName)` the refusal message for a twin
39
+ */
40
+
41
+ const path = require('node:path')
42
+
43
+ const {
44
+ readSnapshot,
45
+ readBase,
46
+ projectionOf,
47
+ recordPush,
48
+ writeFrontmatter,
49
+ stampSubIssueId,
50
+ fieldsOf,
51
+ remoteDescriptionEdited,
52
+ listPhaseFiles,
53
+ } = require('../../sync-core')
54
+ const { makeSpecHelpers } = require('./specs.js')
55
+
56
+ /**
57
+ * The outer accounting wrapper: run the inner apply, and on ANY throw attach
58
+ * what had been stamped versus created by the time it happened.
59
+ */
60
+ async function applySpecPlan(args) {
61
+ const progress = {}
62
+ try {
63
+ return await applyInner({ ...args, progress })
64
+ } catch (error) {
65
+ const r = progress.result
66
+ if (error && typeof error === 'object' && error.stamped === undefined) {
67
+ error.stamped = r ? (r.issue ? 1 : 0) + Object.keys(r.subIssues || {}).length : 0
68
+ error.created = progress.created || []
69
+ error.orphans = error.created.slice(error.stamped)
70
+ }
71
+ throw error
72
+ }
73
+ }
74
+
75
+ async function applyInner({ dir, config, snapshotDir, plan, adapter, ops, progress, forceNew = false, program = 'spec-sync' }) {
76
+ const fields = fieldsOf(config)
77
+ const helpers = makeSpecHelpers({ program })
78
+ const overviewFile = (config.snapshot && config.snapshot.overviewFile) || '00-overview.md'
79
+ const identifier = helpers.linkedIdentifier(path.join(snapshotDir, overviewFile), config)
80
+ const lines = []
81
+ const result = { issue: null, subIssues: {} }
82
+ // Handed out immediately, so a throw from anywhere below still reports what
83
+ // had been stamped by the time it happened.
84
+ if (progress) progress.result = result
85
+
86
+ // 1. Every state resolved BEFORE the first write.
87
+ const wanted = new Set()
88
+ if (plan.issue && plan.issue.state) wanted.add(plan.issue.state)
89
+ for (const s of (plan.subIssues && plan.subIssues.create) || []) if (s.state) wanted.add(s.state)
90
+ for (const s of (plan.subIssues && plan.subIssues.update) || []) if (s.state) wanted.add(s.state)
91
+ ops.prevalidateStates([...wanted])
92
+
93
+ let parentId = null
94
+ if (!identifier) {
95
+ // 2. REFUSE TO MINT A TWIN. An EXACT match held by no spec is a positive
96
+ // signal that the issue already exists; a near-match must never count —
97
+ // being wrong here blocks a legitimate push, and a renamed spec is
98
+ // answered by adopting the issue, not by fuzz.
99
+ if (!forceNew && adapter.searchIssues) {
100
+ const title = String(plan.title || readSnapshot(snapshotDir, config).title || '').trim()
101
+ if (title) {
102
+ let found = []
103
+ try {
104
+ found = (await ops.searchTwin(title)) || []
105
+ } catch {
106
+ // A search we could not run is not evidence of an orphan. Carry on
107
+ // and mint — the cannot-tell case goes to the harmless branch, which
108
+ // here is the one that does the work the caller asked for.
109
+ found = []
110
+ }
111
+ const claimed = new Set(helpers.listSpecs(dir, config).map((sp) => sp.identifier).filter(Boolean))
112
+ const twin = found.find(
113
+ (i) => i && i.identifier && !claimed.has(i.identifier) && String(i.title || '').trim() === title,
114
+ )
115
+ if (twin) throw new Error(ops.twinAdvice(twin, title, path.basename(snapshotDir)))
116
+ }
117
+ }
118
+ // 3. Mint, then stamp IMMEDIATELY: noted before it is stamped, so a stamp
119
+ // that cannot be written can still name the identifier it strands.
120
+ const created = await ops.mintIssue({ title: readSnapshot(snapshotDir, config).title, issue: plan.issue })
121
+ parentId = created.id
122
+ if (progress) (progress.created = progress.created || []).push(created.identifier)
123
+ writeFrontmatter(snapshotDir, config, {
124
+ [fields.identifier]: created.identifier,
125
+ [fields.url]: created.url,
126
+ })
127
+ result.issue = { id: created.id, identifier: created.identifier, url: created.url }
128
+ lines.push(` issue created: ${created.identifier}`)
129
+ } else {
130
+ const existing = await adapter.readIssue(identifier)
131
+ if (!existing || !existing.id) throw new Error(ops.missingIssueMessage(identifier))
132
+ parentId = existing.id
133
+ result.issue = { id: existing.id, identifier: existing.identifier, url: existing.url }
134
+
135
+ // SOMEONE ELSE EDITED THE DESCRIPTION SINCE THE LAST PUSH, and this write
136
+ // replaces it. A WARNING AND NEVER A REFUSAL: one-way sync means the repo
137
+ // wins; what was wrong was winning silently.
138
+ if (remoteDescriptionEdited(readBase(dir, identifier, config), existing, config) === true) {
139
+ lines.push(ops.remoteEditedLine(identifier))
140
+ }
141
+ if (plan.issue) {
142
+ await ops.updateIssue(existing, plan.issue)
143
+ lines.push(` issue updated: ${identifier}`)
144
+ }
145
+ }
146
+
147
+ // 4. Sub-issue creates — each stamped as it lands, for the same reason.
148
+ for (const sub of (plan.subIssues && plan.subIssues.create) || []) {
149
+ const created = await ops.mintSubIssue(parentId, sub)
150
+ if (progress) (progress.created = progress.created || []).push(created.identifier)
151
+ const file = resolvePhaseFileIn(snapshotDir, sub.ref)
152
+ if (!file) throw new Error(`no phase file for ref ${sub.ref}`)
153
+ stampSubIssueId(snapshotDir, file, created.identifier, config)
154
+ result.subIssues[sub.ref] = created.identifier
155
+ lines.push(` sub-issue created: ${sub.ref} → ${created.identifier}`)
156
+ }
157
+
158
+ // 5. Sub-issue updates — keyed by REF, never by id: the read-back matches
159
+ // sub-issues to phases by ref, and a plan written before updates carried a
160
+ // ref still resolves — by id, off the projection.
161
+ const refById = new Map()
162
+ for (const s of projectionOf(snapshotDir, config).subIssues || []) {
163
+ if (s.id != null) refById.set(String(s.id), s.ref)
164
+ }
165
+ for (const sub of (plan.subIssues && plan.subIssues.update) || []) {
166
+ await ops.updateSubIssue(sub)
167
+ result.subIssues[sub.ref || refById.get(String(sub.id)) || sub.id] = sub.id
168
+ lines.push(` sub-issue updated: ${sub.id}`)
169
+ }
170
+
171
+ // 6. Read back what the tracker stored and run the SAME check verify runs.
172
+ const stored = { issue: undefined, subIssues: {} }
173
+ if (result.issue) {
174
+ const back = await adapter.readIssue(result.issue.id)
175
+ if (back && typeof back.description === 'string') stored.issue = back.description
176
+ }
177
+ for (const [ref, id] of Object.entries(result.subIssues)) {
178
+ const back = await adapter.readIssue(id)
179
+ if (back && typeof back.description === 'string') stored.subIssues[ref] = back.description
180
+ }
181
+ const verify = helpers.verifyLines(snapshotDir, config, stored, result.issue ? result.issue.identifier : identifier)
182
+ lines.push(...verify.map((l) => ` ${l}`))
183
+ const lost = verify.some((l) => l.includes('!!') || l.includes('??'))
184
+
185
+ // 7. Record the snapshot from the now-stamped files, so the next push is empty.
186
+ const file = recordPush({ dir, snapshotDir, identifier: helpers.specIdentifier(snapshotDir, config), config })
187
+ lines.push(` snapshot: ${path.relative(dir, file)}`)
188
+ return { result, lines, lost }
189
+ }
190
+
191
+ // The phase file a sub-issue ref names — the ref is the phase-file basename.
192
+ function resolvePhaseFileIn(snapshotDir, ref) {
193
+ const want = String(ref).replace(/\.md$/, '')
194
+ return listPhaseFiles(snapshotDir).find((f) => f.replace(/\.md$/, '') === want) || null
195
+ }
196
+
197
+ module.exports = { applySpecPlan }