@skitterbyte/skitterspec-jira 2.8.0 → 2.9.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,102 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * Everything a ta-da list knows about one repo beyond its sessions: the
5
+ * author's commits in the window attributed to specs, the lifecycle moves
6
+ * those commits made, and how to read a branch or a ticket back to a spec.
7
+ *
8
+ * `git` is the injected reader (`(args) => stdout | null`) and `config` the
9
+ * repo's loaded env config, so this runs against a throwaway repo in tests.
10
+ */
11
+
12
+ const fs = require('node:fs')
13
+ const path = require('node:path')
14
+
15
+ const { describeBaseBranch } = require('../env/resolve.js')
16
+ const { projectName, projectCategory } = require('../env/project.js')
17
+ const { CONTAINS_CAP, authorOf, branchesContaining, knownSpecs, onBaseIn, readCommits, specForTicket, ticketFor } = require('./commits.js')
18
+ const { attributeCommit, branchToSpec, lifecycleEvents } = require('./specs.js')
19
+
20
+ // Enough to tell commits apart in a recap, as `git log --oneline` does.
21
+ const SHORT = 9
22
+
23
+ /**
24
+ * @param {object} a
25
+ * - `repo` the repo root
26
+ * - `git` reader bound to it
27
+ * - `config` its env config (`loadEnvConfig(repo).config`)
28
+ * - `window` `{ since, until }`
29
+ * @returns {{ name, category, skitterspec, base, toSpec, ticket, commits, events, notes }}
30
+ */
31
+ function readRepoFacts({ repo, git, config, window }) {
32
+ const notes = []
33
+ // The positive signal for a skitterspec project: the config folder `init`
34
+ // always writes. A lifecycle folder is not checked — git drops an empty one.
35
+ const skitterspec = fs.existsSync(path.join(repo, 'specs', '.core'))
36
+
37
+ let base = null
38
+ try {
39
+ base = describeBaseBranch(config, git).base
40
+ } catch {
41
+ base = null
42
+ }
43
+ const heads = (git(['for-each-ref', '--format=%(refname:short)', 'refs/heads']) || '').split('\n').filter(Boolean)
44
+ // The base first, so its copy of a spec is the one read unless only a
45
+ // spec branch has it.
46
+ const refs = [...new Set([base, ...heads].filter(Boolean))]
47
+ const known = skitterspec ? knownSpecs(git, refs) : []
48
+ const toSpec = skitterspec ? branchToSpec(config.branch && config.branch.pattern, known) : () => null
49
+ const identifierField = (config.branch && config.branch.identifierField) || null
50
+
51
+ const ticketCache = new Map()
52
+ const ticket = (spec) => {
53
+ if (!ticketCache.has(spec)) ticketCache.set(spec, skitterspec ? ticketFor(git, refs, spec, identifierField) : null)
54
+ return ticketCache.get(spec)
55
+ }
56
+ const specOfTicket = (id) => (skitterspec ? specForTicket(git, refs, id) : null)
57
+
58
+ const span = { since: window.since.toISOString(), until: window.until.toISOString() }
59
+ const author = authorOf(git)
60
+ let raw = []
61
+ if (!author) {
62
+ notes.push(`cannot tell: ${path.basename(repo)} has no user.email or user.name, so its commits were not read`)
63
+ } else {
64
+ raw = readCommits(git, { ...span, author: author.match })
65
+ if (raw === null) {
66
+ notes.push(`cannot tell: git log failed in ${repo}`)
67
+ raw = []
68
+ }
69
+ }
70
+
71
+ const show = (ref, p) => git(['show', `${ref}:${p}`])
72
+ const onBase = onBaseIn(git, base, span)
73
+ const commits = []
74
+ const events = []
75
+ let asked = 0
76
+ // `git log` is newest first, and a rebase stamps a run of commits with one
77
+ // committer second — so walk oldest first, and equal times keep that order.
78
+ raw.slice().reverse().forEach((c) => {
79
+ const landed = onBase.has(c.sha)
80
+ // Only an unlanded commit's branches say anything (`attributeCommit`), so
81
+ // only those are asked — and only up to the cap.
82
+ const branches = !landed && asked++ < CONTAINS_CAP ? branchesContaining(git, c.sha) : []
83
+ const spec = skitterspec ? attributeCommit({ ...c, onBase: landed, branches }, toSpec, specOfTicket) : null
84
+ // Where a commit with no spec is reported: the base branch when it is
85
+ // there, else the first branch holding it.
86
+ 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
+ if (skitterspec) {
89
+ for (const e of lifecycleEvents(c, show)) events.push({ ...e, sha: c.sha.slice(0, SHORT), at: c.at })
90
+ }
91
+ })
92
+ if (asked > CONTAINS_CAP) {
93
+ notes.push(`${asked} unlanded commits in ${path.basename(repo)} — past ${CONTAINS_CAP}, the rest are attributed by their files alone`)
94
+ }
95
+
96
+ // The config's own name, else the repo's folder — the config is read without
97
+ // a checkout anchor, so `projectName` cannot fall back to the folder itself.
98
+ const name = projectName(config) || path.basename(repo)
99
+ return { name, category: projectCategory(config), skitterspec, base, toSpec, ticket, commits, events, notes }
100
+ }
101
+
102
+ module.exports = { readRepoFacts }
@@ -0,0 +1,127 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * The ta-da page as the review server serves it: `/<token>/_tada?on=…`,
5
+ * rendered per request like every other page there. Nothing is stored but the
6
+ * model's recap, a sidecar beside the review notes — the HTML never is, for
7
+ * the reason `env/serve.js` gives: a stored page is a photograph, and a
8
+ * served one cannot be out of date.
9
+ *
10
+ * The digest is the CLI's own answer (`skitterspec tada --json`), run in the
11
+ * server's project so its category scopes the report exactly as it would in a
12
+ * terminal there. One implementation, so the page and the terminal cannot
13
+ * disagree about what the day held.
14
+ */
15
+
16
+ const fs = require('node:fs')
17
+ const path = require('node:path')
18
+ const { execFile } = require('node:child_process')
19
+
20
+ const { windowFor, humanLabel, localDay } = require('./window.js')
21
+ const { renderTadaPage } = require('./page.js')
22
+
23
+ // `_tada`, not `tada`: the route shares a namespace with spec names, and a
24
+ // `/no-spec` branch may be called anything kebab-case — never with a leading
25
+ // underscore.
26
+ const ROUTE = '_tada'
27
+
28
+ const BIN = path.join(__dirname, '..', '..', 'bin', 'skitterspec.js')
29
+
30
+ /**
31
+ * What a request (or a CLI run) asks for, in one shape: the window as an
32
+ * absolute day so a link keeps meaning the same thing tomorrow, and the
33
+ * scope flags. `since` and `on` are both day strings (`YYYY-MM-DD`) or absent.
34
+ */
35
+ function tadaQuery({ on = null, since = null, all = false, chat = false, here = false } = {}) {
36
+ const q = new URLSearchParams()
37
+ if (on) q.set('on', on)
38
+ else if (since) q.set('since', since)
39
+ if (all) q.set('all', '1')
40
+ if (chat) q.set('chat', '1')
41
+ if (here) q.set('here', '1')
42
+ const s = q.toString()
43
+ return s ? `?${s}` : ''
44
+ }
45
+
46
+ /** The query back into a request — refusing a window it cannot read. */
47
+ function readTadaQuery(search, now = new Date()) {
48
+ const q = new URLSearchParams(search || '')
49
+ const on = q.get('on')
50
+ const since = q.get('since')
51
+ const window = windowFor({ on: on || undefined, since: since || undefined }, now)
52
+ 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 }
54
+ }
55
+
56
+ /**
57
+ * The recap sidecar's name. Keyed by the window's START and kind, never its
58
+ * end: `--since friday` runs to now, so an end-keyed recap would be lost the
59
+ * next morning while the link that names it still works.
60
+ */
61
+ function recapKey({ on, since, window, all, chat }) {
62
+ const kind = on ? 'on' : since ? 'since' : 'on'
63
+ return `${kind}-${localDay(window.since)}${all ? '-all' : ''}${chat ? '-chat' : ''}`
64
+ }
65
+
66
+ function recapPath(stateDir, key) {
67
+ return path.join(stateDir, 'tada', `${key}.md`)
68
+ }
69
+
70
+ /** The CLI's digest for one window, run where the server's project lives. */
71
+ function runDigest({ dir, ask, exec = execFile, bin = BIN }) {
72
+ const args = [bin, 'tada', '--json']
73
+ const day = localDay(ask.window.since)
74
+ if (ask.on) args.push('--on', day)
75
+ else if (ask.since) args.push('--since', day)
76
+ if (ask.all) args.push('--all-projects')
77
+ if (ask.chat) args.push('--chat')
78
+ // `--here` in the server's own project: the repo the page was asked for.
79
+ if (ask.here) args.push('--here')
80
+ return new Promise((resolve) => {
81
+ exec(process.execPath, args, { cwd: dir, timeout: 120_000, maxBuffer: 64 * 1024 * 1024 }, (err, stdout) => {
82
+ if (err) return resolve({ error: `cannot tell — the digest could not be built (${err.message.split('\n')[0]})` })
83
+ try {
84
+ resolve({ digest: JSON.parse(stdout) })
85
+ } catch {
86
+ resolve({ error: 'cannot tell — the digest was not readable' })
87
+ }
88
+ })
89
+ })
90
+ }
91
+
92
+ /**
93
+ * The route's whole answer: `{ html }`, or `{ status, error }` for the server
94
+ * to send as text. A window it cannot read is a 400 naming the fix — the
95
+ * server never guesses a day.
96
+ */
97
+ async function renderServedTada({ dir, stateDir, search, project = null, now = new Date(), run = runDigest }) {
98
+ let ask
99
+ try {
100
+ ask = readTadaQuery(search, now)
101
+ } catch (e) {
102
+ return { status: 400, error: e.message }
103
+ }
104
+ const out = await run({ dir, ask })
105
+ if (out.error) return { status: 500, error: out.error }
106
+ let recap = null
107
+ let writtenAt = null
108
+ try {
109
+ const file = recapPath(stateDir, recapKey(ask))
110
+ recap = fs.readFileSync(file, 'utf8')
111
+ writtenAt = fs.statSync(file).mtime
112
+ } catch {
113
+ // No recap saved for this window is an ordinary state: the page is the
114
+ // digest alone, which is still the day's facts.
115
+ }
116
+ return {
117
+ html: renderTadaPage(out.digest, {
118
+ recap,
119
+ writtenAt,
120
+ title: `Ta-da · ${humanLabel(ask.window)}`,
121
+ project,
122
+ category: out.digest.category || null,
123
+ }),
124
+ }
125
+ }
126
+
127
+ module.exports = { ROUTE, tadaQuery, readTadaQuery, recapKey, recapPath, renderServedTada, runDigest }
@@ -0,0 +1,146 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * Turning git facts into spec facts for a ta-da list: which spec a branch
5
+ * belongs to, which lifecycle moves a commit made, and which spec a commit on
6
+ * the base branch was about. Pure — every input arrives already read.
7
+ */
8
+
9
+ const { splitPrefix, phaseIsDone } = require('../env/resolve.js')
10
+
11
+ const TYPES = 'feat|bug|hotfix|chore|issue|incident|epic'
12
+ const BUCKETS = ['backlog', 'in-progress', 'complete', 'cancelled']
13
+
14
+ // A spec document's path, anywhere in the repo — a project may sit in a
15
+ // subfolder, so the `specs/` segment is matched rather than anchored.
16
+ const SPEC_PATH = new RegExp(`(?:^|/)specs/(${BUCKETS.join('|')})/([^/]+)/([^/]+)$`)
17
+
18
+ function specPath(p) {
19
+ const m = SPEC_PATH.exec(p)
20
+ return m ? { bucket: m[1], name: m[2], file: m[3] } : null
21
+ }
22
+
23
+ const escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
24
+
25
+ /**
26
+ * A branch name → the spec it was provisioned for, read back through the
27
+ * project's `branch.pattern`. `{type}` and `{slug}` give the name outright;
28
+ * a pattern without `{type}` names a slug, which only counts when exactly one
29
+ * known spec carries it — two would make the answer a guess.
30
+ *
31
+ * @param {string} pattern `branch.pattern`, e.g. `{type}/{slug}`
32
+ * @param {string[]} known spec folder names this repo can see
33
+ * @returns {(branch: string) => string|null}
34
+ */
35
+ function branchToSpec(pattern, known = []) {
36
+ const p = pattern || '{type}/{slug}'
37
+ if (!p.includes('{slug}')) return () => null
38
+ const shape = (slug) =>
39
+ new RegExp(
40
+ `^${escape(p).replace(/\\\{(type|slug|identifier)\\\}/g, (_, token) => {
41
+ if (token === 'type') return `(?<type>${TYPES})`
42
+ if (token === 'identifier') return '[^/]+'
43
+ return slug === null ? '(?<slug>.+)' : escape(slug)
44
+ })}$`,
45
+ )
46
+ if (p.includes('{type}')) {
47
+ const re = shape(null)
48
+ return (branch) => {
49
+ const m = branch && re.exec(branch)
50
+ return m ? `${m.groups.type}-${m.groups.slug}` : null
51
+ }
52
+ }
53
+ // No `{type}`: where `{slug}` ends is ambiguous beside an `{identifier}`
54
+ // (`ABC-12-orders`), so each known spec's slug is tried as a literal.
55
+ const shapes = known.map((k) => [k, shape(splitPrefix(k).slug)])
56
+ return (branch) => {
57
+ if (!branch) return null
58
+ const hits = shapes.filter(([, re]) => re.test(branch)).map(([k]) => k)
59
+ return hits.length === 1 ? hits[0] : null
60
+ }
61
+ }
62
+
63
+ /**
64
+ * The lifecycle moves one commit made, from its `--name-status` lines and,
65
+ * for a phase, the file's text either side of it.
66
+ *
67
+ * @param {object} commit `{ sha, files: [{ status, path, from? }] }`
68
+ * @param {(ref: string, path: string) => string|null} show `git show ref:path`
69
+ * @returns {Array<{ spec, kind, phase? }>}
70
+ * kind: written · started · completed · cancelled · phase-done
71
+ */
72
+ function lifecycleEvents(commit, show) {
73
+ const events = []
74
+ const seen = new Set()
75
+ const add = (spec, kind, extra = {}) => {
76
+ const key = `${spec}\0${kind}\0${extra.phase || ''}`
77
+ if (seen.has(key)) return
78
+ seen.add(key)
79
+ events.push({ spec, kind, ...extra })
80
+ }
81
+ for (const f of commit.files) {
82
+ const to = specPath(f.path)
83
+ if (!to) continue
84
+ if (f.status === 'R' && f.from) {
85
+ const from = specPath(f.from)
86
+ if (from && from.name === to.name && from.bucket !== to.bucket) {
87
+ if (to.bucket === 'in-progress') add(to.name, 'started')
88
+ else if (to.bucket === 'complete') add(to.name, 'completed')
89
+ else if (to.bucket === 'cancelled') add(to.name, 'cancelled')
90
+ }
91
+ continue
92
+ }
93
+ // `/spec` writes into backlog; `/spec-bug` and its kin write straight into
94
+ // in-progress, so a new overview in either is a spec being written.
95
+ if (f.status === 'A' && to.file === '00-overview.md' && (to.bucket === 'backlog' || to.bucket === 'in-progress')) {
96
+ add(to.name, 'written')
97
+ continue
98
+ }
99
+ const phase = /^(\d+)-.+\.md$/.exec(to.file)
100
+ if (f.status === 'M' && phase && Number(phase[1]) > 0) {
101
+ const after = show(commit.sha, f.path)
102
+ const before = show(`${commit.sha}^`, f.path)
103
+ // Both sides must be read: a phase file git could not show either side
104
+ // of is cannot-tell, never a phase someone finished.
105
+ if (after !== null && before !== null && phaseIsDone(after) && !phaseIsDone(before)) {
106
+ add(to.name, 'phase-done', { phase: Number(phase[1]) })
107
+ }
108
+ }
109
+ }
110
+ return events
111
+ }
112
+
113
+ /** The one spec a commit's documents belong to, or null when none or several. */
114
+ function specTouched(commit) {
115
+ const names = new Set(commit.files.map((f) => specPath(f.path)).filter(Boolean).map((s) => s.name))
116
+ return names.size === 1 ? [...names][0] : null
117
+ }
118
+
119
+ /**
120
+ * Which spec a commit belongs to: a branch that maps to a spec, then the one
121
+ * spec folder it touched, then its `Refs:` ticket. Anything else is `null` —
122
+ * reported under its branch as no spec.
123
+ *
124
+ * THE BRANCH IS ASKED ONLY OF A COMMIT NOT YET ON THE BASE. Containment is
125
+ * not authorship: a spec branch forked this afternoon contains every commit
126
+ * the base had this morning, so asking it about a landed commit attributes the
127
+ * whole day to whichever spec was started last. A landed commit is answered by
128
+ * what it carries — its files and its trailer — which do not move.
129
+ *
130
+ * @param {object} commit `{ onBase, branches, files, refs }`
131
+ * @param {(b: string) => string|null} toSpec
132
+ * @param {(id: string) => string|null} specOfTicket ticket id → spec, asked
133
+ * only when nothing else answered, since it is the one lookup that searches
134
+ */
135
+ function attributeCommit(commit, toSpec, specOfTicket) {
136
+ const touched = specTouched(commit)
137
+ if (!commit.onBase) {
138
+ const fromBranch = commit.branches.map(toSpec).filter(Boolean)
139
+ if (fromBranch.length) return touched && fromBranch.includes(touched) ? touched : fromBranch[0]
140
+ }
141
+ if (touched) return touched
142
+ const tickets = [...new Set(commit.refs.map(specOfTicket).filter(Boolean))]
143
+ return tickets.length === 1 ? tickets[0] : null
144
+ }
145
+
146
+ module.exports = { BUCKETS, attributeCommit, branchToSpec, lifecycleEvents, specPath, specTouched }
@@ -0,0 +1,258 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * Claude Code's session transcripts, read down to what a ta-da list needs:
5
+ * which prompts a person typed, where they were standing (cwd + git branch),
6
+ * and when. Everything else — tool calls, tool results, reminders, caveats —
7
+ * is dropped here, so the model is handed a digest and never a transcript.
8
+ *
9
+ * WHAT WOULD FOOL THIS: the transcript format is Claude Code's, not ours, and
10
+ * nothing promises it stays put. A renamed field would read as a day with no
11
+ * activity — an absence that proves nothing. So a file touched inside the
12
+ * window that yields no readable entry is reported as `cannot tell`, never
13
+ * silently as an idle day (`.claude/rules/negative-checks.md`).
14
+ */
15
+
16
+ const fs = require('node:fs')
17
+ const os = require('node:os')
18
+ const path = require('node:path')
19
+ const readline = require('node:readline')
20
+
21
+ // Enough to recognise a prompt, short enough that a long day stays a digest.
22
+ const PROMPT_CHARS = 200
23
+ // Per session and place: the first few say what it set out to do, the last
24
+ // few where it ended up. The middle is counted, not shown.
25
+ const KEEP_HEAD = 3
26
+ const KEEP_TAIL = 3
27
+
28
+ // Built-in commands that move the session around rather than do work. Kept out
29
+ // so a recap is not half `/clear`; a skill's command is work and stays.
30
+ const HOUSEKEEPING = new Set([
31
+ 'add-dir', 'clear', 'compact', 'config', 'context', 'cost', 'doctor', 'exit', 'fast',
32
+ 'help', 'login', 'logout', 'memory', 'model', 'permissions', 'quit', 'resume', 'status',
33
+ ])
34
+
35
+ /** Where Claude Code keeps transcripts — `CLAUDE_CONFIG_DIR` moves it. */
36
+ function defaultRoot(env = process.env) {
37
+ const base = env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude')
38
+ return path.join(base, 'projects')
39
+ }
40
+
41
+ /**
42
+ * Every `<root>/<project>/<session>.jsonl` modified at or after `since`. A file
43
+ * last written before the window opened cannot hold an entry inside it, so
44
+ * this is a skip and not a guess. Subagent transcripts live a level deeper and
45
+ * are deliberately not read: their prompts were written by Claude, not typed.
46
+ */
47
+ function listTranscripts(root, since) {
48
+ let projects
49
+ try {
50
+ projects = fs.readdirSync(root, { withFileTypes: true })
51
+ } catch {
52
+ return []
53
+ }
54
+ const out = []
55
+ for (const p of projects) {
56
+ if (!p.isDirectory()) continue
57
+ const dir = path.join(root, p.name)
58
+ let files
59
+ try {
60
+ files = fs.readdirSync(dir)
61
+ } catch {
62
+ continue
63
+ }
64
+ for (const f of files) {
65
+ if (!f.endsWith('.jsonl')) continue
66
+ const file = path.join(dir, f)
67
+ let stat
68
+ try {
69
+ stat = fs.statSync(file)
70
+ } catch {
71
+ continue
72
+ }
73
+ if (stat.isFile() && stat.mtime >= since) out.push(file)
74
+ }
75
+ }
76
+ return out.sort()
77
+ }
78
+
79
+ /**
80
+ * What a user entry says, reduced to one of:
81
+ * { text } a prompt someone typed
82
+ * { command, text } a slash command, kept as an event (`/spec-next`)
83
+ * null noise — dropped
84
+ */
85
+ function readPrompt(content) {
86
+ if (typeof content !== 'string') return null // tool results, images
87
+ const s = content.trim()
88
+ if (!s) return null
89
+ const name = /<command-name>\s*([^<\s]+)\s*<\/command-name>/.exec(s)
90
+ if (name) {
91
+ const args = /<command-args>([\s\S]*?)<\/command-args>/.exec(s)
92
+ const command = name[1].startsWith('/') ? name[1] : `/${name[1]}`
93
+ if (HOUSEKEEPING.has(command.slice(1))) return null
94
+ return { command, text: cap(args ? args[1].trim() : '') }
95
+ }
96
+ // Caveats, command output, reminders, task notifications, a bare paste:
97
+ // all arrive as a tagged block, and none of them is something typed.
98
+ if (s.startsWith('<')) return null
99
+ // "[Request interrupted by user]" and its kind.
100
+ if (s.startsWith('[') && s.endsWith(']')) return null
101
+ return { text: cap(s) }
102
+ }
103
+
104
+ function cap(s) {
105
+ const one = s.replace(/\s+/g, ' ').trim()
106
+ return one.length > PROMPT_CHARS ? `${one.slice(0, PROMPT_CHARS - 1)}…` : one
107
+ }
108
+
109
+ /**
110
+ * One transcript, read inside the window. Prompts are attributed to where the
111
+ * session stood when they were typed — a session that `cd`s into a worktree
112
+ * half-way through contributes to two places, which is the point.
113
+ *
114
+ * @returns {Promise<{ id, stamped: number, places: Array<{ cwd, branch,
115
+ * start, end, prompts: Array<{ at, text, command? }> }> }>}
116
+ */
117
+ async function readSession(file, { since, until }) {
118
+ const id = path.basename(file, '.jsonl')
119
+ const places = new Map()
120
+ let cwd = null
121
+ let branch = null
122
+ // Entries carrying a timestamp we could parse, inside the window or not —
123
+ // the positive signal that this is still a format we can read.
124
+ let stamped = 0
125
+
126
+ const rl = readline.createInterface({ input: fs.createReadStream(file), crlfDelay: Infinity })
127
+ for await (const line of rl) {
128
+ if (!line) continue
129
+ let e
130
+ try {
131
+ e = JSON.parse(line)
132
+ } catch {
133
+ continue // a half-written last line, or not ours to read
134
+ }
135
+ // Where the session stands is tracked from every entry, so a `cd` made by
136
+ // a tool call moves the prompts that follow it.
137
+ if (typeof e.cwd === 'string') cwd = e.cwd
138
+ if (typeof e.gitBranch === 'string' && e.gitBranch) branch = e.gitBranch
139
+ const at = Date.parse(e.timestamp)
140
+ if (Number.isNaN(at)) continue
141
+ stamped++
142
+ if (at < since.getTime() || at > until.getTime()) continue
143
+ // A compaction summary arrives as a user entry, written by Claude.
144
+ if (e.type !== 'user' || e.isMeta || e.isSidechain || e.isCompactSummary) continue
145
+ const p = readPrompt(e.message && e.message.content)
146
+ if (!p || !cwd) continue
147
+ const key = `${cwd}\0${branch || ''}`
148
+ if (!places.has(key)) places.set(key, { cwd, branch, start: e.timestamp, end: e.timestamp, prompts: [] })
149
+ const place = places.get(key)
150
+ place.end = e.timestamp
151
+ place.prompts.push({ at: e.timestamp, ...p })
152
+ }
153
+ return { id, stamped, launch: launchDir(path.basename(path.dirname(file))), places: [...places.values()] }
154
+ }
155
+
156
+ /**
157
+ * The directory a session was launched from, read back off its transcript
158
+ * folder's name — Claude Code writes `/Users/me/code/app` as
159
+ * `-Users-me-code-app`, flattening `/` and `.` alike to `-`.
160
+ *
161
+ * That flattening is lossy (`my-app` and `my/app` encode the same), so this
162
+ * decodes only by asking the disk: each `-` is tried as a separator and as a
163
+ * literal, keeping the spellings that exist. More than one survivor, or none,
164
+ * is cannot-tell and returns null — a guessed directory would fold a session
165
+ * into the wrong repo with nothing to show for it.
166
+ */
167
+ function launchDir(name, existsOnDisk = fs.existsSync) {
168
+ if (!name.startsWith('-')) return null
169
+ const parts = name.slice(1).split('-')
170
+ // Each `-` has three readings, so the search is exponential in their count;
171
+ // past this many it is cannot-tell rather than a stall.
172
+ if (parts.length > 16) return null
173
+ const seen = new Map()
174
+ const exists = (p) => {
175
+ if (!seen.has(p)) seen.set(p, existsOnDisk(p))
176
+ return seen.get(p)
177
+ }
178
+ const found = []
179
+ const walk = (i, at, seg) => {
180
+ if (found.length > 1) return
181
+ if (i === parts.length) {
182
+ const full = path.join(at, seg)
183
+ if (exists(full)) found.push(full)
184
+ return
185
+ }
186
+ const next = parts[i]
187
+ // Close the segment here, if what it names exists so far.
188
+ if (seg && exists(path.join(at, seg))) walk(i + 1, path.join(at, seg), next)
189
+ // Or keep it open, through a literal `-` or a `.` (a dotfile, `app.web`).
190
+ if (seg !== '') {
191
+ walk(i + 1, at, `${seg}-${next}`)
192
+ walk(i + 1, at, `${seg}.${next}`)
193
+ } else {
194
+ walk(i + 1, at, `.${next}`)
195
+ }
196
+ }
197
+ walk(1, path.sep, parts[0])
198
+ return found.length === 1 ? found[0] : null
199
+ }
200
+
201
+ /** First and last few prompts, with the middle counted rather than shown. */
202
+ function trimPrompts(prompts) {
203
+ if (prompts.length <= KEEP_HEAD + KEEP_TAIL) return { prompts, omitted: 0 }
204
+ return {
205
+ prompts: [...prompts.slice(0, KEEP_HEAD), ...prompts.slice(-KEEP_TAIL)],
206
+ omitted: prompts.length - KEEP_HEAD - KEEP_TAIL,
207
+ }
208
+ }
209
+
210
+ // Enough of a transcript to see where its session ran. A session's first
211
+ // entries carry its cwd; reading the whole file to learn that is how listing
212
+ // every project would cost a minute.
213
+ const HEAD_BYTES = 64 * 1024
214
+
215
+ /**
216
+ * Every directory any session ran in — read from the head of each transcript,
217
+ * plus the folder each session was launched from. All time, not a window: this
218
+ * answers "which projects do you work in", for `skitterspec project
219
+ * --categories`. Resolving them to repos is the caller's.
220
+ */
221
+ function knownDirs(root) {
222
+ const dirs = new Set()
223
+ for (const file of listTranscripts(root, new Date(0))) {
224
+ const launch = launchDir(path.basename(path.dirname(file)))
225
+ if (launch) dirs.add(launch)
226
+ let head = ''
227
+ try {
228
+ const fd = fs.openSync(file, 'r')
229
+ const buf = Buffer.alloc(HEAD_BYTES)
230
+ const n = fs.readSync(fd, buf, 0, HEAD_BYTES, 0)
231
+ fs.closeSync(fd)
232
+ head = buf.subarray(0, n).toString('utf8')
233
+ } catch {
234
+ continue
235
+ }
236
+ for (const m of head.matchAll(/"cwd":"((?:[^"\\]|\\.)*)"/g)) {
237
+ try {
238
+ dirs.add(JSON.parse(`"${m[1]}"`))
239
+ } catch {
240
+ // a cwd cut off at the head's edge — the next line will carry it
241
+ }
242
+ }
243
+ }
244
+ return [...dirs]
245
+ }
246
+
247
+ module.exports = {
248
+ defaultRoot,
249
+ knownDirs,
250
+ launchDir,
251
+ listTranscripts,
252
+ readPrompt,
253
+ readSession,
254
+ trimPrompts,
255
+ PROMPT_CHARS,
256
+ KEEP_HEAD,
257
+ KEEP_TAIL,
258
+ }