@skitterbyte/skitterspec-linear 19.15.0 → 19.17.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 (45) hide show
  1. package/MIGRATION.md +27 -0
  2. package/README.md +2 -1
  3. package/assets/claude-md-section.md +18 -9
  4. package/assets/commands/allow-main.md +1 -2
  5. package/assets/core/env.config.json.example +0 -1
  6. package/assets/core/env.config.md +28 -26
  7. package/assets/hooks/main-guard.cjs +73 -6
  8. package/assets/hooks/project-guard.cjs +80 -6
  9. package/assets/hooks/review-gate.cjs +73 -6
  10. package/assets/review/page.html +10 -83
  11. package/assets/rules/commit-trailers.md +2 -2
  12. package/assets/rules/spec-planning.md +26 -22
  13. package/assets/rules/spec-reports.md +52 -52
  14. package/assets/skills/no-spec/SKILL.md +2 -2
  15. package/assets/skills/spec/SKILL.md +22 -5
  16. package/assets/skills/spec-bug/SKILL.md +18 -15
  17. package/assets/skills/spec-complete/SKILL.md +23 -1
  18. package/assets/skills/spec-diff/SKILL.md +47 -115
  19. package/assets/skills/spec-hotfix/SKILL.md +18 -15
  20. package/assets/skills/spec-init/SKILL.md +4 -2
  21. package/assets/skills/spec-next/SKILL.md +66 -41
  22. package/assets/skills/spec-park/SKILL.md +92 -0
  23. package/assets/skills/spec-resume/SKILL.md +153 -0
  24. package/assets/skills/spec-review/SKILL.md +2 -2
  25. package/assets/skills/spec-reviewed/SKILL.md +1 -8
  26. package/assets/skills/spec-status/SKILL.md +1 -1
  27. package/assets/skills/spec-sync/SKILL.md +12 -12
  28. package/assets/skills/spec-todo/SKILL.md +5 -2
  29. package/package.json +1 -1
  30. package/src/cli.js +361 -208
  31. package/src/env/bootstrap.js +3 -1
  32. package/src/env/checks.js +49 -0
  33. package/src/env/config.js +27 -7
  34. package/src/env/hooks.js +53 -4
  35. package/src/env/live.js +48 -0
  36. package/src/env/provision.js +10 -2
  37. package/src/env/resume.js +234 -0
  38. package/src/env/review.js +71 -173
  39. package/src/env/serve.js +3 -7
  40. package/src/init.js +383 -50
  41. package/src/tada/todo.js +19 -4
  42. package/src/vendor/linear/cli-sync.js +3 -3
  43. package/src/vendor/provider-kit/src/specs.js +46 -1
  44. package/src/vendor/sync-core/src/summary.js +10 -1
  45. package/assets/commands/spec-remote-review.md +0 -37
@@ -72,7 +72,9 @@ function runSeed(step, { cwd, mainRoot, fs, platform = process.platform }) {
72
72
  }
73
73
  fs.mkdirSync(path.dirname(dst), { recursive: true })
74
74
  if (step.mode === 'copy') {
75
- fs.copyFileSync(src, dst)
75
+ // A seed may be a directory (a local install seeds whole skill folders).
76
+ if (fs.statSync(src).isDirectory()) fs.cpSync(src, dst, { recursive: true })
77
+ else fs.copyFileSync(src, dst)
76
78
  return { outcome: 'seeded', line: `seeded ${step.file} → ${src}` }
77
79
  }
78
80
  // WINDOWS WITHOUT DEVELOPER MODE CANNOT CREATE A SYMLINK (EPERM), and a
@@ -0,0 +1,49 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * Completion checks — the project's own end-of-spec questions, run by
5
+ * `spec-env checks` for `/spec-complete` before it lands (`complete.checks`).
6
+ *
7
+ * ADVISORY, ALWAYS. A check reports and never refuses: a command that exits
8
+ * non-zero is `failed`, the next still runs, and the verb exits 0. A check that
9
+ * stopped a land would be the counting gate this workflow rejects, and what a
10
+ * check prints is a reason to look again, not proof of a fault.
11
+ *
12
+ * Every side effect goes through `io`, so the tests drive it with a fake spawn.
13
+ */
14
+
15
+ const { spawnSync } = require('node:child_process')
16
+
17
+ /**
18
+ * Run each command in `cwd`, in order, capturing its output.
19
+ * Returns `[{ command, status: 'ok' | 'failed', exit, output }]`.
20
+ */
21
+ function runChecks(commands, { cwd, spawn = spawnSync } = {}) {
22
+ const results = []
23
+ for (const command of commands) {
24
+ const res = spawn(command, { cwd, shell: true, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })
25
+ const output = [res.stdout, res.stderr].filter(Boolean).join('').replace(/\s+$/, '')
26
+ if (res.error) {
27
+ results.push({ command, status: 'failed', exit: null, output: res.error.message })
28
+ continue
29
+ }
30
+ const exit = res.status === null ? null : res.status
31
+ results.push({ command, status: exit === 0 ? 'ok' : 'failed', exit, output })
32
+ }
33
+ return results
34
+ }
35
+
36
+ /** The text report: one block per command, its output indented beneath. */
37
+ function formatChecks(spec, results) {
38
+ if (!results.length) return `spec-env checks: ${spec} — no completion checks configured`
39
+ const failed = results.filter((r) => r.status === 'failed').length
40
+ const lines = [`spec-env checks: ${spec} — ${results.length} check(s), ${failed} failed (advisory — never blocks a land)`]
41
+ for (const r of results) {
42
+ const state = r.status === 'ok' ? 'ok' : `failed (${r.exit === null ? 'did not run' : `exit ${r.exit}`})`
43
+ lines.push('', ` ${state} · ${r.command}`)
44
+ for (const l of (r.output || '').split('\n')) if (l) lines.push(` ${l}`)
45
+ }
46
+ return lines.join('\n')
47
+ }
48
+
49
+ module.exports = { runChecks, formatChecks }
package/src/env/config.js CHANGED
@@ -204,6 +204,11 @@ const DEFAULT_CONFIG = Object.freeze({
204
204
  // branch where a spec's tokens mean nothing. Normalised to `{ run, when }`,
205
205
  // `when` null for an always-run entry. Default: none.
206
206
  afterLand: Object.freeze([]),
207
+ // `/spec-complete` runs each `checks` command in the spec's worktree before it
208
+ // lands (`spec-env checks`) and relays the output. Advisory: a failed check is
209
+ // reported and never stops the land. Shell strings, run as written. Default:
210
+ // none.
211
+ complete: Object.freeze({ checks: Object.freeze([]) }),
207
212
  // Host dev servers started on the spec's port block by `spec-env dev up`.
208
213
  // Each: { name, command, portVar, health?, frontPort? }. Default: none.
209
214
  dev: Object.freeze([]),
@@ -310,8 +315,8 @@ const DEFAULT_CONFIG = Object.freeze({
310
315
  // serving-everywhere free of new exposure: `reader` still decides it, so a
311
316
  // remote reader binds every interface exactly as before and a local or
312
317
  // unknown one binds loopback. Serving more never means listening wider.
313
- // `allowNetwork` and `allowRemote` are the two tiers a project permits. They
314
- // exist because the engine CANNOT KNOW where the reader is sitting and kept
318
+ // `allowNetwork` is the switch for the served tiers a project permits. It
319
+ // exists because the engine CANNOT KNOW where the reader is sitting and kept
315
320
  // being asked to guess: detection reported `unknown` on a local session and
316
321
  // produced a page whose buttons cannot POST, reported `remote` and produced a
317
322
  // LAN URL a phone off the network could not reach, and flipped mid-session
@@ -320,14 +325,13 @@ const DEFAULT_CONFIG = Object.freeze({
320
325
  //
321
326
  // So the reader picks instead. `allowNetwork` decides THE BIND — on binds
322
327
  // every interface, off binds loopback — which is the last decision detection
323
- // had. `allowRemote` PERMITS publishing; it never publishes, because each
324
- // publish leaves a page skitterspec cannot delete.
328
+ // had. Its old sibling `allowRemote` permitted publishing, and is retired —
329
+ // see `RETIRED_KEYS`.
325
330
  review: Object.freeze({
326
331
  reader: 'detect',
327
332
  servePort: 'auto',
328
333
  serve: 'always',
329
334
  allowNetwork: true,
330
- allowRemote: false,
331
335
  commitWith: '/commit',
332
336
  required: true,
333
337
  // SUPERSEDED by `project.name`, and still read beneath it so a config that
@@ -403,11 +407,22 @@ function isObject(value) {
403
407
  * them in here would change what this line means from "I ignored a key you wrote"
404
408
  * to "I disagreed with a value you wrote".
405
409
  */
410
+ // Keys this engine once read and now ignores. A config that still sets one is
411
+ // a repo that has not tidied up, not a typo, so it is never reported as
412
+ // unknown: accusing a healthy config is the wrong branch of a cannot-tell
413
+ // (`.claude/rules/negative-checks.md` rule 4).
414
+ //
415
+ // `review.allowRemote` permitted publishing the review as a claude.ai page.
416
+ // That tier is gone, and `remote` is the tailnet on `allowNetwork`'s switch
417
+ // (feat-tailnet-remote-tier).
418
+ const RETIRED_KEYS = new Set(['review.allowRemote'])
419
+
406
420
  function collectUnknownKeys(parsed, known = DEFAULT_CONFIG, prefix = '') {
407
421
  if (!isObject(parsed)) return []
408
422
  const out = []
409
423
  for (const key of Object.keys(parsed)) {
410
424
  const dotted = prefix ? `${prefix}.${key}` : key
425
+ if (RETIRED_KEYS.has(dotted)) continue
411
426
  if (!Object.prototype.hasOwnProperty.call(known, key)) {
412
427
  out.push(dotted)
413
428
  continue
@@ -430,6 +445,7 @@ function defaults() {
430
445
  setup: [],
431
446
  setupTriggers: [],
432
447
  afterLand: [],
448
+ complete: { checks: [] },
433
449
  dev: [],
434
450
  proxy: { ...DEFAULT_CONFIG.proxy },
435
451
  registry: DEFAULT_CONFIG.registry,
@@ -697,6 +713,11 @@ function mergeConfig(base, parsed) {
697
713
  base.afterLand = normalizeAfterLand(parsed.afterLand, base.setupTriggers)
698
714
  }
699
715
 
716
+ // Same rule as `setup`: a stray entry is dropped, never thrown on.
717
+ if (isObject(parsed.complete) && Array.isArray(parsed.complete.checks)) {
718
+ base.complete.checks = parsed.complete.checks.filter((c) => typeof c === 'string' && c.trim())
719
+ }
720
+
700
721
  if (Array.isArray(parsed.dev)) {
701
722
  base.dev = normalizeDev(parsed.dev)
702
723
  }
@@ -824,9 +845,8 @@ function mergeConfig(base, parsed) {
824
845
  // someone WROTE, never something a typo achieved on their behalf.
825
846
  assign(base.review, parsed.review, 'required', 'boolean')
826
847
  // Same shape as the two above: a non-boolean leaves the default standing, so
827
- // a typo cannot quietly widen a bind or permit a publish.
848
+ // a typo cannot quietly widen a bind.
828
849
  assign(base.review, parsed.review, 'allowNetwork', 'boolean')
829
- assign(base.review, parsed.review, 'allowRemote', 'boolean')
830
850
  // An entry that is neither shape is DROPPED rather than refused, like every
831
851
  // other value here — but unlike the scalars above there is no default for it
832
852
  // to fall through to, so a dropped entry is a reviewer that silently never
package/src/env/hooks.js CHANGED
@@ -88,8 +88,11 @@ function isObject(value) {
88
88
  return value !== null && typeof value === 'object' && !Array.isArray(value)
89
89
  }
90
90
 
91
- function settingsPath(dir) {
92
- return path.join(dir, '.claude', 'settings.json')
91
+ // A local install registers its hooks in the per-machine file, so a repo
92
+ // shared with people who do not use skitterspec gains nothing in its committed
93
+ // settings (`init --local`).
94
+ function settingsPath(dir, { local = false } = {}) {
95
+ return path.join(dir, '.claude', local ? 'settings.local.json' : 'settings.json')
93
96
  }
94
97
 
95
98
  function writeSettings(file, settings) {
@@ -181,8 +184,8 @@ function ensureOneHook(parsed, hook) {
181
184
  * already there did change the file, and reporting `present` for it would tell
182
185
  * an operator nothing happened when something did.
183
186
  */
184
- function ensureHooks(dir) {
185
- const file = settingsPath(dir)
187
+ function ensureHooks(dir, { local = false } = {}) {
188
+ const file = settingsPath(dir, { local })
186
189
 
187
190
  let raw
188
191
  try {
@@ -215,6 +218,51 @@ function ensureHooks(dir) {
215
218
  return { changed, reason: 'present' }
216
219
  }
217
220
 
221
+ /**
222
+ * Take OUR hooks out of the committed settings, for `init --local` converting a
223
+ * team install. Per hook OBJECT, never per matcher group: a group can hold ours
224
+ * beside the project's own (a secrets guard, a typecheck), and those stay. A
225
+ * group left with no hooks is dropped, then an empty `PreToolUse`, then an empty
226
+ * `hooks`. Every other key — and every other event — is untouched.
227
+ *
228
+ * Returns `{ removed, emptied, reason }`. `emptied` is true when nothing is left
229
+ * but `{}`: the caller deletes the file then, since a committed `{}` is noise.
230
+ * A missing file is `absent`; an unparseable one is `malformed` and untouched.
231
+ */
232
+ function removeHooks(dir) {
233
+ const file = settingsPath(dir)
234
+ let parsed
235
+ try {
236
+ parsed = JSON.parse(fs.readFileSync(file, 'utf-8'))
237
+ } catch (error) {
238
+ return { removed: 0, emptied: false, reason: error.code === 'ENOENT' ? 'absent' : 'malformed' }
239
+ }
240
+ if (!isObject(parsed)) return { removed: 0, emptied: false, reason: 'malformed' }
241
+ const pre = isObject(parsed.hooks) && Array.isArray(parsed.hooks.PreToolUse) ? parsed.hooks.PreToolUse : null
242
+ if (!pre) return { removed: 0, emptied: false, reason: 'none' }
243
+
244
+ let removed = 0
245
+ const ours = (h) => isObject(h) && typeof h.command === 'string' && HOOKS.some((k) => k.re.test(h.command))
246
+ const kept = []
247
+ for (const group of pre) {
248
+ if (!isObject(group) || !Array.isArray(group.hooks)) {
249
+ kept.push(group)
250
+ continue
251
+ }
252
+ const rest = group.hooks.filter((h) => !ours(h))
253
+ removed += group.hooks.length - rest.length
254
+ if (rest.length) kept.push(rest.length === group.hooks.length ? group : { ...group, hooks: rest })
255
+ }
256
+ if (!removed) return { removed: 0, emptied: false, reason: 'none' }
257
+
258
+ if (kept.length) parsed.hooks.PreToolUse = kept
259
+ else delete parsed.hooks.PreToolUse
260
+ if (!Object.keys(parsed.hooks).length) delete parsed.hooks
261
+ const emptied = !Object.keys(parsed).length
262
+ if (!emptied) writeSettings(file, parsed)
263
+ return { removed, emptied, reason: 'removed' }
264
+ }
265
+
218
266
  // The name this shipped under when there was one hook. Kept as an alias rather
219
267
  // than renamed away, because it is what an installed `init.js` from an older
220
268
  // version calls — and a rename that breaks an upgrade path is not a rename, it
@@ -223,6 +271,7 @@ const ensureReviewGateHook = ensureHooks
223
271
 
224
272
  module.exports = {
225
273
  ensureHooks,
274
+ removeHooks,
226
275
  ensureReviewGateHook,
227
276
  alreadyRegistered,
228
277
  registeredHooks,
package/src/env/live.js CHANGED
@@ -80,6 +80,50 @@ function clearReceipt(rootDir, config) {
80
80
  }
81
81
  }
82
82
 
83
+ // --- the last spec this checkout released ---------------------------------
84
+
85
+ /**
86
+ * Which spec `live release` last handed back to its worktree
87
+ * (bug-live-release-forgets-spec). Releasing leaves the session standing in the
88
+ * primary checkout, where — with several worktrees — a bare resolve had no way
89
+ * to say which spec was just there, so `/spec-next` refused a spec in flight.
90
+ *
91
+ * A HINT, NEVER AN AUTHORITY. It answers only while the spec it names is still
92
+ * provisioned (the caller checks against `git worktree list`), and anything
93
+ * wrong with the file — missing, malformed, no `spec` — reads as null, never an
94
+ * error: a stale record is cannot-tell and falls through to the rungs below it.
95
+ *
96
+ * WHAT WOULD FOOL THIS: a record naming a spec whose worktree was torn down and
97
+ * then re-provisioned would answer for it again. That spec was released from
98
+ * this checkout and is in flight again, so the answer is still a real one.
99
+ */
100
+ function lastLivePath(rootDir, config) {
101
+ return path.resolve(rootDir, path.dirname(config.registry), 'last-live.json')
102
+ }
103
+
104
+ function readLastLive(rootDir, config) {
105
+ try {
106
+ const record = JSON.parse(fs.readFileSync(lastLivePath(rootDir, config), 'utf-8'))
107
+ return record && typeof record.spec === 'string' && record.spec ? record : null
108
+ } catch {
109
+ return null
110
+ }
111
+ }
112
+
113
+ function writeLastLive(rootDir, config, fields) {
114
+ const file = lastLivePath(rootDir, config)
115
+ fs.mkdirSync(path.dirname(file), { recursive: true })
116
+ fs.writeFileSync(file, JSON.stringify(fields, null, 2) + '\n')
117
+ }
118
+
119
+ function clearLastLive(rootDir, config) {
120
+ try {
121
+ fs.unlinkSync(lastLivePath(rootDir, config))
122
+ } catch (error) {
123
+ if (error.code !== 'ENOENT') throw error
124
+ }
125
+ }
126
+
83
127
  // A one-line human summary of a receipt (or the "free" state when null). Pure.
84
128
  function summarizeReceipt(receipt) {
85
129
  if (!receipt) return 'free — no spec is live'
@@ -611,6 +655,10 @@ module.exports = {
611
655
  readReceipt,
612
656
  writeReceipt,
613
657
  clearReceipt,
658
+ lastLivePath,
659
+ readLastLive,
660
+ writeLastLive,
661
+ clearLastLive,
614
662
  summarizeReceipt,
615
663
  globToRegExp,
616
664
  migrationsHit,
@@ -255,7 +255,7 @@ function resolveStack(spec, config, { docs = false, composeFilePresent } = {}) {
255
255
  * filesystem fact arrives in `opts`.
256
256
  */
257
257
  function worktreeSteps(spec, offset, config, opts = {}) {
258
- const { docs = false, wantsDocker = false, composeFilePresent: compose } = opts
258
+ const { docs = false, wantsDocker = false, composeFilePresent: compose, localSeeds = [] } = opts
259
259
  const seed = config.seedFiles || { mode: 'symlink', files: [] }
260
260
  const mode = seed.mode === 'copy' ? 'copy' : 'symlink'
261
261
  const tokens = {
@@ -268,7 +268,15 @@ function worktreeSteps(spec, offset, config, opts = {}) {
268
268
  portOffset: offset === null || offset === undefined ? '' : String(offset),
269
269
  }
270
270
  const envFile = (config.docker && config.docker.envFile) || '.env'
271
- const steps = (seed.files || []).map((file) => ({ kind: 'seed', file, mode }))
271
+ // A local install (`init --local`) keeps skitterspec's own files out of git,
272
+ // so a fresh worktree has none of them; they are seeded first, implicitly from
273
+ // the manifest's scope — nothing in the committed config names them.
274
+ const seeded = new Set(seed.files || [])
275
+ const steps = [...localSeeds.filter((f) => !seeded.has(f)), ...(seed.files || [])].map((file) => ({
276
+ kind: 'seed',
277
+ file,
278
+ mode,
279
+ }))
272
280
  if (wantsDocker) {
273
281
  steps.push({ kind: 'envFile', file: envFile, projectName: spec.projectName, offset })
274
282
  }
@@ -0,0 +1,234 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * Going back into a spec that is already in flight (feat-spec-resume) — the
5
+ * engine behind `skitterspec spec-env resume <name|#N>`.
6
+ *
7
+ * A spec that waits on something outside the repo — a deploy, another
8
+ * project's release, a soak period — is left and come back to. Coming back is
9
+ * not starting: nothing here moves a bucket, assigns anyone or touches a
10
+ * tracker. It answers three things, and the skill acts on them:
11
+ *
12
+ * - which spec the argument means (a folder name, or a tracker ref read off
13
+ * each copy's frontmatter through `branch.identifierField`),
14
+ * - whether it can be resumed (only `in-progress` — read from the spec's OWN
15
+ * copy, since the base branch goes on reading `backlog` for the life of a
16
+ * spec), and how to rebuild its worktree when this machine has none,
17
+ * - what it is blocked on (`> **Blocked on:**`, on the overview or a phase).
18
+ *
19
+ * Pure: callers hand in the copies they could read and whether the worktree
20
+ * and branches exist. `cli.js` does the reading.
21
+ */
22
+
23
+ const { phaseProgress } = require('./phases.js')
24
+ const { shellPath } = require('./project.js')
25
+
26
+ // Same grammar as `specstate.js`'s header(): a blockquote `**Field:**` line.
27
+ function headerValue(text, field) {
28
+ const m = new RegExp(`^>\\s*\\*\\*${field}:\\*\\*[ \\t]*(.*)$`, 'm').exec(String(text || ''))
29
+ if (!m) return null
30
+ const value = m[1].trim()
31
+ return value && value !== '—' && value !== '-' ? value : null
32
+ }
33
+
34
+ // A real calendar date, or null. `2026-02-31` is not one, and a malformed
35
+ // `until` must stay text rather than become a date someone acts on.
36
+ function calendarDate(s) {
37
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(s)) return null
38
+ const d = new Date(`${s}T00:00:00Z`)
39
+ return !Number.isNaN(d.getTime()) && d.toISOString().slice(0, 10) === s ? s : null
40
+ }
41
+
42
+ /**
43
+ * One `Blocked on:` value → `{ text, until }`. A trailing `(until YYYY-MM-DD)`
44
+ * is the only part read as data; anything else — including an `until` that is
45
+ * not a real date — stays in `text`, so a typo is shown rather than obeyed.
46
+ */
47
+ function parseBlockedOn(value) {
48
+ if (!value) return null
49
+ const m = /^(.*?)\s*\(until\s+([^)]*)\)\s*$/.exec(value)
50
+ const until = m ? calendarDate(m[2].trim()) : null
51
+ return until ? { text: m[1].trim() || value, until } : { text: value, until: null }
52
+ }
53
+
54
+ /**
55
+ * Every blocker a spec records: the overview's (`where: 'spec'`), then each
56
+ * phase file's (`where: <phase number>`), in phase order.
57
+ *
58
+ * @param {{ overview: string, phases?: Array<{ n: number, text: string }> }} copy
59
+ * @returns {Array<{ where: 'spec'|number, text: string, until: string|null }>}
60
+ */
61
+ function blockers(copy) {
62
+ const out = []
63
+ const spec = parseBlockedOn(headerValue(copy && copy.overview, 'Blocked on'))
64
+ if (spec) out.push({ where: 'spec', ...spec })
65
+ const phases = ((copy && copy.phases) || []).filter((p) => p && typeof p.text === 'string')
66
+ for (const p of [...phases].sort((a, b) => a.n - b.n)) {
67
+ const b = parseBlockedOn(headerValue(p.text, 'Blocked on'))
68
+ if (b) out.push({ where: p.n, ...b })
69
+ }
70
+ return out
71
+ }
72
+
73
+ /**
74
+ * The blocker that stands in front of the NEXT build, or null.
75
+ *
76
+ * The next build is the first phase not `✅` — the one `/spec-next` would
77
+ * pick. A spec-level blocker holds every phase; a phase's own holds only that
78
+ * phase. A blocker on a LATER phase is not this build's business and says
79
+ * nothing: a spec planned to wait at phase 4 builds phases 1–3 unhindered.
80
+ * Nothing left to build means nothing to block.
81
+ */
82
+ function blockingNext(copy) {
83
+ const all = blockers(copy)
84
+ const phases = ((copy && copy.phases) || []).filter((p) => p && typeof p.text === 'string')
85
+ const heading = (t) => (t.split('\n').find((l) => /^#\s/.test(l)) || '').trim()
86
+ const next = [...phases].sort((a, b) => a.n - b.n).find((p) => !heading(p.text).endsWith('✅'))
87
+ if (!next) return null
88
+ return all.find((b) => b.where === 'spec') || all.find((b) => b.where === next.n) || null
89
+ }
90
+
91
+ // A frontmatter field off an overview's text — the in-memory twin of
92
+ // resolve.js `readFrontmatterField`, for copies read off a branch.
93
+ function frontmatterField(text, field) {
94
+ if (!field) return null
95
+ const fm = /^---\n([\s\S]*?)\n---/.exec(String(text || ''))
96
+ if (!fm) return null
97
+ const m = new RegExp(`^${field}:\\s*(.+)$`, 'm').exec(fm[1])
98
+ return m ? m[1].trim().replace(/^["']|["']$/g, '') || null : null
99
+ }
100
+
101
+ // `#241`, `241` and `"#241"` are one ticket; `ABC-88` only ever matches itself.
102
+ function sameRef(a, b) {
103
+ const norm = (s) => String(s).trim().replace(/^#/, '').toLowerCase()
104
+ return Boolean(a) && Boolean(b) && norm(a) === norm(b)
105
+ }
106
+
107
+ // Which copy speaks for a spec: its own worktree, then a branch (local before
108
+ // remote-tracking), then the checkout the command was run from.
109
+ const RANK = { worktree: 0, branch: 1, here: 2 }
110
+ function rank(c) {
111
+ return RANK[c.origin] * 2 + (c.origin === 'branch' && !c.local ? 1 : 0)
112
+ }
113
+
114
+ /**
115
+ * The copy an argument means, or a refusal.
116
+ *
117
+ * A FOLDER NAME WINS OVER A REF. Folder names carry a kind prefix
118
+ * (`feat-`, `bug-`…) and tracker refs do not, so the two cannot collide in
119
+ * practice — but if one ever did, the name someone typed for a folder is the
120
+ * more specific claim.
121
+ *
122
+ * A REF THAT MATCHES NOTHING NAMES NOTHING. It never falls back to the nearest
123
+ * spec or the only one provisioned: resuming the wrong spec writes into a
124
+ * branch nobody asked about. Without `branch.identifierField` a ref cannot be
125
+ * read at all, and the refusal says that rather than "not found".
126
+ *
127
+ * @param {string} arg
128
+ * @param {Array<{ folder, bucket, origin: 'worktree'|'branch'|'here', local?, ref?, overview, phases }>} copies
129
+ * @param {string} [identifierField]
130
+ */
131
+ function findTarget(arg, copies, identifierField) {
132
+ const wanted = String(arg || '').trim()
133
+ if (!wanted) return { refused: 'no spec given — /spec-resume <name> or /spec-resume #<ticket>' }
134
+ const best = (list) => [...list].sort((a, b) => rank(a) - rank(b))[0]
135
+ const byName = copies.filter((c) => c.folder === wanted)
136
+ if (byName.length) return { target: best(byName), by: 'name' }
137
+
138
+ if (!identifierField) {
139
+ return {
140
+ refused:
141
+ `no spec named ${wanted}` +
142
+ (/^#?[\w-]*\d+$/.test(wanted)
143
+ ? ', and a ticket ref cannot be looked up: branch.identifierField is not set in env.config.json'
144
+ : ''),
145
+ }
146
+ }
147
+ const byRef = copies.filter((c) => sameRef(frontmatterField(c.overview, identifierField), wanted))
148
+ const folders = [...new Set(byRef.map((c) => c.folder))]
149
+ if (!folders.length) return { refused: `no spec named or linked to ${wanted}` }
150
+ if (folders.length > 1) {
151
+ return { refused: `${wanted} is linked from more than one spec (${folders.join(', ')}) — name the one you mean` }
152
+ }
153
+ return { target: best(byRef), by: 'ref' }
154
+ }
155
+
156
+ /**
157
+ * The full answer for a found copy.
158
+ *
159
+ * @param {object} target the copy `findTarget` chose
160
+ * @param {object} env what the caller could see:
161
+ * `{ branch, worktreePath, worktreeExists, localBranch, remoteBranch, remote, identifierField }`
162
+ */
163
+ function planResume(target, env) {
164
+ const progress = phaseProgress((target.phases || []).map((p) => ({ content: p.text })))
165
+ const base = {
166
+ spec: target.folder,
167
+ bucket: target.bucket,
168
+ source: target.origin,
169
+ branch: env.branch,
170
+ identifier: frontmatterField(target.overview, env.identifierField),
171
+ progress: { done: progress.done, total: progress.total, current: progress.current },
172
+ blockers: blockers(target),
173
+ blocking: blockingNext(target),
174
+ worktree: { path: env.worktreePath, present: Boolean(env.worktreeExists) },
175
+ }
176
+ if (target.bucket !== 'in-progress') {
177
+ const how =
178
+ target.bucket === 'backlog'
179
+ ? ' — it was never started; /spec-start puts it in flight'
180
+ : ' — there is nothing left to resume'
181
+ return { ok: false, ...base, refused: `${target.folder} is in ${target.bucket}${how}` }
182
+ }
183
+ if (env.worktreeExists) return { ok: true, ...base, commands: [], then: [] }
184
+
185
+ // NEVER `-b` WITHOUT A BRANCH TO ATTACH. A fresh fork from base would hand
186
+ // back an empty tree with the spec's work out of reach — that is a start,
187
+ // and starting is /spec-start's. So: the local branch, else the remote's,
188
+ // else a refusal.
189
+ let commands
190
+ if (env.localBranch) {
191
+ commands = [`git worktree add ${shellPath(env.worktreePath)} ${env.branch}`]
192
+ } else if (env.remoteBranch) {
193
+ commands = [
194
+ `git fetch ${env.remote} ${env.branch}`,
195
+ `git worktree add ${shellPath(env.worktreePath)} -b ${env.branch} --track ${env.remote}/${env.branch}`,
196
+ ]
197
+ } else {
198
+ return {
199
+ ok: false,
200
+ ...base,
201
+ refused: `${target.folder} has no worktree and no ${env.branch} branch here or on ${env.remote} — nothing to resume from`,
202
+ }
203
+ }
204
+ return { ok: true, ...base, commands, then: [`skitterspec spec-env bootstrap ${target.folder}`] }
205
+ }
206
+
207
+ function blockerLine(b) {
208
+ const where = b.where === 'spec' ? 'spec' : `phase ${b.where}`
209
+ return `${where} — ${b.text}${b.until ? ` (until ${b.until})` : ''}`
210
+ }
211
+
212
+ /** The text report — what `spec-env resume` prints without `--json`. */
213
+ function resumeLines(r) {
214
+ if (r.refusedOnly) return [`spec-env resume: refused — ${r.refused}`]
215
+ const lines = [`spec-env resume: ${r.spec} (${r.bucket}, on ${r.branch})`]
216
+ if (r.identifier) lines.push(` ticket: ${r.identifier}`)
217
+ const { done, total, current } = r.progress
218
+ lines.push(
219
+ ` phases: ${total ? `${done} of ${total} done${current ? `, phase ${current} in progress` : ''}` : 'no phase files'}`,
220
+ )
221
+ for (const b of r.blockers) lines.push(` blocked: ${blockerLine(b)}${r.blocking && b.where === r.blocking.where ? ' ← holds the next build' : ''}`)
222
+ if (!r.ok) {
223
+ lines.push(` refused: ${r.refused}`)
224
+ return lines
225
+ }
226
+ lines.push(` worktree: ${r.worktree.path}${r.worktree.present ? '' : ' (missing — provision below)'}`)
227
+ if (r.commands.length) {
228
+ lines.push('', ' to provision, run:', ...r.commands.map((c) => ` ${c}`))
229
+ lines.push('', ' then, run:', ...r.then.map((c) => ` ${c}`))
230
+ }
231
+ return lines
232
+ }
233
+
234
+ module.exports = { blockers, blockingNext, parseBlockedOn, findTarget, planResume, resumeLines, blockerLine, frontmatterField, sameRef }