@skitterbyte/skitterspec-jira 2.9.1 → 2.11.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,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 }
@@ -15,6 +15,7 @@ const path = require('node:path')
15
15
  const { execFileSync } = require('node:child_process')
16
16
 
17
17
  const { listTranscripts, readSession, trimPrompts } = require('./transcripts.js')
18
+ const { splitPrefix } = require('../env/resolve.js')
18
19
 
19
20
  /**
20
21
  * The repo a cwd belongs to, through the shared git dir — which every worktree
@@ -59,8 +60,11 @@ function memo(fn) {
59
60
  * - `chat` keep every prompt, no-spec ones included (`--chat`)
60
61
  * - `category` the running project's category: only projects carrying the
61
62
  * same one are reported. Null reports every project.
63
+ * - `home` the cwd the run started from; the project it belongs to is
64
+ * stamped `here`, so a recap can keep its closing advice to the
65
+ * work this session owns. Null, or outside any repo, stamps none.
62
66
  */
63
- async function buildDigest({ root, window, here = null, repoOf = gitRepoOf, facts = null, openFor = null, category = null, chat = false }) {
67
+ async function buildDigest({ root, window, here = null, home = null, repoOf = gitRepoOf, facts = null, openFor = null, category = null, chat = false }) {
64
68
  const resolve = memo(repoOf)
65
69
  const notes = []
66
70
  const refolded = new Set()
@@ -133,6 +137,10 @@ async function buildDigest({ root, window, here = null, repoOf = gitRepoOf, fact
133
137
  list = list.filter((p) => p.key === key)
134
138
  }
135
139
 
140
+ // Matched by repo, so a run from one of its worktrees is still home. A home
141
+ // outside any repo stamps nothing: there is no project to have been run from.
142
+ const homeRepo = home ? resolve(path.isAbsolute(home) ? home : path.resolve(home)).repo || null : null
143
+
136
144
  const want = category ? fold(category) : null
137
145
  const reported = list
138
146
  .map((p) => ({ p, f: p.repo && facts ? facts(p.repo) : null }))
@@ -145,6 +153,7 @@ async function buildDigest({ root, window, here = null, repoOf = gitRepoOf, fact
145
153
  return {
146
154
  repo: p.repo,
147
155
  name: (f && f.name) || p.name,
156
+ ...(homeRepo && p.repo === homeRepo ? { here: true } : {}),
148
157
  ...(f && f.category ? { category: f.category } : {}),
149
158
  git: p.git,
150
159
  skitterspec: Boolean(f && f.skitterspec),
@@ -225,7 +234,17 @@ function groupsOf(p, f, open, { chat = false } = {}) {
225
234
  g.commits.sort(byTime)
226
235
  g.events.sort(byTime)
227
236
  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 }
237
+ const wins = winsOf(g)
238
+ return {
239
+ spec: g.spec,
240
+ branch: g.branch,
241
+ ...(ticket ? { ticket } : {}),
242
+ sessions: g.sessions,
243
+ commits: g.commits,
244
+ events: g.events,
245
+ ...(wins.length ? { wins } : {}),
246
+ inFlight: g.inFlight,
247
+ }
229
248
  })
230
249
  .sort((a, b) => {
231
250
  // Activity first, in the order it happened; a spec that is only open —
@@ -239,6 +258,26 @@ function groupsOf(p, f, open, { chat = false } = {}) {
239
258
  })
240
259
  }
241
260
 
261
+ // The kinds whose completion means something was broken and now is not.
262
+ const RESCUES = new Set(['bug', 'hotfix', 'incident'])
263
+
264
+ /**
265
+ * The group's wins, as facts rather than judgement: a completed bug, hotfix or
266
+ * incident is `saved-bacon`; any other completed spec, and a tag cut on one of
267
+ * the window's commits, is a `win`. Read off the spec's folder prefix — the
268
+ * kind's positive signal — and the tags git holds, so the same day always
269
+ * reads the same. A cancelled spec and a finished phase are progress, not wins.
270
+ */
271
+ function winsOf(g) {
272
+ const wins = []
273
+ for (const e of g.events) {
274
+ if (e.kind !== 'completed') continue
275
+ wins.push({ kind: RESCUES.has(splitPrefix(e.spec).type) ? 'saved-bacon' : 'win', what: `${e.spec} completed`, at: e.at })
276
+ }
277
+ for (const c of g.commits) for (const t of c.tags || []) wins.push({ kind: 'win', what: `${t} cut`, at: c.at })
278
+ return wins
279
+ }
280
+
242
281
  // Stable on a tie — a rebased run shares one committer second, and its order
243
282
  // is the walk's, which is oldest first.
244
283
  function byTime(a, b) {
@@ -6,7 +6,8 @@
6
6
  * recap costs. Pure.
7
7
  *
8
8
  * Line markers carry the kind, so the skill can tell them apart without
9
- * labels: `*` a lifecycle move, `+` a commit, `-` a prompt.
9
+ * labels: `*` a lifecycle move, `+` a commit, `-` a prompt, `★` a win. The
10
+ * project the run started from is marked `(here)`.
10
11
  */
11
12
 
12
13
  function formatTada(digest) {
@@ -15,10 +16,11 @@ function formatTada(digest) {
15
16
  const out = [`ta-da: ${w.label || `${w.since} → ${w.until}`}${scope}`]
16
17
  if (digest.projects.length === 0) out.push(' nothing in this window.')
17
18
  for (const p of digest.projects) {
18
- out.push('', `${p.name}${p.repo ? ` (${p.repo})` : ' (not a git repo)'}`)
19
+ out.push('', `${p.name}${p.here ? ' (here)' : ''}${p.repo ? ` (${p.repo})` : ' (not a git repo)'}`)
19
20
  for (const g of p.groups) {
20
21
  const head = g.spec ? `${g.spec}${g.ticket ? ` [${g.ticket.id}]` : ''}` : `${g.branch || '(no branch)'} — no spec`
21
22
  out.push(` ${head}`)
23
+ for (const w of g.wins || []) out.push(` ★ ${w.kind === 'saved-bacon' ? 'saved bacon' : 'win'}: ${w.what}`)
22
24
  for (const e of g.events) out.push(` * ${e.kind === 'phase-done' ? `phase ${e.phase} done` : e.kind}`)
23
25
  for (const c of g.commits) out.push(` + ${c.sha} ${c.subject}`)
24
26
  const sessions = g.sessions.length
package/src/tada/page.js CHANGED
@@ -14,6 +14,10 @@
14
14
  * text, so a `<script>` in a prompt arrives as text, never as a tag.
15
15
  */
16
16
 
17
+ const todo = require('./todo.js')
18
+
19
+ const blockedText = (b) => todo.blockedText(b, new Date())
20
+
17
21
  function escapeHtml(s) {
18
22
  return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c])
19
23
  }
@@ -93,17 +97,28 @@ function groupHtml(g) {
93
97
  ? `<span class="spec">${escapeHtml(g.spec)}</span>${ticketHtml(g.ticket)}`
94
98
  : `<span class="branch">${escapeHtml(g.branch || '(no branch)')}</span> <span class="muted">no spec</span>`
95
99
  const parts = [`<h4>${head}</h4>`]
96
- if (g.events.length) {
100
+ if (g.wins && g.wins.length) {
101
+ parts.push(
102
+ `<div class="chips">${g.wins
103
+ .map((w) => `<span class="chip win">★ ${w.kind === 'saved-bacon' ? 'saved bacon' : 'win'}: ${escapeHtml(w.what)}</span>`)
104
+ .join('')}</div>`,
105
+ )
106
+ }
107
+ // A to-do group carries where it was left and the last thing typed, in
108
+ // place of the day's full moves, commits and sessions.
109
+ if (g.left) parts.push(`<p>left: ${escapeHtml(g.left)}</p>`)
110
+ if (g.prompt) parts.push(`<p class="muted">${escapeHtml(g.prompt)}</p>`)
111
+ if ((g.events || []).length) {
97
112
  parts.push(`<div class="chips">${g.events.map((e) => `<span class="chip">${escapeHtml(eventText(e))}</span>`).join('')}</div>`)
98
113
  }
99
- if (g.commits.length) {
114
+ if ((g.commits || []).length) {
100
115
  parts.push(
101
116
  `<ul class="commits">${g.commits
102
117
  .map((c) => `<li><code>${escapeHtml(c.sha)}</code> ${escapeHtml(c.subject)}</li>`)
103
118
  .join('')}</ul>`,
104
119
  )
105
120
  }
106
- if (g.sessions.length) {
121
+ if ((g.sessions || []).length) {
107
122
  const prompts = g.sessions
108
123
  .map(
109
124
  (s) =>
@@ -121,8 +136,19 @@ function groupHtml(g) {
121
136
  return `<section class="group">${parts.join('\n')}</section>`
122
137
  }
123
138
 
139
+ // A to-do project's blockers and today-so-far; a ta-da project has neither.
140
+ function projectExtras(p) {
141
+ const parts = []
142
+ if ((p.finished || []).length) parts.push(`<p class="muted">finished: ${p.finished.map(escapeHtml).join(', ')}</p>`)
143
+ for (const b of p.blocked || []) parts.push(`<p class="blocked">blocked: ${escapeHtml(blockedText(b))}</p>`)
144
+ if (p.today && (p.today.commits || p.today.moves)) {
145
+ parts.push(`<p class="muted">today so far: ${p.today.commits} commit${p.today.commits === 1 ? '' : 's'}, ${p.today.moves} move${p.today.moves === 1 ? '' : 's'}</p>`)
146
+ }
147
+ return parts.join('\n')
148
+ }
149
+
124
150
  /**
125
- * @param {object} digest `buildDigest`'s answer
151
+ * @param {object} digest `buildDigest`'s answer, or `buildTodo`'s
126
152
  * @param {object} opts
127
153
  * - `recap` the model's markdown recap, or null for the digest alone
128
154
  * - `title` the page title — the caller's, in the reader's own dates
@@ -140,8 +166,8 @@ function renderTadaPage(digest, { recap = null, title = 'Ta-da', project = null,
140
166
  const projects = digest.projects
141
167
  .map(
142
168
  (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>`,
169
+ `<article class="project"><h3>${escapeHtml(p.name)}${p.here ? ' <span class="chip">here</span>' : ''} <span class="muted">${escapeHtml(p.repo || 'not a git repo')}</span></h3>\n` +
170
+ `${p.groups.map(groupHtml).join('\n') || '<p class="muted">nothing here</p>'}${projectExtras(p)}</article>`,
145
171
  )
146
172
  .join('\n')
147
173
  const notes = digest.notes.length ? `<ul class="notes">${digest.notes.map((n) => `<li>${escapeHtml(n)}</li>`).join('')}</ul>` : ''
@@ -187,11 +213,13 @@ code { font: 0.88em ui-monospace, "SF Mono", Menlo, monospace; overflow-wrap: an
187
213
  .group { background: var(--panel); border-radius: 8px; padding: 12px 14px; margin: 10px 0; }
188
214
  .chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 4px 0 8px; }
189
215
  .chip { background: var(--chip-bg); color: var(--chip-fg); border-radius: 999px; padding: 1px 10px; font-size: 0.85em; }
216
+ .chip.win { background: var(--accent); color: var(--bg, #fff); }
190
217
  .ticket { font-weight: normal; font-size: 0.9em; }
191
218
  ul { padding-left: 1.2em; margin: 6px 0; }
192
219
  .commits, .prompts { list-style: none; padding-left: 0; }
193
220
  .commits li, .prompts li { overflow-wrap: anywhere; }
194
221
  .inflight { margin: 8px 0 0; color: var(--good-fg); }
222
+ .blocked { margin: 8px 0 0; font-weight: 600; }
195
223
  .notes { color: var(--muted); font-size: 0.9em; }
196
224
  details summary { cursor: pointer; color: var(--muted); }
197
225
  </style>
@@ -202,7 +230,7 @@ ${eyebrow ? `<p class="eyebrow">${eyebrow}</p>` : ''}
202
230
  <h1>${escapeHtml(name)}</h1>
203
231
  ${recap ? `<section class="recap">${renderMarkdown(recap)}${written}</section>` : ''}
204
232
  <h2>What it was written from</h2>
205
- ${projects || '<p class="muted">Nothing in this window.</p>'}
233
+ ${projects || `<p class="muted">${digest.kind === 'todo' ? 'Nothing in flight.' : 'Nothing in this window.'}</p>`}
206
234
  ${notes}
207
235
  </main>
208
236
  </body>
package/src/tada/repo.js CHANGED
@@ -69,6 +69,7 @@ function readRepoFacts({ repo, git, config, window }) {
69
69
  }
70
70
 
71
71
  const show = (ref, p) => git(['show', `${ref}:${p}`])
72
+ const tags = tagsBySha(git)
72
73
  const onBase = onBaseIn(git, base, span)
73
74
  const commits = []
74
75
  const events = []
@@ -84,7 +85,7 @@ function readRepoFacts({ repo, git, config, window }) {
84
85
  // Where a commit with no spec is reported: the base branch when it is
85
86
  // there, else the first branch holding it.
86
87
  const branch = landed ? base : branches[0] || null
87
- commits.push({ sha: c.sha.slice(0, SHORT), at: c.at, subject: c.subject, spec, branch, refs: c.refs })
88
+ commits.push({ sha: c.sha.slice(0, SHORT), at: c.at, subject: c.subject, spec, branch, refs: c.refs, ...(tags.has(c.sha) ? { tags: tags.get(c.sha) } : {}) })
88
89
  if (skitterspec) {
89
90
  for (const e of lifecycleEvents(c, show)) events.push({ ...e, sha: c.sha.slice(0, SHORT), at: c.at })
90
91
  }
@@ -99,4 +100,23 @@ function readRepoFacts({ repo, git, config, window }) {
99
100
  return { name, category: projectCategory(config), skitterspec, base, toSpec, ticket, commits, events, notes }
100
101
  }
101
102
 
102
- module.exports = { readRepoFacts }
103
+ /**
104
+ * Every tag, keyed by the commit it names — an annotated tag through the
105
+ * commit it peels to. One read for the repo, not one per commit. A failed read
106
+ * is no tags at all: a release missing from the wins is a quieter error than a
107
+ * report that fails to print.
108
+ */
109
+ function tagsBySha(git) {
110
+ const out = git(['for-each-ref', '--format=%(objectname) %(*objectname) %(refname:short)', 'refs/tags']) || ''
111
+ const map = new Map()
112
+ for (const line of out.split('\n')) {
113
+ const [obj, peeled, name] = line.split(' ')
114
+ if (!name) continue
115
+ const sha = peeled || obj
116
+ if (!map.has(sha)) map.set(sha, [])
117
+ map.get(sha).push(name)
118
+ }
119
+ return map
120
+ }
121
+
122
+ module.exports = { readRepoFacts, tagsBySha }
package/src/tada/serve.js CHANGED
@@ -32,8 +32,11 @@ const BIN = path.join(__dirname, '..', '..', 'bin', 'skitterspec.js')
32
32
  * absolute day so a link keeps meaning the same thing tomorrow, and the
33
33
  * scope flags. `since` and `on` are both day strings (`YYYY-MM-DD`) or absent.
34
34
  */
35
- function tadaQuery({ on = null, since = null, all = false, chat = false, here = false } = {}) {
35
+ function tadaQuery({ on = null, since = null, all = false, chat = false, here = false, todo = false } = {}) {
36
36
  const q = new URLSearchParams()
37
+ // The to-do is always "this morning": its window is the engine's to find,
38
+ // so it carries the day it was asked on and nothing else.
39
+ if (todo) q.set('todo', '1')
37
40
  if (on) q.set('on', on)
38
41
  else if (since) q.set('since', since)
39
42
  if (all) q.set('all', '1')
@@ -50,7 +53,7 @@ function readTadaQuery(search, now = new Date()) {
50
53
  const since = q.get('since')
51
54
  const window = windowFor({ on: on || undefined, since: since || undefined }, now)
52
55
  const flag = (k) => ['1', 'true', ''].includes(q.get(k)) && q.has(k)
53
- return { on, since, all: flag('all'), chat: flag('chat'), here: flag('here'), window }
56
+ return { on, since, all: flag('all'), chat: flag('chat'), here: flag('here'), todo: flag('todo'), window }
54
57
  }
55
58
 
56
59
  /**
@@ -58,8 +61,8 @@ function readTadaQuery(search, now = new Date()) {
58
61
  * end: `--since friday` runs to now, so an end-keyed recap would be lost the
59
62
  * next morning while the link that names it still works.
60
63
  */
61
- function recapKey({ on, since, window, all, chat }) {
62
- const kind = on ? 'on' : since ? 'since' : 'on'
64
+ function recapKey({ on, since, window, all, chat, todo = false }) {
65
+ const kind = todo ? 'todo' : on ? 'on' : since ? 'since' : 'on'
63
66
  return `${kind}-${localDay(window.since)}${all ? '-all' : ''}${chat ? '-chat' : ''}`
64
67
  }
65
68
 
@@ -69,9 +72,12 @@ function recapPath(stateDir, key) {
69
72
 
70
73
  /** The CLI's digest for one window, run where the server's project lives. */
71
74
  function runDigest({ dir, ask, exec = execFile, bin = BIN }) {
72
- const args = [bin, 'tada', '--json']
75
+ const args = [bin, ask.todo ? 'todo' : 'tada', '--json']
73
76
  const day = localDay(ask.window.since)
74
- if (ask.on) args.push('--on', day)
77
+ if (ask.todo) {
78
+ // `todo` finds its own window from today; a page asked for a past day's
79
+ // to-do still shows this morning's, which is the only one there is.
80
+ } else if (ask.on) args.push('--on', day)
75
81
  else if (ask.since) args.push('--since', day)
76
82
  if (ask.all) args.push('--all-projects')
77
83
  if (ask.chat) args.push('--chat')
@@ -117,7 +123,7 @@ async function renderServedTada({ dir, stateDir, search, project = null, now = n
117
123
  html: renderTadaPage(out.digest, {
118
124
  recap,
119
125
  writtenAt,
120
- title: `Ta-da · ${humanLabel(ask.window)}`,
126
+ title: `${ask.todo ? 'To-do' : 'Ta-da'} · ${humanLabel(ask.window)}`,
121
127
  project,
122
128
  category: out.digest.category || null,
123
129
  }),
@@ -0,0 +1,245 @@
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
+
183
+ const list = [...projects.values()]
184
+ .map((e) => {
185
+ const specs = e.groups.filter((g) => g.spec && g.inFlight).map((g) => g.spec)
186
+ return { ...e, blocked: e.repo && specs.length ? blockersFor(e.repo, specs) : [] }
187
+ })
188
+ .filter((e) => e.groups.length || e.finished.length || e.today.commits || e.today.moves)
189
+ // The home project first: it is the one this session acts on.
190
+ .sort((a, b) => (a.here !== b.here ? (a.here ? -1 : 1) : a.name.localeCompare(b.name)))
191
+
192
+ return {
193
+ kind: 'todo',
194
+ leftOff: leftOffDay ? { day: localDay(leftOffDay) } : null,
195
+ lookbackDays: LOOKBACK_DAYS,
196
+ ...(today.category ? { category: today.category } : {}),
197
+ projects: list,
198
+ notes: [...new Set([...(leftOff ? leftOff.notes : []), ...today.notes])],
199
+ }
200
+ }
201
+
202
+ const ageText = (at, now) => {
203
+ const ms = now - Date.parse(at)
204
+ if (Number.isNaN(ms) || ms < 0) return ''
205
+ const h = Math.floor(ms / 3_600_000)
206
+ return h < 24 ? ` · ${h}h` : ` · ${Math.floor(h / 24)}d`
207
+ }
208
+
209
+ function blockedText(b, now) {
210
+ if (b.kind === 'gate') return `${b.spec} — gate armed${b.phase ? `, phase ${b.phase}` : ''}: a verdict is owed`
211
+ return `${b.spec} — ${b.verdict || 'a'} verdict waiting (${b.code}${b.at ? ageText(b.at, now) : ''})`
212
+ }
213
+
214
+ /**
215
+ * The to-do as text — the same markers as `tada`, plus `left:` for where a
216
+ * group stopped, `finished:` for the specs that day closed, `blocked:` for what stands in a project's way, and `today:`
217
+ * for what has happened since midnight.
218
+ */
219
+ function formatTodo(todo, now = new Date()) {
220
+ const scope = todo.category ? ` · ${todo.category}` : ''
221
+ const head = todo.leftOff
222
+ ? `todo: left off ${todo.leftOff.label || todo.leftOff.day} · today ${todo.todayLabel || ''}`.trimEnd()
223
+ : `todo: nothing in the last ${todo.lookbackDays} days · today ${todo.todayLabel || ''}`.trimEnd()
224
+ const out = [`${head}${scope}`]
225
+ if (todo.projects.length === 0) out.push(' nothing in flight.')
226
+ for (const p of todo.projects) {
227
+ out.push('', `${p.name}${p.here ? ' (here)' : ''}${p.repo ? ` (${p.repo})` : ''}`)
228
+ for (const g of p.groups) {
229
+ out.push(` ${g.spec ? `${g.spec}${g.ticket ? ` [${g.ticket.id}]` : ''}` : `${g.branch || '(no branch)'} — no spec`}`)
230
+ if (g.left) out.push(` left: ${g.left}`)
231
+ if (g.prompt) out.push(` - ${g.prompt}`)
232
+ if (g.inFlight) out.push(` in flight: ${g.inFlight.detail}${g.inFlight.next ? ` · next: ${g.inFlight.next}` : ''}`)
233
+ }
234
+ if (p.finished.length) out.push(` finished: ${p.finished.join(', ')}`)
235
+ for (const b of p.blocked) out.push(` blocked: ${blockedText(b, now)}`)
236
+ if (p.today.commits || p.today.moves) {
237
+ 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'}`]
238
+ out.push(` today: ${parts.filter(Boolean).join(', ')}`)
239
+ }
240
+ }
241
+ for (const n of todo.notes) out.push('', n)
242
+ return out.join('\n') + '\n'
243
+ }
244
+
245
+ module.exports = { LOOKBACK_DAYS, activityTimes, lastActiveDay, leftOf, blockersFrom, readBlockers, buildTodo, formatTodo, blockedText }