@letsrebase/verify 0.0.0-stage → 0.1.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.
Files changed (49) hide show
  1. package/.claude/commands/rebase-verify.md +118 -0
  2. package/LICENSE +21 -0
  3. package/PRIVACY.md +113 -0
  4. package/README.md +209 -2
  5. package/SECURITY.md +33 -0
  6. package/bin/rebase-verify.mjs +699 -0
  7. package/package.json +38 -4
  8. package/share/practices.json +224 -0
  9. package/share/tech-labels.json +57 -0
  10. package/share/tech-lexicon.json +62 -0
  11. package/src/adapters/claude-code.mjs +225 -0
  12. package/src/adapters/codex.mjs +476 -0
  13. package/src/adapters/cursor.mjs +584 -0
  14. package/src/adapters/kimi.mjs +594 -0
  15. package/src/adapters/omp.mjs +59 -0
  16. package/src/adapters/opencode.mjs +439 -0
  17. package/src/adapters/pi.mjs +414 -0
  18. package/src/adapters/tool-vocab.mjs +15 -0
  19. package/src/agent-run.mjs +10 -0
  20. package/src/agentic-literacy.mjs +211 -0
  21. package/src/agents/acp.mjs +364 -0
  22. package/src/agents/json-answer.mjs +72 -0
  23. package/src/agents/registry.mjs +370 -0
  24. package/src/agents/run.mjs +131 -0
  25. package/src/ai-relationship.mjs +95 -0
  26. package/src/consistency.mjs +357 -0
  27. package/src/days.mjs +45 -0
  28. package/src/digest.mjs +501 -0
  29. package/src/distribution.mjs +54 -0
  30. package/src/enrich.mjs +118 -0
  31. package/src/fingerprint.mjs +134 -0
  32. package/src/forensics.mjs +178 -0
  33. package/src/groundedness.mjs +347 -0
  34. package/src/hub.mjs +136 -0
  35. package/src/intensity.mjs +132 -0
  36. package/src/live-status.mjs +79 -0
  37. package/src/practices-llm.mjs +90 -0
  38. package/src/practices-rules.mjs +295 -0
  39. package/src/practices-sample.mjs +111 -0
  40. package/src/practices.mjs +272 -0
  41. package/src/profile-llm.mjs +249 -0
  42. package/src/profile.mjs +497 -0
  43. package/src/redact.mjs +97 -0
  44. package/src/sources.mjs +91 -0
  45. package/src/submit.mjs +65 -0
  46. package/src/system-text.mjs +3 -0
  47. package/src/tech-usage.mjs +88 -0
  48. package/src/trajectory.mjs +264 -0
  49. package/src/wizard.mjs +411 -0
package/src/digest.mjs ADDED
@@ -0,0 +1,501 @@
1
+ // Per-project digest: the deep, LLM-ready material the profile is written from.
2
+ //
3
+ // Beyond sampled prompts, this reconstructs project CONTEXT from the tool inputs
4
+ // (the files touched draw the domain), detects the stack, reads "landing"
5
+ // signals (did checks run, did work get committed vs reverted), and the
6
+ // learning trajectory (what was searched for). Everything stays redacted and
7
+ // keyed by repo, so worktrees of one product collapse into one project.
8
+
9
+ import { readFileSync, existsSync, readdirSync } from "node:fs";
10
+ import { join } from "node:path";
11
+ import { monthKeyFor, DEFAULT_TZ } from "./days.mjs";
12
+
13
+ const ms = (iso) => (iso ? Date.parse(iso) : NaN);
14
+ const month = (iso) => (iso ? new Date(ms(iso)).toISOString().slice(0, 7) : null);
15
+
16
+ const DELEGATION = new Set(["Task", "Agent"]);
17
+ const PLANNING = new Set(["TodoWrite", "ExitPlanMode"]);
18
+ const MUTATION = new Set(["Edit", "Write", "NotebookEdit", "MultiEdit"]);
19
+ const RESEARCH = new Set(["Read", "Grep", "Glob", "WebSearch", "WebFetch"]);
20
+
21
+ // Ephemeral sandboxes (background tasks) are not real projects. Anchored to
22
+ // the scratch ROOTS (/tmp, /var/folders, with the macOS /private alias) —
23
+ // matching anywhere in the path silently dropped real projects under
24
+ // directories merely named tmp/ or private/ (e.g. ~/tmp/scratchpad-app).
25
+ export const isEphemeral = (cwd) => /^\/(?:private\/)?(?:tmp|var\/folders)\//.test(cwd);
26
+
27
+ // Cluster sessions by product: the repo segment of the working dir.
28
+ export function repoKey(cwd) {
29
+ const m = cwd.match(/\/(?:Github|github|repos?|Projects|Desktop|src|code|dev|work)\/([^/]+)/);
30
+ if (m) return m[1];
31
+ const parts = cwd.split("/").filter((p) => p && p !== "⟨user⟩" && p !== "Users");
32
+ return parts.at(-1) || "unknown";
33
+ }
34
+
35
+ // Reduce an absolute (redacted) path to a 2-3 level repo-relative "area".
36
+ function toArea(path, key) {
37
+ const i = path.indexOf("/" + key + "/");
38
+ if (i < 0) return null;
39
+ let parts = path.slice(i + key.length + 2).split("/").filter(Boolean);
40
+ if (parts.length > 1 && /(-(app|web|api|server|client))$|^(apps|packages|src|web|app)$/.test(parts[0])) {
41
+ parts = parts.slice(1);
42
+ }
43
+ return parts.slice(0, 3).join("/") || null;
44
+ }
45
+
46
+ // --- Stack detection -------------------------------------------------------
47
+ //
48
+ // Two evidence streams, merged. They answer different questions and both belong:
49
+ // 1. package.json DEPENDENCIES across workspaces — what the project *uses*.
50
+ // 2. The files and commands the sessions actually TOUCHED — what the candidate
51
+ // *worked with*, anchored to evidence (file extensions + command text).
52
+ //
53
+ // We never read .env, not even key names (CONTRIBUTING: privacy — "the tool
54
+ // never opens your secrets file"). The cost is that services integrated only
55
+ // over REST (an API key, no npm package) are not auto-detected; that is a
56
+ // disclosed boundary (see the stack note in src/profile.mjs), not a silent miss.
57
+ //
58
+ // Path heuristics are NOT used for libraries: a route that contains the word
59
+ // "prisma" or a stray vite.config is not evidence the project depends on it.
60
+ // Libraries come from dependencies; languages/formats from touched extensions;
61
+ // runnable tools from command text.
62
+
63
+ // File extension -> language/format label. The "extension tally": a touched
64
+ // file is direct evidence the candidate worked with that language/format.
65
+ const EXT_LABELS = {
66
+ py: "Python", rb: "Ruby", go: "Go", rs: "Rust", java: "Java", kt: "Kotlin",
67
+ swift: "Swift", php: "PHP", sql: "SQL", sh: "Shell", vue: "Vue",
68
+ svelte: "Svelte", mdx: "MDX", tf: "Terraform", proto: "Protobuf",
69
+ };
70
+
71
+ // Command-text evidence: tools that surface in what the candidate actually RAN
72
+ // and that dependency scanning can't see (Python-ecosystem tools, deploy CLIs).
73
+ // LIBRARIES are deliberately NOT detected here — they come from dependencies
74
+ // only, so a library merely mentioned in a command never becomes a false
75
+ // positive (this is what produced the spurious "Prisma" the issue flagged).
76
+ // Anchored to a whitespace-delimited token so `cat docs/fastapi-notes.md` does
77
+ // NOT match — only a tool in executable/argument position does.
78
+ const CMD_LABELS = [
79
+ [/(?:^|\s)(?:uvicorn|fastapi|starlette)(?:\s|$)/im, "FastAPI"],
80
+ [/(?:^|\s)pytest(?:\s|$)/im, "pytest"],
81
+ [/(?:^|\s)wrangler(?:\s|$)/im, "Cloudflare"],
82
+ ];
83
+
84
+ // Dependency name -> label. Authoritative for libraries.
85
+ const DEP_LABELS = [
86
+ [/^next$|^react$/, "Next.js/React"], [/^typescript$/, "TypeScript"], [/^vite$/, "Vite"],
87
+ [/supabase/, "Supabase"], [/^pg$|^postgres/, "Postgres"], [/^firebase/, "Firebase/Firestore"],
88
+ [/inngest/, "Inngest (event-driven jobs)"], [/strapi/, "Strapi (headless CMS)"], [/cloudinary/, "Cloudinary"],
89
+ [/^stripe$/, "Stripe"], [/next-auth/, "NextAuth"], [/resend/, "Resend (email)"],
90
+ [/posthog/, "PostHog (analytics)"], [/anthropic/, "Anthropic SDK"], [/^openai$/, "OpenAI"],
91
+ [/google\/gen|generative-ai/, "Google Gemini"], [/elevenlabs/, "ElevenLabs"], [/vercel/, "Vercel"],
92
+ [/tailwind/, "Tailwind"], [/shadcn/, "shadcn/ui"], [/radix/, "Radix UI"],
93
+ [/framer-motion/, "Framer Motion"], [/recharts/, "Recharts"], [/tiptap/, "TipTap (rich text)"],
94
+ [/react-pdf|jspdf/, "React-PDF"], [/puppeteer|chromium/, "Puppeteer (PDF)"], [/^docx$|mammoth/, "docx/mammoth"],
95
+ [/mdx/, "MDX"], [/react-hook-form/, "React Hook Form"], [/^zod$/, "Zod"],
96
+ [/vitest/, "Vitest"], [/playwright/, "Playwright (E2E)"], [/^turbo$|turborepo/, "Turborepo (monorepo)"],
97
+ [/^prisma$|@prisma/, "Prisma"], [/drizzle-orm/, "Drizzle"],
98
+ ];
99
+
100
+ const readJSON = (p) => { try { return JSON.parse(readFileSync(p, "utf8")); } catch { return null; } };
101
+
102
+ // Resolve a working dir to its repo root: the nearest ancestor holding a .git
103
+ // entry (the repo boundary). A session run in a subdir (e.g. apps/web) thus
104
+ // scans the whole repo, not just its corner. Falls back to the dir itself.
105
+ function findRepoRoot(cwd) {
106
+ let dir = cwd;
107
+ for (let i = 0; i < 64 && dir; i++) {
108
+ if (existsSync(join(dir, ".git"))) return dir;
109
+ const parent = dir.slice(0, dir.lastIndexOf("/"));
110
+ if (!parent || parent === dir) break;
111
+ dir = parent;
112
+ }
113
+ return cwd;
114
+ }
115
+
116
+ function listDirs(parent) {
117
+ if (!existsSync(parent)) return [];
118
+ try { return readdirSync(parent, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => join(parent, e.name)); }
119
+ catch { return []; }
120
+ }
121
+
122
+ // Workspace package dirs: honor the root package.json "workspaces" globs when
123
+ // present (npm/yarn array, or { packages: [...] }); fall back to the common
124
+ // apps/* + packages/* layout otherwise.
125
+ function workspaceDirs(root, rootPkg) {
126
+ const globs = Array.isArray(rootPkg?.workspaces) ? rootPkg.workspaces
127
+ : Array.isArray(rootPkg?.workspaces?.packages) ? rootPkg.workspaces.packages : null;
128
+ if (!globs) return [...listDirs(join(root, "apps")), ...listDirs(join(root, "packages"))];
129
+ const dirs = [];
130
+ for (const g of globs) {
131
+ if (g.endsWith("/*")) dirs.push(...listDirs(join(root, g.slice(0, -2))));
132
+ else dirs.push(join(root, g));
133
+ }
134
+ return dirs;
135
+ }
136
+
137
+ // Dependency names across the repo root and its workspaces. npm manifests only.
138
+ function workspaceDepNames(root) {
139
+ const names = new Set();
140
+ const rootPkgPath = join(root, "package.json");
141
+ const rootPkg = readJSON(rootPkgPath);
142
+ const pkgPaths = rootPkg ? [rootPkgPath] : [];
143
+ for (const d of workspaceDirs(root, rootPkg)) {
144
+ const pj = join(d, "package.json");
145
+ if (existsSync(pj)) pkgPaths.push(pj);
146
+ }
147
+ for (const pj of pkgPaths) {
148
+ const j = readJSON(pj);
149
+ if (j) for (const k of Object.keys({ ...(j.dependencies || {}), ...(j.devDependencies || {}) })) names.add(k.toLowerCase());
150
+ }
151
+ return names;
152
+ }
153
+
154
+ // Merge the two evidence streams into one deduped stack list. Exported so it can
155
+ // be unit-tested against an on-disk fixture directly (buildDigest applies the
156
+ // ephemeral-path filter, which would drop a fixture created under /tmp).
157
+ export function detectStack({ cwdRaw, exts, cmdsText }) {
158
+ const labels = new Set();
159
+ if (cwdRaw && existsSync(cwdRaw)) {
160
+ for (const name of workspaceDepNames(findRepoRoot(cwdRaw))) {
161
+ for (const [re, l] of DEP_LABELS) if (re.test(name)) labels.add(l);
162
+ }
163
+ }
164
+ for (const ext of Object.keys(exts || {})) if (EXT_LABELS[ext]) labels.add(EXT_LABELS[ext]);
165
+ for (const [re, l] of CMD_LABELS) if (re.test(cmdsText || "")) labels.add(l);
166
+ return [...labels];
167
+ }
168
+
169
+ // Every label the detector can emit. Exported so the groundedness verifier
170
+ // derives its tech lexicon from the SAME source as detection (tokenising these
171
+ // the same way it tokenises the stack), instead of a separate hardcoded list
172
+ // that silently drifts as the maps grow.
173
+ export function labelVocabulary() {
174
+ return [...new Set([...Object.values(EXT_LABELS), ...CMD_LABELS.map(([, l]) => l), ...DEP_LABELS.map(([, l]) => l)])];
175
+ }
176
+
177
+ // First cwd in a cluster that still exists on disk (else the first seen).
178
+ function resolveCwd(cwds, fallback) {
179
+ for (const c of cwds) if (c && existsSync(c)) return c;
180
+ return cwds[0] || fallback || "";
181
+ }
182
+
183
+ // Extension of a (POSIX-normalised) file path, lowercased; null when none.
184
+ function fileExt(path) {
185
+ const base = path.slice(path.lastIndexOf("/") + 1);
186
+ const dot = base.lastIndexOf(".");
187
+ if (dot <= 0) return null;
188
+ const ext = base.slice(dot + 1).toLowerCase();
189
+ return /^[a-z0-9]{1,5}$/.test(ext) ? ext : null;
190
+ }
191
+
192
+ function classify(p) {
193
+ const tags = [];
194
+ const days = p.firstTs && p.lastTs ? (p.lastTs - p.firstTs) / 86400000 : 0;
195
+ const areas = p.areasText;
196
+ const htmlHeavy = (areas.match(/\.html/g) || []).length >= 3;
197
+
198
+ if (htmlHeavy && p.mutations > 20) tags.push("static-site");
199
+ if (/api\/agent|api\/chat|api\/connectors|\/agents?\//i.test(areas)) tags.push("ai-platform");
200
+ if (/skills?\/[\w.-]+\/SKILL|\/SKILL\.md|commands?\/[\w.-]+\.md/i.test(areas)) tags.push("agent-tooling");
201
+ if (p.researchToMutation != null && p.researchToMutation > 10) tags.push("audit-research");
202
+ if (!tags.includes("static-site")) {
203
+ if (p.mutations > 200 && days > 14) tags.push("product-build");
204
+ else if (p.mutations > 30) tags.push("feature-work");
205
+ }
206
+ if (/migration|schema|\.sql/i.test(areas)) tags.push("data-migration");
207
+ if (/e2e|playwright|\.test\.|\.spec\./i.test(areas)) tags.push("testing");
208
+ if (p.delegation >= 8) tags.push("orchestrated");
209
+ if (p.designQueries >= 5) tags.push("design-research");
210
+ return tags.length ? [...new Set(tags)] : ["exploration"];
211
+ }
212
+
213
+ const DESIGN_RE = /design|ui\b|typograph|layout|figma|css|color|grid|font|spacing|aesthet/i;
214
+
215
+ // Generic agent-launcher commands: a session that runs one of these dispatched
216
+ // work to another agent CLI — evidence of orchestration, independent of any one
217
+ // framework. Extend the list as new agent CLIs appear.
218
+ //
219
+ // A launcher only counts as a dispatch when it is the EXECUTABLE of a
220
+ // (sub)command, not a substring of an argument or path: anchored at `^` with a
221
+ // trailing `(?=\s|$)`, so `cd my-codex-tests` (codex inside a path) does not
222
+ // count while `cd x && opencode run ...` does. `\b` was wrong here precisely
223
+ // because `-` is a word boundary, so the old pattern fired inside hyphenated
224
+ // tokens. No /i flag: executables are case-sensitive, and case-insensitive
225
+ // matching re-admits sentence-initial prose ("Aider is my favorite tool") at
226
+ // a fragment start as a phantom dispatch.
227
+ //
228
+ // Interactive / housekeeping invocations are NOT dispatches — only the
229
+ // HEADLESS mode of each launcher is, uniformly: `claude -p`/`--print` (not
230
+ // bare `claude`, the REPL), `codex exec` (not `codex login`/`mcp`/`resume`),
231
+ // `aider -m`/`--msg`/`--message[-file]` (not bare `aider` or `aider --yes`),
232
+ // `cursor-agent -p`/`--print` (not `cursor-agent login`), `pi -p`/`--print`
233
+ // (not bare `pi`, the REPL), `omp -p`/`--print` (same), `kimi -p`/`--prompt` (not bare `kimi`, its own
234
+ // REPL), and `opencode|crush|goose run`. LAUNCHER_FLAGS
235
+ // lets ordinary flags (with optional values, quoted or bare) sit between the
236
+ // executable and the headless marker, so `claude --model opus -p "x"` still
237
+ // counts. aider alone also skips POSITIONAL tokens (`aider app.py -m "fix"`
238
+ // is its canonical form, and aider has no subcommands to misread); the
239
+ // others stay flags-only so a subcommand's flag never reads as the top-level
240
+ // headless marker (`claude mcp add -p x` is not a dispatch).
241
+ //
242
+ // Every alternative in these fragments is first-char-disjoint on purpose:
243
+ // `--?\w` (not `--?[\w-]+`, which parses `--flag` two ways) and a bare value
244
+ // that cannot start a quote. Same-span ambiguity under the outer `*` is
245
+ // exponential backtracking, and one flag-heavy non-matching command in the
246
+ // logs would hang the whole digest.
247
+ const LAUNCHER_FLAGS = `(?:--?\\w[\\w-]*(?:=\\S*)?(?:\\s+(?:"[^"]*"|'[^']*'|[^-\\s"']\\S*))?\\s+)*`;
248
+ const LAUNCHER_TOKENS = `(?:(?:"[^"]*"|'[^']*'|[^\\s"'])+\\s+)*?`;
249
+ const AGENT_LAUNCHER_RE = new RegExp(
250
+ "^(?:" +
251
+ [
252
+ `claude\\s+${LAUNCHER_FLAGS}(?:-p|--print)`,
253
+ `(?:opencode|crush|goose)\\s+${LAUNCHER_FLAGS}run`,
254
+ `codex\\s+${LAUNCHER_FLAGS}exec`,
255
+ `aider\\s+${LAUNCHER_TOKENS}(?:-m|--msg|--message(?:-file)?)`,
256
+ `cursor-agent\\s+${LAUNCHER_FLAGS}(?:-p|--print)`,
257
+ `pi\\s+${LAUNCHER_FLAGS}(?:-p|--print)`,
258
+ `omp\\s+${LAUNCHER_FLAGS}(?:-p|--print)`,
259
+ `kimi\\s+${LAUNCHER_FLAGS}(?:-p|--prompt)`,
260
+ ].join("|") +
261
+ ")(?=\\s|$)",
262
+ );
263
+
264
+ // Leading env assignments (`FOO=bar`, `FOO="two words"`, `FOO=a\ b`) before
265
+ // the executable. Value atoms are first-char-disjoint (quote, backslash,
266
+ // plain) — linear matching, and an escaped space stays part of the value so
267
+ // `FOO=a\ claude -p x` correctly leaves `-p` as the executable.
268
+ const ENV_ASSIGN_RE = /^(?:[A-Za-z_][A-Za-z0-9_]*=(?:"(?:[^"\\]|\\.)*"|'[^']*'|\\.|[^\s"'\\])*\s+)+/;
269
+
270
+ // Drop heredoc bodies before splitting: `cat > run.sh <<'EOF' … EOF` carries
271
+ // arbitrary text (often agent-written scripts that themselves mention
272
+ // launchers) that never executes in this command. `<<<` here-strings are not
273
+ // heredocs; plain `<<` closes only at an unindented delimiter line, `<<-` also
274
+ // at a tab-indented one (shell semantics — an indented "EOF" inside a plain
275
+ // heredoc is still body, and counting its text would break the lower bound).
276
+ // A `<<` inside quoted or commented prose can over-strip the following lines —
277
+ // that errs toward undercount, which the lower-bound contract absorbs.
278
+ export function stripHeredocs(text) {
279
+ if (!text.includes("<<")) return text;
280
+ const out = [];
281
+ let term = null;
282
+ let dashed = false;
283
+ for (const line of text.split("\n")) {
284
+ if (term) {
285
+ if ((dashed ? line.replace(/^\t+/, "") : line) === term) term = null;
286
+ continue;
287
+ }
288
+ out.push(line);
289
+ const m = line.match(/(?<!<)<<(?!<)(-?)\s*(["']?)([A-Za-z_][\w.-]*)\2/);
290
+ if (m) { term = m[3]; dashed = m[1] === "-"; }
291
+ }
292
+ return out.join("\n");
293
+ }
294
+
295
+ // Split a command at top-level shell separators (&&, ||, ;, |, single & and
296
+ // newline) with quote awareness: a separator inside '…' or "…" (or escaped)
297
+ // is argument text, not a boundary — `git commit -m "a; claude -p b"` is one
298
+ // sub-command whose executable is git. A `#` at word start opens a comment
299
+ // (skipped to end of line), so an apostrophe in `# can't wait` never opens a
300
+ // phantom quote that would swallow the next line's dispatch.
301
+ export function splitTopLevel(text) {
302
+ const parts = [];
303
+ let cur = "";
304
+ let quote = null;
305
+ for (let i = 0; i < text.length; i++) {
306
+ const c = text[i];
307
+ if (quote) {
308
+ cur += c;
309
+ if (c === "\\" && quote === '"' && i + 1 < text.length) cur += text[++i];
310
+ else if (c === quote) quote = null;
311
+ continue;
312
+ }
313
+ if (c === "'" || c === '"') { quote = c; cur += c; continue; }
314
+ if (c === "\\") { cur += c; if (i + 1 < text.length) cur += text[++i]; continue; }
315
+ if (c === "#" && (cur === "" || /\s$/.test(cur))) {
316
+ while (i + 1 < text.length && text[i + 1] !== "\n") i++;
317
+ continue;
318
+ }
319
+ if (c === "&" || c === "|" || c === ";" || c === "\n") {
320
+ parts.push(cur);
321
+ cur = "";
322
+ if ((c === "&" || c === "|") && text[i + 1] === c) i++;
323
+ continue;
324
+ }
325
+ cur += c;
326
+ }
327
+ parts.push(cur);
328
+ return parts;
329
+ }
330
+
331
+ // Count agent-launcher invocations in a product's shell history. Heredoc
332
+ // bodies are dropped, then each command splits at top-level separators
333
+ // (quote-aware) and the matcher sees the executable position of each
334
+ // sub-command: leading subshell/brace openers and control-flow keywords
335
+ // (`(cd x && claude -p y)`, `do claude -p "$f"`) are transparent, as are env
336
+ // assignments. Launchers behind a wrapper (npx/sudo/time) or inside $()
337
+ // substitutions are still NOT counted — dispatchCommands is a lower bound,
338
+ // consistent with the toolCount note below.
339
+ function countDispatch(cmds) {
340
+ let n = 0;
341
+ for (const cmd of cmds) {
342
+ for (const raw of splitTopLevel(stripHeredocs(String(cmd)))) {
343
+ const part = raw
344
+ .trim()
345
+ .replace(/^[({\s]+/, "")
346
+ .replace(/^(?:do|then|else)\s+/, "")
347
+ .replace(ENV_ASSIGN_RE, "");
348
+ if (AGENT_LAUNCHER_RE.test(part)) n++;
349
+ }
350
+ }
351
+ return n;
352
+ }
353
+
354
+ // `tz` buckets the per-product calendar months (`months`) the same way days are
355
+ // bucketed elsewhere (--tz); the older `from`/`to` stay UTC for compatibility.
356
+ export function buildDigest(parsed, { tz = DEFAULT_TZ } = {}) {
357
+ const byRepo = new Map();
358
+ const monthKey = monthKeyFor(tz);
359
+
360
+ for (const s of parsed.sessions) {
361
+ const cwd = s.cwdRaw || s.cwdRedacted || "";
362
+ if (isEphemeral(cwd)) continue;
363
+ const key = repoKey(s.cwdRedacted || cwd);
364
+ if (!byRepo.has(key)) {
365
+ byRepo.set(key, {
366
+ repo: key, cwdRaw: s.cwdRaw || "", cwds: [], sessions: 0, userMessages: 0, prompts: [],
367
+ toolHist: {}, areas: {}, exts: {}, cmds: [], webQueries: [], sources: {}, sourceSpans: {},
368
+ delegation: 0, planning: 0, firstTs: null, lastTs: null, months: new Set(),
369
+ });
370
+ }
371
+ const p = byRepo.get(key);
372
+ if (s.cwdRaw && !p.cwds.includes(s.cwdRaw)) p.cwds.push(s.cwdRaw);
373
+ p.sessions++;
374
+ // Which tool produced this session. mergeSources guarantees the tag for
375
+ // everything the shipped adapters emit; "unknown" is the honest bucket for
376
+ // hand-built bundles and never counts as a distinct CLI (see toolCount).
377
+ const src = s.source || "unknown";
378
+ p.sources[src] = (p.sources[src] || 0) + 1;
379
+ for (const m of s.messages) {
380
+ const t = ms(m.ts);
381
+ if (Number.isFinite(t)) {
382
+ p.months.add(monthKey(t));
383
+ if (!p.firstTs || t < p.firstTs) p.firstTs = t;
384
+ if (!p.lastTs || t > p.lastTs) p.lastTs = t;
385
+ // Per-source activity span, to tell concurrent fan-out apart from a
386
+ // sequential migration between tools (see toolOverlap below).
387
+ const span = p.sourceSpans[src] || (p.sourceSpans[src] = { first: t, last: t });
388
+ if (t < span.first) span.first = t;
389
+ if (t > span.last) span.last = t;
390
+ }
391
+ if (m.role === "user" && m.textRedacted.trim()) {
392
+ p.userMessages++;
393
+ p.prompts.push(m.textRedacted.trim().replace(/\s+/g, " "));
394
+ }
395
+ for (const u of m.toolUses) {
396
+ p.toolHist[u.name] = (p.toolHist[u.name] || 0) + 1;
397
+ if (DELEGATION.has(u.name)) p.delegation++;
398
+ if (PLANNING.has(u.name)) p.planning++;
399
+ const area = u.path ? toArea(u.path, key) : null;
400
+ if (area) p.areas[area] = (p.areas[area] || 0) + 1;
401
+ if (u.path) { const e = fileExt(u.path); if (e) p.exts[e] = (p.exts[e] || 0) + 1; }
402
+ if (u.cmd) p.cmds.push(u.cmd);
403
+ if (u.q) p.webQueries.push(u.q);
404
+ }
405
+ }
406
+ }
407
+
408
+ const projects = [...byRepo.values()]
409
+ .sort((a, b) => b.sessions - a.sessions)
410
+ .map((p) => {
411
+ const mutations = Object.entries(p.toolHist).filter(([k]) => MUTATION.has(k)).reduce((n, [, v]) => n + v, 0);
412
+ const research = Object.entries(p.toolHist).filter(([k]) => RESEARCH.has(k)).reduce((n, [, v]) => n + v, 0);
413
+ const topAreas = Object.entries(p.areas).sort((a, b) => b[1] - a[1]).slice(0, 12);
414
+ const cmdsText = p.cmds.join(" \n ");
415
+ const commits = (cmdsText.match(/git commit/g) || []).length;
416
+ const reverts = (cmdsText.match(/git revert|git reset --hard|git checkout -- /g) || []).length;
417
+ const designQueries = p.webQueries.filter((q) => DESIGN_RE.test(q)).length;
418
+ // First cluster cwd that still exists — a deleted first worktree must not
419
+ // disable dependency detection for the whole cluster.
420
+ const cwdRaw = resolveCwd(p.cwds, p.cwdRaw);
421
+ const dispatchCommands = countDispatch(p.cmds);
422
+ const knownTools = Object.keys(p.sources).filter((k) => k !== "unknown");
423
+ const knownSpans = Object.entries(p.sourceSpans)
424
+ .filter(([k]) => k !== "unknown")
425
+ .map(([, v]) => v);
426
+ let toolOverlap = null;
427
+ if (knownTools.length >= 2 && knownSpans.length >= 2) {
428
+ toolOverlap = knownSpans.some((a, i) =>
429
+ knownSpans.slice(i + 1).some((b) => a.first <= b.last && b.first <= a.last));
430
+ }
431
+ const ctx = {
432
+ mutations, designQueries,
433
+ researchToMutation: mutations ? +(research / mutations).toFixed(2) : null,
434
+ firstTs: p.firstTs, lastTs: p.lastTs,
435
+ areasText: topAreas.map(([a]) => a).join(" "),
436
+ delegation: p.delegation,
437
+ };
438
+ return {
439
+ repo: p.repo,
440
+ cwdRaw, // local-only; first existing cwd in the cluster
441
+ type: classify(ctx),
442
+ // Null when no message carried a timestamp — never the epoch. A
443
+ // fabricated "1970-01" is a claimed date the logs can't back.
444
+ from: p.firstTs ? month(new Date(p.firstTs).toISOString()) : null,
445
+ to: p.lastTs ? month(new Date(p.lastTs).toISOString()) : null,
446
+ // Calendar months (in `tz`) with real message activity, for tech usage.
447
+ months: [...p.months].sort(),
448
+ sessions: p.sessions,
449
+ userMessages: p.userMessages,
450
+ // Code-volume signal for representative selection (edits/writes landed).
451
+ mutations,
452
+ topAreas: Object.fromEntries(topAreas),
453
+ tech: detectStack({ cwdRaw, exts: p.exts, cmdsText }),
454
+ landing: {
455
+ checksRun: /eslint|tsc|typecheck|playwright|npm (run )?build|pnpm build|npm test|pnpm test/i.test(cmdsText),
456
+ commits, reverts,
457
+ revertChurn: commits ? (reverts / Math.max(commits, 1) > 0.3 ? "high" : reverts > 0 ? "med" : "low") : "n/d",
458
+ },
459
+ delegation: p.delegation,
460
+ // Orchestration, three components together: delegating WITHIN a session
461
+ // (sub-agent Task calls), fanning out ACROSS CLIs (distinct tools in one
462
+ // product), and dispatching agent processes (launcher commands). Carried
463
+ // as one object so the narrative input sees all three, not just fan-out.
464
+ // Framework-agnostic. The counts DESCRIBE; nothing ranks (ADR-001).
465
+ //
466
+ // toolCount counts distinct KNOWN tools ("unknown" is honest bucketing
467
+ // for an untagged session, not a distinct CLI — the rest of the
468
+ // pipeline would call the same session claude-code, and a tag can't
469
+ // manufacture fan-out). toolOverlap tells concurrent fan-out apart
470
+ // from sequential migration: true when at least two known tools'
471
+ // activity spans intersect, false when their eras are disjoint (the
472
+ // candidate switched tools, nothing orchestrated anything), null when
473
+ // fewer than two spans exist to compare.
474
+ //
475
+ // NOTE: every count is a LOWER BOUND. Under single-source capture
476
+ // every session is tagged with the one tool that was ingested, so
477
+ // toolCount is pinned at 1 until a second source lands — absence of
478
+ // fan-out here is never evidence that no fan-out happened, only that
479
+ // one tool was read.
480
+ orchestration: {
481
+ delegation: p.delegation,
482
+ tools: p.sources,
483
+ toolCount: Math.max(knownTools.length, 1),
484
+ toolOverlap,
485
+ dispatchCommands,
486
+ },
487
+ researchToMutation: ctx.researchToMutation,
488
+ learningTopics: [...new Set(p.webQueries)].slice(0, 12),
489
+ promptSamples: samplePrompts(p.prompts),
490
+ };
491
+ });
492
+
493
+ return { source: parsed.source, projectCount: projects.length, projects };
494
+ }
495
+
496
+ function samplePrompts(prompts, max = 8, cap = 300) {
497
+ const sub = prompts.filter((p) => p.split(/\s+/).length >= 3 && !p.startsWith("<task-notification>") && !p.startsWith("Your task is to create a detailed summary"));
498
+ if (sub.length <= max) return sub.map((p) => p.slice(0, cap));
499
+ const step = sub.length / max;
500
+ return Array.from({ length: max }, (_, i) => sub[Math.floor(i * step)].slice(0, cap));
501
+ }
@@ -0,0 +1,54 @@
1
+ // Work distribution: breadth vs depth across products. Pure counts from the
2
+ // per-repo clusters — no PII.
3
+ //
4
+ // The discriminant a reader would otherwise have to derive by hand: the same
5
+ // session volume means opposite things at 2 sessions/product (portfolio
6
+ // steering: many products, touched and directed) and at 9 sessions/product
7
+ // (sustained building: few products, returned to repeatedly). Neither pole is
8
+ // better — but for matching it is one of the most telling signals.
9
+ //
10
+ // Four signals, all deterministic:
11
+ // - meanSessionsPerProduct / medianSessionsPerProduct
12
+ // - top3Share (share of all sessions spent in the 3 most-worked products)
13
+ // - multiMonthShare (products whose span covers more than one month)
14
+ // - shape band: portfolio / balanced / deep focus
15
+
16
+ const median = (arr) => {
17
+ if (!arr.length) return 0;
18
+ const s = [...arr].sort((a, b) => a - b);
19
+ return s[Math.floor(s.length / 2)];
20
+ };
21
+
22
+ export function computeDistribution(projects) {
23
+ if (!projects?.length) return null;
24
+ const counts = projects.map((p) => p.sessions ?? 0).sort((a, b) => b - a);
25
+ const products = counts.length;
26
+ const sessions = counts.reduce((a, b) => a + b, 0);
27
+ if (!sessions) return null;
28
+
29
+ const meanSessionsPerProduct = +(sessions / products).toFixed(1);
30
+ const medianSessionsPerProduct = median(counts);
31
+ const top3Share = +(counts.slice(0, 3).reduce((a, b) => a + b, 0) / sessions).toFixed(2);
32
+
33
+ // Continuity: products worked across more than one calendar month.
34
+ const multiMonthProducts = projects.filter((p) => p.from && p.to && p.from !== p.to).length;
35
+ const multiMonthShare = +(multiMonthProducts / products).toFixed(2);
36
+
37
+ // Shape band — purely for the LLM narrative, not a grade. The portfolio
38
+ // band requires real breadth (≥8 products): 3 products touched twice each
39
+ // is occasional use, not portfolio steering.
40
+ let shape = "balanced";
41
+ if (meanSessionsPerProduct >= 6) shape = "deep focus";
42
+ else if (meanSessionsPerProduct <= 2.5 && products >= 8) shape = "portfolio";
43
+
44
+ return {
45
+ products,
46
+ sessions,
47
+ meanSessionsPerProduct,
48
+ medianSessionsPerProduct,
49
+ top3Share,
50
+ multiMonthProducts,
51
+ multiMonthShare,
52
+ shape,
53
+ };
54
+ }
package/src/enrich.mjs ADDED
@@ -0,0 +1,118 @@
1
+ // Local repo enrichment: the highest-signal context per token, read straight
2
+ // from the candidate's machine. package.json gives the exact stack; CLAUDE.md /
3
+ // README describe the project in words; git log says what actually shipped.
4
+ //
5
+ // This is LOCAL CONTEXT for the narrative step only. It contains real names and
6
+ // MUST NOT be copied into the sent bundle — the LLM consumes it and emits an
7
+ // anonymized, context-only description.
8
+
9
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
10
+ import { join } from "node:path";
11
+ import { execSync } from "node:child_process";
12
+
13
+ function repoRoot(cwd) {
14
+ const m = cwd.match(/^(.*\/(?:Github|github|repos?|Projects|src|code|dev|work)\/[^/]+)/);
15
+ return m ? m[1] : cwd;
16
+ }
17
+
18
+ // Find the dir that actually holds package.json (root, or a common monorepo app dir).
19
+ function pkgDir(root) {
20
+ if (existsSync(join(root, "package.json"))) return root;
21
+ let subs = [];
22
+ try {
23
+ subs = readdirSync(root, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name);
24
+ } catch {
25
+ return root;
26
+ }
27
+ const prefer = subs.filter((s) => /-(app|web)$|^(app|web|apps|packages|src|client|frontend)$/.test(s));
28
+ for (const s of [...prefer, ...subs]) if (existsSync(join(root, s, "package.json"))) return join(root, s);
29
+ return root;
30
+ }
31
+
32
+ const readMaybe = (p, cap = 1800) => {
33
+ try {
34
+ return existsSync(p) ? readFileSync(p, "utf8").slice(0, cap) : null;
35
+ } catch {
36
+ return null;
37
+ }
38
+ };
39
+
40
+ export function enrichRepo(cwdRaw) {
41
+ const out = { found: false };
42
+ if (!cwdRaw) return out;
43
+ const root = repoRoot(cwdRaw);
44
+ if (!existsSync(root)) return out;
45
+ out.found = true;
46
+ const dir = pkgDir(root);
47
+
48
+ // package.json: name, description, dependency names (the stack).
49
+ try {
50
+ const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
51
+ out.pkgName = pkg.name || null;
52
+ out.pkgDescription = pkg.description || null;
53
+ out.deps = Object.keys({ ...pkg.dependencies, ...pkg.devDependencies }).slice(0, 60);
54
+ } catch {}
55
+
56
+ // Project self-description.
57
+ out.doc =
58
+ readMaybe(join(dir, "CLAUDE.md")) ||
59
+ readMaybe(join(root, "CLAUDE.md")) ||
60
+ readMaybe(join(dir, "README.md")) ||
61
+ readMaybe(join(root, "README.md")) ||
62
+ null;
63
+
64
+ // What actually shipped (commit subjects), and recency.
65
+ try {
66
+ out.commits = execSync(`git -C "${root}" log --pretty=%s -n 20`, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] })
67
+ .split("\n").map((s) => s.trim()).filter(Boolean);
68
+ out.totalCommits = +execSync(`git -C "${root}" rev-list --count HEAD`, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim() || null;
69
+ } catch {}
70
+
71
+ // "Codified principles": lines ADDED over time to the project's doctrine
72
+ // files (CLAUDE.md, README.md). These are rules the candidate wrote for
73
+ // their future self and their agent — strategic, not technical.
74
+ out.principlesDiff = collectAddedDoctrineLines(root);
75
+
76
+ return out;
77
+ }
78
+
79
+ // One honest line about what the enrichment could NOT see. The empty catches
80
+ // above encode expected absence (a Python repo has no package.json, a non-git
81
+ // dir has no log), so this is computed from the OUTPUT shape instead: an entry
82
+ // that found a root but produced no stack, no doc, and no commits contributed
83
+ // nothing to the narrative. Local-only data — one aggregate note, no per-error
84
+ // noise.
85
+ export function describeContextGaps(enrichments) {
86
+ const list = enrichments ?? [];
87
+ const gaps = list.filter((e) => !e?.found || (!e.pkgName && !e.doc && !e.commits?.length)).length;
88
+ if (!gaps) return null;
89
+ return `repo context unavailable for ${gaps} of ${list.length} selected project${list.length === 1 ? "" : "s"} (the narrative leans on prompts and logs for those)`;
90
+ }
91
+
92
+ function collectAddedDoctrineLines(root) {
93
+ const candidates = [];
94
+ for (const file of ["CLAUDE.md", "README.md"]) {
95
+ try {
96
+ const patch = execSync(
97
+ `git -C "${root}" log --reverse --pretty=format:"||COMMIT %ad" --date=short -p -50 -- "${file}"`,
98
+ { encoding: "utf8", maxBuffer: 4 * 1024 * 1024, stdio: ["ignore", "pipe", "ignore"] },
99
+ );
100
+ if (!patch) continue;
101
+ let date = null;
102
+ for (const line of patch.split("\n")) {
103
+ if (line.startsWith("||COMMIT ")) { date = line.slice(9).trim(); continue; }
104
+ if (!date) continue;
105
+ if (!line.startsWith("+") || line.startsWith("+++")) continue;
106
+ const text = line.slice(1).trim();
107
+ if (text.length < 20 || text.length > 300) continue;
108
+ if (/^[#`*\-_=>\[\]<]/.test(text)) continue; // headings, code, lists, html
109
+ if (/^[A-Z][\w\s]*:$/.test(text)) continue; // "Section:" headers
110
+ candidates.push({ date, file, text });
111
+ }
112
+ } catch {}
113
+ }
114
+ // Dedupe by text, keep earliest date; sort ascending; cap.
115
+ const byText = new Map();
116
+ for (const c of candidates) if (!byText.has(c.text) || c.date < byText.get(c.text).date) byText.set(c.text, c);
117
+ return [...byText.values()].sort((a, b) => a.date.localeCompare(b.date)).slice(-30);
118
+ }