@skitterbyte/skitterspec-linear 19.3.0 → 19.5.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 (71) hide show
  1. package/assets/claude-md-section.md +20 -1
  2. package/assets/core/SETUP.md +5 -0
  3. package/assets/core/env.config.json.example +1 -0
  4. package/assets/core/env.config.md +143 -8
  5. package/assets/core/linear.config.json.example +2 -2
  6. package/assets/core/linear.config.md +49 -16
  7. package/assets/hooks/main-guard.cjs +40 -6
  8. package/assets/hooks/review-gate.cjs +42 -7
  9. package/assets/rules/commit-trailers.md +24 -1
  10. package/assets/rules/spec-planning.md +81 -18
  11. package/assets/rules/spec-reports.md +1 -1
  12. package/assets/skills/spec/SKILL.md +55 -2
  13. package/assets/skills/spec-bug/SKILL.md +36 -3
  14. package/assets/skills/spec-cancel/SKILL.md +37 -0
  15. package/assets/skills/spec-claim/SKILL.md +41 -2
  16. package/assets/skills/spec-complete/SKILL.md +115 -0
  17. package/assets/skills/spec-hotfix/SKILL.md +51 -4
  18. package/assets/skills/spec-incident/SKILL.md +22 -0
  19. package/assets/skills/spec-linear-setup/SKILL.md +23 -1
  20. package/assets/skills/spec-next/SKILL.md +12 -5
  21. package/assets/skills/spec-push/SKILL.md +22 -0
  22. package/assets/skills/spec-review/SKILL.md +34 -0
  23. package/assets/skills/spec-start/SKILL.md +50 -3
  24. package/assets/skills/spec-status/SKILL.md +18 -3
  25. package/assets/skills/spec-sync/SKILL.md +1 -0
  26. package/assets/skills/spec-to-main/SKILL.md +47 -1
  27. package/package.json +1 -1
  28. package/src/cli.js +1188 -79
  29. package/src/env/base.js +104 -0
  30. package/src/env/bootstrap.js +22 -3
  31. package/src/env/classify.js +12 -4
  32. package/src/env/config.js +77 -5
  33. package/src/env/disposition.js +62 -0
  34. package/src/env/handoff.js +81 -0
  35. package/src/env/host.js +262 -0
  36. package/src/env/hotfix.js +237 -9
  37. package/src/env/hotfixland.js +105 -10
  38. package/src/env/inflight.js +98 -0
  39. package/src/env/integrate.js +136 -9
  40. package/src/env/live.js +8 -7
  41. package/src/env/mainguard.js +20 -5
  42. package/src/env/phases.js +28 -0
  43. package/src/env/project.js +223 -0
  44. package/src/env/provision.js +30 -8
  45. package/src/env/resolve.js +147 -25
  46. package/src/env/review.js +21 -7
  47. package/src/env/reviewers.js +7 -10
  48. package/src/env/serve.js +27 -11
  49. package/src/env/specstate.js +101 -0
  50. package/src/env/supervise.js +15 -2
  51. package/src/env/teardown.js +46 -3
  52. package/src/init.js +49 -9
  53. package/src/vendor/linear/cli-sanitise.js +8 -3
  54. package/src/vendor/linear/cli-sync.js +64 -10
  55. package/src/vendor/linear/config.js +27 -21
  56. package/src/vendor/linear/doctor.js +2 -0
  57. package/src/vendor/provider-kit/index.js +4 -0
  58. package/src/vendor/provider-kit/src/apply.js +58 -6
  59. package/src/vendor/provider-kit/src/assignment.js +78 -1
  60. package/src/vendor/provider-kit/src/config.js +34 -1
  61. package/src/vendor/provider-kit/src/credentials.js +7 -2
  62. package/src/vendor/provider-kit/src/list-rows.js +35 -11
  63. package/src/vendor/provider-kit/src/released.js +48 -4
  64. package/src/vendor/provider-kit/src/specs.js +18 -7
  65. package/src/vendor/provider-kit/src/splice.js +64 -0
  66. package/src/vendor/provider-kit/src/status.js +137 -0
  67. package/src/vendor/sync-core/index.js +14 -1
  68. package/src/vendor/sync-core/src/compare.js +81 -6
  69. package/src/vendor/sync-core/src/normalize.js +50 -7
  70. package/src/vendor/sync-core/src/push.js +65 -5
  71. 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,17 +62,30 @@ const {
58
62
  resolveSpec,
59
63
  resolveSpecless,
60
64
  resolveBaseBranch,
65
+ describeBaseBranch,
66
+ baseRemote,
61
67
  liveWorktreePaths,
62
68
  collectSpecFolders,
63
69
  allSpecs,
64
- resolvePrimaryCheckout,
65
70
  assertPrimaryOnMain,
66
71
  currentBranch,
67
72
  repoInfo,
68
73
  expandTokens,
69
74
  splitPrefix,
75
+ parseBaseVersion,
70
76
  BUCKETS,
71
77
  } = require('./env/resolve.js')
78
+ const {
79
+ primaryAnchor,
80
+ attachProject,
81
+ repoRootOf,
82
+ prefixOf,
83
+ toRepoPath,
84
+ projectRelative,
85
+ projectIn,
86
+ projectLine,
87
+ shellPath,
88
+ } = require('./env/project.js')
72
89
  const building = require('./env/building.js')
73
90
  const {
74
91
  readReceipt,
@@ -165,8 +182,12 @@ const {
165
182
  mainGuardStatus,
166
183
  } = require('./env/mainguard.js')
167
184
  const { planPrune, liveSlugsForSpecs, reconcileRegistry } = require('./env/prune.js')
168
- const { planIntegrate, planIntegrateCheckout } = require('./env/integrate.js')
169
- const { planHotfixLand, planHotfixFinish } = require('./env/hotfix.js')
185
+ const { planIntegrate, planIntegrateCheckout, planIntegratePr } = require('./env/integrate.js')
186
+ const { parseRemote, prFor, prPlanCommand, prAbandonCommand, preferRemoteBase } = require('./env/host.js')
187
+ const { collectDisposition } = require('./env/disposition.js')
188
+ const { planHandoff } = require('./env/handoff.js')
189
+ const { collectInFlight, detailOf, formatInFlight, isInFlight } = require('./env/inflight.js')
190
+ const { planHotfixLand, planBranchHotfixLand, planBranchHotfixFinish, planHotfixFinish } = require('./env/hotfix.js')
170
191
  const { runHotfixLand, describeStep: describeHotfixStep } = require('./env/hotfixland.js')
171
192
  const { planDev } = require('./env/dev.js')
172
193
  const { startProcess, stopProcess, waitHealthy, readPid, isAlive } = require('./env/supervise.js')
@@ -243,7 +264,13 @@ Usage:
243
264
  dev up <spec> start host dev servers on the spec's ports
244
265
  dev down <spec> stop the spec's host dev servers
245
266
  connect <spec> expose a spec on the canonical ports (main = off)
246
- integrate <spec> plan rebase + fast-forward onto the base branch
267
+ integrate <spec> plan the land: rebase + fast-forward, or in PR
268
+ mode push + PR (--push, --draft, --strategy)
269
+ disposition <spec>
270
+ list unticked tasks, open phases and surfaced
271
+ follow-ups to dispose before a PR goes ready
272
+ handoff <spec> plan handing a spec to someone else: publish
273
+ its branch, write the ticket note (--json)
247
274
  hotfix land <spec>
248
275
  release, push (--push), carry a hotfix to
249
276
  the base branch (--plan, --also <tag>)
@@ -261,6 +288,12 @@ Usage:
261
288
  documents and everything else
262
289
  status list provisioned specs + port blocks
263
290
  resolve <spec> print resolved slug/type/branch/paths
291
+ base fetch, list baseBranchPattern matches
292
+ newest-first, mark the base, and name
293
+ specs forked from an older match
294
+ skitterspec status What is in flight here: every spec with a worktree,
295
+ its bucket and phase progress read from that
296
+ worktree (--json). Offline; always exits 0.
264
297
  skitterspec gating <cmd> Release-gating check (opt-in; needs
265
298
  specs/.core/gating.config.json). Subcommands:
266
299
  check [spec] report specs with no recorded gating
@@ -437,14 +470,28 @@ function specEnvReviewWaiting(dir, config, flags) {
437
470
  process.stdout.write(section ? `${section.replace(/^\n/, '')}` : 'spec-env review: nothing waiting.\n')
438
471
  }
439
472
 
440
- function specEnvStatus(dir, config) {
473
+ // Every spec with a worktree of its own, sorted. Shared by `spec-env status` and
474
+ // the top-level `skitterspec status`, so the two can never disagree about what
475
+ // is provisioned.
476
+ function provisionedSpecs(dir, config) {
441
477
  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))
478
+ return (
479
+ allSpecs(dir, config, worktreePaths, speclessMap(dir, config))
480
+ .map((s) => ({
481
+ folder: s.folder,
482
+ wt: path.resolve(s.worktreePath),
483
+ project: path.resolve(s.projectPath),
484
+ specless: s.specless,
485
+ }))
486
+ // The primary checkout is itself in `git worktree list`; a spec is
487
+ // provisioned only when it has its OWN worktree, separate from it.
488
+ .filter((s) => s.wt !== dir && worktreePaths.has(s.wt))
489
+ .sort((a, b) => a.folder.localeCompare(b.folder))
490
+ )
491
+ }
492
+
493
+ function specEnvStatus(dir, config) {
494
+ const provisioned = provisionedSpecs(dir, config)
448
495
 
449
496
  // REACHED EITHER WAY. This used to return here, so a repo with nothing in
450
497
  // flight could say nothing about a waiting pass — and a repo with nothing in
@@ -455,8 +502,9 @@ function specEnvStatus(dir, config) {
455
502
  }
456
503
 
457
504
  const registry = readRegistry(dir, config)
505
+ const rows = collectInFlight({ dir, provisioned })
458
506
  process.stdout.write('Provisioned specs:\n')
459
- for (const { folder, wt, specless } of provisioned) {
507
+ for (const [i, { folder, project, specless }] of provisioned.entries()) {
460
508
  const slot = registry.slots[folder]
461
509
  let ports = ''
462
510
  if (slot !== undefined) {
@@ -468,11 +516,41 @@ function specEnvStatus(dir, config) {
468
516
  // looking for `specs/**/<name>/` must not conclude the repo is broken when
469
517
  // there is nothing there — it is not missing, there never was one.
470
518
  const tag = specless ? ' (no spec)' : ''
471
- process.stdout.write(` ${folder}${tag}${ports}\n ${path.relative(dir, wt) || wt}\n`)
519
+ // The worktree's own reading — bucket, progress, any legacy header — after
520
+ // everything this line already carried, so the line is a superset of it.
521
+ const detail = specless ? '' : ` ${detailOf(rows[i])}`
522
+ // The project folder inside the worktree: where a session works on it.
523
+ process.stdout.write(` ${folder}${tag}${ports}${detail}\n ${path.relative(dir, project) || project}\n`)
472
524
  }
473
525
  process.stdout.write(waitingSection(dir, config))
474
526
  }
475
527
 
528
+ /**
529
+ * `skitterspec status` — what is being worked on here, read from each spec's
530
+ * own worktree. Offline and instant: no tracker is asked, ever. Exits 0 in
531
+ * every state, an idle repo included — an empty answer is not a finding.
532
+ */
533
+ function inFlightStatus(argv) {
534
+ const json = argv.includes('--json')
535
+ const at = argv.indexOf('--dir')
536
+ const from = path.resolve(at !== -1 && argv[at + 1] ? argv[at + 1] : process.cwd())
537
+ const anchor = primaryAnchor(from, gitReader(from))
538
+ const dir = anchor.dir
539
+ const { config, present } = loadEnvConfig(dir)
540
+ attachProject(config, anchor)
541
+ const rows = present ? collectInFlight({ dir, provisioned: provisionedSpecs(dir, config) }) : []
542
+ if (json) {
543
+ const specs = rows.map((r) => ({ ...r, inFlight: isInFlight(r) }))
544
+ process.stdout.write(JSON.stringify({ isolation: present, specs }, null, 2) + '\n')
545
+ return
546
+ }
547
+ if (!present) {
548
+ process.stdout.write('no specs in flight — isolation is not enabled here, so no spec has a worktree.\n')
549
+ return
550
+ }
551
+ process.stdout.write(projectLine(anchor) + formatInFlight(rows, { dir }))
552
+ }
553
+
476
554
  // Plan a provision: allocate the slot, persist the registry, and print the plan
477
555
  // the /spec-env skill executes (git worktree add, docker compose up, .env).
478
556
  // This creates no worktree and starts no stack — the caller runs the
@@ -503,8 +581,16 @@ function specIsUntracked(dir, git, spec) {
503
581
  * Returns `{ onFork, foundOn }`; `onFork: null` means "cannot tell" (a hotfix, or
504
582
  * a git that would not answer), which the planner routes to carrying on.
505
583
  */
506
- function specOnForkPoint(dir, git, spec) {
584
+ function specOnForkPoint(dir, git, spec, config) {
507
585
  if (spec.baseRef) return { onFork: null, foundOn: null }
586
+ // BRANCH-MODE SPEC DOCUMENTS ARE EXEMPT the same way a hotfix is: under
587
+ // `land.specDocs: "branch"` the spec rides its feature branch and lands with
588
+ // the work's PR, so it is *supposed* to be absent from the fork point —
589
+ // checking would refuse every spec the mode produces. Cannot-tell, so the
590
+ // planner carries on.
591
+ if (config && config.land && config.land.specDocs === 'branch') {
592
+ return { onFork: null, foundOn: null }
593
+ }
508
594
  // Ask about EVERY bucket, by folder name — never about `spec.path`.
509
595
  //
510
596
  // A spec's folder is its identity; which bucket holds it is a property of the
@@ -514,9 +600,14 @@ function specOnForkPoint(dir, git, spec) {
514
600
  // points outside this repo entirely (`../<repo>-wt/<slug>/specs/...`) — a path
515
601
  // no `cat-file` or `log` can ever match, which turned every in-flight spec
516
602
  // into "not committed" and silently emptied the `it is on <branch>` hint too.
603
+ //
604
+ // `<ref>:<path>` names a path from the REPO ROOT, while the `log` pathspec
605
+ // below is relative to `dir`, the project folder — so the first needs the
606
+ // project's prefix and the second must not have it (feat-subfolder-project).
517
607
  const rels = BUCKETS.map((bucket) => `specs/${bucket}/${spec.folder}`)
608
+ const prefix = prefixOf(config)
518
609
  for (const rel of rels) {
519
- if (git(['cat-file', '-e', `HEAD:${rel}/00-overview.md`]) !== null) {
610
+ if (git(['cat-file', '-e', `${spec.forkFrom || 'HEAD'}:${toRepoPath(rel, prefix)}/00-overview.md`]) !== null) {
520
611
  return { onFork: true, foundOn: null }
521
612
  }
522
613
  }
@@ -627,7 +718,7 @@ function specEnvUpCheckout(dir, config, spec) {
627
718
  const primary = assertPrimaryOnMain(config, git)
628
719
  const base = resolveBaseBranch(config, git)
629
720
  const status = git(['status', '--porcelain', '-uall'])
630
- const onFork = specOnForkPoint(dir, git, spec)
721
+ const onFork = specOnForkPoint(dir, git, spec, config)
631
722
 
632
723
  const plan = planCheckoutUp(
633
724
  spec,
@@ -842,7 +933,7 @@ function specEnvNospec(dir, config, name, flags = {}) {
842
933
  `spec-env nospec: ${name} ` +
843
934
  (attached ? '(plan — worktree exists; will attach)' : '(plan — nothing created yet)'),
844
935
  '',
845
- ` worktree: ${spec.worktreePath}`,
936
+ ` worktree: ${spec.projectPath}`,
846
937
  ` branch: ${spec.branch}`,
847
938
  ' stack: worktree-only (no docker, no port block)',
848
939
  ` recorded: ${already ? 'already in' : 'added to'} ${config.registry} as a specless branch`,
@@ -862,8 +953,8 @@ function specEnvNospec(dir, config, name, flags = {}) {
862
953
  out.push(' to provision, run:')
863
954
  out.push(
864
955
  attached
865
- ? ` git worktree add ${spec.worktreePath} ${spec.branch}`
866
- : ` git worktree add ${spec.worktreePath} -b ${spec.branch}`,
956
+ ? ` git worktree add ${shellPath(spec.worktreePath)} ${spec.branch}`
957
+ : ` git worktree add ${shellPath(spec.worktreePath)} -b ${spec.branch}`,
867
958
  )
868
959
  const seeds = (config.seedFiles && config.seedFiles.files) || []
869
960
  if (seeds.length || (config.setup || []).length) out.push(...bootstrapLines(name))
@@ -922,13 +1013,29 @@ function specEnvUp(dir, config, specArg, flags = {}) {
922
1013
  // Everywhere else `spec.baseRef` comes off the spec and stays the
923
1014
  // authority — which is why passing this to a spec that resolves refuses
924
1015
  // below rather than quietly losing to the header.
1016
+ // `--from` takes either Base version form; a `<branch>@<sha>` forks from
1017
+ // the sha, which is the part git can resolve.
1018
+ const fromVersion = flags.from !== undefined ? parseBaseVersion(flags.from) : null
925
1019
  if (flags.from !== undefined) {
926
- const bad = badForkRef(dir, flags.from)
1020
+ const bad = badForkRef(dir, fromVersion ? fromVersion.ref : flags.from)
927
1021
  if (bad) {
928
1022
  process.stdout.write(bad)
929
1023
  return
930
1024
  }
931
1025
  }
1026
+ // A BRANCH-BASED hotfix (`hotfix.releaseBranch`) forks from the remote's
1027
+ // head of the release branch, fetched now — prod is whatever that branch
1028
+ // holds, not whatever this clone last saw. Resolved to a sha before the
1029
+ // registry is written, so a refusal leaves nothing behind. An explicit
1030
+ // `--from` still wins: the operator named the fork point.
1031
+ let releaseFork = null
1032
+ if (!fromVersion && splitPrefix(specArg).type === 'hotfix' && config.hotfix.releaseBranch) {
1033
+ releaseFork = releaseBranchFork(dir, config)
1034
+ if (releaseFork.refused) {
1035
+ process.stdout.write(`spec-env up: ${releaseFork.refused}\n`)
1036
+ return
1037
+ }
1038
+ }
932
1039
  const beforeAuth = readRegistry(dir, config)
933
1040
  const resolved = resolveSpecless(specArg, dir, config, { spec: true })
934
1041
  writeRegistry(
@@ -937,7 +1044,11 @@ function specEnvUp(dir, config, specArg, flags = {}) {
937
1044
  recordSpecless(beforeAuth, specArg, { branch: resolved.branch, spec: true }),
938
1045
  )
939
1046
  spec = resolved
940
- if (flags.from !== undefined) spec.baseRef = flags.from
1047
+ const fork = fromVersion || releaseFork
1048
+ if (fork) {
1049
+ spec.baseRef = fork.ref
1050
+ spec.baseVersion = fork
1051
+ }
941
1052
  authoring = true
942
1053
  }
943
1054
 
@@ -954,6 +1065,11 @@ function specEnvUp(dir, config, specArg, flags = {}) {
954
1065
  return
955
1066
  }
956
1067
 
1068
+ // Rolling base: fetch first, so a release candidate cut since the last fetch
1069
+ // is the one this spec forks from. A hotfix names its own fork point and is
1070
+ // not about the base at all, so it never fetches here. No pattern, no fetch.
1071
+ if (!spec.baseRef) process.stdout.write(fetchNote('up', config, fetchForPattern(dir, config)))
1072
+
957
1073
  // Checkout mode: the branch is built in the primary checkout, so none of the
958
1074
  // worktree machinery below applies — no slot, no trust entry and no bootstrap.
959
1075
  // Handled first precisely so none of that runs by accident.
@@ -993,6 +1109,20 @@ function specEnvUp(dir, config, specArg, flags = {}) {
993
1109
  const upGit = gitReader(dir)
994
1110
  const upStatus = upGit(['status', '--porcelain'])
995
1111
  const upDirtyPaths = dirtyPaths(upGit)
1112
+ // A worktree forks from whatever the primary checkout has out. Under a
1113
+ // rolling base that can be the previous release candidate, still checked out
1114
+ // after the roll — so where it is not the resolved base, fork from the base
1115
+ // explicitly: the local branch when this clone has one, else its remote image.
1116
+ // No pattern leaves the fork exactly as it was.
1117
+ if (!spec.baseRef && (config.baseBranchPattern || '').trim()) {
1118
+ const ubase = resolveBaseBranch(config, upGit)
1119
+ if (primaryUp.branch !== ubase) {
1120
+ spec.forkFrom =
1121
+ upGit(['show-ref', '--verify', '--quiet', `refs/heads/${ubase}`]) !== null
1122
+ ? ubase
1123
+ : `${baseRemote(config)}/${ubase}`
1124
+ }
1125
+ }
996
1126
  // A spec with no document on disk does not ask whether the spec is on the
997
1127
  // fork point — it is known to be nowhere, and that is the healthy state of
998
1128
  // the authoring lane, not the "would fork without the spec it is for"
@@ -1006,10 +1136,37 @@ function specEnvUp(dir, config, specArg, flags = {}) {
1006
1136
  // so `authoring` is false while `spec.path` is still null. Asking git about a
1007
1137
  // null path threw, which is a crash rather than a refusal: the condition is
1008
1138
  // whether there is a document, and it always was.
1139
+ // RESUME, NOT FORK — a spec whose branch is already published. A spec handed
1140
+ // to someone else mid-flight (`/spec-claim --to` pushes it) lives on the
1141
+ // remote and nowhere on this machine, and forking a fresh branch from base
1142
+ // would hand its new owner an empty tree with the old owner's work out of
1143
+ // reach. So where this clone has no such branch and no worktree for it, ask
1144
+ // the remote, and build from what is there.
1145
+ //
1146
+ // A POSITIVE SIGNAL ONLY: `ls-remote` naming the branch with a sha. An empty
1147
+ // answer is "not published", and the fork goes ahead exactly as before. WHAT
1148
+ // WOULD FOOL THIS: a remote this clone cannot reach answers nothing either —
1149
+ // so a failed ask is said in one line (`resume:`) and still forks, and a repo
1150
+ // with no such remote at all is not asked and says nothing.
1151
+ const resumeRemote = baseRemote(config)
1152
+ if (
1153
+ !fs.existsSync(spec.worktreePath) &&
1154
+ upGit(['show-ref', '--verify', '--quiet', `refs/heads/${spec.branch}`]) === null &&
1155
+ upGit(['remote', 'get-url', resumeRemote]) !== null
1156
+ ) {
1157
+ const head = upGit(['ls-remote', '--heads', resumeRemote, `refs/heads/${spec.branch}`])
1158
+ const sha = head ? head.split(/\s+/)[0] : ''
1159
+ if (sha) spec.resumeFrom = { remote: resumeRemote, sha }
1160
+ else if (head === null) spec.resumeUnknown = resumeRemote
1161
+ }
1162
+
1009
1163
  const noDocument = authoring || !spec.path
1010
- const upOnFork = noDocument
1164
+ // A resumed branch carries the spec itself (it was started there), so whether
1165
+ // the spec is on the BASE is not this run's question: cannot-tell, which the
1166
+ // gate allows.
1167
+ const upOnFork = noDocument || spec.resumeFrom
1011
1168
  ? { onFork: undefined, foundOn: null }
1012
- : specOnForkPoint(dir, upGit, spec)
1169
+ : specOnForkPoint(dir, upGit, spec, config)
1013
1170
  const upSpecUntracked = noDocument ? false : specIsUntracked(dir, upGit, spec)
1014
1171
 
1015
1172
  // Trust the shared worktree root so edits into the freshly-provisioned worktree
@@ -1059,7 +1216,7 @@ function specEnvUp(dir, config, specArg, flags = {}) {
1059
1216
  dirtyPaths: upDirtyPaths,
1060
1217
  specOnFork: upOnFork.onFork,
1061
1218
  specFoundOn: upOnFork.foundOn,
1062
- forkRef: spec.baseRef || currentBranch(upGit) || 'HEAD',
1219
+ forkRef: spec.baseRef || spec.forkFrom || currentBranch(upGit) || 'HEAD',
1063
1220
  specUntracked: upSpecUntracked,
1064
1221
  composeFilePresent: composeFilePresent(dir, config),
1065
1222
  }, { docs })
@@ -1068,6 +1225,17 @@ function specEnvUp(dir, config, specArg, flags = {}) {
1068
1225
  process.stdout.write(`spec-env up: blocked — ${plan.reason}.\n`)
1069
1226
  return
1070
1227
  }
1228
+ // The planned spec commit lands on the branch the primary checkout has out,
1229
+ // and the fork is from the base — so the new branch would miss the very
1230
+ // commit made for it. Refuse rather than plan one that cannot work.
1231
+ if (spec.forkFrom && plan.specCommit) {
1232
+ process.stdout.write(
1233
+ `spec-env up: blocked — ${spec.folder} is uncommitted on ${primaryUp.branch || 'a detached HEAD'}, ` +
1234
+ `but the base is ${spec.forkFrom}. Switch the primary checkout to the base and commit the spec ` +
1235
+ 'there, then re-run.\n',
1236
+ )
1237
+ return
1238
+ }
1071
1239
 
1072
1240
  const out = []
1073
1241
  // `up` is a planner: it prints commands for the caller to run and creates no
@@ -1081,7 +1249,9 @@ function specEnvUp(dir, config, specArg, flags = {}) {
1081
1249
  (attached ? '(plan — worktree exists; will attach)' : '(plan — nothing created yet)'),
1082
1250
  )
1083
1251
  out.push('')
1084
- out.push(` worktree: ${plan.worktreePath}`)
1252
+ // Where the session moves to: the project folder inside the worktree, which
1253
+ // is the worktree itself unless the project sits in a subfolder of its repo.
1254
+ out.push(` worktree: ${plan.projectPath}`)
1085
1255
  out.push(` branch: ${plan.branch}`)
1086
1256
  if (plan.slot !== null) {
1087
1257
  const hi = plan.portOffset + config.docker.portsPerSpec - 1
@@ -1099,6 +1269,24 @@ function specEnvUp(dir, config, specArg, flags = {}) {
1099
1269
  if (plan.docs) {
1100
1270
  out.push(' docs: documents only — no setup commands, no docker')
1101
1271
  }
1272
+ // PR mode forks from LOCAL base — an origin/<base> fork would fork without a
1273
+ // just-landed, not-yet-pushed spec document — so when the remote image is
1274
+ // ahead, say so rather than silently forking behind it. Advisory only, and
1275
+ // silent on every cannot-tell: no remote-tracking ref here is an absence,
1276
+ // not a stale base (`.claude/rules/negative-checks.md`).
1277
+ if (config.land && config.land.strategy === 'pr') {
1278
+ const ugit = gitReader(dir)
1279
+ const ubase = resolveBaseBranch(config, ugit)
1280
+ const uremote = config.land.remote || 'origin'
1281
+ const behind = ubase ? ugit(['rev-list', '--count', `${ubase}..${uremote}/${ubase}`]) : null
1282
+ if (behind !== null && Number(behind) > 0) {
1283
+ out.push(
1284
+ ` note: ${uremote}/${ubase} is ${behind} commit(s) ahead of ${ubase} — the branch forks` +
1285
+ `\n from local ${ubase}; pull first if you want the newer base` +
1286
+ '\n (landing rebases onto the remote base either way)',
1287
+ )
1288
+ }
1289
+ }
1102
1290
  // Positive, so an operator reading the plan knows the missing spec folder is
1103
1291
  // the lane working rather than something the engine failed to find.
1104
1292
  if (authoring) {
@@ -1111,6 +1299,24 @@ function specEnvUp(dir, config, specArg, flags = {}) {
1111
1299
  if (authoring && flags.from !== undefined) {
1112
1300
  out.push(` fork: ${flags.from} (the branch forks from here, not from base)`)
1113
1301
  }
1302
+ // The header the skill writes into the new spec, said once, by the engine
1303
+ // that chose the commit — so the record and the fork cannot disagree.
1304
+ if (authoring && spec.baseVersion && spec.baseVersion.kind === 'branch' && flags.from === undefined) {
1305
+ const v = spec.baseVersion
1306
+ out.push(
1307
+ ` fork: ${v.branch}@${v.sha} (the head of ${baseRemote(config)}/${v.branch})` +
1308
+ `\n record: > **Base version:** ${v.branch}@${v.sha}`,
1309
+ )
1310
+ }
1311
+ if (spec.resumeFrom && !attached) {
1312
+ const { remote, sha } = spec.resumeFrom
1313
+ out.push(` resume: ${remote}/${spec.branch} @ ${sha.slice(0, 12)} (already published — carrying on from it, not forking)`)
1314
+ } else if (spec.resumeUnknown && !attached) {
1315
+ out.push(` resume: could not ask ${spec.resumeUnknown} for ${spec.branch} — forking fresh; if it was handed over, fetch and re-run`)
1316
+ }
1317
+ if (spec.forkFrom && !attached && !spec.resumeFrom) {
1318
+ out.push(` fork: ${spec.forkFrom} (the base — the primary checkout is on ${primaryUp.branch || 'a detached HEAD'})`)
1319
+ }
1114
1320
  if (trust.reason === 'malformed') {
1115
1321
  out.push(
1116
1322
  ' trusted: ! .claude/settings.local.json is not valid JSON — left it;' +
@@ -1223,7 +1429,7 @@ function specEnvBootstrap(dir, config, specArg, flags = {}) {
1223
1429
  if (json) {
1224
1430
  say(
1225
1431
  JSON.stringify(
1226
- { spec: name, worktree: spec.worktreePath, docs, planned: true, steps },
1432
+ { spec: name, worktree: spec.projectPath, docs, planned: true, steps },
1227
1433
  null,
1228
1434
  2,
1229
1435
  ),
@@ -1232,7 +1438,7 @@ function specEnvBootstrap(dir, config, specArg, flags = {}) {
1232
1438
  }
1233
1439
  say(`spec-env bootstrap: ${name} (plan — nothing run)`)
1234
1440
  say('')
1235
- say(` worktree: ${spec.worktreePath}`)
1441
+ say(` worktree: ${spec.projectPath}`)
1236
1442
  if (!steps.length) say(' steps: none — nothing configured to run')
1237
1443
  else steps.forEach((st, i) => say(` ${i + 1}. ${describeStep(st)}`))
1238
1444
  return
@@ -1240,10 +1446,13 @@ function specEnvBootstrap(dir, config, specArg, flags = {}) {
1240
1446
 
1241
1447
  if (!json) {
1242
1448
  say(`spec-env bootstrap: ${name}`)
1243
- say(` worktree: ${spec.worktreePath}`)
1449
+ say(` worktree: ${spec.projectPath}`)
1244
1450
  }
1451
+ // The project folder inside the worktree: setup, seeds and the env file are
1452
+ // all project-relative, as `env.config.json` is (feat-subfolder-project,
1453
+ // decision 5). `mainRoot` is the same folder in the primary checkout.
1245
1454
  const result = runBootstrap(steps, {
1246
- cwd: spec.worktreePath,
1455
+ cwd: spec.projectPath,
1247
1456
  mainRoot: dir,
1248
1457
  // Report lines go to stdout as plain text; under --json they are carried in
1249
1458
  // the payload instead, and spawned output is moved to stderr with them.
@@ -1256,7 +1465,7 @@ function specEnvBootstrap(dir, config, specArg, flags = {}) {
1256
1465
  JSON.stringify(
1257
1466
  {
1258
1467
  spec: name,
1259
- worktree: spec.worktreePath,
1468
+ worktree: spec.projectPath,
1260
1469
  docs,
1261
1470
  planned: false,
1262
1471
  ok: result.ok,
@@ -1308,7 +1517,7 @@ function bootstrapLines(name, { docs = false } = {}) {
1308
1517
  // the same directory. Cannot-tell (either missing) is "not the same".
1309
1518
  function sameDir(a, b) {
1310
1519
  try {
1311
- return fs.realpathSync(a) === fs.realpathSync(b)
1520
+ return fs.realpathSync.native(a) === fs.realpathSync.native(b)
1312
1521
  } catch {
1313
1522
  return false
1314
1523
  }
@@ -1346,6 +1555,38 @@ function speclessMap(dir, config) {
1346
1555
  * tree ref would be rejected here and rejected by `git worktree add` too. Being
1347
1556
  * wrong that way costs a refusal on something that could never have worked.
1348
1557
  */
1558
+ /**
1559
+ * Where a branch-based hotfix forks: the remote's head of `hotfix.releaseBranch`,
1560
+ * fetched first. Returns `{ kind: 'branch', branch, sha, ref }` (the Base version
1561
+ * shape, sha abbreviated to 12) or `{ refused }`.
1562
+ *
1563
+ * A failed fetch is not itself a refusal — the remote-tracking ref already here
1564
+ * still names a real commit on the release line — but a ref that is absent after
1565
+ * the fetch is: forking from anywhere else would build the fix on code prod is
1566
+ * not running, which is the one mistake a hotfix exists to avoid.
1567
+ */
1568
+ function releaseBranchFork(dir, config) {
1569
+ const branch = config.hotfix.releaseBranch
1570
+ const remote = baseRemote(config)
1571
+ let fetchErr = null
1572
+ try {
1573
+ execFileSync('git', ['-C', dir, 'fetch', remote, branch], { stdio: ['ignore', 'ignore', 'pipe'] })
1574
+ } catch (error) {
1575
+ const stderr = error.stderr ? error.stderr.toString() : ''
1576
+ fetchErr = stderr.split('\n').map((l) => l.trim()).find(Boolean) || 'fetch failed'
1577
+ }
1578
+ const git = gitReader(dir)
1579
+ const sha = git(['rev-parse', '--verify', '--quiet', '--short=12', `refs/remotes/${remote}/${branch}^{commit}`])
1580
+ if (!sha) {
1581
+ return {
1582
+ refused:
1583
+ `hotfix.releaseBranch is "${branch}", but ${remote}/${branch} is not known here` +
1584
+ `${fetchErr ? ` (fetch: ${fetchErr})` : ''} — nothing to fork the hotfix from.`,
1585
+ }
1586
+ }
1587
+ return { kind: 'branch', branch, sha, ref: sha }
1588
+ }
1589
+
1349
1590
  function badForkRef(cwd, ref) {
1350
1591
  const git = gitReader(cwd)
1351
1592
  if (!ref) {
@@ -1504,9 +1745,18 @@ function specEnvDown(dir, config, specArg, flags) {
1504
1745
  }
1505
1746
  const dst = dgit(['status', '--porcelain'])
1506
1747
  const contains = dgit(['branch', '--contains', spec.branch, '--list', dbase])
1748
+ let clanded = Boolean(contains && contains.trim())
1749
+ // PR mode: a squash or rebase merge never shows in ancestry, so the host's
1750
+ // answer joins it. Asked only when ancestry says no — trunk projects never
1751
+ // pay the subprocess, and cannot-tell adds nothing (landed stays false).
1752
+ if (!clanded && config.land && config.land.strategy === 'pr') {
1753
+ if (hostPrFor(dir, config.land.remote || 'origin', spec.branch).state === 'merged') {
1754
+ clanded = true
1755
+ }
1756
+ }
1507
1757
  const dplan = planDownCheckout(spec, config, flags, {
1508
1758
  dirty: dst === null || dst.length > 0,
1509
- landed: Boolean(contains && contains.trim()),
1759
+ landed: clanded,
1510
1760
  onBranch: dgit(['rev-parse', '--abbrev-ref', 'HEAD']) === spec.branch,
1511
1761
  base: dbase,
1512
1762
  checkoutPath: dir,
@@ -1538,9 +1788,28 @@ function specEnvDown(dir, config, specArg, flags) {
1538
1788
  }
1539
1789
 
1540
1790
  const base = resolveBaseBranch(config, gitReader(dir))
1541
- const worktreeState = worktreeGitState(spec.worktreePath, base)
1791
+ let worktreeState = worktreeGitState(spec.worktreePath, base)
1792
+ // PR mode: a squash or rebase merge leaves ancestry false forever, so the
1793
+ // host's answer joins `merged`. Asked only when it matters — trunk projects
1794
+ // never pay the subprocess, and an ancestry-merged branch has its answer.
1795
+ // `prState` rides along so the planner's refusal can say what it saw.
1796
+ let prAbandon = null
1797
+ if (
1798
+ config.land && config.land.strategy === 'pr' &&
1799
+ !worktreeState.merged && fs.existsSync(spec.worktreePath)
1800
+ ) {
1801
+ const remote = config.land.remote || 'origin'
1802
+ const pr = hostPrFor(spec.worktreePath, remote, spec.branch)
1803
+ worktreeState = { ...worktreeState, prState: pr.state, prUrl: pr.url }
1804
+ if (pr.state === 'merged') worktreeState.merged = true
1805
+ if (pr.state === 'open' || pr.state === 'draft') {
1806
+ const info = parseRemote(gitReader(spec.worktreePath)(['config', '--get', `remote.${remote}.url`]))
1807
+ prAbandon = prAbandonCommand(info, { branch: spec.branch, id: pr.id })
1808
+ }
1809
+ }
1542
1810
  const plan = planDown(spec, config, flags, {
1543
1811
  worktreeState,
1812
+ prAbandonCommand: prAbandon,
1544
1813
  timestamp: compactTimestamp(),
1545
1814
  composeFilePresent: composeFilePresent(dir, config),
1546
1815
  })
@@ -1706,7 +1975,7 @@ function provisionedSpecChoice(dir, config, cwd = process.cwd()) {
1706
1975
  // so a nested worktree is not shadowed by an ancestor one.
1707
1976
  let here
1708
1977
  try {
1709
- here = fs.realpathSync(path.resolve(cwd))
1978
+ here = fs.realpathSync.native(path.resolve(cwd))
1710
1979
  } catch {
1711
1980
  here = path.resolve(cwd)
1712
1981
  }
@@ -1752,10 +2021,11 @@ function resolveSpecWithWorktree(dir, config, specArg) {
1752
2021
  // one where a missing spec was previously a usage error.
1753
2022
  specArg = specArg || soleProvisionedSpec(dir, config)
1754
2023
  const { slug } = splitPrefix(path.basename(specArg))
1755
- const { repo, repoSlug } = repoInfo(dir)
2024
+ const root = repoRootOf(dir, config)
2025
+ const { repo, repoSlug } = repoInfo(root)
1756
2026
  const wtTokens = { repo, repoSlug, slug }
1757
2027
  const worktreeGuess = path.resolve(
1758
- dir,
2028
+ root,
1759
2029
  expandTokens(config.worktree.root, wtTokens),
1760
2030
  expandTokens(config.worktree.folderPattern, wtTokens),
1761
2031
  )
@@ -1832,7 +2102,7 @@ function specEnvPrune(dir, config, flags) {
1832
2102
  `spec-env prune: reaped a stale review-server pidfile (pid ${reapedPid} is gone).\n`,
1833
2103
  )
1834
2104
  }
1835
- const { repoSlug } = repoInfo(dir)
2105
+ const { repoSlug } = repoInfo(repoRootOf(dir, config))
1836
2106
 
1837
2107
  const vols = listRepoVolumes(repoSlug)
1838
2108
  if (!vols.ok) {
@@ -1901,7 +2171,7 @@ function specEnvPrune(dir, config, flags) {
1901
2171
  // Integrate: land a spec's worktree branch onto the base branch (rebase + ff).
1902
2172
  // Queries git for the facts, prints the plan / block / no-op. The /spec-complete
1903
2173
  // skill executes the printed commands (and aborts a conflicting rebase).
1904
- function specEnvIntegrate(dir, config, specArg) {
2174
+ function specEnvIntegrate(dir, config, specArg, flags = {}) {
1905
2175
 
1906
2176
  // `dir` is already anchored on the primary checkout by the dispatch, so it is
1907
2177
  // both where the spec resolves and the target of the fast-forward — /spec-complete
@@ -1909,7 +2179,34 @@ function specEnvIntegrate(dir, config, specArg) {
1909
2179
  // entirely on its branch may not exist in the primary checkout's specs/** —
1910
2180
  // resolveSpecWithWorktree offers its worktree as a fallback search location.
1911
2181
  const spec = resolveSpecWithWorktree(dir, config, specArg)
2182
+ // Fetch before resolving under a rolling base, so a spec that outlived a
2183
+ // release roll lands on the rc that exists now rather than the one the last
2184
+ // fetch saw. No pattern → no fetch, and the plan below is unchanged.
2185
+ process.stdout.write(fetchNote('integrate', config, fetchForPattern(dir, config)))
1912
2186
  const base = resolveBaseBranch(config, gitReader(dir))
2187
+ const retarget = retargetFor(gitReader(dir), config, spec.branch)
2188
+
2189
+ // PR mode replaces the local land in BOTH modes: the branch is pushed and a
2190
+ // pull request carries it, so nothing below (live handling included) applies —
2191
+ // the primary checkout is never switched and base never moves here.
2192
+ //
2193
+ // `--strategy` overrides the config per invocation — a team that lands one
2194
+ // feature by direct merge and the next by PR picks at the land, not in a
2195
+ // committed file. An unrecognised value REFUSES BY NAME rather than falling
2196
+ // through: config enums fall back because a typo there must not strengthen a
2197
+ // setting, but a flag is being typed right now and the typist can retype it —
2198
+ // silently landing the other way is the worse answer.
2199
+ if (flags.strategy !== undefined && flags.strategy !== 'ff' && flags.strategy !== 'pr') {
2200
+ process.stdout.write(
2201
+ `spec-env integrate: unknown --strategy "${flags.strategy}" — use ff or pr.\n`,
2202
+ )
2203
+ return
2204
+ }
2205
+ const strategy = flags.strategy || (config.land && config.land.strategy) || 'ff'
2206
+ if (strategy === 'pr') {
2207
+ specEnvIntegratePr(dir, config, spec, base, flags, retarget)
2208
+ return
2209
+ }
1913
2210
 
1914
2211
  // Checkout mode short-circuits everything below. The live handling in
1915
2212
  // particular reads "primary is on the spec's branch" as a live session — true
@@ -1939,7 +2236,8 @@ function specEnvIntegrate(dir, config, specArg) {
1939
2236
  return
1940
2237
  }
1941
2238
  const cout = [`spec-env integrate: ${spec.folder}`, '', ' mode: checkout',
1942
- ` base: ${base}`, ` branch: ${cplan.branch}`, '',
2239
+ ` base: ${base}`, ` branch: ${cplan.branch}`,
2240
+ ...retargetLines(retarget), '',
1943
2241
  ' run these (abort the rebase on conflict):']
1944
2242
  for (const cmd of cplan.commands) cout.push(` ${cmd}`)
1945
2243
  process.stdout.write(cout.join('\n') + '\n' + afterLandSection(cplan.afterLand))
@@ -1951,7 +2249,11 @@ function specEnvIntegrate(dir, config, specArg) {
1951
2249
  // branch, clear the receipt — so the normal rebase→ff plan below applies
1952
2250
  // unchanged. Refuse if a *different* spec holds the primary checkout.
1953
2251
  const primary = assertPrimaryOnMain(config, gitReader(dir))
1954
- if (!primary.onBase) {
2252
+ // A primary checkout on an OLDER rolling-base match is not a live session and
2253
+ // not another spec: it is the previous release candidate, still checked out
2254
+ // after the roll. The plan switches it rather than refusing.
2255
+ const primarySwitch = primary.onBase ? null : staleBaseCheckout(dir, config, primary.branch, base)
2256
+ if (!primary.onBase && !primarySwitch) {
1955
2257
  if (primary.branch !== spec.branch) {
1956
2258
  process.stdout.write(
1957
2259
  `spec-env integrate: blocked — another spec (${primary.branch}) holds the ` +
@@ -1987,7 +2289,7 @@ function specEnvIntegrate(dir, config, specArg) {
1987
2289
  process.stdout.write(
1988
2290
  `spec-env integrate: blocked — ${stranded} commit(s) are stranded on the detached ` +
1989
2291
  `HEAD of ${spec.worktreePath} (at ${head}), ahead of ${spec.branch}; re-isolating ` +
1990
- `would abandon them. Recover with \`git -C ${spec.worktreePath} branch <tmp> ${head}\`, ` +
2292
+ `would abandon them. Recover with \`git -C ${shellPath(spec.worktreePath)} branch <tmp> ${head}\`, ` +
1991
2293
  `reconcile onto ${spec.branch}, then re-run.\n`,
1992
2294
  )
1993
2295
  return
@@ -2015,7 +2317,11 @@ function specEnvIntegrate(dir, config, specArg) {
2015
2317
  const wtGit = gitReader(spec.worktreePath)
2016
2318
  const status = wtGit(['status', '--porcelain'])
2017
2319
  const dirty = status !== null && status.length > 0
2018
- const ahead = wtGit(['rev-list', '--count', `${base}..HEAD`])
2320
+ // A base this clone has no local branch for yet (a release candidate cut
2321
+ // since) is measured against its remote image — `<base>..HEAD` would not
2322
+ // resolve, read as "nothing ahead", and report the spec already landed.
2323
+ const baseRef = primarySwitch && primarySwitch.create ? `${baseRemote(config)}/${base}` : base
2324
+ const ahead = wtGit(['rev-list', '--count', `${baseRef}..HEAD`])
2019
2325
  const aheadOfBase = ahead !== null && Number(ahead) > 0
2020
2326
 
2021
2327
  const plan = planIntegrate(spec, config, {
@@ -2023,7 +2329,8 @@ function specEnvIntegrate(dir, config, specArg) {
2023
2329
  base,
2024
2330
  aheadOfBase,
2025
2331
  mainRepoPath: dir,
2026
- changedFiles: landRange(gitReader(dir), base, spec.branch),
2332
+ changedFiles: landRange(gitReader(dir), baseRef, spec.branch),
2333
+ primarySwitch,
2027
2334
  })
2028
2335
 
2029
2336
  if (plan.blocked) {
@@ -2044,12 +2351,311 @@ function specEnvIntegrate(dir, config, specArg) {
2044
2351
  out.push(` base: ${plan.base}`)
2045
2352
  out.push(` branch: ${plan.branch}`)
2046
2353
  out.push(` worktree: ${spec.worktreePath}`)
2354
+ out.push(...retargetLines(retarget))
2355
+ if (primarySwitch) out.push(` primary: on ${primarySwitch.from} — switched to ${base} before the land`)
2047
2356
  out.push('')
2048
2357
  out.push(' run these (abort the rebase on conflict):')
2049
2358
  for (const cmd of plan.commands) out.push(` ${cmd}`)
2050
2359
  process.stdout.write(out.join('\n') + '\n' + afterLandSection(plan.afterLand))
2051
2360
  }
2052
2361
 
2362
+ // The line a plan carries when the rc rolled while the spec was in flight. The
2363
+ // rebase onto the newer rc is the land working, not a mistake — but it should
2364
+ // never happen without the reader seeing it.
2365
+ function retargetLines(retarget) {
2366
+ return retarget ? [` retarget: forked from ${retarget.from} · landing onto ${retarget.to}`] : []
2367
+ }
2368
+
2369
+ // Is the primary checkout sitting on an older rolling-base match? Positive
2370
+ // signal only: the branch it has out must itself match `baseBranchPattern`
2371
+ // (locally or on the remote). Anything else — a live spec, a detached HEAD, no
2372
+ // pattern — returns null and keeps the refusals that were already there.
2373
+ function staleBaseCheckout(dir, config, branch, base) {
2374
+ const pattern = (config.baseBranchPattern || '').trim()
2375
+ if (!pattern || !branch || branch === base) return null
2376
+ const git = gitReader(dir)
2377
+ const remote = baseRemote(config)
2378
+ const local = git(['for-each-ref', '--format=%(refname:short)', `refs/heads/${pattern}`])
2379
+ const onMatch =
2380
+ (local || '').split('\n').map((l) => l.trim()).includes(branch) ||
2381
+ patternMatches(git, config).some((m) => m.name === branch)
2382
+ if (!onMatch) return null
2383
+ const status = git(['status', '--porcelain'])
2384
+ return {
2385
+ from: branch,
2386
+ // Unreadable reads as dirty: being wrong that way costs a refusal, the other
2387
+ // way switches a checkout holding work nobody could see.
2388
+ dirty: status === null || status.length > 0,
2389
+ create: git(['show-ref', '--verify', '--quiet', `refs/heads/${base}`]) === null,
2390
+ remote,
2391
+ }
2392
+ }
2393
+
2394
+ // Subprocess runner for the host adapter (`env/host.js`): never throws, and a
2395
+ // timeout bounds an `az`/`gh` call with no network — a hung lookup must not
2396
+ // hang a teardown. Every failure shape becomes { ok: false }, which the adapter
2397
+ // maps to cannot-tell.
2398
+ function hostExec(file, args, opts = {}) {
2399
+ try {
2400
+ const stdout = execFileSync(file, args, {
2401
+ stdio: ['ignore', 'pipe', 'pipe'],
2402
+ timeout: 15000,
2403
+ cwd: opts.cwd,
2404
+ }).toString()
2405
+ return { ok: true, stdout, stderr: '' }
2406
+ } catch (error) {
2407
+ return {
2408
+ ok: false,
2409
+ stdout: '',
2410
+ stderr: (error.stderr && error.stderr.toString()) || error.message || '',
2411
+ }
2412
+ }
2413
+ }
2414
+
2415
+ // The host's answer about `branch`'s PR, from the tree's own remote URL.
2416
+ // { state: merged|open|draft|none|cannot-tell, id, url } — cannot-tell on every
2417
+ // failure, including a remote this clone does not have.
2418
+ function hostPrFor(treePath, remote, branch) {
2419
+ const url = gitReader(treePath)(['config', '--get', `remote.${remote}.url`])
2420
+ return prFor(parseRemote(url), branch, hostExec, treePath)
2421
+ }
2422
+
2423
+ // PR-mode integrate: plan rebase-onto-remote-base + consent-gated push + PR.
2424
+ // The skill runs what is printed, exactly as the ff path; the difference is
2425
+ // that nothing here moves the base branch — the host does, later.
2426
+ function specEnvIntegratePr(dir, config, spec, base, flags, retarget = null) {
2427
+ const checkout = config.mode === 'checkout'
2428
+ const treePath = checkout ? dir : spec.worktreePath
2429
+ if (!checkout && !fs.existsSync(spec.worktreePath)) {
2430
+ process.stdout.write(
2431
+ `spec-env integrate: ${spec.folder} has no worktree — nothing to integrate.\n`,
2432
+ )
2433
+ return
2434
+ }
2435
+ const remote = (config.land && config.land.remote) || 'origin'
2436
+ const git = gitReader(treePath)
2437
+ const status = git(['status', '--porcelain'])
2438
+ const dirty = status !== null && status.length > 0
2439
+ // Measured against the REMOTE image of base — local base is allowed to go
2440
+ // stale in PR mode. null = no such ref here yet (never fetched): unknown, so
2441
+ // the planner plans rather than claiming landed.
2442
+ const aheadRaw = git(['rev-list', '--count', `${remote}/${base}..HEAD`])
2443
+ const aheadOfRemoteBase = aheadRaw === null ? null : Number(aheadRaw) > 0
2444
+ // A branch already on the remote at this exact HEAD is the positive signal
2445
+ // that the operator published it — the consent the hold otherwise waits for.
2446
+ const headSha = git(['rev-parse', 'HEAD'])
2447
+ const lsRemote = git(['ls-remote', remote, `refs/heads/${spec.branch}`])
2448
+ const pushedAtHead = Boolean(headSha && lsRemote && lsRemote.split(/\s/)[0] === headSha)
2449
+
2450
+ // The host's answer decides what the PR step says — `prPlanCommand` owns the
2451
+ // mapping (create · the-push-updates-it · flip-a-draft-ready · null for
2452
+ // cannot-tell, which keeps the planner's degraded placeholder). `--draft` is
2453
+ // the mid-spec form (/spec-to-main's PR-mode descendant): a draft cannot be
2454
+ // merged, so nothing downstream can close a ticket early. Plain integrate is
2455
+ // the landing verb, so a draft met without the flag is flipped ready.
2456
+ const draft = flags.draft === true
2457
+ const remoteInfo = parseRemote(git(['config', '--get', `remote.${remote}.url`]))
2458
+ const pr = remoteInfo.host ? hostPrFor(treePath, remote, spec.branch) : { state: 'cannot-tell', id: null, url: null }
2459
+
2460
+ const plan = planIntegratePr(spec, config, {
2461
+ prCreateCommand: prPlanCommand(remoteInfo, pr, { branch: spec.branch, base, draft }),
2462
+ // The finish half (printed when the host has merged): catch local base up
2463
+ // in the primary checkout and run the deferred afterLand against the
2464
+ // branch's own range — remote image first, local base as the fallback
2465
+ // when the remote ref is not here.
2466
+ primaryPath: dir,
2467
+ changedFiles: landRange(git, `${remote}/${base}`, spec.branch) || landRange(git, base, spec.branch),
2468
+ worktreeState: { dirty },
2469
+ base,
2470
+ remote,
2471
+ treePath,
2472
+ aheadOfRemoteBase,
2473
+ pushedAtHead,
2474
+ push: flags.push === true,
2475
+ onBranch: checkout
2476
+ ? git(['rev-parse', '--abbrev-ref', 'HEAD']) === spec.branch
2477
+ : undefined,
2478
+ })
2479
+
2480
+ if (plan.blocked) {
2481
+ process.stdout.write(`spec-env integrate: blocked — ${plan.reason}.\n`)
2482
+ return
2483
+ }
2484
+ if (plan.noop) {
2485
+ // Landed on the host — completion run 2. The deferred afterLand comes due
2486
+ // and local base wants catching up; the skill runs these, then its own
2487
+ // finalise (bucket move, teardown).
2488
+ const fout = [
2489
+ `spec-env integrate: ${spec.folder} already landed on ${remote}/${base} — ` +
2490
+ 'finish what the merge deferred:',
2491
+ ]
2492
+ for (const cmd of plan.finish.commands) fout.push(` ${cmd}`)
2493
+ process.stdout.write(fout.join('\n') + '\n' + afterLandSection(plan.finish.afterLand))
2494
+ return
2495
+ }
2496
+
2497
+ const out = []
2498
+ out.push(`spec-env integrate: ${spec.folder} (pr${draft ? ', draft' : ''})`)
2499
+ out.push('')
2500
+ out.push(` base: ${remote}/${base}`)
2501
+ out.push(` branch: ${plan.branch}`)
2502
+ out.push(checkout ? ` checkout: ${treePath}` : ` worktree: ${treePath}`)
2503
+ out.push(...retargetLines(retarget))
2504
+ // Silent on cannot-tell: a line about a lookup that failed accuses nothing
2505
+ // and helps nobody — the placeholder in the commands already degrades.
2506
+ if (pr.state === 'none') out.push(' pr: none yet')
2507
+ else if (pr.state !== 'cannot-tell') {
2508
+ out.push(` pr: ${pr.id ? `#${pr.id} ` : ''}${pr.state}${pr.url ? ` · ${pr.url}` : ''}`)
2509
+ }
2510
+ out.push('')
2511
+ out.push(' run these (abort the rebase on conflict):')
2512
+ for (const cmd of plan.commands) out.push(` ${cmd}`)
2513
+ if (plan.push.via === 'hold') {
2514
+ out.push('')
2515
+ out.push(' then, to publish the branch and open the PR — with your consent')
2516
+ out.push(' (or re-run with --push to plan it all as one list):')
2517
+ for (const cmd of plan.holdCommands) out.push(` ${cmd}`)
2518
+ }
2519
+ if (Array.isArray(config.afterLand) && config.afterLand.length) {
2520
+ out.push('')
2521
+ out.push(' after-land commands are deferred: base moves when the host merges,')
2522
+ out.push(' and the completion run that follows the merge plans them.')
2523
+ }
2524
+ process.stdout.write(out.join('\n') + '\n')
2525
+ }
2526
+
2527
+ // `spec-env disposition [<spec>] [--json]` — enumerate the loose ends a
2528
+ // completion must dispose before a PR goes ready: unticked tasks, phase-index
2529
+ // rows not ✅, surfaced follow-ups. Information only — it never refuses and
2530
+ // nothing gates on it; /spec-complete's PR-mode guard is the consumer, and the
2531
+ // deciding (tick · spin off · drop) is the operator's there.
2532
+ /**
2533
+ * `spec-env handoff <spec> [--json]` — what handing this spec to someone else
2534
+ * needs: its branch published, and a note for the ticket saying where the work
2535
+ * is. A planner, like `integrate`: it prints the push and runs nothing, because
2536
+ * a push is outward-facing and the skill asks before running it. The note is
2537
+ * written under `.spec-env/handoff/` (gitignored) for `spec-sync comment` to
2538
+ * post. Refusals exit 0 — `--json` carries `blocked`, and the `/commit` offer
2539
+ * where uncommitted work is what stands in the way.
2540
+ */
2541
+ function specEnvHandoff(dir, config, specArg, flags = {}) {
2542
+ const spec = resolveSpecWithWorktree(dir, config, specArg)
2543
+ const worktree = Boolean(spec.worktreePath && fs.existsSync(spec.worktreePath))
2544
+ const wtGit = worktree ? gitReader(spec.worktreePath) : () => null
2545
+ const remote = baseRemote(config)
2546
+ const remoteConfigured = worktree && wtGit(['remote', 'get-url', remote]) !== null
2547
+ const lsRemote = remoteConfigured ? wtGit(['ls-remote', '--heads', remote, `refs/heads/${spec.branch}`]) : null
2548
+ let phases = []
2549
+ if (worktree) {
2550
+ for (const bucket of BUCKETS) {
2551
+ const folder = path.join(spec.projectPath, 'specs', bucket, spec.folder)
2552
+ if (!fs.existsSync(path.join(folder, '00-overview.md'))) continue
2553
+ phases = fs
2554
+ .readdirSync(folder)
2555
+ .filter((f) => /^(?!00-)\d{2}-.*\.md$/.test(f))
2556
+ .sort()
2557
+ .map((f) => ({ file: f, content: fs.readFileSync(path.join(folder, f), 'utf-8') }))
2558
+ break
2559
+ }
2560
+ }
2561
+ const plan = planHandoff({
2562
+ spec: { folder: spec.folder, branch: spec.branch, worktreePath: spec.worktreePath },
2563
+ worktree,
2564
+ dirtyPaths: worktree ? dirtyPaths(wtGit) : [],
2565
+ remote,
2566
+ remoteConfigured,
2567
+ headSha: worktree ? wtGit(['rev-parse', 'HEAD']) : null,
2568
+ remoteSha: lsRemote === null ? null : lsRemote.split(/\s+/)[0] || '',
2569
+ phases,
2570
+ })
2571
+
2572
+ let notePath = null
2573
+ if (!plan.blocked) {
2574
+ notePath = path.join(dir, '.spec-env', 'handoff', `${spec.folder}.md`)
2575
+ fs.mkdirSync(path.dirname(notePath), { recursive: true })
2576
+ fs.writeFileSync(notePath, plan.note)
2577
+ }
2578
+ if (flags.json) {
2579
+ const { note, ...rest } = plan
2580
+ process.stdout.write(JSON.stringify({ spec: spec.folder, ...rest, ...(notePath ? { notePath } : {}) }, null, 2) + '\n')
2581
+ return
2582
+ }
2583
+ if (plan.blocked) {
2584
+ const out = [`spec-env handoff: ${spec.folder} — blocked: ${plan.reason}`]
2585
+ if (plan.offer) out.push(` way out: ${plan.offer.command} — ${plan.offer.label}`)
2586
+ process.stdout.write(out.join('\n') + '\n')
2587
+ return
2588
+ }
2589
+ const where = plan.published
2590
+ ? 'already published at HEAD'
2591
+ : plan.remoteUnknown
2592
+ ? `could not ask ${remote} — push to be sure`
2593
+ : `not published at HEAD`
2594
+ const out = [
2595
+ `spec-env handoff: ${spec.folder}`,
2596
+ ` branch: ${plan.branch} @ ${plan.sha} (${plan.progress.total ? `${plan.progress.done} of ${plan.progress.total} phases done` : 'no phase files'})`,
2597
+ ` remote: ${remote} — ${where}`,
2598
+ ` note: ${notePath} (post it: spec-sync comment ${spec.folder} --file <note>)`,
2599
+ ]
2600
+ if (plan.commands.length) {
2601
+ out.push('', ' push it, once the operator agrees:')
2602
+ for (const c of plan.commands) out.push(` ${c}`)
2603
+ }
2604
+ process.stdout.write(out.join('\n') + '\n')
2605
+ }
2606
+
2607
+ function specEnvDisposition(dir, config, specArg, flags = {}) {
2608
+ const spec = resolveSpecWithWorktree(dir, config, specArg)
2609
+ const tree = spec.projectPath && fs.existsSync(spec.projectPath) ? spec.projectPath : dir
2610
+ let folder = null
2611
+ for (const bucket of ['in-progress', 'backlog', 'complete', 'cancelled']) {
2612
+ const p = path.join(tree, 'specs', bucket, spec.folder)
2613
+ if (fs.existsSync(path.join(p, '00-overview.md'))) {
2614
+ folder = p
2615
+ break
2616
+ }
2617
+ }
2618
+ if (!folder) {
2619
+ // A specless (/no-spec) branch, or a legacy bare-file spec: nothing to
2620
+ // enumerate is a clean answer, not an error.
2621
+ const msg = `spec-env disposition: ${spec.folder} — no spec documents found; nothing to enumerate.`
2622
+ process.stdout.write(flags.json ? JSON.stringify({ spec: spec.folder, tasks: [], phases: [], followUps: [], clean: true }, null, 2) + '\n' : msg + '\n')
2623
+ return
2624
+ }
2625
+ const overview = fs.readFileSync(path.join(folder, '00-overview.md'), 'utf-8')
2626
+ const phases = fs
2627
+ .readdirSync(folder)
2628
+ .filter((f) => /^(?!00-)\d{2}-.*\.md$/.test(f))
2629
+ .sort()
2630
+ .map((f) => ({ file: f, content: fs.readFileSync(path.join(folder, f), 'utf-8') }))
2631
+ const d = collectDisposition({ overview, phases })
2632
+ if (flags.json) {
2633
+ process.stdout.write(JSON.stringify({ spec: spec.folder, ...d }, null, 2) + '\n')
2634
+ return
2635
+ }
2636
+ if (d.clean) {
2637
+ process.stdout.write(
2638
+ `spec-env disposition: ${spec.folder} — clean (no unticked tasks, no open phases, no surfaced follow-ups).\n`,
2639
+ )
2640
+ return
2641
+ }
2642
+ const out = [`spec-env disposition: ${spec.folder}`]
2643
+ if (d.tasks.length) {
2644
+ out.push(` unticked tasks (${d.tasks.length}):`)
2645
+ for (const t of d.tasks) out.push(` ${t.file}:${t.line} ${t.text}`)
2646
+ }
2647
+ if (d.phases.length) {
2648
+ out.push(` phases not ✅ (${d.phases.length}):`)
2649
+ for (const p of d.phases) out.push(` ${p.n} ${p.title} — ${p.status}`)
2650
+ }
2651
+ if (d.followUps.length) {
2652
+ out.push(` follow-ups surfaced (${d.followUps.length}):`)
2653
+ for (const f of d.followUps) out.push(` ${f.text}`)
2654
+ }
2655
+ out.push(' dispose each before the PR goes ready: tick with evidence · spin off a ticket · drop with a reason.')
2656
+ process.stdout.write(out.join('\n') + '\n')
2657
+ }
2658
+
2053
2659
  // The files a land brings into the base branch: `base...branch`, merge-base to
2054
2660
  // the branch tip. Read before the rebase runs, so it is the branch's own
2055
2661
  // changes — `base..branch` would also list what the base gained meanwhile and
@@ -2217,14 +2823,19 @@ function hotfixFinish(dir, config, specArg, flags) {
2217
2823
  const cwd = process.cwd()
2218
2824
  const inside = (() => {
2219
2825
  try {
2220
- const rel = path.relative(fs.realpathSync(spec.worktreePath), fs.realpathSync(cwd))
2826
+ const rel = path.relative(fs.realpathSync.native(spec.worktreePath), fs.realpathSync.native(cwd))
2221
2827
  return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel))
2222
2828
  } catch {
2223
2829
  return false
2224
2830
  }
2225
2831
  })()
2226
2832
  if (inside) {
2227
- refuse([`this shell is inside the worktree — \`cd ${dir}\` first, then re-run`])
2833
+ refuse([`this shell is inside the worktree — \`cd ${shellPath(dir)}\` first, then re-run`])
2834
+ return
2835
+ }
2836
+
2837
+ if (spec.baseVersion && spec.baseVersion.kind === 'branch') {
2838
+ hotfixFinishBranch(dir, config, spec, { say, refuse, json })
2228
2839
  return
2229
2840
  }
2230
2841
 
@@ -2269,6 +2880,81 @@ function hotfixFinish(dir, config, specArg, flags) {
2269
2880
  say(` deleted: ${spec.branch} (local; ${remote} keeps it)`)
2270
2881
  }
2271
2882
 
2883
+ // `hotfix finish` for a branch-based hotfix: the land and the carry, each
2884
+ // asked of git first and of the host only where git cannot answer (a squash
2885
+ // merge leaves nothing ancestry can see).
2886
+ function hotfixFinishBranch(dir, config, spec, { say, refuse, json }) {
2887
+ const remote = baseRemote(config)
2888
+ const releaseBranch = spec.baseVersion.branch
2889
+ const releaseRef = `${remote}/${releaseBranch}`
2890
+ const wtGit = gitReader(spec.worktreePath)
2891
+ const git = gitReader(dir)
2892
+ try {
2893
+ execFileSync('git', ['-C', dir, 'fetch', remote, releaseBranch], { stdio: 'ignore' })
2894
+ } catch {}
2895
+ const status = wtGit(['status', '--porcelain'])
2896
+ const record = readHotfixRecord(dir, config, spec.folder) || {}
2897
+ const fixCommits = Array.isArray(record.fixCommits) ? record.fixCommits : null
2898
+
2899
+ // Landed: HEAD on the release branch, or every fix commit's patch there, or
2900
+ // the host saying the PR merged. Only a host that cannot answer is cannot-tell.
2901
+ let landed = wtGit(['merge-base', '--is-ancestor', 'HEAD', releaseRef]) !== null
2902
+ if (!landed && fixCommits) landed = missingOn(git, releaseRef, fixCommits).length === 0
2903
+ if (!landed) {
2904
+ const pr = hostPrFor(spec.worktreePath, remote, spec.branch)
2905
+ landed = pr.state === 'merged' ? true : pr.state === 'cannot-tell' ? undefined : false
2906
+ }
2907
+
2908
+ process.stdout.write(fetchNote('hotfix finish', config, fetchForPattern(dir, config)))
2909
+ const base = resolveBaseBranch(config, git)
2910
+ let carried
2911
+ if (config.hotfix.cherryPickMain === false || base === releaseBranch) carried = 'not-needed'
2912
+ else if (!fixCommits) carried = undefined
2913
+ else {
2914
+ try {
2915
+ execFileSync('git', ['-C', dir, 'fetch', remote, base], { stdio: 'ignore' })
2916
+ } catch {}
2917
+ const refs = [`${remote}/${base}`, base].filter((r) => git(['rev-parse', '--verify', '--quiet', r]) !== null)
2918
+ carried = refs.some((r) => missingOn(git, r, fixCommits).length === 0)
2919
+ if (!carried) {
2920
+ const pr = hostPrFor(dir, remote, `carry/${spec.slug}`)
2921
+ if (pr.state === 'merged') carried = true
2922
+ }
2923
+ }
2924
+
2925
+ const registry = readRegistry(dir, config)
2926
+ const plan = planBranchHotfixFinish(spec, {
2927
+ dirty: status === null || status.length > 0,
2928
+ landed,
2929
+ carried,
2930
+ releaseBranch,
2931
+ base,
2932
+ mainRepoPath: dir,
2933
+ hasSlot: Object.prototype.hasOwnProperty.call(registry.slots, spec.folder),
2934
+ })
2935
+ if (plan.blocked) {
2936
+ refuse(plan.reasons)
2937
+ return
2938
+ }
2939
+ for (const argv of plan.argvs) {
2940
+ if (git(argv) === null) {
2941
+ refuse([`git ${argv.join(' ')} failed — nothing after it ran`])
2942
+ return
2943
+ }
2944
+ }
2945
+ fs.rmSync(hotfixRecordPath(dir, config, spec.folder), { force: true })
2946
+ if (json) {
2947
+ say(JSON.stringify({ ok: true, spec: spec.folder, landedOn: releaseBranch, carriedTo: carried === 'not-needed' ? null : base, removed: spec.worktreePath, branchDeleted: spec.branch }, null, 2))
2948
+ return
2949
+ }
2950
+ say(`spec-env hotfix finish: ${spec.folder}`)
2951
+ say('')
2952
+ say(` landed: on ${releaseRef}`)
2953
+ say(` carried: ${carried === 'not-needed' ? 'nothing to carry' : `to ${base}`}`)
2954
+ say(` removed: ${spec.worktreePath}`)
2955
+ say(` deleted: ${spec.branch}`)
2956
+ }
2957
+
2272
2958
  function specEnvHotfix(dir, config, positional, flags) {
2273
2959
  const action = positional[0]
2274
2960
  const specArg = positional[1]
@@ -2302,6 +2988,13 @@ function specEnvHotfix(dir, config, positional, flags) {
2302
2988
  refuse(`${spec.folder} has no worktree — nothing to land.`)
2303
2989
  return
2304
2990
  }
2991
+ // A release BRANCH rather than a tag: the fix lands on it by `land.strategy`.
2992
+ // Decided by the spec's own header, so a hotfix cut before the project set
2993
+ // `hotfix.releaseBranch` keeps landing the way it was cut.
2994
+ if (spec.baseVersion && spec.baseVersion.kind === 'branch') {
2995
+ hotfixLandBranch(dir, config, spec, flags, { say, refuse, json })
2996
+ return
2997
+ }
2305
2998
 
2306
2999
  const base = resolveBaseBranch(config, gitReader(dir))
2307
3000
  const wtGit = gitReader(spec.worktreePath)
@@ -2425,8 +3118,8 @@ function specEnvHotfix(dir, config, positional, flags) {
2425
3118
  say('')
2426
3119
  say(` prod tag: ${tag} (cut locally — not pushed, nothing carried yet)`)
2427
3120
  say(` to deploy, push the branch, then the tag — re-run with --push, or run:`)
2428
- say(` git -C ${spec.worktreePath} push ${remote} ${spec.branch}`)
2429
- say(` git -C ${spec.worktreePath} push ${remote} ${tag}`)
3121
+ say(` git -C ${shellPath(spec.worktreePath)} push ${remote} ${spec.branch}`)
3122
+ say(` git -C ${shellPath(spec.worktreePath)} push ${remote} ${tag}`)
2430
3123
  say(` then re-run \`skitterspec spec-env hotfix land ${spec.folder}\` to carry the fix.`)
2431
3124
  } else if (result.ok) {
2432
3125
  say('')
@@ -2445,12 +3138,257 @@ function specEnvHotfix(dir, config, positional, flags) {
2445
3138
  if (!result.ok) process.exitCode = 1
2446
3139
  }
2447
3140
 
3141
+ // The fix commits of a branch-based hotfix, and which of them `ref` already
3142
+ // has. The list is taken BEFORE the land — `<release>..HEAD`, the hotfix's own
3143
+ // commits — and recorded, because once the land has happened that range is
3144
+ // empty and nothing else in the history says which commits were the fix.
3145
+ // A recorded list wins on every later run.
3146
+ function branchFixCommits(dir, config, spec, wtGit, releaseRef) {
3147
+ const record = readHotfixRecord(dir, config, spec.folder) || {}
3148
+ if (Array.isArray(record.fixCommits) && record.fixCommits.length) return record.fixCommits
3149
+ const own = wtGit(['rev-list', '--reverse', '--no-merges', `${releaseRef}..HEAD`])
3150
+ const commits = (own ? own.split('\n') : []).map((x) => x.trim()).filter(Boolean)
3151
+ if (commits.length) writeHotfixRecord(dir, config, spec.folder, { ...record, fixCommits: commits })
3152
+ return commits.length ? commits : null
3153
+ }
3154
+
3155
+ // Which of `commits` `ref` does not have yet, by patch rather than by sha — a
3156
+ // cherry-pick or a squash merge is the same change under another sha. `git
3157
+ // cherry` prints `+ <sha>` for a change `ref` lacks, `- <sha>` for one it has
3158
+ // under another sha, and NOTHING when the commit itself is already in `ref`. A
3159
+ // commit git will not compare stays in the list: it then fails as an empty
3160
+ // pick, loudly, which is the safe direction to be wrong in.
3161
+ function missingOn(git, ref, commits) {
3162
+ return commits.filter((sha) => {
3163
+ const out = git(['cherry', ref, sha, `${sha}^`])
3164
+ return out === null || out.split('\n').some((l) => l.trim().startsWith('+'))
3165
+ })
3166
+ }
3167
+
3168
+ // How a branch-based hotfix's carry would run now, or null for no carry.
3169
+ function branchCarry(dir, config, spec, strategy, releaseBranch, fixCommits) {
3170
+ if (config.hotfix.cherryPickMain === false || !fixCommits) return null
3171
+ process.stdout.write(fetchNote('hotfix land', config, fetchForPattern(dir, config)))
3172
+ const base = resolveBaseBranch(config, gitReader(dir))
3173
+ if (base === releaseBranch) return null
3174
+ const remote = baseRemote(config)
3175
+ const git = gitReader(dir)
3176
+ try {
3177
+ execFileSync('git', ['-C', dir, 'fetch', remote, base], { stdio: 'ignore' })
3178
+ } catch {}
3179
+ const hasLocal = git(['show-ref', '--verify', '--quiet', `refs/heads/${base}`]) !== null
3180
+ const files = carryFiles(git, fixCommits)
3181
+ if (strategy === 'pr') {
3182
+ const carryBranch = `carry/${spec.slug}`
3183
+ const commits = missingOn(git, `${remote}/${base}`, fixCommits)
3184
+ const pr = hostPrFor(dir, remote, carryBranch)
3185
+ const info = parseRemote(git(['config', '--get', `remote.${remote}.url`]))
3186
+ return {
3187
+ base,
3188
+ strategy: 'pr',
3189
+ path: dir,
3190
+ root: dir,
3191
+ tmpPath: path.join(path.dirname(spec.worktreePath), `${spec.slug}-carry`),
3192
+ commits,
3193
+ startRef: `${remote}/${base}`,
3194
+ carryBranch,
3195
+ prState: pr.state,
3196
+ prCommand: prPlanCommand(info, pr, { branch: carryBranch, base, draft: false }),
3197
+ files,
3198
+ }
3199
+ }
3200
+ const commits = missingOn(git, hasLocal ? base : `${remote}/${base}`, fixCommits)
3201
+ // Where the base is checked out decides how: in place when clean, refused
3202
+ // when dirty, a throwaway worktree when it is checked out nowhere.
3203
+ const list = git(['worktree', 'list', '--porcelain']) || ''
3204
+ let where = null
3205
+ let current = null
3206
+ for (const line of list.split('\n')) {
3207
+ if (line.startsWith('worktree ')) current = line.slice('worktree '.length)
3208
+ else if (line === `branch refs/heads/${base}`) where = current
3209
+ }
3210
+ if (where) {
3211
+ const st = gitReader(where)(['status', '--porcelain'])
3212
+ return { base, strategy: st ? 'dirty' : 'inplace', path: where, root: dir, commits, files }
3213
+ }
3214
+ const tmpPath = path.join(path.dirname(spec.worktreePath), `${spec.slug}-carry-${base.replace(/[^a-zA-Z0-9]+/g, '-')}`)
3215
+ return { base, strategy: 'worktree', path: dir, root: dir, tmpPath, commits, files }
3216
+ }
3217
+
3218
+ // `hotfix land` for a branch-based hotfix: gather the facts, plan with
3219
+ // `planBranchHotfixLand`, run the steps — land, tag, then carry to the rc.
3220
+ function hotfixLandBranch(dir, config, spec, flags, { say, refuse, json }) {
3221
+ if (flags.strategy !== undefined && flags.strategy !== 'ff' && flags.strategy !== 'pr') {
3222
+ refuse(`unknown --strategy "${flags.strategy}" — use ff or pr.`)
3223
+ return
3224
+ }
3225
+ const strategy = flags.strategy || (config.land && config.land.strategy) || 'ff'
3226
+ const remote = baseRemote(config)
3227
+ const releaseBranch = spec.baseVersion.branch
3228
+ const releaseRef = `${remote}/${releaseBranch}`
3229
+ const wtGit = gitReader(spec.worktreePath)
3230
+
3231
+ // The land is onto the release branch as it is NOW. A failed fetch leaves the
3232
+ // last-fetched image, which a non-fast-forward push refuses loudly if stale.
3233
+ try {
3234
+ execFileSync('git', ['-C', spec.worktreePath, 'fetch', remote, releaseBranch], { stdio: 'ignore' })
3235
+ } catch {}
3236
+
3237
+ const status = wtGit(['status', '--porcelain'])
3238
+ const isAncestor = (a, b) => wtGit(['merge-base', '--is-ancestor', a, b]) !== null
3239
+ const head = wtGit(['rev-parse', 'HEAD'])
3240
+ const tagList = wtGit(['tag', '--list'])
3241
+ const existingTags = tagList ? tagList.split('\n').map((t) => t.trim()).filter(Boolean) : []
3242
+ const record = readHotfixRecord(dir, config, spec.folder)
3243
+ const atHead = (wtGit(['tag', '--points-at', 'HEAD']) || '').split('\n').map((t) => t.trim())
3244
+ // ff: a recorded release counts while HEAD still carries it. pr: the tag sits
3245
+ // on the release branch, never on HEAD, so the record and the tag existing is
3246
+ // the signal.
3247
+ const released =
3248
+ record && record.tag && (strategy === 'pr' ? existingTags.includes(record.tag) : atHead.includes(record.tag))
3249
+ ? record
3250
+ : null
3251
+ const tagPushed = released !== null && Boolean(wtGit(['ls-remote', '--tags', remote, `refs/tags/${released.tag}`]))
3252
+ const remoteHead = (wtGit(['ls-remote', '--heads', remote, `refs/heads/${spec.branch}`]) || '').split(/\s+/)[0] || null
3253
+
3254
+ let pr = null
3255
+ let prCommand = null
3256
+ if (strategy === 'pr') {
3257
+ pr = hostPrFor(spec.worktreePath, remote, spec.branch)
3258
+ const info = parseRemote(wtGit(['config', '--get', `remote.${remote}.url`]))
3259
+ // Ready, never draft: a hotfix is finished work.
3260
+ prCommand = prPlanCommand(info, pr, { branch: spec.branch, base: releaseBranch, draft: false })
3261
+ }
3262
+ const fixCommits = branchFixCommits(dir, config, spec, wtGit, releaseRef)
3263
+ const carry = branchCarry(dir, config, spec, strategy, releaseBranch, fixCommits)
3264
+
3265
+ let plan
3266
+ try {
3267
+ plan = planBranchHotfixLand(spec, config, {
3268
+ dirty: status === null || status.length > 0,
3269
+ remote,
3270
+ strategy,
3271
+ push: flags.push === true,
3272
+ behind: !isAncestor(releaseRef, 'HEAD'),
3273
+ onRelease: isAncestor('HEAD', releaseRef),
3274
+ headOnRemote: Boolean(head) && remoteHead === head,
3275
+ pr,
3276
+ prCommand,
3277
+ lastTag: wtGit(['describe', '--tags', '--abbrev=0', releaseRef]),
3278
+ existingTags,
3279
+ released,
3280
+ tagPushed,
3281
+ carry,
3282
+ })
3283
+ } catch (error) {
3284
+ refuse(`${error.message}.`)
3285
+ return
3286
+ }
3287
+ if (plan.blocked) {
3288
+ refuse(`blocked — ${plan.reason}.`)
3289
+ return
3290
+ }
3291
+ if (plan.noop) {
3292
+ if (json) say(JSON.stringify({ ok: true, noop: true, reason: plan.reason }, null, 2))
3293
+ else say(`spec-env hotfix land: ${plan.reason}.`)
3294
+ return
3295
+ }
3296
+
3297
+ const header = () => {
3298
+ say(`spec-env hotfix land: ${spec.folder}${flags.plan ? ' (plan — nothing run)' : ''}`)
3299
+ say('')
3300
+ say(` release: ${releaseRef} (${strategy === 'pr' ? 'by pull request' : 'fast-forward'})`)
3301
+ say(` branch: ${spec.branch}`)
3302
+ if (carry) say(` carry to: ${carry.base}${carry.strategy === 'pr' ? ` (via ${carry.carryBranch})` : ''}`)
3303
+ }
3304
+ if (flags.plan) {
3305
+ if (json) {
3306
+ say(JSON.stringify({ spec: spec.folder, planned: true, strategy, steps: plan.steps }, null, 2))
3307
+ return
3308
+ }
3309
+ header()
3310
+ say('')
3311
+ plan.steps.forEach((st, i) => say(` ${i + 1}. ${describeHotfixStep(st)}`))
3312
+ return
3313
+ }
3314
+
3315
+ if (!json) {
3316
+ header()
3317
+ say('')
3318
+ }
3319
+ const result = runHotfixLand(plan.steps, {
3320
+ write: json ? () => {} : (line) => say(` ${line}`),
3321
+ childStdout: json ? process.stderr : 'inherit',
3322
+ // Merged into what is there, so the recorded fix commits survive a release.
3323
+ record: (release) =>
3324
+ writeHotfixRecord(dir, config, spec.folder, {
3325
+ ...(readHotfixRecord(dir, config, spec.folder) || {}),
3326
+ ...release,
3327
+ at: new Date().toISOString(),
3328
+ }),
3329
+ })
3330
+ const tag = result.release ? result.release.tag : null
3331
+ const last = result.results[result.results.length - 1]
3332
+
3333
+ if (json) {
3334
+ say(
3335
+ JSON.stringify(
3336
+ {
3337
+ spec: spec.folder,
3338
+ planned: false,
3339
+ strategy,
3340
+ ok: result.ok,
3341
+ held: result.held === true,
3342
+ waiting: Boolean(last && last.step.kind === 'wait'),
3343
+ failedAt: result.failedAt,
3344
+ release: result.release,
3345
+ steps: result.results.map((r) => ({ ...r.step, outcome: r.outcome, line: r.line })),
3346
+ remaining: plan.steps.slice(result.results.length),
3347
+ },
3348
+ null,
3349
+ 2,
3350
+ ),
3351
+ )
3352
+ } else if (result.held && last.step.kind === 'wait') {
3353
+ say('')
3354
+ say(` landing: the PR into ${releaseBranch} is open — re-run \`skitterspec spec-env hotfix land ${spec.folder}\` once it merges`)
3355
+ } else if (result.held && last.step.kind === 'carry') {
3356
+ say('')
3357
+ say(` landed: on ${releaseRef}${tag ? ` · tagged ${tag}` : ''}`)
3358
+ say(` held: the carry to ${last.step.base} — re-run with --push to push ${last.step.carryBranch} and open its PR.`)
3359
+ } else if (result.held) {
3360
+ const st = last.step
3361
+ const refs = [...(Array.isArray(st.refs) ? st.refs : []), ...(st.withTag !== false && tag ? [tag] : [])]
3362
+ say('')
3363
+ say(` held: nothing pushed — the push to ${remote} is what ${strategy === 'pr' ? 'opens the PR' : 'lands the fix'}.`)
3364
+ say(' re-run with --push, or run:')
3365
+ for (const ref of refs) {
3366
+ say(` git -C ${shellPath(spec.worktreePath)} push ${st.force ? '--force-with-lease -u ' : ''}${remote} ${ref}`)
3367
+ }
3368
+ say(` then re-run \`skitterspec spec-env hotfix land ${spec.folder}\`.`)
3369
+ } else if (result.ok) {
3370
+ say('')
3371
+ say(` landed: on ${releaseRef}${tag ? ` · tagged ${tag}` : ''}`)
3372
+ if (result.carried) process.stdout.write(afterLandSection(plan.afterLand))
3373
+ } else {
3374
+ process.stderr.write(` ${last.line}\n`)
3375
+ say(
3376
+ `spec-env hotfix land: stopped at step ${result.failedAt} of ${plan.steps.length} ` +
3377
+ `(${describeHotfixStep(last.step)}) — nothing after it ran.`,
3378
+ )
3379
+ if (tag) say(` ${tag} was cut and is recorded — a re-run carries on from it.`)
3380
+ }
3381
+ if (!result.ok) process.exitCode = 1
3382
+ }
3383
+
2448
3384
  // What the primary checkout has GAINED right now, by content. `dir` is already
2449
3385
  // anchored on the primary checkout by the dispatcher, so this reads the tree the
2450
3386
  // build must not be writing into. See env/building.js for why this is two
2451
3387
  // content-based queries rather than one `status --porcelain`.
2452
- function primaryPaths(dir) {
2453
- const git = gitReader(dir)
3388
+ // Read from the repo ROOT, so a build that leaked outside a subfolder project —
3389
+ // into `Sql/`, say — is still seen (feat-subfolder-project).
3390
+ function primaryPaths(dir, config) {
3391
+ const git = gitReader(repoRootOf(dir, config))
2454
3392
  return building.mergePaths(
2455
3393
  git(['diff', '--name-only', 'HEAD']),
2456
3394
  git(['ls-files', '--others', '--exclude-standard']),
@@ -2464,7 +3402,7 @@ function recordPrimary(dir, config, r) {
2464
3402
  spec: r.folder,
2465
3403
  worktreePath: r.worktreePath,
2466
3404
  primary: dir,
2467
- paths: primaryPaths(dir),
3405
+ paths: primaryPaths(dir, config),
2468
3406
  })
2469
3407
  fs.mkdirSync(path.dirname(file), { recursive: true })
2470
3408
  fs.writeFileSync(file, JSON.stringify(baseline, null, 2) + '\n')
@@ -2492,7 +3430,7 @@ function assertPrimaryClean(dir, config, r) {
2492
3430
  } catch {
2493
3431
  baseline = null
2494
3432
  }
2495
- const result = building.compare(baseline, primaryPaths(dir), {
3433
+ const result = building.compare(baseline, primaryPaths(dir, config), {
2496
3434
  spec: r.folder,
2497
3435
  worktreePath: r.worktreePath,
2498
3436
  primary: dir,
@@ -2538,11 +3476,134 @@ function specEnvResolve(dir, config, specArg, flags = {}) {
2538
3476
  `spec: ${r.folder} (${r.specless ? 'no spec' : r.bucket})\n` +
2539
3477
  `type/slug: ${r.type} / ${r.slug}\n` +
2540
3478
  `branch: ${r.branch}\n` +
2541
- `worktree: ${r.worktreePath}\n` +
2542
- `project: ${r.projectName}\n`,
3479
+ `worktree: ${r.projectPath}\n` +
3480
+ `project: ${r.projectName}\n` +
3481
+ projectLine(config.project),
2543
3482
  )
2544
3483
  }
2545
3484
 
3485
+ /**
3486
+ * `skitterspec spec-env base [--json]`
3487
+ *
3488
+ * Which branch is the base, how it was found, and — under `baseBranchPattern` —
3489
+ * every match newest-first plus the provisioned specs that forked from an older
3490
+ * one. It fetches first, because the resolver itself never does: a release
3491
+ * candidate cut since the last fetch is invisible to it.
3492
+ *
3493
+ * Lists only and always exits 0. A failed fetch is reported and the listing
3494
+ * carries on from the refs already here; nothing is edited, and pinning stays a
3495
+ * hand edit of `baseBranch`.
3496
+ */
3497
+ function specEnvBase(dir, config, flags = {}) {
3498
+ const pattern = (config.baseBranchPattern || '').trim()
3499
+ const remote = baseRemote(config)
3500
+ const git = gitReader(dir)
3501
+
3502
+ // No pattern: the base is today's chain, and there is nothing to fetch for —
3503
+ // origin/HEAD is not updated by a fetch.
3504
+ const fetch = fetchForPattern(dir, config)
3505
+ const { base, how } = describeBaseBranch(config, git)
3506
+
3507
+ let matches = []
3508
+ let forks = []
3509
+ if (pattern) {
3510
+ matches = patternMatches(git, config)
3511
+ const names = matches.map((m) => m.name)
3512
+ forks = provisionedBranches(dir, config).map(({ spec, branch }) => ({
3513
+ spec,
3514
+ forkedFrom: forkedFromMatch(git, config, names, branch),
3515
+ }))
3516
+ }
3517
+
3518
+ const { json, lines } = planBaseReport({ pattern, remote, base, how, fetch, matches, forks })
3519
+ process.stdout.write(flags.json ? JSON.stringify(json, null, 2) + '\n' : lines.join('\n') + '\n')
3520
+ }
3521
+
3522
+ // Fetch the base's remote, but only where `baseBranchPattern` decides the base:
3523
+ // the resolver reads remote-tracking refs and never the network, so a release
3524
+ // candidate cut since the last fetch is invisible until something fetches. With
3525
+ // no pattern nothing is fetched and every plan stays byte-identical.
3526
+ // Returns null (no pattern) or { ok, reason }; never throws.
3527
+ function fetchForPattern(dir, config) {
3528
+ if (!(config.baseBranchPattern || '').trim()) return null
3529
+ try {
3530
+ execFileSync('git', ['-C', dir, 'fetch', '--prune', baseRemote(config)], { stdio: ['ignore', 'ignore', 'pipe'] })
3531
+ return { ok: true, reason: null }
3532
+ } catch (error) {
3533
+ const stderr = error.stderr ? error.stderr.toString() : ''
3534
+ return { ok: false, reason: stderr.split('\n').map((l) => l.trim()).find(Boolean) || null }
3535
+ }
3536
+ }
3537
+
3538
+ // One line for a plan whose fetch failed; nothing for one that worked or never
3539
+ // ran. A failed fetch is not a refusal — the refs already here still resolve.
3540
+ function fetchNote(verb, config, fetch) {
3541
+ if (!fetch || fetch.ok) return ''
3542
+ return (
3543
+ `spec-env ${verb}: fetch from ${baseRemote(config)} failed` +
3544
+ `${fetch.reason ? ` (${fetch.reason})` : ''} — resolving from the refs already here.\n`
3545
+ )
3546
+ }
3547
+
3548
+ // Every remote branch matching `baseBranchPattern`, newest first by committer
3549
+ // date, as { name, date } with the remote prefix stripped.
3550
+ function patternMatches(git, config) {
3551
+ const pattern = (config.baseBranchPattern || '').trim()
3552
+ if (!pattern) return []
3553
+ const prefix = `refs/remotes/${baseRemote(config)}/`
3554
+ const out = git([
3555
+ 'for-each-ref',
3556
+ '--sort=-committerdate',
3557
+ '--format=%(refname)%09%(committerdate:short)',
3558
+ `${prefix}${pattern}`,
3559
+ ])
3560
+ return (out || '')
3561
+ .split('\n')
3562
+ .map((line) => line.split('\t'))
3563
+ .filter(([ref]) => ref && ref.startsWith(prefix) && ref !== `${prefix}HEAD`)
3564
+ .map(([ref, date]) => ({ name: ref.slice(prefix.length), date: date || null }))
3565
+ }
3566
+
3567
+ // Which pattern match `branch` forked from (see `forkMatch`), or null.
3568
+ function forkedFromMatch(git, config, names, branch) {
3569
+ const prefix = `refs/remotes/${baseRemote(config)}/`
3570
+ return forkMatch(
3571
+ names,
3572
+ (name) => git(['merge-base', branch, `${prefix}${name}`]),
3573
+ (a, b) => git(['merge-base', '--is-ancestor', a, b]) !== null,
3574
+ )
3575
+ }
3576
+
3577
+ // `{ from, to }` when a branch forked from an older pattern match than the base
3578
+ // it is about to land on — the rc rolled while the spec was in flight. Null
3579
+ // whenever the pattern did not choose the base (a pin is a deliberate choice,
3580
+ // and no pattern means no roll), and on every cannot-tell.
3581
+ function retargetFor(git, config, branch) {
3582
+ const { base, how } = describeBaseBranch(config, git)
3583
+ if (how !== 'pattern' || !base) return null
3584
+ const from = forkedFromMatch(git, config, patternMatches(git, config).map((m) => m.name), branch)
3585
+ return from && from !== base ? { from, to: base } : null
3586
+ }
3587
+
3588
+ // Every provisioned spec with the branch its worktree has checked out. A
3589
+ // worktree on a detached HEAD (a spec taken live) names no branch and is left
3590
+ // out: there is nothing to compute a fork from, and saying nothing is the
3591
+ // harmless answer.
3592
+ function provisionedBranches(dir, config) {
3593
+ const list = gitReader(dir)(['worktree', 'list', '--porcelain'])
3594
+ const branchAt = new Map()
3595
+ let current = null
3596
+ for (const line of (list || '').split('\n')) {
3597
+ if (line.startsWith('worktree ')) current = path.resolve(line.slice('worktree '.length).trim())
3598
+ else if (line.startsWith('branch refs/heads/') && current) branchAt.set(current, line.slice('branch refs/heads/'.length))
3599
+ }
3600
+ return allSpecs(dir, config, new Set(branchAt.keys()), speclessMap(dir, config))
3601
+ .map((s) => ({ spec: s.folder, wt: path.resolve(s.worktreePath) }))
3602
+ .filter((s) => s.wt !== path.resolve(dir) && branchAt.has(s.wt))
3603
+ .map((s) => ({ spec: s.spec, branch: branchAt.get(s.wt) }))
3604
+ .sort((a, b) => a.spec.localeCompare(b.spec))
3605
+ }
3606
+
2546
3607
  /**
2547
3608
  * `skitterspec spec-env stage [<spec>] [--json]`
2548
3609
  *
@@ -2582,7 +3643,10 @@ function specEnvStage(dir, config, specArg, flags = {}, invokedFrom = dir) {
2582
3643
  // is scoped to its cwd, so reading from a subdirectory would list only that
2583
3644
  // subdirectory's untracked files and report the rest of the spec as absent.
2584
3645
  const git = gitReader(invokedFrom)
2585
- const tree = git(['rev-parse', '--show-toplevel']) || invokedFrom
3646
+ // `path.resolve`d: git prints the toplevel with `/` on every platform
3647
+ // (`C:/Users/…` on Windows), and every other path here is an OS path.
3648
+ const top = git(['rev-parse', '--show-toplevel'])
3649
+ const tree = top ? path.resolve(top) : invokedFrom
2586
3650
  const paths = dirtyPaths(gitReader(tree))
2587
3651
 
2588
3652
  // Three states, not two (`.claude/rules/negative-checks.md` rule 4). A null
@@ -2608,16 +3672,23 @@ function specEnvStage(dir, config, specArg, flags = {}, invokedFrom = dir) {
2608
3672
  return
2609
3673
  }
2610
3674
 
2611
- const { owned, foreign } = classifyDirtyTree(spec, paths, config)
3675
+ // Classified as git paths from the tree's ROOT, reported relative to the
3676
+ // PROJECT folder in it — what a pathspec is when run from where a session
3677
+ // stands. The same thing at the root of a repo (feat-subfolder-project).
3678
+ const prefix = prefixOf(config)
3679
+ const split = classifyDirtyTree(spec, paths, config)
3680
+ const owned = split.owned.map((p) => projectRelative(p, prefix))
3681
+ const foreign = split.foreign.map((p) => projectRelative(p, prefix))
3682
+ const treeShown = prefix ? projectIn(tree, prefix) : tree
2612
3683
 
2613
3684
  if (flags.json) {
2614
- process.stdout.write(JSON.stringify({ spec: spec.folder, tree, owned, foreign }) + '\n')
3685
+ process.stdout.write(JSON.stringify({ spec: spec.folder, tree: treeShown, owned, foreign }) + '\n')
2615
3686
  return
2616
3687
  }
2617
3688
 
2618
3689
  const out = [
2619
3690
  `spec-env stage: ${spec.folder} — ${owned.length} owned, ${foreign.length} foreign`,
2620
- ` tree: ${tree}`,
3691
+ ` tree: ${treeShown}`,
2621
3692
  ]
2622
3693
  // An empty list is omitted rather than printed under its heading: a heading
2623
3694
  // with nothing beneath it reads as a finding.
@@ -2663,7 +3734,10 @@ function specEnvStage(dir, config, specArg, flags = {}, invokedFrom = dir) {
2663
3734
  */
2664
3735
  function resolveSpecDocs(config, spec, invokedFrom) {
2665
3736
  const git = gitReader(invokedFrom)
2666
- const tree = git(['rev-parse', '--show-toplevel']) || invokedFrom
3737
+ // `path.resolve`d: git prints the toplevel with `/` on every platform
3738
+ // (`C:/Users/…` on Windows), and every other path here is an OS path.
3739
+ const top = git(['rev-parse', '--show-toplevel'])
3740
+ const tree = top ? path.resolve(top) : invokedFrom
2667
3741
  // THE CLASSIFICATION IS SHARED with the review server's route for the same
2668
3742
  // spec (`specDocsIn`), so the served page and the written page cannot
2669
3743
  // disagree about which files they show. This function adds only the wording.
@@ -3032,7 +4106,7 @@ function specEnvReviewGate(dir, config, specArg, flags, invokedFrom = dir) {
3032
4106
  if (flags.forCommand !== undefined && judged.state === 'armed') {
3033
4107
  const inside = (child, parent) => {
3034
4108
  try {
3035
- const rel = path.relative(fs.realpathSync(parent), fs.realpathSync(child))
4109
+ const rel = path.relative(fs.realpathSync.native(parent), fs.realpathSync.native(child))
3036
4110
  return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel))
3037
4111
  } catch {
3038
4112
  return false
@@ -3587,7 +4661,9 @@ async function specEnvReview(dir, config, specArg, flags, invokedFrom = dir) {
3587
4661
  }),
3588
4662
  )
3589
4663
 
3590
- const readFrom = docs ? docs.tree : live.state === 'on' ? dir : spec.worktreePath
4664
+ // Always a git ROOT, so every path the reader prints is root-relative and
4665
+ // every pathspec it is handed means the same thing (feat-subfolder-project).
4666
+ const readFrom = docs ? docs.tree : live.state === 'on' ? repoRootOf(dir, config) : spec.worktreePath
3591
4667
  const git = rawGitReader(readFrom)
3592
4668
  const trimmed = gitReader(readFrom)
3593
4669
 
@@ -3605,8 +4681,11 @@ async function specEnvReview(dir, config, specArg, flags, invokedFrom = dir) {
3605
4681
  // tag is not an ancestor of the base branch (a release line that never merged
3606
4682
  // back) the range widens to include commits the hotfix never touched.
3607
4683
  //
3608
- // Lazy, so the common working-tree path pays nothing for it.
3609
- const reviewBase = () => spec.baseRef || resolveBaseBranch(config, trimmed)
4684
+ // Lazy, so the common working-tree path pays nothing for it. PR mode prefers
4685
+ // the remote image of base via `preferRemoteBase` — one helper shared with
4686
+ // serve.js, so the two renders cannot disagree about a spec's range.
4687
+ const reviewBase = () =>
4688
+ spec.baseRef || preferRemoteBase(config, resolveBaseBranch(config, trimmed), trimmed)
3610
4689
 
3611
4690
  if (flags.branch) {
3612
4691
  base = reviewBase()
@@ -4230,7 +5309,9 @@ async function specEnvReview(dir, config, specArg, flags, invokedFrom = dir) {
4230
5309
  // The paths a committing verdict on this page must commit, so the
4231
5310
  // skill that routes on it never recomputes the set the reader saw.
4232
5311
  // Absent for every other mode, which keeps their output identical.
4233
- ...(docs ? { docs: { paths: docs.owned } } : {}),
5312
+ // Project-relative: the pathspec `/commit` is handed runs from the
5313
+ // project folder.
5314
+ ...(docs ? { docs: { paths: docs.owned.map((p) => projectRelative(p, prefixOf(config))) } } : {}),
4234
5315
  out,
4235
5316
  publishCopy,
4236
5317
  reader: reader.reader,
@@ -4442,7 +5523,7 @@ async function specEnvDev(dir, config, positional) {
4442
5523
  if (action === 'up') {
4443
5524
  const out = [`spec-env dev up: ${spec.folder} slot ${slot} (ports from ${plan.portOffset})`]
4444
5525
  for (const proc of plan.procs) {
4445
- const res = startProcess(proc, { cwd: spec.worktreePath, rootDir: dir })
5526
+ const res = startProcess(proc, { cwd: spec.projectPath, rootDir: dir })
4446
5527
  let health = ''
4447
5528
  if (proc.health) {
4448
5529
  health = (await waitHealthy(proc.health)) ? ' health: ok' : ' health: TIMEOUT'
@@ -4530,7 +5611,9 @@ function proxyProcFor(config, routesFileAbs) {
4530
5611
  const sdir = stateDirLabel(config)
4531
5612
  return {
4532
5613
  name: 'proxy',
4533
- command: `node ${path.join(__dirname, 'env', 'proxy.js')} ${routesFileAbs}`,
5614
+ // Quoted: this runs through `sh -c`, which eats a Windows path's
5615
+ // backslashes and splits any path with a space (chore-windows-ci).
5616
+ command: `node ${shellPath(path.join(__dirname, 'env', 'proxy.js'))} ${shellPath(routesFileAbs)}`,
4534
5617
  env: {},
4535
5618
  logFile: `${sdir}/logs/proxy.log`,
4536
5619
  pidFile: `${sdir}/pids/proxy.pid`,
@@ -4598,7 +5681,9 @@ function serveProcFor(config, settingsFileAbs, { root = null } = {}) {
4598
5681
  const sdir = stateDirLabel(config)
4599
5682
  return {
4600
5683
  name: 'review-serve',
4601
- command: `node ${daemonScript(root)} ${settingsFileAbs}`,
5684
+ // Quoted: this runs through `sh -c`, which eats a Windows path's
5685
+ // backslashes and splits any path with a space (chore-windows-ci).
5686
+ command: `node ${shellPath(daemonScript(root))} ${shellPath(settingsFileAbs)}`,
4602
5687
  script: daemonScript(root),
4603
5688
  env: {},
4604
5689
  logFile: `${sdir}/logs/review-serve.log`,
@@ -5311,6 +6396,19 @@ function liveGrammar(dir, config, positional) {
5311
6396
  * would be a second copy free to drift from the first.
5312
6397
  */
5313
6398
  function bareLive(dir, config) {
6399
+ // The workbench must be FREE, not merely un-refused — and it is asked FIRST,
6400
+ // before which spec is even a question. A held instance refuses every bare
6401
+ // take no matter what resolves, so the ambiguity note below would ask the
6402
+ // reader to name a spec that naming cannot help — an ask that buries the
6403
+ // report's own `in-flight:` line, which is the real answer. The report names
6404
+ // the branch, the in-flight spec and the receipt, so it already says why
6405
+ // nothing was taken, and a note here would only contradict it.
6406
+ const primary = assertPrimaryOnMain(config, gitReader(dir))
6407
+ const receipt = readReceipt(dir, config)
6408
+ if (!primary.onBase || (receipt && receipt.spec)) {
6409
+ return { action: 'status', specArg: undefined }
6410
+ }
6411
+
5314
6412
  const choice = provisionedSpecChoice(dir, config)
5315
6413
  if (!choice.folder) {
5316
6414
  // Several worktrees is the only cannot-tell the status report does not
@@ -5324,15 +6422,6 @@ function bareLive(dir, config) {
5324
6422
  return { action: 'status', specArg: undefined, note }
5325
6423
  }
5326
6424
 
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
6425
  // Resolved here rather than passed as `undefined`, so the verb acts on the
5337
6426
  // spec this function actually decided about.
5338
6427
  return { action: 'take', specArg: choice.folder }
@@ -5768,6 +6857,8 @@ async function specEnv(rest) {
5768
6857
  else if (args[i] === '--docs') flags.docs = true
5769
6858
  else if (args[i] === '--plan') flags.plan = true
5770
6859
  else if (args[i] === '--push') flags.push = true
6860
+ else if (args[i] === '--draft') flags.draft = true
6861
+ else if (args[i] === '--strategy') flags.strategy = args[++i]
5771
6862
  else if (args[i] === '--from') flags.from = args[++i]
5772
6863
  else if (args[i] === '--session') flags.session = args[++i]
5773
6864
  else if (args[i] === '--path') flags.path = args[++i]
@@ -5780,11 +6871,15 @@ async function specEnv(rest) {
5780
6871
  // those two ask about the tree in front of you, and the two differ inside a
5781
6872
  // worktree.
5782
6873
  const invokedFrom = dir
5783
- // Anchor on the primary checkout so every subcommand resolves {repo}, worktree
5784
- // paths, and the registry identically whether run from main or a worktree.
5785
- dir = resolvePrimaryCheckout(dir, gitReader(dir))
6874
+ // Anchor on the project folder in the primary checkout so every subcommand
6875
+ // resolves {repo}, worktree paths, and the registry identically whether run
6876
+ // from main or a worktree — and from a project that sits in a subfolder of
6877
+ // its repo (env/project.js).
6878
+ const anchor = primaryAnchor(dir, gitReader(dir))
6879
+ dir = anchor.dir
5786
6880
 
5787
6881
  const { config, present, unknown, badReviewers } = loadEnvConfig(dir)
6882
+ attachProject(config, anchor)
5788
6883
  if (!present) {
5789
6884
  process.stdout.write(
5790
6885
  'spec-env: isolation not enabled (no specs/.core/env.config.json).\n' +
@@ -5865,7 +6960,13 @@ async function specEnv(rest) {
5865
6960
  await specEnvConnect(dir, config, positional[0])
5866
6961
  break
5867
6962
  case 'integrate':
5868
- specEnvIntegrate(dir, config, positional[0])
6963
+ specEnvIntegrate(dir, config, positional[0], flags)
6964
+ break
6965
+ case 'disposition':
6966
+ specEnvDisposition(dir, config, positional[0], flags)
6967
+ break
6968
+ case 'handoff':
6969
+ specEnvHandoff(dir, config, positional[0], flags)
5869
6970
  break
5870
6971
  case 'hotfix':
5871
6972
  specEnvHotfix(dir, config, positional, flags)
@@ -5876,6 +6977,9 @@ async function specEnv(rest) {
5876
6977
  case 'resolve':
5877
6978
  specEnvResolve(dir, config, positional[0], flags)
5878
6979
  break
6980
+ case 'base':
6981
+ specEnvBase(dir, config, flags)
6982
+ break
5879
6983
  case 'stage':
5880
6984
  specEnvStage(dir, config, positional[0], flags, invokedFrom)
5881
6985
  break
@@ -5976,6 +7080,11 @@ async function run(argv) {
5976
7080
  return
5977
7081
  }
5978
7082
 
7083
+ if (cmd === 'status') {
7084
+ inFlightStatus(rest)
7085
+ return
7086
+ }
7087
+
5979
7088
  const { opts, positional } = parse(rest)
5980
7089
  const dir = path.resolve(opts.dir || positional[0] || process.cwd())
5981
7090