@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
package/src/cli.js CHANGED
@@ -35,15 +35,19 @@ const SPEC_ENV_VERBS = Object.freeze([
35
35
  'dev',
36
36
  'connect',
37
37
  'integrate',
38
+ 'disposition',
39
+ 'handoff',
38
40
  'hotfix',
39
41
  'live',
40
42
  'review',
41
43
  'stage',
42
44
  'status',
43
45
  'resolve',
46
+ 'base',
44
47
  'nospec',
45
48
  'main',
46
49
  ])
50
+ const { forkMatch, planBaseReport } = require('./env/base.js')
47
51
  const {
48
52
  readRegistry,
49
53
  writeRegistry,
@@ -58,6 +62,8 @@ const {
58
62
  resolveSpec,
59
63
  resolveSpecless,
60
64
  resolveBaseBranch,
65
+ describeBaseBranch,
66
+ baseRemote,
61
67
  liveWorktreePaths,
62
68
  collectSpecFolders,
63
69
  allSpecs,
@@ -67,6 +73,7 @@ const {
67
73
  repoInfo,
68
74
  expandTokens,
69
75
  splitPrefix,
76
+ parseBaseVersion,
70
77
  BUCKETS,
71
78
  } = require('./env/resolve.js')
72
79
  const building = require('./env/building.js')
@@ -165,8 +172,12 @@ const {
165
172
  mainGuardStatus,
166
173
  } = require('./env/mainguard.js')
167
174
  const { planPrune, liveSlugsForSpecs, reconcileRegistry } = require('./env/prune.js')
168
- const { planIntegrate, planIntegrateCheckout } = require('./env/integrate.js')
169
- const { planHotfixLand, planHotfixFinish } = require('./env/hotfix.js')
175
+ const { planIntegrate, planIntegrateCheckout, planIntegratePr } = require('./env/integrate.js')
176
+ const { parseRemote, prFor, prPlanCommand, prAbandonCommand, preferRemoteBase } = require('./env/host.js')
177
+ const { collectDisposition } = require('./env/disposition.js')
178
+ const { planHandoff } = require('./env/handoff.js')
179
+ const { collectInFlight, detailOf, formatInFlight, isInFlight } = require('./env/inflight.js')
180
+ const { planHotfixLand, planBranchHotfixLand, planBranchHotfixFinish, planHotfixFinish } = require('./env/hotfix.js')
170
181
  const { runHotfixLand, describeStep: describeHotfixStep } = require('./env/hotfixland.js')
171
182
  const { planDev } = require('./env/dev.js')
172
183
  const { startProcess, stopProcess, waitHealthy, readPid, isAlive } = require('./env/supervise.js')
@@ -243,7 +254,13 @@ Usage:
243
254
  dev up <spec> start host dev servers on the spec's ports
244
255
  dev down <spec> stop the spec's host dev servers
245
256
  connect <spec> expose a spec on the canonical ports (main = off)
246
- integrate <spec> plan rebase + fast-forward onto the base branch
257
+ integrate <spec> plan the land: rebase + fast-forward, or in PR
258
+ mode push + PR (--push, --draft, --strategy)
259
+ disposition <spec>
260
+ list unticked tasks, open phases and surfaced
261
+ follow-ups to dispose before a PR goes ready
262
+ handoff <spec> plan handing a spec to someone else: publish
263
+ its branch, write the ticket note (--json)
247
264
  hotfix land <spec>
248
265
  release, push (--push), carry a hotfix to
249
266
  the base branch (--plan, --also <tag>)
@@ -261,6 +278,12 @@ Usage:
261
278
  documents and everything else
262
279
  status list provisioned specs + port blocks
263
280
  resolve <spec> print resolved slug/type/branch/paths
281
+ base fetch, list baseBranchPattern matches
282
+ newest-first, mark the base, and name
283
+ specs forked from an older match
284
+ skitterspec status What is in flight here: every spec with a worktree,
285
+ its bucket and phase progress read from that
286
+ worktree (--json). Offline; always exits 0.
264
287
  skitterspec gating <cmd> Release-gating check (opt-in; needs
265
288
  specs/.core/gating.config.json). Subcommands:
266
289
  check [spec] report specs with no recorded gating
@@ -437,14 +460,23 @@ function specEnvReviewWaiting(dir, config, flags) {
437
460
  process.stdout.write(section ? `${section.replace(/^\n/, '')}` : 'spec-env review: nothing waiting.\n')
438
461
  }
439
462
 
440
- function specEnvStatus(dir, config) {
463
+ // Every spec with a worktree of its own, sorted. Shared by `spec-env status` and
464
+ // the top-level `skitterspec status`, so the two can never disagree about what
465
+ // is provisioned.
466
+ function provisionedSpecs(dir, config) {
441
467
  const worktreePaths = liveWorktreePaths(gitReader(dir))
442
- const provisioned = allSpecs(dir, config, worktreePaths, speclessMap(dir, config))
443
- .map((s) => ({ folder: s.folder, wt: path.resolve(s.worktreePath), specless: s.specless }))
444
- // The primary checkout is itself in `git worktree list`; a spec is
445
- // provisioned only when it has its OWN worktree, separate from it.
446
- .filter((s) => s.wt !== dir && worktreePaths.has(s.wt))
447
- .sort((a, b) => a.folder.localeCompare(b.folder))
468
+ return (
469
+ allSpecs(dir, config, worktreePaths, speclessMap(dir, config))
470
+ .map((s) => ({ folder: s.folder, wt: path.resolve(s.worktreePath), specless: s.specless }))
471
+ // The primary checkout is itself in `git worktree list`; a spec is
472
+ // provisioned only when it has its OWN worktree, separate from it.
473
+ .filter((s) => s.wt !== dir && worktreePaths.has(s.wt))
474
+ .sort((a, b) => a.folder.localeCompare(b.folder))
475
+ )
476
+ }
477
+
478
+ function specEnvStatus(dir, config) {
479
+ const provisioned = provisionedSpecs(dir, config)
448
480
 
449
481
  // REACHED EITHER WAY. This used to return here, so a repo with nothing in
450
482
  // flight could say nothing about a waiting pass — and a repo with nothing in
@@ -455,8 +487,9 @@ function specEnvStatus(dir, config) {
455
487
  }
456
488
 
457
489
  const registry = readRegistry(dir, config)
490
+ const rows = collectInFlight({ dir, provisioned })
458
491
  process.stdout.write('Provisioned specs:\n')
459
- for (const { folder, wt, specless } of provisioned) {
492
+ for (const [i, { folder, wt, specless }] of provisioned.entries()) {
460
493
  const slot = registry.slots[folder]
461
494
  let ports = ''
462
495
  if (slot !== undefined) {
@@ -468,11 +501,38 @@ function specEnvStatus(dir, config) {
468
501
  // looking for `specs/**/<name>/` must not conclude the repo is broken when
469
502
  // there is nothing there — it is not missing, there never was one.
470
503
  const tag = specless ? ' (no spec)' : ''
471
- process.stdout.write(` ${folder}${tag}${ports}\n ${path.relative(dir, wt) || wt}\n`)
504
+ // The worktree's own reading — bucket, progress, any legacy header — after
505
+ // everything this line already carried, so the line is a superset of it.
506
+ const detail = specless ? '' : ` ${detailOf(rows[i])}`
507
+ process.stdout.write(` ${folder}${tag}${ports}${detail}\n ${path.relative(dir, wt) || wt}\n`)
472
508
  }
473
509
  process.stdout.write(waitingSection(dir, config))
474
510
  }
475
511
 
512
+ /**
513
+ * `skitterspec status` — what is being worked on here, read from each spec's
514
+ * own worktree. Offline and instant: no tracker is asked, ever. Exits 0 in
515
+ * every state, an idle repo included — an empty answer is not a finding.
516
+ */
517
+ function inFlightStatus(argv) {
518
+ const json = argv.includes('--json')
519
+ const at = argv.indexOf('--dir')
520
+ const from = path.resolve(at !== -1 && argv[at + 1] ? argv[at + 1] : process.cwd())
521
+ const dir = resolvePrimaryCheckout(from, gitReader(from))
522
+ const { config, present } = loadEnvConfig(dir)
523
+ const rows = present ? collectInFlight({ dir, provisioned: provisionedSpecs(dir, config) }) : []
524
+ if (json) {
525
+ const specs = rows.map((r) => ({ ...r, inFlight: isInFlight(r) }))
526
+ process.stdout.write(JSON.stringify({ isolation: present, specs }, null, 2) + '\n')
527
+ return
528
+ }
529
+ if (!present) {
530
+ process.stdout.write('no specs in flight — isolation is not enabled here, so no spec has a worktree.\n')
531
+ return
532
+ }
533
+ process.stdout.write(formatInFlight(rows, { dir }))
534
+ }
535
+
476
536
  // Plan a provision: allocate the slot, persist the registry, and print the plan
477
537
  // the /spec-env skill executes (git worktree add, docker compose up, .env).
478
538
  // This creates no worktree and starts no stack — the caller runs the
@@ -503,8 +563,16 @@ function specIsUntracked(dir, git, spec) {
503
563
  * Returns `{ onFork, foundOn }`; `onFork: null` means "cannot tell" (a hotfix, or
504
564
  * a git that would not answer), which the planner routes to carrying on.
505
565
  */
506
- function specOnForkPoint(dir, git, spec) {
566
+ function specOnForkPoint(dir, git, spec, config) {
507
567
  if (spec.baseRef) return { onFork: null, foundOn: null }
568
+ // BRANCH-MODE SPEC DOCUMENTS ARE EXEMPT the same way a hotfix is: under
569
+ // `land.specDocs: "branch"` the spec rides its feature branch and lands with
570
+ // the work's PR, so it is *supposed* to be absent from the fork point —
571
+ // checking would refuse every spec the mode produces. Cannot-tell, so the
572
+ // planner carries on.
573
+ if (config && config.land && config.land.specDocs === 'branch') {
574
+ return { onFork: null, foundOn: null }
575
+ }
508
576
  // Ask about EVERY bucket, by folder name — never about `spec.path`.
509
577
  //
510
578
  // A spec's folder is its identity; which bucket holds it is a property of the
@@ -516,7 +584,7 @@ function specOnForkPoint(dir, git, spec) {
516
584
  // into "not committed" and silently emptied the `it is on <branch>` hint too.
517
585
  const rels = BUCKETS.map((bucket) => `specs/${bucket}/${spec.folder}`)
518
586
  for (const rel of rels) {
519
- if (git(['cat-file', '-e', `HEAD:${rel}/00-overview.md`]) !== null) {
587
+ if (git(['cat-file', '-e', `${spec.forkFrom || 'HEAD'}:${rel}/00-overview.md`]) !== null) {
520
588
  return { onFork: true, foundOn: null }
521
589
  }
522
590
  }
@@ -627,7 +695,7 @@ function specEnvUpCheckout(dir, config, spec) {
627
695
  const primary = assertPrimaryOnMain(config, git)
628
696
  const base = resolveBaseBranch(config, git)
629
697
  const status = git(['status', '--porcelain', '-uall'])
630
- const onFork = specOnForkPoint(dir, git, spec)
698
+ const onFork = specOnForkPoint(dir, git, spec, config)
631
699
 
632
700
  const plan = planCheckoutUp(
633
701
  spec,
@@ -922,13 +990,29 @@ function specEnvUp(dir, config, specArg, flags = {}) {
922
990
  // Everywhere else `spec.baseRef` comes off the spec and stays the
923
991
  // authority — which is why passing this to a spec that resolves refuses
924
992
  // below rather than quietly losing to the header.
993
+ // `--from` takes either Base version form; a `<branch>@<sha>` forks from
994
+ // the sha, which is the part git can resolve.
995
+ const fromVersion = flags.from !== undefined ? parseBaseVersion(flags.from) : null
925
996
  if (flags.from !== undefined) {
926
- const bad = badForkRef(dir, flags.from)
997
+ const bad = badForkRef(dir, fromVersion ? fromVersion.ref : flags.from)
927
998
  if (bad) {
928
999
  process.stdout.write(bad)
929
1000
  return
930
1001
  }
931
1002
  }
1003
+ // A BRANCH-BASED hotfix (`hotfix.releaseBranch`) forks from the remote's
1004
+ // head of the release branch, fetched now — prod is whatever that branch
1005
+ // holds, not whatever this clone last saw. Resolved to a sha before the
1006
+ // registry is written, so a refusal leaves nothing behind. An explicit
1007
+ // `--from` still wins: the operator named the fork point.
1008
+ let releaseFork = null
1009
+ if (!fromVersion && splitPrefix(specArg).type === 'hotfix' && config.hotfix.releaseBranch) {
1010
+ releaseFork = releaseBranchFork(dir, config)
1011
+ if (releaseFork.refused) {
1012
+ process.stdout.write(`spec-env up: ${releaseFork.refused}\n`)
1013
+ return
1014
+ }
1015
+ }
932
1016
  const beforeAuth = readRegistry(dir, config)
933
1017
  const resolved = resolveSpecless(specArg, dir, config, { spec: true })
934
1018
  writeRegistry(
@@ -937,7 +1021,11 @@ function specEnvUp(dir, config, specArg, flags = {}) {
937
1021
  recordSpecless(beforeAuth, specArg, { branch: resolved.branch, spec: true }),
938
1022
  )
939
1023
  spec = resolved
940
- if (flags.from !== undefined) spec.baseRef = flags.from
1024
+ const fork = fromVersion || releaseFork
1025
+ if (fork) {
1026
+ spec.baseRef = fork.ref
1027
+ spec.baseVersion = fork
1028
+ }
941
1029
  authoring = true
942
1030
  }
943
1031
 
@@ -954,6 +1042,11 @@ function specEnvUp(dir, config, specArg, flags = {}) {
954
1042
  return
955
1043
  }
956
1044
 
1045
+ // Rolling base: fetch first, so a release candidate cut since the last fetch
1046
+ // is the one this spec forks from. A hotfix names its own fork point and is
1047
+ // not about the base at all, so it never fetches here. No pattern, no fetch.
1048
+ if (!spec.baseRef) process.stdout.write(fetchNote('up', config, fetchForPattern(dir, config)))
1049
+
957
1050
  // Checkout mode: the branch is built in the primary checkout, so none of the
958
1051
  // worktree machinery below applies — no slot, no trust entry and no bootstrap.
959
1052
  // Handled first precisely so none of that runs by accident.
@@ -993,6 +1086,20 @@ function specEnvUp(dir, config, specArg, flags = {}) {
993
1086
  const upGit = gitReader(dir)
994
1087
  const upStatus = upGit(['status', '--porcelain'])
995
1088
  const upDirtyPaths = dirtyPaths(upGit)
1089
+ // A worktree forks from whatever the primary checkout has out. Under a
1090
+ // rolling base that can be the previous release candidate, still checked out
1091
+ // after the roll — so where it is not the resolved base, fork from the base
1092
+ // explicitly: the local branch when this clone has one, else its remote image.
1093
+ // No pattern leaves the fork exactly as it was.
1094
+ if (!spec.baseRef && (config.baseBranchPattern || '').trim()) {
1095
+ const ubase = resolveBaseBranch(config, upGit)
1096
+ if (primaryUp.branch !== ubase) {
1097
+ spec.forkFrom =
1098
+ upGit(['show-ref', '--verify', '--quiet', `refs/heads/${ubase}`]) !== null
1099
+ ? ubase
1100
+ : `${baseRemote(config)}/${ubase}`
1101
+ }
1102
+ }
996
1103
  // A spec with no document on disk does not ask whether the spec is on the
997
1104
  // fork point — it is known to be nowhere, and that is the healthy state of
998
1105
  // the authoring lane, not the "would fork without the spec it is for"
@@ -1006,10 +1113,37 @@ function specEnvUp(dir, config, specArg, flags = {}) {
1006
1113
  // so `authoring` is false while `spec.path` is still null. Asking git about a
1007
1114
  // null path threw, which is a crash rather than a refusal: the condition is
1008
1115
  // whether there is a document, and it always was.
1116
+ // RESUME, NOT FORK — a spec whose branch is already published. A spec handed
1117
+ // to someone else mid-flight (`/spec-claim --to` pushes it) lives on the
1118
+ // remote and nowhere on this machine, and forking a fresh branch from base
1119
+ // would hand its new owner an empty tree with the old owner's work out of
1120
+ // reach. So where this clone has no such branch and no worktree for it, ask
1121
+ // the remote, and build from what is there.
1122
+ //
1123
+ // A POSITIVE SIGNAL ONLY: `ls-remote` naming the branch with a sha. An empty
1124
+ // answer is "not published", and the fork goes ahead exactly as before. WHAT
1125
+ // WOULD FOOL THIS: a remote this clone cannot reach answers nothing either —
1126
+ // so a failed ask is said in one line (`resume:`) and still forks, and a repo
1127
+ // with no such remote at all is not asked and says nothing.
1128
+ const resumeRemote = baseRemote(config)
1129
+ if (
1130
+ !fs.existsSync(spec.worktreePath) &&
1131
+ upGit(['show-ref', '--verify', '--quiet', `refs/heads/${spec.branch}`]) === null &&
1132
+ upGit(['remote', 'get-url', resumeRemote]) !== null
1133
+ ) {
1134
+ const head = upGit(['ls-remote', '--heads', resumeRemote, `refs/heads/${spec.branch}`])
1135
+ const sha = head ? head.split(/\s+/)[0] : ''
1136
+ if (sha) spec.resumeFrom = { remote: resumeRemote, sha }
1137
+ else if (head === null) spec.resumeUnknown = resumeRemote
1138
+ }
1139
+
1009
1140
  const noDocument = authoring || !spec.path
1010
- const upOnFork = noDocument
1141
+ // A resumed branch carries the spec itself (it was started there), so whether
1142
+ // the spec is on the BASE is not this run's question: cannot-tell, which the
1143
+ // gate allows.
1144
+ const upOnFork = noDocument || spec.resumeFrom
1011
1145
  ? { onFork: undefined, foundOn: null }
1012
- : specOnForkPoint(dir, upGit, spec)
1146
+ : specOnForkPoint(dir, upGit, spec, config)
1013
1147
  const upSpecUntracked = noDocument ? false : specIsUntracked(dir, upGit, spec)
1014
1148
 
1015
1149
  // Trust the shared worktree root so edits into the freshly-provisioned worktree
@@ -1059,7 +1193,7 @@ function specEnvUp(dir, config, specArg, flags = {}) {
1059
1193
  dirtyPaths: upDirtyPaths,
1060
1194
  specOnFork: upOnFork.onFork,
1061
1195
  specFoundOn: upOnFork.foundOn,
1062
- forkRef: spec.baseRef || currentBranch(upGit) || 'HEAD',
1196
+ forkRef: spec.baseRef || spec.forkFrom || currentBranch(upGit) || 'HEAD',
1063
1197
  specUntracked: upSpecUntracked,
1064
1198
  composeFilePresent: composeFilePresent(dir, config),
1065
1199
  }, { docs })
@@ -1068,6 +1202,17 @@ function specEnvUp(dir, config, specArg, flags = {}) {
1068
1202
  process.stdout.write(`spec-env up: blocked — ${plan.reason}.\n`)
1069
1203
  return
1070
1204
  }
1205
+ // The planned spec commit lands on the branch the primary checkout has out,
1206
+ // and the fork is from the base — so the new branch would miss the very
1207
+ // commit made for it. Refuse rather than plan one that cannot work.
1208
+ if (spec.forkFrom && plan.specCommit) {
1209
+ process.stdout.write(
1210
+ `spec-env up: blocked — ${spec.folder} is uncommitted on ${primaryUp.branch || 'a detached HEAD'}, ` +
1211
+ `but the base is ${spec.forkFrom}. Switch the primary checkout to the base and commit the spec ` +
1212
+ 'there, then re-run.\n',
1213
+ )
1214
+ return
1215
+ }
1071
1216
 
1072
1217
  const out = []
1073
1218
  // `up` is a planner: it prints commands for the caller to run and creates no
@@ -1099,6 +1244,24 @@ function specEnvUp(dir, config, specArg, flags = {}) {
1099
1244
  if (plan.docs) {
1100
1245
  out.push(' docs: documents only — no setup commands, no docker')
1101
1246
  }
1247
+ // PR mode forks from LOCAL base — an origin/<base> fork would fork without a
1248
+ // just-landed, not-yet-pushed spec document — so when the remote image is
1249
+ // ahead, say so rather than silently forking behind it. Advisory only, and
1250
+ // silent on every cannot-tell: no remote-tracking ref here is an absence,
1251
+ // not a stale base (`.claude/rules/negative-checks.md`).
1252
+ if (config.land && config.land.strategy === 'pr') {
1253
+ const ugit = gitReader(dir)
1254
+ const ubase = resolveBaseBranch(config, ugit)
1255
+ const uremote = config.land.remote || 'origin'
1256
+ const behind = ubase ? ugit(['rev-list', '--count', `${ubase}..${uremote}/${ubase}`]) : null
1257
+ if (behind !== null && Number(behind) > 0) {
1258
+ out.push(
1259
+ ` note: ${uremote}/${ubase} is ${behind} commit(s) ahead of ${ubase} — the branch forks` +
1260
+ `\n from local ${ubase}; pull first if you want the newer base` +
1261
+ '\n (landing rebases onto the remote base either way)',
1262
+ )
1263
+ }
1264
+ }
1102
1265
  // Positive, so an operator reading the plan knows the missing spec folder is
1103
1266
  // the lane working rather than something the engine failed to find.
1104
1267
  if (authoring) {
@@ -1111,6 +1274,24 @@ function specEnvUp(dir, config, specArg, flags = {}) {
1111
1274
  if (authoring && flags.from !== undefined) {
1112
1275
  out.push(` fork: ${flags.from} (the branch forks from here, not from base)`)
1113
1276
  }
1277
+ // The header the skill writes into the new spec, said once, by the engine
1278
+ // that chose the commit — so the record and the fork cannot disagree.
1279
+ if (authoring && spec.baseVersion && spec.baseVersion.kind === 'branch' && flags.from === undefined) {
1280
+ const v = spec.baseVersion
1281
+ out.push(
1282
+ ` fork: ${v.branch}@${v.sha} (the head of ${baseRemote(config)}/${v.branch})` +
1283
+ `\n record: > **Base version:** ${v.branch}@${v.sha}`,
1284
+ )
1285
+ }
1286
+ if (spec.resumeFrom && !attached) {
1287
+ const { remote, sha } = spec.resumeFrom
1288
+ out.push(` resume: ${remote}/${spec.branch} @ ${sha.slice(0, 12)} (already published — carrying on from it, not forking)`)
1289
+ } else if (spec.resumeUnknown && !attached) {
1290
+ out.push(` resume: could not ask ${spec.resumeUnknown} for ${spec.branch} — forking fresh; if it was handed over, fetch and re-run`)
1291
+ }
1292
+ if (spec.forkFrom && !attached && !spec.resumeFrom) {
1293
+ out.push(` fork: ${spec.forkFrom} (the base — the primary checkout is on ${primaryUp.branch || 'a detached HEAD'})`)
1294
+ }
1114
1295
  if (trust.reason === 'malformed') {
1115
1296
  out.push(
1116
1297
  ' trusted: ! .claude/settings.local.json is not valid JSON — left it;' +
@@ -1346,6 +1527,38 @@ function speclessMap(dir, config) {
1346
1527
  * tree ref would be rejected here and rejected by `git worktree add` too. Being
1347
1528
  * wrong that way costs a refusal on something that could never have worked.
1348
1529
  */
1530
+ /**
1531
+ * Where a branch-based hotfix forks: the remote's head of `hotfix.releaseBranch`,
1532
+ * fetched first. Returns `{ kind: 'branch', branch, sha, ref }` (the Base version
1533
+ * shape, sha abbreviated to 12) or `{ refused }`.
1534
+ *
1535
+ * A failed fetch is not itself a refusal — the remote-tracking ref already here
1536
+ * still names a real commit on the release line — but a ref that is absent after
1537
+ * the fetch is: forking from anywhere else would build the fix on code prod is
1538
+ * not running, which is the one mistake a hotfix exists to avoid.
1539
+ */
1540
+ function releaseBranchFork(dir, config) {
1541
+ const branch = config.hotfix.releaseBranch
1542
+ const remote = baseRemote(config)
1543
+ let fetchErr = null
1544
+ try {
1545
+ execFileSync('git', ['-C', dir, 'fetch', remote, branch], { stdio: ['ignore', 'ignore', 'pipe'] })
1546
+ } catch (error) {
1547
+ const stderr = error.stderr ? error.stderr.toString() : ''
1548
+ fetchErr = stderr.split('\n').map((l) => l.trim()).find(Boolean) || 'fetch failed'
1549
+ }
1550
+ const git = gitReader(dir)
1551
+ const sha = git(['rev-parse', '--verify', '--quiet', '--short=12', `refs/remotes/${remote}/${branch}^{commit}`])
1552
+ if (!sha) {
1553
+ return {
1554
+ refused:
1555
+ `hotfix.releaseBranch is "${branch}", but ${remote}/${branch} is not known here` +
1556
+ `${fetchErr ? ` (fetch: ${fetchErr})` : ''} — nothing to fork the hotfix from.`,
1557
+ }
1558
+ }
1559
+ return { kind: 'branch', branch, sha, ref: sha }
1560
+ }
1561
+
1349
1562
  function badForkRef(cwd, ref) {
1350
1563
  const git = gitReader(cwd)
1351
1564
  if (!ref) {
@@ -1504,9 +1717,18 @@ function specEnvDown(dir, config, specArg, flags) {
1504
1717
  }
1505
1718
  const dst = dgit(['status', '--porcelain'])
1506
1719
  const contains = dgit(['branch', '--contains', spec.branch, '--list', dbase])
1720
+ let clanded = Boolean(contains && contains.trim())
1721
+ // PR mode: a squash or rebase merge never shows in ancestry, so the host's
1722
+ // answer joins it. Asked only when ancestry says no — trunk projects never
1723
+ // pay the subprocess, and cannot-tell adds nothing (landed stays false).
1724
+ if (!clanded && config.land && config.land.strategy === 'pr') {
1725
+ if (hostPrFor(dir, config.land.remote || 'origin', spec.branch).state === 'merged') {
1726
+ clanded = true
1727
+ }
1728
+ }
1507
1729
  const dplan = planDownCheckout(spec, config, flags, {
1508
1730
  dirty: dst === null || dst.length > 0,
1509
- landed: Boolean(contains && contains.trim()),
1731
+ landed: clanded,
1510
1732
  onBranch: dgit(['rev-parse', '--abbrev-ref', 'HEAD']) === spec.branch,
1511
1733
  base: dbase,
1512
1734
  checkoutPath: dir,
@@ -1538,9 +1760,28 @@ function specEnvDown(dir, config, specArg, flags) {
1538
1760
  }
1539
1761
 
1540
1762
  const base = resolveBaseBranch(config, gitReader(dir))
1541
- const worktreeState = worktreeGitState(spec.worktreePath, base)
1763
+ let worktreeState = worktreeGitState(spec.worktreePath, base)
1764
+ // PR mode: a squash or rebase merge leaves ancestry false forever, so the
1765
+ // host's answer joins `merged`. Asked only when it matters — trunk projects
1766
+ // never pay the subprocess, and an ancestry-merged branch has its answer.
1767
+ // `prState` rides along so the planner's refusal can say what it saw.
1768
+ let prAbandon = null
1769
+ if (
1770
+ config.land && config.land.strategy === 'pr' &&
1771
+ !worktreeState.merged && fs.existsSync(spec.worktreePath)
1772
+ ) {
1773
+ const remote = config.land.remote || 'origin'
1774
+ const pr = hostPrFor(spec.worktreePath, remote, spec.branch)
1775
+ worktreeState = { ...worktreeState, prState: pr.state, prUrl: pr.url }
1776
+ if (pr.state === 'merged') worktreeState.merged = true
1777
+ if (pr.state === 'open' || pr.state === 'draft') {
1778
+ const info = parseRemote(gitReader(spec.worktreePath)(['config', '--get', `remote.${remote}.url`]))
1779
+ prAbandon = prAbandonCommand(info, { branch: spec.branch, id: pr.id })
1780
+ }
1781
+ }
1542
1782
  const plan = planDown(spec, config, flags, {
1543
1783
  worktreeState,
1784
+ prAbandonCommand: prAbandon,
1544
1785
  timestamp: compactTimestamp(),
1545
1786
  composeFilePresent: composeFilePresent(dir, config),
1546
1787
  })
@@ -1901,7 +2142,7 @@ function specEnvPrune(dir, config, flags) {
1901
2142
  // Integrate: land a spec's worktree branch onto the base branch (rebase + ff).
1902
2143
  // Queries git for the facts, prints the plan / block / no-op. The /spec-complete
1903
2144
  // skill executes the printed commands (and aborts a conflicting rebase).
1904
- function specEnvIntegrate(dir, config, specArg) {
2145
+ function specEnvIntegrate(dir, config, specArg, flags = {}) {
1905
2146
 
1906
2147
  // `dir` is already anchored on the primary checkout by the dispatch, so it is
1907
2148
  // both where the spec resolves and the target of the fast-forward — /spec-complete
@@ -1909,7 +2150,34 @@ function specEnvIntegrate(dir, config, specArg) {
1909
2150
  // entirely on its branch may not exist in the primary checkout's specs/** —
1910
2151
  // resolveSpecWithWorktree offers its worktree as a fallback search location.
1911
2152
  const spec = resolveSpecWithWorktree(dir, config, specArg)
2153
+ // Fetch before resolving under a rolling base, so a spec that outlived a
2154
+ // release roll lands on the rc that exists now rather than the one the last
2155
+ // fetch saw. No pattern → no fetch, and the plan below is unchanged.
2156
+ process.stdout.write(fetchNote('integrate', config, fetchForPattern(dir, config)))
1912
2157
  const base = resolveBaseBranch(config, gitReader(dir))
2158
+ const retarget = retargetFor(gitReader(dir), config, spec.branch)
2159
+
2160
+ // PR mode replaces the local land in BOTH modes: the branch is pushed and a
2161
+ // pull request carries it, so nothing below (live handling included) applies —
2162
+ // the primary checkout is never switched and base never moves here.
2163
+ //
2164
+ // `--strategy` overrides the config per invocation — a team that lands one
2165
+ // feature by direct merge and the next by PR picks at the land, not in a
2166
+ // committed file. An unrecognised value REFUSES BY NAME rather than falling
2167
+ // through: config enums fall back because a typo there must not strengthen a
2168
+ // setting, but a flag is being typed right now and the typist can retype it —
2169
+ // silently landing the other way is the worse answer.
2170
+ if (flags.strategy !== undefined && flags.strategy !== 'ff' && flags.strategy !== 'pr') {
2171
+ process.stdout.write(
2172
+ `spec-env integrate: unknown --strategy "${flags.strategy}" — use ff or pr.\n`,
2173
+ )
2174
+ return
2175
+ }
2176
+ const strategy = flags.strategy || (config.land && config.land.strategy) || 'ff'
2177
+ if (strategy === 'pr') {
2178
+ specEnvIntegratePr(dir, config, spec, base, flags, retarget)
2179
+ return
2180
+ }
1913
2181
 
1914
2182
  // Checkout mode short-circuits everything below. The live handling in
1915
2183
  // particular reads "primary is on the spec's branch" as a live session — true
@@ -1939,7 +2207,8 @@ function specEnvIntegrate(dir, config, specArg) {
1939
2207
  return
1940
2208
  }
1941
2209
  const cout = [`spec-env integrate: ${spec.folder}`, '', ' mode: checkout',
1942
- ` base: ${base}`, ` branch: ${cplan.branch}`, '',
2210
+ ` base: ${base}`, ` branch: ${cplan.branch}`,
2211
+ ...retargetLines(retarget), '',
1943
2212
  ' run these (abort the rebase on conflict):']
1944
2213
  for (const cmd of cplan.commands) cout.push(` ${cmd}`)
1945
2214
  process.stdout.write(cout.join('\n') + '\n' + afterLandSection(cplan.afterLand))
@@ -1951,7 +2220,11 @@ function specEnvIntegrate(dir, config, specArg) {
1951
2220
  // branch, clear the receipt — so the normal rebase→ff plan below applies
1952
2221
  // unchanged. Refuse if a *different* spec holds the primary checkout.
1953
2222
  const primary = assertPrimaryOnMain(config, gitReader(dir))
1954
- if (!primary.onBase) {
2223
+ // A primary checkout on an OLDER rolling-base match is not a live session and
2224
+ // not another spec: it is the previous release candidate, still checked out
2225
+ // after the roll. The plan switches it rather than refusing.
2226
+ const primarySwitch = primary.onBase ? null : staleBaseCheckout(dir, config, primary.branch, base)
2227
+ if (!primary.onBase && !primarySwitch) {
1955
2228
  if (primary.branch !== spec.branch) {
1956
2229
  process.stdout.write(
1957
2230
  `spec-env integrate: blocked — another spec (${primary.branch}) holds the ` +
@@ -2015,7 +2288,11 @@ function specEnvIntegrate(dir, config, specArg) {
2015
2288
  const wtGit = gitReader(spec.worktreePath)
2016
2289
  const status = wtGit(['status', '--porcelain'])
2017
2290
  const dirty = status !== null && status.length > 0
2018
- const ahead = wtGit(['rev-list', '--count', `${base}..HEAD`])
2291
+ // A base this clone has no local branch for yet (a release candidate cut
2292
+ // since) is measured against its remote image — `<base>..HEAD` would not
2293
+ // resolve, read as "nothing ahead", and report the spec already landed.
2294
+ const baseRef = primarySwitch && primarySwitch.create ? `${baseRemote(config)}/${base}` : base
2295
+ const ahead = wtGit(['rev-list', '--count', `${baseRef}..HEAD`])
2019
2296
  const aheadOfBase = ahead !== null && Number(ahead) > 0
2020
2297
 
2021
2298
  const plan = planIntegrate(spec, config, {
@@ -2023,7 +2300,8 @@ function specEnvIntegrate(dir, config, specArg) {
2023
2300
  base,
2024
2301
  aheadOfBase,
2025
2302
  mainRepoPath: dir,
2026
- changedFiles: landRange(gitReader(dir), base, spec.branch),
2303
+ changedFiles: landRange(gitReader(dir), baseRef, spec.branch),
2304
+ primarySwitch,
2027
2305
  })
2028
2306
 
2029
2307
  if (plan.blocked) {
@@ -2044,12 +2322,311 @@ function specEnvIntegrate(dir, config, specArg) {
2044
2322
  out.push(` base: ${plan.base}`)
2045
2323
  out.push(` branch: ${plan.branch}`)
2046
2324
  out.push(` worktree: ${spec.worktreePath}`)
2325
+ out.push(...retargetLines(retarget))
2326
+ if (primarySwitch) out.push(` primary: on ${primarySwitch.from} — switched to ${base} before the land`)
2047
2327
  out.push('')
2048
2328
  out.push(' run these (abort the rebase on conflict):')
2049
2329
  for (const cmd of plan.commands) out.push(` ${cmd}`)
2050
2330
  process.stdout.write(out.join('\n') + '\n' + afterLandSection(plan.afterLand))
2051
2331
  }
2052
2332
 
2333
+ // The line a plan carries when the rc rolled while the spec was in flight. The
2334
+ // rebase onto the newer rc is the land working, not a mistake — but it should
2335
+ // never happen without the reader seeing it.
2336
+ function retargetLines(retarget) {
2337
+ return retarget ? [` retarget: forked from ${retarget.from} · landing onto ${retarget.to}`] : []
2338
+ }
2339
+
2340
+ // Is the primary checkout sitting on an older rolling-base match? Positive
2341
+ // signal only: the branch it has out must itself match `baseBranchPattern`
2342
+ // (locally or on the remote). Anything else — a live spec, a detached HEAD, no
2343
+ // pattern — returns null and keeps the refusals that were already there.
2344
+ function staleBaseCheckout(dir, config, branch, base) {
2345
+ const pattern = (config.baseBranchPattern || '').trim()
2346
+ if (!pattern || !branch || branch === base) return null
2347
+ const git = gitReader(dir)
2348
+ const remote = baseRemote(config)
2349
+ const local = git(['for-each-ref', '--format=%(refname:short)', `refs/heads/${pattern}`])
2350
+ const onMatch =
2351
+ (local || '').split('\n').map((l) => l.trim()).includes(branch) ||
2352
+ patternMatches(git, config).some((m) => m.name === branch)
2353
+ if (!onMatch) return null
2354
+ const status = git(['status', '--porcelain'])
2355
+ return {
2356
+ from: branch,
2357
+ // Unreadable reads as dirty: being wrong that way costs a refusal, the other
2358
+ // way switches a checkout holding work nobody could see.
2359
+ dirty: status === null || status.length > 0,
2360
+ create: git(['show-ref', '--verify', '--quiet', `refs/heads/${base}`]) === null,
2361
+ remote,
2362
+ }
2363
+ }
2364
+
2365
+ // Subprocess runner for the host adapter (`env/host.js`): never throws, and a
2366
+ // timeout bounds an `az`/`gh` call with no network — a hung lookup must not
2367
+ // hang a teardown. Every failure shape becomes { ok: false }, which the adapter
2368
+ // maps to cannot-tell.
2369
+ function hostExec(file, args, opts = {}) {
2370
+ try {
2371
+ const stdout = execFileSync(file, args, {
2372
+ stdio: ['ignore', 'pipe', 'pipe'],
2373
+ timeout: 15000,
2374
+ cwd: opts.cwd,
2375
+ }).toString()
2376
+ return { ok: true, stdout, stderr: '' }
2377
+ } catch (error) {
2378
+ return {
2379
+ ok: false,
2380
+ stdout: '',
2381
+ stderr: (error.stderr && error.stderr.toString()) || error.message || '',
2382
+ }
2383
+ }
2384
+ }
2385
+
2386
+ // The host's answer about `branch`'s PR, from the tree's own remote URL.
2387
+ // { state: merged|open|draft|none|cannot-tell, id, url } — cannot-tell on every
2388
+ // failure, including a remote this clone does not have.
2389
+ function hostPrFor(treePath, remote, branch) {
2390
+ const url = gitReader(treePath)(['config', '--get', `remote.${remote}.url`])
2391
+ return prFor(parseRemote(url), branch, hostExec, treePath)
2392
+ }
2393
+
2394
+ // PR-mode integrate: plan rebase-onto-remote-base + consent-gated push + PR.
2395
+ // The skill runs what is printed, exactly as the ff path; the difference is
2396
+ // that nothing here moves the base branch — the host does, later.
2397
+ function specEnvIntegratePr(dir, config, spec, base, flags, retarget = null) {
2398
+ const checkout = config.mode === 'checkout'
2399
+ const treePath = checkout ? dir : spec.worktreePath
2400
+ if (!checkout && !fs.existsSync(spec.worktreePath)) {
2401
+ process.stdout.write(
2402
+ `spec-env integrate: ${spec.folder} has no worktree — nothing to integrate.\n`,
2403
+ )
2404
+ return
2405
+ }
2406
+ const remote = (config.land && config.land.remote) || 'origin'
2407
+ const git = gitReader(treePath)
2408
+ const status = git(['status', '--porcelain'])
2409
+ const dirty = status !== null && status.length > 0
2410
+ // Measured against the REMOTE image of base — local base is allowed to go
2411
+ // stale in PR mode. null = no such ref here yet (never fetched): unknown, so
2412
+ // the planner plans rather than claiming landed.
2413
+ const aheadRaw = git(['rev-list', '--count', `${remote}/${base}..HEAD`])
2414
+ const aheadOfRemoteBase = aheadRaw === null ? null : Number(aheadRaw) > 0
2415
+ // A branch already on the remote at this exact HEAD is the positive signal
2416
+ // that the operator published it — the consent the hold otherwise waits for.
2417
+ const headSha = git(['rev-parse', 'HEAD'])
2418
+ const lsRemote = git(['ls-remote', remote, `refs/heads/${spec.branch}`])
2419
+ const pushedAtHead = Boolean(headSha && lsRemote && lsRemote.split(/\s/)[0] === headSha)
2420
+
2421
+ // The host's answer decides what the PR step says — `prPlanCommand` owns the
2422
+ // mapping (create · the-push-updates-it · flip-a-draft-ready · null for
2423
+ // cannot-tell, which keeps the planner's degraded placeholder). `--draft` is
2424
+ // the mid-spec form (/spec-to-main's PR-mode descendant): a draft cannot be
2425
+ // merged, so nothing downstream can close a ticket early. Plain integrate is
2426
+ // the landing verb, so a draft met without the flag is flipped ready.
2427
+ const draft = flags.draft === true
2428
+ const remoteInfo = parseRemote(git(['config', '--get', `remote.${remote}.url`]))
2429
+ const pr = remoteInfo.host ? hostPrFor(treePath, remote, spec.branch) : { state: 'cannot-tell', id: null, url: null }
2430
+
2431
+ const plan = planIntegratePr(spec, config, {
2432
+ prCreateCommand: prPlanCommand(remoteInfo, pr, { branch: spec.branch, base, draft }),
2433
+ // The finish half (printed when the host has merged): catch local base up
2434
+ // in the primary checkout and run the deferred afterLand against the
2435
+ // branch's own range — remote image first, local base as the fallback
2436
+ // when the remote ref is not here.
2437
+ primaryPath: dir,
2438
+ changedFiles: landRange(git, `${remote}/${base}`, spec.branch) || landRange(git, base, spec.branch),
2439
+ worktreeState: { dirty },
2440
+ base,
2441
+ remote,
2442
+ treePath,
2443
+ aheadOfRemoteBase,
2444
+ pushedAtHead,
2445
+ push: flags.push === true,
2446
+ onBranch: checkout
2447
+ ? git(['rev-parse', '--abbrev-ref', 'HEAD']) === spec.branch
2448
+ : undefined,
2449
+ })
2450
+
2451
+ if (plan.blocked) {
2452
+ process.stdout.write(`spec-env integrate: blocked — ${plan.reason}.\n`)
2453
+ return
2454
+ }
2455
+ if (plan.noop) {
2456
+ // Landed on the host — completion run 2. The deferred afterLand comes due
2457
+ // and local base wants catching up; the skill runs these, then its own
2458
+ // finalise (bucket move, teardown).
2459
+ const fout = [
2460
+ `spec-env integrate: ${spec.folder} already landed on ${remote}/${base} — ` +
2461
+ 'finish what the merge deferred:',
2462
+ ]
2463
+ for (const cmd of plan.finish.commands) fout.push(` ${cmd}`)
2464
+ process.stdout.write(fout.join('\n') + '\n' + afterLandSection(plan.finish.afterLand))
2465
+ return
2466
+ }
2467
+
2468
+ const out = []
2469
+ out.push(`spec-env integrate: ${spec.folder} (pr${draft ? ', draft' : ''})`)
2470
+ out.push('')
2471
+ out.push(` base: ${remote}/${base}`)
2472
+ out.push(` branch: ${plan.branch}`)
2473
+ out.push(checkout ? ` checkout: ${treePath}` : ` worktree: ${treePath}`)
2474
+ out.push(...retargetLines(retarget))
2475
+ // Silent on cannot-tell: a line about a lookup that failed accuses nothing
2476
+ // and helps nobody — the placeholder in the commands already degrades.
2477
+ if (pr.state === 'none') out.push(' pr: none yet')
2478
+ else if (pr.state !== 'cannot-tell') {
2479
+ out.push(` pr: ${pr.id ? `#${pr.id} ` : ''}${pr.state}${pr.url ? ` · ${pr.url}` : ''}`)
2480
+ }
2481
+ out.push('')
2482
+ out.push(' run these (abort the rebase on conflict):')
2483
+ for (const cmd of plan.commands) out.push(` ${cmd}`)
2484
+ if (plan.push.via === 'hold') {
2485
+ out.push('')
2486
+ out.push(' then, to publish the branch and open the PR — with your consent')
2487
+ out.push(' (or re-run with --push to plan it all as one list):')
2488
+ for (const cmd of plan.holdCommands) out.push(` ${cmd}`)
2489
+ }
2490
+ if (Array.isArray(config.afterLand) && config.afterLand.length) {
2491
+ out.push('')
2492
+ out.push(' after-land commands are deferred: base moves when the host merges,')
2493
+ out.push(' and the completion run that follows the merge plans them.')
2494
+ }
2495
+ process.stdout.write(out.join('\n') + '\n')
2496
+ }
2497
+
2498
+ // `spec-env disposition [<spec>] [--json]` — enumerate the loose ends a
2499
+ // completion must dispose before a PR goes ready: unticked tasks, phase-index
2500
+ // rows not ✅, surfaced follow-ups. Information only — it never refuses and
2501
+ // nothing gates on it; /spec-complete's PR-mode guard is the consumer, and the
2502
+ // deciding (tick · spin off · drop) is the operator's there.
2503
+ /**
2504
+ * `spec-env handoff <spec> [--json]` — what handing this spec to someone else
2505
+ * needs: its branch published, and a note for the ticket saying where the work
2506
+ * is. A planner, like `integrate`: it prints the push and runs nothing, because
2507
+ * a push is outward-facing and the skill asks before running it. The note is
2508
+ * written under `.spec-env/handoff/` (gitignored) for `spec-sync comment` to
2509
+ * post. Refusals exit 0 — `--json` carries `blocked`, and the `/commit` offer
2510
+ * where uncommitted work is what stands in the way.
2511
+ */
2512
+ function specEnvHandoff(dir, config, specArg, flags = {}) {
2513
+ const spec = resolveSpecWithWorktree(dir, config, specArg)
2514
+ const worktree = Boolean(spec.worktreePath && fs.existsSync(spec.worktreePath))
2515
+ const wtGit = worktree ? gitReader(spec.worktreePath) : () => null
2516
+ const remote = baseRemote(config)
2517
+ const remoteConfigured = worktree && wtGit(['remote', 'get-url', remote]) !== null
2518
+ const lsRemote = remoteConfigured ? wtGit(['ls-remote', '--heads', remote, `refs/heads/${spec.branch}`]) : null
2519
+ let phases = []
2520
+ if (worktree) {
2521
+ for (const bucket of BUCKETS) {
2522
+ const folder = path.join(spec.worktreePath, 'specs', bucket, spec.folder)
2523
+ if (!fs.existsSync(path.join(folder, '00-overview.md'))) continue
2524
+ phases = fs
2525
+ .readdirSync(folder)
2526
+ .filter((f) => /^(?!00-)\d{2}-.*\.md$/.test(f))
2527
+ .sort()
2528
+ .map((f) => ({ file: f, content: fs.readFileSync(path.join(folder, f), 'utf-8') }))
2529
+ break
2530
+ }
2531
+ }
2532
+ const plan = planHandoff({
2533
+ spec: { folder: spec.folder, branch: spec.branch, worktreePath: spec.worktreePath },
2534
+ worktree,
2535
+ dirtyPaths: worktree ? dirtyPaths(wtGit) : [],
2536
+ remote,
2537
+ remoteConfigured,
2538
+ headSha: worktree ? wtGit(['rev-parse', 'HEAD']) : null,
2539
+ remoteSha: lsRemote === null ? null : lsRemote.split(/\s+/)[0] || '',
2540
+ phases,
2541
+ })
2542
+
2543
+ let notePath = null
2544
+ if (!plan.blocked) {
2545
+ notePath = path.join(dir, '.spec-env', 'handoff', `${spec.folder}.md`)
2546
+ fs.mkdirSync(path.dirname(notePath), { recursive: true })
2547
+ fs.writeFileSync(notePath, plan.note)
2548
+ }
2549
+ if (flags.json) {
2550
+ const { note, ...rest } = plan
2551
+ process.stdout.write(JSON.stringify({ spec: spec.folder, ...rest, ...(notePath ? { notePath } : {}) }, null, 2) + '\n')
2552
+ return
2553
+ }
2554
+ if (plan.blocked) {
2555
+ const out = [`spec-env handoff: ${spec.folder} — blocked: ${plan.reason}`]
2556
+ if (plan.offer) out.push(` way out: ${plan.offer.command} — ${plan.offer.label}`)
2557
+ process.stdout.write(out.join('\n') + '\n')
2558
+ return
2559
+ }
2560
+ const where = plan.published
2561
+ ? 'already published at HEAD'
2562
+ : plan.remoteUnknown
2563
+ ? `could not ask ${remote} — push to be sure`
2564
+ : `not published at HEAD`
2565
+ const out = [
2566
+ `spec-env handoff: ${spec.folder}`,
2567
+ ` branch: ${plan.branch} @ ${plan.sha} (${plan.progress.total ? `${plan.progress.done} of ${plan.progress.total} phases done` : 'no phase files'})`,
2568
+ ` remote: ${remote} — ${where}`,
2569
+ ` note: ${notePath} (post it: spec-sync comment ${spec.folder} --file <note>)`,
2570
+ ]
2571
+ if (plan.commands.length) {
2572
+ out.push('', ' push it, once the operator agrees:')
2573
+ for (const c of plan.commands) out.push(` ${c}`)
2574
+ }
2575
+ process.stdout.write(out.join('\n') + '\n')
2576
+ }
2577
+
2578
+ function specEnvDisposition(dir, config, specArg, flags = {}) {
2579
+ const spec = resolveSpecWithWorktree(dir, config, specArg)
2580
+ const tree = spec.worktreePath && fs.existsSync(spec.worktreePath) ? spec.worktreePath : dir
2581
+ let folder = null
2582
+ for (const bucket of ['in-progress', 'backlog', 'complete', 'cancelled']) {
2583
+ const p = path.join(tree, 'specs', bucket, spec.folder)
2584
+ if (fs.existsSync(path.join(p, '00-overview.md'))) {
2585
+ folder = p
2586
+ break
2587
+ }
2588
+ }
2589
+ if (!folder) {
2590
+ // A specless (/no-spec) branch, or a legacy bare-file spec: nothing to
2591
+ // enumerate is a clean answer, not an error.
2592
+ const msg = `spec-env disposition: ${spec.folder} — no spec documents found; nothing to enumerate.`
2593
+ process.stdout.write(flags.json ? JSON.stringify({ spec: spec.folder, tasks: [], phases: [], followUps: [], clean: true }, null, 2) + '\n' : msg + '\n')
2594
+ return
2595
+ }
2596
+ const overview = fs.readFileSync(path.join(folder, '00-overview.md'), 'utf-8')
2597
+ const phases = fs
2598
+ .readdirSync(folder)
2599
+ .filter((f) => /^(?!00-)\d{2}-.*\.md$/.test(f))
2600
+ .sort()
2601
+ .map((f) => ({ file: f, content: fs.readFileSync(path.join(folder, f), 'utf-8') }))
2602
+ const d = collectDisposition({ overview, phases })
2603
+ if (flags.json) {
2604
+ process.stdout.write(JSON.stringify({ spec: spec.folder, ...d }, null, 2) + '\n')
2605
+ return
2606
+ }
2607
+ if (d.clean) {
2608
+ process.stdout.write(
2609
+ `spec-env disposition: ${spec.folder} — clean (no unticked tasks, no open phases, no surfaced follow-ups).\n`,
2610
+ )
2611
+ return
2612
+ }
2613
+ const out = [`spec-env disposition: ${spec.folder}`]
2614
+ if (d.tasks.length) {
2615
+ out.push(` unticked tasks (${d.tasks.length}):`)
2616
+ for (const t of d.tasks) out.push(` ${t.file}:${t.line} ${t.text}`)
2617
+ }
2618
+ if (d.phases.length) {
2619
+ out.push(` phases not ✅ (${d.phases.length}):`)
2620
+ for (const p of d.phases) out.push(` ${p.n} ${p.title} — ${p.status}`)
2621
+ }
2622
+ if (d.followUps.length) {
2623
+ out.push(` follow-ups surfaced (${d.followUps.length}):`)
2624
+ for (const f of d.followUps) out.push(` ${f.text}`)
2625
+ }
2626
+ out.push(' dispose each before the PR goes ready: tick with evidence · spin off a ticket · drop with a reason.')
2627
+ process.stdout.write(out.join('\n') + '\n')
2628
+ }
2629
+
2053
2630
  // The files a land brings into the base branch: `base...branch`, merge-base to
2054
2631
  // the branch tip. Read before the rebase runs, so it is the branch's own
2055
2632
  // changes — `base..branch` would also list what the base gained meanwhile and
@@ -2228,6 +2805,11 @@ function hotfixFinish(dir, config, specArg, flags) {
2228
2805
  return
2229
2806
  }
2230
2807
 
2808
+ if (spec.baseVersion && spec.baseVersion.kind === 'branch') {
2809
+ hotfixFinishBranch(dir, config, spec, { say, refuse, json })
2810
+ return
2811
+ }
2812
+
2231
2813
  const wtGit = gitReader(spec.worktreePath)
2232
2814
  const status = wtGit(['status', '--porcelain'])
2233
2815
  const head = wtGit(['rev-parse', 'HEAD'])
@@ -2269,6 +2851,81 @@ function hotfixFinish(dir, config, specArg, flags) {
2269
2851
  say(` deleted: ${spec.branch} (local; ${remote} keeps it)`)
2270
2852
  }
2271
2853
 
2854
+ // `hotfix finish` for a branch-based hotfix: the land and the carry, each
2855
+ // asked of git first and of the host only where git cannot answer (a squash
2856
+ // merge leaves nothing ancestry can see).
2857
+ function hotfixFinishBranch(dir, config, spec, { say, refuse, json }) {
2858
+ const remote = baseRemote(config)
2859
+ const releaseBranch = spec.baseVersion.branch
2860
+ const releaseRef = `${remote}/${releaseBranch}`
2861
+ const wtGit = gitReader(spec.worktreePath)
2862
+ const git = gitReader(dir)
2863
+ try {
2864
+ execFileSync('git', ['-C', dir, 'fetch', remote, releaseBranch], { stdio: 'ignore' })
2865
+ } catch {}
2866
+ const status = wtGit(['status', '--porcelain'])
2867
+ const record = readHotfixRecord(dir, config, spec.folder) || {}
2868
+ const fixCommits = Array.isArray(record.fixCommits) ? record.fixCommits : null
2869
+
2870
+ // Landed: HEAD on the release branch, or every fix commit's patch there, or
2871
+ // the host saying the PR merged. Only a host that cannot answer is cannot-tell.
2872
+ let landed = wtGit(['merge-base', '--is-ancestor', 'HEAD', releaseRef]) !== null
2873
+ if (!landed && fixCommits) landed = missingOn(git, releaseRef, fixCommits).length === 0
2874
+ if (!landed) {
2875
+ const pr = hostPrFor(spec.worktreePath, remote, spec.branch)
2876
+ landed = pr.state === 'merged' ? true : pr.state === 'cannot-tell' ? undefined : false
2877
+ }
2878
+
2879
+ process.stdout.write(fetchNote('hotfix finish', config, fetchForPattern(dir, config)))
2880
+ const base = resolveBaseBranch(config, git)
2881
+ let carried
2882
+ if (config.hotfix.cherryPickMain === false || base === releaseBranch) carried = 'not-needed'
2883
+ else if (!fixCommits) carried = undefined
2884
+ else {
2885
+ try {
2886
+ execFileSync('git', ['-C', dir, 'fetch', remote, base], { stdio: 'ignore' })
2887
+ } catch {}
2888
+ const refs = [`${remote}/${base}`, base].filter((r) => git(['rev-parse', '--verify', '--quiet', r]) !== null)
2889
+ carried = refs.some((r) => missingOn(git, r, fixCommits).length === 0)
2890
+ if (!carried) {
2891
+ const pr = hostPrFor(dir, remote, `carry/${spec.slug}`)
2892
+ if (pr.state === 'merged') carried = true
2893
+ }
2894
+ }
2895
+
2896
+ const registry = readRegistry(dir, config)
2897
+ const plan = planBranchHotfixFinish(spec, {
2898
+ dirty: status === null || status.length > 0,
2899
+ landed,
2900
+ carried,
2901
+ releaseBranch,
2902
+ base,
2903
+ mainRepoPath: dir,
2904
+ hasSlot: Object.prototype.hasOwnProperty.call(registry.slots, spec.folder),
2905
+ })
2906
+ if (plan.blocked) {
2907
+ refuse(plan.reasons)
2908
+ return
2909
+ }
2910
+ for (const argv of plan.argvs) {
2911
+ if (git(argv) === null) {
2912
+ refuse([`git ${argv.join(' ')} failed — nothing after it ran`])
2913
+ return
2914
+ }
2915
+ }
2916
+ fs.rmSync(hotfixRecordPath(dir, config, spec.folder), { force: true })
2917
+ if (json) {
2918
+ say(JSON.stringify({ ok: true, spec: spec.folder, landedOn: releaseBranch, carriedTo: carried === 'not-needed' ? null : base, removed: spec.worktreePath, branchDeleted: spec.branch }, null, 2))
2919
+ return
2920
+ }
2921
+ say(`spec-env hotfix finish: ${spec.folder}`)
2922
+ say('')
2923
+ say(` landed: on ${releaseRef}`)
2924
+ say(` carried: ${carried === 'not-needed' ? 'nothing to carry' : `to ${base}`}`)
2925
+ say(` removed: ${spec.worktreePath}`)
2926
+ say(` deleted: ${spec.branch}`)
2927
+ }
2928
+
2272
2929
  function specEnvHotfix(dir, config, positional, flags) {
2273
2930
  const action = positional[0]
2274
2931
  const specArg = positional[1]
@@ -2302,6 +2959,13 @@ function specEnvHotfix(dir, config, positional, flags) {
2302
2959
  refuse(`${spec.folder} has no worktree — nothing to land.`)
2303
2960
  return
2304
2961
  }
2962
+ // A release BRANCH rather than a tag: the fix lands on it by `land.strategy`.
2963
+ // Decided by the spec's own header, so a hotfix cut before the project set
2964
+ // `hotfix.releaseBranch` keeps landing the way it was cut.
2965
+ if (spec.baseVersion && spec.baseVersion.kind === 'branch') {
2966
+ hotfixLandBranch(dir, config, spec, flags, { say, refuse, json })
2967
+ return
2968
+ }
2305
2969
 
2306
2970
  const base = resolveBaseBranch(config, gitReader(dir))
2307
2971
  const wtGit = gitReader(spec.worktreePath)
@@ -2445,6 +3109,249 @@ function specEnvHotfix(dir, config, positional, flags) {
2445
3109
  if (!result.ok) process.exitCode = 1
2446
3110
  }
2447
3111
 
3112
+ // The fix commits of a branch-based hotfix, and which of them `ref` already
3113
+ // has. The list is taken BEFORE the land — `<release>..HEAD`, the hotfix's own
3114
+ // commits — and recorded, because once the land has happened that range is
3115
+ // empty and nothing else in the history says which commits were the fix.
3116
+ // A recorded list wins on every later run.
3117
+ function branchFixCommits(dir, config, spec, wtGit, releaseRef) {
3118
+ const record = readHotfixRecord(dir, config, spec.folder) || {}
3119
+ if (Array.isArray(record.fixCommits) && record.fixCommits.length) return record.fixCommits
3120
+ const own = wtGit(['rev-list', '--reverse', '--no-merges', `${releaseRef}..HEAD`])
3121
+ const commits = (own ? own.split('\n') : []).map((x) => x.trim()).filter(Boolean)
3122
+ if (commits.length) writeHotfixRecord(dir, config, spec.folder, { ...record, fixCommits: commits })
3123
+ return commits.length ? commits : null
3124
+ }
3125
+
3126
+ // Which of `commits` `ref` does not have yet, by patch rather than by sha — a
3127
+ // cherry-pick or a squash merge is the same change under another sha. `git
3128
+ // cherry` prints `+ <sha>` for a change `ref` lacks, `- <sha>` for one it has
3129
+ // under another sha, and NOTHING when the commit itself is already in `ref`. A
3130
+ // commit git will not compare stays in the list: it then fails as an empty
3131
+ // pick, loudly, which is the safe direction to be wrong in.
3132
+ function missingOn(git, ref, commits) {
3133
+ return commits.filter((sha) => {
3134
+ const out = git(['cherry', ref, sha, `${sha}^`])
3135
+ return out === null || out.split('\n').some((l) => l.trim().startsWith('+'))
3136
+ })
3137
+ }
3138
+
3139
+ // How a branch-based hotfix's carry would run now, or null for no carry.
3140
+ function branchCarry(dir, config, spec, strategy, releaseBranch, fixCommits) {
3141
+ if (config.hotfix.cherryPickMain === false || !fixCommits) return null
3142
+ process.stdout.write(fetchNote('hotfix land', config, fetchForPattern(dir, config)))
3143
+ const base = resolveBaseBranch(config, gitReader(dir))
3144
+ if (base === releaseBranch) return null
3145
+ const remote = baseRemote(config)
3146
+ const git = gitReader(dir)
3147
+ try {
3148
+ execFileSync('git', ['-C', dir, 'fetch', remote, base], { stdio: 'ignore' })
3149
+ } catch {}
3150
+ const hasLocal = git(['show-ref', '--verify', '--quiet', `refs/heads/${base}`]) !== null
3151
+ const files = carryFiles(git, fixCommits)
3152
+ if (strategy === 'pr') {
3153
+ const carryBranch = `carry/${spec.slug}`
3154
+ const commits = missingOn(git, `${remote}/${base}`, fixCommits)
3155
+ const pr = hostPrFor(dir, remote, carryBranch)
3156
+ const info = parseRemote(git(['config', '--get', `remote.${remote}.url`]))
3157
+ return {
3158
+ base,
3159
+ strategy: 'pr',
3160
+ path: dir,
3161
+ root: dir,
3162
+ tmpPath: path.join(path.dirname(spec.worktreePath), `${spec.slug}-carry`),
3163
+ commits,
3164
+ startRef: `${remote}/${base}`,
3165
+ carryBranch,
3166
+ prState: pr.state,
3167
+ prCommand: prPlanCommand(info, pr, { branch: carryBranch, base, draft: false }),
3168
+ files,
3169
+ }
3170
+ }
3171
+ const commits = missingOn(git, hasLocal ? base : `${remote}/${base}`, fixCommits)
3172
+ // Where the base is checked out decides how: in place when clean, refused
3173
+ // when dirty, a throwaway worktree when it is checked out nowhere.
3174
+ const list = git(['worktree', 'list', '--porcelain']) || ''
3175
+ let where = null
3176
+ let current = null
3177
+ for (const line of list.split('\n')) {
3178
+ if (line.startsWith('worktree ')) current = line.slice('worktree '.length)
3179
+ else if (line === `branch refs/heads/${base}`) where = current
3180
+ }
3181
+ if (where) {
3182
+ const st = gitReader(where)(['status', '--porcelain'])
3183
+ return { base, strategy: st ? 'dirty' : 'inplace', path: where, root: dir, commits, files }
3184
+ }
3185
+ const tmpPath = path.join(path.dirname(spec.worktreePath), `${spec.slug}-carry-${base.replace(/[^a-zA-Z0-9]+/g, '-')}`)
3186
+ return { base, strategy: 'worktree', path: dir, root: dir, tmpPath, commits, files }
3187
+ }
3188
+
3189
+ // `hotfix land` for a branch-based hotfix: gather the facts, plan with
3190
+ // `planBranchHotfixLand`, run the steps — land, tag, then carry to the rc.
3191
+ function hotfixLandBranch(dir, config, spec, flags, { say, refuse, json }) {
3192
+ if (flags.strategy !== undefined && flags.strategy !== 'ff' && flags.strategy !== 'pr') {
3193
+ refuse(`unknown --strategy "${flags.strategy}" — use ff or pr.`)
3194
+ return
3195
+ }
3196
+ const strategy = flags.strategy || (config.land && config.land.strategy) || 'ff'
3197
+ const remote = baseRemote(config)
3198
+ const releaseBranch = spec.baseVersion.branch
3199
+ const releaseRef = `${remote}/${releaseBranch}`
3200
+ const wtGit = gitReader(spec.worktreePath)
3201
+
3202
+ // The land is onto the release branch as it is NOW. A failed fetch leaves the
3203
+ // last-fetched image, which a non-fast-forward push refuses loudly if stale.
3204
+ try {
3205
+ execFileSync('git', ['-C', spec.worktreePath, 'fetch', remote, releaseBranch], { stdio: 'ignore' })
3206
+ } catch {}
3207
+
3208
+ const status = wtGit(['status', '--porcelain'])
3209
+ const isAncestor = (a, b) => wtGit(['merge-base', '--is-ancestor', a, b]) !== null
3210
+ const head = wtGit(['rev-parse', 'HEAD'])
3211
+ const tagList = wtGit(['tag', '--list'])
3212
+ const existingTags = tagList ? tagList.split('\n').map((t) => t.trim()).filter(Boolean) : []
3213
+ const record = readHotfixRecord(dir, config, spec.folder)
3214
+ const atHead = (wtGit(['tag', '--points-at', 'HEAD']) || '').split('\n').map((t) => t.trim())
3215
+ // ff: a recorded release counts while HEAD still carries it. pr: the tag sits
3216
+ // on the release branch, never on HEAD, so the record and the tag existing is
3217
+ // the signal.
3218
+ const released =
3219
+ record && record.tag && (strategy === 'pr' ? existingTags.includes(record.tag) : atHead.includes(record.tag))
3220
+ ? record
3221
+ : null
3222
+ const tagPushed = released !== null && Boolean(wtGit(['ls-remote', '--tags', remote, `refs/tags/${released.tag}`]))
3223
+ const remoteHead = (wtGit(['ls-remote', '--heads', remote, `refs/heads/${spec.branch}`]) || '').split(/\s+/)[0] || null
3224
+
3225
+ let pr = null
3226
+ let prCommand = null
3227
+ if (strategy === 'pr') {
3228
+ pr = hostPrFor(spec.worktreePath, remote, spec.branch)
3229
+ const info = parseRemote(wtGit(['config', '--get', `remote.${remote}.url`]))
3230
+ // Ready, never draft: a hotfix is finished work.
3231
+ prCommand = prPlanCommand(info, pr, { branch: spec.branch, base: releaseBranch, draft: false })
3232
+ }
3233
+ const fixCommits = branchFixCommits(dir, config, spec, wtGit, releaseRef)
3234
+ const carry = branchCarry(dir, config, spec, strategy, releaseBranch, fixCommits)
3235
+
3236
+ let plan
3237
+ try {
3238
+ plan = planBranchHotfixLand(spec, config, {
3239
+ dirty: status === null || status.length > 0,
3240
+ remote,
3241
+ strategy,
3242
+ push: flags.push === true,
3243
+ behind: !isAncestor(releaseRef, 'HEAD'),
3244
+ onRelease: isAncestor('HEAD', releaseRef),
3245
+ headOnRemote: Boolean(head) && remoteHead === head,
3246
+ pr,
3247
+ prCommand,
3248
+ lastTag: wtGit(['describe', '--tags', '--abbrev=0', releaseRef]),
3249
+ existingTags,
3250
+ released,
3251
+ tagPushed,
3252
+ carry,
3253
+ })
3254
+ } catch (error) {
3255
+ refuse(`${error.message}.`)
3256
+ return
3257
+ }
3258
+ if (plan.blocked) {
3259
+ refuse(`blocked — ${plan.reason}.`)
3260
+ return
3261
+ }
3262
+ if (plan.noop) {
3263
+ if (json) say(JSON.stringify({ ok: true, noop: true, reason: plan.reason }, null, 2))
3264
+ else say(`spec-env hotfix land: ${plan.reason}.`)
3265
+ return
3266
+ }
3267
+
3268
+ const header = () => {
3269
+ say(`spec-env hotfix land: ${spec.folder}${flags.plan ? ' (plan — nothing run)' : ''}`)
3270
+ say('')
3271
+ say(` release: ${releaseRef} (${strategy === 'pr' ? 'by pull request' : 'fast-forward'})`)
3272
+ say(` branch: ${spec.branch}`)
3273
+ if (carry) say(` carry to: ${carry.base}${carry.strategy === 'pr' ? ` (via ${carry.carryBranch})` : ''}`)
3274
+ }
3275
+ if (flags.plan) {
3276
+ if (json) {
3277
+ say(JSON.stringify({ spec: spec.folder, planned: true, strategy, steps: plan.steps }, null, 2))
3278
+ return
3279
+ }
3280
+ header()
3281
+ say('')
3282
+ plan.steps.forEach((st, i) => say(` ${i + 1}. ${describeHotfixStep(st)}`))
3283
+ return
3284
+ }
3285
+
3286
+ if (!json) {
3287
+ header()
3288
+ say('')
3289
+ }
3290
+ const result = runHotfixLand(plan.steps, {
3291
+ write: json ? () => {} : (line) => say(` ${line}`),
3292
+ childStdout: json ? process.stderr : 'inherit',
3293
+ // Merged into what is there, so the recorded fix commits survive a release.
3294
+ record: (release) =>
3295
+ writeHotfixRecord(dir, config, spec.folder, {
3296
+ ...(readHotfixRecord(dir, config, spec.folder) || {}),
3297
+ ...release,
3298
+ at: new Date().toISOString(),
3299
+ }),
3300
+ })
3301
+ const tag = result.release ? result.release.tag : null
3302
+ const last = result.results[result.results.length - 1]
3303
+
3304
+ if (json) {
3305
+ say(
3306
+ JSON.stringify(
3307
+ {
3308
+ spec: spec.folder,
3309
+ planned: false,
3310
+ strategy,
3311
+ ok: result.ok,
3312
+ held: result.held === true,
3313
+ waiting: Boolean(last && last.step.kind === 'wait'),
3314
+ failedAt: result.failedAt,
3315
+ release: result.release,
3316
+ steps: result.results.map((r) => ({ ...r.step, outcome: r.outcome, line: r.line })),
3317
+ remaining: plan.steps.slice(result.results.length),
3318
+ },
3319
+ null,
3320
+ 2,
3321
+ ),
3322
+ )
3323
+ } else if (result.held && last.step.kind === 'wait') {
3324
+ say('')
3325
+ say(` landing: the PR into ${releaseBranch} is open — re-run \`skitterspec spec-env hotfix land ${spec.folder}\` once it merges`)
3326
+ } else if (result.held && last.step.kind === 'carry') {
3327
+ say('')
3328
+ say(` landed: on ${releaseRef}${tag ? ` · tagged ${tag}` : ''}`)
3329
+ say(` held: the carry to ${last.step.base} — re-run with --push to push ${last.step.carryBranch} and open its PR.`)
3330
+ } else if (result.held) {
3331
+ const st = last.step
3332
+ const refs = [...(Array.isArray(st.refs) ? st.refs : []), ...(st.withTag !== false && tag ? [tag] : [])]
3333
+ say('')
3334
+ say(` held: nothing pushed — the push to ${remote} is what ${strategy === 'pr' ? 'opens the PR' : 'lands the fix'}.`)
3335
+ say(' re-run with --push, or run:')
3336
+ for (const ref of refs) {
3337
+ say(` git -C ${spec.worktreePath} push ${st.force ? '--force-with-lease -u ' : ''}${remote} ${ref}`)
3338
+ }
3339
+ say(` then re-run \`skitterspec spec-env hotfix land ${spec.folder}\`.`)
3340
+ } else if (result.ok) {
3341
+ say('')
3342
+ say(` landed: on ${releaseRef}${tag ? ` · tagged ${tag}` : ''}`)
3343
+ if (result.carried) process.stdout.write(afterLandSection(plan.afterLand))
3344
+ } else {
3345
+ process.stderr.write(` ${last.line}\n`)
3346
+ say(
3347
+ `spec-env hotfix land: stopped at step ${result.failedAt} of ${plan.steps.length} ` +
3348
+ `(${describeHotfixStep(last.step)}) — nothing after it ran.`,
3349
+ )
3350
+ if (tag) say(` ${tag} was cut and is recorded — a re-run carries on from it.`)
3351
+ }
3352
+ if (!result.ok) process.exitCode = 1
3353
+ }
3354
+
2448
3355
  // What the primary checkout has GAINED right now, by content. `dir` is already
2449
3356
  // anchored on the primary checkout by the dispatcher, so this reads the tree the
2450
3357
  // build must not be writing into. See env/building.js for why this is two
@@ -2543,6 +3450,128 @@ function specEnvResolve(dir, config, specArg, flags = {}) {
2543
3450
  )
2544
3451
  }
2545
3452
 
3453
+ /**
3454
+ * `skitterspec spec-env base [--json]`
3455
+ *
3456
+ * Which branch is the base, how it was found, and — under `baseBranchPattern` —
3457
+ * every match newest-first plus the provisioned specs that forked from an older
3458
+ * one. It fetches first, because the resolver itself never does: a release
3459
+ * candidate cut since the last fetch is invisible to it.
3460
+ *
3461
+ * Lists only and always exits 0. A failed fetch is reported and the listing
3462
+ * carries on from the refs already here; nothing is edited, and pinning stays a
3463
+ * hand edit of `baseBranch`.
3464
+ */
3465
+ function specEnvBase(dir, config, flags = {}) {
3466
+ const pattern = (config.baseBranchPattern || '').trim()
3467
+ const remote = baseRemote(config)
3468
+ const git = gitReader(dir)
3469
+
3470
+ // No pattern: the base is today's chain, and there is nothing to fetch for —
3471
+ // origin/HEAD is not updated by a fetch.
3472
+ const fetch = fetchForPattern(dir, config)
3473
+ const { base, how } = describeBaseBranch(config, git)
3474
+
3475
+ let matches = []
3476
+ let forks = []
3477
+ if (pattern) {
3478
+ matches = patternMatches(git, config)
3479
+ const names = matches.map((m) => m.name)
3480
+ forks = provisionedBranches(dir, config).map(({ spec, branch }) => ({
3481
+ spec,
3482
+ forkedFrom: forkedFromMatch(git, config, names, branch),
3483
+ }))
3484
+ }
3485
+
3486
+ const { json, lines } = planBaseReport({ pattern, remote, base, how, fetch, matches, forks })
3487
+ process.stdout.write(flags.json ? JSON.stringify(json, null, 2) + '\n' : lines.join('\n') + '\n')
3488
+ }
3489
+
3490
+ // Fetch the base's remote, but only where `baseBranchPattern` decides the base:
3491
+ // the resolver reads remote-tracking refs and never the network, so a release
3492
+ // candidate cut since the last fetch is invisible until something fetches. With
3493
+ // no pattern nothing is fetched and every plan stays byte-identical.
3494
+ // Returns null (no pattern) or { ok, reason }; never throws.
3495
+ function fetchForPattern(dir, config) {
3496
+ if (!(config.baseBranchPattern || '').trim()) return null
3497
+ try {
3498
+ execFileSync('git', ['-C', dir, 'fetch', '--prune', baseRemote(config)], { stdio: ['ignore', 'ignore', 'pipe'] })
3499
+ return { ok: true, reason: null }
3500
+ } catch (error) {
3501
+ const stderr = error.stderr ? error.stderr.toString() : ''
3502
+ return { ok: false, reason: stderr.split('\n').map((l) => l.trim()).find(Boolean) || null }
3503
+ }
3504
+ }
3505
+
3506
+ // One line for a plan whose fetch failed; nothing for one that worked or never
3507
+ // ran. A failed fetch is not a refusal — the refs already here still resolve.
3508
+ function fetchNote(verb, config, fetch) {
3509
+ if (!fetch || fetch.ok) return ''
3510
+ return (
3511
+ `spec-env ${verb}: fetch from ${baseRemote(config)} failed` +
3512
+ `${fetch.reason ? ` (${fetch.reason})` : ''} — resolving from the refs already here.\n`
3513
+ )
3514
+ }
3515
+
3516
+ // Every remote branch matching `baseBranchPattern`, newest first by committer
3517
+ // date, as { name, date } with the remote prefix stripped.
3518
+ function patternMatches(git, config) {
3519
+ const pattern = (config.baseBranchPattern || '').trim()
3520
+ if (!pattern) return []
3521
+ const prefix = `refs/remotes/${baseRemote(config)}/`
3522
+ const out = git([
3523
+ 'for-each-ref',
3524
+ '--sort=-committerdate',
3525
+ '--format=%(refname)%09%(committerdate:short)',
3526
+ `${prefix}${pattern}`,
3527
+ ])
3528
+ return (out || '')
3529
+ .split('\n')
3530
+ .map((line) => line.split('\t'))
3531
+ .filter(([ref]) => ref && ref.startsWith(prefix) && ref !== `${prefix}HEAD`)
3532
+ .map(([ref, date]) => ({ name: ref.slice(prefix.length), date: date || null }))
3533
+ }
3534
+
3535
+ // Which pattern match `branch` forked from (see `forkMatch`), or null.
3536
+ function forkedFromMatch(git, config, names, branch) {
3537
+ const prefix = `refs/remotes/${baseRemote(config)}/`
3538
+ return forkMatch(
3539
+ names,
3540
+ (name) => git(['merge-base', branch, `${prefix}${name}`]),
3541
+ (a, b) => git(['merge-base', '--is-ancestor', a, b]) !== null,
3542
+ )
3543
+ }
3544
+
3545
+ // `{ from, to }` when a branch forked from an older pattern match than the base
3546
+ // it is about to land on — the rc rolled while the spec was in flight. Null
3547
+ // whenever the pattern did not choose the base (a pin is a deliberate choice,
3548
+ // and no pattern means no roll), and on every cannot-tell.
3549
+ function retargetFor(git, config, branch) {
3550
+ const { base, how } = describeBaseBranch(config, git)
3551
+ if (how !== 'pattern' || !base) return null
3552
+ const from = forkedFromMatch(git, config, patternMatches(git, config).map((m) => m.name), branch)
3553
+ return from && from !== base ? { from, to: base } : null
3554
+ }
3555
+
3556
+ // Every provisioned spec with the branch its worktree has checked out. A
3557
+ // worktree on a detached HEAD (a spec taken live) names no branch and is left
3558
+ // out: there is nothing to compute a fork from, and saying nothing is the
3559
+ // harmless answer.
3560
+ function provisionedBranches(dir, config) {
3561
+ const list = gitReader(dir)(['worktree', 'list', '--porcelain'])
3562
+ const branchAt = new Map()
3563
+ let current = null
3564
+ for (const line of (list || '').split('\n')) {
3565
+ if (line.startsWith('worktree ')) current = path.resolve(line.slice('worktree '.length).trim())
3566
+ else if (line.startsWith('branch refs/heads/') && current) branchAt.set(current, line.slice('branch refs/heads/'.length))
3567
+ }
3568
+ return allSpecs(dir, config, new Set(branchAt.keys()), speclessMap(dir, config))
3569
+ .map((s) => ({ spec: s.folder, wt: path.resolve(s.worktreePath) }))
3570
+ .filter((s) => s.wt !== path.resolve(dir) && branchAt.has(s.wt))
3571
+ .map((s) => ({ spec: s.spec, branch: branchAt.get(s.wt) }))
3572
+ .sort((a, b) => a.spec.localeCompare(b.spec))
3573
+ }
3574
+
2546
3575
  /**
2547
3576
  * `skitterspec spec-env stage [<spec>] [--json]`
2548
3577
  *
@@ -3605,8 +4634,11 @@ async function specEnvReview(dir, config, specArg, flags, invokedFrom = dir) {
3605
4634
  // tag is not an ancestor of the base branch (a release line that never merged
3606
4635
  // back) the range widens to include commits the hotfix never touched.
3607
4636
  //
3608
- // Lazy, so the common working-tree path pays nothing for it.
3609
- const reviewBase = () => spec.baseRef || resolveBaseBranch(config, trimmed)
4637
+ // Lazy, so the common working-tree path pays nothing for it. PR mode prefers
4638
+ // the remote image of base via `preferRemoteBase` — one helper shared with
4639
+ // serve.js, so the two renders cannot disagree about a spec's range.
4640
+ const reviewBase = () =>
4641
+ spec.baseRef || preferRemoteBase(config, resolveBaseBranch(config, trimmed), trimmed)
3610
4642
 
3611
4643
  if (flags.branch) {
3612
4644
  base = reviewBase()
@@ -5311,6 +6343,19 @@ function liveGrammar(dir, config, positional) {
5311
6343
  * would be a second copy free to drift from the first.
5312
6344
  */
5313
6345
  function bareLive(dir, config) {
6346
+ // The workbench must be FREE, not merely un-refused — and it is asked FIRST,
6347
+ // before which spec is even a question. A held instance refuses every bare
6348
+ // take no matter what resolves, so the ambiguity note below would ask the
6349
+ // reader to name a spec that naming cannot help — an ask that buries the
6350
+ // report's own `in-flight:` line, which is the real answer. The report names
6351
+ // the branch, the in-flight spec and the receipt, so it already says why
6352
+ // nothing was taken, and a note here would only contradict it.
6353
+ const primary = assertPrimaryOnMain(config, gitReader(dir))
6354
+ const receipt = readReceipt(dir, config)
6355
+ if (!primary.onBase || (receipt && receipt.spec)) {
6356
+ return { action: 'status', specArg: undefined }
6357
+ }
6358
+
5314
6359
  const choice = provisionedSpecChoice(dir, config)
5315
6360
  if (!choice.folder) {
5316
6361
  // Several worktrees is the only cannot-tell the status report does not
@@ -5324,15 +6369,6 @@ function bareLive(dir, config) {
5324
6369
  return { action: 'status', specArg: undefined, note }
5325
6370
  }
5326
6371
 
5327
- // The workbench must be FREE, not merely un-refused. When it is not, the
5328
- // report names the branch, the in-flight spec and the receipt — so it already
5329
- // says why nothing was taken, and a note here would only repeat it.
5330
- const primary = assertPrimaryOnMain(config, gitReader(dir))
5331
- const receipt = readReceipt(dir, config)
5332
- if (!primary.onBase || (receipt && receipt.spec)) {
5333
- return { action: 'status', specArg: undefined }
5334
- }
5335
-
5336
6372
  // Resolved here rather than passed as `undefined`, so the verb acts on the
5337
6373
  // spec this function actually decided about.
5338
6374
  return { action: 'take', specArg: choice.folder }
@@ -5768,6 +6804,8 @@ async function specEnv(rest) {
5768
6804
  else if (args[i] === '--docs') flags.docs = true
5769
6805
  else if (args[i] === '--plan') flags.plan = true
5770
6806
  else if (args[i] === '--push') flags.push = true
6807
+ else if (args[i] === '--draft') flags.draft = true
6808
+ else if (args[i] === '--strategy') flags.strategy = args[++i]
5771
6809
  else if (args[i] === '--from') flags.from = args[++i]
5772
6810
  else if (args[i] === '--session') flags.session = args[++i]
5773
6811
  else if (args[i] === '--path') flags.path = args[++i]
@@ -5865,7 +6903,13 @@ async function specEnv(rest) {
5865
6903
  await specEnvConnect(dir, config, positional[0])
5866
6904
  break
5867
6905
  case 'integrate':
5868
- specEnvIntegrate(dir, config, positional[0])
6906
+ specEnvIntegrate(dir, config, positional[0], flags)
6907
+ break
6908
+ case 'disposition':
6909
+ specEnvDisposition(dir, config, positional[0], flags)
6910
+ break
6911
+ case 'handoff':
6912
+ specEnvHandoff(dir, config, positional[0], flags)
5869
6913
  break
5870
6914
  case 'hotfix':
5871
6915
  specEnvHotfix(dir, config, positional, flags)
@@ -5876,6 +6920,9 @@ async function specEnv(rest) {
5876
6920
  case 'resolve':
5877
6921
  specEnvResolve(dir, config, positional[0], flags)
5878
6922
  break
6923
+ case 'base':
6924
+ specEnvBase(dir, config, flags)
6925
+ break
5879
6926
  case 'stage':
5880
6927
  specEnvStage(dir, config, positional[0], flags, invokedFrom)
5881
6928
  break
@@ -5976,6 +7023,11 @@ async function run(argv) {
5976
7023
  return
5977
7024
  }
5978
7025
 
7026
+ if (cmd === 'status') {
7027
+ inFlightStatus(rest)
7028
+ return
7029
+ }
7030
+
5979
7031
  const { opts, positional } = parse(rest)
5980
7032
  const dir = path.resolve(opts.dir || positional[0] || process.cwd())
5981
7033