@skitterbyte/skitterspec-linear 19.6.0 → 19.8.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.
package/src/env/review.js CHANGED
@@ -269,7 +269,7 @@ function resolveReader(config, env = {}) {
269
269
  * `buttons` is the button set the page renders — see `BUTTON_SETS`. It is the
270
270
  * caller's declaration about the work, not a reading of the gate.
271
271
  */
272
- function collectReview({ spec, git, mode = 'working', ref, base = null, now, notes = null, gate = null, fellBack = false, buttons = null, only = null, treePath = null, live = null, tiers = null }) {
272
+ function collectReview({ spec, git, mode = 'working', ref, base = null, now, notes = null, gate = null, fellBack = false, buttons = null, only = null, treePath = null, live = null, tiers = null, project = null }) {
273
273
  // WHICH TREE THE SPEC'S OWN DOCUMENTS ARE READ FROM. Every render but one
274
274
  // reads the spec's worktree, and for those the two are the same path — so
275
275
  // `treePath` left null keeps the existing behaviour exactly. The `docs` mode
@@ -360,6 +360,9 @@ function collectReview({ spec, git, mode = 'working', ref, base = null, now, not
360
360
  return {
361
361
  spec: spec.folder,
362
362
  title: spec.folder,
363
+ // The project's name, for the tab and the line above the heading. Absent
364
+ // when the caller could not tell, and the page then renders as before.
365
+ ...(project ? { project } : {}),
363
366
  branch: spec.branch,
364
367
  // The tree the diff was read from. Identical to the worktree for every
365
368
  // mode but `docs`, where there is no worktree and this is the checkout the
@@ -603,6 +606,10 @@ const ACTIONS = ['live-on', 'allow-network', 'allow-remote']
603
606
  */
604
607
  function tierAction(tier) {
605
608
  if (!tier || !tier.off) return null
609
+ // A loopback bind is off for a reason no press can fix: widening it restarts
610
+ // the server, which mints a new token and kills every link already open. Its
611
+ // command is named on the line; the page offers nothing.
612
+ if (tier.bound === 'loopback') return null
606
613
  if (tier.tier === 'network') return 'allow-network'
607
614
  if (tier.tier === 'remote') return 'allow-remote'
608
615
  return null
@@ -742,6 +749,11 @@ function reviewTierStack({ served, fileUrl, publishedUrl, config }) {
742
749
  return isTailnetAddress(host) ? { url: u, label: 'tailnet' } : { url: u }
743
750
  }),
744
751
  })
752
+ } else if (served && served.loopback && served.widen) {
753
+ // Permitted, and the machine has addresses — but the running server is
754
+ // bound to loopback. "No network address" here sent readers looking for a
755
+ // network problem; the fix is one command, so the line names it.
756
+ tiers.push({ tier: 'network', off: true, bound: 'loopback', enable: served.widen })
745
757
  } else {
746
758
  // Permitted, but there is no address to offer — a machine with no network,
747
759
  // or a server that could not take one. Not a problem to report as an error.
@@ -2309,16 +2321,22 @@ function fragmentTemplate(template = null) {
2309
2321
  */
2310
2322
  function renderReviewFragment(data, { template = null, reviewHtml = '' } = {}) {
2311
2323
  const values = {
2312
- [TITLE_PLACEHOLDER]: escapeHtml(data.title),
2324
+ [TITLE_PLACEHOLDER]: escapeHtml(tabTitle(data)),
2313
2325
  [REVIEW_PLACEHOLDER]: reviewHtml,
2314
2326
  [DATA_PLACEHOLDER]: escapeIsland(JSON.stringify(data)),
2315
2327
  }
2316
2328
  return fragmentTemplate(template).replace(PLACEHOLDER_RE, (m) => values[m])
2317
2329
  }
2318
2330
 
2331
+ // The tab name: `<project> · <spec>`, so pages from two projects open side by
2332
+ // side can be told apart from the tab alone — all a phone shows.
2333
+ function tabTitle(data) {
2334
+ return data.project ? `${data.project} · ${data.title}` : data.title
2335
+ }
2336
+
2319
2337
  function renderReviewPage(data, { template = null, reviewHtml = '' } = {}) {
2320
2338
  const values = {
2321
- [TITLE_PLACEHOLDER]: escapeHtml(data.title),
2339
+ [TITLE_PLACEHOLDER]: escapeHtml(tabTitle(data)),
2322
2340
  [REVIEW_PLACEHOLDER]: reviewHtml,
2323
2341
  [DATA_PLACEHOLDER]: escapeIsland(JSON.stringify(data)),
2324
2342
  }
package/src/env/serve.js CHANGED
@@ -35,10 +35,14 @@ const {
35
35
  allSpecs,
36
36
  resolveSpec,
37
37
  resolveBaseBranch,
38
+ isEpic,
38
39
  } = require('./resolve.js')
40
+ const { epicTree, worktreeOverview, epicsInFlight, memberReaders, epicAnswer } = require('./epicread.js')
41
+ const { specBranchDocs } = require('./specbranches.js')
42
+ const { renderEpicPage } = require('./epicpage.js')
39
43
  const { readRegistry } = require('./registry.js')
40
44
  const { loadEnvConfig } = require('./config.js')
41
- const { primaryAnchor, attachProject, repoRootOf, prefixOf, fromRepoPath, toRepoPath } = require('./project.js')
45
+ const { primaryAnchor, attachProject, projectName, repoRootOf, prefixOf, fromRepoPath, toRepoPath } = require('./project.js')
42
46
  const { specDocsIn, classifyDirtyTree, dirtyPaths } = require('./classify.js')
43
47
  const { liveStateFor } = require('./live.js')
44
48
  const { preferRemoteBase } = require('./host.js')
@@ -124,8 +128,19 @@ function escapeHtml(s) {
124
128
  * palette on bare `:root`, redefined under `prefers-color-scheme`) so the two
125
129
  * do not disagree when opened side by side.
126
130
  */
127
- function renderIndex(entries, { token = null } = {}) {
131
+ function renderIndex(entries, { token = null, epics = [], project = null } = {}) {
128
132
  const prefix = token ? `/${token}` : ''
133
+ // The heading and tab name the project, so two servers' indexes open side by
134
+ // side can be told apart. No name — cannot tell — reads as it always did.
135
+ const heading = project ? `${escapeHtml(project)} · spec diffs` : 'spec diffs'
136
+ // Epics with a member in flight, each a doorway to its epic page. Listed
137
+ // above the diffs because an epic page is where a reader running several
138
+ // members starts; absent entirely on a repo with no epic in flight.
139
+ const epicList = epics.length
140
+ ? `<h2>epics</h2>\n<ul>\n${epics
141
+ .map((e) => `<li><a href="${prefix}/${encodeURIComponent(e)}">${escapeHtml(e)}</a><span class="b">what to run next, per member</span></li>`)
142
+ .join('\n')}\n</ul>\n<h2>diffs</h2>`
143
+ : ''
129
144
  const rows = entries
130
145
  .map((e) => {
131
146
  const t = e.totals || { files: 0, additions: 0, deletions: 0 }
@@ -150,7 +165,7 @@ function renderIndex(entries, { token = null } = {}) {
150
165
  <head>
151
166
  <meta charset="utf-8">
152
167
  <meta name="viewport" content="width=device-width, initial-scale=1">
153
- <title>spec diffs</title>
168
+ <title>${heading}</title>
154
169
  <style>
155
170
  :root { --bg:#fff; --fg:#1a1a1a; --dim:#6b6b6b; --line:#e3e3e3; --add:#0a7b34; --del:#b3261e; --link:#0b5fbd }
156
171
  @media (prefers-color-scheme: dark) {
@@ -161,6 +176,7 @@ body { margin:0; padding:2rem 1.25rem; background:var(--bg); color:var(--fg);
161
176
  font:15px/1.5 ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,sans-serif }
162
177
  main { max-width:52rem; margin:0 auto }
163
178
  h1 { font-size:1.1rem; margin:0 0 1.25rem; font-weight:600 }
179
+ h2 { font-size:.9rem; margin:1.25rem 0 .25rem; font-weight:600; color:var(--dim) }
164
180
  ul { list-style:none; margin:0; padding:0 }
165
181
  li { display:flex; flex-wrap:wrap; gap:.75rem; align-items:baseline;
166
182
  padding:.7rem 0; border-top:1px solid var(--line) }
@@ -176,7 +192,8 @@ code { font-family:ui-monospace,SFMono-Regular,Menlo,monospace }
176
192
  </head>
177
193
  <body>
178
194
  <main>
179
- <h1>spec diffs</h1>
195
+ <h1>${heading}</h1>
196
+ ${epicList}
180
197
  ${body}
181
198
  </main>
182
199
  </body>
@@ -548,6 +565,7 @@ function renderSpecPage(dir, config, spec, { branch = false } = {}) {
548
565
  notes,
549
566
  gate: gateRead.corrupt ? null : gateRead.gate,
550
567
  buttons,
568
+ project: projectName(config),
551
569
  only: view.owned,
552
570
  treePath: view.tree,
553
571
  })
@@ -625,6 +643,7 @@ function renderSpecPage(dir, config, spec, { branch = false } = {}) {
625
643
  buttons,
626
644
  live,
627
645
  tiers,
646
+ project: projectName(config),
628
647
  })
629
648
 
630
649
  if (!branch && data.totals.files === 0) {
@@ -647,6 +666,7 @@ function renderSpecPage(dir, config, spec, { branch = false } = {}) {
647
666
  buttons,
648
667
  live,
649
668
  tiers,
669
+ project: projectName(config),
650
670
  fellBack: true,
651
671
  })
652
672
  if (wider.totals.files > 0) {
@@ -792,7 +812,7 @@ function readBody(req, limit = MAX_PASS_BYTES) {
792
812
  })
793
813
  }
794
814
 
795
- function createReviewServer({ resolveEntries, render, receive = null, passState = null, token = null }) {
815
+ function createReviewServer({ resolveEntries, resolveEpics = () => [], render, receive = null, passState = null, token = null, project = null }) {
796
816
  return http.createServer((req, res) => {
797
817
  const send = (code, body, type = 'text/html; charset=utf-8') => {
798
818
  res.writeHead(code, { 'content-type': type, 'cache-control': 'no-store' })
@@ -846,7 +866,7 @@ function createReviewServer({ resolveEntries, render, receive = null, passState
846
866
  }
847
867
 
848
868
  try {
849
- if (route.kind === 'index') return send(200, renderIndex(resolveEntries(), { token }))
869
+ if (route.kind === 'index') return send(200, renderIndex(resolveEntries(), { token, epics: resolveEpics(), project }))
850
870
  const out = render(route.spec, { branch: route.branch })
851
871
  if (!out) return send(404, 'not found', 'text/plain; charset=utf-8')
852
872
  if (out.error) return send(409, out.error, 'text/plain; charset=utf-8')
@@ -995,9 +1015,55 @@ function serverHooks(dir, config) {
995
1015
  }
996
1016
  })
997
1017
 
1018
+ // Every provisioned spec's own copy — what an epic's members are read off.
1019
+ const worktrees = () =>
1020
+ allSpecs(dir, config, liveWorktreePaths(trimmedGit), specless())
1021
+ .filter((s) => !s.specless && s.worktreePath && s.worktreePath !== dir && fs.existsSync(s.worktreePath))
1022
+ .map((s) => worktreeOverview(s.projectPath || s.worktreePath, s.folder))
1023
+ .filter(Boolean)
1024
+
1025
+ // The epic page, read per request like every other page. null — a 404 — when
1026
+ // no such epic exists and no spec names it; an unreadable base branch is a
1027
+ // 409 saying so, never an empty plan.
1028
+ const epicPage = (folder) => {
1029
+ let base
1030
+ try {
1031
+ base = resolveBaseBranch(config, trimmedGit)
1032
+ } catch (err) {
1033
+ return { error: `cannot tell — ${err.message}` }
1034
+ }
1035
+ const tree = epicTree(trimmedGit, base)
1036
+ if (!tree) return { error: `cannot tell — the base branch ${base} could not be read` }
1037
+ const inputs = { dir, config, base, ...tree, worktrees: worktrees(), branches: specBranchDocs(trimmedGit, config, base) }
1038
+ const answer = epicAnswer(folder, inputs, memberReaders({ ...inputs, git: trimmedGitReader, linkFor: (s) => encodeURIComponent(s) }))
1039
+ if (!answer.found && !answer.members.length) return null
1040
+ return { html: renderEpicPage(answer, { project: projectName(config) }) }
1041
+ }
1042
+
998
1043
  return {
999
1044
  resolveEntries,
1000
- render: (folder, opts) => renderSpecPage(dir, config, resolveOne(folder), opts),
1045
+ // What the index calls this project. Read once: the server is per project.
1046
+ project: projectName(config),
1047
+ resolveEpics: () => {
1048
+ try {
1049
+ return epicsInFlight(worktrees())
1050
+ } catch {
1051
+ // The index is a doorway; an unreadable worktree costs a link, never the page.
1052
+ return []
1053
+ }
1054
+ },
1055
+ render: (folder, opts) => {
1056
+ // AN EPIC BEING WRITTEN KEEPS ITS AUTHORING PAGE. `/spec` renders a new
1057
+ // epic's own documents at this same address, with verdict buttons, and
1058
+ // that page must still be the one a reader gets while the documents are
1059
+ // uncommitted. Every other epic address is the epic page.
1060
+ if (isEpic(folder)) {
1061
+ const one = resolveOne(folder)
1062
+ const view = one ? viewFor(dir, config, one, trimmedGit) : null
1063
+ if (!view || view.kind !== 'docs') return epicPage(folder)
1064
+ }
1065
+ return renderSpecPage(dir, config, resolveOne(folder), opts)
1066
+ },
1001
1067
  receive: (folder, blob) => receivePass(dir, config, resolveOne(folder), blob),
1002
1068
  // A spec this daemon cannot resolve is not a pass that was claimed — it is
1003
1069
  // a lookup that could not see, so it says nothing rather than reporting the
@@ -0,0 +1,120 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * Specs that live only on their own branch (feat-tracker-spec-branches).
5
+ *
6
+ * Under `land.specDocs: "branch"` — the default once a ticketing provider is
7
+ * configured — a spec document never lands on the base branch until its work
8
+ * does, so `ls specs/backlog/` on base cannot see it. The checks that read the
9
+ * backlog (`gating check`, `epic status`, `docs-freshness check`) ask this
10
+ * instead, so the specs that mode produces are not invisible to them.
11
+ *
12
+ * What a branch is FOR is read off what it changed: the spec folders its range
13
+ * (`<base>...<ref>`) touches. Every spec branch forks from base and so carries
14
+ * every base spec too; only the ones it changed are its own.
15
+ *
16
+ * Read with git and never fetched. An advisory check that can hang on the
17
+ * network is worse than one that is a fetch behind, so remote-tracking refs are
18
+ * read as they stand and a caller labels them "as of last fetch".
19
+ *
20
+ * WHAT WOULD FOOL THIS: a remote that was never fetched (its specs are simply
21
+ * absent — an extra miss, never an accusation), and a spec branch whose name
22
+ * does not match `branch.pattern` (renamed by hand; it is not found). Every
23
+ * unreadable git call reads as nothing found.
24
+ */
25
+
26
+ const { BUCKETS } = require('./resolve.js')
27
+
28
+ const OVERVIEW_RE = /^specs\/([^/]+)\/([^/]+)\/00-overview\.md$/
29
+ const SPEC_PATH_RE = /^specs\/([^/]+)\/([^/]+)\//
30
+
31
+ // `branch.pattern` as a for-each-ref glob: every `{token}` becomes `*`.
32
+ function refGlob(config) {
33
+ const pattern = (config && config.branch && config.branch.pattern) || '{type}/{slug}'
34
+ return pattern.replace(/\{[^}]+\}/g, '*')
35
+ }
36
+
37
+ function lines(out) {
38
+ return String(out || '').split('\n').map((l) => l.trim()).filter(Boolean)
39
+ }
40
+
41
+ /**
42
+ * The spec branches this clone can see: local first, then remote-tracking, as
43
+ * `{ ref, name, local }`. The base branch itself is never a spec branch.
44
+ */
45
+ function specRefs(git, config, base) {
46
+ const glob = refGlob(config)
47
+ const remote = (config && config.land && config.land.remote) || 'origin'
48
+ const local = lines(git(['for-each-ref', '--format=%(refname)', `refs/heads/${glob}`]))
49
+ .map((ref) => ({ ref, name: ref.slice('refs/heads/'.length), local: true }))
50
+ const prefix = `refs/remotes/${remote}/`
51
+ const tracking = lines(git(['for-each-ref', '--format=%(refname)', `${prefix}${glob}`]))
52
+ .map((ref) => ({ ref, name: ref.slice(prefix.length), local: false }))
53
+ return [...local, ...tracking].filter((r) => r.name !== base && r.name !== 'HEAD')
54
+ }
55
+
56
+ /**
57
+ * Every spec folder a spec branch changed, read off that branch:
58
+ * `[{ folder, bucket, ref, local, overview, phases: [{ n, text }] }]`.
59
+ *
60
+ * Precedence (Decision 7): a folder the base branch has FINISHED — in
61
+ * `complete/` or `cancelled/` — is dropped, since the work is done and a
62
+ * lingering branch is history; otherwise a local branch beats a
63
+ * remote-tracking one. Base's own `backlog/` copy losing to a branch copy is
64
+ * the caller's merge, via `preferBranches`.
65
+ */
66
+ function specBranchDocs(git, config, base) {
67
+ if (!base) return []
68
+ const finished = new Set()
69
+ for (const p of lines(git(['ls-tree', '-r', '--name-only', base, '--', 'specs/complete', 'specs/cancelled']))) {
70
+ const m = OVERVIEW_RE.exec(p)
71
+ if (m) finished.add(m[2])
72
+ }
73
+ const found = new Map()
74
+ for (const { ref, local } of specRefs(git, config, base)) {
75
+ const changed = new Set()
76
+ for (const p of lines(git(['diff', '--name-only', `${base}...${ref}`, '--', 'specs']))) {
77
+ const m = SPEC_PATH_RE.exec(p)
78
+ if (m && BUCKETS.includes(m[1])) changed.add(m[2])
79
+ }
80
+ if (!changed.size) continue
81
+ const tree = lines(git(['ls-tree', '-r', '--name-only', ref, '--', 'specs']))
82
+ for (const folder of changed) {
83
+ if (finished.has(folder)) continue
84
+ if (found.has(folder) && (found.get(folder).local || !local)) continue
85
+ const overviewPath = tree.find((p) => {
86
+ const m = OVERVIEW_RE.exec(p)
87
+ return m && m[2] === folder
88
+ })
89
+ if (!overviewPath) continue // the branch deleted it, or moved it out of specs/
90
+ const overview = git(['show', `${ref}:${overviewPath}`])
91
+ if (overview === null) continue
92
+ const bucket = OVERVIEW_RE.exec(overviewPath)[1]
93
+ const dirPrefix = `specs/${bucket}/${folder}/`
94
+ const phases = tree
95
+ .filter((p) => p.startsWith(dirPrefix) && /^\d\d-.+\.md$/.test(p.slice(dirPrefix.length)) && !p.endsWith('/00-overview.md'))
96
+ .map((p) => ({ n: Number(p.slice(dirPrefix.length, dirPrefix.length + 2)), text: git(['show', `${ref}:${p}`]) }))
97
+ found.set(folder, { folder, bucket, ref, local, overview, phases })
98
+ }
99
+ }
100
+ return [...found.values()].sort((a, b) => a.folder.localeCompare(b.folder))
101
+ }
102
+
103
+ /**
104
+ * Merge a disk scan with branch copies: a branch copy replaces the disk entry
105
+ * for the same folder, and adds one where there is none. Both lists carry
106
+ * `folder`; the result keeps the disk entries' order, then the new ones.
107
+ */
108
+ function preferBranches(disk, branches) {
109
+ const byFolder = new Map(branches.map((b) => [b.folder, b]))
110
+ const merged = disk.map((d) => byFolder.get(d.folder) || d)
111
+ const seen = new Set(disk.map((d) => d.folder))
112
+ return [...merged, ...branches.filter((b) => !seen.has(b.folder))]
113
+ }
114
+
115
+ /** The label a branch-sourced row carries. */
116
+ function branchLabel(entry) {
117
+ return entry.local ? `on ${entry.ref.replace(/^refs\/heads\//, '')}` : `on ${entry.ref.replace(/^refs\/remotes\//, '')}, as of last fetch`
118
+ }
119
+
120
+ module.exports = { specBranchDocs, specRefs, preferBranches, branchLabel, refGlob }
@@ -47,6 +47,15 @@ function planDown(spec, config, flags, ctx) {
47
47
  // can use `-D` — the same question ("are these commits recoverable?"), so the
48
48
  // two must never answer it differently.
49
49
  const landed = Boolean(worktreeState.merged || worktreeState.reachableFromTag)
50
+ // A spec-documents-only branch under `land.specDocs: "branch"` — authored,
51
+ // perhaps pushed, never started (feat-tracker-spec-branches). It holds no
52
+ // code to lose and was never meant to have a PR, and left on the remote it
53
+ // reads as backlog to every check that scans spec branches. `docsOnly` is a
54
+ // positive signal the caller computes from the branch's own range; anything
55
+ // it cannot read stays false, which keeps every guard below as it was.
56
+ const docsLane = Boolean(
57
+ worktreeState.docsOnly && config.land && config.land.specDocs === 'branch',
58
+ )
50
59
 
51
60
  // --- guards (overridable with --force) ---
52
61
  if (!force) {
@@ -69,7 +78,7 @@ function planDown(spec, config, flags, ctx) {
69
78
  // PR and the exit where git's cannot. `--force` bypasses, and still plans
70
79
  // `-d` below, so a genuinely unlanded branch fails loudly rather than
71
80
  // being -D'd.
72
- if (config.land && config.land.strategy === 'pr' && !landed) {
81
+ if (config.land && config.land.strategy === 'pr' && !landed && !docsLane) {
73
82
  const prState = worktreeState.prState
74
83
  const at = worktreeState.prUrl ? ` — see ${worktreeState.prUrl}` : ''
75
84
  if (prState === 'open' || prState === 'draft') {
@@ -188,9 +197,15 @@ function planDown(spec, config, flags, ctx) {
188
197
  // this delete a no-op: `git push --delete` errors with "remote ref does not
189
198
  // exist", which is loud and destroys nothing. The skills report that as
190
199
  // already-gone, never as a failed teardown.
200
+ //
201
+ // The docs lane is the one unlanded branch that may be offered: its remote
202
+ // copy backs up only the spec document being cancelled, and the ticket keeps
203
+ // the record. It is ALWAYS confirm-first — "always" folds the landed delete
204
+ // into the run-blind list, but deleting the last copy of a document is not
205
+ // what that policy was set for.
191
206
  const remoteCommands = []
192
207
  const policy = (config.teardown && config.teardown.deleteRemoteBranch) || 'prompt'
193
- if (spec.branch && landed && worktreeState.remoteBranch && policy !== 'never') {
208
+ if (spec.branch && (landed || docsLane) && worktreeState.remoteBranch && policy !== 'never') {
194
209
  // `remoteBranch` is a short ref like "origin/feat/thing" and the branch name
195
210
  // itself contains slashes, so the remote is what remains once the exact
196
211
  // "/<branch>" suffix is stripped — not the text before the first slash.
@@ -206,7 +221,7 @@ function planDown(spec, config, flags, ctx) {
206
221
  const cmd = `git push ${remote} --delete ${spec.branch}`
207
222
  // "always" is the project saying it never wants to be asked, so the push
208
223
  // joins the run-blind list. Everything else keeps it quarantined.
209
- if (policy === 'always') commands.push(cmd)
224
+ if (policy === 'always' && landed) commands.push(cmd)
210
225
  else remoteCommands.push(cmd)
211
226
  }
212
227
  }
package/src/gating.js CHANGED
@@ -15,6 +15,7 @@
15
15
 
16
16
  const fs = require('node:fs')
17
17
  const path = require('node:path')
18
+ const { preferBranches, branchLabel } = require('./env/specbranches.js')
18
19
 
19
20
  const CONFIG_FILE = path.join('specs', '.core', 'gating.config.json')
20
21
 
@@ -87,6 +88,12 @@ function readGatingField(specPath) {
87
88
  } catch {
88
89
  return { raw: null, kind: 'missing' }
89
90
  }
91
+ return readGatingText(raw)
92
+ }
93
+
94
+ // The same reading over an overview's text — a spec read off its own branch
95
+ // (`env/specbranches.js`) has text and no path on disk.
96
+ function readGatingText(raw) {
90
97
  const m = /^>\s*\*\*Gating:\*\*\s*(.*)$/m.exec(raw)
91
98
  if (!m) return { raw: null, kind: 'missing' }
92
99
  const value = m[1].trim().replace(/^["'`]|["'`]$/g, '')
@@ -130,15 +137,19 @@ function activeSpecs(dir) {
130
137
  * @returns {{configured: boolean, findings: Array<{folder, bucket, kind, raw}>,
131
138
  * checked: number, guidance: string}}
132
139
  */
133
- function checkGating(dir, specs) {
140
+ function checkGating(dir, specs, { branches = [] } = {}) {
134
141
  const { config, present } = loadGatingConfig(dir)
135
142
  if (!present) return { configured: false, findings: [], checked: 0, guidance: '' }
136
- const targets = specs && specs.length ? specs : activeSpecs(dir)
143
+ // Branch copies (`env/specbranches.js`) win over the disk copy of the same
144
+ // spec and add the ones the base branch cannot see; finished buckets are not
145
+ // gating's business either way.
146
+ const active = branches.filter((b) => ACTIVE_BUCKETS.includes(b.bucket))
147
+ const targets = specs && specs.length ? specs : preferBranches(activeSpecs(dir), active)
137
148
  const findings = []
138
149
  for (const spec of targets) {
139
- const { kind, raw } = readGatingField(spec.path)
150
+ const { kind, raw } = spec.ref ? readGatingText(spec.overview) : readGatingField(spec.path)
140
151
  if (kind === 'missing' || kind === 'invalid') {
141
- findings.push({ folder: spec.folder, bucket: spec.bucket, kind, raw })
152
+ findings.push({ folder: spec.folder, bucket: spec.bucket, kind, raw, ...(spec.ref ? { from: branchLabel(spec) } : {}) })
142
153
  }
143
154
  }
144
155
  return { configured: true, findings, checked: targets.length, guidance: config.guidance }
@@ -150,6 +161,7 @@ module.exports = {
150
161
  ACTIVE_BUCKETS,
151
162
  loadGatingConfig,
152
163
  readGatingField,
164
+ readGatingText,
153
165
  activeSpecs,
154
166
  checkGating,
155
167
  }
@@ -37,6 +37,10 @@
37
37
  * - `remoteEditedLine(identifier)` the someone-else-edited warning
38
38
  * - `twinAdvice(twin, title, specName)` the refusal message for a twin
39
39
  * - `afterIssue(issue)` optional; → a report line or null
40
+ * - `retireSubIssue(id)` optional; close a leftover phase
41
+ * sub-issue as not planned and
42
+ * unlink it. Absent means this tracker
43
+ * cannot, and the push names the ids.
40
44
  * - `setParent(issue, parentIdentifier)` optional; make the spec issue a
41
45
  * child of its epic's → `{ changed }`.
42
46
  * Absent means this tracker cannot
@@ -226,6 +230,26 @@ async function applyInner({ dir, config, snapshotDir, plan, adapter, ops, progre
226
230
  lines.push(` sub-issue updated: ${sub.id}`)
227
231
  }
228
232
 
233
+ // 5b. Retire an epic's leftover phase sub-issues (spec feat-epic-migration,
234
+ // Decision 2). Never fatal: a tracker without the seam names the ids once and
235
+ // they are forgotten — the line is the record; a retire that FAILS keeps its
236
+ // id in the snapshot, so the next push tries again.
237
+ const keepSubIssues = []
238
+ const retire = (plan.subIssues && plan.subIssues.retire) || []
239
+ if (retire.length && typeof ops.retireSubIssue !== 'function') {
240
+ lines.push(` this tracker cannot retire sub-issues here — close by hand: ${retire.join(', ')}`)
241
+ } else {
242
+ for (const id of retire) {
243
+ try {
244
+ await ops.retireSubIssue(id)
245
+ lines.push(` sub-issue retired: ${id} (no phase claims it on an epic)`)
246
+ } catch (error) {
247
+ keepSubIssues.push(id)
248
+ lines.push(` ?? retire ${id}: ${String((error && error.message) || error).split('\n')[0]}`)
249
+ }
250
+ }
251
+ }
252
+
229
253
  // 6. Read back what the tracker stored and run the SAME check verify runs.
230
254
  const stored = { issue: undefined, subIssues: {} }
231
255
  if (result.issue) {
@@ -241,7 +265,7 @@ async function applyInner({ dir, config, snapshotDir, plan, adapter, ops, progre
241
265
  const lost = verify.some((l) => l.includes('!!') || l.includes('??'))
242
266
 
243
267
  // 7. Record the snapshot from the now-stamped files, so the next push is empty.
244
- const file = recordPush({ dir, snapshotDir, identifier: helpers.specIdentifier(snapshotDir, config), config, sent })
268
+ const file = recordPush({ dir, snapshotDir, identifier: helpers.specIdentifier(snapshotDir, config), config, sent, keepSubIssues })
245
269
  // A repo path, `/`-separated on every platform — the form every other
246
270
  // spec path in this output takes.
247
271
  lines.push(` snapshot: ${path.relative(dir, file).split(path.sep).join('/')}`)
@@ -252,7 +252,7 @@ function remapped(recorded, current) {
252
252
  * `plan.issue` (when present) is the spec issue's description + state; the push
253
253
  * skill applies its provider's project/grouping choice on top of it.
254
254
  */
255
- function planChanges(projection, snapshot, { linked = false } = {}) {
255
+ function planChanges(projection, snapshot, { linked = false, epic = false } = {}) {
256
256
  const p = projection || {}
257
257
  const snap = snapshot || {}
258
258
  const snapS = snap.subIssues || {}
@@ -297,6 +297,13 @@ function planChanges(projection, snapshot, { linked = false } = {}) {
297
297
  }
298
298
  }
299
299
 
300
+ // AN EPIC'S UNCLAIMED IDS ARE LEFTOVERS, NOT LOST STAMPS. An epic has no
301
+ // phases by construction (spec feat-epics, Decision 1), so every sub-issue the
302
+ // snapshot remembers belongs to the plan spec it was converted from — a
303
+ // positive signal. On any other kind an unclaimed id stays the ambiguity it
304
+ // is above, and nothing is retired (spec feat-epic-migration, Decision 2).
305
+ if (epic && unclaimed.length) subIssues.retire = unclaimed.slice()
306
+
300
307
  const plan = { subIssues }
301
308
  if (unstamped.length) plan.unstamped = unstamped
302
309
  const issue = issueChanges(p, snap, { linked })
@@ -394,7 +401,8 @@ function issueChanges(projection, snapshot, { linked = false } = {}) {
394
401
 
395
402
  // True when a plan would push nothing.
396
403
  function isEmptyPlan(plan) {
397
- return !plan.issue && !plan.subIssues.create.length && !plan.subIssues.update.length
404
+ const retire = plan.subIssues.retire || []
405
+ return !plan.issue && !plan.subIssues.create.length && !plan.subIssues.update.length && !retire.length
398
406
  }
399
407
 
400
408
  module.exports = {
@@ -1,5 +1,7 @@
1
1
  'use strict'
2
2
 
3
+ const path = require('node:path')
4
+
3
5
  /**
4
6
  * `push` — repo → Linear, one-way. The repo is the source of truth; Linear is a
5
7
  * generated mirror. We never read remote content: `push` builds the local
@@ -102,7 +104,8 @@ function isLinked(snapshotDir, config) {
102
104
  function push({ dir, snapshotDir, identifier, config }) {
103
105
  const projection = projectionOf(snapshotDir, config)
104
106
  const snapshot = readBase(dir, identifier, config)
105
- const plan = planChanges(projection, snapshot, { linked: isLinked(snapshotDir, config) })
107
+ const epic = path.basename(String(snapshotDir || '')).startsWith('epic-')
108
+ const plan = planChanges(projection, snapshot, { linked: isLinked(snapshotDir, config), epic })
106
109
  // A spec still linked under the pre-9.0 model reads as unlinked here, so the
107
110
  // plan above is all-creates and would abandon a live mirror. Carry the finding
108
111
  // ON THE PLAN, not as a warning: `--json` routes warnings to stderr, and the
@@ -134,10 +137,18 @@ function push({ dir, snapshotDir, identifier, config }) {
134
137
  // that was NOT sent would claim the tracker holds it, and silence the very remap
135
138
  // this record exists to catch. Without `sent` (a hand-applied MCP push) nothing
136
139
  // new is recorded and what was there is kept.
137
- function recordPush({ dir, snapshotDir, identifier, config, sent = null }) {
140
+ // `keepSubIssues` names ids the projection no longer claims but the tracker may
141
+ // still hold — a retire that failed — so the next push plans them again rather
142
+ // than forgetting them.
143
+ function recordPush({ dir, snapshotDir, identifier, config, sent = null, keepSubIssues = [] }) {
138
144
  const projection = projectionOf(snapshotDir, config)
139
145
  const snapshot = snapshotOf(projection, config)
140
- const names = stateNamesRecord(projection, readBase(dir, identifier, config), sent)
146
+ const before = readBase(dir, identifier, config)
147
+ for (const id of keepSubIssues) {
148
+ const hash = before && before.subIssues && before.subIssues[String(id)]
149
+ if (hash !== undefined) snapshot.subIssues[String(id)] = hash
150
+ }
151
+ const names = stateNamesRecord(projection, before, sent)
141
152
  if (names) snapshot.stateNames = names
142
153
  return writeBase(dir, identifier, config, snapshot)
143
154
  }