|
| 1 | +import { cmd } from "./cmd" |
| 2 | +import * as prompts from "./clack" |
| 3 | +import { UI } from "../ui" |
| 4 | +import { dim, bold, highlight, printDivider, irisFetch, requireAuth, IRIS_API } from "./iris-api" |
| 5 | +import { homedir } from "os" |
| 6 | +import { join } from "path" |
| 7 | +import { existsSync, readdirSync, readFileSync, statSync } from "fs" |
| 8 | +import { execFileSync } from "child_process" |
| 9 | + |
| 10 | +/** |
| 11 | + * `iris timeline` — what happened, across every channel that already writes it down. |
| 12 | + * |
| 13 | + * DELIBERATELY NOT A NEW STORE. The corpus (fl-api `signal_observations`) holds numeric metrics |
| 14 | + * for scoring; a timeline needs EVENTS. Rather than stand up a second spine before knowing the |
| 15 | + * output is useful, this reads the four places that already contain dated, human- or |
| 16 | + * model-written titles: |
| 17 | + * |
| 18 | + * diary GET /api/v6/diary/list 126 days already synced, Feb -> Aug |
| 19 | + * git commit subjects across every nested repo |
| 20 | + * opencode session `title` 79/79 titled |
| 21 | + * claude `ai-title` / `custom-title` 53/68 titled |
| 22 | + * |
| 23 | + * NOTHING IS SYNTHESISED. Every line was already written by a human or by the tool that produced |
| 24 | + * the session, so this cannot hallucinate and needs no model. Persisting these as |
| 25 | + * `signal_episodes` is the follow-up (TL-01) once the shape is proven. |
| 26 | + * |
| 27 | + * SESSION CONTENT IS NEVER READ — titles and timestamps only. `corpus-collect.mjs` established |
| 28 | + * that rule because prompts carry credentials and client data, and this inherits it rather than |
| 29 | + * re-litigating it. |
| 30 | + */ |
| 31 | + |
| 32 | +type Episode = { date: string; source: string; title: string; ref?: string } |
| 33 | + |
| 34 | +const SOURCES = ["diary", "git", "opencode", "claude"] as const |
| 35 | + |
| 36 | +/** Field separator for git's pretty-format. Unit Separator cannot occur in a commit subject. */ |
| 37 | +const SEP = "\x1f" |
| 38 | + |
| 39 | +function parseSince(v: string): Date { |
| 40 | + const m = String(v).match(/^(\d+)\s*(d|w|mo|m|y)?$/i) |
| 41 | + const now = new Date() |
| 42 | + if (!m) return new Date(now.getTime() - 120 * 864e5) |
| 43 | + const n = parseInt(m[1], 10) |
| 44 | + const unit = (m[2] || "d").toLowerCase() |
| 45 | + const days = unit === "y" ? n * 365 : unit === "mo" || unit === "m" ? n * 30 : unit === "w" ? n * 7 : n |
| 46 | + return new Date(now.getTime() - days * 864e5) |
| 47 | +} |
| 48 | + |
| 49 | +/** ISO week key (Monday-anchored), so weeks sort lexically. */ |
| 50 | +function weekKey(iso: string): string { |
| 51 | + const d = new Date(iso + "T00:00:00Z") |
| 52 | + if (Number.isNaN(d.getTime())) return iso |
| 53 | + const day = (d.getUTCDay() + 6) % 7 |
| 54 | + d.setUTCDate(d.getUTCDate() - day) |
| 55 | + return d.toISOString().slice(0, 10) |
| 56 | +} |
| 57 | + |
| 58 | +// -- diary -------------------------------------------------------------------- |
| 59 | + |
| 60 | +/** The diary is USER-SCOPED; without user_id the endpoint answers for nobody and returns []. */ |
| 61 | +function sdkUserId(): string | undefined { |
| 62 | + const envPath = join(homedir(), ".iris", "sdk", ".env") |
| 63 | + if (!existsSync(envPath)) return undefined |
| 64 | + const m = readFileSync(envPath, "utf-8").match(/IRIS_USER_ID=(\d+)/) |
| 65 | + return m ? m[1] : undefined |
| 66 | +} |
| 67 | + |
| 68 | +async function fromDiary(since: Date): Promise<Episode[]> { |
| 69 | + const days = Math.ceil((Date.now() - since.getTime()) / 864e5) |
| 70 | + try { |
| 71 | + const token = await requireAuth() |
| 72 | + if (!token) return [] |
| 73 | + const params = new URLSearchParams({ days: String(days) }) |
| 74 | + const uid = sdkUserId() |
| 75 | + if (uid) params.set("user_id", uid) |
| 76 | + const res = await irisFetch(`/api/v6/diary/list?${params}`, {}, IRIS_API) |
| 77 | + if (!res.ok) return [] |
| 78 | + const body: any = await res.json() |
| 79 | + // The endpoint returns { entries: [...] }; `data` and a bare array are accepted defensively. |
| 80 | + const rows: any[] = body?.entries ?? body?.data ?? (Array.isArray(body) ? body : []) |
| 81 | + const out: Episode[] = [] |
| 82 | + for (const r of rows) { |
| 83 | + const date = String(r?.date ?? "").slice(0, 10) |
| 84 | + if (!date) continue |
| 85 | + // entry_titles is the already-written summary; fall back to the day's summary line. |
| 86 | + const titles: string[] = Array.isArray(r.entry_titles) ? r.entry_titles : [] |
| 87 | + if (titles.length) { |
| 88 | + for (const t of titles) out.push({ date, source: "diary", title: String(t) }) |
| 89 | + } else if (r.summary) { |
| 90 | + out.push({ date, source: "diary", title: String(r.summary) }) |
| 91 | + } |
| 92 | + } |
| 93 | + return out |
| 94 | + } catch { |
| 95 | + return [] |
| 96 | + } |
| 97 | +} |
| 98 | + |
| 99 | +// -- git ---------------------------------------------------------------------- |
| 100 | +/** |
| 101 | + * Walks nested repos. This monorepo has ELEVEN and NO `.gitmodules`, so anything reading |
| 102 | + * `.gitmodules` reports zero — the same 416x undercount the corpus collector hit. Gitlinks are |
| 103 | + * read from the index instead, and each candidate must be its OWN toplevel: `git -C` on an |
| 104 | + * uninitialised gitlink silently walks UP and answers about the parent, double-counting it. |
| 105 | + */ |
| 106 | +function gitRepos(root: string): string[] { |
| 107 | + const out = [root] |
| 108 | + try { |
| 109 | + const staged = execFileSync("git", ["-C", root, "ls-files", "--stage"], { |
| 110 | + encoding: "utf8", |
| 111 | + maxBuffer: 64e6, |
| 112 | + }) |
| 113 | + for (const line of staged.split("\n")) { |
| 114 | + if (!line.startsWith("160000")) continue |
| 115 | + const p = line.split("\t")[1] |
| 116 | + if (!p) continue |
| 117 | + const abs = join(root, p) |
| 118 | + if (!existsSync(join(abs, ".git"))) continue |
| 119 | + try { |
| 120 | + const top = execFileSync("git", ["-C", abs, "rev-parse", "--show-toplevel"], { |
| 121 | + encoding: "utf8", |
| 122 | + }).trim() |
| 123 | + if (top === abs) out.push(abs) |
| 124 | + } catch { |
| 125 | + /* not a repo */ |
| 126 | + } |
| 127 | + } |
| 128 | + } catch { |
| 129 | + /* not a repo */ |
| 130 | + } |
| 131 | + return out |
| 132 | +} |
| 133 | + |
| 134 | +function fromGit(root: string, since: Date): Episode[] { |
| 135 | + const iso = since.toISOString().slice(0, 10) |
| 136 | + const out: Episode[] = [] |
| 137 | + for (const repo of gitRepos(root)) { |
| 138 | + const name = repo === root ? "." : repo.slice(root.length + 1) |
| 139 | + try { |
| 140 | + const log = execFileSync( |
| 141 | + "git", |
| 142 | + ["-C", repo, "log", `--since=${iso}`, "--date=short", `--pretty=format:%ad${SEP}%h${SEP}%s`], |
| 143 | + { encoding: "utf8", maxBuffer: 128e6 }, |
| 144 | + ) |
| 145 | + for (const line of log.split("\n")) { |
| 146 | + const [date, sha, subject] = line.split(SEP) |
| 147 | + if (!date || !subject) continue |
| 148 | + out.push({ date, source: "git", title: subject, ref: `${name}@${sha}` }) |
| 149 | + } |
| 150 | + } catch { |
| 151 | + /* empty or unreadable */ |
| 152 | + } |
| 153 | + } |
| 154 | + return out |
| 155 | +} |
| 156 | + |
| 157 | +// -- opencode ----------------------------------------------------------------- |
| 158 | +function fromOpencode(since: Date): Episode[] { |
| 159 | + const base = join(homedir(), ".local", "share", "opencode", "storage", "session") |
| 160 | + if (!existsSync(base)) return [] |
| 161 | + const out: Episode[] = [] |
| 162 | + const walk = (dir: string) => { |
| 163 | + for (const e of readdirSync(dir, { withFileTypes: true })) { |
| 164 | + const p = join(dir, e.name) |
| 165 | + if (e.isDirectory()) walk(p) |
| 166 | + else if (e.name.endsWith(".json")) { |
| 167 | + try { |
| 168 | + const o = JSON.parse(readFileSync(p, "utf8")) |
| 169 | + const created = o?.time?.created |
| 170 | + if (!o?.title || !created) continue |
| 171 | + const d = new Date(created) |
| 172 | + if (d < since) continue |
| 173 | + out.push({ |
| 174 | + date: d.toISOString().slice(0, 10), |
| 175 | + source: "opencode", |
| 176 | + title: String(o.title), |
| 177 | + ref: o.id, |
| 178 | + }) |
| 179 | + } catch { |
| 180 | + /* skip */ |
| 181 | + } |
| 182 | + } |
| 183 | + } |
| 184 | + } |
| 185 | + try { |
| 186 | + walk(base) |
| 187 | + } catch { |
| 188 | + /* skip */ |
| 189 | + } |
| 190 | + return out |
| 191 | +} |
| 192 | + |
| 193 | +// -- claude code -------------------------------------------------------------- |
| 194 | +/** Titles and the first timestamp only — never message content. */ |
| 195 | +function fromClaude(since: Date): Episode[] { |
| 196 | + const base = join(homedir(), ".claude", "projects") |
| 197 | + if (!existsSync(base)) return [] |
| 198 | + const out: Episode[] = [] |
| 199 | + let projects: string[] = [] |
| 200 | + try { |
| 201 | + projects = readdirSync(base) |
| 202 | + } catch { |
| 203 | + return [] |
| 204 | + } |
| 205 | + |
| 206 | + for (const proj of projects) { |
| 207 | + const dir = join(base, proj) |
| 208 | + let files: string[] = [] |
| 209 | + try { |
| 210 | + files = readdirSync(dir).filter((f) => f.endsWith(".jsonl")) |
| 211 | + } catch { |
| 212 | + continue |
| 213 | + } |
| 214 | + for (const f of files) { |
| 215 | + const full = join(dir, f) |
| 216 | + try { |
| 217 | + if (statSync(full).mtime < since) continue |
| 218 | + } catch { |
| 219 | + continue |
| 220 | + } |
| 221 | + let title: string | null = null |
| 222 | + let date: string | null = null |
| 223 | + try { |
| 224 | + for (const line of readFileSync(full, "utf8").split("\n")) { |
| 225 | + if (!line) continue |
| 226 | + let o: any |
| 227 | + try { |
| 228 | + o = JSON.parse(line) |
| 229 | + } catch { |
| 230 | + continue |
| 231 | + } |
| 232 | + // custom-title is a human's word for it, and outranks the generated one. |
| 233 | + if (o.type === "custom-title" && o.customTitle) title = String(o.customTitle) |
| 234 | + else if (o.type === "ai-title" && o.aiTitle && !title) title = String(o.aiTitle) |
| 235 | + if (!date && o.timestamp) date = String(o.timestamp).slice(0, 10) |
| 236 | + } |
| 237 | + } catch { |
| 238 | + continue |
| 239 | + } |
| 240 | + if (title && date && new Date(date) >= since) { |
| 241 | + out.push({ date, source: "claude", title, ref: f.replace(/\.jsonl$/, "").slice(0, 8) }) |
| 242 | + } |
| 243 | + } |
| 244 | + } |
| 245 | + return out |
| 246 | +} |
| 247 | + |
| 248 | +const MARK: Record<string, string> = { diary: "D", git: "G", opencode: "O", claude: "C" } |
| 249 | + |
| 250 | +function warn(s: string): string { |
| 251 | + return `${UI.Style.TEXT_WARNING}${s}${UI.Style.TEXT_NORMAL}` |
| 252 | +} |
| 253 | + |
| 254 | +const TimelineCommand = cmd({ |
| 255 | + command: "timeline", |
| 256 | + aliases: ["history"], |
| 257 | + describe: "what happened across diary, git and coding sessions — grouped by week", |
| 258 | + builder: (y) => |
| 259 | + y |
| 260 | + .option("since", { type: "string", default: "4mo", describe: "window, e.g. 30d / 6w / 4mo / 1y" }) |
| 261 | + .option("source", { type: "string", describe: `comma-separated: ${SOURCES.join(",")}` }) |
| 262 | + .option("grep", { type: "string", describe: "only episodes whose title matches" }) |
| 263 | + .option("limit", { type: "number", default: 8, describe: "max lines per source per week" }) |
| 264 | + .option("json", { type: "boolean", default: false, describe: "JSON output" }), |
| 265 | + async handler(args) { |
| 266 | + const since = parseSince(String(args.since)) |
| 267 | + const sinceIso = since.toISOString().slice(0, 10) |
| 268 | + const want = new Set( |
| 269 | + (args.source ? String(args.source).split(",").map((s) => s.trim()) : [...SOURCES]).filter(Boolean), |
| 270 | + ) |
| 271 | + |
| 272 | + if (!args.json) { |
| 273 | + UI.empty() |
| 274 | + prompts.intro("◈ Timeline") |
| 275 | + console.log(dim(` since ${sinceIso}`)) |
| 276 | + } |
| 277 | + |
| 278 | + const perSource: Record<string, Episode[]> = {} |
| 279 | + if (want.has("diary")) perSource.diary = await fromDiary(since) |
| 280 | + if (want.has("git")) perSource.git = fromGit(process.cwd(), since) |
| 281 | + if (want.has("opencode")) perSource.opencode = fromOpencode(since) |
| 282 | + if (want.has("claude")) perSource.claude = fromClaude(since) |
| 283 | + |
| 284 | + let episodes = Object.values(perSource).flat().filter((e) => e.date >= sinceIso) |
| 285 | + if (args.grep) { |
| 286 | + const g = String(args.grep).toLowerCase() |
| 287 | + episodes = episodes.filter((e) => e.title.toLowerCase().includes(g)) |
| 288 | + } |
| 289 | + |
| 290 | + if (args.json) { |
| 291 | + console.log(JSON.stringify({ since: sinceIso, episodes }, null, 2)) |
| 292 | + return |
| 293 | + } |
| 294 | + |
| 295 | + /* COVERAGE IS PRINTED PER SOURCE, AND THAT IS THE POINT. These sources begin on different |
| 296 | + * dates — Claude Code only reaches back to mid-July, opencode to May — so a merged view with |
| 297 | + * no per-source range silently presents "nothing happened before May" as a fact about the |
| 298 | + * business rather than a fact about the instrument. */ |
| 299 | + printDivider() |
| 300 | + console.log() |
| 301 | + console.log(dim(" COVERAGE") + dim(" (a source that starts late is not a quiet period)")) |
| 302 | + for (const s of SOURCES) { |
| 303 | + if (!want.has(s)) continue |
| 304 | + const eps = perSource[s] ?? [] |
| 305 | + if (!eps.length) { |
| 306 | + console.log(` ${MARK[s]} ${bold(s.padEnd(9))} ${warn("0 episodes (no data in window)")}`) |
| 307 | + continue |
| 308 | + } |
| 309 | + const ds = eps.map((e) => e.date).sort() |
| 310 | + console.log( |
| 311 | + ` ${MARK[s]} ${bold(s.padEnd(9))} ${String(eps.length).padStart(5)} episodes ` + |
| 312 | + dim(`${ds[0]} → ${ds[ds.length - 1]}`), |
| 313 | + ) |
| 314 | + } |
| 315 | + console.log() |
| 316 | + |
| 317 | + if (!episodes.length) { |
| 318 | + console.log(dim(" Nothing in that window.")) |
| 319 | + console.log() |
| 320 | + prompts.outro("Done") |
| 321 | + return |
| 322 | + } |
| 323 | + |
| 324 | + const byWeek = new Map<string, Episode[]>() |
| 325 | + for (const e of episodes) { |
| 326 | + const k = weekKey(e.date) |
| 327 | + if (!byWeek.has(k)) byWeek.set(k, []) |
| 328 | + byWeek.get(k)!.push(e) |
| 329 | + } |
| 330 | + |
| 331 | + printDivider() |
| 332 | + const cap = Number(args.limit) |
| 333 | + for (const [wk, eps] of [...byWeek.entries()].sort((a, b) => b[0].localeCompare(a[0]))) { |
| 334 | + console.log() |
| 335 | + console.log(` ${highlight("week of " + wk)} ${dim(String(eps.length))}`) |
| 336 | + for (const s of SOURCES) { |
| 337 | + const rows = eps.filter((e) => e.source === s).sort((a, b) => b.date.localeCompare(a.date)) |
| 338 | + if (!rows.length) continue |
| 339 | + for (const r of rows.slice(0, cap)) { |
| 340 | + console.log(` ${MARK[s]} ${dim(r.date)} ${r.title.slice(0, 86)}`) |
| 341 | + } |
| 342 | + // Never truncate silently — say what was left out and how to see it. |
| 343 | + if (rows.length > cap) { |
| 344 | + console.log(dim(` … ${rows.length - cap} more from ${s} this week (raise --limit)`)) |
| 345 | + } |
| 346 | + } |
| 347 | + } |
| 348 | + |
| 349 | + console.log() |
| 350 | + printDivider() |
| 351 | + console.log(` ${bold(String(episodes.length))} episodes · ${bold(String(byWeek.size))} weeks`) |
| 352 | + console.log(dim(" Nothing here was summarised by a model — every line was already written.")) |
| 353 | + console.log() |
| 354 | + prompts.outro("Done") |
| 355 | + }, |
| 356 | +}) |
| 357 | + |
| 358 | +export const TimelineCommands = [TimelineCommand] |
0 commit comments