literally-aeo 0.4.2 → 0.4.3

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 (122) hide show
  1. package/README.md +16 -0
  2. package/dist/cli.mjs +1503 -548
  3. package/dist/lib/agents/methodology.js +3 -3
  4. package/dist/lib/bundle/contracts.js +1 -1
  5. package/dist/lib/bundle/export.js +12 -12
  6. package/dist/lib/bundle/journal.js +2 -2
  7. package/dist/lib/bundle/project-journal.js +5 -5
  8. package/dist/lib/bundle/project.js +10 -10
  9. package/dist/lib/bundle/read.js +13 -13
  10. package/dist/lib/bundle/recorder.js +3 -3
  11. package/dist/lib/bundle/redact.js +2 -2
  12. package/dist/lib/bundle/trace-coverage.js +2 -2
  13. package/dist/lib/bundle/verify-integrity.js +4 -4
  14. package/dist/lib/bundle/verify-measurement.js +2 -2
  15. package/dist/lib/bundle/verify-report.js +3 -3
  16. package/dist/lib/bundle/verify.js +8 -8
  17. package/dist/lib/checks/run-checks.js +4 -4
  18. package/dist/lib/chunks/{chunk-22SP35NA.js → chunk-2ANSPIUT.js} +1 -1
  19. package/dist/lib/chunks/{chunk-ITLJZUKL.js → chunk-54GMIPWV.js} +1 -1
  20. package/dist/lib/chunks/{chunk-QJX6YXXQ.js → chunk-65OIYOUH.js} +2 -2
  21. package/dist/lib/chunks/{chunk-ENPRRXH5.js → chunk-6MGXILUJ.js} +1 -1
  22. package/dist/lib/chunks/chunk-6OURIXQZ.js +472 -0
  23. package/dist/lib/chunks/{chunk-AMK6IHJD.js → chunk-746643QV.js} +1 -1
  24. package/dist/lib/chunks/{chunk-AMF3T5A3.js → chunk-74K4E3ZS.js} +1 -1
  25. package/dist/lib/chunks/{chunk-5EM6J7TG.js → chunk-7HCVSLVG.js} +1 -1
  26. package/dist/lib/chunks/{chunk-RWVXK7XE.js → chunk-7K2XT3WI.js} +5 -5
  27. package/dist/lib/chunks/{chunk-VOK4TUXV.js → chunk-7L4Y6N3V.js} +1 -1
  28. package/dist/lib/chunks/{chunk-TD47AB37.js → chunk-7QWT7LFM.js} +2 -2
  29. package/dist/lib/chunks/{chunk-ATKP5ZW6.js → chunk-7SA2CRSS.js} +1 -1
  30. package/dist/lib/chunks/{chunk-Q6TZB2OQ.js → chunk-ARKZ5PJN.js} +1 -1
  31. package/dist/lib/chunks/{chunk-FBMO6UV4.js → chunk-B6XGNJUU.js} +1 -1
  32. package/dist/lib/chunks/{chunk-RR63UE5H.js → chunk-BNX7S4GK.js} +4 -4
  33. package/dist/lib/chunks/chunk-BWBPEXEU.js +83 -0
  34. package/dist/lib/chunks/{chunk-DKR7LSP2.js → chunk-BZAPAGXM.js} +1 -1
  35. package/dist/lib/chunks/{chunk-FFDMGNRO.js → chunk-C2Q7YE7Y.js} +6 -6
  36. package/dist/lib/chunks/{chunk-NWABYXDQ.js → chunk-D2LJMNH3.js} +2 -2
  37. package/dist/lib/chunks/{chunk-XT5M3PPQ.js → chunk-EVEJ3MFU.js} +3 -3
  38. package/dist/lib/chunks/{chunk-U4AROC2Z.js → chunk-GC7DISQO.js} +1 -1
  39. package/dist/lib/chunks/{chunk-YRXYTCMY.js → chunk-JHUI2K5X.js} +1 -1
  40. package/dist/lib/chunks/chunk-JQFLWUCA.js +123 -0
  41. package/dist/lib/chunks/{chunk-HJEIEMPE.js → chunk-JREYIUNG.js} +4 -4
  42. package/dist/lib/chunks/{chunk-FXCUGNFL.js → chunk-JXQOWHWB.js} +1 -1
  43. package/dist/lib/chunks/{chunk-BKAERR7J.js → chunk-KFJ5O5CL.js} +2 -2
  44. package/dist/lib/chunks/{chunk-6P7EZJI7.js → chunk-KSJ3NZIJ.js} +4 -2
  45. package/dist/lib/chunks/{chunk-EZ23TKTX.js → chunk-L5HFTFFG.js} +2 -2
  46. package/dist/lib/chunks/{chunk-DI4LZR37.js → chunk-LJD37WAV.js} +2 -2
  47. package/dist/lib/chunks/{chunk-YPGJN232.js → chunk-MKA2EP7M.js} +1 -1
  48. package/dist/lib/chunks/{chunk-JN4332MJ.js → chunk-MMJ5UR2E.js} +1 -1
  49. package/dist/lib/chunks/{chunk-A2RW4ZMR.js → chunk-MQFFMD4Q.js} +1 -1
  50. package/dist/lib/chunks/{chunk-CRXJFOCK.js → chunk-NM2LUMQT.js} +4 -4
  51. package/dist/lib/chunks/{chunk-RYV25YGT.js → chunk-P5VVHTZU.js} +1 -1
  52. package/dist/lib/chunks/{chunk-JKBXKACC.js → chunk-PFG3ESJE.js} +7 -7
  53. package/dist/lib/chunks/{chunk-OF3WIGG7.js → chunk-Q7CWM6LZ.js} +6 -6
  54. package/dist/lib/chunks/{chunk-DU3MAXVC.js → chunk-R5NLULQW.js} +1 -1
  55. package/dist/lib/chunks/{chunk-T5Q5CBTA.js → chunk-RM7U5M5L.js} +1 -1
  56. package/dist/lib/chunks/{chunk-JGBJQ3TO.js → chunk-RQ6GUJI5.js} +1 -1
  57. package/dist/lib/chunks/{chunk-CMB2KSW2.js → chunk-RUSMX6JH.js} +16 -7
  58. package/dist/lib/chunks/{chunk-KFYTORIT.js → chunk-UNNRLD2U.js} +4 -4
  59. package/dist/lib/chunks/chunk-VFN2J4Z3.js +626 -0
  60. package/dist/lib/chunks/{chunk-3DVFQMJT.js → chunk-VPJN2GNC.js} +1 -1
  61. package/dist/lib/chunks/{chunk-NZOKSFIA.js → chunk-XSOTCSD3.js} +3 -3
  62. package/dist/lib/chunks/{chunk-M4XGUJMO.js → chunk-YX4EH6FR.js} +1 -1
  63. package/dist/lib/chunks/{chunk-WIRVKAYB.js → chunk-ZC4MKS3J.js} +11 -11
  64. package/dist/lib/chunks/{chunk-KC35BXW7.js → chunk-ZM4RHMBI.js} +1 -1
  65. package/dist/lib/cli/bundle-commands.js +57 -32
  66. package/dist/lib/cli/guide-command.js +1 -1
  67. package/dist/lib/cli/run-commands.js +36 -36
  68. package/dist/lib/cli/status-command.js +18 -18
  69. package/dist/lib/codex-workflow/aggregate.js +2 -2
  70. package/dist/lib/codex-workflow/author.js +3 -3
  71. package/dist/lib/codex-workflow/capture.js +5 -5
  72. package/dist/lib/codex-workflow/copy-editor.js +3 -3
  73. package/dist/lib/codex-workflow/copy.js +2 -2
  74. package/dist/lib/codex-workflow/finish.js +5 -5
  75. package/dist/lib/codex-workflow/loop.js +13 -13
  76. package/dist/lib/codex-workflow/run-source.js +5 -5
  77. package/dist/lib/codex-workflow/stage.js +4 -4
  78. package/dist/lib/engine/audit-file.js +3 -3
  79. package/dist/lib/engine/author.js +10 -10
  80. package/dist/lib/engine/cost-estimate.js +3 -3
  81. package/dist/lib/engine/local-run.js +17 -17
  82. package/dist/lib/engine/preflight.js +3 -3
  83. package/dist/lib/engine/rejudge.js +24 -24
  84. package/dist/lib/engine/resources.js +1 -1
  85. package/dist/lib/engine/run-bindings.js +3 -3
  86. package/dist/lib/engine/run-method.js +2 -2
  87. package/dist/lib/engine/run-models.js +4 -4
  88. package/dist/lib/engine/run-status.js +18 -18
  89. package/dist/lib/engine/templates.js +4 -4
  90. package/dist/lib/grounding/grounding-runtime.js +5 -5
  91. package/dist/lib/grounding/recorded-tools.js +4 -4
  92. package/dist/lib/pipeline.js +4 -4
  93. package/dist/lib/probes/bindings.js +2 -2
  94. package/dist/lib/probes/charged-trace.js +3 -3
  95. package/dist/lib/probes/probes.js +3 -3
  96. package/dist/lib/viewer/alternatives.js +8 -0
  97. package/dist/lib/viewer/cited-domains.js +8 -0
  98. package/dist/lib/viewer/page.js +3 -1
  99. package/dist/lib/viewer/presentation.js +41 -0
  100. package/dist/lib/viewer/server.js +15 -10
  101. package/dist/types/bundle/contracts.d.ts +1 -1
  102. package/dist/types/engine/resources.d.ts +2 -0
  103. package/dist/types/viewer/alternatives.d.ts +16 -0
  104. package/dist/types/viewer/cited-domains.d.ts +22 -0
  105. package/dist/types/viewer/page.d.ts +9 -2
  106. package/dist/types/viewer/presentation.d.ts +112 -0
  107. package/dist/types/viewer/server.d.ts +7 -3
  108. package/package.json +2 -1
  109. package/resources/fonts/Mulish-OFL.txt +93 -0
  110. package/resources/fonts/Mulish-VariableFont_wght.ttf +0 -0
  111. package/resources/fonts/SourceCodePro-OFL.txt +93 -0
  112. package/resources/fonts/SourceCodePro-VariableFont_wght.ttf +0 -0
  113. package/src/bundle/contracts.ts +1 -1
  114. package/src/cli/bundle-commands.ts +21 -0
  115. package/src/engine/resources.ts +9 -5
  116. package/src/report/core/rate-interval.ts +1 -2
  117. package/src/viewer/alternatives.ts +202 -0
  118. package/src/viewer/cited-domains.ts +127 -0
  119. package/src/viewer/page.ts +549 -236
  120. package/src/viewer/presentation.ts +759 -0
  121. package/src/viewer/server.ts +25 -4
  122. package/dist/lib/chunks/chunk-3TF4JGQA.js +0 -323
@@ -0,0 +1,759 @@
1
+ import { z } from 'zod';
2
+ import { aeoFinalCopyDraftSchema } from '../agents/copy-schema';
3
+ import { bundlePaths } from '../bundle/contracts';
4
+ import { parseBundleJson } from '../bundle/json';
5
+ import { capturedRecordsSchema } from '../codex-workflow/run-inputs';
6
+ import { intervalPercents } from '../report/core/rate-interval';
7
+ import {
8
+ formatReportDate,
9
+ reportSectionTitle,
10
+ } from '../report/core/report-presentation';
11
+ import {
12
+ aeoPerceptionSchema,
13
+ aeoSnapshotSchema,
14
+ aeoSourceMixSchema,
15
+ brandSchema,
16
+ sourceCategories,
17
+ type AeoMatrixRow,
18
+ type AeoPerception,
19
+ type AeoRateEvidence,
20
+ type AeoSnapshot,
21
+ type AeoSourceMix,
22
+ type AeoVisibility,
23
+ type SourceMixCounts,
24
+ } from '../report/core/schema';
25
+ import {
26
+ isAgentSurface,
27
+ surfaceFamilyOf,
28
+ surfaceLabels,
29
+ } from '../report/core/surfaces';
30
+ import { rankAlternatives, type RankedAlternative } from './alternatives';
31
+ import { groupCitedDomains, type CitedDomain } from './cited-domains';
32
+
33
+ // ============================================================================
34
+ // What the local viewer shows, derived from a bundle's own documents: the
35
+ // hosted report's figures and tables (scorecards, the prompt by surface
36
+ // matrix, alternatives, cited domains), computed here in typed code so the
37
+ // page's script only renders them. Everything in a bundle is untrusted: each
38
+ // document is parsed with its contract, and every string reaches the page as
39
+ // data the page inserts as text.
40
+ // ============================================================================
41
+
42
+ // The parts of a snapshot the page shows, each read with its contract; the
43
+ // rest is not read. A bundle an earlier release exported may lack the brand
44
+ // or the counts: the brand then comes from the audit config, and the counts
45
+ // from the matrix.
46
+ const viewedSnapshotSchema = z.object({
47
+ brand: brandSchema.optional(),
48
+ sections: aeoSnapshotSchema.shape.sections,
49
+ sourceMix: aeoSourceMixSchema.optional(),
50
+ perception: aeoPerceptionSchema.optional(),
51
+ meta: aeoSnapshotSchema.shape.meta
52
+ .pick({
53
+ generatedAt: true,
54
+ promptCount: true,
55
+ probeCount: true,
56
+ partialFailures: true,
57
+ surfaceLabels: true,
58
+ methodology: true,
59
+ reusedProbes: true,
60
+ })
61
+ .partial({ promptCount: true, probeCount: true, partialFailures: true }),
62
+ });
63
+
64
+ const configBrandSchema = z.object({
65
+ brand: z.object({ name: z.string().min(1), domain: z.string().min(1) }),
66
+ });
67
+
68
+ type Brand = { name: string; domain: string };
69
+
70
+ export type IntervalView = {
71
+ text: string;
72
+ /** The interval named for a screen reader, which reaches it alone. */
73
+ label: string;
74
+ counts: string;
75
+ };
76
+
77
+ export type RateView = { percent: string; interval?: IntervalView };
78
+
79
+ export type ScorecardView = {
80
+ headline: string;
81
+ headlineInterval?: IntervalView;
82
+ label: string;
83
+ detail?: string;
84
+ detailInterval?: IntervalView;
85
+ };
86
+
87
+ export type RunView = {
88
+ runNumber: number;
89
+ surface: string;
90
+ cliVersion?: string;
91
+ status: 'primary' | 'mentioned' | 'absent' | 'no_overview';
92
+ retrieval?: 'searched' | 'memory' | 'unknown';
93
+ snippet?: string;
94
+ /** The captured answer, when the bundle holds it. */
95
+ answer?: string;
96
+ mentionedBrands: string[];
97
+ citedUrls: string[];
98
+ };
99
+
100
+ export type CellView = {
101
+ status: 'no_data' | 'absent' | 'primary' | 'mentioned';
102
+ mentioned: number;
103
+ runs: RunView[];
104
+ };
105
+
106
+ export type SectionView = {
107
+ key: string;
108
+ title: string;
109
+ scorecards: ScorecardView[];
110
+ surfaceRates: Array<{
111
+ surface: string;
112
+ shareOfVoice: RateView;
113
+ citationRate: RateView;
114
+ }>;
115
+ matrix: {
116
+ assistantSurfaces: string[];
117
+ agentSurfaces: string[];
118
+ rows: Array<{ prompt: string; category: string; cells: CellView[] }>;
119
+ };
120
+ alternatives: Array<{
121
+ name: string;
122
+ domain?: string;
123
+ share: number;
124
+ percent: string;
125
+ mentioning: number;
126
+ captured: number;
127
+ }>;
128
+ citedDomains: CitedDomain[];
129
+ sourceMix?: {
130
+ rows: Array<{ surface: string; counts: SourceMixCounts }>;
131
+ total: SourceMixCounts;
132
+ };
133
+ perception?: {
134
+ positive: number;
135
+ neutral: number;
136
+ negative: number;
137
+ phrases: Array<{ text: string; count: number; surfaces: string[] }>;
138
+ };
139
+ };
140
+
141
+ export type ReportPresentation =
142
+ | {
143
+ outcome: 'shown';
144
+ brand: { name: string; domain: string };
145
+ hero: {
146
+ title: string;
147
+ subtitle: string;
148
+ measuredOn: string;
149
+ probeCount: number;
150
+ facts: string[];
151
+ };
152
+ intro?: { heading: string; lead: string };
153
+ sections: SectionView[];
154
+ footer: { baseline: string; methodology: string[]; notes: string[] };
155
+ }
156
+ | { outcome: 'missing' }
157
+ | { outcome: 'unreadable'; reason: string };
158
+
159
+ /** presentReport derives the page's report from a bundle's files. */
160
+ export const presentReport = (
161
+ files: ReadonlyMap<string, Buffer>,
162
+ ): ReportPresentation => {
163
+ const snapshotFile = files.get(bundlePaths.snapshot);
164
+
165
+ if (snapshotFile === undefined) {
166
+ return { outcome: 'missing' };
167
+ }
168
+
169
+ const snapshot = parseDocument(snapshotFile, viewedSnapshotSchema);
170
+
171
+ if (snapshot === undefined) {
172
+ return {
173
+ outcome: 'unreadable',
174
+ reason: `${bundlePaths.snapshot} does not match the report contract of this release.`,
175
+ };
176
+ }
177
+
178
+ const brand =
179
+ snapshot.brand ??
180
+ parseDocument(files.get(bundlePaths.config), configBrandSchema)?.brand;
181
+
182
+ if (brand === undefined) {
183
+ return {
184
+ outcome: 'unreadable',
185
+ reason: `Neither ${bundlePaths.snapshot} nor ${bundlePaths.config} names the audited brand.`,
186
+ };
187
+ }
188
+
189
+ const copy = parseDocument(
190
+ files.get(bundlePaths.copy),
191
+ aeoFinalCopyDraftSchema,
192
+ );
193
+ const captured = parseDocument(
194
+ files.get(bundlePaths.captures),
195
+ capturedRecordsSchema,
196
+ );
197
+ const answers = new Map(
198
+ (captured ?? []).map((record) => [answerKey(record), record.probe.text]),
199
+ );
200
+ const { meta } = snapshot;
201
+ const measuredOn = measurementPeriod(meta);
202
+ const labelOf = surfaceLabelFor(meta.surfaceLabels ?? {});
203
+ const visibilities = snapshot.sections.map((s) => s.visibility);
204
+ const surfaces = [...new Set(visibilities.flatMap((v) => v.surfaces))];
205
+ // A snapshot from before the counts were recorded: every analysed answer
206
+ // is one matrix row, so the count never exceeds what was captured.
207
+ const promptCount =
208
+ meta.promptCount ??
209
+ visibilities.reduce((sum, v) => sum + v.prompts.length, 0);
210
+ const probeCount =
211
+ meta.probeCount ??
212
+ visibilities.reduce((sum, v) => sum + v.matrix.length, 0);
213
+ const presentation: ReportPresentation = {
214
+ outcome: 'shown',
215
+ brand: { name: brand.name, domain: brand.domain },
216
+ hero: {
217
+ title: copy?.hero.title.text ?? `How AI engines see ${brand.name}`,
218
+ subtitle:
219
+ copy?.hero.subtitle.text ??
220
+ defaultSubtitle(brand.name, surfaces, labelOf),
221
+ measuredOn,
222
+ probeCount,
223
+ facts: [
224
+ `${promptCount} buyer-style prompts`,
225
+ `${surfaces.length} AI surfaces${surfaces.some(isAgentSurface) ? ', coding agents included' : ''}`,
226
+ // Only when the bundle holds them: a redaction can withhold them all.
227
+ ...(answers.size > 0 ? ['Raw answers preserved and inspectable'] : []),
228
+ ],
229
+ },
230
+ ...(copy?.intro[0] !== undefined && {
231
+ intro: {
232
+ heading: `How AI engines see ${brand.name}`,
233
+ lead: copy.intro[0].text,
234
+ },
235
+ }),
236
+ sections: snapshot.sections.map((section) =>
237
+ presentSection(section, {
238
+ brand,
239
+ sourceMix: snapshot.sourceMix?.sections.find(
240
+ (s) => s.key === section.key,
241
+ ),
242
+ perception: snapshot.perception?.sections.find(
243
+ (s) => s.key === section.key,
244
+ ),
245
+ labelOf,
246
+ answers,
247
+ }),
248
+ ),
249
+ footer: {
250
+ baseline: `Measured ${measuredOn}: ${promptCount} prompts, ${probeCount} captured answers across ${listOf(surfaces.map(labelOf))}.`,
251
+ methodology: meta.methodology ?? [],
252
+ notes: [
253
+ ...reusedNote(meta.reusedProbes),
254
+ ...unanalyzedNote(meta.partialFailures ?? []),
255
+ ],
256
+ },
257
+ };
258
+
259
+ return presentation;
260
+ };
261
+
262
+ type SectionContext = {
263
+ brand: Brand;
264
+ sourceMix: AeoSourceMix['sections'][number] | undefined;
265
+ perception: AeoPerception['sections'][number] | undefined;
266
+ labelOf: (surface: string) => string;
267
+ answers: ReadonlyMap<string, string>;
268
+ };
269
+
270
+ const presentSection = (
271
+ { key, visibility }: AeoSnapshot['sections'][number],
272
+ { brand, sourceMix, perception, labelOf, answers }: SectionContext,
273
+ ): SectionView => {
274
+ const alternatives = rankAlternatives(visibility.matrix, brand);
275
+ const assistantSurfaces = visibility.surfaces.filter(
276
+ (s) => !isAgentSurface(s),
277
+ );
278
+ const agentSurfaces = visibility.surfaces.filter(isAgentSurface);
279
+ const runViewOf = (row: AeoMatrixRow, index: number): RunView => {
280
+ const answer =
281
+ row.runIndex === undefined
282
+ ? undefined
283
+ : answers.get(
284
+ answerKey({
285
+ sectionKey: key,
286
+ promptText: visibility.prompts[row.promptIdx]?.text ?? '',
287
+ surface: row.surface,
288
+ runIndex: row.runIndex,
289
+ }),
290
+ );
291
+
292
+ return presentRun(row, {
293
+ runNumber: row.runIndex ?? index + 1,
294
+ label: labelOf(row.surface),
295
+ answer,
296
+ });
297
+ };
298
+ const section: SectionView = {
299
+ key,
300
+ title: reportSectionTitle(key.replace(/_/g, ' ')),
301
+ scorecards: presentScorecards(visibility, alternatives[0], labelOf),
302
+ surfaceRates: visibility.surfaces.flatMap((surface) => {
303
+ const rates = visibility.summary.byModel[surface];
304
+ const name = labelOf(surface);
305
+
306
+ // A rate without its counts (calculation version 1) has no row, as
307
+ // on the hosted report.
308
+ return rates?.shareOfVoiceEvidence === undefined
309
+ ? []
310
+ : [
311
+ {
312
+ surface: name,
313
+ shareOfVoice: rateOf(
314
+ rates.shareOfVoice,
315
+ rates.shareOfVoiceEvidence,
316
+ { subject: `${name} share of voice`, counted: 'Mentioned' },
317
+ ),
318
+ citationRate: rateOf(
319
+ rates.citationRate,
320
+ rates.citationRateEvidence,
321
+ { subject: `${name} citation rate`, counted: 'Cited' },
322
+ ),
323
+ },
324
+ ];
325
+ }),
326
+ matrix: {
327
+ assistantSurfaces: assistantSurfaces.map(labelOf),
328
+ agentSurfaces: agentSurfaces.map(labelOf),
329
+ rows: visibility.prompts.map((prompt, promptIdx) => ({
330
+ prompt: prompt.text,
331
+ category: prompt.category.replace(/_/g, ' '),
332
+ cells: [...assistantSurfaces, ...agentSurfaces].map((surface) =>
333
+ presentCell(
334
+ visibility.matrix
335
+ .filter(
336
+ (row) => row.promptIdx === promptIdx && row.surface === surface,
337
+ )
338
+ .map(runViewOf),
339
+ ),
340
+ ),
341
+ })),
342
+ },
343
+ alternatives: alternatives.slice(0, 10).map((alternative) => {
344
+ const share = alternative.mentioning / alternative.captured;
345
+
346
+ return { ...alternative, share, percent: percentOf(share) };
347
+ }),
348
+ citedDomains: groupCitedDomains(visibility, brand.domain).map((domain) => ({
349
+ ...domain,
350
+ urls: domain.urls.map((url) => ({
351
+ ...url,
352
+ surfaces: url.surfaces.map(labelOf),
353
+ })),
354
+ })),
355
+ ...(sourceMix !== undefined && {
356
+ sourceMix: {
357
+ rows: sourceMix.perSurface
358
+ .filter(({ counts }) =>
359
+ sourceCategories.some((category) => counts[category] > 0),
360
+ )
361
+ .map(({ surface, counts }) => ({
362
+ surface: labelOf(surface),
363
+ counts,
364
+ })),
365
+ total: sourceMix.total,
366
+ },
367
+ }),
368
+ ...(perception !== undefined && {
369
+ perception: {
370
+ ...perception.sentiment,
371
+ phrases: groupPhrases(perception.narratives, labelOf),
372
+ },
373
+ }),
374
+ };
375
+
376
+ return section;
377
+ };
378
+
379
+ const presentScorecards = (
380
+ visibility: AeoVisibility,
381
+ topAlternative: RankedAlternative | undefined,
382
+ labelOf: (surface: string) => string,
383
+ ): ScorecardView[] => {
384
+ const { summary } = visibility;
385
+ const namesOf = (family: 'chat' | 'consumer' | 'agents') =>
386
+ listOf(
387
+ visibility.surfaces
388
+ .filter((s) => surfaceFamilyOf(s) === family)
389
+ .map(labelOf),
390
+ );
391
+ // A null rate is a scope the run did not measure: no tile, never a 0%.
392
+ const familyCard = (
393
+ family: 'chat' | 'consumer' | 'agents',
394
+ scope: string,
395
+ rates: {
396
+ shareOfVoice: number | null | undefined;
397
+ citationRate: number | null | undefined;
398
+ shareOfVoiceEvidence: AeoRateEvidence | undefined;
399
+ citationRateEvidence: AeoRateEvidence | undefined;
400
+ },
401
+ ): ScorecardView[] => {
402
+ if (rates.shareOfVoice === null || rates.shareOfVoice === undefined) {
403
+ return [];
404
+ }
405
+
406
+ const headline = rateOf(rates.shareOfVoice, rates.shareOfVoiceEvidence, {
407
+ subject: `share of voice across ${scope}`,
408
+ counted: 'Mentioned',
409
+ });
410
+ const detail = rateOf(rates.citationRate ?? 0, rates.citationRateEvidence, {
411
+ subject: `citation rate across ${scope}`,
412
+ counted: 'Cited',
413
+ });
414
+ const card = {
415
+ headline: headline.percent,
416
+ ...(headline.interval !== undefined && {
417
+ headlineInterval: headline.interval,
418
+ }),
419
+ label: `Share of voice — ${scope}`,
420
+ detail: `${detail.percent} citation rate across ${namesOf(family)}`,
421
+ ...(detail.interval !== undefined && { detailInterval: detail.interval }),
422
+ };
423
+
424
+ return [card];
425
+ };
426
+ // Measured prompt by surface cells in which no run named the brand.
427
+ const cellMentions = new Map<string, boolean>();
428
+
429
+ for (const row of visibility.matrix) {
430
+ const cell = `${row.promptIdx}:${row.surface}`;
431
+
432
+ cellMentions.set(
433
+ cell,
434
+ (cellMentions.get(cell) ?? false) || row.prospectMentioned,
435
+ );
436
+ }
437
+
438
+ const absentCells = [...cellMentions.values()].filter(
439
+ (mentioned) => !mentioned,
440
+ ).length;
441
+ const scorecards = [
442
+ ...familyCard('chat', 'AI assistants', {
443
+ shareOfVoice: summary.prospectShareOfVoice,
444
+ citationRate: summary.prospectCitationRate,
445
+ shareOfVoiceEvidence: summary.prospectShareOfVoiceEvidence,
446
+ citationRateEvidence: summary.prospectCitationRateEvidence,
447
+ }),
448
+ ...familyCard('consumer', 'consumer apps', {
449
+ shareOfVoice: summary.consumerShareOfVoice,
450
+ citationRate: summary.consumerCitationRate,
451
+ shareOfVoiceEvidence: summary.consumerShareOfVoiceEvidence,
452
+ citationRateEvidence: summary.consumerCitationRateEvidence,
453
+ }),
454
+ ...familyCard('agents', 'coding agents', {
455
+ shareOfVoice: summary.agentShareOfVoice,
456
+ citationRate: summary.agentCitationRate,
457
+ shareOfVoiceEvidence: summary.agentShareOfVoiceEvidence,
458
+ citationRateEvidence: summary.agentCitationRateEvidence,
459
+ }),
460
+ ...(topAlternative === undefined
461
+ ? []
462
+ : [
463
+ {
464
+ headline: percentOf(
465
+ topAlternative.mentioning / topAlternative.captured,
466
+ ),
467
+ label: `${topAlternative.name} share of voice`,
468
+ detail: `Named most often: ${topAlternative.mentioning} of ${topAlternative.captured} captured answers`,
469
+ },
470
+ ]),
471
+ {
472
+ headline: `${absentCells}/${cellMentions.size}`,
473
+ label: 'Cells with zero mentions',
474
+ detail: 'Prompts and surfaces where the brand was absent',
475
+ },
476
+ ];
477
+
478
+ return scorecards;
479
+ };
480
+
481
+ const presentRun = (
482
+ row: AeoMatrixRow,
483
+ {
484
+ runNumber,
485
+ label,
486
+ answer,
487
+ }: { runNumber: number; label: string; answer: string | undefined },
488
+ ): RunView => {
489
+ const mentionedBrands = [
490
+ ...new Set(
491
+ (row.mentionedBrands ?? []).map((brand) => brand.domain ?? brand.name),
492
+ ),
493
+ ];
494
+ const run: RunView = {
495
+ runNumber,
496
+ surface: label,
497
+ ...(row.agentCliVersion !== undefined && {
498
+ cliVersion: row.agentCliVersion,
499
+ }),
500
+ status: statusOf(row),
501
+ ...(row.usedWebSearch !== undefined && {
502
+ retrieval: retrievalOf(row.usedWebSearch),
503
+ }),
504
+ ...(row.contextSnippet !== null && { snippet: row.contextSnippet }),
505
+ ...(answer !== undefined && { answer }),
506
+ mentionedBrands,
507
+ citedUrls: row.citedUrls ?? [],
508
+ };
509
+
510
+ return run;
511
+ };
512
+
513
+ // Agent runs only. Null is a stream that could not be read: retrieval is
514
+ // unknown, never either measured state.
515
+ const retrievalOf = (
516
+ usedWebSearch: boolean | null,
517
+ ): NonNullable<RunView['retrieval']> => {
518
+ if (usedWebSearch === null) {
519
+ return 'unknown';
520
+ }
521
+
522
+ return usedWebSearch ? 'searched' : 'memory';
523
+ };
524
+
525
+ const statusOf = (row: AeoMatrixRow): RunView['status'] => {
526
+ // A results page without an AI Overview: no answer to be absent from.
527
+ if (row.noOverview) {
528
+ return 'no_overview';
529
+ }
530
+
531
+ if (!row.prospectMentioned) {
532
+ return 'absent';
533
+ }
534
+
535
+ return row.prospectPosition === 'primary' ? 'primary' : 'mentioned';
536
+ };
537
+
538
+ const presentCell = (runs: RunView[]): CellView => {
539
+ const mentioned = runs.filter(
540
+ (run) => run.status === 'primary' || run.status === 'mentioned',
541
+ ).length;
542
+
543
+ if (runs.length === 0) {
544
+ return { status: 'no_data', mentioned, runs };
545
+ }
546
+
547
+ if (mentioned === 0) {
548
+ return { status: 'absent', mentioned, runs };
549
+ }
550
+
551
+ const status = runs.some((run) => run.status === 'primary')
552
+ ? 'primary'
553
+ : 'mentioned';
554
+
555
+ return { status, mentioned, runs };
556
+ };
557
+
558
+ const rateOf = (
559
+ rate: number,
560
+ evidence: AeoRateEvidence | undefined,
561
+ {
562
+ subject,
563
+ counted,
564
+ }: {
565
+ /** The rate named for a screen reader. */
566
+ subject: string;
567
+ /** What the count counts: answers that mentioned, or that cited. */
568
+ counted: 'Mentioned' | 'Cited';
569
+ },
570
+ ): RateView => {
571
+ const percent = percentOf(rate);
572
+
573
+ // A bundle is shown even when it fails verification: bounds that are out
574
+ // of order are not an interval.
575
+ if (evidence === undefined || evidence.low > evidence.high) {
576
+ return { percent };
577
+ }
578
+
579
+ const { low, high } = intervalPercents(evidence);
580
+ const text = `approx. 95% interval ${low}–${high}%`;
581
+ const view = {
582
+ percent,
583
+ interval: {
584
+ text,
585
+ label: `${text} for ${subject}`,
586
+ counts: `${counted} in ${evidence.count} of ${evidence.planned} planned answers; ${evidence.captured} captured`,
587
+ },
588
+ };
589
+
590
+ return view;
591
+ };
592
+
593
+ const groupPhrases = (
594
+ narratives: ReadonlyArray<{ phrase: string; surface: string }>,
595
+ labelOf: (surface: string) => string,
596
+ ) => {
597
+ const byPhrase = new Map<
598
+ string,
599
+ { text: string; count: number; surfaces: string[] }
600
+ >();
601
+
602
+ for (const narrative of narratives) {
603
+ const text = narrative.phrase.trim();
604
+ const key = text.toLowerCase();
605
+
606
+ if (key === '') {
607
+ continue;
608
+ }
609
+
610
+ const entry = byPhrase.get(key) ?? { text, count: 0, surfaces: [] };
611
+ const surface = labelOf(narrative.surface);
612
+
613
+ entry.count += 1;
614
+ if (!entry.surfaces.includes(surface)) {
615
+ entry.surfaces.push(surface);
616
+ }
617
+ byPhrase.set(key, entry);
618
+ }
619
+
620
+ const phrases = [...byPhrase.values()]
621
+ .sort((a, b) => b.count - a.count)
622
+ .slice(0, 20);
623
+
624
+ return phrases;
625
+ };
626
+
627
+ /** The run's own label first (a custom surface, or one asked of another
628
+ * model); otherwise the engine's, without "(API)", as the hosted report
629
+ * names them. The methodology sentences say how each surface was asked. */
630
+ const surfaceLabelFor =
631
+ (runLabels: Readonly<Record<string, string>>) =>
632
+ (surface: string): string => {
633
+ return (
634
+ runLabels[surface] ??
635
+ surfaceLabels[surface]?.replace(/ \(API\)$/, '') ??
636
+ surface
637
+ );
638
+ };
639
+
640
+ const defaultSubtitle = (
641
+ brandName: string,
642
+ surfaces: readonly string[],
643
+ labelOf: (surface: string) => string,
644
+ ): string => {
645
+ const assistants = surfaces.filter((s) => !isAgentSurface(s)).map(labelOf);
646
+ const agents = surfaces.filter(isAgentSurface).map(labelOf);
647
+ const asked =
648
+ assistants.length > 0
649
+ ? `How often ${listOf(assistants)} mention and cite ${brandName}.`
650
+ : `How often AI answers mention and cite ${brandName}.`;
651
+ const subtitle =
652
+ agents.length > 0
653
+ ? `${asked} Plus ${agents.length === 1 ? 'one coding agent' : `${agents.length} coding agents`}: ${listOf(agents)}.`
654
+ : asked;
655
+
656
+ return subtitle;
657
+ };
658
+
659
+ type ReusedProbes = NonNullable<AeoSnapshot['meta']['reusedProbes']>;
660
+
661
+ // A run that reused earlier captures mixes their ages: the date the report
662
+ // was generated would, alone, overstate how fresh its answers are.
663
+ const measurementPeriod = ({
664
+ generatedAt,
665
+ reusedProbes,
666
+ }: {
667
+ generatedAt: string;
668
+ reusedProbes?: ReusedProbes;
669
+ }): string => {
670
+ const generated = formatReportDate(generatedAt);
671
+
672
+ if (reusedProbes === undefined) {
673
+ return generated;
674
+ }
675
+
676
+ return reusedProbes.oldestCapturedAt === null
677
+ ? `by ${generated}`
678
+ : `${formatReportDate(reusedProbes.oldestCapturedAt)} to ${generated}`;
679
+ };
680
+
681
+ const reusedNote = (reusedProbes: ReusedProbes | undefined): string[] => {
682
+ if (reusedProbes === undefined) {
683
+ return [];
684
+ }
685
+
686
+ const { count } = reusedProbes;
687
+
688
+ return [
689
+ `${count} answer${count === 1 ? ' was' : 's were'} reused from an earlier capture, not asked again by this run.`,
690
+ ];
691
+ };
692
+
693
+ // A prompt whose analysis failed is left out of the matrix and recorded as
694
+ // `analysis:search:<section>:<prompt>`.
695
+ const unanalyzedNote = (
696
+ partialFailures: ReadonlyArray<{ step: string }>,
697
+ ): string[] => {
698
+ const count = partialFailures.filter((f) =>
699
+ f.step.startsWith('analysis:search:'),
700
+ ).length;
701
+
702
+ if (count === 0) {
703
+ return [];
704
+ }
705
+
706
+ return [
707
+ `${count} prompt${count === 1 ? '' : 's'} could not be analyzed in this run and show${count === 1 ? 's' : ''} as no data.`,
708
+ ];
709
+ };
710
+
711
+ /** A captured answer's identity: its section, question, surface and run. */
712
+ const answerKey = ({
713
+ sectionKey,
714
+ promptText,
715
+ surface,
716
+ runIndex,
717
+ }: {
718
+ sectionKey: string;
719
+ promptText: string;
720
+ surface: string;
721
+ runIndex: number;
722
+ }): string => {
723
+ return JSON.stringify([sectionKey, promptText, surface, runIndex]);
724
+ };
725
+
726
+ const percentOf = (share: number): string => {
727
+ return `${(share * 100).toFixed(0)}%`;
728
+ };
729
+
730
+ const listOf = (names: readonly string[]): string => {
731
+ const unique = [...new Set(names)];
732
+
733
+ if (unique.length <= 1) {
734
+ return unique[0] ?? 'the measured surfaces';
735
+ }
736
+
737
+ return `${unique.slice(0, -1).join(', ')} and ${unique.at(-1) ?? ''}`;
738
+ };
739
+
740
+ /** A bundle document read with its contract; undefined when the document
741
+ * is absent (withheld included), is not JSON, repeats a key or does not
742
+ * match. */
743
+ const parseDocument = <Document>(
744
+ file: Buffer | undefined,
745
+ schema: z.ZodType<Document>,
746
+ ): Document | undefined => {
747
+ if (file === undefined) {
748
+ return undefined;
749
+ }
750
+
751
+ try {
752
+ const parsed = schema.safeParse(parseBundleJson(file.toString('utf8')));
753
+
754
+ return parsed.success ? parsed.data : undefined;
755
+ } catch {
756
+ // Text that is not JSON, or JSON with a duplicate key.
757
+ return undefined;
758
+ }
759
+ };