@skitterbyte/skitterspec-linear 18.0.0 → 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 (51) 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/no-spec/SKILL.md +3 -2
  7. package/assets/skills/spec-complete/SKILL.md +67 -25
  8. package/assets/skills/spec-hotfix/SKILL.md +21 -11
  9. package/assets/skills/spec-sync/SKILL.md +10 -1
  10. package/package.json +1 -1
  11. package/src/cli.js +295 -37
  12. package/src/env/config.js +14 -2
  13. package/src/env/hotfix.js +261 -15
  14. package/src/env/hotfixland.js +302 -0
  15. package/src/env/resolve.js +22 -8
  16. package/src/init.js +36 -4
  17. package/src/vendor/linear/api.js +43 -56
  18. package/src/vendor/linear/cli-sanitise.js +2 -2
  19. package/src/vendor/linear/cli-sync.js +87 -390
  20. package/src/vendor/linear/config.js +46 -171
  21. package/src/vendor/linear/credentials.js +40 -370
  22. package/src/vendor/linear/dialect.js +177 -0
  23. package/src/vendor/linear/doctor.js +7 -15
  24. package/src/vendor/linear/identity.js +20 -70
  25. package/src/vendor/linear/released.js +4 -222
  26. package/src/vendor/{sync-core/src → linear}/sanitise.js +4 -3
  27. package/src/vendor/provider-kit/index.js +41 -0
  28. package/src/vendor/provider-kit/src/adapter.js +23 -0
  29. package/src/vendor/provider-kit/src/apply.js +197 -0
  30. package/src/vendor/provider-kit/src/args.js +68 -0
  31. package/src/vendor/provider-kit/src/config.js +198 -0
  32. package/src/vendor/provider-kit/src/credentials.js +404 -0
  33. package/src/vendor/provider-kit/src/doctor.js +35 -0
  34. package/src/vendor/provider-kit/src/http.js +44 -0
  35. package/src/vendor/provider-kit/src/identity.js +93 -0
  36. package/src/vendor/provider-kit/src/md-compare.js +39 -0
  37. package/src/vendor/{sync-core/src/tables.js → provider-kit/src/md-tables.js} +10 -18
  38. package/src/vendor/provider-kit/src/prompt.js +50 -0
  39. package/src/vendor/provider-kit/src/released.js +226 -0
  40. package/src/vendor/provider-kit/src/specs.js +166 -0
  41. package/src/vendor/provider-kit/src/transport.js +22 -0
  42. package/src/vendor/sync-core/index.js +22 -5
  43. package/src/vendor/sync-core/src/compare.js +14 -12
  44. package/src/vendor/sync-core/src/dialect.js +51 -0
  45. package/src/vendor/sync-core/src/fields.js +36 -0
  46. package/src/vendor/sync-core/src/legacy.js +19 -9
  47. package/src/vendor/sync-core/src/normalize.js +30 -158
  48. package/src/vendor/sync-core/src/push.js +1 -1
  49. package/src/vendor/sync-core/src/retarget.js +21 -17
  50. package/src/vendor/sync-core/src/verify.js +24 -45
  51. package/src/vendor/sync-core/src/write.js +7 -5
@@ -83,73 +83,20 @@ const {
83
83
  removeUser,
84
84
  } = require('./credentials.js')
85
85
  const { resolveIdentity, displayNameOf } = require('./identity.js')
86
+ const { resolveTransport } = require('../provider-kit/src/transport.js')
87
+ const { readAllStdin, promptHidden } = require('../provider-kit/src/prompt.js')
88
+ const { applySpecPlan } = require('../provider-kit/src/apply.js')
86
89
 
87
- // Resolve a spec argument to its snapshot dir. Accepts a spec name/folder found
88
- // under specs/** (preferred) or a literal path to a snapshot directory.
89
- function resolveSnapshotDir(specArg, dir) {
90
- const found = findSpecFolder(specArg, dir)
91
- if (found) return found.path
92
- const literal = path.resolve(dir, specArg)
93
- if (fs.existsSync(literal) && fs.statSync(literal).isDirectory()) return literal
94
- return null
95
- }
96
-
97
- // The identifier keying the snapshot sidecar: the spec's linear_identifier if
98
- // set, else its folder name (so the engine is usable before a spec is linked).
99
- function specIdentifier(snapshotDir, config) {
100
- try {
101
- const { frontmatter } = readSnapshot(snapshotDir, config)
102
- if (frontmatter.linear_identifier) return String(frontmatter.linear_identifier)
103
- } catch {
104
- /* fall through to folder name */
105
- }
106
- return path.basename(snapshotDir)
107
- }
90
+ // Spec resolution, listing and lint reporting come from the provider kit
91
+ // (`src/specs.js`), keyed by this provider's `config.fields`. `linkedIdentifier`
92
+ // keeps a config-free arity below for its many local callers.
93
+ const specHelpers = require('../provider-kit/src/specs.js').makeSpecHelpers({ program: 'spec-sync' })
94
+ const { resolveSnapshotDir, specIdentifier, listSpecs, resolveOrExit, warningLines, warnToErr } = specHelpers
108
95
 
109
- // Read a spec's `linear_identifier` without throwing: an unlinked spec, an
110
- // unreadable file and a spec with no frontmatter all read as `null`.
111
- function linkedIdentifier(overviewPath) {
112
- let raw
113
- try {
114
- raw = fs.readFileSync(overviewPath, 'utf-8')
115
- } catch {
116
- return null
117
- }
118
- const { data } = parseFrontmatter(raw)
119
- return data.linear_identifier ? String(data.linear_identifier) : null
120
- }
121
-
122
- // Every spec under specs/<bucket>/, paired with the Linear issue it is linked to
123
- // (`null` when it has never been pushed). Folder specs read `snapshot.overviewFile`;
124
- // legacy bare `<name>.md` specs read the file itself. Sorted for stable output.
125
- function listSpecs(dir, config) {
126
- const overviewFile = (config.snapshot && config.snapshot.overviewFile) || '00-overview.md'
127
- const specs = []
128
- for (const bucket of BUCKETS) {
129
- const root = path.join(dir, 'specs', bucket)
130
- let entries
131
- try {
132
- entries = fs.readdirSync(root, { withFileTypes: true })
133
- } catch {
134
- continue
135
- }
136
- for (const entry of entries) {
137
- let name
138
- let overviewPath
139
- if (entry.isDirectory()) {
140
- name = entry.name
141
- overviewPath = path.join(root, name, overviewFile)
142
- } else if (entry.isFile() && entry.name.endsWith('.md')) {
143
- name = entry.name.slice(0, -3)
144
- overviewPath = path.join(root, entry.name)
145
- } else {
146
- continue
147
- }
148
- specs.push({ spec: name, bucket, identifier: linkedIdentifier(overviewPath) })
149
- }
150
- }
151
- return specs.sort((a, b) => a.spec.localeCompare(b.spec))
152
- }
96
+ // The stamp key is fixed for this provider, so the config-free arity survives
97
+ // for the call sites that predate the kit.
98
+ const linkedIdentifier = (overviewPath) =>
99
+ specHelpers.linkedIdentifier(overviewPath, { fields: require('./config.js').DEFAULT_CONFIG.fields })
153
100
 
154
101
  /**
155
102
  * `spec-sync linked` — which Linear issues are already adopted by a spec.
@@ -177,41 +124,6 @@ function specSyncLinked(dir, config, flags, out) {
177
124
  out.write(lines.join('\n') + '\n')
178
125
  }
179
126
 
180
- // Phase-status warnings for a spec, one formatted line each.
181
- //
182
- // A spec states each phase's status three times — the phase file's h1 emoji, its
183
- // `> **Status:**` line, and the overview phase-index row — and only the h1 is
184
- // read. Get it wrong and the phase projects as `backlog`, pushes cleanly, and is
185
- // recorded as intended: invisible. So every subcommand that reads a projection
186
- // reports these, and none of them treats one as fatal — a legacy spec must still
187
- // push. See sync-core `lintPhases`.
188
- function warningLines(snapshotDir, config) {
189
- return lintPhases(snapshotDir, config).map((w) => ` warning ${w.file}: ${w.message}`)
190
- }
191
-
192
- // Emit warnings on stderr, keeping stdout pure for a machine-readable payload.
193
- function warnToErr(snapshotDir, config, err) {
194
- const lines = warningLines(snapshotDir, config)
195
- if (lines.length) err.write(lines.join('\n') + '\n')
196
- }
197
-
198
- // Resolve a spec argument to its folder, or null with a message on stdout.
199
- // EVERY failure path here must print and EVERY caller must return a non-zero
200
- // code: /spec-push checks $? before it applies a plan, so a resolve failure that
201
- // exits 0 reads as "nothing to do" rather than "I could not find the spec".
202
- function resolveOrExit(specArg, dir, out) {
203
- if (!specArg) {
204
- out.write('spec-sync: no spec given\n')
205
- return null
206
- }
207
- const snapshotDir = resolveSnapshotDir(specArg, dir)
208
- if (!snapshotDir) {
209
- out.write(`spec-sync: spec not found: ${specArg}\n`)
210
- return null
211
- }
212
- return snapshotDir
213
- }
214
-
215
127
  // `spec-sync normalize <spec>` — print the local projection as JSON.
216
128
  function specSyncNormalize(dir, config, specArg, out, err) {
217
129
  const snapshotDir = resolveOrExit(specArg, dir, out)
@@ -455,7 +367,7 @@ function specSyncStamp(dir, config, specArg, flags, out) {
455
367
  lines.push(` overview: ${written.join(', ')}`)
456
368
  }
457
369
  for (const s of subs) {
458
- stampSubIssueId(snapshotDir, s.file, s.id)
370
+ stampSubIssueId(snapshotDir, s.file, s.id, config)
459
371
  lines.push(` ${s.file}: linear_issue_id = ${s.id}`)
460
372
  }
461
373
  lines.push(' next: skitterspec spec-sync record <spec>')
@@ -626,7 +538,7 @@ function specSyncStatus(dir, config, specArg, flags, out) {
626
538
  lines.push(' drift: none — Linear workflow-state matches the spec')
627
539
  }
628
540
  lines.push(...assigneeLines(remote, projection, plan))
629
- lines.push(...descriptionDriftLines(remote, snapshot, identifier))
541
+ lines.push(...descriptionDriftLines(remote, snapshot, identifier, config))
630
542
  }
631
543
 
632
544
  out.write(lines.join('\n') + '\n')
@@ -651,8 +563,8 @@ function specSyncStatus(dir, config, specArg, flags, out) {
651
563
  * the state line has one because it is always askable, and this one is not.
652
564
  * (`.claude/rules/negative-checks.md`.)
653
565
  */
654
- function descriptionDriftLines(remote, snapshot, identifier) {
655
- if (remoteDescriptionEdited(snapshot, remote) !== true) return []
566
+ function descriptionDriftLines(remote, snapshot, identifier, config) {
567
+ if (remoteDescriptionEdited(snapshot, remote, config) !== true) return []
656
568
  const lines = [
657
569
  ` drift: ${identifier}'s description was edited on Linear since the last push`,
658
570
  ' (repo wins on next push — read it before pushing)',
@@ -762,48 +674,8 @@ function specSyncVerify(dir, config, specArg, flags, out) {
762
674
  return 0
763
675
  }
764
676
 
765
- /**
766
- * The verify comparison itself, as reportable lines.
767
- *
768
- * Split out of `specSyncVerify` so `apply` runs the SAME check on the read-back
769
- * it does itself, rather than a second implementation that could disagree about
770
- * what counts as lost text.
771
- */
772
- function verifyLines(snapshotDir, config, stored, identifier) {
773
- const projection = projectionOf(snapshotDir, config)
774
- const checks = []
775
- if (typeof stored.issue === 'string') checks.push(['issue', projection.description, stored.issue])
776
- for (const [ref, text] of Object.entries(stored.subIssues || {})) {
777
- const sub = projection.subIssues.find((s) => s.ref === ref)
778
- if (!sub) {
779
- checks.push([`sub-issue ${ref}`, null, text])
780
- continue
781
- }
782
- checks.push([`sub-issue ${ref}`, sub.goal, text])
783
- }
784
-
785
- const lines = [`spec-sync verify: ${identifier}`]
786
- let bad = 0
787
- for (const [label, sent, got] of checks) {
788
- if (sent == null) {
789
- lines.push(` ?? ${label}: read back, but the projection has no such phase — stale ref?`)
790
- bad++
791
- continue
792
- }
793
- const r = compareStored(sent, got)
794
- if (r.ok) continue
795
- bad++
796
- lines.push(
797
- ` !! ${label}: the tracker stored different text — ${Math.abs(r.lost)} character(s) ` +
798
- `${r.lost > 0 ? 'lost' : 'added'}, first difference at ${r.at}`,
799
- ` sent: …${r.sentContext}…`,
800
- ` stored: …${r.storedContext}…`,
801
- )
802
- }
803
- if (!bad) lines.push(` ${checks.length} description(s) round-tripped intact`)
804
- else lines.push(' the repo is unchanged and still correct; re-push to overwrite the mirror')
805
- return lines
806
- }
677
+ // The read-back comparison rendering is the kit's (`specHelpers.verifyLines`).
678
+ const verifyLines = specHelpers.verifyLines
807
679
 
808
680
  /**
809
681
  * `spec-sync doctor [--json]` — is this project set up, across every layer?
@@ -1281,7 +1153,7 @@ async function specSyncReleased(dir, config, rangeArg, flags, out) {
1281
1153
  // Titles are an ENRICHMENT: the scan itself is offline. No key, the MCP
1282
1154
  // transport, or a read failure degrades to bare refs — never a failure.
1283
1155
  const key = resolveApiKey(config, flags.env || process.env)
1284
- const transport = flags.via || (config.apply && config.apply.transport) || (key.ok ? 'api' : 'mcp')
1156
+ const transport = resolveTransport(flags, config, key.ok)
1285
1157
  let titles = null
1286
1158
  let titleNote = ''
1287
1159
  if (report.tickets.length && transport === 'api') {
@@ -1384,7 +1256,7 @@ async function specSyncStage(dir, config, stageKey, rangeArg, flags, out) {
1384
1256
  })
1385
1257
 
1386
1258
  const key = resolveApiKey(config, flags.env || process.env)
1387
- const transport = flags.via || (config.apply && config.apply.transport) || (key.ok ? 'api' : 'mcp')
1259
+ const transport = resolveTransport(flags, config, key.ok)
1388
1260
  const applying = Boolean(flags.apply)
1389
1261
 
1390
1262
  if (applying && transport !== 'api') {
@@ -1660,7 +1532,7 @@ async function specSyncRetarget(dir, config, flags, out) {
1660
1532
  }
1661
1533
 
1662
1534
  const key = resolveApiKey(config, flags.env || process.env)
1663
- const transport = flags.via || (config.apply && config.apply.transport) || (key.ok ? 'api' : 'mcp')
1535
+ const transport = resolveTransport(flags, config, key.ok)
1664
1536
 
1665
1537
  // Linear's MCP `get_team` does not return the team key (observed 2026-09-02),
1666
1538
  // so the one fact detection needs is unavailable there. Report what IS known
@@ -1810,7 +1682,7 @@ async function spotCheck({ dir, config, plan, adapter, oldKey, newKey }) {
1810
1682
  */
1811
1683
  async function specSyncStates(dir, config, flags, out) {
1812
1684
  const key = resolveApiKey(config, flags.env || process.env)
1813
- const transport = flags.via || (config.apply && config.apply.transport) || (key.ok ? 'api' : 'mcp')
1685
+ const transport = resolveTransport(flags, config, key.ok)
1814
1686
 
1815
1687
  if (transport === 'mcp') {
1816
1688
  if (flags.json) {
@@ -2041,7 +1913,7 @@ async function specSyncReattach(dir, config, specArg, flags, out) {
2041
1913
  const phaseTitle = String(ph.name || '').trim()
2042
1914
  const hits = children.filter((c) => String(c.title || '').trim() === phaseTitle)
2043
1915
  if (hits.length === 1) {
2044
- stampSubIssueId(snapshotDir, file, hits[0].identifier)
1916
+ stampSubIssueId(snapshotDir, file, hits[0].identifier, config)
2045
1917
  lines.push(` phase ${ref} → ${hits[0].identifier}`)
2046
1918
  } else if (hits.length > 1) {
2047
1919
  // Refused individually, never for the whole run: the spec issue is
@@ -2063,7 +1935,7 @@ async function specSyncReattach(dir, config, specArg, flags, out) {
2063
1935
 
2064
1936
  async function specSyncProjects(dir, config, flags, out) {
2065
1937
  const key = resolveApiKey(config, flags.env || process.env)
2066
- const transport = flags.via || (config.apply && config.apply.transport) || (key.ok ? 'api' : 'mcp')
1938
+ const transport = resolveTransport(flags, config, key.ok)
2067
1939
  const teamId = (config.linear && config.linear.teamId) || null
2068
1940
 
2069
1941
  const degrade = (reason) => {
@@ -2227,7 +2099,7 @@ async function specSyncList(dir, config, flags, out) {
2227
2099
  }
2228
2100
 
2229
2101
  const key = resolveApiKey(config, flags.env || process.env)
2230
- const transport = flags.via || (config.apply && config.apply.transport) || (key.ok ? 'api' : 'mcp')
2102
+ const transport = resolveTransport(flags, config, key.ok)
2231
2103
  const teamId = (config.linear && config.linear.teamId) || null
2232
2104
 
2233
2105
  const degrade = (reason) => {
@@ -2627,209 +2499,73 @@ function describeRefusal(error) {
2627
2499
  }
2628
2500
 
2629
2501
  /**
2630
- * Apply a plan, and say what landed even when it throws.
2631
- *
2632
- * A thin wrapper, because the caller has to answer a question the inner
2633
- * function's `result` knows and a thrown error does not carry: **was anything
2634
- * written?** That decides whether re-running is a resume or a fresh start, and
2635
- * the failure line claimed `ids stamped so far are saved` on both paths —
2636
- * including the one where nothing had been created.
2637
- *
2638
- * Counted from what was actually stamped, never inferred from which call
2639
- * failed: the second reading goes wrong the moment the order changes.
2502
+ * Apply one spec's plan over the API adapter. The orchestration — ordering,
2503
+ * stamping, orphan accounting, twin guard, read-back verify, record — is the
2504
+ * kit's (`provider-kit/src/apply.js`); the ops below are what is Linear's:
2505
+ * workflow state folds into each create/update payload as a stateId, nulls are
2506
+ * stripped (`withoutNull`) except the assignee clear, and the refusal texts
2507
+ * name Linear and its commands.
2640
2508
  */
2641
- async function applyOneSpec(args) {
2642
- const progress = {}
2643
- try {
2644
- return await applyOneSpecInner({ ...args, progress })
2645
- } catch (error) {
2646
- const r = progress.result
2647
- if (error && typeof error === 'object' && error.stamped === undefined) {
2648
- error.stamped = r ? (r.issue ? 1 : 0) + Object.keys(r.subIssues || {}).length : 0
2649
- // THE ONE CASE A RE-RUN MAKES WORSE. `created` is what Linear holds;
2650
- // `stamped` is what the repo recorded. They part company when a create
2651
- // lands and its stamp cannot be written — and then the next plan still
2652
- // reads the spec as unlinked, so re-running mints a SECOND issue beside a
2653
- // perfectly good one. The identifiers travel out so the caller can name
2654
- // them and send the reader to `reattach` instead.
2655
- error.created = progress.created || []
2656
- error.orphans = error.created.slice(error.stamped)
2657
- }
2658
- throw error
2659
- }
2660
- }
2661
-
2662
- async function applyOneSpecInner({ dir, config, snapshotDir, plan, adapter, teamId, project, states, progress, forceNew = false }) {
2663
- const overviewFile = (config.snapshot && config.snapshot.overviewFile) || '00-overview.md'
2664
- const identifier = linkedIdentifier(path.join(snapshotDir, overviewFile))
2665
- const lines = []
2666
- const result = { issue: null, subIssues: {} }
2667
- // Handed out immediately, so a throw from anywhere below still reports what
2668
- // had been stamped by the time it happened.
2669
- if (progress) progress.result = result
2509
+ async function applyOneSpec({ dir, config, snapshotDir, plan, adapter, teamId, project, states, forceNew = false }) {
2670
2510
  const stateId = (bucket) => (bucket ? stateIdFor(bucket, config, states) : null)
2671
-
2672
- // Resolve every state id BEFORE the first write, so a bad config.states value
2673
- // cannot strand the spec mid-apply.
2674
- const wanted = new Set()
2675
- if (plan.issue && plan.issue.state) wanted.add(plan.issue.state)
2676
- for (const s of (plan.subIssues && plan.subIssues.create) || []) if (s.state) wanted.add(s.state)
2677
- for (const s of (plan.subIssues && plan.subIssues.update) || []) if (s.state) wanted.add(s.state)
2678
- for (const bucket of wanted) stateId(bucket)
2679
-
2680
- // 1. The spec issue. No identifier yet → this push mints it.
2681
- let parentId = null
2682
- if (!identifier) {
2683
- // REFUSE TO MINT A TWIN. This is the guard SKS-284 needed: the push was
2684
- // creating because the spec read as unlinked, while SKS-283 sat unclaimed
2685
- // with exactly this title. An EXACT match held by no spec is a positive
2686
- // signal that the issue already exists.
2687
- //
2688
- // WHAT WOULD FOOL A FUZZY VERSION: a title that merely reads similarly.
2689
- // Being wrong here BLOCKS a legitimate push, so a near-match must never
2690
- // count (`.claude/rules/negative-checks.md` rule 1) — and the cost, a
2691
- // renamed spec that is not recognised, is answered by `reattach --to`.
2692
- //
2693
- // Only on a MINT. An update already has its issue, and checking one would
2694
- // find its own mirror.
2695
- if (!forceNew && adapter.searchIssues) {
2696
- const wanted = String(plan.title || readSnapshot(snapshotDir, config).title || '').trim()
2697
- if (wanted) {
2698
- let found = []
2699
- try {
2700
- found = (await adapter.searchIssues({ query: wanted, teamId })) || []
2701
- } catch {
2702
- // A search we could not run is not evidence of an orphan. Carry on and
2703
- // mint — the cannot-tell case goes to the harmless branch, which here
2704
- // is the one that does the work the caller asked for (rule 4).
2705
- found = []
2706
- }
2707
- const claimed = new Set(listSpecs(dir, config).map((sp) => sp.identifier).filter(Boolean))
2708
- const twin = found.find(
2709
- (i) => i && i.identifier && !claimed.has(i.identifier) && String(i.title || '').trim() === wanted,
2710
- )
2711
- if (twin) {
2712
- throw new Error(
2713
- `${twin.identifier} is already titled "${wanted}" and no spec claims it — ` +
2714
- `adopt it with \`spec-sync reattach ${path.basename(snapshotDir)} --to ${twin.identifier}\`, ` +
2715
- 'or pass --force-new to create a second',
2716
- )
2717
- }
2718
- }
2719
- }
2720
- const created = await adapter.createIssue(withoutNull({
2721
- title: readSnapshot(snapshotDir, config).title,
2722
- teamId,
2723
- projectId: project || (config.linear && config.linear.projectId) || null,
2724
- description: plan.issue && plan.issue.description,
2725
- stateId: stateId(plan.issue && plan.issue.state),
2726
- // Assert only. An issue being minted has no assignee to retract, so
2727
- // `withoutNull` dropping a null here is exactly right.
2728
- assigneeId: (plan.issue && plan.issue.assignee) || null,
2729
- }))
2730
- if (!created || !created.identifier) throw new Error('Linear returned no issue for the spec create')
2731
- parentId = created.id
2732
- // NOTED BEFORE IT IS STAMPED. The stamp can fail — a read-only tree, a
2733
- // permission error — and then this identifier exists in Linear with nothing
2734
- // in the repo pointing at it. Recorded here so the failure can name it.
2735
- if (progress) (progress.created = progress.created || []).push(created.identifier)
2736
- // Stamped NOW: an interrupt after this point must not mint a second issue.
2737
- writeFrontmatter(snapshotDir, config, { linear_identifier: created.identifier, linear_url: created.url })
2738
- result.issue = { id: created.id, identifier: created.identifier, url: created.url }
2739
- lines.push(` issue created: ${created.identifier}`)
2740
- } else {
2741
- const existing = await adapter.readIssue(identifier)
2742
- if (!existing || !existing.id) throw new Error(`no Linear issue found for ${identifier}`)
2743
- parentId = existing.id
2744
- result.issue = { id: existing.id, identifier: existing.identifier, url: existing.url }
2745
-
2746
- // SOMEONE ELSE EDITED THE DESCRIPTION SINCE WE LAST PUSHED, and this write
2747
- // is about to replace it. Said here because this is the one moment the
2748
- // engine has both halves in hand for free — the read-back it already does,
2749
- // and the snapshot on disk — so no extra round trip buys the warning.
2750
- //
2751
- // A WARNING AND NEVER A REFUSAL. One-way sync means the repo wins, and that
2752
- // is not in question; what was wrong was winning silently. Turning this
2753
- // into a gate would stop a legitimate push over a typo fix, and the whole
2754
- // point is that only a person can judge which it was. The exit code is
2755
- // untouched, deliberately.
2756
- if (remoteDescriptionEdited(readBase(dir, identifier, config), existing) === true) {
2757
- lines.push(
2758
- ` !! ${identifier}'s description was edited on Linear since the last push — this replaces it`,
2759
- )
2760
- }
2761
- if (plan.issue) {
2511
+ const ops = {
2512
+ prevalidateStates: (buckets) => {
2513
+ for (const bucket of buckets) stateId(bucket)
2514
+ },
2515
+ searchTwin: (title) => adapter.searchIssues({ query: title, teamId }),
2516
+ twinAdvice: (twin, wanted, specName) =>
2517
+ `${twin.identifier} is already titled "${wanted}" and no spec claims it — ` +
2518
+ `adopt it with \`spec-sync reattach ${specName} --to ${twin.identifier}\`, ` +
2519
+ 'or pass --force-new to create a second',
2520
+ missingIssueMessage: (identifier) => `no Linear issue found for ${identifier}`,
2521
+ remoteEditedLine: (identifier) =>
2522
+ ` !! ${identifier}'s description was edited on Linear since the last push — this replaces it`,
2523
+ mintIssue: async ({ title, issue }) => {
2524
+ const created = await adapter.createIssue(withoutNull({
2525
+ title,
2526
+ teamId,
2527
+ projectId: project || (config.linear && config.linear.projectId) || null,
2528
+ description: issue && issue.description,
2529
+ stateId: stateId(issue && issue.state),
2530
+ // Assert only. An issue being minted has no assignee to retract, so
2531
+ // `withoutNull` dropping a null here is exactly right.
2532
+ assigneeId: (issue && issue.assignee) || null,
2533
+ }))
2534
+ if (!created || !created.identifier) throw new Error('Linear returned no issue for the spec create')
2535
+ return created
2536
+ },
2537
+ updateIssue: async (existing, issue) => {
2762
2538
  const updates = withoutNull({
2763
- description: plan.issue.description,
2764
- stateId: stateId(plan.issue.state),
2539
+ description: issue.description,
2540
+ stateId: stateId(issue.state),
2765
2541
  })
2766
2542
  // APPLIED AFTER `withoutNull`, and that ordering is the whole point: null
2767
2543
  // is MEANINGFUL for this field — it is how Linear unassigns an issue — so
2768
2544
  // passing it through the stripper would drop exactly the clear that
2769
- // finishing a spec depends on, and the mirror would keep a finished spec
2770
- // assigned forever. The plan only carries the key when there is something
2771
- // to say, so `in` is the test, not truthiness.
2772
- if ('assignee' in plan.issue) updates.assigneeId = plan.issue.assignee ?? null
2545
+ // finishing a spec depends on. The plan only carries the key when there
2546
+ // is something to say, so `in` is the test, not truthiness.
2547
+ if ('assignee' in issue) updates.assigneeId = issue.assignee ?? null
2773
2548
  await adapter.updateIssue(existing.id, updates)
2774
- lines.push(` issue updated: ${identifier}`)
2775
- }
2549
+ },
2550
+ mintSubIssue: async (parentId, sub) => {
2551
+ const created = await adapter.createSubIssue(parentId, withoutNull({
2552
+ title: sub.name,
2553
+ teamId,
2554
+ description: sub.goal,
2555
+ stateId: stateId(sub.state),
2556
+ }))
2557
+ if (!created || !created.identifier) throw new Error(`Linear returned no issue for sub-issue ${sub.ref}`)
2558
+ return created
2559
+ },
2560
+ updateSubIssue: async (sub) => {
2561
+ await adapter.updateIssue(sub.id, withoutNull({
2562
+ title: sub.name,
2563
+ description: sub.goal,
2564
+ stateId: stateId(sub.state),
2565
+ }))
2566
+ },
2776
2567
  }
2777
-
2778
- // 2. Sub-issue creates — each stamped as it lands, for the same reason.
2779
- for (const sub of (plan.subIssues && plan.subIssues.create) || []) {
2780
- const created = await adapter.createSubIssue(parentId, withoutNull({
2781
- title: sub.name,
2782
- teamId,
2783
- description: sub.goal,
2784
- stateId: stateId(sub.state),
2785
- }))
2786
- if (!created || !created.identifier) throw new Error(`Linear returned no issue for sub-issue ${sub.ref}`)
2787
- if (progress) (progress.created = progress.created || []).push(created.identifier)
2788
- const file = resolvePhaseFile(snapshotDir, sub.ref)
2789
- if (!file) throw new Error(`no phase file for ref ${sub.ref}`)
2790
- stampSubIssueId(snapshotDir, file, created.identifier)
2791
- result.subIssues[sub.ref] = created.identifier
2792
- lines.push(` sub-issue created: ${sub.ref} → ${created.identifier}`)
2793
- }
2794
-
2795
- // 3. Sub-issue updates — already linked, nothing to stamp.
2796
- //
2797
- // Keyed by REF, never by id: step 4 matches the read-back against the
2798
- // projection, which keys phases by ref. Keying an update by its id made every
2799
- // updated sub-issue report as a stale ref on every push. A plan written before
2800
- // updates carried a ref still resolves — by id, off the projection.
2801
- const refById = new Map()
2802
- for (const s of projectionOf(snapshotDir, config).subIssues || []) {
2803
- if (s.id != null) refById.set(String(s.id), s.ref)
2804
- }
2805
- for (const sub of (plan.subIssues && plan.subIssues.update) || []) {
2806
- await adapter.updateIssue(sub.id, withoutNull({
2807
- title: sub.name,
2808
- description: sub.goal,
2809
- stateId: stateId(sub.state),
2810
- }))
2811
- result.subIssues[sub.ref || refById.get(String(sub.id)) || sub.id] = sub.id
2812
- lines.push(` sub-issue updated: ${sub.id}`)
2813
- }
2814
-
2815
- // 4. Read back what Linear stored and run the SAME check `verify` runs.
2816
- const stored = { issue: undefined, subIssues: {} }
2817
- if (result.issue) {
2818
- const back = await adapter.readIssue(result.issue.id)
2819
- if (back && typeof back.description === 'string') stored.issue = back.description
2820
- }
2821
- for (const [ref, id] of Object.entries(result.subIssues)) {
2822
- const back = await adapter.readIssue(id)
2823
- if (back && typeof back.description === 'string') stored.subIssues[ref] = back.description
2824
- }
2825
- const verify = verifyLines(snapshotDir, config, stored, result.issue ? result.issue.identifier : identifier)
2826
- lines.push(...verify.map((l) => ` ${l}`))
2827
- const lost = verify.some((l) => l.includes('!!') || l.includes('??'))
2828
-
2829
- // 5. Record the snapshot from the now-stamped files, so the next push is empty.
2830
- const file = recordPush({ dir, snapshotDir, identifier: specIdentifier(snapshotDir, config), config })
2831
- lines.push(` snapshot: ${path.relative(dir, file)}`)
2832
- return { result, lines, lost }
2568
+ return applySpecPlan({ dir, config, snapshotDir, plan, adapter, ops, forceNew })
2833
2569
  }
2834
2570
 
2835
2571
  /**
@@ -2966,7 +2702,7 @@ async function specSyncWhoami(dir, config, flags, out) {
2966
2702
  */
2967
2703
  async function specSyncUsers(dir, config, query, flags, out) {
2968
2704
  const key = resolveApiKey(config, flags.env || process.env)
2969
- const transport = flags.via || (config.apply && config.apply.transport) || (key.ok ? 'api' : 'mcp')
2705
+ const transport = resolveTransport(flags, config, key.ok)
2970
2706
 
2971
2707
  if (transport === 'mcp') {
2972
2708
  if (flags.json) {
@@ -3095,7 +2831,7 @@ async function specSyncApply(dir, config, specArg, flags, out) {
3095
2831
  }
3096
2832
 
3097
2833
  const key = resolveApiKey(config, flags.env || process.env)
3098
- const transport = flags.via || (config.apply && config.apply.transport) || (key.ok ? 'api' : 'mcp')
2834
+ const transport = resolveTransport(flags, config, key.ok)
3099
2835
 
3100
2836
  if (transport === 'mcp') {
3101
2837
  if (bulk) {
@@ -3783,7 +3519,7 @@ async function specSyncPreserve(dir, config, specArg, flags, out) {
3783
3519
  }
3784
3520
 
3785
3521
  const key = resolveApiKey(config, flags.env || process.env)
3786
- const transport = flags.via || (config.apply && config.apply.transport) || (key.ok ? 'api' : 'mcp')
3522
+ const transport = resolveTransport(flags, config, key.ok)
3787
3523
 
3788
3524
  if (transport === 'mcp' && description == null) {
3789
3525
  return say({
@@ -3921,47 +3657,8 @@ async function specSyncPreserve(dir, config, specArg, flags, out) {
3921
3657
  })
3922
3658
  }
3923
3659
 
3924
- // Read stdin to completion (for `--stdin`).
3925
- function readAllStdin(input) {
3926
- return new Promise((resolve, reject) => {
3927
- let data = ''
3928
- input.setEncoding('utf-8')
3929
- input.on('data', (chunk) => (data += chunk))
3930
- input.on('end', () => resolve(data))
3931
- input.on('error', reject)
3932
- })
3933
- }
3660
+ // `readAllStdin` and `promptHidden` come from the provider kit (`src/prompt.js`).
3934
3661
 
3935
- // Prompt on a TTY with the input hidden. `_writeToOutput` is readline's own echo
3936
- // hook — filtering it is what keeps the key off the screen (and out of a
3937
- // screen-shared terminal or a recorded session).
3938
- //
3939
- // READLINE OWNS THE PROMPT, deliberately. Writing it ourselves and then starting
3940
- // the interface loses it: readline clears from the cursor to the end of the
3941
- // screen (`ESC[0J`) before its first redraw, so the prompt was wiped the instant
3942
- // it appeared and the user was left staring at a blank line while the process
3943
- // waited for a key — indistinguishable from a hang.
3944
- //
3945
- // The hook is assigned BEFORE `question`, so the very first redraw goes through
3946
- // it. readline hands it `prompt + what has been typed`; re-writing only the
3947
- // prompt is what keeps the key hidden while the prompt survives every redraw.
3948
- function promptHidden(question, input, out) {
3949
- const readline = require('node:readline')
3950
- return new Promise((resolve) => {
3951
- // `out`, never `process.stdout`: they are the same stream in production, and
3952
- // hardcoding one half meant readline cleared a screen the prompt had not
3953
- // been written to under test — the split that hid this bug from the suite.
3954
- const rl = readline.createInterface({ input, output: out, terminal: true })
3955
- rl._writeToOutput = (s) => {
3956
- if (s.includes(question)) out.write(question)
3957
- }
3958
- rl.question(question, (answer) => {
3959
- out.write('\n')
3960
- rl.close()
3961
- resolve(answer)
3962
- })
3963
- })
3964
- }
3965
3662
 
3966
3663
  async function specSync(rest, io = {}) {
3967
3664
  const out = io.out || process.stdout