@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,134 @@
1
+ // Statistical fingerprint + provenance manifest.
2
+ //
3
+ // The fingerprint is the texture of how someone works: tool mix, research vs
4
+ // mutation, latency, thinking depth, prompt style. It feeds both the profile
5
+ // and the verifier (a sudden discontinuity in this texture across sessions is
6
+ // itself a signal). The manifest pins the raw bytes so the bundle can't be
7
+ // edited after generation without the hashes diverging.
8
+
9
+ import { createHash } from "node:crypto";
10
+ import { activeDayKeys, dayKeyFor, DEFAULT_TZ } from "./days.mjs";
11
+
12
+ const sha256 = (s) => createHash("sha256").update(s).digest("hex");
13
+ const ms = (iso) => (iso ? Date.parse(iso) : NaN);
14
+
15
+ function percentile(sorted, p) {
16
+ if (!sorted.length) return null;
17
+ const i = Math.min(sorted.length - 1, Math.floor((p / 100) * sorted.length));
18
+ return sorted[i];
19
+ }
20
+ const median = (arr) => percentile([...arr].sort((a, b) => a - b), 50);
21
+
22
+ const MUTATION_TOOLS = new Set(["Edit", "Write", "NotebookEdit", "MultiEdit"]);
23
+ const RESEARCH_TOOLS = new Set(["Read", "Grep", "Glob", "WebSearch", "WebFetch"]);
24
+
25
+ export function computeFingerprint(parsed, { tz = DEFAULT_TZ } = {}) {
26
+ let messages = 0, user = 0, assistant = 0, toolUses = 0;
27
+ const tokens = { input: 0, output: 0, cacheRead: 0, cacheCreate: 0 };
28
+ const toolHistogram = {};
29
+ const models = new Set();
30
+ const cliVersions = new Set();
31
+ const projects = new Set();
32
+ const latencies = [];
33
+ const thinking = [];
34
+ const promptWords = [];
35
+ let shortPrompts = 0;
36
+ let allTs = [];
37
+
38
+ for (const s of parsed.sessions) {
39
+ projects.add(s.projectLabel);
40
+ for (const m of s.models) models.add(m);
41
+ for (const v of s.cliVersions) cliVersions.add(v);
42
+
43
+ let lastUserTs = null;
44
+ for (const m of s.messages) {
45
+ // Only user/assistant rows are conversation turns: pi emits toolResult
46
+ // rows as their own message rows (unlike claude-code/opencode/codex,
47
+ // which fold them into the assistant message), which would otherwise
48
+ // inflate this counter and make it non-comparable across sources.
49
+ if (m.role === "user" || m.role === "assistant") messages++;
50
+ if (ms(m.ts)) allTs.push(ms(m.ts));
51
+ if (m.role === "user") {
52
+ user++;
53
+ const words = m.textRedacted.trim().split(/\s+/).filter(Boolean).length;
54
+ if (words > 0) promptWords.push(words);
55
+ if (words > 0 && words <= 4) shortPrompts++;
56
+ lastUserTs = ms(m.ts);
57
+ } else if (m.role === "assistant") {
58
+ assistant++;
59
+ const reasoning = m.thinkingChars > 0 ? m.thinkingChars : m.signatureChars || 0;
60
+ if (reasoning > 0) thinking.push(reasoning);
61
+ if (lastUserTs && ms(m.ts)) {
62
+ const dt = ms(m.ts) - lastUserTs;
63
+ if (dt > 0 && dt < 1000 * 60 * 30) latencies.push(dt);
64
+ lastUserTs = null;
65
+ }
66
+ }
67
+ if (m.usage) {
68
+ tokens.input += m.usage.input;
69
+ tokens.output += m.usage.output;
70
+ tokens.cacheRead += m.usage.cacheRead;
71
+ tokens.cacheCreate += m.usage.cacheCreate;
72
+ }
73
+ for (const u of m.toolUses) {
74
+ toolUses++;
75
+ toolHistogram[u.name] = (toolHistogram[u.name] || 0) + 1;
76
+ }
77
+ }
78
+ }
79
+
80
+ const mutations = Object.entries(toolHistogram)
81
+ .filter(([k]) => MUTATION_TOOLS.has(k))
82
+ .reduce((n, [, v]) => n + v, 0);
83
+ const research = Object.entries(toolHistogram)
84
+ .filter(([k]) => RESEARCH_TOOLS.has(k))
85
+ .reduce((n, [, v]) => n + v, 0);
86
+
87
+ allTs = allTs.filter(Number.isFinite).sort((a, b) => a - b);
88
+ // Shared definition: distinct days carrying real message activity, bucketed in
89
+ // `tz` (default UTC — identical to the prior toISOString bucketing).
90
+ const dayKey = dayKeyFor(tz);
91
+ const days = activeDayKeys(allTs, tz);
92
+ const latSorted = [...latencies].sort((a, b) => a - b);
93
+
94
+ // Provenance manifest: per-file hashes + a bundle hash over them.
95
+ const fileHashes = parsed.files.map((f) => ({ file: f.relPath, sha256: f.sha256, bytes: f.bytes }));
96
+ const bundleHash = sha256(fileHashes.map((f) => f.sha256).sort().join(""));
97
+
98
+ return {
99
+ source: parsed.source,
100
+ totals: {
101
+ sessions: parsed.sessions.length,
102
+ projects: projects.size,
103
+ messages,
104
+ userMessages: user,
105
+ assistantMessages: assistant,
106
+ toolUses,
107
+ activeDays: days.size,
108
+ activeDaysTimezone: tz, // recorded so the count is reproducible (CONTRIBUTING: determinism)
109
+ // firstDay/lastDay bucket in the SAME zone as activeDays — otherwise a
110
+ // UTC span could be self-reportedly shorter than the tz-bucketed activeDays.
111
+ firstDay: allTs.length ? dayKey(allTs[0]) : null,
112
+ lastDay: allTs.length ? dayKey(allTs.at(-1)) : null,
113
+ },
114
+ tokens,
115
+ toolHistogram,
116
+ ratios: {
117
+ researchToMutation: mutations ? +(research / mutations).toFixed(2) : null,
118
+ toolsPerUserMessage: user ? +(toolUses / user).toFixed(2) : null,
119
+ },
120
+ style: {
121
+ medianPromptWords: median(promptWords),
122
+ shortPromptRate: user ? +(shortPrompts / user).toFixed(2) : null,
123
+ medianThinkingChars: median(thinking),
124
+ },
125
+ latencyMs: {
126
+ p50: percentile(latSorted, 50),
127
+ p90: percentile(latSorted, 90),
128
+ samples: latSorted.length,
129
+ },
130
+ models: [...models],
131
+ cliVersions: [...cliVersions],
132
+ manifest: { files: fileHashes, bundleHash },
133
+ };
134
+ }
@@ -0,0 +1,178 @@
1
+ // Internal-consistency forensics.
2
+ //
3
+ // None of these prove authenticity — logs are unsigned and the file is fully
4
+ // under the candidate's control. What they catch is the *cheap* fake: a hand
5
+ // edited transcript, a generated highlight reel, someone else's logs stitched
6
+ // in. A real session keeps timestamps, uuid chains, token accounting and
7
+ // tool pairing mutually consistent for free; a forgery has to keep all of them
8
+ // consistent at once, which is where it slips. The live reproduction gate is
9
+ // what handles the expensive fakes.
10
+ //
11
+ // Hardening note: every threshold here was calibrated against KNOWN-GENUINE
12
+ // logs that initially tripped naive checks. Claude Code interleaves sub-agent
13
+ // sidechains, resumes sessions across files, and injects <synthetic> messages —
14
+ // so "file order = time order" and "cache_read needs an earlier cache_write in
15
+ // this session" are both false. We check causality along the parent→child DAG
16
+ // (with clock-skew tolerance) and judge token caching dataset-wide. See
17
+ // test/forensics.test.mjs for the regression fixtures.
18
+
19
+ const now = () => Date.now();
20
+ const ms = (iso) => (iso ? Date.parse(iso) : NaN);
21
+ const SKEW_TOLERANCE_MS = 2000;
22
+ const SYNTHETIC = "<synthetic>";
23
+
24
+ function check(id, label, severity, status, detail) {
25
+ return { id, label, severity, status, detail };
26
+ }
27
+
28
+ // Verification scope: only full-capture sources carry the tamper-evident
29
+ // fields these checks inspect (request ids, signatures, usage shapes).
30
+ // Sessions from structural sources are excluded up front rather than allowed
31
+ // to pass the prefix checks vacuously on their null ids. A missing source tag
32
+ // (older bundles, test fixtures) defaults to claude-code.
33
+ const FULL_CAPTURE_SOURCES = new Set(["claude-code"]);
34
+
35
+ export function computeForensics(parsed) {
36
+ const checks = [];
37
+ const sessions = parsed.sessions.filter((s) => FULL_CAPTURE_SOURCES.has(s.source || "claude-code"));
38
+
39
+ // Global maps across all files/sidechains: a parent may live in another file
40
+ // of the same (resumed or sub-agent) session.
41
+ const tsByUuid = new Map();
42
+ const parentByUuid = new Map();
43
+ for (const s of sessions)
44
+ for (const c of s.chain) {
45
+ if (c.uuid) {
46
+ tsByUuid.set(c.uuid, ms(c.ts));
47
+ parentByUuid.set(c.uuid, c.parentUuid ?? null);
48
+ }
49
+ }
50
+
51
+ // 1. Malformed JSONL lines — a clean log has none.
52
+ const malformed = parsed.files.reduce((n, f) => n + f.malformed, 0);
53
+ checks.push(
54
+ malformed === 0
55
+ ? check("malformed_lines", "JSONL ben formato", "high", "pass", "nessuna riga corrotta")
56
+ : check("malformed_lines", "JSONL ben formato", "high", "flag", `${malformed} righe non parsabili`),
57
+ );
58
+
59
+ // 2. UUID chain integrity — non-null parents must resolve in the global set.
60
+ // A handful of unresolved parents are normal resume boundaries.
61
+ let orphans = 0;
62
+ let withParent = 0;
63
+ for (const [uuid, parent] of parentByUuid) {
64
+ if (parent) {
65
+ withParent++;
66
+ if (!tsByUuid.has(parent)) orphans++;
67
+ }
68
+ }
69
+ const orphanRate = withParent ? orphans / withParent : 0;
70
+ checks.push(
71
+ orphanRate <= 0.01
72
+ ? check("uuid_chain", "Catene UUID integre", "high", "pass", `${withParent} archi, ${orphans} orfani (${(orphanRate * 100).toFixed(2)}%)`)
73
+ : check("uuid_chain", "Catene UUID integre", "high", "flag", `${orphans}/${withParent} genitori irrisolti (${(orphanRate * 100).toFixed(1)}%)`),
74
+ );
75
+
76
+ // 3. Causal ordering: a child must not predate its parent (beyond clock skew).
77
+ let causalViol = 0;
78
+ let edges = 0;
79
+ for (const [uuid, parent] of parentByUuid) {
80
+ if (parent && tsByUuid.has(parent)) {
81
+ const cu = tsByUuid.get(uuid);
82
+ const pu = tsByUuid.get(parent);
83
+ if (Number.isFinite(cu) && Number.isFinite(pu)) {
84
+ edges++;
85
+ if (cu < pu - SKEW_TOLERANCE_MS) causalViol++;
86
+ }
87
+ }
88
+ }
89
+ // Flag by rate, not count: months of sessions accumulate a few sub-2s clock
90
+ // corrections (sleep/NTP) past tolerance; mass timestamp editing would not.
91
+ const causalRate = edges ? causalViol / edges : 0;
92
+ checks.push(
93
+ causalRate <= 0.005
94
+ ? check("ts_causal", "Ordine causale dei timestamp", "high", "pass", `${edges} archi, ${causalViol} oltre tolleranza (${(causalRate * 100).toFixed(3)}%)`)
95
+ : check("ts_causal", "Ordine causale dei timestamp", "high", "flag", `${causalViol}/${edges} figli datati prima del genitore (${(causalRate * 100).toFixed(1)}%)`),
96
+ );
97
+
98
+ // 4. No future timestamps.
99
+ let future = 0;
100
+ const t0 = now();
101
+ for (const t of tsByUuid.values()) if (t > t0) future++;
102
+ checks.push(
103
+ future === 0
104
+ ? check("ts_future", "Nessun timestamp nel futuro", "high", "pass", "ok")
105
+ : check("ts_future", "Nessun timestamp nel futuro", "high", "flag", `${future} eventi datati nel futuro`),
106
+ );
107
+
108
+ // 5. ID prefixes (Anthropic: req_… / msg_…). Skip <synthetic> harness messages.
109
+ let badId = 0;
110
+ let idTotal = 0;
111
+ for (const s of sessions)
112
+ for (const m of s.messages)
113
+ if (m.role === "assistant" && m.model && m.model !== SYNTHETIC) {
114
+ idTotal++;
115
+ const okReq = !m.requestId || m.requestId.startsWith("req_");
116
+ const okMsg = !m.messageId || m.messageId.startsWith("msg_");
117
+ if (!okReq || !okMsg) badId++;
118
+ }
119
+ checks.push(
120
+ badId === 0
121
+ ? check("id_format", "Formato ID coerente", "medium", "pass", `${idTotal} messaggi assistant`)
122
+ : check("id_format", "Formato ID coerente", "medium", "flag", `${badId} ID con prefisso anomalo`),
123
+ );
124
+
125
+ // 6. Token accounting, dataset-wide. Per-session is unreliable (resumes read a
126
+ // cache created by a prior process), so only a global impossibility flags.
127
+ let cacheRead = 0, cacheCreate = 0, withUsage = 0;
128
+ for (const s of sessions)
129
+ for (const m of s.messages)
130
+ if (m.usage) {
131
+ withUsage++;
132
+ cacheRead += m.usage.cacheRead;
133
+ cacheCreate += m.usage.cacheCreate;
134
+ }
135
+ const cacheImpossible = cacheRead > 0 && cacheCreate === 0;
136
+ checks.push(
137
+ !cacheImpossible
138
+ ? check("token_accounting", "Contabilità token coerente", "low", "pass", `${withUsage} messaggi con usage, cache create/read = ${cacheCreate}/${cacheRead}`)
139
+ : check("token_accounting", "Contabilità token coerente", "low", "flag", `cache-read ${cacheRead} senza alcuna cache-write nel dataset`),
140
+ );
141
+
142
+ // 7. Tool pairing: every tool_use should have a matching tool_result.
143
+ let unmatched = 0;
144
+ let toolUses = 0;
145
+ for (const s of sessions) {
146
+ const resultIds = new Set();
147
+ for (const m of s.messages) for (const r of m.toolResults) resultIds.add(r.forId);
148
+ for (const m of s.messages)
149
+ for (const u of m.toolUses) {
150
+ toolUses++;
151
+ if (!resultIds.has(u.id)) unmatched++;
152
+ }
153
+ }
154
+ const unmatchedRate = toolUses ? unmatched / toolUses : 0;
155
+ checks.push(
156
+ unmatchedRate <= 0.02
157
+ ? check("tool_pairing", "Pairing tool_use/result", "medium", "pass", `${toolUses} chiamate, ${unmatched} senza risultato`)
158
+ : check("tool_pairing", "Pairing tool_use/result", "medium", "flag", `${unmatched}/${toolUses} chiamate senza risultato (${(unmatchedRate * 100).toFixed(0)}%)`),
159
+ );
160
+
161
+ // Score: weighted deductions. A screen, not a verdict.
162
+ //
163
+ // UNSCORED when no full-capture session was screened: every session-based
164
+ // check above iterates the (now empty) `sessions` array and passes vacuously,
165
+ // so a positive score would assert a clean tamper screen over ZERO verified
166
+ // sessions — e.g. an opencode-only bundle, or a sparse ~/.claude alongside
167
+ // opencode. Return null instead, mirroring the groundedness gate's "unscored
168
+ // is not a pass" stance. The structural sources still surface in the profile's
169
+ // sources block; the screen just declines to vouch for what it cannot verify.
170
+ const weights = { high: 25, medium: 12, low: 5 };
171
+ let score = sessions.length === 0 ? null : 100;
172
+ if (score !== null) {
173
+ for (const c of checks) if (c.status === "flag") score -= weights[c.severity] || 5;
174
+ score = Math.max(0, score);
175
+ }
176
+
177
+ return { score, checks };
178
+ }
@@ -0,0 +1,347 @@
1
+ // Pre-submit groundedness check.
2
+ //
3
+ // The profile mixes deterministic fields (numbers, tags, stack) with prose
4
+ // fields written by the LLM (summary, cognitive narrative, trajectory
5
+ // narrative, did, why_representative, domain, principles_adopted). The risk
6
+ // is that the prose drifts from the data — claims numbers that aren't in the
7
+ // logs, name a technology nobody touched, invent a behaviour.
8
+ //
9
+ // We don't try to be a fact-checker. We extract verifiable ANCHORS from the
10
+ // prose (numbers, technology names, type tags, year-months) and check that
11
+ // each anchor exists somewhere in the structured data the prose was generated
12
+ // from. The score is the percentage of anchors supported.
13
+ //
14
+ // Designed to be transparent: every flagged anchor is shown to the candidate
15
+ // before submission so they can re-generate or edit if something is off.
16
+
17
+ import { labelVocabulary } from "./digest.mjs";
18
+
19
+ // Stack tokens AND AI-tooling vocabulary. A narrative that says "Claude" or
20
+ // "SDK" or "MCP" is referring to general AI/dev primitives that are part of
21
+ // the trajectory even when not listed in a project's `tech` array. We treat
22
+ // these as inherently grounded — the candidate is using them right now to
23
+ // generate this profile.
24
+ const TECH_NAMES = [
25
+ // Web / framework stack
26
+ "Supabase","Postgres","Inngest","Playwright","Tailwind","shadcn","Zod","Prisma","Next.js","React",
27
+ "Stripe","Drizzle","Brevo","Resend","Vercel","TypeScript","Python","Node","Vitest","Jest","ESLint",
28
+ ];
29
+
30
+ // The lexicon the prose is checked against = the hardcoded names ABOVE plus
31
+ // every label the detector can emit (src/digest.mjs labelVocabulary()),
32
+ // tokenised exactly as the support pool is (splitTech), so a token a narrative
33
+ // cites matches a token the pool carries. Deriving it from the same maps means
34
+ // detection and verification can never drift apart. A stoplist drops the generic
35
+ // English words that leak from descriptive labels ("event-driven jobs",
36
+ // "analytics") so they don't become spurious tech anchors.
37
+ //
38
+ // Exported because share/tech-lexicon.json is generated from it (npm run
39
+ // lexicon) — the checked-in artifact the play-new-dashboard intake vendors so
40
+ // its groundedness recompute extracts the same tech anchors this module does.
41
+ // test/lexicon-artifact.test.mjs fails when the artifact goes stale.
42
+ const LEXICON_STOP = new Set([
43
+ "event-driven", "jobs", "rich", "text", "analytics", "email", "headless",
44
+ "cms", "pdf", "monorepo", "google", "motion", "hook", "form", "shell",
45
+ ]);
46
+ export const TECH_LEXICON = [...new Set([...TECH_NAMES, ...labelVocabulary()].flatMap(splitTech))]
47
+ .filter((t) => t.length >= 3 && !LEXICON_STOP.has(t));
48
+
49
+ // AI-tooling vocabulary — always considered grounded, since the candidate is
50
+ // (by definition) using these tools to participate in Apply New.
51
+ const AI_TOOLING = new Set([
52
+ "claude","claude code","claude.ai","anthropic","openai","gpt","gemini","codex",
53
+ "sdk","api","mcp","agent","agents","subagent","sub-agent","skill","skills",
54
+ "llm","llms","prompt","tool use","tool-use","reasoning","thinking","context window",
55
+ ]);
56
+
57
+ const TYPE_TAGS = [
58
+ "product-build","audit-research","agent-tooling","static-site","ai-platform",
59
+ "data-migration","feature-work","testing","quality-gating","orchestrated","design-research","exploration",
60
+ ];
61
+
62
+ const COGNITIVE_TAGS = [
63
+ "research-first","decomposer","orchestrator","verification-heavy","risk-calibrated",
64
+ ];
65
+
66
+ // Extract candidate ANCHORS from a chunk of prose.
67
+ function extractAnchors(text) {
68
+ if (!text || typeof text !== "string") return [];
69
+ const anchors = [];
70
+
71
+ // Numbers that look meaningful (>1 digit OR followed by a unit/word).
72
+ for (const m of text.matchAll(/\b\d{1,5}(?:[.,]\d+)?\b/g)) {
73
+ const n = Number(m[0].replace(",", "."));
74
+ if (Number.isFinite(n) && n >= 2) anchors.push({ kind: "number", value: n, raw: m[0] });
75
+ }
76
+
77
+ // Percentages.
78
+ for (const m of text.matchAll(/(\d{1,3})\s*%/g)) {
79
+ anchors.push({ kind: "percent", value: Number(m[1]) / 100, raw: m[0] });
80
+ }
81
+
82
+ // Year-months (2026-03, 2026-Q1).
83
+ for (const m of text.matchAll(/\b20\d{2}-(?:Q[1-4]|0?[1-9]|1[0-2])\b/g)) {
84
+ anchors.push({ kind: "period", value: m[0], raw: m[0] });
85
+ }
86
+
87
+ // Technology names — case-insensitive but anchored on word boundary.
88
+ // AI-tooling words are pre-grounded (a candidate using Apply New is using
89
+ // Claude / an SDK / an MCP server / agents by definition).
90
+ for (const t of TECH_LEXICON) {
91
+ const re = new RegExp(`\\b${t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`, "i");
92
+ if (re.test(text)) anchors.push({ kind: "tech", value: t.toLowerCase(), raw: t });
93
+ }
94
+ for (const t of AI_TOOLING) {
95
+ const re = new RegExp(`\\b${t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`, "i");
96
+ if (re.test(text)) anchors.push({ kind: "ai-tooling", value: t, raw: t });
97
+ }
98
+
99
+ // Type tags & cognitive tags, only if they appear in prose form.
100
+ for (const t of [...TYPE_TAGS, ...COGNITIVE_TAGS]) {
101
+ if (text.toLowerCase().includes(t)) anchors.push({ kind: "tag", value: t, raw: t });
102
+ }
103
+
104
+ return anchors;
105
+ }
106
+
107
+ function collectSupportPool(profile) {
108
+ const numbers = new Set();
109
+ // Percent anchors get their own pool. The number pool is full of COUNTS,
110
+ // and a count collides with a percent exactly at the fractions' edges: a 1
111
+ // anywhere (one delegation, median 1 session/day) equals the "100%" anchor
112
+ // value 1.0, a 0 equals "0%" — so any such profile silently grounded any
113
+ // fabricated percentage. Only share/rate-typed fields (activeDaysRatio,
114
+ // top3Share, multiMonthShare, percent-format trajectory shifts) may support
115
+ // a percent claim.
116
+ const ratios = new Set();
117
+ const periods = new Set();
118
+ const tech = new Set();
119
+ const tags = new Set();
120
+
121
+ const addNumber = (n) => {
122
+ if (n == null) return;
123
+ const v = Number(n);
124
+ if (Number.isFinite(v)) numbers.add(v);
125
+ };
126
+ const addRatio = (n) => {
127
+ if (n == null) return;
128
+ const v = Number(n);
129
+ if (Number.isFinite(v)) ratios.add(v);
130
+ };
131
+ const addText = (s) => {
132
+ if (!s) return;
133
+ for (const m of String(s).match(/\b20\d{2}-(?:Q[1-4]|0?[1-9]|1[0-2])\b/g) ?? []) periods.add(m);
134
+ };
135
+
136
+ // Top-level volume + window + authenticity
137
+ addNumber(profile?.volume?.sessions);
138
+ addNumber(profile?.volume?.products);
139
+ addNumber(profile?.volume?.instructions);
140
+ addNumber(profile?.authenticity?.score);
141
+ // Per-source capture counts are citable ("941 sessions read from …")
142
+ for (const s of profile?.sources ?? []) addNumber(s.sessions);
143
+ addText(profile?.window?.from);
144
+ addText(profile?.window?.to);
145
+
146
+ // Per project structured facts
147
+ for (const p of profile?.projects ?? []) {
148
+ addNumber(p.sessions);
149
+ addNumber(p?.landing?.commits);
150
+ addNumber(p?.landing?.reverts);
151
+ addNumber(p?.metrics?.researchToMutation);
152
+ addNumber(p?.metrics?.delegation);
153
+ // Orchestration counts a narrative may cite ("N dispatches across M CLIs").
154
+ // Only values >= 2 pool: number anchors start at 2, so 0/1 buy nothing.
155
+ // (Percent anchors no longer read this pool at all — see the ratios set —
156
+ // so this gate is hygiene: counts that nothing can cite stay out.)
157
+ const addCount = (n) => { if (Number(n) >= 2) addNumber(n); };
158
+ addCount(p?.metrics?.orchestration?.dispatchCommands);
159
+ addCount(p?.metrics?.orchestration?.toolCount);
160
+ // The narrative is fed the per-CLI session split (orchestration.tools, e.g.
161
+ // {"claude-code": 38, opencode: 12}); pool those counts too, so once a
162
+ // second source lands a narrative citing "38 via Claude, 12 via opencode" is
163
+ // grounded, not flagged. (Single-source: tools is {claude-code: p.sessions},
164
+ // already pooled via p.sessions above — so this is inert until a 2nd source.)
165
+ for (const v of Object.values(p?.metrics?.orchestration?.tools ?? {})) addCount(v);
166
+ addText(p?.span?.from);
167
+ addText(p?.span?.to);
168
+ for (const t of p.tech ?? []) for (const w of splitTech(t)) tech.add(w);
169
+ for (const t of p.type ?? []) tags.add(t);
170
+ }
171
+ for (const o of profile?.otherProjects ?? []) {
172
+ addNumber(o.sessions);
173
+ addText(o?.span?.from);
174
+ addText(o?.span?.to);
175
+ for (const t of o.type ?? []) tags.add(t);
176
+ }
177
+
178
+ for (const t of profile?.stackAdopted ?? []) for (const w of splitTech(t)) tech.add(w);
179
+ for (const t of profile?.cognitive?.tags ?? []) tags.add(t);
180
+
181
+ // Domains rollup counts (sum-checked separately in assessGroundedness; once
182
+ // they pass that check the prose may cite them)
183
+ for (const d of profile?.domains ?? []) {
184
+ addNumber(d.products);
185
+ addNumber(d.sessions);
186
+ }
187
+
188
+ // Practice-intensity numbers (the narrative may quote any of them, raw or
189
+ // as %: the fraction feeds the ratios pool, the rounded percent stays a
190
+ // citable number — "87%" extracts both a percent anchor 0.87 and a number
191
+ // anchor 87)
192
+ const it = profile?.intensity;
193
+ if (it) {
194
+ addNumber(it.observedDays);
195
+ addNumber(it.activeDays);
196
+ addNumber(it.longestStreak);
197
+ addNumber(it.medianSessionsPerActiveDay);
198
+ addNumber(it.medianSessionToolCalls);
199
+ addNumber(it.peakDayToolCalls);
200
+ addRatio(it.activeDaysRatio);
201
+ if (it.activeDaysRatio != null) addNumber(Math.round(it.activeDaysRatio * 100));
202
+ }
203
+
204
+ // Work distribution numbers (same fraction/rounded-percent split)
205
+ const dist = profile?.distribution;
206
+ if (dist) {
207
+ addNumber(dist.meanSessionsPerProduct);
208
+ addNumber(dist.medianSessionsPerProduct);
209
+ addNumber(dist.multiMonthProducts);
210
+ addRatio(dist.top3Share);
211
+ addNumber(Math.round(dist.top3Share * 100));
212
+ addRatio(dist.multiMonthShare);
213
+ addNumber(Math.round(dist.multiMonthShare * 100));
214
+ }
215
+
216
+ // Technology-usage counts (the prose may cite "Supabase in 7 months"). Names
217
+ // already join the tech pool through the projects' stacks; names seen only in
218
+ // non-representative products are pooled here. Months pool as year-months too.
219
+ for (const t of profile?.techUsage?.technologies ?? []) {
220
+ for (const w of splitTech(t.name)) tech.add(w);
221
+ addNumber(t.sessions);
222
+ addNumber(t.products);
223
+ addNumber(t.months);
224
+ addText(t.firstMonth);
225
+ addText(t.lastMonth);
226
+ }
227
+
228
+ // Practice counts ("in 18 of 25 sessions, over 4 months").
229
+ for (const t of profile?.practices?.items ?? []) {
230
+ addNumber(t.seen);
231
+ addNumber(t.of);
232
+ addNumber(t.products);
233
+ addNumber(t.months);
234
+ }
235
+
236
+ // Trajectory numbers. Percent-format shifts (delegation rate, verification
237
+ // rate) hold fractions the prose cites as percents; number/ratio-format
238
+ // shifts (prompt words, research:mutation) are cited as plain numbers.
239
+ const s = profile?.trajectory?.shifts;
240
+ if (s?.deltas) for (const d of s.deltas) {
241
+ if (d.format === "percent") {
242
+ addRatio(d.early);
243
+ addRatio(d.late);
244
+ if (d.early != null) addNumber(Math.round(d.early * 100));
245
+ if (d.late != null) addNumber(Math.round(d.late * 100));
246
+ } else {
247
+ addNumber(d.early);
248
+ addNumber(d.late);
249
+ }
250
+ }
251
+ if (s?.midpoint) addText(s.midpoint);
252
+ for (const q of profile?.trajectory?.topics ?? []) { addText(q.quarter); for (const th of q.themes ?? []) addNumber(th.count); }
253
+ for (const pr of profile?.trajectory?.principlesAdopted ?? []) addText(pr.when);
254
+
255
+ return { numbers, ratios, periods, tech, tags };
256
+ }
257
+
258
+ // "Supabase/Postgres" or "Playwright (E2E)" should make both "supabase",
259
+ // "postgres", "playwright" individually grounded.
260
+ function splitTech(label) {
261
+ return String(label)
262
+ .toLowerCase()
263
+ .split(/[\s/(),]+/)
264
+ .map((s) => s.replace(/[^a-z.+-]/g, ""))
265
+ .filter((s) => s.length >= 3);
266
+ }
267
+
268
+ // Numbers in prose match if they equal a structured number or are within 5%
269
+ // of one (the LLM may round "153 commits" as "around 150").
270
+ function numberMatches(n, numberSet) {
271
+ if (numberSet.has(n)) return true;
272
+ for (const v of numberSet) {
273
+ if (v === 0 || n === 0) continue;
274
+ if (Math.abs((n - v) / v) <= 0.05) return true;
275
+ }
276
+ return false;
277
+ }
278
+
279
+ function classifyTextFields(profile) {
280
+ // Returns a list of { where, text } prose fields to verify.
281
+ const fields = [];
282
+ if (profile?.summary) fields.push({ where: "summary", text: profile.summary });
283
+ if (profile?.cognitive?.narrative) fields.push({ where: "cognitive.narrative", text: profile.cognitive.narrative });
284
+ if (profile?.trajectory?.narrative) fields.push({ where: "trajectory.narrative", text: profile.trajectory.narrative });
285
+ if (profile?.distribution?.narrative) fields.push({ where: "distribution.narrative", text: profile.distribution.narrative });
286
+ if (profile?.intensity?.narrative) fields.push({ where: "intensity.narrative", text: profile.intensity.narrative });
287
+ for (const [i, d] of (profile?.domains ?? []).entries()) {
288
+ if (d?.note) fields.push({ where: `domains[${i}].note`, text: d.note });
289
+ }
290
+ for (const p of profile?.projects ?? []) {
291
+ if (p.domain) fields.push({ where: `${p.id}.domain`, text: p.domain });
292
+ if (p.did) fields.push({ where: `${p.id}.did`, text: p.did });
293
+ if (p.whyRepresentative) fields.push({ where: `${p.id}.whyRepresentative`, text: p.whyRepresentative });
294
+ }
295
+ for (const pr of profile?.trajectory?.principlesAdopted ?? []) {
296
+ if (pr?.text) fields.push({ where: "trajectory.principles", text: pr.text });
297
+ }
298
+ return fields;
299
+ }
300
+
301
+ export function assessGroundedness(profile) {
302
+ const pool = collectSupportPool(profile);
303
+ const fields = classifyTextFields(profile);
304
+
305
+ let total = 0;
306
+ let supported = 0;
307
+ const anomalies = [];
308
+
309
+ for (const f of fields) {
310
+ const anchors = extractAnchors(f.text);
311
+ for (const a of anchors) {
312
+ total++;
313
+ let ok = false;
314
+ if (a.kind === "number") ok = numberMatches(a.value, pool.numbers);
315
+ else if (a.kind === "percent") ok = numberMatches(a.value, pool.ratios);
316
+ else if (a.kind === "period") ok = pool.periods.has(a.value);
317
+ else if (a.kind === "tech") ok = pool.tech.has(a.value);
318
+ else if (a.kind === "tag") ok = pool.tags.has(a.value);
319
+ else if (a.kind === "ai-tooling") ok = true; // pre-grounded by definition
320
+ if (ok) supported++;
321
+ else anomalies.push({ where: f.where, anchor: a.raw, kind: a.kind });
322
+ }
323
+ }
324
+
325
+ // Domains rollup: per-domain products/sessions are LLM claims. The sums must
326
+ // not exceed the deterministic totals — an excess is an invented count.
327
+ const domains = profile?.domains ?? [];
328
+ if (domains.length) {
329
+ const sumProducts = domains.reduce((n, d) => n + (Number(d.products) || 0), 0);
330
+ const sumSessions = domains.reduce((n, d) => n + (Number(d.sessions) || 0), 0);
331
+ total += 2;
332
+ if (sumProducts <= (profile?.volume?.products ?? 0)) supported++;
333
+ else anomalies.push({ where: "domains", anchor: `${sumProducts} products across domains`, kind: "number" });
334
+ if (sumSessions <= (profile?.volume?.sessions ?? 0)) supported++;
335
+ else anomalies.push({ where: "domains", anchor: `${sumSessions} sessions across domains`, kind: "number" });
336
+ }
337
+
338
+ // Soft floor: a profile with very few anchors should not be 0% just because
339
+ // there's nothing to check. If we found < 4 anchors total, score is "n/a".
340
+ const score = total >= 4 ? Math.round((supported / total) * 100) : null;
341
+ return {
342
+ score,
343
+ supported,
344
+ total,
345
+ anomalies: anomalies.slice(0, 12), // cap the surfaced ones
346
+ };
347
+ }