@letsrebase/verify 0.0.0-stage → 0.1.1

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 +210 -2
  5. package/SECURITY.md +33 -0
  6. package/bin/rebase-verify.mjs +700 -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 +382 -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 +279 -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,279 @@
1
+ // Counts the seven code practices of `rebase-practices/v1` per session, in the
2
+ // order the events happened (message order, then tool-use order). Every number
3
+ // is "sessions where the practice was seen" over "sessions where it could have
4
+ // been": a session whose log lacks a field a practice needs (see `needs` in
5
+ // practices-rules.mjs), or whose adapter cannot show it (ADAPTERS_WITHOUT), is
6
+ // left out of that denominator, never counted as "not seen".
7
+ import { DEFAULT_TZ, isValidTimezone, monthKeyFor } from "./days.mjs";
8
+ import { isEphemeral, repoKey, splitTopLevel, stripHeredocs } from "./digest.mjs";
9
+ import {
10
+ ADAPTERS_WITHOUT, CODE_PRACTICES, EDIT_TOOLS as EDIT_TOOL_NAMES, PLAN_TOOLS as PLAN_TOOL_NAMES, RUBRIC,
11
+ isCheckCommand, isCommitCommand, isDesignDocPath, isDiffCommand, isPlanPath, isPullRequestCommand, isSecurityCommand, isSourcePath, isTestPath, stripToExecutable,
12
+ } from "./practices-rules.mjs";
13
+
14
+ const EDIT_TOOLS = new Set(EDIT_TOOL_NAMES);
15
+ const PLAN_TOOLS = new Set(PLAN_TOOL_NAMES);
16
+
17
+ const CODE_FILE = /\.(?:js|mjs|cjs|jsx|ts|mts|cts|tsx|py|go|rs|rb|java|kt|php|cs|c|cpp|h|swift|sh)$/i;
18
+
19
+ const subCommands = (cmd) => splitTopLevel(stripHeredocs(String(cmd ?? ""))).map((p) => p.trim()).filter(Boolean);
20
+
21
+ // A comparable key for "the same check": the first check sub-command, reduced
22
+ // to its executable words (env assignments and the npx, uv run, python -m,
23
+ // pnpm exec wrappers dropped, runner lower-cased) up to the first flag or
24
+ // path-like argument. A narrower run of a check keys like the broader one:
25
+ // "pytest tests/a.py -q", "pytest -x tests/", "uv run pytest" -> "pytest"
26
+ // "FOO=1 npx vitest run test/a.test.ts" -> "vitest run"
27
+ // "go test -run X ./pkg/..." -> "go test"
28
+ // A command that holds no check has no key ("").
29
+ export function normalizeCommand(cmd) {
30
+ const part = subCommands(cmd).find((p) => isCheckCommand(p));
31
+ if (!part) return "";
32
+ const tokens = stripToExecutable(part).split(/\s+/).filter(Boolean);
33
+ const at = tokens.findIndex((t, i) => i > 0 && (t.startsWith("-") || t === "." || t === ".." || /[\\/]/.test(t) || CODE_FILE.test(t)));
34
+ const kept = at < 0 ? tokens : tokens.slice(0, at);
35
+ if (kept.length) kept[0] = kept[0].toLowerCase();
36
+ return kept.join(" ");
37
+ }
38
+
39
+ // The ordered "atoms" of a session: one per edit, planning tool, or sub-command
40
+ // of a shell command (so `npm test && git commit` keeps its internal order).
41
+ // An edit path relative to the session's working directory, so a folder above
42
+ // the project (test, specs, plans) does not decide the classification. A path
43
+ // outside the directory, or already relative, stays as it is.
44
+ function relativeTo(path, session) {
45
+ const norm = (x) => String(x ?? "").replace(/\\/g, "/").replace(/\/+$/, "");
46
+ const p = path.replace(/\\/g, "/");
47
+ for (const root of [session?.cwdRedacted, session?.cwdRaw]) {
48
+ const r = norm(root);
49
+ if (r && p.toLowerCase().startsWith(`${r.toLowerCase()}/`)) return p.slice(r.length + 1);
50
+ }
51
+ return path;
52
+ }
53
+
54
+ function readSession(session) {
55
+ const messages = Array.isArray(session?.messages) ? session.messages : [];
56
+ const results = new Map();
57
+ const uses = [];
58
+ let hasToolUses = false;
59
+ let hasResults = false;
60
+ for (const m of messages) {
61
+ if (Array.isArray(m?.toolUses)) { hasToolUses = true; uses.push(...m.toolUses.filter(Boolean)); }
62
+ if (Array.isArray(m?.toolResults)) {
63
+ hasResults = true;
64
+ for (const r of m.toolResults) if (r && r.forId != null) results.set(r.forId, r.isError);
65
+ }
66
+ }
67
+ const atoms = [];
68
+ const bash = []; // one per Bash tool use: { e, id, cmd }
69
+ let cmdOk = hasToolUses;
70
+ let pathOk = hasToolUses;
71
+ uses.forEach((u, e) => {
72
+ if (EDIT_TOOLS.has(u.name)) {
73
+ // An empty path (codex apply_patch it could not parse) names no file.
74
+ if (typeof u.path !== "string" || u.path === "") pathOk = false;
75
+ atoms.push({ e, edit: true, path: typeof u.path === "string" ? relativeTo(u.path, session) : "" });
76
+ } else if (PLAN_TOOLS.has(u.name)) {
77
+ atoms.push({ e, plan: true });
78
+ } else if (u.name === "Bash") {
79
+ if (typeof u.cmd !== "string") { cmdOk = false; return; }
80
+ bash.push({ e, id: u.id, cmd: u.cmd });
81
+ for (const part of subCommands(u.cmd)) {
82
+ atoms.push({
83
+ e,
84
+ check: isCheckCommand(part),
85
+ security: isSecurityCommand(part),
86
+ diff: isDiffCommand(part),
87
+ commit: isCommitCommand(part),
88
+ pr: isPullRequestCommand(part),
89
+ });
90
+ }
91
+ }
92
+ });
93
+ return { atoms, bash, results, ok: { "toolUses.cmd": cmdOk, "toolUses.path": pathOk, "toolResults.isError": hasResults } };
94
+ }
95
+
96
+ // A check after the last edit before some commit (anywhere before it when no
97
+ // edit precedes it).
98
+ function checkedBeforeCommit(atoms) {
99
+ let lastEdit = -1;
100
+ let lastCheck = -1;
101
+ for (const [i, a] of atoms.entries()) {
102
+ if (a.check) lastCheck = i;
103
+ if (a.commit && lastCheck > lastEdit) return true;
104
+ if (a.edit) lastEdit = i;
105
+ }
106
+ return false;
107
+ }
108
+
109
+ function reviewedBeforeDelivery(atoms) {
110
+ let diffSeen = false;
111
+ for (const a of atoms) {
112
+ if (a.diff) diffSeen = true;
113
+ if ((a.commit || a.pr) && diffSeen) return true;
114
+ }
115
+ return false;
116
+ }
117
+
118
+ // A check command failed, files were edited, and the same check then succeeded.
119
+ function failureReproduced(bash, atoms, results) {
120
+ const editEvents = atoms.filter((a) => a.edit).map((a) => a.e);
121
+ for (const f of bash) {
122
+ if (results.get(f.id) !== true) continue;
123
+ const key = normalizeCommand(f.cmd);
124
+ if (!key) continue;
125
+ const fix = editEvents.find((e) => e > f.e);
126
+ if (fix === undefined) continue;
127
+ if (bash.some((c) => c.e > fix && results.get(c.id) === false && normalizeCommand(c.cmd) === key)) return true;
128
+ }
129
+ return false;
130
+ }
131
+
132
+ // One session's facts. `seen` and `denom` are keyed by practice id.
133
+ export function sessionFacts(session) {
134
+ const { atoms, bash, results, ok } = readSession(session);
135
+ const edits = atoms.filter((a) => a.edit);
136
+ const commits = atoms.filter((a) => a.commit).length;
137
+ const prs = atoms.filter((a) => a.pr).length;
138
+ const failed = bash.filter((c) => results.get(c.id) === true);
139
+ const sourceEdits = edits.filter((a) => isSourcePath(a.path)).length;
140
+ const testEdits = edits.filter((a) => isTestPath(a.path)).length;
141
+ const firstEdit = atoms.findIndex((a) => a.edit);
142
+
143
+ const seen = {
144
+ checks_before_commit: checkedBeforeCommit(atoms),
145
+ tests_with_changes: sourceEdits > 0 && testEdits > 0,
146
+ failure_reproduced_before_fix: failureReproduced(bash, atoms, results),
147
+ plan_before_edit: firstEdit >= 0 && (atoms.slice(0, firstEdit).some((a) => a.plan) || isPlanPath(atoms[firstEdit].path)),
148
+ reviews_changes: reviewedBeforeDelivery(atoms),
149
+ design_documents: edits.some((a) => isDesignDocPath(a.path)),
150
+ security_checks: atoms.some((a) => a.security),
151
+ };
152
+ const has = {
153
+ checks_before_commit: commits > 0,
154
+ tests_with_changes: sourceEdits > 0,
155
+ failure_reproduced_before_fix: failed.some((c) => normalizeCommand(c.cmd)) && !ADAPTERS_WITHOUT.failure_reproduced_before_fix.includes(session?.source),
156
+ plan_before_edit: edits.length > 0,
157
+ reviews_changes: commits + prs > 0,
158
+ design_documents: edits.length > 0,
159
+ security_checks: edits.length > 0,
160
+ };
161
+ const denom = {};
162
+ for (const p of CODE_PRACTICES) denom[p.id] = has[p.id] && p.needs.every((f) => ok[f]);
163
+ return { edits: edits.length, sourceEdits, testEdits, commits, prs, failedCommands: failed.length, seen, denom };
164
+ }
165
+
166
+ // The sessions the digest reads (ephemeral sandboxes are skipped), each with the
167
+ // product and month the counts are grouped by.
168
+ export function* eachSession(parsed, tz) {
169
+ const monthKey = monthKeyFor(tz);
170
+ const sessions = Array.isArray(parsed?.sessions) ? parsed.sessions : [];
171
+ for (const [i, s] of sessions.entries()) {
172
+ const cwd = s?.cwdRaw || s?.cwdRedacted || "";
173
+ if (isEphemeral(cwd)) continue;
174
+ let month = null;
175
+ for (const m of Array.isArray(s.messages) ? s.messages : []) {
176
+ const t = m?.ts ? Date.parse(m.ts) : NaN;
177
+ if (Number.isFinite(t)) { month = monthKey(t); break; }
178
+ }
179
+ yield {
180
+ session: s,
181
+ meta: { id: String(s.sessionId ?? `#${i}`), product: repoKey(s.cwdRedacted || cwd), month, source: s.source || "unknown" },
182
+ };
183
+ }
184
+ }
185
+
186
+ export function practiceSessions(parsed, { tz = DEFAULT_TZ } = {}) {
187
+ return [...eachSession(parsed, tz)].map(({ meta }) => meta);
188
+ }
189
+
190
+ export function computeCodePractices(parsed, { tz = DEFAULT_TZ } = {}) {
191
+ const acc = new Map(CODE_PRACTICES.map((p) => [p.id, { seen: 0, of: 0, products: new Set(), months: new Set() }]));
192
+ for (const { session, meta } of eachSession(parsed, tz)) {
193
+ if (!meta.month) continue; // no time: cannot be placed in a month
194
+ const facts = sessionFacts(session);
195
+ for (const [id, a] of acc) {
196
+ if (!facts.denom[id]) continue;
197
+ a.of++;
198
+ if (!facts.seen[id]) continue;
199
+ a.seen++;
200
+ a.products.add(meta.product);
201
+ a.months.add(meta.month);
202
+ }
203
+ }
204
+ const items = CODE_PRACTICES.filter((p) => acc.get(p.id).of > 0).map((p) => {
205
+ const a = acc.get(p.id);
206
+ return { id: p.id, method: p.method, seen: a.seen, of: a.of, products: a.products.size, months: a.months.size };
207
+ });
208
+ return items.length ? { items } : null;
209
+ }
210
+
211
+ // The zone a submit recounts the code practices in: the one the block recorded,
212
+ // never the machine's, so the recount measures the data and not the bucketing.
213
+ export function recordedPracticesTz(profile) {
214
+ const tz = profile?.practices?.timezone;
215
+ return isValidTimezone(tz) ? tz : DEFAULT_TZ;
216
+ }
217
+
218
+ // The block as the profile carries it: the rubric id and the zone the months
219
+ // were bucketed in travel with the counts. No items, no block. `classifiedBy`
220
+ // ({ agent, model }) names who read the sessions for the model items.
221
+ export function practicesBlock(items, { tz = DEFAULT_TZ, classifiedBy } = {}) {
222
+ if (!Array.isArray(items) || !items.length) return null;
223
+ return { rubric: RUBRIC, timezone: tz, items, ...(classifiedBy ? { classifiedBy } : {}) };
224
+ }
225
+
226
+ const isPlain = (x) => x != null && typeof x === "object" && !Array.isArray(x);
227
+
228
+ // The model's answers, keyed by the opaque sample id then by practice id: every
229
+ // sampled session and every id present, booleans only, nothing else.
230
+ export function validateModelAnswers(answers, sample, ids) {
231
+ if (!isPlain(answers)) return { ok: false, error: "the answers must be an object keyed by session id" };
232
+ const sessions = new Set(sample.map((s) => s.id));
233
+ for (const key of Object.keys(answers)) {
234
+ if (!sessions.has(key)) return { ok: false, error: `session ${key} is not in the sample` };
235
+ }
236
+ for (const id of sessions) {
237
+ const row = answers[id];
238
+ if (!isPlain(row)) return { ok: false, error: `session ${id} has no answers` };
239
+ for (const key of Object.keys(row)) {
240
+ if (!ids.includes(key)) return { ok: false, error: `session ${id}: "${key}" is not a practice to classify` };
241
+ }
242
+ for (const p of ids) {
243
+ if (!(p in row)) return { ok: false, error: `session ${id}: practice ${p} is missing` };
244
+ if (typeof row[p] !== "boolean") return { ok: false, error: `session ${id}: practice ${p} must be true or false` };
245
+ }
246
+ }
247
+ return { ok: true };
248
+ }
249
+
250
+ // Counts per model practice, as the code practices do: products and months are
251
+ // those of the sessions where it was seen; `of` is the sessions classified.
252
+ export function computeModelPractices(answers, sample, ids) {
253
+ if (!sample.length) return [];
254
+ return ids.map((id) => {
255
+ const seen = sample.filter((s) => answers[s.id]?.[id] === true);
256
+ return {
257
+ id, method: "model", seen: seen.length, of: sample.length,
258
+ products: new Set(seen.map((s) => s.product)).size, months: new Set(seen.map((s) => s.month)).size,
259
+ };
260
+ });
261
+ }
262
+
263
+ // The per-session answers with the real session ids; local only, never sent.
264
+ export function practicesDetail(answers, sample) {
265
+ return sample.map((s) => ({ session: s.session, date: s.date, product: s.product, answers: answers[s.id] }));
266
+ }
267
+
268
+ // Validates, then appends the model items after the code items in the one block.
269
+ // `classifiedBy` is recorded only when model items were added.
270
+ export function mergeModelPractices(codeBlock, answers, sample, ids, { tz = DEFAULT_TZ, classifiedBy } = {}) {
271
+ const v = validateModelAnswers(answers, sample, ids);
272
+ if (!v.ok) throw new Error(v.error);
273
+ const model = computeModelPractices(answers, sample, ids);
274
+ const items = [...(codeBlock?.items ?? []), ...model];
275
+ return {
276
+ block: practicesBlock(items, { tz: codeBlock?.timezone ?? tz, classifiedBy: model.length ? classifiedBy : undefined }),
277
+ detail: practicesDetail(answers, sample),
278
+ };
279
+ }
@@ -0,0 +1,249 @@
1
+ // Narrative step. Turns the deep digest + local enrichment into the qualitative
2
+ // prose fields (summary, per-project domain/did, cognitive profile, learning).
3
+ // Deterministic facts stay in the structured profile; this only writes what
4
+ // resists structuring.
5
+ //
6
+ // Anonymization happens HERE: the system prompt forbids proper names and the
7
+ // projects are keyed by opaque id (p1, p2…), never by repo name. So enrichment
8
+ // (which is full of real names) goes in, context-only prose comes out.
9
+
10
+ import { readFileSync } from "node:fs";
11
+ import { firstJsonObject } from "./agents/json-answer.mjs";
12
+
13
+ export const MODEL = "claude-opus-4-7";
14
+
15
+ export const NARRATIVE_SYSTEM = `You write a candidate's work profile from the logs of their activity with AI development tools.
16
+
17
+ HARD RULES:
18
+ - NO proper names: no companies, clients, people, products, brands, or repositories. Describe each project ONLY by abstract domain and context (e.g. "talent and campaigns management platform", not the actual product name). Exception: the agent CLI names in the orchestration data (e.g. Claude Code, opencode, codex, aider) are tools, not client brands — you may name them when citing the per-CLI split.
19
+ - Use only the data provided. No invention, no empty praise, no hyperbolic adjectives.
20
+ - Concrete and evidence-based: every claim must rest on signals in the digest (areas touched, stack, landing signals, prompts, commits).
21
+ - English, dry, readable by a human. No emojis, no em dashes.
22
+
23
+ You receive a JSON with the selected projects (opaque ids p1, p2, ...), each with: type, span, volumes, code areas, stack, landing signals (commits/reverts/checks), an orchestration block, web-search topics, sampled prompts, and LOCAL repo context (description, docs, dependencies, commit subjects).
24
+
25
+ The orchestration block has: delegation (sub-agent Task calls inside sessions), tools (per-CLI session split, e.g. {"claude-code": 38, "opencode": 12}), toolCount (distinct agent CLIs; an "unknown" bucket never counts as one), toolOverlap (true when at least two CLIs were active in overlapping periods; false when their eras are disjoint; null when there is nothing to compare), and dispatchCommands (shell commands that launched an agent CLI headless — which may target the same CLI: claude -p from a Claude Code session is the most common case). Apply these caveats strictly: every count is a lower bound — under single-source capture toolCount is pinned at 1 and dispatchCommands misses wrapped or nested launchers — so NEVER present toolCount 1 or dispatchCommands 0 as evidence that the candidate did not orchestrate or fan out. toolCount >= 2 with toolOverlap false means the CLIs were used in different periods: describe that as tool adoption or migration, never as concurrent fan-out. Describe cross-CLI fan-out only when toolOverlap is true; dispatchCommands > 0 is evidence of programmatic agent dispatch, not of cross-CLI fan-out on its own.
26
+
27
+ You also receive a TRAJECTORY block (what changed over the window) with: behavioral shifts (numbers, early vs late half), topic clusters from web research, new vocabulary adopted late, principles the candidate added to their own CLAUDE.md / README diffs, and compaction summaries the model wrote about earlier sessions.
28
+
29
+ For the trajectory narrative, focus on STRATEGIC AND CULTURAL change, NOT on stack adopted (the stack is rendered separately). Think: how their way of working evolved, what they came to value, the mental models they took on. Cite the numbers when they back a claim. Stay evidence-based.
30
+
31
+ You may also receive a PRACTICE_INTENSITY block with active-days ratio, median sessions per active day, median session depth, longest streak, peak day, and pre-classified cadence/sessionShape strings. Write 1-2 sentences in intensity.narrative describing how deeply Claude is embedded in the candidate's workflow (e.g. "daily driver with frequent multi-day streaks", "occasional, short bursts on specific tasks"). Evidence-based, no labels.
32
+
33
+ You may also receive a WORK_DISTRIBUTION block: products, sessions, mean/median sessions per product, top-3 concentration share, multi-month product share, and a pre-classified shape (portfolio / balanced / deep focus). Write 1-2 sentences in distribution.narrative on how this person spreads their work: many products each touched briefly (portfolio steering, direction across fronts) vs few products returned to repeatedly (sustained building, continuity). Say what this implies about how they engage. Neither pole is better; no judgement. The summary should also reflect this breadth-vs-depth shape in one clause.
34
+
35
+ You may also receive a DOMAIN_EVIDENCE array covering ALL products (not just the selected ones), each with: type tags, sessions, span, stack, code areas, web-search topics. From it, derive 3-5 aggregate DOMAINS — the fields of work this person operates in (e.g. "talent and creator operations", "business intelligence and finance ops", "agentic platforms and tooling", "nonprofit / civic"). For each domain output: label (abstract, NO proper names), products (how many products fall in it), sessions (their summed sessions), note (optional, 1 short clause of evidence). Every product should be assigned to exactly one domain; products + sessions across domains must not exceed the totals. The summary must say WHAT this person works on (the top domains) as well as how they work.
36
+
37
+ You may also receive an AGENTIC_LITERACY block with three groups of counts:
38
+ - uses: sub-agent delegations, task-tracking events, slash commands (built-in vs custom), MCP servers (public vs custom).
39
+ - builds: skills / commands / agents / hooks authored, CLAUDE.md files maintained.
40
+ - designs: ExitPlanMode, TodoWrite, AskUserQuestion invocations.
41
+ Write 2-3 sentences in agentic_literacy.narrative describing how mature this person is in the agentic stack. Mention concretely what they do (e.g. "has authored custom commands"; "integrates a custom MCP server"; "orchestrates extensively via sub-agents"; "tracks-while-running rather than plans-first"). **NEVER name any custom skill, custom command, custom MCP server, project, client, or company** — only describe in the abstract. Evidence-based, no labels.
42
+
43
+ You also receive an AI_RELATIONSHIP block with a numeric split on a single continuous axis with two poles:
44
+ - directing: treats the model like a careful junior, with long structured prompts, file paths, numbered steps, acceptance criteria.
45
+ - co-thinking: thinks out loud with the model, short conversational turns, open questions, lets the model push back.
46
+ The midpoint of the axis is co-construction (using the model to define the problem, not just execute it). And a few example prompts for each pole. Write 2-3 sentences in ai_relationship.narrative about WHEN they pick one mode vs the other (e.g. "structured spec on data and security work; conversational on UI exploration"). Stay evidence-based, no labels, no judgement.
47
+
48
+ The trajectory block also carries a vocabularyCandidates array: raw words that show up only in the late half of the window and recur across distinct prompts. Many of these are common chat words (verbs, adverbs). Pick the 6–10 that are clearly technical / domain-specific / concept names (e.g. business or technical jargon, framework or product names, methodology terms) and put them in trajectory.vocabulary_adopted. SKIP common verbs, adverbs, filler words.
49
+
50
+ Reply ONLY with a valid JSON in this shape:
51
+ {
52
+ "summary": "2-3 sentences: what this person works on (top domains) and how they work with AI",
53
+ "domains": [ { "label": "abstract field of work, no proper names", "products": 0, "sessions": 0, "note": "1 short clause of evidence (optional)" } ],
54
+ "cognitive": { "narrative": "4-6 sentences on the cognitive profile: decomposition, verification, error handling, orchestration, risk, calibrated trust in AI" },
55
+ "ai_relationship": { "narrative": "2-3 sentences on when they pick directing vs co-thinking mode" },
56
+ "agentic_literacy": { "narrative": "2-3 sentences on agentic-stack maturity. No proper names." },
57
+ "intensity": { "narrative": "1-2 sentences on how deeply Claude is embedded in their daily workflow." },
58
+ "distribution": { "narrative": "1-2 sentences on how they spread work across products: breadth vs depth, and what it implies about how they engage." },
59
+ "trajectory": {
60
+ "narrative": "3-5 sentences on strategic/cultural shift over the window. Cite the data. NO stack names here.",
61
+ "vocabulary_adopted": ["6-10 technical/domain words picked from vocabularyCandidates"],
62
+ "principles_adopted": [
63
+ { "when": "YYYY-MM (optional)", "text": "a principle the candidate codified" }
64
+ ]
65
+ },
66
+ "projects": [ { "id": "p1", "domain": "abstract domain", "did": "2-3 sentences on what they did", "why_representative": "1 sentence" } ]
67
+ }`;
68
+
69
+ // Scrub probable proper nouns from the prompt samples we hand to the model
70
+ // as evidence. The LLM has a hard anti-naming rule but we don't rely on
71
+ // soft constraints alone: replace capitalised tokens (not at sentence start)
72
+ // with a generic marker. False positives are acceptable, false negatives are
73
+ // the leak risk.
74
+ export function scrubProperNouns(text) {
75
+ if (!text) return text;
76
+ return text
77
+ .replace(/(?<!^|[.!?]\s|\n)\b([A-ZÀ-Ý][a-zà-ÿ]{2,})(?!\.\w)/g, "⟨name⟩");
78
+ }
79
+ function scrubExamples(examples) {
80
+ if (!examples) return examples;
81
+ return {
82
+ directing: (examples.directing ?? []).map(scrubProperNouns),
83
+ coThinking: (examples.coThinking ?? []).map(scrubProperNouns),
84
+ };
85
+ }
86
+
87
+ function narrativeInput(selected, enrichments, trajectory, compactionSummaries, aiRelationship, agenticLiteracy, intensity, distribution, allProjects) {
88
+ return {
89
+ // Compact per-product evidence across ALL products (not just the selected
90
+ // ones) so the model can derive the aggregate domains. Local-only input;
91
+ // the output side carries abstract labels and counts, never names.
92
+ domainEvidence: (allProjects ?? []).map((p) => ({
93
+ type: p.type,
94
+ sessions: p.sessions,
95
+ span: `${p.from ?? "n/a"}->${p.to ?? "n/a"}`,
96
+ tech: p.tech ?? [],
97
+ areas: Object.keys(p.topAreas ?? {}).slice(0, 6),
98
+ topics: (p.learningTopics ?? []).slice(0, 6),
99
+ })),
100
+ projects: selected.map((p, i) => {
101
+ const e = enrichments[i] || {};
102
+ return {
103
+ id: `p${i + 1}`,
104
+ repoLabel: p.repo || null,
105
+ type: p.type,
106
+ span: `${p.from ?? "n/a"}->${p.to ?? "n/a"}`,
107
+ sessions: p.sessions,
108
+ topAreas: Object.keys(p.topAreas).slice(0, 10),
109
+ tech: p.tech,
110
+ landing: p.landing,
111
+ orchestration: p.orchestration ?? null,
112
+ learningTopics: p.learningTopics,
113
+ promptSamples: p.promptSamples,
114
+ repoDescription: e.pkgDescription || null,
115
+ repoDoc: e.doc ? e.doc.slice(0, 1200) : null,
116
+ deps: e.deps || [],
117
+ commits: e.commits || [],
118
+ };
119
+ }),
120
+ trajectory: trajectory
121
+ ? {
122
+ shifts: trajectory.shifts?.available
123
+ ? {
124
+ midpoint: trajectory.shifts.midpoint,
125
+ early: trajectory.shifts.early,
126
+ late: trajectory.shifts.late,
127
+ deltas: trajectory.shifts.deltas,
128
+ }
129
+ : null,
130
+ topicsByQuarter: trajectory.topics,
131
+ vocabularyCandidates: trajectory.vocabularyCandidates,
132
+ }
133
+ : null,
134
+ // Lines added to CLAUDE.md/README over time across the selected projects
135
+ // — candidate's own doctrine for their future self and their agent.
136
+ principlesDiff: enrichments
137
+ .flatMap((e) => (e.principlesDiff || []).map((p) => ({ ...p, repo: e.pkgName || null })))
138
+ .slice(-30),
139
+ // Dense self-portraits of how earlier work went, written by the model
140
+ // inside Claude Code as compaction summaries.
141
+ compactionSummaries: (compactionSummaries || []).slice(-6),
142
+ aiRelationship: aiRelationship
143
+ ? {
144
+ mode: aiRelationship.mode,
145
+ directing: aiRelationship.directing,
146
+ coThinking: aiRelationship.coThinking,
147
+ sampledPrompts: aiRelationship.sampledPrompts,
148
+ examples: scrubExamples(aiRelationship.examples),
149
+ }
150
+ : null,
151
+ agenticLiteracy: agenticLiteracy || null,
152
+ intensity: intensity || null,
153
+ distribution: distribution || null,
154
+ };
155
+ }
156
+
157
+ async function postMessage(key, system, user, maxTokens, signal) {
158
+ const res = await fetch("https://api.anthropic.com/v1/messages", {
159
+ method: "POST",
160
+ signal,
161
+ headers: { "x-api-key": key, "anthropic-version": "2023-06-01", "content-type": "application/json" },
162
+ body: JSON.stringify({
163
+ model: MODEL,
164
+ max_tokens: maxTokens,
165
+ system,
166
+ messages: [{ role: "user", content: user }],
167
+ }),
168
+ });
169
+ if (!res.ok) throw new Error(`Anthropic API ${res.status}: ${await res.text()}`);
170
+ const data = await res.json();
171
+ return data.content?.find((b) => b.type === "text")?.text || "";
172
+ }
173
+
174
+ async function callAnthropic(input, key) {
175
+ const text = await postMessage(key, NARRATIVE_SYSTEM, JSON.stringify(input), 3000);
176
+ return firstJsonObject(text);
177
+ }
178
+
179
+ // A `call({ system, user }) => Promise<string>` for the raw text answer; `signal` aborts the request.
180
+ export const anthropicCall = (key, { signal } = {}) => ({ system, user }) => postMessage(key, system, user, 3000, signal);
181
+
182
+ // The runtime warning printed before anything is sent to api.anthropic.com.
183
+ export function warnApiKey(what = "the narrative input (project labels, README/CLAUDE.md excerpts,\n dependency names, commit subjects, sampled prompts)") {
184
+ console.error(
185
+ `[rebase-verify] ANTHROPIC_API_KEY is set: ${what} is being sent to api.anthropic.com.\n` +
186
+ " To stay fully local until submit, unset the key and use the /rebase-verify slash command\n" +
187
+ " (subscription path) or `prepare` + a hand-written narrative file. See PRIVACY.md."
188
+ );
189
+ }
190
+
191
+ // Light validation of the narrative shape. We don't want a malformed model
192
+ // reply to silently sail into the profile — that's the worst kind of bug.
193
+ // Throws with a precise pointer to the bad field. Tolerates extra keys.
194
+ export function validateNarrative(n, ctx) {
195
+ const where = (p) => `narrative${ctx ? ` (${ctx})` : ""}: ${p}`;
196
+ const str = (v) => typeof v === "string" && v.trim().length > 0;
197
+ if (!n || typeof n !== "object") throw new Error(where("not an object"));
198
+ if (!str(n.summary)) throw new Error(where("missing summary"));
199
+ if (!n.cognitive || typeof n.cognitive !== "object") throw new Error(where("missing cognitive"));
200
+ if (!str(n.cognitive.narrative)) throw new Error(where("missing cognitive.narrative"));
201
+ // domains is optional in older shapes; if present, it must be well-formed.
202
+ if (n.domains != null) {
203
+ if (!Array.isArray(n.domains)) throw new Error(where("domains not an array"));
204
+ for (const [i, d] of n.domains.entries()) {
205
+ if (!d || typeof d !== "object") throw new Error(where(`domains[${i}] not an object`));
206
+ if (!str(d.label)) throw new Error(where(`domains[${i}].label missing`));
207
+ if (!Number.isFinite(Number(d.products)) || Number(d.products) < 1) throw new Error(where(`domains[${i}].products must be a count >= 1`));
208
+ if (!Number.isFinite(Number(d.sessions)) || Number(d.sessions) < 1) throw new Error(where(`domains[${i}].sessions must be a count >= 1`));
209
+ }
210
+ }
211
+ // trajectory is optional in older shapes; if present, it must be well-formed.
212
+ if (n.trajectory != null) {
213
+ if (typeof n.trajectory !== "object") throw new Error(where("trajectory not an object"));
214
+ if (n.trajectory.narrative != null && !str(n.trajectory.narrative)) throw new Error(where("trajectory.narrative empty"));
215
+ if (n.trajectory.principles_adopted != null && !Array.isArray(n.trajectory.principles_adopted)) {
216
+ throw new Error(where("trajectory.principles_adopted not an array"));
217
+ }
218
+ }
219
+ if (!Array.isArray(n.projects)) throw new Error(where("projects not an array"));
220
+ for (const [i, p] of n.projects.entries()) {
221
+ if (!p || typeof p !== "object") throw new Error(where(`projects[${i}] not an object`));
222
+ if (!str(p.id)) throw new Error(where(`projects[${i}].id missing`));
223
+ if (!str(p.domain)) throw new Error(where(`projects[${i}].domain missing`));
224
+ if (!str(p.did)) throw new Error(where(`projects[${i}].did missing`));
225
+ }
226
+ return n;
227
+ }
228
+
229
+ // Builds the narrative input only. Never touches the network, so `prepare`
230
+ // can call it whatever the environment holds.
231
+ export function narrativeInputFor(selected, enrichments, { trajectory, compactionSummaries, aiRelationship, agenticLiteracy, intensity, distribution, allProjects } = {}) {
232
+ return narrativeInput(selected, enrichments, trajectory, compactionSummaries, aiRelationship, agenticLiteracy, intensity, distribution, allProjects);
233
+ }
234
+
235
+ // Returns { narrative, input, source }. narrative is null if no key and no
236
+ // override; source is "file", "api" or null.
237
+ // An explicit --narrative-file always wins over the env key: the API path
238
+ // sends the narrative input off-machine, so it must never engage silently
239
+ // or discard a hand-curated narrative just because a key is in the env.
240
+ export async function generateNarrative(selected, enrichments, { overrideFile, trajectory, compactionSummaries, aiRelationship, agenticLiteracy, intensity, distribution, allProjects } = {}) {
241
+ const input = narrativeInputFor(selected, enrichments, { trajectory, compactionSummaries, aiRelationship, agenticLiteracy, intensity, distribution, allProjects });
242
+ if (overrideFile) return { narrative: validateNarrative(JSON.parse(readFileSync(overrideFile, "utf8")), overrideFile), input, source: "file" };
243
+ const key = process.env.ANTHROPIC_API_KEY;
244
+ if (key) {
245
+ warnApiKey();
246
+ return { narrative: validateNarrative(await callAnthropic(input, key), "API"), input, source: "api" };
247
+ }
248
+ return { narrative: null, input, source: null };
249
+ }