@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
@@ -0,0 +1,91 @@
1
+ // Source resolution: which log sources get read for a run, and where they
2
+ // come from. Shared by `rebase-verify generate` (the producer) and `rebase-verify
3
+ // submit` (which re-derives ground truth from the same logs).
4
+ //
5
+ // Sources can be combined:
6
+ // - claude-code: ~/.claude/projects, always read
7
+ // - opencode: ~/.local/share/opencode/{storage,opencode.db}, opt-out
8
+ // - codex: ~/.codex/sessions, opt-out
9
+ // - pi: ~/.pi/agent/sessions, opt-out
10
+ // - omp: ~/.omp/agent/sessions, opt-out (oh-my-pi, pi's format)
11
+ // - cursor: ~/.cursor/chats, opt-out (readCursor returns an EMPTY
12
+ // bundle with stats.backend: null on Node < 22.5 — no
13
+ // node:sqlite — so it just contributes zero sessions there)
14
+ // - kimi: ~/.kimi-code/sessions, opt-out
15
+ //
16
+ // Both opencode backends (sqlite and JSON) live in src/adapters/opencode.mjs;
17
+ // this file just decides *whether* to read each source at all and *which*
18
+ // backend, keyed by source name so future adapters slot in as another
19
+ // `sources.<name>` block below without touching the others.
20
+
21
+ import { readClaudeCode } from "./adapters/claude-code.mjs";
22
+ import { readOpencode, readOpencodeJson, defaultOpencodeRoot, mergeSources } from "./adapters/opencode.mjs";
23
+ import { readCodex, defaultCodexRoot } from "./adapters/codex.mjs";
24
+ import { readPi, defaultPiRoot } from "./adapters/pi.mjs";
25
+ import { readOmp, defaultOmpRoot } from "./adapters/omp.mjs";
26
+ import { isAgentRun } from "./agent-run.mjs";
27
+ import { readCursor, defaultCursorRoot } from "./adapters/cursor.mjs";
28
+ import { readKimi, defaultKimiRoot } from "./adapters/kimi.mjs";
29
+
30
+ // rebase-verify's own agent runs leave transcripts in the agents' session
31
+ // stores; they are dropped here, once, for every source.
32
+ function dropAgentRuns(b) {
33
+ // Files go too: they feed the provenance manifest and the malformed-line
34
+ // count, and a run killed mid-write leaves a truncated line. A file is an
35
+ // agent run's by its recorded cwd, or by its path (encoded cwd dirs).
36
+ const sessions = b.sessions.filter((s) => !isAgentRun(s.cwdRaw));
37
+ const files = b.files.filter((f) => !isAgentRun(f.cwdRaw) && !isAgentRun(f.relPath));
38
+ return { ...b, sessions, files };
39
+ }
40
+
41
+ // The sources in the order they are read and shown. `claude-code` is the base
42
+ // and is always read by readAllSources; the others are opt-out.
43
+ export const SOURCES = [
44
+ { id: "claude-code", label: "Claude Code" },
45
+ { id: "opencode", label: "opencode" },
46
+ { id: "codex", label: "Codex" },
47
+ { id: "pi", label: "pi" },
48
+ { id: "omp", label: "oh-my-pi" },
49
+ { id: "cursor", label: "Cursor" },
50
+ { id: "kimi", label: "Kimi" },
51
+ ];
52
+
53
+ /**
54
+ * Read one source by its id (see SOURCES) with agent-run transcripts dropped,
55
+ * or null when `sources.<id>.disabled`. Same roots and flags as readAllSources.
56
+ */
57
+ export function readSource(id, { claudeRoot, sources }) {
58
+ if (id === "claude-code") return dropAgentRuns(readClaudeCode(claudeRoot));
59
+ const o = sources?.[id] ?? {};
60
+ if (o.disabled) return null;
61
+ switch (id) {
62
+ case "opencode": {
63
+ // `flag("opencode-root")` returns null when the flag is absent, so we
64
+ // can't rely on a default parameter alone. Fall back to
65
+ // defaultOpencodeRoot() when o.root is null OR undefined.
66
+ const root = o.root ?? defaultOpencodeRoot();
67
+ return dropAgentRuns(o.json ? readOpencodeJson(root) : readOpencode(root));
68
+ }
69
+ case "codex": return dropAgentRuns(readCodex(o.root ?? defaultCodexRoot()));
70
+ case "pi": return dropAgentRuns(readPi(o.root ?? defaultPiRoot()));
71
+ case "omp": return dropAgentRuns(readOmp(o.root ?? defaultOmpRoot()));
72
+ case "cursor": return dropAgentRuns(readCursor(o.root ?? defaultCursorRoot()));
73
+ case "kimi": return dropAgentRuns(readKimi(o.root ?? defaultKimiRoot()));
74
+ default: throw new Error(`unknown source: ${id}`);
75
+ }
76
+ }
77
+
78
+ /** One parsed set from the bundles read (a single bundle is returned as it is). */
79
+ export function combineSources(bundles) {
80
+ return bundles.length > 1 ? mergeSources(...bundles) : bundles[0];
81
+ }
82
+
83
+ export function readAllSources({ claudeRoot, sources }) {
84
+ const bundles = [];
85
+ for (const { id } of SOURCES) {
86
+ const b = readSource(id, { claudeRoot, sources });
87
+ // claude-code is always part of the result; the others only when they have sessions.
88
+ if (b && (id === "claude-code" || b.sessions.length)) bundles.push(b);
89
+ }
90
+ return combineSources(bundles);
91
+ }
package/src/submit.mjs ADDED
@@ -0,0 +1,65 @@
1
+ // Sending the profile to the rebase hub.
2
+ //
3
+ // The candidate generates the profile FIRST (saved locally), then submits as a
4
+ // second, explicit step: sign in in the browser (src/hub.mjs), then POST
5
+ // candidate.json as the single multipart part `profile`. The hub knows who
6
+ // sent it from the token, so `contact` never leaves the machine, and it takes
7
+ // no attachments, so a project artifact must be a link.
8
+
9
+ import { readFileSync, existsSync } from "node:fs";
10
+ import { resolveHub, signIn, USER_AGENT } from "./hub.mjs";
11
+
12
+ // The exact JSON that leaves the machine, as one pure step, shared by the
13
+ // real POST and `submit --dry-run`, so what the candidate inspects IS what is
14
+ // sent. Does not mutate its input.
15
+ export function buildPayload(profile) {
16
+ if (profile.schema !== "playnew-profile/v1") throw new Error(`expected schema playnew-profile/v1, got ${profile.schema}`);
17
+ const file = (profile.projects ?? []).find((p) => p.artifact?.type === "file");
18
+ if (file) {
19
+ throw new Error(`project ${file.id} attaches a file; the hub takes links only. Replace it with a link (a deploy URL, a repo, a PR) or remove the artifact in out/candidate.json.`);
20
+ }
21
+ const payload = structuredClone(profile);
22
+ // Strip repoLabel from every project before sending. The label is the
23
+ // candidate's own directory name and is meant ONLY to help them recognise
24
+ // their projects locally during curation, it must not reach rebase.
25
+ stripRepoLabels(payload);
26
+ // The sign-in identifies the person; nothing typed about them is sent.
27
+ delete payload.contact;
28
+ return payload;
29
+ }
30
+
31
+ // Signs in, then posts. `fetchFn`, `open`, `sleep` and `log` are injectable.
32
+ export async function submitProfile(profilePath, { hub, fetchFn = fetch, ...flow } = {}) {
33
+ if (!existsSync(profilePath)) throw new Error(`profile not found: ${profilePath}`);
34
+ // Refuse before signing in: no point asking for a browser round trip for a payload the hub would reject.
35
+ const payload = buildPayload(JSON.parse(readFileSync(profilePath, "utf8")));
36
+
37
+ const base = resolveHub(hub);
38
+ const token = await signIn(base, { fetchFn, ...flow });
39
+
40
+ const form = new FormData();
41
+ form.append("profile", new Blob([JSON.stringify(payload)], { type: "application/json" }), "candidate.json");
42
+ let res;
43
+ try {
44
+ res = await fetchFn(`${base}/api/hub/work-profiles`, {
45
+ method: "POST",
46
+ headers: { authorization: `Bearer ${token}`, "user-agent": USER_AGENT },
47
+ body: form,
48
+ });
49
+ } catch (e) {
50
+ throw new Error(`could not reach the hub to send the profile (${e.message}). The sign-in is spent by the first attempt, so run submit again and sign in anew.`);
51
+ }
52
+ if (res.status === 401) {
53
+ throw new Error("the hub did not accept the sign-in (it is valid for one profile only and 15 minutes). Run submit again to sign in anew.");
54
+ }
55
+ if (!res.ok) {
56
+ const text = await res.text().catch(() => "");
57
+ throw new Error(`submit failed ${res.status}: ${text}. If the profile was refused for its content, fix it and run submit again; a retry needs a new sign-in.`);
58
+ }
59
+ return await res.json().catch(() => ({}));
60
+ }
61
+
62
+ function stripRepoLabels(profile) {
63
+ for (const p of profile.projects ?? []) delete p.repoLabel;
64
+ for (const o of profile.otherProjects ?? []) delete o.repoLabel;
65
+ }
@@ -0,0 +1,3 @@
1
+ // User-role text the framework injects, not the person's own words: task
2
+ // notifications and the compaction request and continuation turns.
3
+ export const SYSTEM_PROMPT_RE = /^(<task-notification>|Your task is to create a detailed summary of the conversation|This session is being continued from a previous conversation)/i;
@@ -0,0 +1,88 @@
1
+ // Technology usage: for each technology the stack detection saw, how often it
2
+ // shows up across ALL products. Pure counts from the per-product clusters, no
3
+ // model, no PII, never a score (ADR-001): the band is a plain-language label
4
+ // for the counts printed next to it, nothing more.
5
+ //
6
+ // Source of the names: the very same `tech` arrays the projects carry, i.e.
7
+ // detectStack() in src/digest.mjs. That function can only emit labels from its
8
+ // fixed maps (labelVocabulary()), so a name here is always a public technology
9
+ // label, never a repo, client or private package name. A custom or private
10
+ // dependency matches no map entry and therefore never appears.
11
+ //
12
+ // Counts, per technology:
13
+ // - products: products whose detected stack includes it
14
+ // - sessions: sessions of those products. The stack is detected per product
15
+ // (dependency manifests, file extensions, shell commands), not per session,
16
+ // so this is "sessions in products where it was detected": an upper bound
17
+ // on sessions that touched it, stated as such in the docs.
18
+ // - months: distinct calendar months in which those products had real message
19
+ // activity, bucketed in the recorded timezone (same --tz as the day counts)
20
+ // - firstMonth / lastMonth: earliest and latest of those months
21
+ //
22
+ // Band, derived only from `months` and the span first..last (inclusive):
23
+ // continuous present in 6+ distinct months AND in at least 75% of the months
24
+ // between its first and last month
25
+ // recurring present in 3+ distinct months (not continuous)
26
+ // occasional present in 1-2 distinct months
27
+ // Like the cognitive-tag thresholds these are EMPIRICAL: chosen so that a
28
+ // stack used all year reads differently from one touched in a single sprint.
29
+ // They are not calibrated against outcomes and say nothing about skill.
30
+
31
+ import { DEFAULT_TZ, isValidTimezone } from "./days.mjs";
32
+
33
+ export const BAND_CONTINUOUS_MIN_MONTHS = 6;
34
+ export const BAND_CONTINUOUS_MIN_COVERAGE = 0.75;
35
+ export const BAND_RECURRING_MIN_MONTHS = 3;
36
+
37
+ // Inclusive number of calendar months from a to b ("YYYY-MM").
38
+ export function monthSpan(a, b) {
39
+ const [ya, ma] = a.split("-").map(Number);
40
+ const [yb, mb] = b.split("-").map(Number);
41
+ return (yb - ya) * 12 + (mb - ma) + 1;
42
+ }
43
+
44
+ // The band from the counts alone, so submit-time structure checks can verify a
45
+ // claimed band against the claimed counts without any logs.
46
+ export function bandFor({ months, firstMonth, lastMonth }) {
47
+ if (!(months >= 1) || !firstMonth || !lastMonth) return null;
48
+ const span = monthSpan(firstMonth, lastMonth);
49
+ if (months >= BAND_CONTINUOUS_MIN_MONTHS && months / span >= BAND_CONTINUOUS_MIN_COVERAGE) return "continuous";
50
+ if (months >= BAND_RECURRING_MIN_MONTHS) return "recurring";
51
+ return "occasional";
52
+ }
53
+
54
+ // `projects`: digest projects (all of them, not just the representatives).
55
+ export function computeTechUsage(projects, { tz = DEFAULT_TZ } = {}) {
56
+ const byTech = new Map();
57
+ for (const p of projects ?? []) {
58
+ for (const name of new Set(p.tech ?? [])) {
59
+ let t = byTech.get(name);
60
+ if (!t) byTech.set(name, (t = { name, sessions: 0, products: 0, monthSet: new Set() }));
61
+ t.products++;
62
+ t.sessions += p.sessions ?? 0;
63
+ for (const m of p.months ?? []) t.monthSet.add(m);
64
+ }
65
+ }
66
+ const technologies = [...byTech.values()]
67
+ .filter((t) => t.monthSet.size > 0)
68
+ .map((t) => {
69
+ const ms = [...t.monthSet].sort();
70
+ const row = { name: t.name, sessions: t.sessions, products: t.products, months: ms.length, firstMonth: ms[0], lastMonth: ms.at(-1) };
71
+ const out = { ...row, band: bandFor(row) };
72
+ // The sorted month list backs the submit-time window check. Non-enumerable
73
+ // so it never reaches candidate.json or the payload.
74
+ Object.defineProperty(out, "monthList", { value: ms, enumerable: false });
75
+ return out;
76
+ })
77
+ .sort((a, b) => b.sessions - a.sessions || b.months - a.months || a.name.localeCompare(b.name));
78
+ if (!technologies.length) return null;
79
+ return { timezone: tz, technologies };
80
+ }
81
+
82
+ // The zone the submit-time re-derivation must bucket months in: the one the
83
+ // profile recorded, never the machine's. An absent or invalid recorded zone
84
+ // falls back to UTC (an invalid one is reported separately by assessStructure).
85
+ export function recordedTechUsageTz(profile) {
86
+ const tz = profile?.techUsage?.timezone;
87
+ return isValidTimezone(tz) ? tz : DEFAULT_TZ;
88
+ }
@@ -0,0 +1,264 @@
1
+ // Trajectory: what changed in how this person works over the window.
2
+ //
3
+ // Three deterministic signals, each computed across ALL sessions (not per
4
+ // project), splitting the window in half by time:
5
+ //
6
+ // 1. Behavioral shifts — same metric measured early vs late.
7
+ // Median prompt length, delegation rate, research:mutation, verification
8
+ // frequency. Each gets a magnitude (number) and a direction tag.
9
+ //
10
+ // 2. Topic clusters — web queries grouped by theme, chronological. Tells
11
+ // the cultural reading list, not just "which framework".
12
+ //
13
+ // 3. New vocabulary — words that show up only in the late half AND recur
14
+ // across multiple distinct prompts (one-offs filtered out).
15
+ //
16
+ // Output goes into the digest, the candidate.json (under `trajectory`), and is
17
+ // rendered both in profile.md and on the dashboard detail page.
18
+
19
+ import { SYSTEM_PROMPT_RE } from "./system-text.mjs";
20
+
21
+ const ms = (iso) => (iso ? Date.parse(iso) : NaN);
22
+
23
+ const MUTATION = new Set(["Edit", "Write", "NotebookEdit", "MultiEdit"]);
24
+ const RESEARCH = new Set(["Read", "Grep", "Glob", "WebSearch", "WebFetch"]);
25
+ const DELEGATION = new Set(["Task", "Agent"]);
26
+ const CHECK_RE = /\b(eslint|tsc|typecheck|playwright|npm (run )?(build|test)|pnpm (build|test)|vitest|jest)\b/i;
27
+
28
+ // Theme clusters for web queries — broad on purpose. The point is to surface
29
+ // the cultural reading list, not to classify with precision.
30
+ const TOPIC_RULES = [
31
+ ["agent architecture", /agent|mcp\b|skill|claude code|subagent|orchestrat|sdk/i],
32
+ ["design & UI", /design|typograph|figma|swiss|grid|color|spacing|aesthet|ui\b|notebooklm|shadcn/i],
33
+ ["security & auth", /auth\b|oauth|jwt|rls|injection|security|csrf|cors|encryption/i],
34
+ ["dev tooling", /eslint|prettier|tsc|playwright|vitest|jest|next\.config|build|vercel|deploy/i],
35
+ ["data & schema", /supabase|postgres|sql|schema|migration|drizzle|prisma|index\b/i],
36
+ ["AI patterns", /prompt|caching|tool use|streaming|context window|anthropic|llm\b|reasoning/i],
37
+ ["business & domain", /booking\.com|hotel|venue|invoice|fic\b|crm|brand|creator|youtube|instagram|tiktok/i],
38
+ ];
39
+
40
+ // Stop words: common function words in EN and IT, plus high-frequency
41
+ // non-content words specific to coding chats. The signal we want is concepts
42
+ // adopted, not connective tissue.
43
+ const STOPWORDS = new Set([
44
+ // EN function words
45
+ "the","and","for","with","this","that","from","into","onto","when","then","else","over","than","more","less",
46
+ "have","has","had","what","which","there","here","just","also","like","want","need","make","made","does","done","very",
47
+ "these","those","some","other","such","each","both","most","many","much","only","even","still","they",
48
+ "their","them","your","yours","ours","mine","about","after","before","while","where","because","been",
49
+ "being","its","not","but","can","cannot","could","would","should","shall","will","please","using","use","used","one","two",
50
+ "let","yes","okay","fine","needs","got","get","see","look","files","file","line","code","thanks","really","truly",
51
+ "say","said","saying","tell","told","think","thought","know","knew","known","find","found","right","wrong",
52
+ "good","bad","new","old","next","previous","last","first","second","third","another","example","every","always","never",
53
+ "between","without","within","through","throughout","across","along","around","without","via","per","upon","unless","until",
54
+ "instead","whether","though","although","however","therefore","thus","hence","indeed","actually","essentially",
55
+ // IT function words and very common verbs
56
+ "puoi","sono","sei","della","dello","delle","degli","alla","allo","alle","agli","negli","nello","nelle",
57
+ "questo","questa","questi","queste","cosa","come","dove","quando","perche","perché","tutto","tutti","tutte",
58
+ "anche","molto","solo","ancora","gia","già","mai","sempre","ora","adesso","forse","tipo","fatto","fare","fai",
59
+ "ho","ha","hai","hanno","cui","gli","io","tu","lui","lei","loro","noi","voi","della","del","dell","nel",
60
+ "facciamo","faccio","facevo","fece","fatto","fatti","fatta","fatte","detto","detti","dico","dici","dice",
61
+ "vedere","vedo","vedi","vede","visto","vista","visti","viste","quello","quella","quelli","quelle","quale",
62
+ "ecco","poi","quindi","invece","mentre","sotto","sopra","sempre","ancora","subito","spesso","mai","ogni",
63
+ "altro","altra","altri","altre","stesso","stessa","stessi","stesse","prima","dopo","durante","oltre",
64
+ "perfetto","esempio","esempi","parte","parti","modo","modi","cose","cosa","caso","casi","punto","punti",
65
+ "magari","credo","penso","pensavo","sembra","sembrava","mostra","mostri","mostro","metti","metto","mette","messo",
66
+ "vorrei","volere","voglio","vogliamo","puoi","posso","possiamo","può","possono","provo","provare","prova",
67
+ "fammi","dimmi","sai","so","sappiamo","sapere","capito","capire","capisco","grazie","ciao","salve",
68
+ "che","chi","con","per","tra","fra","una","uno","una","alle","del","dal","dai","dagli","sulle","sui","sul",
69
+ "avere","aver","mettere","dentro","fuori","sopra","tutta","senso","giusto","nulla","niente","forse","probabilmente",
70
+ "molto","poco","spesso","mai","sempre","ovviamente","sicuramente","ovvio","semplice","facile","difficile","meglio","peggio",
71
+ // Italian function/common words that kept slipping through the >=4 char filter.
72
+ "allora","ormai","appena","presto","tardi","subito","raramente","tanto","tanti","tante","alcuni","alcune","ancora",
73
+ "domanda","domande","rispondi","risposta","risposte","risponde","chiede","chiedi","chiedo","chiesto","chiesti","chieste",
74
+ "dire","dico","dici","dice","detto","detti","detta","dette","dicono","dicendo","dicevo","disse","dissi","dissero",
75
+ "vero","veri","vera","vere","verita","verità","falso","falsi","falsa","false",
76
+ "essere","siamo","siete","era","eri","ero","erano","fosse","fossi","fui","fu","stato","stata","stati","state","stando",
77
+ "andare","andiamo","andate","vado","vada","venire","vengo","viene","vieni","veniamo","venite","venuto","venuti",
78
+ "primo","seconda","secondo","terzo","ultimo","ultima","ultimi","ultime","prossimo","prossima","prossimi","prossime",
79
+ "qui","qua","lì","là","quella","quello","queste","questi","quelli","quelle",
80
+ "bene","molto","poco","poca","pochi","tutto","tutta","tutti","tutte","stesso","stessa","stessi","stesse",
81
+ "okay","perfetto","ottimo","ottima","ottimi","ottime","brava","bravo","brave","bravi","grazie",
82
+ "sembra","sembrava","sembrano","pare","pareva","parre","credo","penso","pensavo","credevo",
83
+ "cosa","cose","cosi","così","punto","punti","parte","parti","modo","modi","tipo","tipi",
84
+ "quindi","quello","questa","questo","cose","cose","contro","tra","fra","oltre","durante","mentre",
85
+ ]);
86
+
87
+ function median(arr) {
88
+ if (!arr.length) return null;
89
+ const s = [...arr].sort((a, b) => a - b);
90
+ return s[Math.floor(s.length / 2)];
91
+ }
92
+
93
+ function direction(early, late, threshold = 0.15) {
94
+ if (early == null || late == null) return "n/a";
95
+ if (early === 0 && late === 0) return "stable";
96
+ const base = Math.max(Math.abs(early), 1e-9);
97
+ const delta = (late - early) / base;
98
+ if (Math.abs(delta) < threshold) return "stable";
99
+ return delta > 0 ? "up" : "down";
100
+ }
101
+
102
+ // Split sessions by their first timestamp at the midpoint of the global window.
103
+ function splitHalves(parsed) {
104
+ const sessTs = parsed.sessions
105
+ .map((s) => ({ s, t: Number.isFinite(ms(s.firstTs)) ? ms(s.firstTs) : null }))
106
+ .filter((x) => x.t != null)
107
+ .sort((a, b) => a.t - b.t);
108
+ if (sessTs.length < 4) return { early: [], late: [], midpoint: null };
109
+ const tMin = sessTs[0].t;
110
+ const tMax = sessTs.at(-1).t;
111
+ const mid = (tMin + tMax) / 2;
112
+ return {
113
+ early: sessTs.filter((x) => x.t < mid).map((x) => x.s),
114
+ late: sessTs.filter((x) => x.t >= mid).map((x) => x.s),
115
+ midpoint: new Date(mid).toISOString().slice(0, 7),
116
+ };
117
+ }
118
+
119
+ function metricsFor(sessions) {
120
+ let userMsgs = 0;
121
+ let delegations = 0;
122
+ let mutations = 0;
123
+ let research = 0;
124
+ const promptWords = [];
125
+ let sessWithChecks = 0;
126
+
127
+ for (const s of sessions) {
128
+ let hasCheck = false;
129
+ for (const m of s.messages) {
130
+ // Exclude system-injected user messages from the median: compaction summary
131
+ // requests are 1000+ words and dwarf the candidate's own input, and task
132
+ // notifications are XML noise.
133
+ if (m.role === "user" && m.textRedacted.trim() && !SYSTEM_PROMPT_RE.test(m.textRedacted.trim())) {
134
+ userMsgs++;
135
+ const w = m.textRedacted.trim().split(/\s+/).length;
136
+ if (w > 0) promptWords.push(w);
137
+ }
138
+ for (const u of m.toolUses) {
139
+ if (DELEGATION.has(u.name)) delegations++;
140
+ if (MUTATION.has(u.name)) mutations++;
141
+ if (RESEARCH.has(u.name)) research++;
142
+ if (u.cmd && CHECK_RE.test(u.cmd)) hasCheck = true;
143
+ }
144
+ }
145
+ if (hasCheck) sessWithChecks++;
146
+ }
147
+
148
+ return {
149
+ sessions: sessions.length,
150
+ medianPromptWords: median(promptWords),
151
+ delegationRate: userMsgs ? +(delegations / userMsgs).toFixed(3) : 0,
152
+ researchToMutation: mutations ? +(research / mutations).toFixed(2) : null,
153
+ verificationRate: sessions.length ? +(sessWithChecks / sessions.length).toFixed(2) : 0,
154
+ };
155
+ }
156
+
157
+ function computeShifts(parsed) {
158
+ const { early, late, midpoint } = splitHalves(parsed);
159
+ if (!early.length || !late.length) return { available: false };
160
+ const e = metricsFor(early);
161
+ const l = metricsFor(late);
162
+ return {
163
+ available: true,
164
+ midpoint,
165
+ early: e,
166
+ late: l,
167
+ deltas: [
168
+ { metric: "median prompt words", format: "number", early: e.medianPromptWords, late: l.medianPromptWords, dir: direction(e.medianPromptWords, l.medianPromptWords) },
169
+ { metric: "delegation rate", format: "percent", early: e.delegationRate, late: l.delegationRate, dir: direction(e.delegationRate, l.delegationRate) },
170
+ { metric: "research:mutation", format: "ratio", early: e.researchToMutation, late: l.researchToMutation, dir: direction(e.researchToMutation, l.researchToMutation) },
171
+ { metric: "verification rate", format: "percent", early: e.verificationRate, late: l.verificationRate, dir: direction(e.verificationRate, l.verificationRate) },
172
+ ],
173
+ };
174
+ }
175
+
176
+ function computeTopics(parsed) {
177
+ const buckets = new Map(); // quarter -> theme -> count
178
+ for (const s of parsed.sessions) {
179
+ for (const m of s.messages) {
180
+ for (const u of m.toolUses) {
181
+ if (!u.q) continue;
182
+ const t = ms(m.ts);
183
+ if (!Number.isFinite(t)) continue;
184
+ const q = `${new Date(t).getUTCFullYear()}-Q${Math.floor(new Date(t).getUTCMonth() / 3) + 1}`;
185
+ let theme = "other";
186
+ for (const [name, re] of TOPIC_RULES) if (re.test(u.q)) { theme = name; break; }
187
+ if (theme === "other") continue;
188
+ if (!buckets.has(q)) buckets.set(q, new Map());
189
+ const m2 = buckets.get(q);
190
+ m2.set(theme, (m2.get(theme) || 0) + 1);
191
+ }
192
+ }
193
+ }
194
+ return [...buckets.entries()]
195
+ .sort((a, b) => a[0].localeCompare(b[0]))
196
+ .map(([quarter, themes]) => ({
197
+ quarter,
198
+ themes: [...themes.entries()]
199
+ .sort((a, b) => b[1] - a[1])
200
+ .slice(0, 4)
201
+ .map(([name, count]) => ({ name, count })),
202
+ }));
203
+ }
204
+
205
+ function computeNewVocabulary(parsed) {
206
+ const earlyTs = [];
207
+ // First pass to find median session timestamp = "midpoint"
208
+ for (const s of parsed.sessions) if (s.firstTs && ms(s.firstTs)) earlyTs.push(ms(s.firstTs));
209
+ if (earlyTs.length < 4) return [];
210
+ earlyTs.sort((a, b) => a - b);
211
+ const mid = earlyTs[Math.floor(earlyTs.length / 2)];
212
+
213
+ // word -> { firstSeenTs, latePrompts, total }
214
+ // We produce CANDIDATES here: late-only words that recur. Telling
215
+ // "domain-specific" apart from "common chat" requires semantics, so the
216
+ // LLM step does the final filter on this list.
217
+ const word = new Map();
218
+ const promptId = (s, m) => `${s.sessionId}:${m.uuid || m.ts}`;
219
+ const wordRe = /[A-Za-z][A-Za-z-]{3,}/g;
220
+
221
+ for (const s of parsed.sessions) {
222
+ for (const m of s.messages) {
223
+ if (m.role !== "user" || !m.textRedacted) continue;
224
+ if (SYSTEM_PROMPT_RE.test(m.textRedacted.trim())) continue;
225
+ const t = ms(m.ts);
226
+ if (!Number.isFinite(t)) continue;
227
+ const seen = new Set();
228
+ const pid = promptId(s, m);
229
+ const tokens = m.textRedacted.toLowerCase().match(wordRe) || [];
230
+ for (const w of tokens) {
231
+ if (STOPWORDS.has(w)) continue;
232
+ if (seen.has(w)) continue;
233
+ seen.add(w);
234
+ if (!word.has(w)) word.set(w, { first: t, latePrompts: new Set(), total: 0 });
235
+ const entry = word.get(w);
236
+ entry.total++;
237
+ if (t < entry.first) entry.first = t;
238
+ if (t >= mid) entry.latePrompts.add(pid);
239
+ }
240
+ }
241
+ }
242
+
243
+ const candidates = [];
244
+ for (const [w, e] of word) {
245
+ if (e.first >= mid && e.latePrompts.size >= 3) {
246
+ candidates.push({ word: w, count: e.total, distinctLate: e.latePrompts.size });
247
+ }
248
+ }
249
+ candidates.sort((a, b) => b.distinctLate - a.distinctLate || b.count - a.count);
250
+ // Up to 30 candidates: the LLM gets generous breadth and picks ~6-10 that
251
+ // are actually domain/technical concepts.
252
+ return candidates.slice(0, 30).map((c) => c.word);
253
+ }
254
+
255
+ export function buildTrajectory(parsed) {
256
+ return {
257
+ shifts: computeShifts(parsed),
258
+ topics: computeTopics(parsed),
259
+ // Raw recurring-late words. The LLM step picks the technical/domain ones
260
+ // out of this list and writes them into trajectory.vocabularyAdopted on
261
+ // the final profile.
262
+ vocabularyCandidates: computeNewVocabulary(parsed),
263
+ };
264
+ }