@skitterbyte/skitterspec-linear 19.8.0 → 19.9.1

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,145 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * A repo's side of the ta-da list: the author's commits in the window, which
5
+ * branches hold each one, and the tickets its specs carry. Every git call
6
+ * goes through an injected reader — `(args) => stdout | null` — so this is
7
+ * testable against a throwaway repo and never shells out on its own.
8
+ */
9
+
10
+ const { readTicket } = require('../env/resolve.js')
11
+ const { BUCKETS } = require('./specs.js')
12
+
13
+ const RS = '\x1e'
14
+ const US = '\x1f'
15
+
16
+ // Past this many commits in one window the per-commit branch lookup is the
17
+ // slow half; the commits are still listed, attributed by their files alone.
18
+ const CONTAINS_CAP = 200
19
+
20
+ const escapeRegex = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
21
+
22
+ /**
23
+ * Who "you" are in this repo: its own `user.email`, else `user.name`. Read per
24
+ * repo because a work repo and a personal one often carry different
25
+ * identities. Null is cannot-tell — the caller says so rather than reporting
26
+ * a day with no commits.
27
+ */
28
+ function authorOf(git) {
29
+ const email = git(['config', 'user.email'])
30
+ if (email) return { match: escapeRegex(email), who: email }
31
+ const name = git(['config', 'user.name'])
32
+ if (name) return { match: escapeRegex(name), who: name }
33
+ return null
34
+ }
35
+
36
+ /**
37
+ * The author's non-merge commits in the window, on any ref, each with the
38
+ * files it touched and its `Refs:` trailers.
39
+ *
40
+ * @returns {Array<{ sha, at, subject, refs: string[], files }>|null}
41
+ * null when git could not be read at all
42
+ */
43
+ function readCommits(git, { since, until, author }) {
44
+ const out = git([
45
+ 'log',
46
+ // Every ref but the stash: a stash entry is a commit too, and `--all`
47
+ // reports it as work ("index on feat/x: …") done twice.
48
+ '--exclude=refs/stash',
49
+ '--all',
50
+ '--no-merges',
51
+ `--since=${since}`,
52
+ `--until=${until}`,
53
+ `--author=${author}`,
54
+ '--name-status',
55
+ '-M',
56
+ `--format=${RS}%H${US}%cI${US}%s${US}%(trailers:key=Refs,valueonly,separator=%x2c)`,
57
+ ])
58
+ if (out === null) return null
59
+ const commits = []
60
+ for (const record of out.split(RS)) {
61
+ if (!record.trim()) continue
62
+ const [head, ...rest] = record.split('\n')
63
+ const [sha, at, subject, refs] = head.split(US)
64
+ const files = []
65
+ for (const line of rest) {
66
+ if (!line.trim()) continue
67
+ const [status, a, b] = line.split('\t')
68
+ // `R087` — a rename with its similarity score; the letter is the fact.
69
+ if (status[0] === 'R' && b) files.push({ status: 'R', from: a, path: b })
70
+ else if (a) files.push({ status: status[0], path: a })
71
+ }
72
+ commits.push({
73
+ sha,
74
+ at,
75
+ subject,
76
+ refs: (refs || '').split(',').map((r) => r.trim()).filter(Boolean),
77
+ files,
78
+ })
79
+ }
80
+ return commits
81
+ }
82
+
83
+ /** The shas the base branch holds in the window — one walk, not one per commit. */
84
+ function onBaseIn(git, base, { since, until }) {
85
+ if (!base) return new Set()
86
+ const out = git(['log', base, '--no-merges', `--since=${since}`, `--until=${until}`, '--format=%H'])
87
+ return new Set(out ? out.split('\n').filter(Boolean) : [])
88
+ }
89
+
90
+ /** The local branches that hold a commit — most recent first is not promised. */
91
+ function branchesContaining(git, sha) {
92
+ const out = git(['for-each-ref', '--contains', sha, '--format=%(refname:short)', 'refs/heads'])
93
+ return out ? out.split('\n').filter(Boolean) : []
94
+ }
95
+
96
+ /**
97
+ * Every spec folder this repo can see across `refs` — the base branch and the
98
+ * spec branches, since under `land.specDocs: "branch"` a spec exists only on
99
+ * its own. One `ls-tree` per ref; nothing is read until it is asked for.
100
+ */
101
+ function knownSpecs(git, refs) {
102
+ const known = new Set()
103
+ for (const ref of refs) {
104
+ const listing = git(['ls-tree', '-r', '--name-only', ref, '--', ...BUCKETS.map((b) => `specs/${b}`)])
105
+ if (!listing) continue
106
+ for (const p of listing.split('\n')) {
107
+ const m = /^specs\/[^/]+\/([^/]+)\/00-overview\.md$/.exec(p)
108
+ if (m) known.add(m[1])
109
+ }
110
+ }
111
+ return [...known]
112
+ }
113
+
114
+ /** A spec's ticket, read off the first of `refs` that holds its overview. */
115
+ function ticketFor(git, refs, spec, identifierField = null) {
116
+ for (const ref of refs) {
117
+ for (const bucket of BUCKETS) {
118
+ const text = git(['show', `${ref}:specs/${bucket}/${spec}/00-overview.md`])
119
+ if (text === null) continue
120
+ return readTicket(text, identifierField)
121
+ }
122
+ }
123
+ return null
124
+ }
125
+
126
+ /**
127
+ * The spec a `Refs:` ticket names, found by the identifier stamped in its
128
+ * overview. Exactly one match or null — two specs claiming one ticket is a
129
+ * question, not an answer.
130
+ */
131
+ function specForTicket(git, refs, id) {
132
+ const value = escapeRegex(id)
133
+ const names = new Set()
134
+ for (const ref of refs) {
135
+ const out = git(['grep', '-l', '-E', `^[A-Za-z][A-Za-z0-9]*_identifier:[[:space:]]*["']?${value}["']?[[:space:]]*$`, ref, '--', 'specs/*/*/00-overview.md'])
136
+ if (!out) continue
137
+ for (const line of out.split('\n')) {
138
+ const m = /specs\/[^/]+\/([^/]+)\/00-overview\.md$/.exec(line)
139
+ if (m) names.add(m[1])
140
+ }
141
+ }
142
+ return names.size === 1 ? [...names][0] : null
143
+ }
144
+
145
+ module.exports = { CONTAINS_CAP, authorOf, branchesContaining, knownSpecs, onBaseIn, readCommits, specForTicket, ticketFor }
@@ -0,0 +1,262 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * The ta-da digest: the window's sessions, folded into the repo each one
5
+ * worked in and grouped by branch. This is what `skitterspec tada` prints and
6
+ * what the skill writes its recap from — never the transcripts themselves.
7
+ *
8
+ * The project is the REPO, not the cwd. A session that `cd`s into
9
+ * `../<repo>-wt/<slug>` is still working on `<repo>`, and grouping by cwd
10
+ * reported one repo as one project per worktree (Decision 3).
11
+ */
12
+
13
+ const fs = require('node:fs')
14
+ const path = require('node:path')
15
+ const { execFileSync } = require('node:child_process')
16
+
17
+ const { listTranscripts, readSession, trimPrompts } = require('./transcripts.js')
18
+
19
+ /**
20
+ * The repo a cwd belongs to, through the shared git dir — which every worktree
21
+ * of a repo points at, so they all fold into the primary checkout.
22
+ *
23
+ * @returns {{ repo: string } | { repo: null } | { missing: true }}
24
+ * `repo: null` is a directory that exists outside any repo; `missing` is one
25
+ * that no longer exists (a torn-down worktree), and is not the same fact.
26
+ */
27
+ function gitRepoOf(cwd) {
28
+ if (!fs.existsSync(cwd)) return { missing: true }
29
+ let common
30
+ try {
31
+ common = execFileSync('git', ['-C', cwd, 'rev-parse', '--path-format=absolute', '--git-common-dir'], {
32
+ stdio: ['ignore', 'pipe', 'ignore'],
33
+ })
34
+ .toString()
35
+ .trim()
36
+ } catch {
37
+ return { repo: null }
38
+ }
39
+ return { repo: path.basename(common) === '.git' ? path.dirname(common) : common }
40
+ }
41
+
42
+ function memo(fn) {
43
+ const seen = new Map()
44
+ return (k) => {
45
+ if (!seen.has(k)) seen.set(k, fn(k))
46
+ return seen.get(k)
47
+ }
48
+ }
49
+
50
+ /**
51
+ * @param {object} a
52
+ * - `root` the transcripts root (`defaultRoot()`)
53
+ * - `window` `{ since, until }` from `windowFor`
54
+ * - `here` a cwd to narrow to its repo, or null for every project
55
+ * - `repoOf` `gitRepoOf`, injectable
56
+ * - `facts` `(repo) => readRepoFacts(…)` — commits, lifecycle moves and
57
+ * spec lookups for a repo; omitted, groups are sessions only
58
+ * - `openFor` `(repo) => [{ spec, detail, next }]` — what is in flight there
59
+ * - `chat` keep every prompt, no-spec ones included (`--chat`)
60
+ * - `category` the running project's category: only projects carrying the
61
+ * same one are reported. Null reports every project.
62
+ */
63
+ async function buildDigest({ root, window, here = null, repoOf = gitRepoOf, facts = null, openFor = null, category = null, chat = false }) {
64
+ const resolve = memo(repoOf)
65
+ const notes = []
66
+ const refolded = new Set()
67
+ const files = listTranscripts(root, window.since)
68
+ const projects = new Map()
69
+ let stamped = 0
70
+
71
+ for (const file of files) {
72
+ const session = await readSession(file, window)
73
+ stamped += session.stamped
74
+ // A cwd that is gone takes the repo of a place in the same session that
75
+ // still resolves, else of the directory the session was launched from —
76
+ // it started somewhere real before it moved.
77
+ const fallback =
78
+ session.places.map((p) => resolve(p.cwd)).find((r) => r.repo) ||
79
+ (session.launch && [resolve(session.launch)].find((r) => r.repo))
80
+
81
+ for (const place of session.places) {
82
+ let r = resolve(place.cwd)
83
+ if (r.missing) {
84
+ // The usual reason is a worktree torn down by /spec-complete — the
85
+ // normal end of a spec — so these are counted, not listed one by one.
86
+ if (fallback) {
87
+ refolded.add(place.cwd)
88
+ r = fallback
89
+ } else {
90
+ notes.push(`cannot tell: ${place.cwd} no longer exists, and nothing in its session does`)
91
+ r = { repo: null }
92
+ }
93
+ }
94
+ const key = r.repo || place.cwd
95
+ if (!projects.has(key)) {
96
+ projects.set(key, { key, repo: r.repo, name: path.basename(key), git: Boolean(r.repo), groups: new Map() })
97
+ }
98
+ const groups = projects.get(key).groups
99
+ const branch = place.branch || null
100
+ if (!groups.has(branch)) groups.set(branch, new Map())
101
+ const sessions = groups.get(branch)
102
+ if (!sessions.has(session.id)) sessions.set(session.id, { id: session.id, start: place.start, end: place.end, prompts: [] })
103
+ const s = sessions.get(session.id)
104
+ if (place.start < s.start) s.start = place.start
105
+ if (place.end > s.end) s.end = place.end
106
+ s.prompts.push(...place.prompts)
107
+ }
108
+ }
109
+
110
+ if (refolded.size > 0) {
111
+ notes.push(
112
+ `${refolded.size} working director${refolded.size === 1 ? 'y' : 'ies'} no longer exist ` +
113
+ "(torn-down worktrees, usually) — counted under the repo their session started in, on the branch it recorded",
114
+ )
115
+ }
116
+
117
+ // The positive signal behind an empty day: transcripts changed inside the
118
+ // window, yet not one entry in any of them carried a timestamp we could read.
119
+ // That is a format we no longer understand, not a day off.
120
+ if (files.length > 0 && stamped === 0) {
121
+ notes.push(
122
+ `cannot tell: ${files.length} transcript(s) changed in the window but none carried a readable ` +
123
+ 'timestamp — the transcript format may have changed',
124
+ )
125
+ }
126
+
127
+ let list = [...projects.values()]
128
+ if (here) {
129
+ // An absolute cwd is taken as written, like every session's own: resolving
130
+ // `/repo` on Windows prefixes the drive, and it then matches nothing.
131
+ const at = path.isAbsolute(here) ? here : path.resolve(here)
132
+ const key = resolve(at).repo || at
133
+ list = list.filter((p) => p.key === key)
134
+ }
135
+
136
+ const want = category ? fold(category) : null
137
+ const reported = list
138
+ .map((p) => ({ p, f: p.repo && facts ? facts(p.repo) : null }))
139
+ // Scoped by category: a project counts only when its own config carries
140
+ // the same one. Uncategorised projects — and repos with no skitterspec
141
+ // config, which have nowhere to declare one — are left out entirely.
142
+ .filter(({ f }) => !want || (f && f.category && fold(f.category) === want))
143
+ .map(({ p, f }) => {
144
+ if (f) notes.push(...f.notes)
145
+ return {
146
+ repo: p.repo,
147
+ name: (f && f.name) || p.name,
148
+ ...(f && f.category ? { category: f.category } : {}),
149
+ git: p.git,
150
+ skitterspec: Boolean(f && f.skitterspec),
151
+ groups: groupsOf(p, f, f && openFor ? openFor(p.repo) : [], { chat }),
152
+ }
153
+ })
154
+ // A project whose only activity was chatter that led nowhere has nothing
155
+ // left to report once that is dropped.
156
+ .filter((p) => p.groups.length > 0)
157
+ .sort((a, b) => a.name.localeCompare(b.name))
158
+
159
+ return {
160
+ window: { since: window.since.toISOString(), until: window.until.toISOString() },
161
+ ...(category ? { category } : {}),
162
+ projects: reported,
163
+ notes: [...new Set(notes)],
164
+ }
165
+ }
166
+
167
+ const fold = (s) => s.trim().toLowerCase()
168
+
169
+ /**
170
+ * Changes over chatter (Decision 3): prompts typed where no spec was in play
171
+ * are dropped — unless the same session went on to stand on a spec's branch,
172
+ * in which case they were the conversation that led to that spec, and they
173
+ * move into it. The spec the session reached first afterwards takes them;
174
+ * failing that, the first it reached at all.
175
+ *
176
+ * Only prompts are dropped. A no-spec group's commits are changes, and stay.
177
+ */
178
+ function foldChatter(placed) {
179
+ const out = placed.filter((x) => x.spec)
180
+ for (const x of placed.filter((y) => !y.spec)) {
181
+ const onSpecs = out.filter((y) => y.s.id === x.s.id).sort((a, b) => (a.s.start < b.s.start ? -1 : 1))
182
+ const into = onSpecs.find((y) => y.s.start >= x.s.start) || onSpecs[0]
183
+ if (!into) continue
184
+ into.s.prompts.push(...x.s.prompts)
185
+ if (x.s.start < into.s.start) into.s.start = x.s.start
186
+ }
187
+ return out
188
+ }
189
+
190
+ /**
191
+ * One project's groups: a spec where the branch, a commit or an in-flight row
192
+ * names one, else the branch. Sessions, commits, lifecycle moves and open
193
+ * state for one spec land in one group, whichever of them found it.
194
+ */
195
+ function groupsOf(p, f, open, { chat = false } = {}) {
196
+ const groups = new Map()
197
+ const group = (spec, branch) => {
198
+ const key = spec ? `spec\0${spec}` : `branch\0${branch || ''}`
199
+ if (!groups.has(key)) {
200
+ groups.set(key, { spec: spec || null, branch: branch || null, sessions: [], commits: [], events: [], inFlight: null })
201
+ }
202
+ const g = groups.get(key)
203
+ if (!g.branch && branch) g.branch = branch
204
+ return g
205
+ }
206
+
207
+ const placed = []
208
+ for (const [branch, sessions] of p.groups) {
209
+ const spec = f ? f.toSpec(branch) : null
210
+ for (const s of sessions.values()) placed.push({ spec, branch, s })
211
+ }
212
+ for (const { spec, branch, s } of chat ? placed : foldChatter(placed)) {
213
+ s.prompts.sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0))
214
+ group(spec, branch).sessions.push({ id: s.id, start: s.start, end: s.end, ...trimPrompts(s.prompts) })
215
+ }
216
+ if (f) {
217
+ for (const c of f.commits) group(c.spec, c.spec ? null : c.branch).commits.push(c)
218
+ for (const e of f.events) group(e.spec, null).events.push(e)
219
+ }
220
+ for (const row of open) group(row.spec, null).inFlight = row
221
+
222
+ return [...groups.values()]
223
+ .map((g) => {
224
+ g.sessions.sort((a, b) => (a.start < b.start ? -1 : 1))
225
+ g.commits.sort(byTime)
226
+ g.events.sort(byTime)
227
+ const ticket = g.spec && f ? f.ticket(g.spec) || refTicket(g.commits) : null
228
+ return { spec: g.spec, branch: g.branch, ...(ticket ? { ticket } : {}), sessions: g.sessions, commits: g.commits, events: g.events, inFlight: g.inFlight }
229
+ })
230
+ .sort((a, b) => {
231
+ // Activity first, in the order it happened; a spec that is only open —
232
+ // in flight, untouched in this window — goes last.
233
+ const ta = firstAt(a)
234
+ const tb = firstAt(b)
235
+ if (ta === tb) return 0
236
+ if (ta === null) return 1
237
+ if (tb === null) return -1
238
+ return ta < tb ? -1 : 1
239
+ })
240
+ }
241
+
242
+ // Stable on a tie — a rebased run shares one committer second, and its order
243
+ // is the walk's, which is oldest first.
244
+ function byTime(a, b) {
245
+ const ta = Date.parse(a.at)
246
+ const tb = Date.parse(b.at)
247
+ return ta < tb ? -1 : ta > tb ? 1 : 0
248
+ }
249
+
250
+ function firstAt(g) {
251
+ const times = [...g.sessions.map((s) => s.start), ...g.commits.map((c) => c.at)].map((t) => Date.parse(t))
252
+ return times.length ? Math.min(...times) : null
253
+ }
254
+
255
+ // A spec whose overview carries no ticket can still be named by the `Refs:`
256
+ // its commits carried — the id alone, since only the overview holds a url.
257
+ function refTicket(commits) {
258
+ const ids = [...new Set(commits.flatMap((c) => c.refs || []))]
259
+ return ids.length === 1 ? { id: ids[0], url: null } : null
260
+ }
261
+
262
+ module.exports = { buildDigest, gitRepoOf }
@@ -0,0 +1,37 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * The digest as text — what `skitterspec tada` prints and what the skill
5
+ * reads. A fifth of the JSON's size, because every byte here is a token the
6
+ * recap costs. Pure.
7
+ *
8
+ * Line markers carry the kind, so the skill can tell them apart without
9
+ * labels: `*` a lifecycle move, `+` a commit, `-` a prompt.
10
+ */
11
+
12
+ function formatTada(digest) {
13
+ const w = digest.window
14
+ const scope = digest.category ? ` · ${digest.category}` : ''
15
+ const out = [`ta-da: ${w.label || `${w.since} → ${w.until}`}${scope}`]
16
+ if (digest.projects.length === 0) out.push(' nothing in this window.')
17
+ for (const p of digest.projects) {
18
+ out.push('', `${p.name}${p.repo ? ` (${p.repo})` : ' (not a git repo)'}`)
19
+ for (const g of p.groups) {
20
+ const head = g.spec ? `${g.spec}${g.ticket ? ` [${g.ticket.id}]` : ''}` : `${g.branch || '(no branch)'} — no spec`
21
+ out.push(` ${head}`)
22
+ for (const e of g.events) out.push(` * ${e.kind === 'phase-done' ? `phase ${e.phase} done` : e.kind}`)
23
+ for (const c of g.commits) out.push(` + ${c.sha} ${c.subject}`)
24
+ const sessions = g.sessions.length
25
+ if (sessions) out.push(` ${sessions} session${sessions === 1 ? '' : 's'}:`)
26
+ for (const s of g.sessions) {
27
+ for (const pr of s.prompts) out.push(` - ${pr.command ? `${pr.command} ` : ''}${pr.text}`.trimEnd())
28
+ if (s.omitted) out.push(` … ${s.omitted} more`)
29
+ }
30
+ if (g.inFlight) out.push(` in flight: ${g.inFlight.detail}${g.inFlight.next ? ` · next: ${g.inFlight.next}` : ''}`)
31
+ }
32
+ }
33
+ for (const n of digest.notes) out.push('', n)
34
+ return out.join('\n') + '\n'
35
+ }
36
+
37
+ module.exports = { formatTada }
@@ -0,0 +1,213 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * The ta-da list as a page: the model's recap on top, the digest it was
5
+ * written from underneath. PURE — digest and recap in, HTML out.
6
+ *
7
+ * READ-ONLY AND UNSERVED. No form, no buttons, no script beyond nothing: a
8
+ * recap asks no verdict, so it has nothing to send back and no server to send
9
+ * it to. It is a file on this machine; publishing it is a separate act.
10
+ *
11
+ * EVERYTHING IS ESCAPED BEFORE IT IS FORMATTED. The digest quotes the reader's
12
+ * own prompts and commit subjects, and the recap is model-written markdown —
13
+ * neither is trusted to be HTML. The markdown subset below works on escaped
14
+ * text, so a `<script>` in a prompt arrives as text, never as a tag.
15
+ */
16
+
17
+ function escapeHtml(s) {
18
+ return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c])
19
+ }
20
+
21
+ // Inline markdown on ALREADY-ESCAPED text: code first, so `**` inside a code
22
+ // span stays literal; then bold, then italic.
23
+ function inline(escaped) {
24
+ return escaped
25
+ .replace(/`([^`]+)`/g, '<code>$1</code>')
26
+ .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
27
+ .replace(/(^|[^*\w])\*([^*\s][^*]*)\*(?!\w)/g, '$1<em>$2</em>')
28
+ }
29
+
30
+ /**
31
+ * The markdown a recap uses and nothing more: `#`–`###` headings, `-`/`*`
32
+ * bullets (one level), paragraphs, and inline code, bold and italic. Anything
33
+ * else reads as a paragraph of text — the safe failure for a recap.
34
+ */
35
+ function renderMarkdown(md) {
36
+ const out = []
37
+ let list = false
38
+ let para = []
39
+ const flushPara = () => {
40
+ if (para.length) out.push(`<p>${inline(escapeHtml(para.join(' ')))}</p>`)
41
+ para = []
42
+ }
43
+ const closeList = () => {
44
+ if (list) out.push('</ul>')
45
+ list = false
46
+ }
47
+ for (const raw of String(md || '').split('\n')) {
48
+ const line = raw.trimEnd()
49
+ const heading = /^(#{1,3})\s+(.*)$/.exec(line)
50
+ const bullet = /^\s*[-*]\s+(.*)$/.exec(line)
51
+ if (!line.trim()) {
52
+ flushPara()
53
+ closeList()
54
+ } else if (heading) {
55
+ flushPara()
56
+ closeList()
57
+ const level = heading[1].length + 1 // the page's own title is the h1
58
+ out.push(`<h${level}>${inline(escapeHtml(heading[2]))}</h${level}>`)
59
+ } else if (bullet) {
60
+ flushPara()
61
+ if (!list) out.push('<ul>')
62
+ list = true
63
+ out.push(`<li>${inline(escapeHtml(bullet[1]))}</li>`)
64
+ } else {
65
+ closeList()
66
+ para.push(line.trim())
67
+ }
68
+ }
69
+ flushPara()
70
+ closeList()
71
+ return out.join('\n')
72
+ }
73
+
74
+ // `14:05 on Thursday 12 November`, in the reader's local time.
75
+ function timeText(d) {
76
+ const t = new Date(d)
77
+ const pad = (n) => String(n).padStart(2, '0')
78
+ const day = t.toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'long' })
79
+ return `${pad(t.getHours())}:${pad(t.getMinutes())} on ${day}`
80
+ }
81
+
82
+ const EVENT = { written: 'spec written', started: 'started', completed: 'completed', cancelled: 'cancelled' }
83
+ const eventText = (e) => (e.kind === 'phase-done' ? `phase ${e.phase} done` : EVENT[e.kind] || e.kind)
84
+
85
+ function ticketHtml(t) {
86
+ if (!t) return ''
87
+ const id = escapeHtml(t.id)
88
+ return t.url ? ` <a class="ticket" href="${escapeHtml(t.url)}">${id}</a>` : ` <span class="ticket">${id}</span>`
89
+ }
90
+
91
+ function groupHtml(g) {
92
+ const head = g.spec
93
+ ? `<span class="spec">${escapeHtml(g.spec)}</span>${ticketHtml(g.ticket)}`
94
+ : `<span class="branch">${escapeHtml(g.branch || '(no branch)')}</span> <span class="muted">no spec</span>`
95
+ const parts = [`<h4>${head}</h4>`]
96
+ if (g.events.length) {
97
+ parts.push(`<div class="chips">${g.events.map((e) => `<span class="chip">${escapeHtml(eventText(e))}</span>`).join('')}</div>`)
98
+ }
99
+ if (g.commits.length) {
100
+ parts.push(
101
+ `<ul class="commits">${g.commits
102
+ .map((c) => `<li><code>${escapeHtml(c.sha)}</code> ${escapeHtml(c.subject)}</li>`)
103
+ .join('')}</ul>`,
104
+ )
105
+ }
106
+ if (g.sessions.length) {
107
+ const prompts = g.sessions
108
+ .map(
109
+ (s) =>
110
+ s.prompts.map((p) => `<li>${p.command ? `<code>${escapeHtml(p.command)}</code> ` : ''}${escapeHtml(p.text)}</li>`).join('') +
111
+ (s.omitted ? `<li class="muted">… ${s.omitted} more</li>` : ''),
112
+ )
113
+ .join('')
114
+ const n = g.sessions.length
115
+ parts.push(`<details><summary>${n} session${n === 1 ? '' : 's'}</summary><ul class="prompts">${prompts}</ul></details>`)
116
+ }
117
+ if (g.inFlight) {
118
+ const next = g.inFlight.next ? ` · next: <code>${escapeHtml(g.inFlight.next)}</code>` : ''
119
+ parts.push(`<p class="inflight">in flight: ${escapeHtml(g.inFlight.detail)}${next}</p>`)
120
+ }
121
+ return `<section class="group">${parts.join('\n')}</section>`
122
+ }
123
+
124
+ /**
125
+ * @param {object} digest `buildDigest`'s answer
126
+ * @param {object} opts
127
+ * - `recap` the model's markdown recap, or null for the digest alone
128
+ * - `title` the page title — the caller's, in the reader's own dates
129
+ * (`humanLabel`); the digest only knows UTC instants
130
+ * - `project` the name of the project the report was run from, set in
131
+ * small type above the heading as on every generated page
132
+ * - `category` the scope the report was cut to, beside it
133
+ * - `writtenAt` when the recap was written — a served page is drawn now,
134
+ * and the recap above it may be hours older than the facts
135
+ */
136
+ function renderTadaPage(digest, { recap = null, title = 'Ta-da', project = null, category = null, writtenAt = null } = {}) {
137
+ const name = title
138
+ const eyebrow = [project, category].filter(Boolean).map(escapeHtml).join(' · ')
139
+ const written = recap && writtenAt ? `<p class="muted">Recap written ${escapeHtml(timeText(writtenAt))}</p>` : ''
140
+ const projects = digest.projects
141
+ .map(
142
+ (p) =>
143
+ `<article class="project"><h3>${escapeHtml(p.name)} <span class="muted">${escapeHtml(p.repo || 'not a git repo')}</span></h3>\n` +
144
+ `${p.groups.map(groupHtml).join('\n') || '<p class="muted">nothing here</p>'}</article>`,
145
+ )
146
+ .join('\n')
147
+ const notes = digest.notes.length ? `<ul class="notes">${digest.notes.map((n) => `<li>${escapeHtml(n)}</li>`).join('')}</ul>` : ''
148
+
149
+ return `<!doctype html>
150
+ <html lang="en">
151
+ <head>
152
+ <meta charset="utf-8">
153
+ <meta name="viewport" content="width=device-width, initial-scale=1">
154
+ <title>${escapeHtml(project ? `${project} · ${name}` : name)}</title>
155
+ <style>
156
+ /* The light palette is complete on bare :root; the dark blocks only redefine. */
157
+ :root {
158
+ --bg: #ffffff; --fg: #1b1b1f; --muted: #5c6070; --line: #e1e3e8;
159
+ --panel: #f6f7f9; --accent: #0b5fd0; --chip-bg: #eceef2; --chip-fg: #46506a;
160
+ --good-fg: #1a7f37; --good-bg: #eaf8ee;
161
+ }
162
+ :root:not([data-theme="light"]) {
163
+ @media (prefers-color-scheme: dark) {
164
+ --bg: #121316; --fg: #e4e6ea; --muted: #969bab; --line: #2a2c34;
165
+ --panel: #1a1c21; --accent: #7fb0ff; --chip-bg: #23262d; --chip-fg: #a3aabd;
166
+ --good-fg: #7ee08a; --good-bg: #12261a;
167
+ }
168
+ }
169
+ :root[data-theme="dark"] {
170
+ --bg: #121316; --fg: #e4e6ea; --muted: #969bab; --line: #2a2c34;
171
+ --panel: #1a1c21; --accent: #7fb0ff; --chip-bg: #23262d; --chip-fg: #a3aabd;
172
+ --good-fg: #7ee08a; --good-bg: #12261a;
173
+ }
174
+ * { box-sizing: border-box; }
175
+ body { margin: 0; background: var(--bg); color: var(--fg); font: 16px/1.55 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }
176
+ main { max-width: 820px; margin: 0 auto; padding: 24px 16px 64px; }
177
+ h1 { font-size: 1.6rem; margin: 0 0 16px; }
178
+ h2 { font-size: 1.25rem; margin: 28px 0 8px; }
179
+ h3 { font-size: 1.1rem; margin: 0 0 12px; overflow-wrap: anywhere; }
180
+ h4 { font-size: 1rem; margin: 0 0 6px; overflow-wrap: anywhere; }
181
+ a { color: var(--accent); }
182
+ code { font: 0.88em ui-monospace, "SF Mono", Menlo, monospace; overflow-wrap: anywhere; }
183
+ .muted { color: var(--muted); font-weight: normal; font-size: 0.9em; }
184
+ .eyebrow { color: var(--muted); font-size: 0.85em; margin: 0 0 2px; }
185
+ .recap { border: 1px solid var(--line); border-radius: 10px; padding: 4px 18px 12px; background: var(--good-bg); }
186
+ .project { border-top: 1px solid var(--line); padding-top: 18px; margin-top: 24px; }
187
+ .group { background: var(--panel); border-radius: 8px; padding: 12px 14px; margin: 10px 0; }
188
+ .chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 4px 0 8px; }
189
+ .chip { background: var(--chip-bg); color: var(--chip-fg); border-radius: 999px; padding: 1px 10px; font-size: 0.85em; }
190
+ .ticket { font-weight: normal; font-size: 0.9em; }
191
+ ul { padding-left: 1.2em; margin: 6px 0; }
192
+ .commits, .prompts { list-style: none; padding-left: 0; }
193
+ .commits li, .prompts li { overflow-wrap: anywhere; }
194
+ .inflight { margin: 8px 0 0; color: var(--good-fg); }
195
+ .notes { color: var(--muted); font-size: 0.9em; }
196
+ details summary { cursor: pointer; color: var(--muted); }
197
+ </style>
198
+ </head>
199
+ <body>
200
+ <main>
201
+ ${eyebrow ? `<p class="eyebrow">${eyebrow}</p>` : ''}
202
+ <h1>${escapeHtml(name)}</h1>
203
+ ${recap ? `<section class="recap">${renderMarkdown(recap)}${written}</section>` : ''}
204
+ <h2>What it was written from</h2>
205
+ ${projects || '<p class="muted">Nothing in this window.</p>'}
206
+ ${notes}
207
+ </main>
208
+ </body>
209
+ </html>
210
+ `
211
+ }
212
+
213
+ module.exports = { renderTadaPage, renderMarkdown, escapeHtml }