@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,497 @@
1
+ // playnew-profile/v1: one source of truth (JSON) + a deterministic Markdown
2
+ // render. Structured facts come from the digest/fingerprint/forensics; the
3
+ // prose fields come from the narrative step. The Markdown is just a view, so
4
+ // human and agent never diverge.
5
+
6
+ // --- representative selection: significance leads, diversity breaks ties -----
7
+ //
8
+ // The pick is driven by how SIGNIFICANT the work is, not by how many chat
9
+ // sessions a repo accumulated. Each signal is normalised against the
10
+ // candidate's own portfolio (scale-free: a light user and a heavy user are
11
+ // scored on the same 0..1 axis), then weighted. Recency and type diversity are
12
+ // bounded nudges that can break a near-tie but never outweigh real substance.
13
+
14
+ // Relative significance weights. The point of taring lives here: if real-data
15
+ // selection looks skewed, adjust these, not the structure.
16
+ const W = { sessions: 0.30, commits: 0.25, mutations: 0.20, span: 0.10, type: 0.15 };
17
+ const CHECKS_BONUS = 0.05; // verification discipline
18
+ const CHURN_PENALTY = 0.05; // high revert churn
19
+ const RECENCY_BONUS = 0.15; // within the last 2 months of the window
20
+ const DIVERSITY_NUDGE = 0.10; // a primary type the picks don't cover yet
21
+
22
+ // How much each project TYPE counts toward significance. Shipping a product
23
+ // outweighs an exploratory poke even at equal volume.
24
+ const TYPE_WEIGHT = {
25
+ "product-build": 1.0, "ai-platform": 1.0, "product": 1.0,
26
+ "feature-work": 0.6, "data-migration": 0.6, "audit-research": 0.6,
27
+ "agent-tooling": 0.6, "static-site": 0.5, "testing": 0.5,
28
+ "exploration": 0.2,
29
+ };
30
+ const primary = (p) => p.type?.[0] || "exploration";
31
+ const typeWeight = (p) => TYPE_WEIGHT[primary(p)] ?? 0.5;
32
+
33
+ // "Recent" = last 2 months of the candidate's own window, not a fixed date.
34
+ // Returns a "YYYY-MM" cutoff or null if the projects don't carry a usable end.
35
+ function recencyCutoff(projects) {
36
+ const tos = projects.map((p) => p.to).filter(Boolean).sort();
37
+ if (!tos.length) return null;
38
+ const [y, m] = tos.at(-1).split("-").map(Number);
39
+ if (!Number.isFinite(y) || !Number.isFinite(m)) return null;
40
+ const d = new Date(Date.UTC(y, m - 1 - 2, 1)); // 2 months before the last end
41
+ return `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, "0")}`;
42
+ }
43
+
44
+ const isRecent = (p, recentSince) => !!(recentSince && p.to && p.to >= recentSince);
45
+
46
+ // Months spanned by a project, from "YYYY-MM" bounds (inclusive, min 1).
47
+ function spanMonths(p) {
48
+ if (!p.from || !p.to) return 1;
49
+ const [fy, fm] = p.from.split("-").map(Number);
50
+ const [ty, tm] = p.to.split("-").map(Number);
51
+ if (![fy, fm, ty, tm].every(Number.isFinite)) return 1;
52
+ return Math.max(1, (ty - fy) * 12 + (tm - fm) + 1);
53
+ }
54
+
55
+ // Build per-portfolio normalisers (the max of each signal, guarded against 0).
56
+ function normalizers(projects) {
57
+ const max = (f) => Math.max(1, ...projects.map(f));
58
+ return {
59
+ sessions: max((p) => p.sessions || 0),
60
+ commits: max((p) => p.landing?.commits || 0),
61
+ mutations: max((p) => p.mutations || 0),
62
+ span: max(spanMonths),
63
+ };
64
+ }
65
+
66
+ // Composite significance in roughly [0,1]. No recency or diversity here — those
67
+ // are applied at selection time so the same score drives adaptiveCount cleanly.
68
+ function significance(p, nrm) {
69
+ let s =
70
+ W.sessions * ((p.sessions || 0) / nrm.sessions) +
71
+ W.commits * ((p.landing?.commits || 0) / nrm.commits) +
72
+ W.mutations * ((p.mutations || 0) / nrm.mutations) +
73
+ W.span * (spanMonths(p) / nrm.span) +
74
+ W.type * typeWeight(p);
75
+ if (p.landing?.checksRun) s += CHECKS_BONUS;
76
+ if (p.landing?.revertChurn === "high") s -= CHURN_PENALTY;
77
+ return s;
78
+ }
79
+
80
+ // Adaptive count: 3 to 5, decided by the portfolio itself. Three picks always;
81
+ // a 4th and a 5th slot only when the next-ranked project EARNS it — it covers a
82
+ // primary type the picks don't, or it is nearly as significant as the 3rd pick
83
+ // (>= 60% of its significance). A concentrated, homogeneous history stays at 3;
84
+ // a spread, diverse one grows to 5.
85
+ function adaptiveCount(ranked, sig) {
86
+ let n = Math.min(3, ranked.length);
87
+ const types = new Set(ranked.slice(0, n).map(primary));
88
+ const anchor = ranked[2] ? sig(ranked[2]) : 0;
89
+ for (let i = n; i < Math.min(ranked.length, 5); i++) {
90
+ const p = ranked[i];
91
+ if (!types.has(primary(p)) || sig(p) >= 0.6 * anchor) {
92
+ n++;
93
+ types.add(primary(p));
94
+ } else break;
95
+ }
96
+ return n;
97
+ }
98
+
99
+ export function selectRepresentatives(projects, n = "auto") {
100
+ const recentSince = recencyCutoff(projects);
101
+ const nrm = normalizers(projects);
102
+ const sig = (p) => significance(p, nrm) + (isRecent(p, recentSince) ? RECENCY_BONUS : 0);
103
+ // Significance drives the count; the diversity nudge is selection-only.
104
+ const ranked = [...projects].sort((a, b) => sig(b) - sig(a));
105
+ if (n === "auto" || n == null || !Number.isFinite(+n)) n = adaptiveCount(ranked, sig);
106
+
107
+ // Greedy pick: at each step take the highest adjusted score, where a not-yet-
108
+ // covered primary type gets a small nudge. Significance leads; the nudge only
109
+ // breaks near-ties, it can't lift a marginal project over a substantial one.
110
+ const picked = [];
111
+ const types = new Set();
112
+ const remaining = new Set(projects);
113
+ while (picked.length < n && remaining.size) {
114
+ let best = null, bestScore = -Infinity;
115
+ for (const p of remaining) {
116
+ const adj = sig(p) + (types.has(primary(p)) ? 0 : DIVERSITY_NUDGE);
117
+ if (adj > bestScore) { bestScore = adj; best = p; }
118
+ }
119
+ picked.push(best);
120
+ types.add(primary(best));
121
+ remaining.delete(best);
122
+ }
123
+ const pickedSet = new Set(picked);
124
+ return projects.map((p) => ({ ...p, selected: pickedSet.has(p) }));
125
+ }
126
+
127
+ // --- cognitive tags from aggregate signals -----------------------------------
128
+
129
+ function cognitiveTags(projects, fingerprint) {
130
+ const tags = [];
131
+ const totalCommits = projects.reduce((n, p) => n + (p.landing.commits || 0), 0);
132
+ const totalReverts = projects.reduce((n, p) => n + (p.landing.reverts || 0), 0);
133
+ const totalDeleg = projects.reduce((n, p) => n + (p.delegation || 0), 0);
134
+ const checks = projects.filter((p) => p.landing.checksRun).length;
135
+ const rms = projects.map((p) => p.researchToMutation).filter((x) => x != null);
136
+ const avgRM = rms.length ? rms.reduce((a, b) => a + b, 0) / rms.length : 0;
137
+
138
+ if (avgRM > 2) tags.push("research-first");
139
+ if ((fingerprint?.style?.medianPromptWords || 0) >= 25) tags.push("decomposer");
140
+ if (totalDeleg >= 15) tags.push("orchestrator");
141
+ if (checks >= projects.length / 2) tags.push("verification-heavy");
142
+ if (totalCommits > 20 && totalReverts / Math.max(totalCommits, 1) < 0.1) tags.push("risk-calibrated");
143
+ return tags;
144
+ }
145
+
146
+ // --- sources ------------------------------------------------------------------
147
+
148
+ // Capture level per source. "full" = tamper-evident records the forensic
149
+ // screen can actually verify (request ids, signatures, usage shapes);
150
+ // "structural" = well-formed session data with no verification story.
151
+ // Unknown sources default to structural — honesty about what we can't verify.
152
+ const CAPTURE_LEVEL = { "claude-code": "full" };
153
+
154
+ // Per-source coverage summary for the profile: which sources were read, at
155
+ // what capture level, how many sessions each contributed, over which months.
156
+ // Counts here are CAPTURE counts (everything read, ephemeral included), so
157
+ // they are an upper bound on what enters the profile — and the profile's own
158
+ // window/counts stay lower bounds of the candidate's real activity, because
159
+ // logs rotate and old sessions are pruned.
160
+ export function summarizeSources(parsed) {
161
+ if (!parsed?.sessions?.length) return null;
162
+ const by = new Map();
163
+ for (const s of parsed.sessions) {
164
+ const key = s.source || "claude-code";
165
+ const e = by.get(key) || { source: key, sessions: 0, from: null, to: null };
166
+ e.sessions++;
167
+ const from = typeof s.firstTs === "string" ? s.firstTs.slice(0, 7) : null;
168
+ const to = typeof s.lastTs === "string" ? s.lastTs.slice(0, 7) : from;
169
+ if (from && (!e.from || from < e.from)) e.from = from;
170
+ if (to && (!e.to || to > e.to)) e.to = to;
171
+ by.set(key, e);
172
+ }
173
+ return [...by.values()].map((e) => ({
174
+ source: e.source,
175
+ captureLevel: CAPTURE_LEVEL[e.source] ?? "structural",
176
+ sessions: e.sessions,
177
+ window: e.from ? { from: e.from, to: e.to } : null,
178
+ // Which read path served this source, when it has more than one (e.g.
179
+ // opencode's sqlite db vs its partial JSON cache). mergeSources carries it
180
+ // out of the adapters; null for sources with a single read path.
181
+ backend: parsed.backends?.[e.source] ?? null,
182
+ }));
183
+ }
184
+
185
+ // --- assemble ----------------------------------------------------------------
186
+
187
+ export function assembleProfile({ contact, projects, narrative, fingerprint, forensics, manifestHash, trajectory, groundedness, aiRelationship, agenticLiteracy, intensity, distribution, techUsage, practices, sources, generatedBy }) {
188
+ const froms = projects.map((p) => p.from).filter(Boolean).sort();
189
+ const tos = projects.map((p) => p.to).filter(Boolean).sort();
190
+ const selected = projects.filter((p) => p.selected);
191
+ const others = projects.filter((p) => !p.selected);
192
+ const nById = (i) => narrative?.projects?.find((x) => x.id === `p${i + 1}`) || {};
193
+
194
+ return {
195
+ schema: "playnew-profile/v1",
196
+ generatedAt: new Date().toISOString(),
197
+ // Optional and nullable: the schema keeps the field for readers of older profiles, but this tool no
198
+ // longer asks for it (the hub's sign-in identifies the person) and `submit` never sends it.
199
+ contact: contact && typeof contact === "object" ? contact : null,
200
+ window: { from: froms[0] || null, to: tos.at(-1) || null },
201
+ volume: {
202
+ products: projects.length,
203
+ sessions: projects.reduce((n, p) => n + p.sessions, 0),
204
+ instructions: projects.reduce((n, p) => n + p.userMessages, 0),
205
+ },
206
+ // Coverage disclosure (optional; absent on profiles from older versions).
207
+ // What was read, at what capture level — the profile's own honesty about
208
+ // its inputs. Spread keeps the old shape byte-identical when absent.
209
+ ...(sources?.length ? { sources } : {}),
210
+ // Who wrote the narrative ({ narrative: { agent, model } }), when known.
211
+ ...(generatedBy ? { generatedBy } : {}),
212
+ summary: narrative?.summary || null,
213
+ // Aggregate fields of work, derived by the LLM from per-product evidence.
214
+ // Counts, not names: each entry is { label, products, sessions, note? }.
215
+ domains: narrative?.domains || [],
216
+ projects: selected.map((p, i) => ({
217
+ id: `p${i + 1}`,
218
+ // Repo label: the directory name of the candidate's own repo. Lets the
219
+ // candidate match `p1` to a concrete project they recognise during
220
+ // curation. They can remove it from candidate.json before submitting
221
+ // if it would leak a client name.
222
+ repoLabel: p.repo || null,
223
+ selected: true,
224
+ type: p.type,
225
+ domain: nById(i).domain || null,
226
+ span: { from: p.from, to: p.to },
227
+ sessions: p.sessions,
228
+ did: nById(i).did || null,
229
+ whyRepresentative: nById(i).why_representative || null,
230
+ tech: p.tech,
231
+ landing: p.landing,
232
+ metrics: { researchToMutation: p.researchToMutation, delegation: p.delegation, orchestration: p.orchestration || null },
233
+ artifact: null, // candidate opt-in
234
+ })),
235
+ otherProjects: others.map((p) => ({
236
+ repoLabel: p.repo || null,
237
+ type: p.type, span: { from: p.from, to: p.to }, sessions: p.sessions, includedBy: "tool:inventory",
238
+ })),
239
+ cognitive: { tags: cognitiveTags(projects, fingerprint), narrative: narrative?.cognitive?.narrative || null },
240
+ aiRelationship: aiRelationship
241
+ ? {
242
+ mode: aiRelationship.mode,
243
+ directing: aiRelationship.directing,
244
+ coThinking: aiRelationship.coThinking,
245
+ narrative: narrative?.ai_relationship?.narrative || null,
246
+ }
247
+ : null,
248
+ agenticLiteracy: agenticLiteracy
249
+ ? {
250
+ ...agenticLiteracy,
251
+ narrative: narrative?.agentic_literacy?.narrative || null,
252
+ }
253
+ : null,
254
+ intensity: intensity
255
+ ? { ...intensity, narrative: narrative?.intensity?.narrative || null }
256
+ : null,
257
+ distribution: distribution
258
+ ? { ...distribution, narrative: narrative?.distribution?.narrative || null }
259
+ : null,
260
+ // Per-technology usage counts and bands (optional/nullable: absent on
261
+ // profiles from older versions). Deterministic, so no narrative rides on it.
262
+ techUsage: techUsage || null,
263
+ // Per-session counts of work practices (optional/nullable: absent on
264
+ // profiles from older versions). Counts only, no narrative rides on it.
265
+ practices: practices || null,
266
+ trajectory: trajectory
267
+ ? {
268
+ // Deterministic facts (Lot 1).
269
+ shifts: trajectory.shifts?.available ? trajectory.shifts : null,
270
+ topics: trajectory.topics || [],
271
+ // ONLY the narrative's filtered pick. The raw vocabularyCandidates
272
+ // are unfiltered late-half words and can carry client or product
273
+ // names — they must never reach candidate.json.
274
+ newVocabulary: narrative?.trajectory?.vocabulary_adopted ?? [],
275
+ // LLM-derived (Lot 2). Optional — may be null if no narrative ran.
276
+ narrative: narrative?.trajectory?.narrative || null,
277
+ principlesAdopted: narrative?.trajectory?.principles_adopted || [],
278
+ }
279
+ : null,
280
+ stackAdopted: [...new Set(projects.flatMap((p) => p.tech))],
281
+ authenticity: {
282
+ score: forensics?.score ?? null,
283
+ manifestHash: manifestHash || null,
284
+ // The forensic checks inspect tamper-evident fields only full-capture
285
+ // sources carry; say so the moment a structural source is in the mix.
286
+ // A null score means there was no full-capture source to screen at all —
287
+ // disclose that rather than rendering a vacuous number.
288
+ note: forensics?.score == null
289
+ ? "n/a — no full-capture source to screen"
290
+ : sources?.some((s) => s.captureLevel !== "full")
291
+ ? "screen, not proof; verifies full-capture sources only"
292
+ : "screen, not proof",
293
+ },
294
+ groundedness: groundedness
295
+ ? { score: groundedness.score, supported: groundedness.supported, total: groundedness.total }
296
+ : null,
297
+ };
298
+ }
299
+
300
+ // --- render -------------------------------------------------------------------
301
+
302
+ const land = (l) =>
303
+ `commits ${l.commits} · reverts ${l.reverts} · churn ${l.revertChurn}${l.checksRun ? " · checks passed" : ""}`;
304
+
305
+ export function renderMarkdown(p) {
306
+ const L = [];
307
+ const c = p.contact || {};
308
+ L.push(`# Agentic profile${c.name ? ` — ${c.name}` : ""}`);
309
+ const meta = [c.email, c.city, c.status].filter(Boolean).join(" · ");
310
+ if (meta) L.push(meta);
311
+ L.push(
312
+ `Window: ${p.window.from} → ${p.window.to} · ${p.volume.sessions} sessions · ${p.volume.instructions} instructions · ${p.volume.products} products`,
313
+ );
314
+ L.push(`Log consistency screen: ${p.authenticity.score == null ? "n/a" : `${p.authenticity.score}/100`} (${p.authenticity.note})`);
315
+ if (p.sources?.length) {
316
+ const src = p.sources
317
+ .map((s) => `${s.source} (${s.captureLevel} capture${s.backend ? `, ${s.backend}` : ""}) · ${s.sessions} sessions read`)
318
+ .join(" · ");
319
+ L.push(`Sources: ${src}`);
320
+ L.push(`Window and counts are lower bounds: logs rotate and old sessions are pruned.`);
321
+ }
322
+ if (p.summary) L.push(`\n${p.summary}`);
323
+
324
+ if (p.domains?.length) {
325
+ L.push(`\n## Domains`);
326
+ for (const d of p.domains) {
327
+ const note = d.note ? ` — ${d.note}` : "";
328
+ L.push(`- **${d.label}** · ${d.products} products · ${d.sessions} sessions${note}`);
329
+ }
330
+ }
331
+
332
+ L.push(`\n## Representative projects`);
333
+ for (const pr of p.projects) {
334
+ const headTail = pr.repoLabel ? ` _(${pr.id} — ${pr.repoLabel})_` : ` _(${pr.id})_`;
335
+ L.push(`\n### ${pr.domain || "(domain)"} · ${pr.type.join(" · ")}${headTail}`);
336
+ L.push(`${pr.span.from ?? "n/a"}→${pr.span.to ?? "n/a"} · ${pr.sessions} sessions · ${land(pr.landing)}`);
337
+ if (pr.tech.length) L.push(`stack: ${pr.tech.join(", ")}`);
338
+ // The orchestration data candidate.json submits, on the human review
339
+ // surface too. Rendered only when it says something (multi-tool, dispatch
340
+ // or delegation counts) — a single-tool zero line is noise, and the exact
341
+ // payload stays inspectable via submit --dry-run.
342
+ const o = pr.metrics?.orchestration;
343
+ if (o && (o.toolCount >= 2 || o.dispatchCommands > 0 || o.delegation > 0)) {
344
+ const bits = [];
345
+ const tools = Object.entries(o.tools ?? {}).map(([k, v]) => `${k} ${v}`).join(" + ");
346
+ if (o.toolCount >= 2 && tools) {
347
+ bits.push(`sessions by tool: ${tools}${o.toolOverlap === false ? " (different periods)" : ""}`);
348
+ }
349
+ if (o.dispatchCommands > 0) bits.push(`${o.dispatchCommands} agent dispatches`);
350
+ if (o.delegation > 0) bits.push(`${o.delegation} sub-agent delegations`);
351
+ L.push(`orchestration: ${bits.join(" · ")}`);
352
+ }
353
+ if (pr.did) L.push(pr.did);
354
+ if (pr.whyRepresentative) L.push(`_why representative:_ ${pr.whyRepresentative}`);
355
+ L.push(`artifact: ${pr.artifact ? pr.artifact.label : "— (none attached)"}`);
356
+ }
357
+
358
+ if (p.otherProjects.length) {
359
+ L.push(`\n## Other projects (inventory)`);
360
+ for (const o of p.otherProjects) {
361
+ const tag = o.repoLabel ? ` _(${o.repoLabel})_` : "";
362
+ L.push(`- ${o.type.join(" · ")} · ${o.span.from ?? "n/a"}→${o.span.to ?? "n/a"} · ${o.sessions} sess${tag}`);
363
+ }
364
+ }
365
+
366
+ L.push(`\n## Cognitive profile`);
367
+ if (p.cognitive.tags.length) L.push(`tags: ${p.cognitive.tags.join(" · ")}`);
368
+ if (p.cognitive.narrative) L.push(p.cognitive.narrative);
369
+
370
+ if (p.aiRelationship) {
371
+ L.push(`\n## How they work with the AI`);
372
+ L.push(`${p.aiRelationship.directing}% directing · ${p.aiRelationship.coThinking}% co-thinking · ${p.aiRelationship.mode}`);
373
+ if (p.aiRelationship.narrative) L.push(p.aiRelationship.narrative);
374
+ }
375
+
376
+ if (p.intensity) {
377
+ const i = p.intensity;
378
+ L.push(`\n## Practice intensity`);
379
+ const tzNote = i.timezone && i.timezone !== "UTC" ? ` (days counted in ${i.timezone})` : "";
380
+ L.push(`- Active days: ${i.activeDays} / ${i.observedDays} (${Math.round(i.activeDaysRatio * 100)}%)${tzNote}`);
381
+ L.push(`- Median sessions per active day: ${i.medianSessionsPerActiveDay}`);
382
+ L.push(`- Median session depth: ${i.medianSessionToolCalls} tool calls`);
383
+ L.push(`- Longest streak: ${i.longestStreak} consecutive days`);
384
+ L.push(`- Peak day: ${i.peakDayToolCalls} tool calls`);
385
+ L.push(`Cadence: ${i.cadence} · ${i.sessionShape}`);
386
+ if (i.narrative) L.push(`\n${i.narrative}`);
387
+ }
388
+
389
+ if (p.distribution) {
390
+ const d = p.distribution;
391
+ L.push(`\n## Work distribution`);
392
+ L.push(`- Sessions per product: median ${d.medianSessionsPerProduct} · mean ${d.meanSessionsPerProduct}`);
393
+ L.push(`- Top 3 products: ${Math.round(d.top3Share * 100)}% of all sessions`);
394
+ L.push(`- Multi-month products: ${d.multiMonthProducts} / ${d.products} (${Math.round(d.multiMonthShare * 100)}%)`);
395
+ L.push(`Shape: ${d.shape}`);
396
+ if (d.narrative) L.push(`\n${d.narrative}`);
397
+ }
398
+
399
+ if (p.techUsage?.technologies?.length) {
400
+ const u = p.techUsage;
401
+ const tzNote = u.timezone && u.timezone !== "UTC" ? ` (months counted in ${u.timezone})` : "";
402
+ L.push(`\n## Technology usage`);
403
+ L.push(`Counts per technology detected in the stack, across all products${tzNote}. Sessions are those of the products where it was detected. The band only labels the month counts.`);
404
+ for (const t of u.technologies) {
405
+ const span = t.firstMonth === t.lastMonth ? t.firstMonth : `${t.firstMonth} to ${t.lastMonth}`;
406
+ L.push(`- ${t.name}: ${t.band} · ${t.sessions} sessions · ${t.products} ${t.products === 1 ? "product" : "products"} · ${t.months} ${t.months === 1 ? "month" : "months"} (${span})`);
407
+ }
408
+ }
409
+
410
+ if (p.practices?.items?.length) {
411
+ const u = p.practices;
412
+ const tzNote = u.timezone && u.timezone !== "UTC" ? ` (months counted in ${u.timezone})` : "";
413
+ L.push(`\n## How the work is done`);
414
+ L.push(`Counts of sessions where a practice was seen, out of the sessions where it could have been${tzNote}. Each row says how it was counted: by code, or by the person's own model.`);
415
+ for (const t of u.items) {
416
+ const how = t.method === "model" ? "classified by the person's model" : "counted by code";
417
+ L.push(`- ${t.id}: in ${t.seen} of ${t.of} ${t.of === 1 ? "session" : "sessions"} · ${t.products} ${t.products === 1 ? "product" : "products"} · ${t.months} ${t.months === 1 ? "month" : "months"} · ${how}`);
418
+ }
419
+ }
420
+
421
+ if (p.agenticLiteracy) {
422
+ const a = p.agenticLiteracy;
423
+ L.push(`\n## Agentic literacy`);
424
+ L.push(`Uses`);
425
+ L.push(`- Sub-agent delegations: ${a.uses.subagentDelegations}`);
426
+ L.push(`- Task tracking events: ${a.uses.taskTrackingEvents}`);
427
+ L.push(`- Built-in slash commands invoked: ${a.uses.builtinSlashInvocations}`);
428
+ L.push(`- Custom skills/commands: ${a.uses.customSkillsCommands.distinct} distinct, ${a.uses.customSkillsCommands.invocations} invocations`);
429
+ L.push(`- Public MCP servers: ${a.uses.publicMcp.servers} · ${a.uses.publicMcp.calls} calls`);
430
+ L.push(`- Custom MCP servers: ${a.uses.customMcp.servers} · ${a.uses.customMcp.tools} tools · ${a.uses.customMcp.calls} calls`);
431
+ L.push(`\nBuilds`);
432
+ L.push(`- Skills authored: ${a.builds.skillsAuthored}`);
433
+ L.push(`- Commands authored: ${a.builds.commandsAuthored}`);
434
+ L.push(`- Agents authored: ${a.builds.agentsAuthored}`);
435
+ L.push(`- Hooks edited: ${a.builds.hooksEdited}`);
436
+ L.push(`- Project memory files (CLAUDE.md): ${a.builds.projectMemoryFiles}`);
437
+ L.push(`\nDesigns`);
438
+ L.push(`- Plans-first (ExitPlanMode): ${a.designs.plansFirst}`);
439
+ L.push(`- Subtask tracking (TodoWrite): ${a.designs.subtaskTracking}`);
440
+ L.push(`- Clarifies (AskUserQuestion): ${a.designs.clarifies}`);
441
+ if (a.narrative) L.push(`\n${a.narrative}`);
442
+ }
443
+
444
+ // Trajectory: what changed strategically over the window. Numbers first, then
445
+ // the LLM narrative, then the principles the candidate codified for themselves.
446
+ if (p.trajectory) {
447
+ L.push(`\n## Trajectory`);
448
+ if (p.trajectory.narrative) L.push(p.trajectory.narrative);
449
+
450
+ if (p.trajectory.shifts && p.trajectory.shifts.deltas) {
451
+ L.push(`\nBehavioral shifts (early → late half${p.trajectory.shifts.midpoint ? `, split at ${p.trajectory.shifts.midpoint}` : ""}):`);
452
+ for (const d of p.trajectory.shifts.deltas) {
453
+ const arrow = d.dir === "up" ? "↑" : d.dir === "down" ? "↓" : d.dir === "stable" ? "·" : "";
454
+ L.push(`- ${d.metric}: ${formatVal(d.early, d.format)} → ${formatVal(d.late, d.format)} ${arrow}`);
455
+ }
456
+ }
457
+
458
+ if (p.trajectory.topics?.length) {
459
+ L.push(`\nTopics explored, by quarter:`);
460
+ for (const q of p.trajectory.topics) {
461
+ L.push(`- ${q.quarter}: ${q.themes.map((t) => `${t.name} (${t.count})`).join(", ")}`);
462
+ }
463
+ }
464
+
465
+ if (p.trajectory.newVocabulary?.length) {
466
+ L.push(`\nNew vocabulary adopted: ${p.trajectory.newVocabulary.join(", ")}`);
467
+ }
468
+
469
+ if (p.trajectory.principlesAdopted?.length) {
470
+ L.push(`\nPrinciples codified:`);
471
+ for (const pr of p.trajectory.principlesAdopted) {
472
+ const when = pr.when ? `_${pr.when}_ — ` : "";
473
+ L.push(`- ${when}${pr.text}`);
474
+ }
475
+ }
476
+ }
477
+
478
+ if (p.stackAdopted?.length) {
479
+ L.push(`\n## Stack adopted`);
480
+ L.push(p.stackAdopted.join(", "));
481
+ // Disclosed boundaries — detection reads package.json + touched files, never
482
+ // .env: (1) deps reflect the repo as it stands now, not at session time;
483
+ // (2) npm manifests only — no pyproject/requirements; (3) deps are absent if
484
+ // the project folder no longer exists; (4) REST-only services (an API key,
485
+ // no package) are not auto-detected.
486
+ L.push(`_Stack as currently declared in the repo: from package.json dependencies (npm manifests only) and the files touched. Dependencies are unavailable if the project folder no longer exists, and services used only over REST (no package) are not auto-detected._`);
487
+ }
488
+
489
+ return L.join("\n") + "\n";
490
+ }
491
+
492
+ function formatVal(v, fmt) {
493
+ if (v == null) return "n/a";
494
+ if (fmt === "percent") return `${Math.round(v * 100)}%`;
495
+ if (fmt === "ratio") return typeof v === "number" ? v.toFixed(2) : String(v);
496
+ return String(v);
497
+ }
package/src/redact.mjs ADDED
@@ -0,0 +1,97 @@
1
+ // Deterministic, structural PII redaction.
2
+ //
3
+ // This layer handles the PII that has a *shape* (paths, emails, secrets, IPs).
4
+ // Named entities (people, companies, product names) have no reliable shape and
5
+ // are left to the LLM pass — see profile.mjs. Structural fields used by the
6
+ // forensics (timestamps, uuids, token usage) are NEVER passed through here;
7
+ // only human-readable text is redacted. This structural layer also scrubs the
8
+ // local account name, because logs quote it both in dash-encoded paths and in
9
+ // plain prose.
10
+
11
+ import os from "node:os";
12
+ import { basename } from "node:path";
13
+
14
+ const RULES = [
15
+ // Secrets first, before anything else can partially mask them.
16
+ { re: /\bsk-ant-[A-Za-z0-9_-]{16,}/g, to: "⟨anthropic-key⟩" },
17
+ { re: /\bsk-[A-Za-z0-9]{20,}/g, to: "⟨api-key⟩" },
18
+ { re: /\bgithub_pat_[A-Za-z0-9_]{20,}/g, to: "⟨gh-token⟩" },
19
+ { re: /\bgh[pousr]_[A-Za-z0-9]{20,}/g, to: "⟨gh-token⟩" },
20
+ { re: /\bAKIA[0-9A-Z]{16}\b/g, to: "⟨aws-key⟩" },
21
+ { re: /\bAIza[0-9A-Za-z_-]{20,}\b/g, to: "⟨google-key⟩" },
22
+ { re: /\bxox[baprs]-[A-Za-z0-9-]{10,}/g, to: "⟨slack-token⟩" },
23
+ { re: /\bBearer\s+[A-Za-z0-9._-]{12,}/g, to: "Bearer ⟨token⟩" },
24
+ // NAME=secret style env assignments: keep the variable name, drop the value.
25
+ {
26
+ re: /\b([A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|PWD|CREDENTIAL|API)[A-Z0-9_]*)(\s*[=:]\s*)["']?([^"'\s]{6,})/g,
27
+ to: (_m, name, sep) => `${name}${sep}⟨secret⟩`,
28
+ },
29
+ // Emails.
30
+ { re: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g, to: "⟨email⟩" },
31
+ // Home-directory usernames, unix + windows. Keep the path shape, drop the user.
32
+ { re: /\/(Users|home)\/([^/\s"':]+)/g, to: "/$1/⟨user⟩" },
33
+ { re: /([A-Za-z]:\\Users\\)([^\\/\s"':]+)/g, to: "$1⟨user⟩" },
34
+ // Dash-encoded home paths (Claude Code encodes project/scratchpad dirs this
35
+ // way, e.g. /private/tmp/claude-501/-Users-<name>-Projects-...). The leading
36
+ // dash is the encoded-path marker; a rare false positive like "my-home-made"
37
+ // becoming "my-home-⟨user⟩" is accepted over-redaction.
38
+ { re: /-(Users|home)-([^-\s"':]+)/g, to: "-$1-⟨user⟩" },
39
+ // IPv4 (4 octets — won't catch semver's 3).
40
+ { re: /\b(?:\d{1,3}\.){3}\d{1,3}\b/g, to: "⟨ip⟩" },
41
+ ];
42
+
43
+ // Bare mentions of the local account name have no structural shape, but the
44
+ // machine knows its own username — so we build literal rules for it at module
45
+ // init. Names under 4 chars are skipped: short/common names (e.g. "al", "cj")
46
+ // are too likely to clobber ordinary words, so over-redaction risk outweighs
47
+ // the privacy gain. These rules are appended AFTER the path rules above, so
48
+ // the path rules get first crack and keep their shaped ⟨user⟩ output.
49
+ function localAccountNames() {
50
+ const names = new Set();
51
+ try {
52
+ const u = os.userInfo().username;
53
+ if (u) names.add(u);
54
+ } catch {
55
+ // no-op: redaction must never throw at import.
56
+ }
57
+ try {
58
+ const h = basename(os.homedir());
59
+ if (h) names.add(h);
60
+ } catch {
61
+ // no-op: redaction must never throw at import.
62
+ }
63
+ return [...names].filter((n) => n.length >= 4);
64
+ }
65
+
66
+ function escapeRegExp(s) {
67
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
68
+ }
69
+
70
+ for (const name of localAccountNames()) {
71
+ RULES.push({ re: new RegExp(escapeRegExp(name), "gi"), to: "⟨user⟩" });
72
+ }
73
+
74
+ /** Redact a single string. Returns the redacted string. */
75
+ export function redactText(input) {
76
+ if (typeof input !== "string" || input.length === 0) return input;
77
+ let out = input;
78
+ for (const { re, to } of RULES) out = out.replace(re, to);
79
+ return out;
80
+ }
81
+
82
+ /** Count how many redactions a string would trigger (for the redaction-rate signal). */
83
+ export function countRedactions(input) {
84
+ if (typeof input !== "string" || input.length === 0) return 0;
85
+ // Count progressively, mirroring redactText: rules can overlap (e.g. the
86
+ // literal account-name rule vs. the path rules), so counting each rule
87
+ // against the original input would double-count what redactText only
88
+ // substitutes once.
89
+ let out = input;
90
+ let n = 0;
91
+ for (const { re, to } of RULES) {
92
+ const m = out.match(re);
93
+ if (m) n += m.length;
94
+ out = out.replace(re, to);
95
+ }
96
+ return n;
97
+ }