@skitterbyte/skitterspec-github 2.10.0 → 2.12.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.
@@ -0,0 +1,250 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * The morning half of the ta-da list (feat-spec-todo, phase 2): where each
5
+ * project was left on the last day with any activity, and what is ahead. It
6
+ * reads the same digest `skitterspec tada` does — once for the lookback, once
7
+ * for the day it found — so the two can never disagree about what happened.
8
+ * Pure: every input arrives already read.
9
+ */
10
+
11
+ const fs = require('node:fs')
12
+ const path = require('node:path')
13
+
14
+ const { localDay } = require('./window.js')
15
+ const { waitingPasses, readGate, gateState } = require('../env/review.js')
16
+
17
+ // Far enough to bridge a long weekend or a week away; past it, "where did I
18
+ // leave off" has no useful answer and the report says so.
19
+ const LOOKBACK_DAYS = 14
20
+
21
+ function daysBefore(d, n) {
22
+ return new Date(d.getFullYear(), d.getMonth(), d.getDate() - n)
23
+ }
24
+
25
+ /** Every instant a digest saw something happen: prompts, sessions, commits, moves. */
26
+ function activityTimes(digest) {
27
+ const times = []
28
+ for (const p of digest.projects) {
29
+ for (const g of p.groups) {
30
+ for (const s of g.sessions) {
31
+ times.push(s.start, s.end)
32
+ for (const pr of s.prompts) times.push(pr.at)
33
+ }
34
+ for (const c of g.commits) times.push(c.at)
35
+ for (const e of g.events) times.push(e.at)
36
+ }
37
+ }
38
+ return times.filter(Boolean)
39
+ }
40
+
41
+ /**
42
+ * The local midnight of the most recent day before `todayStart` with any
43
+ * activity, at most `lookback` days back — so Monday reads Friday and a day
44
+ * off is skipped. Null when nothing falls in the lookback.
45
+ *
46
+ * @param {string[]} times ISO instants (`activityTimes`)
47
+ * @param {Date} todayStart local midnight today
48
+ */
49
+ function lastActiveDay(times, todayStart, lookback = LOOKBACK_DAYS) {
50
+ const floor = daysBefore(todayStart, lookback).getTime()
51
+ const end = todayStart.getTime()
52
+ let best = null
53
+ for (const t of times) {
54
+ const ms = Date.parse(t)
55
+ if (Number.isNaN(ms) || ms < floor || ms >= end) continue
56
+ if (best === null || ms > best) best = ms
57
+ }
58
+ if (best === null) return null
59
+ const d = new Date(best)
60
+ return new Date(d.getFullYear(), d.getMonth(), d.getDate())
61
+ }
62
+
63
+ const EVENT = { written: 'written', started: 'started', completed: 'completed', cancelled: 'cancelled' }
64
+ const eventText = (e) => (e.kind === 'phase-done' ? `phase ${e.phase} done` : EVENT[e.kind] || e.kind)
65
+
66
+ /**
67
+ * Where one group was left: its last move or commit, whichever came later —
68
+ * a commit after a move is the newer fact. Null when the group only has
69
+ * sessions or an in-flight row.
70
+ */
71
+ function leftOf(g) {
72
+ const last = [
73
+ ...g.events.map((e) => ({ at: e.at, text: eventText(e) })),
74
+ ...g.commits.map((c) => ({ at: c.at, text: `${c.sha} ${c.subject}` })),
75
+ ].sort((a, b) => Date.parse(a.at) - Date.parse(b.at))
76
+ return last.length ? last[last.length - 1].text : null
77
+ }
78
+
79
+ // The last thing typed in the group's last session — what was on the
80
+ // person's mind when they stopped.
81
+ function lastPrompt(g) {
82
+ const s = g.sessions[g.sessions.length - 1]
83
+ const p = s && s.prompts[s.prompts.length - 1]
84
+ return p ? `${p.command ? `${p.command} ` : ''}${p.text}`.trim() : null
85
+ }
86
+
87
+ /**
88
+ * What stands in a project's way, read only for the specs in flight there: a
89
+ * pass waiting on the review page, or a gate armed by a phase that ended. A
90
+ * pass for a spec no longer in flight is an old one nobody is waiting on, and
91
+ * is left out rather than reported as a blocker.
92
+ *
93
+ * @param {object} a
94
+ * - `specs` the project's in-flight spec names
95
+ * - `passes` `waitingPasses(...).passes`
96
+ * - `gates` `{ [spec]: gateState(...) }`; a missing or `unknown` state is
97
+ * cannot-tell, and says nothing
98
+ */
99
+ function blockersFrom({ specs, passes = [], gates = {} }) {
100
+ const want = new Set(specs)
101
+ const out = []
102
+ for (const p of passes) {
103
+ if (want.has(p.spec)) out.push({ spec: p.spec, kind: 'verdict', verdict: p.verdict, code: p.code, at: p.at })
104
+ }
105
+ for (const spec of specs) {
106
+ const g = gates[spec]
107
+ if (g && g.state === 'armed') out.push({ spec, kind: 'gate', phase: g.gate ? g.gate.phase : null })
108
+ }
109
+ return out
110
+ }
111
+
112
+ /**
113
+ * `blockersFrom`, read off one repo's review store. A store that does not
114
+ * exist — a repo that never rendered a review — is nothing in the way, not a
115
+ * failure; an unreadable gate is `gateState`'s cannot-tell and says nothing.
116
+ *
117
+ * @param {string} reviews the repo's reviews dir (`<state dir>/reviews`)
118
+ * @param {string[]} specs its in-flight spec names
119
+ * @param {boolean} [required] `review.required`; false opts the gates out
120
+ */
121
+ function readBlockers(reviews, specs, required) {
122
+ if (!fs.existsSync(reviews)) return []
123
+ const gates = {}
124
+ for (const spec of specs) gates[spec] = gateState({ ...readGate(path.join(reviews, `${spec}.html`), spec), required })
125
+ return blockersFrom({ specs, passes: waitingPasses(reviews).passes, gates })
126
+ }
127
+
128
+ /**
129
+ * The to-do: the left-off day's projects, each open spec reduced to where it
130
+ * was left, the specs that day finished by name, today's activity so far, and
131
+ * what is blocking each project.
132
+ *
133
+ * @param {object} a
134
+ * - `leftOff` the digest for the left-off day, or null when none
135
+ * - `leftOffDay` that day's local midnight, or null
136
+ * - `today` today's digest so far
137
+ * - `home` the home project as a digest project (in-flight groups
138
+ * only) for when neither digest lists it, else null
139
+ * - `blockersFor` `(repo, specs) => blockers` — read only for a repo
140
+ */
141
+ function buildTodo({ leftOff, leftOffDay, today, home = null, blockersFor = () => [] }) {
142
+ const projects = new Map()
143
+ const keyOf = (p) => p.repo || p.name
144
+ const entry = (p) => {
145
+ const k = keyOf(p)
146
+ if (!projects.has(k)) projects.set(k, { repo: p.repo, name: p.name, here: false, groups: [], finished: [], today: { commits: 0, moves: 0 } })
147
+ const e = projects.get(k)
148
+ if (p.here) e.here = true
149
+ return e
150
+ }
151
+
152
+ for (const p of leftOff ? leftOff.projects : []) {
153
+ const e = entry(p)
154
+ for (const g of p.groups) {
155
+ // The morning wants what is still open. A spec the day finished is said
156
+ // once, by name; work on no spec is history, not a place to pick up.
157
+ if (!g.inFlight) {
158
+ if (g.spec && g.events.some((ev) => ev.kind === 'completed' || ev.kind === 'cancelled')) e.finished.push(g.spec)
159
+ continue
160
+ }
161
+ const left = leftOf(g)
162
+ const prompt = lastPrompt(g)
163
+ e.groups.push({ spec: g.spec, branch: g.branch, ...(g.ticket ? { ticket: g.ticket } : {}), left, prompt, inFlight: g.inFlight })
164
+ }
165
+ }
166
+ for (const p of today.projects) {
167
+ const e = entry(p)
168
+ const known = new Set(e.groups.map((g) => g.spec).filter(Boolean))
169
+ for (const g of p.groups) {
170
+ e.today.commits += g.commits.length
171
+ e.today.moves += g.events.length
172
+ // What is ahead in a project the left-off day did not touch.
173
+ if (g.spec && g.inFlight && !known.has(g.spec)) {
174
+ e.groups.push({ spec: g.spec, branch: g.branch, ...(g.ticket ? { ticket: g.ticket } : {}), left: null, prompt: null, inFlight: g.inFlight })
175
+ }
176
+ }
177
+ }
178
+ if (home && !projects.has(keyOf(home))) {
179
+ const e = entry({ ...home, here: true })
180
+ for (const g of home.groups) if (g.inFlight) e.groups.push({ spec: g.spec, branch: null, left: null, prompt: null, inFlight: g.inFlight })
181
+ }
182
+ // Ideas are counted for home only: the count is this project's to act on,
183
+ // and asking every project's tracker would turn a morning read into a crawl.
184
+ // Null — could not ask — and zero both print nothing.
185
+ if (home && home.ideas > 0) projects.get(keyOf(home)).ideas = home.ideas
186
+
187
+ const list = [...projects.values()]
188
+ .map((e) => {
189
+ const specs = e.groups.filter((g) => g.spec && g.inFlight).map((g) => g.spec)
190
+ return { ...e, blocked: e.repo && specs.length ? blockersFor(e.repo, specs) : [] }
191
+ })
192
+ .filter((e) => e.groups.length || e.finished.length || e.today.commits || e.today.moves || e.ideas)
193
+ // The home project first: it is the one this session acts on.
194
+ .sort((a, b) => (a.here !== b.here ? (a.here ? -1 : 1) : a.name.localeCompare(b.name)))
195
+
196
+ return {
197
+ kind: 'todo',
198
+ leftOff: leftOffDay ? { day: localDay(leftOffDay) } : null,
199
+ lookbackDays: LOOKBACK_DAYS,
200
+ ...(today.category ? { category: today.category } : {}),
201
+ projects: list,
202
+ notes: [...new Set([...(leftOff ? leftOff.notes : []), ...today.notes])],
203
+ }
204
+ }
205
+
206
+ const ageText = (at, now) => {
207
+ const ms = now - Date.parse(at)
208
+ if (Number.isNaN(ms) || ms < 0) return ''
209
+ const h = Math.floor(ms / 3_600_000)
210
+ return h < 24 ? ` · ${h}h` : ` · ${Math.floor(h / 24)}d`
211
+ }
212
+
213
+ function blockedText(b, now) {
214
+ if (b.kind === 'gate') return `${b.spec} — gate armed${b.phase ? `, phase ${b.phase}` : ''}: a verdict is owed`
215
+ return `${b.spec} — ${b.verdict || 'a'} verdict waiting (${b.code}${b.at ? ageText(b.at, now) : ''})`
216
+ }
217
+
218
+ /**
219
+ * The to-do as text — the same markers as `tada`, plus `left:` for where a
220
+ * group stopped, `finished:` for the specs that day closed, `blocked:` for what stands in a project's way, and `today:`
221
+ * for what has happened since midnight.
222
+ */
223
+ function formatTodo(todo, now = new Date()) {
224
+ const scope = todo.category ? ` · ${todo.category}` : ''
225
+ const head = todo.leftOff
226
+ ? `todo: left off ${todo.leftOff.label || todo.leftOff.day} · today ${todo.todayLabel || ''}`.trimEnd()
227
+ : `todo: nothing in the last ${todo.lookbackDays} days · today ${todo.todayLabel || ''}`.trimEnd()
228
+ const out = [`${head}${scope}`]
229
+ if (todo.projects.length === 0) out.push(' nothing in flight.')
230
+ for (const p of todo.projects) {
231
+ out.push('', `${p.name}${p.here ? ' (here)' : ''}${p.repo ? ` (${p.repo})` : ''}`)
232
+ for (const g of p.groups) {
233
+ out.push(` ${g.spec ? `${g.spec}${g.ticket ? ` [${g.ticket.id}]` : ''}` : `${g.branch || '(no branch)'} — no spec`}`)
234
+ if (g.left) out.push(` left: ${g.left}`)
235
+ if (g.prompt) out.push(` - ${g.prompt}`)
236
+ if (g.inFlight) out.push(` in flight: ${g.inFlight.detail}${g.inFlight.next ? ` · next: ${g.inFlight.next}` : ''}`)
237
+ }
238
+ if (p.finished.length) out.push(` finished: ${p.finished.join(', ')}`)
239
+ for (const b of p.blocked) out.push(` blocked: ${blockedText(b, now)}`)
240
+ if (p.ideas) out.push(` ideas: ${p.ideas} waiting · /spec-idea lists them`)
241
+ if (p.today.commits || p.today.moves) {
242
+ const parts = [p.today.commits && `${p.today.commits} commit${p.today.commits === 1 ? '' : 's'}`, p.today.moves && `${p.today.moves} move${p.today.moves === 1 ? '' : 's'}`]
243
+ out.push(` today: ${parts.filter(Boolean).join(', ')}`)
244
+ }
245
+ }
246
+ for (const n of todo.notes) out.push('', n)
247
+ return out.join('\n') + '\n'
248
+ }
249
+
250
+ module.exports = { LOOKBACK_DAYS, activityTimes, lastActiveDay, leftOf, blockersFrom, readBlockers, buildTodo, formatTodo, blockedText }
@@ -413,10 +413,15 @@ function specSyncPlan(dir, config, specArg, flags, out, err) {
413
413
  }
414
414
 
415
415
  async function specSyncApply(dir, config, specArg, flags, out, err) {
416
- if (!flags.plan && !flags.all) {
416
+ if (!flags.plan && !flags.all && !flags.sendHeld) {
417
417
  out.write(`${PROGRAM} apply: pass --plan <file> (from \`plan --json\`), or --all <bucket>\n`)
418
418
  return 1
419
419
  }
420
+ const held = kit.heldFlags(flags, PROGRAM)
421
+ if (held.error) {
422
+ out.write(held.error + '\n')
423
+ return 1
424
+ }
420
425
  const cred = apiAdapterFor(config, flags)
421
426
  const transport = kit.resolveTransport(flags, config, cred.ok)
422
427
  if (transport === 'mcp') {
@@ -425,6 +430,8 @@ async function specSyncApply(dir, config, specArg, flags, out, err) {
425
430
  return 1
426
431
  }
427
432
  out.write(`${PROGRAM} apply: transport = mcp — nothing written by the engine.\n ${APPLY_OVER_MCP}\n`)
433
+ const heldNote = kit.heldOverMcp(held, PROGRAM)
434
+ if (heldNote) out.write(heldNote + '\n')
428
435
  return 0
429
436
  }
430
437
  if (!cred.ok) {
@@ -446,6 +453,8 @@ async function specSyncApply(dir, config, specArg, flags, out, err) {
446
453
  adapter: cred.adapter,
447
454
  ops: applyOps({ adapter: cred.adapter, config, kind: specKindOf(snapshotDir), snapshotDir }),
448
455
  forceNew: !!flags.forceNew,
456
+ holdState: held.holdState,
457
+ sendHeld: held.sendHeld,
449
458
  program: PROGRAM,
450
459
  })
451
460
 
@@ -488,13 +497,19 @@ async function specSyncApply(dir, config, specArg, flags, out, err) {
488
497
  const snapshotDir = resolveOrExit(specArg, dir, out)
489
498
  if (!snapshotDir) return 1
490
499
  let plan
491
- try {
492
- plan = JSON.parse(fs.readFileSync(flags.plan, 'utf-8'))
493
- } catch (error) {
494
- out.write(`${PROGRAM} apply: cannot read --plan: ${error.message}\n`)
495
- return 1
500
+ if (!flags.plan) {
501
+ // --send-held computes its own. After the merge it is normally empty, and
502
+ // that empty plan is what tells apply that run 1 held the state.
503
+ plan = push({ dir, snapshotDir, identifier: specIdentifier(snapshotDir, config), config }).plan
504
+ } else {
505
+ try {
506
+ plan = JSON.parse(fs.readFileSync(flags.plan, 'utf-8'))
507
+ } catch (error) {
508
+ out.write(`${PROGRAM} apply: cannot read --plan: ${error.message}\n`)
509
+ return 1
510
+ }
496
511
  }
497
- if (isEmptyPlan(plan)) {
512
+ if (!held.sendHeld && isEmptyPlan(plan)) {
498
513
  out.write(`${PROGRAM} apply: empty plan — nothing to do\n`)
499
514
  return 0
500
515
  }
@@ -586,7 +601,10 @@ function specSyncRecord(dir, config, specArg, flags, out) {
586
601
  const snapshotDir = resolveOrExit(specArg, dir, out)
587
602
  if (!snapshotDir) return 1
588
603
  const keepSubIssues = (flags && flags.keepSubIssues) || []
589
- const file = recordPush({ dir, snapshotDir, identifier: specIdentifier(snapshotDir, config), config, keepSubIssues })
604
+ // --held: the hand-applied twin of `apply --hold-state` — the state was left
605
+ // out on purpose, and is recorded as sent so run 2 rewrites nothing.
606
+ const sent = flags && flags.held ? { issue: true, subIssues: new Set() } : null
607
+ const file = recordPush({ dir, snapshotDir, identifier: specIdentifier(snapshotDir, config), config, sent, keepSubIssues })
590
608
  out.write(`${PROGRAM} record: snapshot written — ${path.relative(dir, file).split(path.sep).join('/')}\n`)
591
609
  return 0
592
610
  }
@@ -894,6 +912,10 @@ async function specSyncIntake(dir, config, query, flags, out) {
894
912
  }
895
913
  const claimed = new Set(listSpecs(dir, config).map((s) => s.identifier).filter(Boolean))
896
914
  const own = new Set(['spec', 'phase'].flatMap((k) => markersFor(config, k).labels).map((l) => l.toLowerCase()))
915
+ // An idea is the operator's own parked thought, listed by `idea list`; the
916
+ // intake inbox is for what other people filed. Without this an unset
917
+ // `intake.label` (every open issue) would list each idea twice over.
918
+ if (config.intake.ideaLabel) own.add(config.intake.ideaLabel.toLowerCase())
897
919
  const want = String(query || '').toLowerCase().trim()
898
920
  const bug = new Set((config.intake.bugLabels || []).map((l) => l.toLowerCase()))
899
921
  const hot = new Set((config.intake.hotfixLabels || []).map((l) => l.toLowerCase()))
@@ -922,6 +944,120 @@ async function specSyncIntake(dir, config, query, flags, out) {
922
944
  return 0
923
945
  }
924
946
 
947
+ // `idea add|list|drop` — the store `skitterspec idea` hands GitHub: an open
948
+ // issue carrying `intake.ideaLabel`, deliberately NEVER added to the board. The
949
+ // board is for specs; a parked thought does not get a column. `/spec #N` adopts
950
+ // one like any other issue, which is why an adopted idea drops out of `list`.
951
+ //
952
+ // Without the API a capture REFUSES (exit 1) and hands the text back with the
953
+ // MCP plan — a write that did not happen must not read as one that did. The
954
+ // listing degrades to one line and exit 0, as intake's does, and `--count`
955
+ // answers null rather than 0: zero ideas and "could not ask" are not the same.
956
+ async function specSyncIdea(dir, config, positional, flags, out) {
957
+ const [verb, ...words] = positional
958
+ const label = config.intake.ideaLabel
959
+ const text = words.join(' ')
960
+ const say = (json, lines) => out.write(flags.json ? JSON.stringify(json, null, 2) + '\n' : lines.join('\n') + '\n')
961
+ const refuse = (reason, extra = {}) => {
962
+ const back = verb === 'add' && text ? `\n your idea, so nothing is lost:\n ${text.replace(/\n/g, '\n ')}` : ''
963
+ say({ ok: false, store: 'github', refused: reason, ...extra }, [`${PROGRAM} idea: ${reason}${back}`])
964
+ return 1
965
+ }
966
+ if (!['add', 'list', 'drop'].includes(verb)) {
967
+ out.write(`Usage: ${PROGRAM} idea add <text> | list [--count] | drop <#N> [--reason <why>] [--json]\n`)
968
+ return verb ? 1 : 0
969
+ }
970
+ if (!label) return refuse('intake.ideaLabel is empty — an idea is an issue carrying that label, so set one')
971
+
972
+ const cred = apiAdapterFor(config, flags)
973
+ if (kit.resolveTransport(flags, config, cred.ok) === 'mcp' || !cred.ok) {
974
+ const why = cred.ok ? 'pass --via api' : cred.error.split('\n')[0]
975
+ if (verb === 'list') {
976
+ say({ store: 'github', count: null, ideas: null }, [
977
+ `${PROGRAM} idea: needs the API transport — ${why}`,
978
+ ` (over MCP: list_issues with label "${label}", then drop the ones \`spec-sync linked\` names)`,
979
+ ])
980
+ return 0
981
+ }
982
+ const plan =
983
+ verb === 'add'
984
+ ? `create_issue with label "${label}" and do NOT add it to the project`
985
+ : `close the issue as not planned, with the reason as a comment`
986
+ return refuse(`needs the API transport — ${why}; nothing was written\n (over MCP: ${plan})`, verb === 'add' ? { text } : {})
987
+ }
988
+ const gh = cred.adapter
989
+
990
+ if (verb === 'add') {
991
+ const lines = text.replace(/\r\n/g, '\n').split('\n')
992
+ const at = lines.findIndex((l) => l.trim())
993
+ if (at === -1) return refuse('nothing to capture — give the idea some text')
994
+ const title = lines[at].trim()
995
+ const body = lines.slice(at + 1).join('\n').trim()
996
+ let made
997
+ try {
998
+ made = await gh.createIssue({ title, description: body, labels: [label] })
999
+ } catch (error) {
1000
+ return refuse(`GitHub refused the idea — ${error.message}`, { text })
1001
+ }
1002
+ say({ ok: true, store: 'github', action: 'add', identifier: made.identifier, url: made.url, title }, [
1003
+ `${PROGRAM} idea: filed ${made.identifier} "${title}" (labelled "${label}", not on the board)`,
1004
+ ` url: ${made.url}`,
1005
+ ` promote: /spec ${made.identifier}`,
1006
+ ])
1007
+ return 0
1008
+ }
1009
+
1010
+ if (verb === 'list') {
1011
+ let issues
1012
+ try {
1013
+ issues = await gh.listIssues({ labels: [label] })
1014
+ } catch (error) {
1015
+ say({ store: 'github', count: null, ideas: null }, [`${PROGRAM} idea: ${error.message}`])
1016
+ return 1
1017
+ }
1018
+ const claimed = new Set(listSpecs(dir, config).map((s) => s.identifier).filter(Boolean))
1019
+ const ideas = issues
1020
+ .filter((i) => !claimed.has(i.identifier))
1021
+ .map((i) => ({ identifier: i.identifier, title: i.title, url: i.url, author: i.author, promote: `/spec ${i.identifier}` }))
1022
+ if (flags.count) {
1023
+ say({ store: 'github', count: ideas.length }, [String(ideas.length)])
1024
+ return 0
1025
+ }
1026
+ const lines = ideas.length
1027
+ ? [`${PROGRAM} idea: ${repoLabel(config)} · "${label}"`, ...ideas.map((i) => ` ${i.identifier}\t${i.title || ''}${i.author ? ` (${i.author})` : ''}`)]
1028
+ : [`${PROGRAM} idea: nothing waiting under "${label}"`]
1029
+ say({ store: 'github', label, ideas }, lines)
1030
+ return 0
1031
+ }
1032
+
1033
+ // drop
1034
+ const ref = words[0]
1035
+ if (!ref) return refuse('name the idea to drop — `idea list` shows them')
1036
+ let issue
1037
+ try {
1038
+ issue = await gh.readIssue(ref)
1039
+ } catch (error) {
1040
+ return refuse(error.message)
1041
+ }
1042
+ if (!issue) return refuse(`no GitHub issue ${ref}`)
1043
+ // Closing an arbitrary issue under the name of an idea is the expensive
1044
+ // mistake here, so the label is the positive signal that it is one.
1045
+ if (!(issue.labels || []).some((l) => String(l).toLowerCase() === label.toLowerCase())) {
1046
+ return refuse(`${issue.identifier || ref} does not carry "${label}" — not an idea, left open`)
1047
+ }
1048
+ const why = flags.reason && String(flags.reason).trim() ? String(flags.reason).trim() : 'no reason given'
1049
+ try {
1050
+ await gh.createComment(ref, `Dropped as an idea: ${why}`)
1051
+ await gh.setIssueOpen(ref, { open: false, reason: 'not_planned' })
1052
+ } catch (error) {
1053
+ return refuse(`GitHub refused the drop — ${error.message}`)
1054
+ }
1055
+ say({ ok: true, store: 'github', action: 'drop', identifier: issue.identifier, title: issue.title, reason: why }, [
1056
+ `${PROGRAM} idea: dropped ${issue.identifier} "${issue.title || ''}" — closed as not planned (${why})`,
1057
+ ])
1058
+ return 0
1059
+ }
1060
+
925
1061
  // The `Refs:` trailer's source of truth: the ticket for the spec this branch
926
1062
  // (or the named spec) belongs to. Bare identifier on stdout ONLY on success —
927
1063
  // every no-ref case writes stderr and exits 1, so `$(spec-sync ref)` cannot
@@ -1493,14 +1629,16 @@ const USAGE = `Usage: ${BIN} spec-sync <subcommand>
1493
1629
  normalize <spec> print the local projection as JSON
1494
1630
  plan <spec> --workspace-states <f> what a push would change (dry, JSON)
1495
1631
  apply <spec> --plan <f> | --all <b> apply a plan over the API
1632
+ apply <spec> --hold-state | --send-held PR-mode completion: hold Done for run 2, then send it
1496
1633
  stamp <spec> --issue #N [--sub r=#N] write returned numbers into the spec
1497
- record <spec> write the last-pushed snapshot
1634
+ record <spec> [--held] write the last-pushed snapshot
1498
1635
  status <spec> [--remote <f>] read-only drift report
1499
1636
  verify <spec> --stored <f> compare a read-back against the repo
1500
1637
  splice <spec> --live <f> [--phase <ref>] the body to write over MCP (summary mode)
1501
1638
  states [--json] the board's Status options + bucket map
1502
1639
  list [--all | --state NAME|BUCKET | --next N] [--mine | --by USER] the board's issues
1503
1640
  intake [query] [--json] issues waiting to become specs
1641
+ idea add|list|drop [--json] ideas: issues labelled intake.ideaLabel, off the board
1504
1642
  linked [--json] specs and their linked issues (offline)
1505
1643
  ownership [--json] who owns status and assignee (offline)
1506
1644
  board <spec> [--json] is the issue finished where the spec is not?
@@ -1594,6 +1732,8 @@ async function specSync(rest, io = {}) {
1594
1732
  return specSyncList(dir, config, flags, out)
1595
1733
  case 'intake':
1596
1734
  return specSyncIntake(dir, config, positional[0], flags, out)
1735
+ case 'idea':
1736
+ return specSyncIdea(dir, config, positional, flags, out)
1597
1737
  case 'ref':
1598
1738
  return specSyncRef(dir, config, positional[0], flags, out, err)
1599
1739
  case 'released':
@@ -1644,6 +1784,9 @@ function parseArgs(args, sub) {
1644
1784
  '--via': { kind: 'string' },
1645
1785
  '--force': { kind: 'boolean' },
1646
1786
  '--force-new': { kind: 'boolean', name: 'forceNew' },
1787
+ '--hold-state': { kind: 'boolean', name: 'holdState' },
1788
+ '--send-held': { kind: 'boolean', name: 'sendHeld' },
1789
+ '--held': { kind: 'boolean' },
1647
1790
  '--issue': { kind: 'string' },
1648
1791
  '--url': { kind: 'value' },
1649
1792
  '--sub': { kind: 'list', name: 'subs' },
@@ -1660,6 +1803,8 @@ function parseArgs(args, sub) {
1660
1803
  '--name': { kind: 'value' },
1661
1804
  '--release': { kind: 'boolean' },
1662
1805
  '--if-unassigned': { kind: 'boolean', name: 'ifUnassigned' },
1806
+ '--reason': { kind: 'value' },
1807
+ '--count': { kind: 'boolean' },
1663
1808
  '--mine': { kind: 'boolean' },
1664
1809
  '--next': { kind: 'number' },
1665
1810
  '--by': { kind: 'string' },
@@ -92,7 +92,7 @@ const DEFAULT_CONFIG = Object.freeze({
92
92
  assigneeId: 'github_assignee_id',
93
93
  assigneeName: 'github_assignee_name',
94
94
  }),
95
- intake: Object.freeze({ label: '', bugLabels: Object.freeze(['bug']), hotfixLabels: Object.freeze([]) }),
95
+ intake: Object.freeze({ label: '', ideaLabel: 'idea', bugLabels: Object.freeze(['bug']), hotfixLabels: Object.freeze([]) }),
96
96
  release: Object.freeze({ ignorePaths: Object.freeze(['specs/', 'CHANGELOG.md', 'RELEASES.md']) }),
97
97
  branch: Object.freeze({ pattern: '{type}/{slug}' }),
98
98
  // An env-var NAME, not a value. A classic PAT with `repo` + `project`: the
@@ -145,6 +145,7 @@ function defaults() {
145
145
  fields: { ...DEFAULT_CONFIG.fields },
146
146
  intake: {
147
147
  label: DEFAULT_CONFIG.intake.label,
148
+ ideaLabel: DEFAULT_CONFIG.intake.ideaLabel,
148
149
  bugLabels: [...DEFAULT_CONFIG.intake.bugLabels],
149
150
  hotfixLabels: [...DEFAULT_CONFIG.intake.hotfixLabels],
150
151
  },
@@ -246,6 +247,7 @@ function mergeConfig(base, parsed) {
246
247
 
247
248
  if (isObject(parsed.intake)) {
248
249
  assign(base.intake, parsed.intake, 'label', 'string?')
250
+ assign(base.intake, parsed.intake, 'ideaLabel', 'string?')
249
251
  if (Array.isArray(parsed.intake.bugLabels)) base.intake.bugLabels = stringList(parsed.intake.bugLabels)
250
252
  if (Array.isArray(parsed.intake.hotfixLabels)) base.intake.hotfixLabels = stringList(parsed.intake.hotfixLabels)
251
253
  }
@@ -52,6 +52,7 @@ const path = require('node:path')
52
52
  const {
53
53
  readSnapshot,
54
54
  readBase,
55
+ isEmptyPlan,
55
56
  projectionOf,
56
57
  recordPush,
57
58
  writeFrontmatter,
@@ -85,16 +86,58 @@ async function applySpecPlan(args) {
85
86
  }
86
87
  }
87
88
 
88
- async function applyInner({ dir, config, snapshotDir, plan, adapter, ops, progress, forceNew = false, program = 'spec-sync' }) {
89
+ async function applyInner({
90
+ dir,
91
+ config,
92
+ snapshotDir,
93
+ plan,
94
+ adapter,
95
+ ops,
96
+ progress,
97
+ forceNew = false,
98
+ holdState = false,
99
+ sendHeld = false,
100
+ program = 'spec-sync',
101
+ }) {
89
102
  const fields = fieldsOf(config)
90
103
  const helpers = makeSpecHelpers({ program })
91
104
  const overviewFile = (config.snapshot && config.snapshot.overviewFile) || '00-overview.md'
92
105
  const identifier = helpers.linkedIdentifier(path.join(snapshotDir, overviewFile), config)
93
106
  const lines = []
94
107
  const result = { issue: null, subIssues: {} }
108
+
109
+ // PR-MODE COMPLETION, `branch` lane (spec bug-pr-complete-snapshot-on-base).
110
+ // Run 1 commits the move to ride the PR, but the Done waits for the merge —
111
+ // and run 2 sends it from the base branch, where no spec branch is left to
112
+ // commit a snapshot to. So run 1 HOLDS the state yet records it as sent, and
113
+ // run 2 SENDS only that state: the snapshot it records is byte-identical to
114
+ // the one the merge brought, and the base branch stays clean.
115
+ if (holdState && sendHeld) throw new Error(`${program} apply: --hold-state and --send-held are two runs, not one`)
116
+ if ((holdState || sendHeld) && !identifier) {
117
+ throw new Error(`${program} apply: an unlinked spec has no transition to hold — push it plainly`)
118
+ }
119
+ let heldState = false
120
+ let fellBack = false
121
+ if (holdState && plan.issue && plan.issue.state != null) {
122
+ const { state, stateResend, ...rest } = plan.issue
123
+ plan = { ...plan, issue: Object.keys(rest).length ? rest : undefined }
124
+ heldState = state
125
+ } else if (sendHeld) {
126
+ // A NON-EMPTY PLAN MEANS RUN 1 HELD NOTHING — it predates the hold, so the
127
+ // whole completion is still unsent. Sending the state alone would strand
128
+ // the rest; apply it all, as before, and say which file that leaves dirty.
129
+ if (isEmptyPlan(plan)) {
130
+ const status = projectionOf(snapshotDir, config).status
131
+ if (status != null) plan = { ...plan, issue: { state: status } }
132
+ } else {
133
+ fellBack = true
134
+ }
135
+ }
136
+
95
137
  // Which items this apply carried a state for — the snapshot records today's
96
- // state name for these and only these (`recordPush`).
97
- const sent = { issue: !!(plan.issue && plan.issue.state != null), subIssues: new Set() }
138
+ // state name for these and only these (`recordPush`). A held state counts:
139
+ // run 2 sends it, and what run 2 records has to match what run 1 committed.
140
+ const sent = { issue: !!heldState || !!(plan.issue && plan.issue.state != null), subIssues: new Set() }
98
141
  // Handed out immediately, so a throw from anywhere below still reports what
99
142
  // had been stamped by the time it happened.
100
143
  if (progress) progress.result = result
@@ -268,7 +311,12 @@ async function applyInner({ dir, config, snapshotDir, plan, adapter, ops, progre
268
311
  const file = recordPush({ dir, snapshotDir, identifier: helpers.specIdentifier(snapshotDir, config), config, sent, keepSubIssues })
269
312
  // A repo path, `/`-separated on every platform — the form every other
270
313
  // spec path in this output takes.
271
- lines.push(` snapshot: ${path.relative(dir, file).split(path.sep).join('/')}`)
314
+ const snapshotPath = path.relative(dir, file).split(path.sep).join('/')
315
+ lines.push(` snapshot: ${snapshotPath}`)
316
+ if (heldState) lines.push(` state held: ${identifier} → ${heldState} waits for the merge — run 2 sends it with --send-held`)
317
+ if (fellBack) {
318
+ lines.push(` !! nothing was held for ${identifier} — sent the whole plan; ${snapshotPath} now differs from the merged copy`)
319
+ }
272
320
  return { result, lines, lost }
273
321
  }
274
322
 
@@ -304,4 +352,41 @@ function resolvePhaseFileIn(snapshotDir, ref) {
304
352
  return listPhaseFiles(snapshotDir).find((f) => f.replace(/\.md$/, '') === want) || null
305
353
  }
306
354
 
307
- module.exports = { applySpecPlan }
355
+ /**
356
+ * `--hold-state` / `--send-held` as every provider's `apply` reads them: one
357
+ * spec, one of the two, never both. Returns `{ holdState, sendHeld }`, or
358
+ * `{ error }` for the provider to print and exit 1 on.
359
+ */
360
+ function heldFlags(flags, program) {
361
+ const holdState = !!(flags && flags.holdState)
362
+ const sendHeld = !!(flags && flags.sendHeld)
363
+ if (holdState && sendHeld) return { error: `${program} apply: --hold-state and --send-held are two runs, not one` }
364
+ if ((holdState || sendHeld) && flags.all != null) {
365
+ return { error: `${program} apply --all: --hold-state and --send-held act on one spec at a time` }
366
+ }
367
+ return { holdState, sendHeld }
368
+ }
369
+
370
+ /**
371
+ * What the MCP transport adds to its "nothing written" note, so the hand-applied
372
+ * push ends with the same snapshot the API path would record. Null when neither
373
+ * flag is set.
374
+ */
375
+ function heldOverMcp({ holdState, sendHeld }, program) {
376
+ if (holdState) {
377
+ return (
378
+ " --hold-state: apply the plan WITHOUT the spec issue's state, then record with\n" +
379
+ ` \`${program} record <spec> --held\` — run 2 sends the state after the merge.`
380
+ )
381
+ }
382
+ if (sendHeld) {
383
+ return (
384
+ " --send-held: if `plan` is empty, send the spec issue's state alone and record\n" +
385
+ ' nothing — the merged snapshot already says it. If it is not, run 1 held\n' +
386
+ ' nothing: apply it whole and record as usual.'
387
+ )
388
+ }
389
+ return null
390
+ }
391
+
392
+ module.exports = { applySpecPlan, heldFlags, heldOverMcp }