@skilldeck/craft 0.0.0-stage → 0.1.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,109 @@
1
+ ---
2
+ name: grill
3
+ description: Use when the user asks to be grilled, wants a plan, design, spec or idea stress-tested or poked holes in, says "interrogate this" or "what am I missing", or wants to resume an earlier grilling session from docs/decisions/.
4
+ ---
5
+
6
+ # Grill
7
+
8
+ A plan fails on the questions nobody asked. Grilling asks them, one at a time, each with a recommended answer the user can accept in a word, and writes every outcome to a decision log so the session survives a break, a context reset or a second person. It ends with a summary that [[writing-plans]] can turn into tasks.
9
+
10
+ This is not [[brainstorming]]. Brainstorming shapes a design from a request. Grill attacks a plan or idea that already exists, whether that is a spec, a design doc, a pasted paragraph or a half-formed idea.
11
+
12
+ Announce: "Using grill to stress-test <topic>. One question at a time; decisions go to docs/decisions/<topic>.md."
13
+
14
+ **Script location.** The helper lives in `${CLAUDE_SKILL_DIR}/scripts/`. If `CLAUDE_SKILL_DIR` is not set, use the absolute path of the directory holding this SKILL.md. Below, `$S` is that folder. Node 20+, no dependencies.
15
+
16
+ ## The Rule
17
+
18
+ ```
19
+ One question per message, with a recommended answer.
20
+ Every answer is written to the log before the next question.
21
+ No more than 7 open questions at once.
22
+ ```
23
+
24
+ ## Checklist
25
+
26
+ ```
27
+ - [ ] 1. Opened or resumed the log; goal stated in one sentence
28
+ - [ ] 2. Seeded the frontier (at most the cap) from the plan and the question bank
29
+ - [ ] 3. Asked one question at a time, each with a recommendation; logged every answer
30
+ - [ ] 4. Sent ungrillable questions to a timeboxed prototype
31
+ - [ ] 5. Frontier empty, prototypes settled or deferred
32
+ - [ ] 6. Printed the summary and handed it to writing-plans
33
+ ```
34
+
35
+ ## 1. Open or resume the log
36
+
37
+ ```bash
38
+ node $S/scripts/decision-log.mjs init <topic> --goal "<one sentence>" # creates docs/decisions/<topic>.md
39
+ node $S/scripts/decision-log.mjs status <topic> # where we left off, next question
40
+ ```
41
+
42
+ If the log exists, `init` resumes instead of overwriting. Read the Resolved section aloud in two or three lines so the user knows what is already settled, and do not re-ask any of it. If the goal can't be stated in one sentence, that is your first question.
43
+
44
+ ## 2. Seed the frontier
45
+
46
+ Read the plan, then pick the questions that would hurt most if answered wrong. Pull from `references/question-bank.md` (data, failure modes, users, scale, security, rollout), but only the questions this plan actually raises. A generic checklist is not a grilling.
47
+
48
+ ```bash
49
+ node $S/scripts/decision-log.mjs add <topic> "<question>" --recommend "<your answer>" --domain failure
50
+ ```
51
+
52
+ The frontier holds at most 7 open questions (`--cap` on init to change it). When `add` exits 3, the frontier is full. Resolve, defer or prototype something before adding more. The cap is what keeps the session finishing. Order the frontier by blast radius, putting the questions whose answers change other answers first.
53
+
54
+ ## 3. Ask, one at a time
55
+
56
+ Each message holds exactly one question in this shape:
57
+
58
+ ```
59
+ Q4 (failure modes): What happens to an in-flight checkout when the payment webhook arrives twice?
60
+ Recommended: make the handler idempotent on the provider's event id, stored with a unique index.
61
+ Why it matters: double-charging is the one bug support can't undo.
62
+ Accept, change, or "defer"?
63
+ ```
64
+
65
+ - **Recommend, always.** The user should be able to answer "yes". If you have no recommendation, you haven't thought about it enough, so think first.
66
+ - **Log before moving on.** `resolve <topic> Q4 --answer "..." --why "..."`. Use the user's words for the answer, and fill in the reason they gave or the one they accepted.
67
+ - **Follow the answer.** If an answer opens a sharper question, add it, but only if the frontier has room. Otherwise note it for later in the reply.
68
+ - **Defer out loud.** `defer <topic> Q7 --reason "..."` covers questions that are real but not for this plan. Deferred isn't forgotten, since it appears in the summary.
69
+
70
+ ## 4. Ungrillable questions go to a prototype
71
+
72
+ Some questions can't be settled by talking: "Is the query fast enough?", "Will the SDK let us do X?", "Does this layout read on a phone?" Two rounds of "it depends" is the signal. Stop debating:
73
+
74
+ ```bash
75
+ node $S/scripts/decision-log.mjs prototype <topic> Q5 --probe "p95 of the join on 1M rows < 50ms" --timebox 30m
76
+ ```
77
+
78
+ State the probe as a pass or fail claim. Run it as a spike (the spike path in [[brainstorming]]), in a scratch branch, inside the timebox. Then `resolve` with the measured result. A prototype that runs out of time without an answer is still an answer: resolve it as "unknown, design for the slow case", or defer it.
79
+
80
+ ## 5. Finish and hand off
81
+
82
+ Grilling is done when `status` reports the frontier empty and nothing pending a prototype, or when the user calls time (then the open items are listed as blockers).
83
+
84
+ ```bash
85
+ node $S/scripts/decision-log.mjs summary <topic>
86
+ ```
87
+
88
+ Paste the summary, commit the log (`git add docs/decisions/<topic>.md`), and continue with [[writing-plans]], passing it the summary and the log path. If decisions changed the design itself, update the spec first.
89
+
90
+ ## Output
91
+
92
+ ```
93
+ Grill summary: <topic> (log: docs/decisions/<topic>.md)
94
+ Decisions: <n> Deferred: <n> Prototypes run: <n> Still open: <n>
95
+ <summary block from the script>
96
+ Next: writing-plans with this summary
97
+ ```
98
+
99
+ ## Red flags
100
+
101
+ | Thought | Reality |
102
+ |---|---|
103
+ | "I'll batch five questions to save time." | Batched questions get batched, shallow answers. One per message. |
104
+ | "I'll ask what they think first, then give my view." | An open question costs the user effort; a recommendation costs them one word. Recommend. |
105
+ | "I'll remember the answers and log them at the end." | The log is the state. A reset loses everything you were holding in your head. |
106
+ | "The frontier is full, but this one's important." | Then something open is less important: defer it. The cap is what makes the session end. |
107
+ | "We've argued it three times, one more round." | It's ungrillable. Timebox a prototype. |
108
+ | "Let me run the whole question bank." | Ask only what this plan raises. Irrelevant questions burn the user's patience for the ones that matter. |
109
+ | "Grilling's done, I'll start coding." | Hand the summary to [[writing-plans]] first. Code comes after the plan. |
@@ -0,0 +1,75 @@
1
+ # Question bank
2
+
3
+ Raw material for seeding the frontier. **Do not run through it top to bottom.** Pick the few questions this plan actually raises, rewrite them in the plan's own nouns, and attach a recommendation to each. A question with no recommendation isn't ready to ask yet.
4
+
5
+ Each entry gives the question, what a weak answer sounds like, and a typical recommendation to adapt.
6
+
7
+ ## Data
8
+
9
+ | Question | Weak answer | Typical recommendation |
10
+ |---|---|---|
11
+ | What is the source of truth for <entity>, and who else keeps a copy? | "We'll sync them." | One owner; others read through it or hold a cache with a stated staleness bound. |
12
+ | What happens to existing rows when this ships? | "It's a new column." | Nullable or defaulted column, backfill in batches, then tighten the constraint (see the migrate pack). |
13
+ | Which fields are required, and what does the system do when one is missing? | "It's always set." | Validate at the boundary and reject with a named error; never default silently. |
14
+ | How do two concurrent writers to the same <entity> resolve? | "Unlikely to happen." | Optimistic version column, or a unique constraint that turns the race into a clean error. |
15
+ | How long is the data kept, and how is it deleted? | "Forever." | A stated retention period, plus a delete path that also covers backups and derived stores. |
16
+ | Is any of this data personal or regulated? | "Not really." | List the fields; decide encryption, access and export/delete handling up front. |
17
+
18
+ ## Failure modes
19
+
20
+ | Question | Weak answer | Typical recommendation |
21
+ |---|---|---|
22
+ | What happens when <dependency> is down or slow? | "It's reliable." | A timeout, plus a stated degraded behavior (cached, queued, or failing closed with a message). |
23
+ | What if this runs twice? | "It won't." | Idempotency key or natural unique key; at-least-once delivery is the default everywhere. |
24
+ | What if it stops halfway? | "Transactions." | Name the step boundary; make each step resumable or compensatable. |
25
+ | How will we know it's broken before a user tells us? | "Logs." | One metric or alert per user-visible promise, with a named threshold. |
26
+ | What is the blast radius of a bad deploy? | "We'll be careful." | A flag or percentage rollout, plus a rollback that doesn't need a migration. |
27
+ | What input breaks it? | "We validate." | Name the three nastiest inputs (empty, huge, malformed) and the response to each. |
28
+
29
+ ## Users
30
+
31
+ | Question | Weak answer | Typical recommendation |
32
+ |---|---|---|
33
+ | Who exactly uses this first, and what are they doing right before? | "Everyone." | One named persona and the trigger moment; design for them, accept rough edges elsewhere. |
34
+ | What does the user see while it's working, and when it fails? | "A spinner." | A specific loading, empty and error state for each screen or response. |
35
+ | What is the smallest version a user would actually use? | "All of it." | Cut to the one flow that proves value; list the rest as deferred. |
36
+ | How does an existing user discover the change, and can they undo it? | "They'll notice." | An in-context hint or changelog entry, and a reversible setting where behavior changes. |
37
+ | What does success look like in numbers, one month after launch? | "People like it." | One leading metric and the target that would make us keep it. |
38
+
39
+ ## Scale
40
+
41
+ | Question | Weak answer | Typical recommendation |
42
+ |---|---|---|
43
+ | What are the expected and the worst-case volumes (rows, requests per second, payload size)? | "Not much." | Write both numbers down; design for 10x expected, and test at the worst case. |
44
+ | Which operation grows with the data rather than with the request? | "None." | Find the N+1, the full scan, the unbounded list; paginate or index it now. |
45
+ | Where is the first bottleneck? | "The database, probably." | Name it, and name the measurement that would show it (this is often a prototype). |
46
+ | What is the cost per unit at 10x? | "Cheap." | Rough per-request or per-user cost, including third-party API calls. |
47
+ | What has to happen synchronously, and what can be queued? | "All of it, synchronously." | Keep the user-facing path minimal; queue the rest, with a visible status. |
48
+
49
+ ## Security
50
+
51
+ | Question | Weak answer | Typical recommendation |
52
+ |---|---|---|
53
+ | Who is allowed to do this, and where is that checked? | "Logged-in users." | One authorization check at the boundary, tested with a denied case. |
54
+ | Can a user reach another tenant's or user's data by changing an id? | "IDs are random." | Scope every query by the caller's tenant or user; add a test that tries it. |
55
+ | What secrets does this need, and where do they live? | "An env var." | A secret store, with rotation and a scope no wider than this feature. |
56
+ | What untrusted input reaches a query, a shell, a template or a URL fetch? | "We sanitize." | Parameterize queries and use allow-lists; name each sink explicitly. |
57
+ | What gets logged, and does any of it contain tokens or personal data? | "Request bodies." | Log ids and outcomes, never secrets; redact named fields. |
58
+ | What is the abuse case (spam, scraping, cost amplification)? | "Rate limits, later." | A rate limit, and a quota on the most expensive operation, from day one. |
59
+
60
+ ## Rollout
61
+
62
+ | Question | Weak answer | Typical recommendation |
63
+ |---|---|---|
64
+ | How does it ship dark and turn on gradually? | "Merge and deploy." | A flag, then internal users, then a percentage, then everyone, with a named owner. |
65
+ | What has to be deployed in which order (schema, backend, clients)? | "Together." | Expand, then migrate, then contract; old clients keep working at every step. |
66
+ | How do we roll back, and what data does rollback strand? | "Revert the commit." | A rollback that leaves data readable by the old code, rehearsed once. |
67
+ | Who needs to know before launch (support, docs, sales, on-call)? | "We'll announce it." | List them with the date each needs to know. |
68
+ | What is the kill criterion? | "We'll see." | The metric threshold or incident count that turns the flag off with no debate. |
69
+
70
+ ## Writing a good question
71
+
72
+ - **Specific nouns.** "What happens when Stripe retries `invoice.paid`?" rather than "How do we handle webhooks?"
73
+ - **One decision per question.** If the answer would be "yes to the first part, no to the second", split it.
74
+ - **Recommendation first, reasons second.** The user decides faster when the default is visible.
75
+ - **Prefer questions whose answers change the design.** If every possible answer leads to the same code, skip the question.
@@ -0,0 +1,334 @@
1
+ #!/usr/bin/env node
2
+ // craft / decision-log.mjs
3
+ //
4
+ // A living, resumable decision log for a grilling session. One Markdown file per
5
+ // topic at docs/decisions/<topic>.md with four sections: Resolved, Open frontier,
6
+ // Deferred, Prototype-needed. The file is the state: humans can read and edit it,
7
+ // and this script parses it back. The open frontier is capped (default 7) so a
8
+ // session can't sprawl: resolve, defer or prototype before adding more.
9
+ //
10
+ // node decision-log.mjs init <topic> [--goal "..."] [--cap 7]
11
+ // node decision-log.mjs add <topic> "<question>" [--recommend "..."] [--domain data]
12
+ // node decision-log.mjs resolve <topic> <Q#> --answer "..." [--why "..."]
13
+ // node decision-log.mjs defer <topic> <Q#> --reason "..."
14
+ // node decision-log.mjs prototype <topic> <Q#> --probe "..." [--timebox 30m]
15
+ // node decision-log.mjs status <topic> [--json]
16
+ // node decision-log.mjs summary <topic>
17
+ //
18
+ // Every command takes --dir <folder> (default docs/decisions) or --file <path>.
19
+ // Exit 0 on success, 1 on a missing log or unknown id, 2 on bad usage,
20
+ // 3 when adding would exceed the frontier cap.
21
+ // Zero dependencies. Node 20+.
22
+
23
+ import fs from 'node:fs'
24
+ import path from 'node:path'
25
+ import { pathToFileURL } from 'node:url'
26
+
27
+ const HELP = `decision-log: a resumable decision log for grilling a plan
28
+
29
+ node decision-log.mjs init <topic> [--goal "..."] [--cap 7]
30
+ node decision-log.mjs add <topic> "<question>" [--recommend "..."] [--domain <d>]
31
+ node decision-log.mjs resolve <topic> <Q#> --answer "..." [--why "..."]
32
+ node decision-log.mjs defer <topic> <Q#> --reason "..."
33
+ node decision-log.mjs prototype <topic> <Q#> --probe "..." [--timebox 30m]
34
+ node decision-log.mjs status <topic> [--json] counts, frontier, next question
35
+ node decision-log.mjs summary <topic> hand-off block for writing-plans
36
+
37
+ --dir <folder> where logs live (default docs/decisions)
38
+ --file <path> explicit log path (overrides --dir)
39
+
40
+ The open frontier is capped (default 7). "add" exits 3 when it is full:
41
+ resolve, defer or prototype an open question first.
42
+ `
43
+
44
+ export const SECTIONS = ['Resolved', 'Open frontier', 'Deferred', 'Prototype-needed']
45
+ export const DEFAULT_CAP = 7
46
+
47
+ const FIELD_ORDER = ['domain', 'recommended', 'answer', 'why', 'reason', 'probe', 'timebox', 'raised', 'closed']
48
+
49
+ export function slugify(topic) {
50
+ const s = String(topic)
51
+ .toLowerCase()
52
+ .replace(/[^a-z0-9]+/g, '-')
53
+ .replace(/^-+|-+$/g, '')
54
+ if (!s) throw new Error('topic must contain letters or digits')
55
+ return s
56
+ }
57
+
58
+ const today = () => new Date().toISOString().slice(0, 10)
59
+ const oneLine = (v) => String(v ?? '').replace(/\s*\n\s*/g, ' ').trim()
60
+
61
+ /** A fresh, empty log. */
62
+ export function createLog(topic, { goal = '', cap = DEFAULT_CAP, date = today() } = {}) {
63
+ if (!Number.isInteger(cap) || cap < 1) throw new Error('cap must be a positive integer')
64
+ return { topic: slugify(topic), goal: oneLine(goal), cap, started: date, updated: date, items: [] }
65
+ }
66
+
67
+ /** Render a log to Markdown. parseLog(renderLog(x)) round-trips. */
68
+ export function renderLog(log) {
69
+ const L = []
70
+ L.push(`# Decisions: ${log.topic}`, '')
71
+ L.push(`- **Topic:** ${log.topic}`)
72
+ L.push(`- **Goal:** ${log.goal || '(not stated yet)'}`)
73
+ L.push(`- **Frontier cap:** ${log.cap}`)
74
+ L.push(`- **Started:** ${log.started}`)
75
+ L.push(`- **Updated:** ${log.updated}`)
76
+ L.push('')
77
+ L.push('<!-- Managed by craft/grill decision-log.mjs. Edit freely; keep the "### Q<n>." headings and "- key: value" lines. -->')
78
+ for (const section of SECTIONS) {
79
+ L.push('', `## ${section}`, '')
80
+ const items = log.items.filter((i) => i.section === section).sort((a, b) => a.id - b.id)
81
+ if (!items.length) L.push('_none_')
82
+ for (const item of items) {
83
+ L.push(`### Q${item.id}. ${item.question}`)
84
+ for (const k of FIELD_ORDER) if (item.fields[k]) L.push(`- ${k}: ${item.fields[k]}`)
85
+ for (const [k, v] of Object.entries(item.fields)) if (!FIELD_ORDER.includes(k) && v) L.push(`- ${k}: ${v}`)
86
+ L.push('')
87
+ }
88
+ if (L[L.length - 1] === '') L.pop()
89
+ }
90
+ return L.join('\n') + '\n'
91
+ }
92
+
93
+ /** Parse a log written by renderLog (or hand-edited in the same shape). */
94
+ export function parseLog(text) {
95
+ const log = { topic: '', goal: '', cap: DEFAULT_CAP, started: '', updated: '', items: [] }
96
+ let section = null
97
+ let item = null
98
+ for (const raw of text.split(/\r?\n/)) {
99
+ const line = raw.trimEnd()
100
+ let m
101
+ if ((m = /^# Decisions:\s*(.+)$/.exec(line))) log.topic = m[1].trim()
102
+ else if ((m = /^- \*\*(Topic|Goal|Frontier cap|Started|Updated):\*\*\s*(.*)$/.exec(line)) && !section) {
103
+ const v = m[2].trim()
104
+ if (m[1] === 'Topic') log.topic = v
105
+ if (m[1] === 'Goal') log.goal = v === '(not stated yet)' ? '' : v
106
+ if (m[1] === 'Frontier cap') log.cap = Number.parseInt(v, 10) || DEFAULT_CAP
107
+ if (m[1] === 'Started') log.started = v
108
+ if (m[1] === 'Updated') log.updated = v
109
+ } else if ((m = /^## (.+)$/.exec(line))) {
110
+ const name = m[1].trim()
111
+ section = SECTIONS.find((s) => s.toLowerCase() === name.toLowerCase()) ?? null
112
+ item = null
113
+ } else if ((m = /^### Q(\d+)\.\s*(.*)$/.exec(line)) && section) {
114
+ item = { id: Number(m[1]), question: m[2].trim(), section, fields: {} }
115
+ log.items.push(item)
116
+ } else if ((m = /^- ([a-z][\w-]*):\s?(.*)$/.exec(line)) && item) item.fields[m[1]] = m[2].trim()
117
+ }
118
+ log.items.sort((a, b) => a.id - b.id)
119
+ const ids = log.items.map((i) => i.id)
120
+ const dup = ids.find((id, i) => ids.indexOf(id) !== i)
121
+ if (dup !== undefined) throw new Error(`duplicate question id Q${dup}`)
122
+ return log
123
+ }
124
+
125
+ const open = (log) => log.items.filter((i) => i.section === 'Open frontier')
126
+
127
+ function find(log, ref) {
128
+ const id = Number(String(ref).replace(/^Q/i, ''))
129
+ const item = log.items.find((i) => i.id === id)
130
+ if (!item) throw Object.assign(new Error(`no question ${ref} in ${log.topic}`), { code: 'ENOID' })
131
+ return item
132
+ }
133
+
134
+ /** Add a question to the open frontier. Throws code EFRONTIER when the cap is reached. */
135
+ export function addQuestion(log, question, { recommend = '', domain = '', date = today() } = {}) {
136
+ const q = oneLine(question)
137
+ if (!q) throw new Error('question is empty')
138
+ if (open(log).length >= log.cap) {
139
+ throw Object.assign(
140
+ new Error(`frontier is full (${open(log).length}/${log.cap}): resolve, defer or prototype an open question before adding another`),
141
+ { code: 'EFRONTIER' },
142
+ )
143
+ }
144
+ const id = log.items.reduce((m, i) => Math.max(m, i.id), 0) + 1
145
+ const fields = {}
146
+ if (oneLine(domain)) fields.domain = oneLine(domain)
147
+ if (oneLine(recommend)) fields.recommended = oneLine(recommend)
148
+ fields.raised = date
149
+ const item = { id, question: q, section: 'Open frontier', fields }
150
+ log.items.push(item)
151
+ log.updated = date
152
+ return item
153
+ }
154
+
155
+ function move(log, ref, section, fields, date) {
156
+ const item = find(log, ref)
157
+ item.section = section
158
+ for (const [k, v] of Object.entries(fields)) if (v !== undefined && v !== '') item.fields[k] = oneLine(v)
159
+ log.updated = date
160
+ return item
161
+ }
162
+
163
+ export function resolveQuestion(log, ref, { answer, why = '', date = today() } = {}) {
164
+ if (!oneLine(answer)) throw new Error('resolve needs --answer')
165
+ return move(log, ref, 'Resolved', { answer, why, closed: date }, date)
166
+ }
167
+
168
+ export function deferQuestion(log, ref, { reason, date = today() } = {}) {
169
+ if (!oneLine(reason)) throw new Error('defer needs --reason')
170
+ return move(log, ref, 'Deferred', { reason }, date)
171
+ }
172
+
173
+ export function markPrototype(log, ref, { probe, timebox = '30m', date = today() } = {}) {
174
+ if (!oneLine(probe)) throw new Error('prototype needs --probe (what the prototype must show)')
175
+ return move(log, ref, 'Prototype-needed', { probe, timebox }, date)
176
+ }
177
+
178
+ export function status(log) {
179
+ const by = Object.fromEntries(SECTIONS.map((s) => [s, log.items.filter((i) => i.section === s)]))
180
+ const frontier = by['Open frontier'].sort((a, b) => a.id - b.id)
181
+ return {
182
+ topic: log.topic,
183
+ goal: log.goal,
184
+ cap: log.cap,
185
+ counts: Object.fromEntries(SECTIONS.map((s) => [s, by[s].length])),
186
+ frontierFull: frontier.length >= log.cap,
187
+ next: frontier[0] ? { id: `Q${frontier[0].id}`, question: frontier[0].question, recommended: frontier[0].fields.recommended || '' } : null,
188
+ frontier: frontier.map((i) => ({ id: `Q${i.id}`, question: i.question, recommended: i.fields.recommended || '' })),
189
+ done: frontier.length === 0 && by['Prototype-needed'].length === 0,
190
+ }
191
+ }
192
+
193
+ /** The hand-off block a grilling session ends with, ready for writing-plans. */
194
+ export function summary(log) {
195
+ const s = (name) => log.items.filter((i) => i.section === name).sort((a, b) => a.id - b.id)
196
+ const L = [`## Grill summary: ${log.topic}`, '']
197
+ if (log.goal) L.push(`**Goal:** ${log.goal}`, '')
198
+ L.push('**Decisions**')
199
+ for (const i of s('Resolved')) L.push(`- Q${i.id} ${i.question} -> ${i.fields.answer}${i.fields.why ? ` (why: ${i.fields.why})` : ''}`)
200
+ if (!s('Resolved').length) L.push('- none yet')
201
+ const rest = [
202
+ ['Still open (blocks planning)', s('Open frontier'), (i) => (i.fields.recommended ? `recommended: ${i.fields.recommended}` : '')],
203
+ ['Needs a prototype first', s('Prototype-needed'), (i) => `probe: ${i.fields.probe}, timebox ${i.fields.timebox}`],
204
+ ['Deferred (out of scope for this plan)', s('Deferred'), (i) => `reason: ${i.fields.reason}`],
205
+ ]
206
+ for (const [title, items, note] of rest) {
207
+ if (!items.length) continue
208
+ L.push('', `**${title}**`)
209
+ for (const i of items) {
210
+ const n = note(i)
211
+ L.push(`- Q${i.id} ${i.question}${n ? ` (${n})` : ''}`)
212
+ }
213
+ }
214
+ L.push('', `Source: docs/decisions/${log.topic}.md`)
215
+ return L.join('\n') + '\n'
216
+ }
217
+
218
+ // ---------------------------------------------------------------------------
219
+ // CLI
220
+ // ---------------------------------------------------------------------------
221
+
222
+ function parseArgs(argv) {
223
+ const valued = new Set(['--dir', '--file', '--goal', '--cap', '--recommend', '--domain', '--answer', '--why', '--reason', '--probe', '--timebox'])
224
+ const opts = {}
225
+ const pos = []
226
+ for (let i = 0; i < argv.length; i++) {
227
+ const a = argv[i]
228
+ if (valued.has(a)) opts[a.slice(2)] = argv[++i]
229
+ else if (a.startsWith('--')) opts[a.slice(2)] = true
230
+ else pos.push(a)
231
+ }
232
+ return { opts, pos }
233
+ }
234
+
235
+ function logPath(topic, opts) {
236
+ if (opts.file) return path.resolve(opts.file)
237
+ return path.resolve(opts.dir ?? path.join('docs', 'decisions'), `${slugify(topic)}.md`)
238
+ }
239
+
240
+ function load(file) {
241
+ if (!fs.existsSync(file)) throw Object.assign(new Error(`no log at ${file}; run "init" first`), { code: 'ENOLOG' })
242
+ return parseLog(fs.readFileSync(file, 'utf8'))
243
+ }
244
+
245
+ function save(file, log) {
246
+ fs.mkdirSync(path.dirname(file), { recursive: true })
247
+ fs.writeFileSync(file, renderLog(log))
248
+ }
249
+
250
+ function printStatus(st, file) {
251
+ const c = st.counts
252
+ console.log(`${st.topic}: ${c['Resolved']} resolved, ${c['Open frontier']}/${st.cap} open, ${c['Deferred']} deferred, ${c['Prototype-needed']} prototype-needed`)
253
+ console.log(`log: ${file}`)
254
+ if (st.goal) console.log(`goal: ${st.goal}`)
255
+ if (st.frontier.length) {
256
+ console.log('\nOpen frontier:')
257
+ for (const q of st.frontier) console.log(` ${q.id} ${q.question}${q.recommended ? `\n recommended: ${q.recommended}` : ''}`)
258
+ }
259
+ if (st.next) console.log(`\nNext: ${st.next.id} ${st.next.question}`)
260
+ else if (st.done) console.log('\nFrontier empty and no prototypes pending: ready for the summary hand-off.')
261
+ else console.log('\nFrontier empty; prototypes still pending.')
262
+ if (st.frontierFull) console.log('Frontier is at its cap: resolve, defer or prototype before adding.')
263
+ }
264
+
265
+ export function main(argv) {
266
+ if (!argv.length || argv.includes('--help') || argv.includes('-h')) {
267
+ process.stdout.write(HELP)
268
+ return argv.length ? 0 : 2
269
+ }
270
+ const { opts, pos } = parseArgs(argv)
271
+ const [cmd, topic, third] = pos
272
+ if (!topic) {
273
+ process.stderr.write(`decision-log: "${cmd}" needs a <topic>\n`)
274
+ return 2
275
+ }
276
+ try {
277
+ const file = logPath(topic, opts)
278
+ switch (cmd) {
279
+ case 'init': {
280
+ if (fs.existsSync(file)) {
281
+ console.log(`exists: ${file} (resuming)`)
282
+ printStatus(status(load(file)), file)
283
+ return 0
284
+ }
285
+ const cap = opts.cap === undefined ? DEFAULT_CAP : Number(opts.cap)
286
+ save(file, createLog(topic, { goal: opts.goal, cap }))
287
+ console.log(`created: ${file}`)
288
+ return 0
289
+ }
290
+ case 'add': {
291
+ if (!third) throw Object.assign(new Error('add needs a "<question>"'), { code: 'EUSAGE' })
292
+ const log = load(file)
293
+ const item = addQuestion(log, third, { recommend: opts.recommend, domain: opts.domain })
294
+ save(file, log)
295
+ console.log(`added Q${item.id} (${open(log).length}/${log.cap} open)`)
296
+ return 0
297
+ }
298
+ case 'resolve':
299
+ case 'defer':
300
+ case 'prototype': {
301
+ if (!third) throw Object.assign(new Error(`${cmd} needs a question id like Q3`), { code: 'EUSAGE' })
302
+ const log = load(file)
303
+ const item =
304
+ cmd === 'resolve'
305
+ ? resolveQuestion(log, third, { answer: opts.answer, why: opts.why })
306
+ : cmd === 'defer'
307
+ ? deferQuestion(log, third, { reason: opts.reason })
308
+ : markPrototype(log, third, { probe: opts.probe, timebox: opts.timebox })
309
+ save(file, log)
310
+ console.log(`Q${item.id} -> ${item.section} (${open(log).length}/${log.cap} open)`)
311
+ return 0
312
+ }
313
+ case 'status': {
314
+ const st = status(load(file))
315
+ if (opts.json) console.log(JSON.stringify({ file, ...st }, null, 2))
316
+ else printStatus(st, file)
317
+ return 0
318
+ }
319
+ case 'summary':
320
+ process.stdout.write(summary(load(file)))
321
+ return 0
322
+ default:
323
+ process.stderr.write(`decision-log: unknown command "${cmd}"\n${HELP}`)
324
+ return 2
325
+ }
326
+ } catch (err) {
327
+ process.stderr.write(`decision-log: ${err.message}\n`)
328
+ if (err.code === 'EFRONTIER') return 3
329
+ if (err.code === 'EUSAGE') return 2
330
+ return 1
331
+ }
332
+ }
333
+
334
+ if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) process.exitCode = main(process.argv.slice(2))
@@ -0,0 +1,110 @@
1
+ ---
2
+ name: tdd-loop
3
+ description: Use when the user asks to TDD something, pair on red-green-refactor, or drive a specific change test by test, when you need to choose test seams for code that is awkward to test, or when deciding whether TDD fits a change at all.
4
+ ---
5
+
6
+ # TDD Loop
7
+
8
+ [[test-first]] is the rule: no production code without a failing test that demands it. This skill is the hands-on driver for that rule. It decides whether TDD fits, agrees on where the tests attach before any are written, and then runs tight loops in which each step leaves evidence: pasted red output, then green, then a refactor.
9
+
10
+ Announce: "Using tdd-loop to drive <change>, one behavior per loop."
11
+
12
+ ## The Rule
13
+
14
+ ```
15
+ Fit-check first. Seams confirmed before the first test.
16
+ Paste the failing output before writing any implementation.
17
+ One behavior per loop. Refactor only at green.
18
+ ```
19
+
20
+ ## Checklist
21
+
22
+ ```
23
+ - [ ] 1. Fit-check done: TDD fits, or the alternative is stated and agreed
24
+ - [ ] 2. Overlap check: sibling tests and open tickets read
25
+ - [ ] 3. Seams proposed, each with an example test; user confirmed
26
+ - [ ] 4. Behavior list written, smallest first
27
+ - [ ] 5. Each loop: red (pasted), green (minimal), refactor, commit
28
+ - [ ] 6. Full suite green; loop log reported
29
+ ```
30
+
31
+ ## 1. Fit-check
32
+
33
+ Say which case applies and why, in one sentence:
34
+
35
+ | Change | TDD fits? | Instead |
36
+ |---|---|---|
37
+ | Pure logic, parsing, calculations, state machines, validation | **Yes**, the best case | — |
38
+ | Module boundary, HTTP handler, CLI command, repository | **Yes**, at a seam (step 3) | — |
39
+ | Bugfix with a reproducible trigger | **Yes**: the first red test reproduces the bug | — |
40
+ | UI glue, layout, styling, animation | Usually no | Extract the logic into a pure function and TDD that; check the view by eye or with a screenshot or story |
41
+ | Config, wiring, dependency bumps, infra | No | A smoke check: boot the app or run the command, and state the expected output |
42
+ | Exploratory spike | No | Timebox it, throw it away, then TDD the real version (the spike path in [[brainstorming]]) |
43
+ | Generated code | No | Test the generator, or the output contract |
44
+
45
+ When TDD doesn't fit, say what you'll do instead and get an OK. That exception belongs to [[test-first]], so don't grant it to yourself.
46
+
47
+ ## 2. Check for overlap
48
+
49
+ Before proposing tests, read what already exists:
50
+ - **Sibling tests.** Search the test folder for the module, the function and the domain noun. Extend an existing `describe` rather than starting a parallel file, and don't re-test behavior that's already covered.
51
+ - **Tickets and plan.** If a plan in `docs/plans/` or a linked ticket names this behavior, use its acceptance criteria as your behavior list. If another open ticket touches the same code, say so now, before both changes collide.
52
+ - **Test command.** Find the exact command that runs one test, and paste it.
53
+
54
+ ## 3. Propose seams, then wait
55
+
56
+ A seam is the place where the test touches the code: what it calls, and what it substitutes. For each seam, show a concrete example test in the project's own framework and say what it substitutes. `references/seams.md` has patterns for pure functions, module boundaries, HTTP handlers, CLIs and DB repositories.
57
+
58
+ ```
59
+ Seam 1, pure function: priceFor(cart, rules) -> Money. Nothing substituted.
60
+ test("applies the bulk discount at 10 units", () => {
61
+ expect(priceFor(cart({ sku: "A", qty: 10 }), rules)).toEqual(money(90))
62
+ })
63
+ Seam 2, HTTP handler via app.inject. Repository faked in memory; clock injected.
64
+ ...
65
+ Confirm these seams, or adjust?
66
+ ```
67
+
68
+ **Stop and wait for confirmation.** A seam chosen badly means every test in this change is coupled to the wrong thing. If the code has no seam (hard-coded `new Date()`, a global client, a module-level singleton), the first loop creates one through a parameter or a constructor argument, and that loop's test comes first like any other.
69
+
70
+ ## 4. Behavior list
71
+
72
+ Write the behaviors as test names, simplest first, and keep the list visible: `returns empty for empty cart`, `sums line items`, `applies bulk discount at 10`, `rejects negative qty`. Each loop crosses one off. New ideas go to the bottom of the list. They don't go into the current loop.
73
+
74
+ ## 5. The loop
75
+
76
+ For each behavior:
77
+
78
+ 1. **Red.** Write one test. Run the single-test command. **Paste the failing output**, the assertion line included. It must fail for the stated reason: an assertion on the missing behavior. An import error, a typo or a fixture crash doesn't count. A test that passes on the first run means the behavior already exists or the test is wrong. Fix the test, or cross the behavior off.
79
+ 2. **Green.** Write the least code that makes it pass. Hard-coding is fine if the next behavior will force generality. Run the test, then the file, and paste the pass line.
80
+ 3. **Refactor, at green only.** Remove duplication, fix names, extract a helper. Re-run after each change. Never refactor while red, and never change behavior while refactoring.
81
+ 4. **Commit.** One behavior, one commit: `test+feat: <behavior>`.
82
+
83
+ No implementation edit happens without a red output pasted above it in the conversation. That paste is the proof of the rule.
84
+
85
+ ## Output
86
+
87
+ ```
88
+ TDD loop: <change>
89
+ Seams: <seam list> Command: <single-test command>
90
+ | # | Behavior | Red (failure reason) | Green | Refactor |
91
+ |---|---|---|---|---|
92
+ | 1 | returns empty for empty cart | expected [] got undefined | pass | none |
93
+ | 2 | sums line items | expected 30 got 0 | pass | extracted lineTotal |
94
+ Suite: <n> passed, 0 failed
95
+ Not covered by TDD (agreed): <items + how they were checked>
96
+ ```
97
+
98
+ Before claiming the change is done, run the full suite and follow [[verify-before-done]].
99
+
100
+ ## Red flags
101
+
102
+ | Thought | Reality |
103
+ |---|---|
104
+ | "I'll write the test and the code together, it's quicker." | Then you never saw red. Paste the failure first. |
105
+ | "This test can cover three behaviors." | One behavior per loop. When it fails, you should know why from its name. |
106
+ | "The seams are obvious, I'll skip the confirmation." | Obvious to you. Confirming takes one message; rewriting a whole suite takes much longer. |
107
+ | "I'll clean this up while I'm making it pass." | Green first, then refactor. Mixing the two hides which change broke what. |
108
+ | "There's probably no existing test for this." | Search before writing. A duplicate test doubles the maintenance and fragments the spec. |
109
+ | "It's UI, so no tests at all." | Pull the logic out and TDD that; check the view by eye. |
110
+ | "The test failed with an import error, that's red." | That's a broken test. Red means an assertion on the missing behavior. |