@skitterbyte/skitterspec-linear 19.3.0 → 19.4.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 (60) hide show
  1. package/assets/claude-md-section.md +20 -1
  2. package/assets/core/env.config.json.example +1 -0
  3. package/assets/core/env.config.md +90 -6
  4. package/assets/core/linear.config.json.example +2 -2
  5. package/assets/core/linear.config.md +49 -16
  6. package/assets/hooks/main-guard.cjs +18 -2
  7. package/assets/hooks/review-gate.cjs +19 -2
  8. package/assets/rules/commit-trailers.md +24 -1
  9. package/assets/rules/spec-planning.md +81 -18
  10. package/assets/rules/spec-reports.md +1 -1
  11. package/assets/skills/spec/SKILL.md +55 -2
  12. package/assets/skills/spec-bug/SKILL.md +36 -3
  13. package/assets/skills/spec-cancel/SKILL.md +37 -0
  14. package/assets/skills/spec-claim/SKILL.md +41 -2
  15. package/assets/skills/spec-complete/SKILL.md +115 -0
  16. package/assets/skills/spec-hotfix/SKILL.md +51 -4
  17. package/assets/skills/spec-incident/SKILL.md +22 -0
  18. package/assets/skills/spec-linear-setup/SKILL.md +23 -1
  19. package/assets/skills/spec-next/SKILL.md +12 -5
  20. package/assets/skills/spec-push/SKILL.md +22 -0
  21. package/assets/skills/spec-review/SKILL.md +34 -0
  22. package/assets/skills/spec-start/SKILL.md +50 -3
  23. package/assets/skills/spec-status/SKILL.md +18 -3
  24. package/assets/skills/spec-sync/SKILL.md +1 -0
  25. package/assets/skills/spec-to-main/SKILL.md +47 -1
  26. package/package.json +1 -1
  27. package/src/cli.js +1091 -39
  28. package/src/env/base.js +104 -0
  29. package/src/env/config.js +75 -3
  30. package/src/env/disposition.js +62 -0
  31. package/src/env/handoff.js +80 -0
  32. package/src/env/host.js +262 -0
  33. package/src/env/hotfix.js +225 -0
  34. package/src/env/hotfixland.js +103 -9
  35. package/src/env/inflight.js +95 -0
  36. package/src/env/integrate.js +130 -4
  37. package/src/env/mainguard.js +6 -0
  38. package/src/env/phases.js +28 -0
  39. package/src/env/provision.js +18 -6
  40. package/src/env/resolve.js +108 -9
  41. package/src/env/serve.js +6 -1
  42. package/src/env/specstate.js +101 -0
  43. package/src/env/teardown.js +42 -0
  44. package/src/vendor/linear/cli-sync.js +55 -6
  45. package/src/vendor/linear/config.js +27 -21
  46. package/src/vendor/linear/doctor.js +2 -0
  47. package/src/vendor/provider-kit/index.js +4 -0
  48. package/src/vendor/provider-kit/src/apply.js +49 -4
  49. package/src/vendor/provider-kit/src/assignment.js +78 -1
  50. package/src/vendor/provider-kit/src/config.js +34 -1
  51. package/src/vendor/provider-kit/src/list-rows.js +35 -11
  52. package/src/vendor/provider-kit/src/released.js +14 -1
  53. package/src/vendor/provider-kit/src/specs.js +4 -2
  54. package/src/vendor/provider-kit/src/splice.js +64 -0
  55. package/src/vendor/provider-kit/src/status.js +137 -0
  56. package/src/vendor/sync-core/index.js +14 -1
  57. package/src/vendor/sync-core/src/compare.js +17 -5
  58. package/src/vendor/sync-core/src/normalize.js +50 -7
  59. package/src/vendor/sync-core/src/push.js +26 -2
  60. package/src/vendor/sync-core/src/summary.js +257 -0
@@ -0,0 +1,104 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * `spec-env base` — which branch skitterspec will fork from and land onto, and
5
+ * which in-flight specs forked from an older one.
6
+ *
7
+ * Pure: the CLI fetches, reads refs and computes merge-bases, and hands the
8
+ * facts in. Nothing here touches git, and nothing here edits config — pinning
9
+ * is a hand edit of `baseBranch`, deliberately without a verb (the pin is the
10
+ * exception, so it does not get one).
11
+ */
12
+
13
+ const HOW = Object.freeze({
14
+ pin: 'pinned by baseBranch',
15
+ pattern: 'newest match',
16
+ 'origin-head': 'origin/HEAD',
17
+ local: 'local branch',
18
+ fallback: 'nothing detected — default',
19
+ })
20
+
21
+ /**
22
+ * Which match a spec branch forked from: the one whose merge-base with the
23
+ * branch is newest. `matches` is newest-first; `mergeBase(name)` returns a sha
24
+ * or null; `isAncestor(a, b)` is true when `a` is an ancestor of (or equal to) `b`.
25
+ *
26
+ * WHAT WOULD FOOL THIS: a release candidate cut from a base that already holds
27
+ * the old rc's tip. Both merge-bases are then the same commit and nothing in
28
+ * the history says which one the spec was forked from — so a tie goes to the
29
+ * NEWER match, and the spec is not reported as behind. Being wrong that way
30
+ * costs a row that should have printed; the rebase onto the newer match is a
31
+ * no-op for exactly the commits the two share, so nothing lands wrong.
32
+ */
33
+ function forkMatch(matches, mergeBase, isAncestor) {
34
+ let best = null
35
+ for (const name of matches) {
36
+ const sha = mergeBase(name)
37
+ if (!sha) continue
38
+ // Strictly newer only: an equal merge-base keeps the newer match already held.
39
+ if (!best || (sha !== best.sha && isAncestor(best.sha, sha))) best = { name, sha }
40
+ }
41
+ return best ? best.name : null
42
+ }
43
+
44
+ /**
45
+ * Build the report. `facts`:
46
+ * { pattern, remote, base, how, fetch: { ok, reason } | null,
47
+ * matches: [{ name, date }] (newest first), forks: [{ spec, forkedFrom }] }
48
+ * Returns `{ json, lines }`; the CLI prints one of them and always exits 0.
49
+ */
50
+ function planBaseReport(facts) {
51
+ const { pattern, remote, base, how } = facts
52
+ const matches = facts.matches || []
53
+ const fetch = facts.fetch || null
54
+ // Behind = forked from a match that is not the base. Only meaningful when the
55
+ // pattern chose the base: a pin is a deliberate choice of base, and the
56
+ // matches beside it are not competing for the role.
57
+ const stale =
58
+ how === 'pattern' && base
59
+ ? (facts.forks || []).filter((f) => f.forkedFrom && f.forkedFrom !== base)
60
+ : []
61
+
62
+ const json = {
63
+ base: base || null,
64
+ how,
65
+ pattern: pattern || null,
66
+ remote,
67
+ fetch,
68
+ matches: matches.map((m) => ({ ...m, base: m.name === base })),
69
+ stale,
70
+ }
71
+
72
+ const lines = []
73
+ if (!pattern) {
74
+ lines.push(`spec-env base: ${base} (${HOW[how]})`)
75
+ return { json, lines }
76
+ }
77
+
78
+ if (base) lines.push(`spec-env base: ${base} (${HOW[how]}${how === 'pin' ? ` — ${pattern} not used` : ` for ${pattern}`})`)
79
+ else lines.push(`spec-env base: none — no branch on ${remote} matches ${pattern}`)
80
+
81
+ if (fetch) {
82
+ lines.push(
83
+ fetch.ok
84
+ ? ` fetched ${remote}`
85
+ : ` fetch from ${remote} failed${fetch.reason ? ` (${fetch.reason})` : ''} — listing the refs already here`,
86
+ )
87
+ }
88
+
89
+ if (matches.length) {
90
+ const width = Math.max(...matches.map((m) => m.name.length))
91
+ for (const m of matches) {
92
+ const mark = m.name === base ? (how === 'pin' ? ' ← base (pin)' : ' ← base') : ''
93
+ lines.push(` ${m.name.padEnd(width)} ${m.date || ''}${mark}`.trimEnd())
94
+ }
95
+ }
96
+
97
+ if (stale.length) {
98
+ lines.push(' forked from an older match:')
99
+ for (const s of stale) lines.push(` ${s.spec} · forked from ${s.forkedFrom}`)
100
+ }
101
+ return { json, lines }
102
+ }
103
+
104
+ module.exports = { forkMatch, planBaseReport }
package/src/env/config.js CHANGED
@@ -41,13 +41,21 @@
41
41
  * // spec alongside its own folder (provider-neutral; {slug} and
42
42
  * // {identifier} expand); empty = the spec folder only
43
43
  * baseBranch: "", // "" = auto-detect (origin/HEAD → main → master)
44
+ * baseBranchPattern: "", // glob over remote branch names; newest match
45
+ * // by commit date is the base (rolling release-candidate)
46
+ * land: { strategy, remote, draft, specDocs }, // how a branch lands:
47
+ * // "ff" (default, trunk-based local fast-forward) or "pr"
48
+ * // (push + pull request; base moves when the host merges)
44
49
  * guards: { refuseTeardownIfDirty, refuseTeardownIfUnpushed },
45
50
  * teardown: { deleteRemoteBranch },
46
51
  * live: { migrations: [ "glob", ... ] } // migration globs → `live take`
47
52
  * // refuses a branch that changes them (code-only v1)
48
- * hotfix: { bump, cherryPickMain, targets } // `hotfix land`: patch-bump the
49
- * // deploy tag, also cherry-pick onto the base branch (main), and
50
- * // onto any extra base tags in `targets` (test/demo lines)
53
+ * hotfix: { bump, cherryPickMain, targets, releaseWith, releaseBranch, tag }
54
+ * // `hotfix land`: patch-bump the deploy tag, also cherry-pick
55
+ * // onto the base branch (main), and onto any extra base tags in
56
+ * // `targets` (test/demo lines). `releaseBranch` makes the hotfix
57
+ * // branch-based: it forks from <remote>/<releaseBranch> instead
58
+ * // of a tag; `tag` keeps (true) or drops the release-tag cut
51
59
  * }
52
60
  */
53
61
 
@@ -206,6 +214,26 @@ const DEFAULT_CONFIG = Object.freeze({
206
214
  spec: Object.freeze({ companionPaths: Object.freeze([]) }),
207
215
  // Integration base branch. Empty = auto-detect (origin/HEAD → main → master).
208
216
  baseBranch: '',
217
+ // A glob over the remote's branch names (`"20??/Q?"`) for a base that rolls:
218
+ // the newest match by commit date is the base, so cutting the next release
219
+ // candidate is all it takes to move every spec onto it. An explicit
220
+ // `baseBranch` still wins. Empty = off, and resolution is exactly as before.
221
+ baseBranchPattern: '',
222
+ // How a finished branch reaches the base branch. `strategy: "ff"` (the
223
+ // default) is trunk-based landing exactly as it has always been: rebase, then
224
+ // a local `merge --ff-only` — nothing changes for an installed repo on
225
+ // upgrade. `"pr"` lands by pushing the branch and opening a pull request on
226
+ // the host: the base branch moves only when the host merges, so integrate's
227
+ // plan ends in a consent-gated push (the hotfix pattern: already-pushed is
228
+ // honoured, `--push` is the recorded yes, otherwise the plan holds) and the
229
+ // project's `afterLand` commands are deferred to the completion run that
230
+ // follows the merge. `remote` names where the branch is pushed. `draft`
231
+ // opens mid-spec PRs as drafts (a draft cannot be merged, so nothing
232
+ // downstream can close a ticket early). `specDocs` decides where a spec
233
+ // DOCUMENT lands under "pr": "trunk" keeps today's authoring land (needs
234
+ // direct push for docs), "branch" has the spec ride the feature branch and
235
+ // land with the work's PR.
236
+ land: Object.freeze({ strategy: 'ff', remote: 'origin', draft: true, specDocs: 'trunk' }),
209
237
  // `mainIsLandingZone` defaults ON wherever isolation is configured, matching
210
238
  // the review gate's precedent: the push toward not working on the base branch
211
239
  // is the normal path, and stepping off it is the deliberate act. That does
@@ -301,11 +329,19 @@ const DEFAULT_CONFIG = Object.freeze({
301
329
  // `releaseWith` is a project's own release command, run in the hotfix
302
330
  // worktree in place of the built-in tagger — e.g. skittership's
303
331
  // `node scripts/release-hotfix.cjs --json`. Empty (the default) = built-in.
332
+ // `releaseBranch` names a release LINE that is a branch rather than a tag
333
+ // (e.g. "master", where prod is whatever master holds): the hotfix forks from
334
+ // the remote's head of it and records `Base version: <branch>@<sha>`. Empty
335
+ // (the default) = today's tag-based hotfix, unchanged. `tag` (default true)
336
+ // keeps the release-tag cut; false is for a team whose deploy is driven by a
337
+ // branch merge rather than a tag.
304
338
  hotfix: Object.freeze({
305
339
  bump: 'patch',
306
340
  cherryPickMain: true,
307
341
  targets: Object.freeze([]),
308
342
  releaseWith: '',
343
+ releaseBranch: '',
344
+ tag: true,
309
345
  }),
310
346
  })
311
347
 
@@ -370,6 +406,8 @@ function defaults() {
370
406
  branch: { ...DEFAULT_CONFIG.branch },
371
407
  spec: { companionPaths: [] },
372
408
  baseBranch: DEFAULT_CONFIG.baseBranch,
409
+ baseBranchPattern: DEFAULT_CONFIG.baseBranchPattern,
410
+ land: { ...DEFAULT_CONFIG.land },
373
411
  guards: { ...DEFAULT_CONFIG.guards },
374
412
  teardown: { ...DEFAULT_CONFIG.teardown },
375
413
  review: { ...DEFAULT_CONFIG.review, reviewers: [] },
@@ -637,6 +675,15 @@ function mergeConfig(base, parsed) {
637
675
  assign(base, parsed, 'registry', 'string')
638
676
  assign(base, parsed, 'baseBranch', 'string')
639
677
 
678
+ // Dropped rather than thrown on, like every field here — and dropping is the
679
+ // safe direction: an unusable pattern resolves the base exactly as an unset
680
+ // one does. Whitespace and `..` can never name a branch, so a pattern holding
681
+ // either is a typo, not a glob.
682
+ if (typeof parsed.baseBranchPattern === 'string') {
683
+ const pattern = parsed.baseBranchPattern.trim()
684
+ if (pattern && !/\s/.test(pattern) && !pattern.includes('..')) base.baseBranchPattern = pattern
685
+ }
686
+
640
687
  // Same treatment as `teardown.deleteRemoteBranch` below, for the same reason:
641
688
  // an unrecognised value falls through to the default rather than erroring or
642
689
  // being taken literally. The fallback direction matters — "worktree" is the
@@ -646,6 +693,23 @@ function mergeConfig(base, parsed) {
646
693
  base.mode = parsed.mode
647
694
  }
648
695
 
696
+ // The enums fall through to their defaults on an unrecognised value, like
697
+ // `mode` above — and the fallback direction matters the same way: "ff" is the
698
+ // conservative strategy (nothing leaves the machine), so a typo ("PR",
699
+ // "pull-request") costs a local land that was meant to be a push, never a
700
+ // push that was meant to stay local. Same for `specDocs`: "trunk" is today's
701
+ // behaviour.
702
+ if (isObject(parsed.land)) {
703
+ if (parsed.land.strategy === 'ff' || parsed.land.strategy === 'pr') {
704
+ base.land.strategy = parsed.land.strategy
705
+ }
706
+ assign(base.land, parsed.land, 'remote', 'string')
707
+ assign(base.land, parsed.land, 'draft', 'boolean')
708
+ if (parsed.land.specDocs === 'trunk' || parsed.land.specDocs === 'branch') {
709
+ base.land.specDocs = parsed.land.specDocs
710
+ }
711
+ }
712
+
649
713
  if (isObject(parsed.guards)) {
650
714
  assign(base.guards, parsed.guards, 'refuseTeardownIfDirty', 'boolean')
651
715
  assign(base.guards, parsed.guards, 'refuseTeardownIfUnpushed', 'boolean')
@@ -739,6 +803,14 @@ function mergeConfig(base, parsed) {
739
803
  assign(base.hotfix, parsed.hotfix, 'bump', 'string')
740
804
  assign(base.hotfix, parsed.hotfix, 'cherryPickMain', 'boolean')
741
805
  assign(base.hotfix, parsed.hotfix, 'releaseWith', 'string')
806
+ assign(base.hotfix, parsed.hotfix, 'tag', 'boolean')
807
+ // Trimmed, and dropped when it could never name a branch — the same
808
+ // direction as `baseBranchPattern`: unusable means unset, which is the
809
+ // tag-based flow every hotfix had before this key existed.
810
+ if (typeof parsed.hotfix.releaseBranch === 'string') {
811
+ const name = parsed.hotfix.releaseBranch.trim()
812
+ if (name && !/[\s@~^:?*[\\]/.test(name) && !name.includes('..')) base.hotfix.releaseBranch = name
813
+ }
742
814
  if (Array.isArray(parsed.hotfix.targets)) {
743
815
  base.hotfix.targets = normalizeFileList(parsed.hotfix.targets)
744
816
  }
@@ -0,0 +1,62 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * Disposition enumeration for `spec-env disposition` — the input to
5
+ * /spec-complete's PR-mode guard.
6
+ *
7
+ * Once a PR is ready, anyone can merge from the host's UI and the tracker
8
+ * closes the ticket, so readying it is the last moment skitterspec is
9
+ * guaranteed to be standing there. Before that happens, every loose end is
10
+ * ENUMERATED here and DISPOSED by the operator in the skill (tick with
11
+ * evidence · spin off as a linked ticket · drop with a recorded reason).
12
+ * Enumeration is automatic; deciding is human — the same split the review
13
+ * marks use, and like them this is information: nothing here refuses, counts
14
+ * toward a gate, or exits non-zero.
15
+ *
16
+ * Pure: the caller reads the files and hands them over, so every shape is
17
+ * unit-testable with no filesystem.
18
+ *
19
+ * @param {object} input { overview, phases: [{ file, content }] }
20
+ * @returns {object} { tasks, phases, followUps, clean }
21
+ * tasks — unticked `- [ ]` items, per phase file, with line numbers
22
+ * phases — phase-index rows whose status is not ✅
23
+ * followUps — Changelog `Follow-up surfaced:` lines (all of them: whether a
24
+ * spec was later written for one is not knowable from this file,
25
+ * so the operator reads the list rather than trusting a guess)
26
+ * clean — nothing enumerated; the guard has nothing to ask about
27
+ */
28
+ function collectDisposition(input) {
29
+ const overview = (input && input.overview) || ''
30
+ const phaseFiles = (input && Array.isArray(input.phases)) ? input.phases : []
31
+
32
+ const tasks = []
33
+ for (const { file, content } of phaseFiles) {
34
+ const lines = String(content || '').split('\n')
35
+ lines.forEach((line, i) => {
36
+ const m = line.match(/^\s*- \[ \] (.+)$/)
37
+ if (m) tasks.push({ file, line: i + 1, text: m[1].trim() })
38
+ })
39
+ }
40
+
41
+ // Phase-index rows: | <n> | <title> | <status> | [<file>](<file>) | — only
42
+ // rows whose status cell is not ✅. The index is the overview's summary of
43
+ // the phase files, so a row here and no unticked tasks usually means the
44
+ // index lagged; both are listed and the operator reconciles.
45
+ const phases = []
46
+ for (const line of overview.split('\n')) {
47
+ const m = line.match(/^\|\s*(\d+)\s*\|\s*(.+?)\s*\|\s*([^|]+?)\s*\|\s*\[([^\]]+)\]/)
48
+ if (m && !m[3].includes('✅')) {
49
+ phases.push({ n: Number(m[1]), title: m[2], status: m[3].trim(), file: m[4] })
50
+ }
51
+ }
52
+
53
+ const followUps = []
54
+ for (const line of overview.split('\n')) {
55
+ const m = line.match(/Follow-up surfaced:\s*(.+)$/)
56
+ if (m) followUps.push({ text: m[1].trim() })
57
+ }
58
+
59
+ return { tasks, phases, followUps, clean: !tasks.length && !phases.length && !followUps.length }
60
+ }
61
+
62
+ module.exports = { collectDisposition }
@@ -0,0 +1,80 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * `spec-env handoff <spec>` — make a spec's work reachable by its next owner.
5
+ *
6
+ * A spec branch lives in a local worktree, and nothing requires it ever to
7
+ * reach a remote — so a ticket handed to someone else points at code only its
8
+ * old owner can see. This plans the two things that close that: the branch
9
+ * published (a push the operator consents to, since it is outward-facing), and
10
+ * a note for the ticket naming where the work is. `/spec-start` on the new
11
+ * owner's machine then resumes from the published branch rather than forking.
12
+ *
13
+ * Pure: every fact arrives as an argument, so each answer is testable without a
14
+ * repo. The CLI reads git and writes the note.
15
+ */
16
+
17
+ const { phaseProgress, progressText } = require('./phases.js')
18
+
19
+ // Uncommitted work cannot travel with a push, so a hand-over would silently
20
+ // leave it behind in the old worktree. The engine declares the way out rather
21
+ // than leaving the skill to infer one (`offered-unblocks.md`): committing is
22
+ // what the guard asks for, so it is a `satisfy`, and nothing is weakened.
23
+ const COMMIT_FIRST = Object.freeze({ kind: 'satisfy', label: 'Commit first, then hand it over', command: '/commit' })
24
+
25
+ /**
26
+ * @param {object} f
27
+ * - `spec` `{ folder, branch, worktreePath }`
28
+ * - `worktree` true when the worktree exists on this machine
29
+ * - `dirtyPaths` uncommitted paths in that worktree ([] when clean)
30
+ * - `remote` the remote name, and `remoteConfigured` whether it exists
31
+ * - `headSha` the worktree's HEAD
32
+ * - `remoteSha` the branch's sha on the remote, '' when unpublished,
33
+ * null when the remote could not be asked
34
+ * - `phases` `[{ file, content }]`
35
+ */
36
+ function planHandoff(f) {
37
+ const { spec } = f
38
+ const refuse = (reason, offer) => ({ blocked: true, reason, ...(offer ? { offer } : {}) })
39
+
40
+ if (!f.worktree) {
41
+ return refuse(`${spec.folder} has no worktree on this machine — hand it over from wherever it is being built`)
42
+ }
43
+ if (f.dirtyPaths && f.dirtyPaths.length) {
44
+ return refuse(
45
+ `${spec.folder}'s worktree has ${f.dirtyPaths.length} uncommitted path(s) — a push carries commits, so they would stay behind`,
46
+ COMMIT_FIRST,
47
+ )
48
+ }
49
+ if (!f.remoteConfigured) {
50
+ return refuse(`no remote named ${f.remote} — publish ${spec.branch} somewhere the new owner can reach first`)
51
+ }
52
+
53
+ const progress = phaseProgress(f.phases)
54
+ // Published AT HEAD is the positive signal the push is already done; an
55
+ // unpublished branch and a stale one both need it, and a remote that could
56
+ // not be asked is planned as if it does (a redundant push is harmless).
57
+ const published = Boolean(f.headSha && f.remoteSha && f.remoteSha === f.headSha)
58
+ const commands = published ? [] : [`git -C ${spec.worktreePath} push -u ${f.remote} ${spec.branch}`]
59
+ const sha = (f.headSha || '').slice(0, 12)
60
+ const note = [
61
+ `**Handed over** — the work is on \`${spec.branch}\` at \`${sha}\` (${f.remote}), ${progressText(progress)}.`,
62
+ '',
63
+ `\`/spec-start ${spec.folder}\` resumes from that branch rather than forking a new one.`,
64
+ '',
65
+ ].join('\n')
66
+
67
+ return {
68
+ blocked: false,
69
+ branch: spec.branch,
70
+ sha,
71
+ remote: f.remote,
72
+ published,
73
+ remoteUnknown: f.remoteSha === null,
74
+ progress,
75
+ commands,
76
+ note,
77
+ }
78
+ }
79
+
80
+ module.exports = { planHandoff, phaseProgress, progressText, COMMIT_FIRST }
@@ -0,0 +1,262 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * Host adapter — the one place skitterspec talks to a PR host.
5
+ *
6
+ * PR mode (`land.strategy: "pr"`) needs two things git alone cannot answer once
7
+ * a host merges by squash or rebase: *is the PR for this branch merged?* (the
8
+ * ancestry test goes false forever under a rewritten merge) and *what command
9
+ * opens / readies / abandons a PR here?* Both are answered from the remote URL
10
+ * — `dev.azure.com` / `visualstudio.com` → the `az` CLI, `github.com` → `gh` —
11
+ * and never from extra config: the URL is the one place the host is already
12
+ * written down.
13
+ *
14
+ * Everything here is pure except `prFor`, which takes an injected `exec` so the
15
+ * CLI supplies a real subprocess and tests supply a fake. Every failure shape —
16
+ * unknown host, missing CLI, non-zero exit, no network, unparseable output —
17
+ * returns `state: "cannot-tell"` and says nothing: an absence is not evidence,
18
+ * and the callers route cannot-tell to inaction
19
+ * (`.claude/rules/negative-checks.md` rule 4).
20
+ */
21
+
22
+ /**
23
+ * Parse a git remote URL into { host, org, project, repo, orgUrl }.
24
+ *
25
+ * host: 'github' | 'azure' | null (null = no adapter; callers degrade to
26
+ * ancestry + cannot-tell). `project` is Azure-only. `orgUrl` is the
27
+ * `--organization` value the az CLI wants, composed as dev.azure.com even for
28
+ * a legacy visualstudio.com remote — Azure serves both.
29
+ *
30
+ * WHAT WOULD FOOL THIS: a GitHub Enterprise or Azure DevOps Server install on
31
+ * its own domain parses to host null. That is the degrade-to-ancestry path by
32
+ * design — guessing a host from an unrecognised domain risks running the wrong
33
+ * CLI against someone's internal URL.
34
+ */
35
+ function parseRemote(url) {
36
+ const none = { host: null, org: null, project: null, repo: null, orgUrl: null }
37
+ if (typeof url !== 'string' || !url.trim()) return none
38
+ const u = url.trim()
39
+
40
+ // github: https://github.com/owner/repo(.git) · git@github.com:owner/repo(.git)
41
+ // · ssh://git@github.com/owner/repo(.git)
42
+ let m = u.match(/^(?:https:\/\/|ssh:\/\/git@|git@)github\.com[/:]([^/]+)\/([^/]+?)(?:\.git)?\/?$/)
43
+ if (m) return { host: 'github', org: m[1], project: null, repo: m[2], orgUrl: null }
44
+
45
+ // azure, modern: https://[org@]dev.azure.com/org/project/_git/repo
46
+ m = u.match(/^https:\/\/(?:[^@/]+@)?dev\.azure\.com\/([^/]+)\/([^/]+)\/_git\/([^/]+?)\/?$/)
47
+ if (m) {
48
+ return azure(m[1], m[2], m[3])
49
+ }
50
+ // azure, ssh: git@ssh.dev.azure.com:v3/org/project/repo
51
+ m = u.match(/^git@ssh\.dev\.azure\.com:v3\/([^/]+)\/([^/]+)\/([^/]+?)\/?$/)
52
+ if (m) return azure(m[1], m[2], m[3])
53
+ // azure, legacy: https://org.visualstudio.com/[DefaultCollection/]project/_git/repo
54
+ m = u.match(/^https:\/\/([^.@/]+)\.visualstudio\.com\/(?:DefaultCollection\/)?([^/]+)\/_git\/([^/]+?)\/?$/)
55
+ if (m) return azure(m[1], m[2], m[3])
56
+
57
+ return none
58
+ }
59
+
60
+ function azure(org, project, repo) {
61
+ return {
62
+ host: 'azure',
63
+ org: decode(org),
64
+ project: decode(project),
65
+ repo: decode(repo),
66
+ orgUrl: `https://dev.azure.com/${org}`,
67
+ }
68
+ }
69
+
70
+ // Azure project/repo names may carry spaces, which arrive %20-encoded in the
71
+ // remote URL and must be literal in the az flags.
72
+ function decode(part) {
73
+ try {
74
+ return decodeURIComponent(part)
75
+ } catch {
76
+ return part
77
+ }
78
+ }
79
+
80
+ // Shell-quote one az/gh flag value. Values come from a remote URL, so spaces
81
+ // (Azure project names) are the realistic case; a quote inside one is not a
82
+ // name Azure or GitHub accepts, but escape it anyway rather than truncate.
83
+ function q(value) {
84
+ return /[^A-Za-z0-9_\-./]/.test(value) ? `"${String(value).replace(/"/g, '\\"')}"` : value
85
+ }
86
+
87
+ /**
88
+ * Ask the host for the PR whose source is `branch`.
89
+ *
90
+ * `exec(file, args, opts)` must return `{ ok, stdout, stderr }` and never
91
+ * throw. Returns `{ state, id, url }` with state one of:
92
+ * merged · open · draft · none · cannot-tell
93
+ *
94
+ * "none" is a POSITIVE answer — the host replied and no (live) PR exists —
95
+ * where "cannot-tell" is the lookup itself failing. The two route differently
96
+ * (none can offer a create command; cannot-tell must not conclude anything),
97
+ * so a failure is never softened into none.
98
+ */
99
+ function prFor(remoteInfo, branch, exec, cwd) {
100
+ const cannot = { state: 'cannot-tell', id: null, url: null }
101
+ if (!remoteInfo || !remoteInfo.host) return cannot
102
+
103
+ if (remoteInfo.host === 'github') {
104
+ // Run in the repo (gh resolves owner/repo from the git remotes there).
105
+ const r = exec('gh', ['pr', 'view', branch, '--json', 'state,isDraft,number,url'], { cwd })
106
+ if (!r.ok) {
107
+ // gh exits 1 both for "no PR" and for real failures; only the former is
108
+ // an answer.
109
+ return /no pull requests? found/i.test(r.stderr || '') ? { state: 'none', id: null, url: null } : cannot
110
+ }
111
+ return githubPrState(r.stdout)
112
+ }
113
+
114
+ // azure
115
+ const r = exec(
116
+ 'az',
117
+ [
118
+ 'repos', 'pr', 'list',
119
+ '--organization', remoteInfo.orgUrl,
120
+ '--project', remoteInfo.project,
121
+ '--repository', remoteInfo.repo,
122
+ '--source-branch', branch,
123
+ '--status', 'all',
124
+ '--output', 'json',
125
+ ],
126
+ { cwd },
127
+ )
128
+ if (!r.ok) return cannot
129
+ return azurePrState(r.stdout)
130
+ }
131
+
132
+ // Map `gh pr view --json state,isDraft,number,url` output. Unparseable JSON is
133
+ // a cannot-tell, never a guess.
134
+ function githubPrState(stdout) {
135
+ let pr
136
+ try {
137
+ pr = JSON.parse(stdout)
138
+ } catch {
139
+ return { state: 'cannot-tell', id: null, url: null }
140
+ }
141
+ const id = pr.number != null ? String(pr.number) : null
142
+ const url = pr.url || null
143
+ if (pr.state === 'MERGED') return { state: 'merged', id, url }
144
+ if (pr.state === 'OPEN') return { state: pr.isDraft ? 'draft' : 'open', id, url }
145
+ if (pr.state === 'CLOSED') return { state: 'none', id, url }
146
+ return { state: 'cannot-tell', id, url }
147
+ }
148
+
149
+ // Map `az repos pr list --status all` output: the newest PR for the branch is
150
+ // the one whose state matters (an abandoned early attempt must not shadow the
151
+ // live PR). An empty list is a positive "none".
152
+ function azurePrState(stdout) {
153
+ let list
154
+ try {
155
+ list = JSON.parse(stdout)
156
+ } catch {
157
+ return { state: 'cannot-tell', id: null, url: null }
158
+ }
159
+ if (!Array.isArray(list)) return { state: 'cannot-tell', id: null, url: null }
160
+ if (list.length === 0) return { state: 'none', id: null, url: null }
161
+ const pr = list.reduce((a, b) => ((a.pullRequestId || 0) >= (b.pullRequestId || 0) ? a : b))
162
+ const id = pr.pullRequestId != null ? String(pr.pullRequestId) : null
163
+ const url = null // az's list payload carries no stable web URL; callers compose nothing
164
+ if (pr.status === 'completed') return { state: 'merged', id, url }
165
+ if (pr.status === 'active') return { state: pr.isDraft ? 'draft' : 'open', id, url }
166
+ if (pr.status === 'abandoned') return { state: 'none', id, url }
167
+ return { state: 'cannot-tell', id, url }
168
+ }
169
+
170
+ /**
171
+ * The command that opens a PR for `branch` → `base`. Null for an unknown host —
172
+ * the caller keeps its placeholder comment rather than inventing a CLI.
173
+ */
174
+ function prCreateCommand(remoteInfo, { branch, base, draft }) {
175
+ if (!remoteInfo || !remoteInfo.host) return null
176
+ if (remoteInfo.host === 'github') {
177
+ return `gh pr create --head ${branch} --base ${base} --fill${draft ? ' --draft' : ''}`
178
+ }
179
+ return (
180
+ `az repos pr create --organization ${remoteInfo.orgUrl} --project ${q(remoteInfo.project)} ` +
181
+ `--repository ${q(remoteInfo.repo)} --source-branch ${branch} --target-branch ${base}` +
182
+ (draft ? ' --draft true' : '')
183
+ )
184
+ }
185
+
186
+ // Flip a draft PR to ready. Azure addresses a PR by id, so without one there is
187
+ // no command to print — null, and the caller says nothing.
188
+ function prReadyCommand(remoteInfo, { branch, id }) {
189
+ if (!remoteInfo || !remoteInfo.host) return null
190
+ if (remoteInfo.host === 'github') return `gh pr ready ${branch}`
191
+ if (!id) return null
192
+ return `az repos pr update --organization ${remoteInfo.orgUrl} --id ${id} --draft false`
193
+ }
194
+
195
+ // Close/abandon the PR without merging (the /spec-cancel path).
196
+ function prAbandonCommand(remoteInfo, { branch, id }) {
197
+ if (!remoteInfo || !remoteInfo.host) return null
198
+ if (remoteInfo.host === 'github') return `gh pr close ${branch}`
199
+ if (!id) return null
200
+ return `az repos pr update --organization ${remoteInfo.orgUrl} --id ${id} --status abandoned`
201
+ }
202
+
203
+ /**
204
+ * The PR step of an integrate plan, selected from the host's answer about the
205
+ * branch. One function so the CLI and its tests cannot disagree with each
206
+ * other about what each state means:
207
+ *
208
+ * none / merged → the real create command (merged = that PR is history and
209
+ * new commits need a new one)
210
+ * open → a comment: the push updates it, a create would only error
211
+ * draft, wanted draft → the same comment (mid-spec re-push)
212
+ * draft, wanted ready → the ready command — or, where the host needs an id
213
+ * nobody has (Azure without one), a comment naming the manual
214
+ * step rather than nothing
215
+ * cannot-tell → null; the caller keeps its degraded placeholder
216
+ */
217
+ function prPlanCommand(remoteInfo, pr, { branch, base, draft }) {
218
+ if (!pr || pr.state === 'cannot-tell') return null
219
+ if (pr.state === 'none' || pr.state === 'merged') {
220
+ return prCreateCommand(remoteInfo, { branch, base, draft })
221
+ }
222
+ if (pr.state === 'open' || (pr.state === 'draft' && draft)) {
223
+ return `# PR ${pr.id ? `#${pr.id} ` : ''}already ${pr.state} — the push updates it`
224
+ }
225
+ // draft, and the caller wants it ready
226
+ return (
227
+ prReadyCommand(remoteInfo, { branch, id: pr.id })
228
+ || `# PR ${pr.id ? `#${pr.id} ` : ''}is a draft — mark it ready on the host`
229
+ )
230
+ }
231
+
232
+ /**
233
+ * The base a PR-mode view measures from: the REMOTE image of base when its
234
+ * remote-tracking ref exists in this clone, else the local name unchanged.
235
+ * Trunk configs pass through untouched, and nothing here fetches — a render
236
+ * must stay offline-safe, so a missing ref is the local fallback, never an
237
+ * error. `trimmed(argv)` is the caller's git reader (string | null).
238
+ *
239
+ * One helper because two copies of this selection (the server's render and the
240
+ * CLI's) must not disagree about which range one spec's page shows.
241
+ */
242
+ function preferRemoteBase(config, name, trimmed) {
243
+ if (!name) return name
244
+ if (!config || !config.land || config.land.strategy !== 'pr') return name
245
+ const remoteRef = `${config.land.remote || 'origin'}/${name}`
246
+ if (trimmed(['rev-parse', '--verify', '--quiet', `refs/remotes/${remoteRef}`])) {
247
+ return remoteRef
248
+ }
249
+ return name
250
+ }
251
+
252
+ module.exports = {
253
+ parseRemote,
254
+ preferRemoteBase,
255
+ prFor,
256
+ githubPrState,
257
+ azurePrState,
258
+ prCreateCommand,
259
+ prReadyCommand,
260
+ prAbandonCommand,
261
+ prPlanCommand,
262
+ }