@skitterbyte/skitterspec-linear 19.10.0 → 19.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,389 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * The project guard — is this session about to work on ANOTHER project?
5
+ *
6
+ * A session belongs to the project it was started in. A ta-da list read across
7
+ * every project once ended on another repo's `/spec-complete`, the session ran
8
+ * it, `cd`-ed into that repo and started completing a spec there — work nobody
9
+ * in that project's own sessions could see, from a session whose rules, hooks
10
+ * and context were somebody else's. Reports may still SUGGEST work elsewhere;
11
+ * this is what stops a suggestion becoming an act.
12
+ *
13
+ * WHAT IT REFUSES, and nothing wider:
14
+ * - a write tool whose path lands in another skitterspec project
15
+ * - a `skitterspec …` lifecycle verb, or a git command that changes
16
+ * something, whose directory is another skitterspec project
17
+ * Reads stay open — `git log` there, `skitterspec tada` — and so does every
18
+ * other program: this is a guard on lifecycle work, not a sandbox for the shell.
19
+ *
20
+ * "ANOTHER SKITTERSPEC PROJECT" IS A POSITIVE SIGNAL: a git checkout with a
21
+ * `specs/.core/` folder, which the installer always writes, at or above the
22
+ * path. This repo and every worktree of it share one git common dir and are
23
+ * home. A sibling folder with no `specs/.core` is nobody's project to guard.
24
+ *
25
+ * IT FAILS OPEN. A path git cannot place, a command it cannot parse, a
26
+ * directory that is gone — each allows (`.claude/rules/negative-checks.md`).
27
+ * Being wrong that way costs one unguarded act the skills also warn against;
28
+ * being wrong the other way refuses ordinary work with no reason anyone can see.
29
+ */
30
+
31
+ const fs = require('node:fs')
32
+ const os = require('node:os')
33
+ const path = require('node:path')
34
+
35
+ // Where the lifts live. Gitignored and beside the registry, like the main
36
+ // guard's allow: one person's decision about one session.
37
+ const ALLOW_FILE = 'project-allow.json'
38
+
39
+ // The engine under every name a distribution ships it as.
40
+ const ENGINES = new Set(['skitterspec', 'skitterspec-linear', 'skitterspec-jira', 'skitterspec-github', 'skitterspec-azure-boards'])
41
+
42
+ // git subcommands that only read. Anything else is a change.
43
+ //
44
+ // WHAT WOULD FOOL THIS: an alias (`git co`) or a subcommand added to git later
45
+ // reads as a change and is refused in another project — the strict side, and
46
+ // the refusal names the exit. A read missing from this list costs one
47
+ // `/allow-project`; a write wrongly on it would let the guard be walked past.
48
+ const GIT_READS = new Set([
49
+ 'status', 'log', 'diff', 'show', 'rev-parse', 'ls-files', 'ls-tree', 'blame', 'describe',
50
+ 'shortlog', 'for-each-ref', 'cat-file', 'grep', 'reflog', 'merge-base', 'rev-list', 'name-rev',
51
+ ])
52
+
53
+ // skitterspec verbs that only read, as `verb` or `verb sub`.
54
+ const ENGINE_READS = new Set([
55
+ 'tada', 'todo', 'idea list', 'status', 'help', '--help', '-h', '--version', '-v',
56
+ 'spec-env status', 'spec-env resolve',
57
+ 'epic status', 'epic check', 'gating check', 'spec-sync ownership', 'spec-sync board',
58
+ ])
59
+
60
+ function allowPath(rootDir, config) {
61
+ return path.resolve(rootDir, path.dirname(config.registry), ALLOW_FILE)
62
+ }
63
+
64
+ /** The recorded lifts. Missing or unreadable is none — the strict, safe answer. */
65
+ function readAllows(rootDir, config) {
66
+ try {
67
+ const parsed = JSON.parse(fs.readFileSync(allowPath(rootDir, config), 'utf-8'))
68
+ return Array.isArray(parsed && parsed.allows) ? parsed.allows.filter((a) => a && typeof a === 'object') : []
69
+ } catch {
70
+ return []
71
+ }
72
+ }
73
+
74
+ function writeAllows(rootDir, config, allows) {
75
+ const file = allowPath(rootDir, config)
76
+ fs.mkdirSync(path.dirname(file), { recursive: true })
77
+ fs.writeFileSync(file, JSON.stringify({ allows }, null, 2) + '\n')
78
+ }
79
+
80
+ /**
81
+ * Does a recorded lift cover `project` for `sessionId`? Pure.
82
+ *
83
+ * A lift names the project by its root, or by its folder name when it was typed
84
+ * as a name — and a SESSION lift with no session id to compare does not apply,
85
+ * for the main guard's reason: "cannot tell whose session" must not widen a
86
+ * session lift into a permanent one.
87
+ */
88
+ function liftApplies(lift, project, sessionId) {
89
+ const names = lift.root ? lift.root === project.root : lift.name === project.name
90
+ if (!names) return false
91
+ if (lift.scope === 'repo') return true
92
+ return lift.scope === 'session' && Boolean(sessionId) && lift.session === sessionId
93
+ }
94
+
95
+ function real(p) {
96
+ try {
97
+ return fs.realpathSync.native(p)
98
+ } catch {
99
+ return null
100
+ }
101
+ }
102
+
103
+ /**
104
+ * The skitterspec project a path is in, or null when it is in none.
105
+ *
106
+ * NEAREST EXISTING ANCESTOR first, because a `Write` usually creates its file —
107
+ * and `git -C` on a folder that does not exist yet fails, which read as "no
108
+ * repo" would wave through exactly the new file in another project.
109
+ *
110
+ * @param {string} target
111
+ * @param {(dir: string) => (args: string[]) => string|null} gitAt
112
+ * @returns {{ common, root, name } | null}
113
+ */
114
+ function projectAt(target, gitAt) {
115
+ let at = path.resolve(target)
116
+ while (!fs.existsSync(at)) {
117
+ const up = path.dirname(at)
118
+ if (up === at) return null
119
+ at = up
120
+ }
121
+ if (!fs.statSync(at).isDirectory()) at = path.dirname(at)
122
+ const git = gitAt(at)
123
+ const top = git(['rev-parse', '--show-toplevel'])
124
+ const common = git(['rev-parse', '--path-format=absolute', '--git-common-dir'])
125
+ if (!top || !common) return null
126
+ // A `specs/.core/` between the path and its checkout's top — a project may
127
+ // sit in a subfolder of its repo, so the top alone is not enough to ask.
128
+ let skitterspec = false
129
+ for (let d = at; ; d = path.dirname(d)) {
130
+ if (fs.existsSync(path.join(d, 'specs', '.core'))) {
131
+ skitterspec = true
132
+ break
133
+ }
134
+ if (real(d) === real(top) || path.dirname(d) === d) break
135
+ }
136
+ if (!skitterspec) return null
137
+ const commonReal = real(common.trim())
138
+ if (!commonReal) return null
139
+ // The primary checkout's folder names the project, whichever worktree the
140
+ // path is in — `ereqs`, never `perf-alerts`.
141
+ const root = path.basename(commonReal) === '.git' ? path.dirname(commonReal) : commonReal
142
+ return { common: commonReal, root, name: path.basename(root) }
143
+ }
144
+
145
+ /** The home project's git common dir, or null when it cannot be read. */
146
+ function homeCommon(home, gitAt) {
147
+ const common = gitAt(home)(['rev-parse', '--path-format=absolute', '--git-common-dir'])
148
+ return common ? real(common.trim()) : null
149
+ }
150
+
151
+ function refusal(project, what) {
152
+ return {
153
+ refuse: true,
154
+ project,
155
+ reason:
156
+ `${what} is in ${project.name} (${project.root}), and this session belongs to another project. ` +
157
+ 'A session works on the project it was started in — reports may suggest work elsewhere, ' +
158
+ 'but doing it belongs to a session opened there.\n\n' +
159
+ ` open a session in ${project.root} and run it there\n\n` +
160
+ `If this session really should act on ${project.name}, the USER types /allow-project ${project.name} — ` +
161
+ 'it is theirs to run, not yours.',
162
+ }
163
+ }
164
+
165
+ const ALLOWS = { refuse: false, reason: null }
166
+
167
+ /**
168
+ * Should a write to `target` be refused? `home` is the session's project dir.
169
+ *
170
+ * WHAT WOULD FOOL THIS: a symlink from inside this repo into another one is
171
+ * resolved by git to where it points, so a write through it is judged by the
172
+ * other project — the strict side, and the refusal names the exit.
173
+ */
174
+ function checkPath({ home, target, gitAt, allows = [], sessionId = null }) {
175
+ try {
176
+ const mine = homeCommon(home, gitAt)
177
+ if (!mine) return ALLOWS
178
+ const other = projectAt(target, gitAt)
179
+ if (!other || other.common === mine) return ALLOWS
180
+ if (allows.some((l) => liftApplies(l, other, sessionId))) return ALLOWS
181
+ return refusal(other, `${target}`)
182
+ } catch {
183
+ return ALLOWS
184
+ }
185
+ }
186
+
187
+ /**
188
+ * A shell command split into segments, each with the directory it runs in.
189
+ * Returns null when it cannot be read — unbalanced quotes, a heredoc — and
190
+ * the caller allows.
191
+ *
192
+ * Segments split on `&&`, `||`, `;`, `|` and newlines; a `cd <dir>` moves every
193
+ * later segment, as it does in the shell. Subshell parentheses are dropped,
194
+ * so `(cd x && …)` is read as if it changed the directory for the rest — the
195
+ * strict side, refusing more, never less.
196
+ */
197
+ function segmentsOf(command, cwd) {
198
+ if (typeof command !== 'string') return null
199
+ if (/<<-?\s*['"]?\w+/.test(command)) return null
200
+ const tokens = []
201
+ let cur = ''
202
+ let quote = null
203
+ let has = false
204
+ const push = () => {
205
+ if (has) tokens.push({ word: cur })
206
+ cur = ''
207
+ has = false
208
+ }
209
+ for (let i = 0; i < command.length; i++) {
210
+ const c = command[i]
211
+ if (quote) {
212
+ if (c === quote) quote = null
213
+ else if (c === '\\' && quote === '"' && i + 1 < command.length) cur += command[++i]
214
+ else cur += c
215
+ continue
216
+ }
217
+ if (c === '"' || c === "'") {
218
+ quote = c
219
+ has = true
220
+ } else if (c === '\\' && i + 1 < command.length) {
221
+ cur += command[++i]
222
+ has = true
223
+ } else if (/\s/.test(c) && c !== '\n') {
224
+ push()
225
+ } else if (c === '\n' || c === ';' || c === '(' || c === ')') {
226
+ push()
227
+ tokens.push({ op: true })
228
+ } else if ((c === '&' || c === '|') && command[i + 1] === c) {
229
+ push()
230
+ tokens.push({ op: true })
231
+ i++
232
+ } else if (c === '|' || c === '&') {
233
+ push()
234
+ tokens.push({ op: true })
235
+ } else {
236
+ cur += c
237
+ has = true
238
+ }
239
+ }
240
+ if (quote) return null
241
+ push()
242
+
243
+ const segments = []
244
+ let dir = cwd
245
+ let words = []
246
+ const close = () => {
247
+ if (!words.length) return
248
+ if (words[0] === 'cd' || words[0] === 'pushd') {
249
+ const to = words[1]
250
+ if (to && to !== '-') dir = path.resolve(dir, to.replace(/^~(?=$|\/)/, os.homedir()))
251
+ } else {
252
+ segments.push({ dir, words })
253
+ }
254
+ words = []
255
+ }
256
+ for (const t of tokens) {
257
+ if (t.op) close()
258
+ else words.push(t.word)
259
+ }
260
+ close()
261
+ return segments
262
+ }
263
+
264
+ /**
265
+ * What a segment runs, if it is one this guard is about: `{ kind, dir, verb }`
266
+ * for git or the engine, null for anything else. `dir` is where it acts — its
267
+ * `-C` or `--dir` when it names one.
268
+ */
269
+ function lifecycleOf(seg) {
270
+ let w = seg.words.slice()
271
+ // Leading `VAR=value` assignments and `env` are not the program.
272
+ while (w.length && (/^[A-Za-z_][A-Za-z0-9_]*=/.test(w[0]) || w[0] === 'env')) w.shift()
273
+ // A package runner in front of the engine.
274
+ if (['pnpm', 'npm', 'yarn', 'bunx', 'npx'].includes(w[0])) {
275
+ w = w.slice(1)
276
+ while (w.length && (w[0] === 'exec' || w[0] === 'dlx' || w[0] === 'run' || w[0].startsWith('-'))) w.shift()
277
+ }
278
+ if (!w.length) return null
279
+ const prog = path.basename(w[0]).replace(/\.c?js$/, '')
280
+ if (prog === 'git') {
281
+ let dir = seg.dir
282
+ let i = 1
283
+ for (; i < w.length; i++) {
284
+ if (w[i] === '-C' && w[i + 1]) dir = path.resolve(dir, w[++i])
285
+ else if (w[i] === '-c' && w[i + 1]) i++
286
+ else if (!w[i].startsWith('-')) break
287
+ }
288
+ const sub = w[i] || ''
289
+ const rest = w.slice(i + 1)
290
+ let read = GIT_READS.has(sub)
291
+ if (sub === 'worktree') read = rest[0] === 'list'
292
+ if (sub === 'branch') read = rest.every((a) => ['--show-current', '-a', '-r', '--list', '-v', '-vv', '--all', '--remotes'].includes(a))
293
+ if (sub === 'remote') read = rest.every((a) => a === '-v' || a === 'show' || a === 'get-url')
294
+ if (sub === 'config') read = rest.some((a) => a === '--get' || a === '--list' || a === '-l' || a === '--get-all')
295
+ if (sub === 'stash') read = rest[0] === 'list' || rest[0] === 'show'
296
+ if (sub === 'tag') read = rest.length === 0 || rest.every((a) => a === '-l' || a === '--list' || a.startsWith('--points-at') || a.startsWith('--contains'))
297
+ return read ? null : { kind: 'git', dir, verb: sub }
298
+ }
299
+ if (ENGINES.has(prog)) {
300
+ let dir = seg.dir
301
+ const args = []
302
+ for (let i = 1; i < w.length; i++) {
303
+ if (w[i] === '--dir' && w[i + 1]) dir = path.resolve(dir, w[++i])
304
+ else args.push(w[i])
305
+ }
306
+ const verbs = args.filter((a) => !a.startsWith('--') || ['--help', '--version'].includes(a))
307
+ const one = verbs[0] || 'help'
308
+ const two = verbs.slice(0, 2).join(' ')
309
+ if (ENGINE_READS.has(one) || ENGINE_READS.has(two)) return null
310
+ // `review waiting`, and a guard's own `status`/`check`, read. Lifting a
311
+ // guard in another project (`main allow`, `project allow`) does not.
312
+ if (two === 'spec-env review' && verbs[2] === 'waiting') return null
313
+ if ((two === 'spec-env main' || two === 'spec-env project') && ['status', 'check', undefined].includes(verbs[2])) return null
314
+ // `project` without --name/--category reads.
315
+ if (one === 'project' && !args.some((a) => a === '--name' || a === '--category')) return null
316
+ return { kind: 'skitterspec', dir, verb: two || one }
317
+ }
318
+ return null
319
+ }
320
+
321
+ /**
322
+ * Should `command`, run from `cwd`, be refused?
323
+ *
324
+ * WHAT WOULD FOOL THIS: anything that is not git or the engine — `rm`, `sed -i`,
325
+ * a script that commits for you. Parsing arbitrary shell for its effects cannot
326
+ * be done reliably, so it is not tried; the guard covers lifecycle work and
327
+ * the skills carry the rule for the rest. A variable in a path (`cd $REPO`) is
328
+ * taken literally and lands nowhere real, so it allows.
329
+ */
330
+ function checkCommand({ home, cwd, command, gitAt, allows = [], sessionId = null }) {
331
+ try {
332
+ const mine = homeCommon(home, gitAt)
333
+ if (!mine) return ALLOWS
334
+ const segments = segmentsOf(command, cwd)
335
+ if (!segments) return ALLOWS
336
+ for (const seg of segments) {
337
+ const act = lifecycleOf(seg)
338
+ if (!act) continue
339
+ const other = projectAt(act.dir, gitAt)
340
+ if (!other || other.common === mine) continue
341
+ if (allows.some((l) => liftApplies(l, other, sessionId))) continue
342
+ return refusal(other, `\`${act.kind === 'git' ? 'git' : 'skitterspec'} ${act.verb}\` in ${act.dir}`)
343
+ }
344
+ return ALLOWS
345
+ } catch {
346
+ return ALLOWS
347
+ }
348
+ }
349
+
350
+ /**
351
+ * Record a lift. `what` is a path (judged to its project's root) or a name.
352
+ * Returns the lift written, or `{ error }` when a path names no project.
353
+ */
354
+ function recordLift(rootDir, config, { what, sessionId = null, gitAt, at = null }) {
355
+ let lift
356
+ if (what && (what.includes('/') || what.includes(path.sep) || what === '.' || what === '..')) {
357
+ const project = projectAt(path.resolve(what), gitAt)
358
+ if (!project) return { error: `${what} is not in a skitterspec project` }
359
+ lift = { root: project.root, name: project.name }
360
+ } else {
361
+ lift = { name: what }
362
+ }
363
+ lift = sessionId ? { ...lift, scope: 'session', session: sessionId, at } : { ...lift, scope: 'repo', at }
364
+ const kept = readAllows(rootDir, config).filter((l) => !(l.name === lift.name && l.session === lift.session && l.scope === lift.scope))
365
+ writeAllows(rootDir, config, [...kept, lift])
366
+ return lift
367
+ }
368
+
369
+ /** Clear every lift for `name` (any session). Returns how many were cleared. */
370
+ function clearLift(rootDir, config, name) {
371
+ const all = readAllows(rootDir, config)
372
+ const kept = all.filter((l) => l.name !== name)
373
+ if (kept.length !== all.length) writeAllows(rootDir, config, kept)
374
+ return all.length - kept.length
375
+ }
376
+
377
+ module.exports = {
378
+ ALLOW_FILE,
379
+ allowPath,
380
+ readAllows,
381
+ liftApplies,
382
+ projectAt,
383
+ segmentsOf,
384
+ lifecycleOf,
385
+ checkPath,
386
+ checkCommand,
387
+ recordLift,
388
+ clearLift,
389
+ }
@@ -0,0 +1,50 @@
1
+ 'use strict'
2
+
3
+ const { globToRegExp } = require('./glob.js')
4
+
5
+ /**
6
+ * Decide a list of `{ run, when }` command entries against the files a change
7
+ * brings in — shared by `afterLand` (a land) and `live.afterSwitch` (a live
8
+ * switch), which are the same question asked about two different moves.
9
+ *
10
+ * `range` is those files: a list (possibly empty) when known, null when it is
11
+ * not. Each entry gets a decision — `always` (no `when`), `matched` (with the
12
+ * first path that hit), `skipped`, or `unknown` — and `commands` is every entry
13
+ * but the skipped ones, in config order.
14
+ *
15
+ * AN UNKNOWN RANGE RUNS THE CONDITIONAL ENTRIES. A move made elsewhere, or a
16
+ * diff git would not answer, says nothing about what changed, and only one
17
+ * reading is harmless: a redundant generate costs seconds, a skipped one leaves
18
+ * the tree broken with nothing pointing at why (`.claude/rules/negative-checks.md`
19
+ * rule 4). An EMPTY known range is not unknown — a change that touches no files
20
+ * is healthy, and it skips them.
21
+ */
22
+ function planTriggered(raw, cwd, range = null) {
23
+ const list = Array.isArray(raw) ? raw : []
24
+ const entries = list.map((e) => decide(asEntry(e), range))
25
+ const commands = entries.filter((e) => e.decision !== 'skipped').map((e) => e.run)
26
+ return { cwd: entries.length ? cwd : null, commands, entries, range }
27
+ }
28
+
29
+ function decide(entry, range) {
30
+ if (!entry.when) return { ...entry, decision: 'always', matched: null }
31
+ if (range === null) return { ...entry, decision: 'unknown', matched: null }
32
+ const res = entry.when.map(globToRegExp)
33
+ const matched = range.find((f) => res.some((r) => r.test(f)))
34
+ return matched === undefined
35
+ ? { ...entry, decision: 'skipped', matched: null }
36
+ : { ...entry, decision: 'matched', matched }
37
+ }
38
+
39
+ // Normalised config holds `{ run, when }`; a pure caller may still hand over
40
+ // the plain string an entry is written as.
41
+ function asEntry(entry) {
42
+ return typeof entry === 'string' ? { run: entry, when: null } : { run: entry.run, when: entry.when || null }
43
+ }
44
+
45
+ // The empty form: a blocked or no-op plan, where nothing moved and nothing follows.
46
+ function noTriggered() {
47
+ return { cwd: null, commands: [], entries: [], range: null }
48
+ }
49
+
50
+ module.exports = { planTriggered, noTriggered }
package/src/idea.js ADDED
@@ -0,0 +1,190 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * Ideas — the inbox for work that is not a spec yet.
5
+ *
6
+ * `/spec-idea` captures a thought without grilling it, somewhere the team can
7
+ * see. Where a ticketing provider can hold ideas, it does (an issue kept off
8
+ * the board); everywhere else they live in one file on the base branch,
9
+ * `specs/ideas.md`. This module is the pure half: the file's format, the id
10
+ * an entry is addressed by, the add/drop planners, and the choice of store.
11
+ * Every git call lives in the CLI.
12
+ */
13
+
14
+ const IDEAS_FILE = 'specs/ideas.md'
15
+
16
+ const PREAMBLE = [
17
+ '# Ideas',
18
+ '',
19
+ 'Captured with `/spec-idea`, not specced yet. Promote one with',
20
+ '`/spec idea:<id>`; discard one with `/spec-idea --drop <id>`.',
21
+ '',
22
+ ].join('\n')
23
+
24
+ // `## <id> · <YYYY-MM-DD> · <author>`
25
+ const HEADER = /^## ([a-z0-9][a-z0-9-]*) · (\d{4}-\d{2}-\d{2}) · (.+)$/
26
+
27
+ // The id is part of a commit subject (`docs(ideas): drop <id>`), and the
28
+ // subject line is held to 50 characters.
29
+ const MAX_ID = 30
30
+
31
+ /**
32
+ * Parse `specs/ideas.md`. Everything before the first `## ` line is the
33
+ * preamble and is kept verbatim. A `## ` line that is not an entry header is
34
+ * reported in `malformed` rather than guessed at, because rewriting the file
35
+ * around a hand edit we did not understand would lose it.
36
+ */
37
+ function parseIdeas(text) {
38
+ const lines = String(text || '').split('\n')
39
+ const first = lines.findIndex((line) => line.startsWith('## '))
40
+ const preamble = first === -1 ? lines.join('\n') : lines.slice(0, first).join('\n')
41
+ const entries = []
42
+ const malformed = []
43
+ if (first === -1) return { preamble, entries, malformed }
44
+
45
+ let current = null
46
+ for (const line of lines.slice(first)) {
47
+ if (line.startsWith('## ')) {
48
+ const m = HEADER.exec(line)
49
+ if (!m) {
50
+ malformed.push(line)
51
+ current = null
52
+ continue
53
+ }
54
+ current = { id: m[1], date: m[2], author: m[3].trim(), lines: [] }
55
+ entries.push(current)
56
+ } else if (current) {
57
+ current.lines.push(line)
58
+ }
59
+ }
60
+ return {
61
+ preamble,
62
+ entries: entries.map(({ lines: body, ...rest }) => ({ ...rest, ...splitText(body.join('\n')) })),
63
+ malformed,
64
+ }
65
+ }
66
+
67
+ /** First non-empty line is the title; whatever follows it is the body. */
68
+ function splitText(text) {
69
+ const lines = String(text || '').replace(/\r\n/g, '\n').split('\n')
70
+ const at = lines.findIndex((line) => line.trim())
71
+ if (at === -1) return { title: '', body: '' }
72
+ return { title: lines[at].trim(), body: lines.slice(at + 1).join('\n').trim() }
73
+ }
74
+
75
+ function formatIdeas({ preamble, entries }) {
76
+ const head = (preamble && preamble.trim() ? preamble : PREAMBLE).replace(/\s+$/, '')
77
+ const blocks = entries.map((e) =>
78
+ [`## ${e.id} · ${e.date} · ${e.author}`, e.title, ...(e.body ? [e.body] : [])].join('\n'),
79
+ )
80
+ return [head, ...blocks].join('\n\n') + '\n'
81
+ }
82
+
83
+ /** A short kebab id from the title, unique among `taken`. */
84
+ function ideaId(title, taken = []) {
85
+ const words = String(title || '')
86
+ .toLowerCase()
87
+ .replace(/[^a-z0-9]+/g, ' ')
88
+ .trim()
89
+ .split(/\s+/)
90
+ .filter(Boolean)
91
+ let stem = ''
92
+ for (const word of words) {
93
+ const next = stem ? `${stem}-${word}` : word
94
+ if (next.length > MAX_ID) break
95
+ stem = next
96
+ }
97
+ if (!stem) stem = words.length ? words[0].slice(0, MAX_ID) : 'idea'
98
+ const used = new Set(taken)
99
+ if (!used.has(stem)) return stem
100
+ for (let n = 2; ; n++) {
101
+ const suffix = `-${n}`
102
+ const candidate = `${stem.slice(0, MAX_ID - suffix.length)}${suffix}`
103
+ if (!used.has(candidate)) return candidate
104
+ }
105
+ }
106
+
107
+ function refuseMalformed(parsed) {
108
+ if (!parsed.malformed.length) return null
109
+ return (
110
+ `${IDEAS_FILE} has ${parsed.malformed.length} heading(s) that are not idea entries ` +
111
+ `(first: "${parsed.malformed[0]}") — fix them by hand; nothing was written`
112
+ )
113
+ }
114
+
115
+ /**
116
+ * Plan an add: `{ id, content, message }`, or `{ refused }`. `text` is what
117
+ * was typed — the first line becomes the title.
118
+ */
119
+ function planAdd(current, { text, author, date }) {
120
+ const { title, body } = splitText(text)
121
+ if (!title) return { refused: 'nothing to capture — give the idea some text' }
122
+ const parsed = parseIdeas(current)
123
+ const bad = refuseMalformed(parsed)
124
+ if (bad) return { refused: bad }
125
+ const id = ideaId(title, parsed.entries.map((e) => e.id))
126
+ // A body line that opens with `## ` would read back as an entry header.
127
+ const safe = body.replace(/^(#+ )/gm, '\\$1')
128
+ const entry = { id, date, author: author || 'unknown', title, body: safe }
129
+ return {
130
+ id,
131
+ entry,
132
+ content: formatIdeas({ preamble: parsed.preamble, entries: [...parsed.entries, entry] }),
133
+ message: `docs(ideas): add ${id}\n\n- Capture "${title}" in ${IDEAS_FILE}\n`,
134
+ }
135
+ }
136
+
137
+ /** Plan a drop: `{ id, content, message }`, or `{ refused }`. */
138
+ function planDrop(current, { id, reason }) {
139
+ const parsed = parseIdeas(current)
140
+ const bad = refuseMalformed(parsed)
141
+ if (bad) return { refused: bad }
142
+ const entry = parsed.entries.find((e) => e.id === id)
143
+ if (!entry) return { refused: `no idea "${id}" — \`skitterspec idea list\` shows them` }
144
+ const why = reason && reason.trim() ? reason.trim() : 'no reason given'
145
+ return {
146
+ id,
147
+ entry,
148
+ content: formatIdeas({ preamble: parsed.preamble, entries: parsed.entries.filter((e) => e !== entry) }),
149
+ message: `docs(ideas): drop ${id}\n\n- Discard "${entry.title}": ${why}\n`,
150
+ }
151
+ }
152
+
153
+ // A provider that can hold ideas registers its store here; one that cannot
154
+ // registers `{ supports: false }`. Left unregistered, the answer is unknown.
155
+ let providerIdeaStore
156
+ function setProviderIdeaStore(store) {
157
+ providerIdeaStore = store
158
+ }
159
+ function getProviderIdeaStore() {
160
+ return providerIdeaStore
161
+ }
162
+
163
+ /**
164
+ * Which store holds ideas: `file`, `provider`, or `unknown`.
165
+ *
166
+ * The file is chosen only on a POSITIVE answer — no provider configured, or a
167
+ * provider that registered `supports: false`. A configured provider that said
168
+ * nothing is unknown, and capture refuses instead of writing to the file:
169
+ * filing there while the team reads the tracker would put one idea in each
170
+ * store with nothing to say which is the real one.
171
+ */
172
+ function selectStore({ providerConfigured, store }) {
173
+ if (!providerConfigured) return 'file'
174
+ if (store && store.supports === true) return 'provider'
175
+ if (store && store.supports === false) return 'file'
176
+ return 'unknown'
177
+ }
178
+
179
+ module.exports = {
180
+ IDEAS_FILE,
181
+ parseIdeas,
182
+ formatIdeas,
183
+ splitText,
184
+ ideaId,
185
+ planAdd,
186
+ planDrop,
187
+ selectStore,
188
+ setProviderIdeaStore,
189
+ getProviderIdeaStore,
190
+ }