#!/usr/bin/env node // Built So Far — local scanner. // Reads coding-agent history and git metadata on THIS machine and writes aggregated // facts to a local file. It makes no network requests and uploads nothing. // Usage: node scan.mjs [--year 2026] [--out recap-scan.json] // To read the messages behind something in the scan (prints to the terminal, writes nothing): // node scan.mjs --messages "[,]" [--about ""] [--limit 60] // (use --messages "*" to search every project folder) import fs from 'node:fs'; import path from 'node:path'; import os from 'node:os'; import readline from 'node:readline'; import { execFileSync } from 'node:child_process'; const arg = (k, d) => { const i = process.argv.indexOf(k); return i > 0 ? process.argv[i + 1] : d; }; const YEAR = +arg('--year', new Date().getFullYear()); const OUT = arg('--out', 'recap-scan.json'); const MESSAGES = arg('--messages', null), ABOUT = (arg('--about', '') || '').toLowerCase(), LIMIT = +arg('--limit', 60); const HOME = os.homedir(); const Y0 = new Date(YEAR, 0, 1).getTime(), Y1 = new Date(YEAR + 1, 0, 1).getTime(); const projects = new Map(); // root path -> stats const daily = new Map(); // yyyy-mm-dd -> prompts const hours = Array(24).fill(0); const phrases = new Map(); // normalised short prompt -> {count, example} const models = new Map(); const sources = {}; let sessions = 0, prompts = 0, images = 0, interruptions = 0, compactions = 0, approvals = 0, opinions = 0; const weekday = Array(7).fill(0), dayRoots = new Map(), sidTs = new Map(); // build-habit signals const tok = new Map(), tokSeen = new Set(); let tokOut = 0, tokProcessed = 0; // tokens the agents wrote, per project root const quals = new Map(); // "more obvious" -> count const fam = {}; // word families -> prompts containing them const convo = new Map(); // session -> {n, first, last, root} let longest = { chars: 0, project: null }; const FAMILIES = { too_anything: /\btoo [a-z]{3,}\b/, please: /\bplease\b|\bpls\b/, thanks: /\bthanks?\b|thank you/, bigger_smaller: /\b(bigger|smaller|larger|tinier)\b/, start_over: /start over|from scratch|\bredo\b|\brevert\b|\bundo\b|roll ?back/, screenshot_mentions: /screenshot/, laughs: /\blol\b|\bhaha+\b|\blmao\b/, swearing: /\bfuck|\bshit\b|\bdamn\b|\bwtf\b/, still_broken: /\bstill (not|doesn'?t|broken|wrong|the same)/, why_questions: /^why\b/, one_more_thing: /one more thing|one last thing|also,? can you/, make_it_pop: /\bpop\b|\bpunchier\b|\bbolder\b/, simpler: /\b(minimal|simpler|simple|cleaner|clean)\b/, premium: /\b(premium|polish|polished|elegant|refined|tasteful)\b/ }; const VAGUE = new Set('same first second last next other whole way one two new current main right left top bottom user users thing things text page website app code design part time moment rest end start middle following above below problem issue reason idea case example'.split(' ')); // Words every interface has. Things named with these are listed after the builder's more distinctive ones. const GENERIC = new Set('background description image images font fonts home page homepage screen screens name names option options visual visuals working tree card cards list lists button buttons panel panels size height width view views block blocks line lines table tables content section sections color colors colour title titles header footer menu icon icons logo layout border padding spacing margin video videos agent agents script chat search place places'.split(' ').concat(['home page', 'working tree'])); const GLUE = new Set('that this when with from should have will more into they also need does looks like just your because then which where what there here only still after before could would'.split(' ')); const ROUTINE = /^(yes|yep|ok|okay|go|commit|push|deploy|merge|approve|continue|next|try again|done|start|build|run|ship|proceed|sure|no|not now|keep|reply with)\b/; const dayKey = t => { const d = new Date(t); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; }; const bump = (m, k, n = 1) => m.set(k, (m.get(k) || 0) + n); // A working directory is a "project" unless it is home, a temp dir, or app scratch space. function rootOf(cwd) { if (!cwd) return null; let p = cwd.split('/.claude/worktrees/')[0].split('/.codex/worktrees/')[0].replace(/\/+$/, ''); if (p === HOME || p === path.join(HOME, 'Desktop') || p === path.join(HOME, 'Documents')) return null; if (/^(\/private)?\/tmp\b|\/var\/folders\/|\/Library\/Application Support\/|\/\.claude\/|\/\.codex\/|\/\.slock\//.test(p)) return null; return p; } function proj(root) { if (!projects.has(root)) projects.set(root, { name: path.basename(root), path: root, sessions: 0, prompts: 0, days: new Set(), first: null, last: null, agents: new Set(), all: [], monthly: Array(12).fill(0), elem: new Map(), deploy: 0 }); return projects.get(root); } // Real typed prompts only: skip injected context, tool results, slash commands. function cleanPrompt(text) { if (typeof text !== 'string') return null; const t = text.trim(); if (!t || t.startsWith('<') || t.startsWith('/') || t.startsWith('[') || t.startsWith('Caveat:') || t.startsWith('This session is being continued') || t.startsWith('# In app browser') || t.startsWith('New message received:')) return null; return t; } // People paste keys, passwords and addresses into prompts. Blank them out the moment a prompt is read, so nothing that // looks like a secret can reach the scan file, the --messages output, or the agent reading either. const SECRETS = [ [/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(-----END [A-Z ]*PRIVATE KEY-----|$)/g, '[private key removed]'], [/\b(sk-[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|AKIA[0-9A-Z]{16}|xox[abprs]-[A-Za-z0-9-]{10,}|AIza[0-9A-Za-z_-]{30,}|eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{5,})/g, '[key removed]'], [/\b(Bearer|Basic)\s+[A-Za-z0-9._~+\/=-]{16,}/gi, '$1 [key removed]'], [/\b(pass(word|wd)?|secret|token|api[_-]?key|access[_-]?key|auth|credential)s?(["']?\s*[:=]\s*["']?)[^\s"',;]{6,}/gi, '$1$3[removed]'], [/(\/\/)[^\s\/:@]+:[^\s\/@]+@/g, '$1[login removed]@'], [/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g, '[email removed]'], [/\b(?=[A-Za-z0-9+\/_-]*\d)(?=[A-Za-z0-9+\/_-]*[A-Za-z])[A-Za-z0-9+\/_-]{40,}={0,2}/g, '[long code removed]'], ]; // Identifying details are removed too: links and site names, usernames, file paths, long ids, and the builder's own // name and email name as git knows them. Names the script cannot recognise (people, clients) may remain in the local // file; the agent is told never to put them in the recap. const escRe = x => x.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); const gitGlobal = k => { try { return execFileSync('git', ['config', '--global', k], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim(); } catch { return ''; } }; const MY_NAME = gitGlobal('user.name'), MY_MAIL = gitGlobal('user.email'), OS_USER = (() => { try { return os.userInfo().username; } catch { return ''; } })(); const IDENT = [ [/\bhttps?:\/\/[^\s)>\]"'`]+/g, '[link]'], [/\b(?:[a-z0-9-]+\.)+(?:com|io|dev|app|ai|org|net|co|xyz|me|so|design|studio|site|tech|page|sh|gg|tv|fm|edu)\b(?:\/[^\s)>\]"'`]*)?/gi, '[site]'], [/(?:\/Users|\/home)\/[^\/\s"'`]+/g, '~'], [/(^|[\s(])@[A-Za-z0-9][A-Za-z0-9_-]{2,}/g, '$1[handle]'], [/\b[a-f0-9]{24,}\b/gi, '[id removed]'], [/\b(?=[A-Za-z0-9_-]*\d)(?=[A-Za-z0-9_-]*[A-Za-z])[A-Za-z0-9_-]{32,}\b/g, '[id removed]'], ]; if (MY_NAME.length >= 5 && /\s/.test(MY_NAME)) IDENT.push([new RegExp(escRe(MY_NAME), 'gi'), '[me]']); for (const u of new Set([OS_USER, MY_MAIL.split('@')[0]])) if (u && u.length >= 4) IDENT.push([new RegExp('\\b' + escRe(u) + '\\b', 'gi'), '[me]']); const redact = t => [...SECRETS, ...IDENT].reduce((x, [re, to]) => x.replace(re, to), t); // Messages about private matters are still counted, but their text is never excerpted or printed. const PERSONAL = /\b(resume|résumé|curriculum vitae|cover letter|job description|job posting|job application|interview(s|ing|er)?|recruiter|salary|offer letter|take[- ]home|visa|immigration|diagnos\w*|medication|therapy|therapist|bank account|social security|passport|landlord|lawsuit|divorce)\b/i; const buf = []; function record(root, agent, ts, text, sid) { if (!(ts >= Y0 && ts < Y1)) return false; buf.push([root, agent, ts, redact(text), sid]); return true; } function tally(root, agent, ts, text, sid) { const low = text.toLowerCase(); // Habit phrases are counted only in shorter messages: long ones are usually pasted briefs or documents, not something said in passing. if (text.length <= 800) for (const k in FAMILIES) if (FAMILIES[k].test(low)) fam[k] = (fam[k] || 0) + 1; if (text.length <= 800) for (const q of new Set([...low.matchAll(/\b(more|less|too) ([a-z]{3,})\b/g)].map(m => m[1] + ' ' + m[2]))) bump(quals, q); // one count per prompt, however often the phrase repeats in it if (text.length <= 40 && /^(yes|yep|yeah|ok|okay|sure|go|go ahead|do it|approve|continue|proceed|push it|ship it|sounds good|looks good)\b/i.test(text) && text.split(/\s+/).length <= 5) approvals++; if (text.length <= 800 && /what do you think|do you think|other (options|choices|ways|ideas)|more options|any better|alternatives|your (opinion|take|recommendation)|which (one )?(is better|would you)/i.test(text)) opinions++; weekday[new Date(ts).getDay()]++; if (root) { const dk = dayKey(ts); if (!dayRoots.has(dk)) dayRoots.set(dk, new Set()); dayRoots.get(dk).add(root); } if (!sidTs.has(sid)) sidTs.set(sid, []); sidTs.get(sid).push(ts); const cv = convo.get(sid) || { n: 0, first: ts, last: ts, root }; cv.n++; cv.first = Math.min(cv.first, ts); cv.last = Math.max(cv.last, ts); convo.set(sid, cv); if (text.length > longest.chars) longest = { chars: text.length, project: root && path.basename(root) }; prompts++; bump(daily, dayKey(ts)); hours[new Date(ts).getHours()]++; if (root) { const p = proj(root); p.prompts++; p.days.add(dayKey(ts)); p.agents.add(agent); p.first = Math.min(p.first ?? ts, ts); p.last = Math.max(p.last ?? ts, ts); if (text.length <= 800 && /\b(re)?deploy(ed|ing|ment)?\b|\bvercel\b|\bnetlify\b|go(es)? live|push (it )?live|\bin production\b/i.test(text)) p.deploy++; // What did they keep coming back to? Record each named thing ("the clouds") against the days it was mentioned. if (text.length <= 900) for (const m of new Set([...text.toLowerCase().matchAll(/\bthe ([a-z]{4,}(?: [a-z]{4,})?)/g)].map(x => x[1]))) { const w = m.split(' '), k = (w[1] && GLUE.has(w[1])) ? w[0] : m; if (VAGUE.has(k) || VAGUE.has(w[0])) continue; if (!p.elem.has(k)) p.elem.set(k, new Set()); p.elem.get(k).add(dayKey(ts)); } p.monthly[new Date(ts).getMonth()]++; if (text.length > 40 && !PERSONAL.test(text)) p.all.push([ts, text.slice(0, 220).replace(/\s+/g, ' ')]); } if (text.length <= 80) { const n = text.toLowerCase().replace(/[^\p{L}\p{N}\s']/gu, ' ').replace(/\s+/g, ' ').trim(); if (n.split(' ').length >= 2 && !ROUTINE.test(n)) { const e = phrases.get(n) || { count: 0, example: text }; e.count++; phrases.set(n, e); } } return true; } async function lines(file, fn) { const rl = readline.createInterface({ input: fs.createReadStream(file), crlfDelay: Infinity }); for await (const l of rl) { if (!l) continue; let d; try { d = JSON.parse(l); } catch { continue; } fn(d); } } function walk(dir, out = []) { let ents; try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch { return out; } for (const e of ents) { const f = path.join(dir, e.name); if (e.isDirectory()) walk(f, out); else if (e.name.endsWith('.jsonl')) out.push(f); } return out; } // ---- Claude Code: ~/.claude/projects//.jsonl async function claudeCode() { const base = path.join(HOME, '.claude', 'projects'); if (!fs.existsSync(base)) return; let n = 0; for (const dir of fs.readdirSync(base)) { for (const f of fs.readdirSync(path.join(base, dir)).filter(x => x.endsWith('.jsonl'))) { let root, hit = false; await lines(path.join(base, dir, f), d => { const u = d.type === 'assistant' && d.message?.usage; if (u) { const t = Date.parse(d.timestamp), key = d.message.id + '|' + d.requestId; if (t >= Y0 && t < Y1 && !tokSeen.has(key)) { tokSeen.add(key); const r = rootOf(d.cwd); tokOut += u.output_tokens || 0; tokProcessed += (u.input_tokens || 0) + (u.cache_creation_input_tokens || 0) + (u.cache_read_input_tokens || 0) + (u.output_tokens || 0); if (r) bump(tok, r, u.output_tokens || 0); } } if (d.isSidechain) return; if (root === undefined && d.cwd) root = rootOf(d.cwd); const ts = Date.parse(d.timestamp); if (d.type === 'assistant' && d.message?.model && ts >= Y0 && ts < Y1) bump(models, d.message.model); if (d.type !== 'user' || d.isMeta || d.toolUseResult) return; const c = d.message?.content; if (ts >= Y0 && ts < Y1 && JSON.stringify(c || '').includes('Request interrupted by user')) { interruptions++; return; } if (ts >= Y0 && ts < Y1 && d.type === 'user' && !d.isSidechain && JSON.stringify(c || '').slice(0, 200).includes('This session is being continued from a previous conversation')) compactions++; if (Array.isArray(c) && c.some(b => b.type === 'image') && ts >= Y0 && ts < Y1) images++; const text = cleanPrompt(typeof c === 'string' ? c : Array.isArray(c) && !c.some(b => b.type === 'tool_result') ? c.filter(b => b.type === 'text').map(b => b.text).join('\n') : null); if (text && record(root, 'claude-code', ts, text, f)) hit = true; }); if (hit) { sessions++; n++; if (root) proj(root).sessions++; } } } if (n) sources['claude-code'] = n; } // ---- Codex: ~/.codex/sessions/**/rollout-*.jsonl (+ archived_sessions) async function codex() { const files = [...walk(path.join(HOME, '.codex', 'sessions')), ...walk(path.join(HOME, '.codex', 'archived_sessions'))]; // Sessions imported from another agent are copies (already counted at their source), and // sub-agent sessions are not prompts the builder typed — skip both. let imported = new Set(); try { imported = new Set(JSON.parse(fs.readFileSync(path.join(HOME, '.codex', 'external_agent_session_imports.json'), 'utf8')).records.map(r => r.imported_thread_id)); } catch {} let n = 0; for (const f of files) { let root, hit = false, skip = false, cx = 0; await lines(f, d => { if (skip) return; const p = d.payload || {}; if (d.type === 'event_msg' && p.type === 'token_count') { const ts2 = Date.parse(d.timestamp); if (ts2 >= Y0 && ts2 < Y1) cx = Math.max(cx, p.info?.total_token_usage?.output_tokens || 0); return; } if (d.type === 'session_meta') { root = rootOf(p.cwd); skip = imported.has(p.id) || imported.has(p.session_id) || (p.source && typeof p.source !== 'string') || !!p.parent_thread_id; return; } const ts = Date.parse(d.timestamp); if (d.type === 'turn_context' && p.model && ts >= Y0 && ts < Y1) bump(models, p.model); if (d.type !== 'response_item' || p.type !== 'message' || p.role !== 'user') return; const text = cleanPrompt((p.content || []).filter(b => b.type === 'input_text').map(b => b.text).join('\n')); if (text && record(root, 'codex', ts, text, f)) hit = true; }); if (cx && !skip) { tokOut += cx; tokProcessed += cx; if (root) bump(tok, root, cx); } if (hit) { sessions++; n++; if (root) proj(root).sessions++; } } if (n) sources['codex'] = n; } // ---- git: commit counts and commit days for each project folder that still exists function git(root, args) { try { return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 15000 }).trim(); } catch { return ''; } } function gitFacts(p) { if (!fs.existsSync(path.join(p.path, '.git'))) return { exists: fs.existsSync(p.path) }; // Count only the builder's own commits: a cloned or shared repo is full of other people's. const me = git(p.path, ['config', 'user.email']).toLowerCase(); const log = git(p.path, ['log', `--since=${YEAR}-01-01`, `--until=${YEAR + 1}-01-01`, '--format=%ad|%ae', '--date=short']); const rows = log ? log.split('\n').map(l => l.split('|')) : []; const days = (me ? rows.filter(r => (r[1] || '').toLowerCase() === me) : rows).map(r => r[0]); const others = rows.length - days.length; days.forEach(d => p.days.add(d)); const has = f => fs.existsSync(path.join(p.path, f)); return { exists: true, git: true, commits: days.length, ...(others ? { commits_by_others: others } : {}), ...(me ? {} : { commit_author_unknown: true }), has_remote: !!git(p.path, ['remote']), deploy_config: ['vercel.json', '.vercel', 'netlify.toml', 'fly.toml', 'Dockerfile', 'wrangler.toml'].filter(has), stack_files: ['package.json', 'pyproject.toml', 'requirements.txt', 'Cargo.toml', 'go.mod', 'Package.swift', 'next.config.js', 'next.config.ts', 'next.config.mjs', 'vite.config.ts', 'vite.config.js'].filter(has) }; } // Evenly spaced prompts across a project's life, so the agent can see how it evolved. function sample(all, k) { all.sort((a, b) => a[0] - b[0]); if (all.length <= k) return all.map(x => `${dayKey(x[0])}: ${x[1]}`); return Array.from({ length: k }, (_, i) => all[Math.round(i * (all.length - 1) / (k - 1))]).map(x => `${dayKey(x[0])}: ${x[1]}`); } function habits() { const NOT_ADJ = new Set(['than', 'about', 'like', 'just', 'the', 'and', 'for', 'that', 'this', 'time', 'with', 'from', 'info', 'information', 'details', 'context', 'space']); const q = [...quals].filter(([k]) => !NOT_ADJ.has(k.split(' ')[1])); const get = k => quals.get(k) || 0, contradictions = []; for (const adj of new Set(q.map(([k]) => k.split(' ')[1]))) { const more = get('more ' + adj), back = get('too ' + adj) + get('less ' + adj); if (more >= 4 && back >= 4) contradictions.push({ word: adj, asked_for_more: more, said_too_or_less: back }); } const cv = [...convo.values()].sort((a, b) => b.n - a.n)[0]; const busiest = [...daily].sort((a, b) => b[1] - a[1])[0]; const late = hours[23] + hours[0] + hours[1] + hours[2] + hours[3]; let rapid = 0; for (const a of sidTs.values()) { a.sort((x, y) => x - y); for (let i = 1; i < a.length; i++) if (a[i] - a[i - 1] < 90000) rapid++; } const busiestRoots = [...dayRoots].sort((a, b) => b[1].size - a[1].size)[0]; const build = { note: 'Build habits: how the builder works, not how they type.', interruptions, rapid_followups_within_90s: rapid, weekday_prompts_sun_to_sat: weekday, most_project_folders_in_one_day: busiestRoots && { day: busiestRoots[0], folders: busiestRoots[1].size }, times_agent_ran_out_of_context: compactions, short_approvals: approvals, asked_agent_for_opinion_or_options: opinions, prompts_between_midnight_and_5am: hours[0] + hours[1] + hours[2] + hours[3] + hours[4], weekend_prompts: weekday[0] + weekday[6], sessions_started_by_own_pipelines: genSessions.size, pipeline_templates: pipes, do_overs: fam.start_over || 0, screenshots_pasted: images }; return { build, note: 'Word-level patterns. Counts are prompts containing the pattern.', contradictions: contradictions.sort((a, b) => b.asked_for_more + b.said_too_or_less - a.asked_for_more - a.said_too_or_less).slice(0, 8), pet_qualifiers: q.sort((a, b) => b[1] - a[1]).slice(0, 20).map(([k, v]) => ({ phrase: k, count: v })), word_families: fam, screenshots_pasted: images, longest_conversation: cv && { prompts: cv.n, days: Math.round((cv.last - cv.first) / 864e5) + 1, project: cv.root && path.basename(cv.root) }, longest_prompt: longest, busiest_day: busiest && { day: busiest[0], prompts: busiest[1] }, late_night_share: prompts ? +(late / prompts).toFixed(3) : 0, peak_hour: hours.indexOf(Math.max(...hours)) }; } await claudeCode(); await codex(); // Prompts written by the builder's own pipelines (agents prompting agents) are long and share // an opening once names, quotes and dates are removed. Count them separately, not as typed. const tkey = t => t.toLowerCase().replace(/[“"][^”"]*[”"]/g, '').replace(/\S*\d\S*/g, '').replace(/\s+/g, ' ').slice(0, 30); const tcount = new Map(); for (const r of buf) if (r[3].length > 150) bump(tcount, tkey(r[3])); // Other people who committed to these repos: remove their names from the builder's messages as well. { const mine = MY_MAIL.toLowerCase(), names = new Set(); for (const root of new Set(buf.map(r => r[0]).filter(Boolean))) { if (!fs.existsSync(path.join(root, '.git'))) continue; const me = (git(root, ['config', 'user.email']) || mine).toLowerCase(); for (const l of new Set(git(root, ['log', `--since=${YEAR}-01-01`, '--format=%an|%ae']).split('\n'))) { const [n, e] = l.split('|'); if (n && e && e.toLowerCase() !== me && e.toLowerCase() !== mine && !/bot|noreply|\[/i.test(n + e)) { if (n.length >= 5) names.add(n); const f = n.split(/\s+/)[0]; if (f.length >= 4 && /^[A-Z][a-z]+$/.test(f)) names.add(f); } } } if (names.size) { const re = new RegExp('\\b(' + [...names].sort((a, b) => b.length - a.length).map(escRe).join('|') + ')\\b', 'g'); for (const r of buf) r[3] = r[3].replace(re, '[someone]'); } } // --messages: print the builder's own typed prompts for one or more project folders, optionally only those mentioning // a word, then stop. Prompts written by their pipelines are left out, so the count matches the scan's `prompts`. if (MESSAGES) { const wants = MESSAGES.toLowerCase().split(',').map(x => x.trim()).filter(Boolean), all = wants.includes('*'); const typed = buf.filter(r => !(r[3].length > 150 && tcount.get(tkey(r[3])) >= 4)); const hits = typed.filter(r => r[0] && (all || wants.some(w => path.basename(r[0]).toLowerCase().includes(w))) && (!ABOUT || r[3].toLowerCase().includes(ABOUT))).sort((a, b) => a[2] - b[2]); const pick = hits.length <= LIMIT ? hits : Array.from({ length: LIMIT }, (_, i) => hits[Math.round(i * (hits.length - 1) / (LIMIT - 1))]); console.log(`${hits.length} typed prompts in ${all ? 'all project folders' : 'folders matching "' + wants.join('", "') + '"'}${ABOUT ? ` that mention "${ABOUT}"` : ''}${hits.length > pick.length ? `; showing ${pick.length} spread across them` : ''}. Links, usernames and anything that looks like a secret are blanked out. Nothing was written or uploaded.\n`); for (const r of pick) console.log(`${dayKey(r[2])} [${path.basename(r[0])}] ${PERSONAL.test(r[3]) ? '(a message about a personal matter, left out)' : r[3].replace(/\s+/g, ' ').slice(0, 700)}\n`); process.exit(0); } let generated = 0; const genSessions = new Set(), tpl = new Map(); for (const r of buf) { if (r[3].length > 150 && tcount.get(tkey(r[3])) >= 4) { generated++; genSessions.add(r[4]); if (r[0]) { const p = proj(r[0]); p.generated = (p.generated || 0) + 1; } const k = tkey(r[3]), e = tpl.get(k) || { opening: r[3].replace(/\s+/g, ' ').slice(0, 90), prompts: 0, sessions: new Set(), project: r[0] && path.basename(r[0]) }; e.prompts++; e.sessions.add(r[4]); tpl.set(k, e); continue; } tally(...r); } // Each repeated opening is one pipeline. Listed so the agent can tell real delegation from test runs. const pipes = [...tpl.values()].sort((a, b) => b.sessions.size - a.sessions.size).slice(0, 20).map(e => ({ opening: e.opening, prompts: e.prompts, sessions: e.sessions.size, project: e.project })); const typedSessions = [...convo.values()]; const commitDays = new Map(); const projList = [...projects.values()].filter(p => p.prompts > 0 || p.generated > 0).map(p => { const g = gitFacts(p); return { name: p.name, path: p.path.replace(HOME, '~'), sessions: typedSessions.filter(c => c.root === p.path).length, prompts: p.prompts, generated_prompts: p.generated || 0, output_tokens: tok.get(p.path) || 0, active_days: p.days.size, active_dates: [...p.days].filter(d => d.startsWith(String(YEAR))).sort().map(d => d.slice(5)), deploy_mentions: p.deploy, first: p.first && dayKey(p.first), last: p.last && dayKey(p.last), agents: [...p.agents], ...g, monthly: p.monthly, samples: sample(p.all, 8), revisited: [...p.elem].filter(([, d]) => d.size >= 3).sort((a, b) => (GENERIC.has(a[0]) - GENERIC.has(b[0])) || b[1].size - a[1].size).slice(0, 8).map(([thing, d]) => { const ds = [...d].sort(); return { thing, days: ds.length, first: ds[0], last: ds[ds.length - 1] }; }), _days: p.days }; }).sort((a, b) => b.prompts - a.prompts); // Daily series for the whole year so far: prompts per day, plus days that only had commits. const allDays = new Set(daily.keys()); projList.forEach(p => p._days.forEach(d => { if (d.startsWith(String(YEAR))) allDays.add(d); })); const end = Math.min(Date.now(), Y1 - 1), series = []; for (let t = Y0; t <= end; t += 864e5) { const k = dayKey(t + 432e5); series.push(daily.get(k) || (allDays.has(k) ? 1 : 0)); } projList.forEach(p => delete p._days); const out = { scanner: 3, year: YEAR, generated: new Date().toISOString(), coverage: { sources, first_day: [...allDays].sort()[0] || null, last_day: [...allDays].sort().pop() || null, note: 'Counts cover only agent history still stored on this machine and git repos in folders that still exist. sources counts every session per agent, including pipeline-started ones; totals.sessions counts only sessions with typed prompts. Commits are the builder\'s own (matched on git user.email).' }, totals: { projects: projList.length, sessions: typedSessions.length, prompts, generated_prompts: generated, generated_sessions: genSessions.size, output_tokens: tokOut, output_tokens_outside_projects: tokOut - [...tok.values()].reduce((a, b) => a + b, 0), tokens_processed: tokProcessed, active_days: series.filter(Boolean).length, commits: projList.reduce((a, p) => a + (p.commits || 0), 0) }, daily: series, hours, models: Object.fromEntries([...models].sort((a, b) => b[1] - a[1]).slice(0, 8)), habits: habits(), repeated_prompts: [...phrases].filter(([, v]) => v.count >= 3).sort((a, b) => b[1].count - a[1].count).slice(0, 40).map(([k, v]) => ({ text: v.example, normalised: k, count: v.count })), projects: projList, }; fs.writeFileSync(OUT, JSON.stringify(out, null, 1)); console.log(`Scanned ${typedSessions.length} sessions, ${prompts} typed prompts (+${generated} pipeline-generated), ${projList.length} project folders, ${out.totals.active_days} active days in ${YEAR}.`); console.log(`Wrote ${OUT} (local file, nothing was uploaded).`);