@sanity/ailf 4.0.6 → 4.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 (79) hide show
  1. package/bin/ailf.js +6 -1
  2. package/dist/_vendor/ailf-core/schemas/external-providers.d.ts +136 -0
  3. package/dist/_vendor/ailf-core/schemas/external-providers.js +136 -0
  4. package/dist/_vendor/ailf-core/schemas/index.d.ts +2 -0
  5. package/dist/_vendor/ailf-core/schemas/index.js +2 -0
  6. package/dist/_vendor/ailf-core/schemas/pipeline-request.d.ts +2 -3
  7. package/dist/_vendor/ailf-core/schemas/report.d.ts +251 -0
  8. package/dist/_vendor/ailf-core/schemas/report.js +235 -0
  9. package/dist/_vendor/ailf-core/services/index.d.ts +1 -0
  10. package/dist/_vendor/ailf-core/services/index.js +1 -0
  11. package/dist/_vendor/ailf-core/services/report-to-markdown.d.ts +38 -0
  12. package/dist/_vendor/ailf-core/services/report-to-markdown.js +696 -0
  13. package/dist/_vendor/ailf-core/types/api-requests.d.ts +159 -0
  14. package/dist/_vendor/ailf-core/types/api-requests.js +27 -0
  15. package/dist/_vendor/ailf-core/types/index.d.ts +3 -0
  16. package/dist/_vendor/ailf-core/types/pipeline-request.d.ts +112 -0
  17. package/dist/_vendor/ailf-core/types/pipeline-request.js +18 -0
  18. package/dist/_vendor/ailf-core/types/repo-config.d.ts +146 -0
  19. package/dist/_vendor/ailf-core/types/repo-config.js +18 -0
  20. package/dist/_vendor/ailf-shared/index.d.ts +7 -5
  21. package/dist/_vendor/ailf-shared/index.js +7 -5
  22. package/dist/adapters/api-client/types.d.ts +2 -5
  23. package/dist/adapters/task-sources/content-lake-task-source.d.ts +58 -1
  24. package/dist/adapters/task-sources/content-lake-task-source.js +1 -1
  25. package/dist/adapters/task-sources/index.d.ts +1 -1
  26. package/dist/adapters/task-sources/index.js +1 -1
  27. package/dist/adapters/task-sources/repo-schemas.d.ts +3 -2
  28. package/dist/adapters/task-sources/repo-schemas.js +3 -1
  29. package/dist/adapters/task-sources/repo-task-source.d.ts +11 -1
  30. package/dist/adapters/task-sources/repo-task-source.js +7 -4
  31. package/dist/adapters/task-sources/repo-validation.d.ts +6 -6
  32. package/dist/adapters/task-sources/repo-validation.js +1 -1
  33. package/dist/agent-observer/agentic-provider.d.ts +1 -0
  34. package/dist/agent-observer/agentic-provider.js +43 -36
  35. package/dist/agent-observer/config-schemas.d.ts +61 -0
  36. package/dist/agent-observer/config-schemas.js +65 -0
  37. package/dist/agent-observer/provider.d.ts +1 -0
  38. package/dist/agent-observer/provider.js +19 -17
  39. package/dist/cli.js +4 -4
  40. package/dist/commands/validate-tasks.js +2 -2
  41. package/dist/composition-root.d.ts +7 -0
  42. package/dist/composition-root.js +27 -12
  43. package/dist/index.d.ts +1 -1
  44. package/dist/index.js +1 -1
  45. package/dist/job-store.js +2 -2
  46. package/dist/lib/dotenv-resolution.d.ts +21 -0
  47. package/dist/lib/dotenv-resolution.js +30 -0
  48. package/dist/orchestration/steps/fetch-docs-step.js +10 -30
  49. package/dist/orchestration/steps/generate-configs-step.d.ts +8 -15
  50. package/dist/orchestration/steps/generate-configs-step.js +26 -118
  51. package/dist/orchestration/steps/mirror-repo-tasks-step.js +26 -3
  52. package/dist/orchestration/steps/run-eval-step.js +21 -3
  53. package/dist/pipeline/agent-behavior-report.d.ts +2 -8
  54. package/dist/pipeline/cache.d.ts +2 -2
  55. package/dist/pipeline/checks.d.ts +10 -2
  56. package/dist/pipeline/checks.js +14 -4
  57. package/dist/pipeline/compiler/literacy-bridge.js +2 -2
  58. package/dist/pipeline/compiler/mode-handlers/agent-harness/types.d.ts +2 -2
  59. package/dist/pipeline/compiler/mode-handlers/index.d.ts +1 -1
  60. package/dist/pipeline/compiler/mode-handlers/knowledge-probe/types.d.ts +2 -2
  61. package/dist/pipeline/compiler/mode-handlers/literacy/index.d.ts +1 -1
  62. package/dist/pipeline/compiler/mode-handlers/literacy/types.d.ts +3 -3
  63. package/dist/pipeline/compiler/promptfoo-compiler.js +7 -11
  64. package/dist/pipeline/compiler/provider-assembler.js +33 -3
  65. package/dist/pipeline/compiler/rubric-resolution.d.ts +2 -2
  66. package/dist/pipeline/mirror-repo-tasks.d.ts +13 -5
  67. package/dist/pipeline/mirror-repo-tasks.js +16 -8
  68. package/dist/pipeline/pr-comment.d.ts +22 -9
  69. package/dist/pipeline/pr-comment.js +52 -472
  70. package/dist/pipeline/resolve-mappings.d.ts +8 -3
  71. package/dist/promptfoo-providers/mock-path.d.ts +12 -0
  72. package/dist/promptfoo-providers/mock-path.js +15 -0
  73. package/dist/report-store.d.ts +63 -1
  74. package/dist/report-store.js +111 -31
  75. package/dist/sanity/client.d.ts +58 -0
  76. package/dist/sanity/client.js +106 -0
  77. package/package.json +8 -7
  78. package/dist/orchestration/load-pipeline-tasks.d.ts +0 -40
  79. package/dist/orchestration/load-pipeline-tasks.js +0 -57
@@ -1,459 +1,70 @@
1
1
  /**
2
- * pipeline/pr-comment.ts — Generates a markdown PR comment from eval score-summary.json.
2
+ * pipeline/pr-comment.ts — Generate a markdown PR comment from
3
+ * `results/latest/score-summary.json` (and an optional comparison-report).
3
4
  *
4
- * All functions accept rootDir as a parameter — no module-level constants.
5
- * No process.argv parsing. No env var fallbacks.
5
+ * Thin wrapper around `@sanity/ailf-core`'s unified renderer (W0150).
6
+ * Reads the local JSON files, applies legacy-field normalization on the
7
+ * scores, builds a `RenderableReport` envelope (so the CLI's
8
+ * `--promptfoo-url` flag flows through `provenance.promptfooUrls[0]`),
9
+ * then delegates rendering.
6
10
  *
7
- * Reads: results/latest/score-summary.json
8
- * Writes: markdown to stdout or --output file
11
+ * All functions accept `rootDir` as a parameter — no module-level
12
+ * constants. No `process.argv` parsing. No env-var fallbacks.
9
13
  */
10
14
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
11
15
  import { resolve } from "node:path";
12
- function formatCost(cost) {
13
- if (cost === 0) {
14
- return "$0.00";
15
- }
16
- if (cost < 0.01) {
17
- return `$${cost.toFixed(4)}`;
18
- }
19
- return `$${cost.toFixed(2)}`;
20
- }
21
- function generateComment(summary, options = {}) {
22
- const { belowCritical, overall, scores, source, timestamp } = summary;
23
- const sorted = [...scores].sort((a, b) => b.totalScore - a.totalScore);
24
- const lines = [];
25
- // Header
26
- lines.push(`## ${overallEmoji(overall.avgScore)} AI Literacy Score Report`);
27
- lines.push("");
28
- const totalCost = scores.reduce((sum, s) => sum + (s.totalCost ?? 0), 0);
29
- const graderCostValue = overall.cost?.graderTotal ?? 0;
30
- const combinedCostValue = totalCost + graderCostValue;
31
- const costStr = combinedCostValue > 0 ? ` · Cost: ${formatCost(combinedCostValue)}` : "";
32
- const actualStr = overall.avgActualScore !== undefined
33
- ? ` · Actual: ${Math.round(overall.avgActualScore)}/100`
34
- : "";
35
- const retGapStr = overall.avgRetrievalGap !== undefined
36
- ? ` · Ret. Gap: ${Math.round(overall.avgRetrievalGap)}`
37
- : "";
38
- lines.push(`**Overall: ${Math.round(overall.avgScore)}/100** · Doc Lift: +${Math.round(overall.avgDocLift)}${actualStr}${retGapStr} · ${scores.reduce((sum, s) => sum + s.testCount, 0)} tests across ${scores.length} areas${costStr}`);
39
- lines.push("");
40
- // Critical warnings
41
- if (belowCritical.length > 0) {
42
- lines.push(`> ⚠️ **Below critical threshold:** ${belowCritical.map((a) => `\`${a}\``).join(", ")}`);
43
- lines.push("");
44
- }
45
- // Environment info
46
- if (source) {
47
- lines.push("<details>");
48
- lines.push("<summary>🔧 Environment</summary>");
49
- lines.push("");
50
- lines.push("| Setting | Value |");
51
- lines.push("|---------|-------|");
52
- lines.push(`| **Source** | ${source.name} |`);
53
- lines.push(`| **Docs URL** | ${source.baseUrl} |`);
54
- if (source.dataset) {
55
- lines.push(`| **Dataset** | ${source.dataset} |`);
56
- }
57
- lines.push(`| **Project** | ${source.projectId} |`);
58
- lines.push("");
59
- lines.push("</details>");
60
- lines.push("");
61
- }
62
- // Source verification
63
- const { sourceIsolation, sourceVerification } = summary;
64
- if (sourceVerification || sourceIsolation) {
65
- lines.push("<details>");
66
- lines.push("<summary>🔍 Source verification</summary>");
67
- lines.push("");
68
- lines.push("| Setting | Value |");
69
- lines.push("|---------|-------|");
70
- if (sourceVerification) {
71
- lines.push(`| **Source** | ${sourceVerification.source} |`);
72
- lines.push(`| **Mode** | ${sourceVerification.mode} |`);
73
- if (sourceVerification.allowedOrigins) {
74
- lines.push(`| **Sandbox** | ${sourceVerification.allowedOrigins.join(", ")} |`);
75
- }
76
- if (sourceVerification.searchMode) {
77
- lines.push(`| **Search** | ${sourceVerification.searchMode} |`);
78
- }
79
- }
80
- if (sourceIsolation) {
81
- const pct = Math.round(sourceIsolation.isolationScore * 100);
82
- const icon = sourceIsolation.offOrigin === 0 ? "✅" : "⚠️";
83
- lines.push(`| **Agent isolation** | ${icon} ${pct}% (${sourceIsolation.onOrigin}/${sourceIsolation.total} on-origin) |`);
84
- if (sourceIsolation.offOrigin > 0) {
85
- lines.push(`| **Off-origin fetches** | ${sourceIsolation.offOriginUrls.slice(0, 5).join(", ")} |`);
86
- }
87
- }
88
- if (sourceVerification?.urlFetch) {
89
- const uf = sourceVerification.urlFetch;
90
- lines.push(`| **URL fetch** | ${uf.totalFetched} fetched, ${uf.totalFailed} failed |`);
91
- for (const f of uf.fetchedUrls) {
92
- lines.push(`| | ✅ ${f.url} (via ${f.method}) |`);
93
- }
94
- for (const f of uf.failures) {
95
- // oxlint-disable-next-line @typescript-eslint/prefer-nullish-coalescing -- empty error string should show "unknown"
96
- lines.push(`| | ⚠️ ${f.url}: ${f.error || "unknown"} |`);
97
- }
98
- }
99
- lines.push("");
100
- lines.push("</details>");
101
- lines.push("");
102
- }
103
- // Score table
104
- lines.push("### Scores by Feature Area");
105
- lines.push("");
106
- lines.push("| Feature | Score | Grade | Task | Code | Docs | Doc Lift | Tests |");
107
- lines.push("|---------|-------|-------|------|------|------|----------|-------|");
108
- for (const s of sorted) {
109
- lines.push(`| ${s.feature} | **${Math.round(s.totalScore)}** | ${gradeEmoji(s.totalScore)} ${gradeLetter(s.totalScore)} | ${Math.round(s.taskCompletion)} | ${Math.round(s.codeCorrectness)} | ${Math.round(s.docCoverage)} | ${liftArrow(s.docLift)} | ${s.testCount} |`);
110
- }
111
- lines.push("");
112
- // Breakdown legend
113
- lines.push("<details>");
114
- lines.push("<summary>📊 Score breakdown legend</summary>");
115
- lines.push("");
116
- lines.push("| Column | Description |");
117
- lines.push("|--------|-------------|");
118
- lines.push("| **Score** | Overall AI literacy score (0–100) — weighted sum of Task + Code + Docs |");
119
- lines.push("| **Task** | Task completion — does the LLM understand what to build? |");
120
- lines.push("| **Code** | Code correctness — does the generated code actually work? |");
121
- lines.push("| **Docs** | Documentation coverage — are the right APIs/patterns referenced? |");
122
- lines.push("| **Doc Lift** | Score improvement when docs are provided vs baseline (no docs) |");
123
- lines.push("| **Grade** | ✅ A (≥80) · 🟡 B (≥70) · 🟠 C (≥50) · 🔴 D (<50) |");
124
- lines.push("");
125
- lines.push("</details>");
126
- lines.push("");
127
- // Negative Doc Lift warning (always visible, not collapsible)
128
- const negDocLiftAreas = sorted.filter((s) => s.negativeDocLift);
129
- if (negDocLiftAreas.length > 0) {
130
- for (const s of negDocLiftAreas) {
131
- lines.push(`> 🚨 **Negative Doc Lift:** \`${s.feature}\` (${s.docLift}) — docs hurt performance. Floor: ${s.floorScore}, Ceiling: ${s.ceilingScore}`);
132
- }
133
- lines.push("");
134
- }
135
- // Three-layer decomposition (when actual scores are present)
136
- const hasActualScores = sorted.some((s) => s.actualScore !== undefined);
137
- if (hasActualScores) {
138
- // Full decomposition — show all three layers prominently
139
- lines.push("### 🔬 Three-Layer Decomposition");
140
- lines.push("");
141
- lines.push("| Feature | Floor | Ceiling | Actual | Doc Lift | Retr. Gap | Infra % |");
142
- lines.push("|---------|-------|---------|--------|----------|-----------|---------|");
143
- for (const s of sorted) {
144
- const actualStr = s.actualScore !== undefined ? String(s.actualScore) : "—";
145
- const gapStr = s.retrievalGap !== undefined
146
- ? s.retrievalGap >= 0
147
- ? `+${s.retrievalGap}`
148
- : String(s.retrievalGap)
149
- : "—";
150
- const infraStr = s.infrastructureEfficiency != null
151
- ? `${Math.round(s.infrastructureEfficiency * 100)}%`
152
- : "—";
153
- const flag = s.invertedRetrievalGap ? " 🔄" : "";
154
- lines.push(`| ${s.feature} | ${s.floorScore} | ${s.ceilingScore} | ${actualStr} | ${liftArrow(s.docLift)} | ${gapStr}${flag} | ${infraStr} |`);
155
- }
156
- lines.push("");
157
- // Decomposition guide
158
- lines.push("<details>");
159
- lines.push("<summary>📖 What do these numbers mean?</summary>");
160
- lines.push("");
161
- lines.push("- **Floor:** How well models do without any documentation (just training data)");
162
- lines.push("- **Ceiling:** How well models do with perfect documentation (hand-picked, injected)");
163
- lines.push("- **Actual:** How well models do when they have to find docs themselves (like real users)");
164
- lines.push("- **Doc Lift:** How much docs help (Ceiling − Floor). Negative = docs hurt");
165
- lines.push("- **Retr. Gap:** How much quality is lost in discovery (Ceiling − Actual)");
166
- lines.push("- **Infra %:** What fraction of doc quality reaches agents (Actual ÷ Ceiling)");
167
- if (sorted.some((s) => s.invertedRetrievalGap)) {
168
- lines.push("- **🔄:** Inverted retrieval gap — agents avoid bad docs, scoring higher than ceiling");
169
- }
170
- lines.push("");
171
- lines.push("</details>");
172
- lines.push("");
173
- }
174
- else {
175
- // Baseline-only — show the existing ceiling decomposition
176
- lines.push("<details>");
177
- lines.push("<summary>📊 Ceiling decomposition</summary>");
178
- lines.push("");
179
- lines.push("| Feature | Floor | Ceiling | Doc Lift | Quality Gap |");
180
- lines.push("|---------|-------|---------|----------|-------------|");
181
- for (const s of sorted) {
182
- lines.push(`| ${s.feature} | ${s.floorScore} | ${s.ceilingScore} | ${liftArrow(s.docLift)} | ${s.docQualityGap} |`);
183
- }
184
- lines.push("");
185
- lines.push("</details>");
186
- lines.push("");
187
- // With vs without docs comparison (uses ceiling/floor model)
188
- lines.push("<details>");
189
- lines.push("<summary>📄 With docs vs without docs</summary>");
190
- lines.push("");
191
- lines.push("| Feature | With Docs | Without Docs | Lift |");
192
- lines.push("|---------|-----------|--------------|------|");
193
- for (const s of sorted) {
194
- lines.push(`| ${s.feature} | ${s.ceilingScore} | ${s.floorScore} | ${liftArrow(s.docLift)} |`);
195
- }
196
- lines.push("");
197
- lines.push("</details>");
198
- lines.push("");
199
- }
200
- // Cost breakdown (only when cost data is available)
201
- if (totalCost > 0 || overall.cost) {
202
- const graderCost = overall.cost?.graderTotal ?? 0;
203
- const combinedCost = totalCost + graderCost;
204
- lines.push("<details>");
205
- lines.push("<summary>💰 Eval cost breakdown</summary>");
206
- lines.push("");
207
- lines.push("| Category | Cost |");
208
- lines.push("|----------|------|");
209
- lines.push(`| Provider (model inference) | ${formatCost(totalCost)} |`);
210
- if (graderCost > 0) {
211
- const graderLabel = overall.cost?.graderModel ?? "unknown";
212
- lines.push(`| Grader (${graderLabel}) | ${formatCost(graderCost)} |`);
213
- }
214
- lines.push(`| **Total** | **${formatCost(combinedCost)}** |`);
215
- lines.push("");
216
- // Per-feature provider cost breakdown
217
- lines.push("**Provider cost by feature area:**");
218
- lines.push("");
219
- lines.push("| Feature | Tests | Cost | Avg/Test |");
220
- lines.push("|---------|-------|------|----------|");
221
- for (const s of sorted) {
222
- const avgCost = s.testCount > 0 ? s.totalCost / s.testCount : 0;
223
- lines.push(`| ${s.feature} | ${s.testCount} | ${formatCost(s.totalCost)} | ${formatCost(avgCost)} |`);
224
- }
225
- lines.push("");
226
- lines.push("</details>");
227
- lines.push("");
228
- }
229
- // Per-model breakdown (when multiple models were evaluated)
230
- if (summary.perModel && summary.perModel.length > 1) {
231
- const sorted = [...summary.perModel].sort((a, b) => b.overall.avgScore - a.overall.avgScore);
232
- lines.push("<details>");
233
- lines.push("<summary>🤖 Per-model scores</summary>");
234
- lines.push("");
235
- lines.push("| Model | Score | Doc Lift | Tests | Cost |");
236
- lines.push("|-------|-------|----------|-------|------|");
237
- for (const entry of sorted) {
238
- const displayName = entry.label || entry.modelId;
239
- const costStr = entry.overall.cost ? formatCost(entry.overall.cost) : "—";
240
- const liftStr = entry.overall.avgDocLift >= 0
241
- ? `+${Math.round(entry.overall.avgDocLift)}`
242
- : String(Math.round(entry.overall.avgDocLift));
243
- lines.push(`| ${displayName} | **${Math.round(entry.overall.avgScore)}** | ${liftStr} | ${entry.overall.testCount} | ${costStr} |`);
244
- }
245
- lines.push("");
246
- // Per-model × per-area table
247
- for (const entry of sorted) {
248
- const displayName = entry.label || entry.modelId;
249
- lines.push(`**${displayName}** (${entry.modelId}):`);
250
- lines.push("");
251
- lines.push("| Feature | Score | Task | Code | Docs | Lift |");
252
- lines.push("|---------|-------|------|------|------|------|");
253
- for (const s of entry.scores) {
254
- const lift = s.docLift >= 0 ? `+${s.docLift}` : String(s.docLift);
255
- lines.push(`| ${s.feature} | **${s.totalScore}** | ${s.taskCompletion} | ${s.codeCorrectness} | ${s.docCoverage} | ${lift} |`);
256
- }
257
- lines.push("");
258
- }
259
- // Cost per quality point
260
- const withCost = sorted.filter((e) => e.overall.cost && e.overall.cost > 0);
261
- if (withCost.length > 0) {
262
- lines.push("**Cost efficiency:**");
263
- lines.push("");
264
- lines.push("| Model | $/point | Score | Cost |");
265
- lines.push("|-------|---------|-------|------|");
266
- for (const entry of withCost) {
267
- const costPerPoint = entry.overall.avgScore > 0
268
- ? (entry.overall.cost ?? 0) / entry.overall.avgScore
269
- : 0;
270
- lines.push(`| ${entry.label} | ${formatCost(costPerPoint)} | ${Math.round(entry.overall.avgScore)} | ${formatCost(entry.overall.cost ?? 0)} |`);
271
- }
272
- lines.push("");
273
- }
274
- lines.push("</details>");
275
- lines.push("");
276
- }
277
- // Comparison section (when --compare was used)
278
- if (options.comparisonReport) {
279
- const report = options.comparisonReport;
280
- const overallDelta = report.deltas.overall;
281
- const overallDeltaStr = overallDelta > 0
282
- ? `+${Math.round(overallDelta)}`
283
- : String(Math.round(overallDelta));
284
- const overallChangeIcon = overallDelta > report.noiseThreshold
285
- ? "📈"
286
- : overallDelta < -report.noiseThreshold
287
- ? "📉"
288
- : "➡️";
289
- lines.push("### 📊 Score Comparison");
290
- lines.push("");
291
- lines.push(`**Overall: ${Math.round(report.baseline.overall.avgScore)} → ${Math.round(report.experiment.overall.avgScore)}** (${overallChangeIcon} ${overallDeltaStr})`);
292
- lines.push("");
293
- // Check if comparison data includes actual/retrieval gap deltas
294
- const hasActualDeltas = report.areas.some((a) => a.actualDelta !== undefined);
295
- if (hasActualDeltas) {
296
- lines.push("| Feature | Baseline | Current | Delta | Actual Δ | Ret. Gap Δ | Infra Δ |");
297
- lines.push("|---------|----------|---------|-------|----------|------------|---------|");
298
- for (const a of report.areas.filter((a) => a.change !== "not-evaluated")) {
299
- const icon = a.change === "improved"
300
- ? "📈"
301
- : a.change === "regressed"
302
- ? "📉"
303
- : "➡️";
304
- const d = (n) => n > 0 ? `+${Math.round(n)}` : String(Math.round(n));
305
- const actualStr = a.actualDelta !== undefined ? d(a.actualDelta) : "—";
306
- const retGapStr = a.retrievalGapDelta !== undefined ? d(a.retrievalGapDelta) : "—";
307
- const infraStr = a.infrastructureEfficiencyDelta !== undefined
308
- ? `${a.infrastructureEfficiencyDelta > 0 ? "+" : ""}${Math.round(a.infrastructureEfficiencyDelta * 100)}pp`
309
- : "—";
310
- lines.push(`| ${a.area} | ${a.baseline} | ${a.experiment} | ${icon} ${d(a.delta)} | ${actualStr} | ${retGapStr} | ${infraStr} |`);
311
- }
312
- }
313
- else {
314
- lines.push("| Feature | Baseline | Current | Delta | Task | Code | Docs |");
315
- lines.push("|---------|----------|---------|-------|------|------|------|");
316
- for (const a of report.areas.filter((a) => a.change !== "not-evaluated")) {
317
- const icon = a.change === "improved"
318
- ? "📈"
319
- : a.change === "regressed"
320
- ? "📉"
321
- : "➡️";
322
- const d = (n) => n > 0 ? `+${Math.round(n)}` : String(Math.round(n));
323
- // TODO(multi-mode): These dimension keys are literacy-specific.
324
- // For other modes, iterate Object.entries(a.dimensions) dynamically.
325
- lines.push(`| ${a.area} | ${a.baseline} | ${a.experiment} | ${icon} ${d(a.delta)} | ${d(a.dimensions.taskCompletion.delta)} | ${d(a.dimensions.codeCorrectness.delta)} | ${d(a.dimensions.docCoverage.delta)} |`);
326
- }
327
- }
328
- lines.push("");
329
- const parts = [];
330
- if (report.improved.length > 0) {
331
- parts.push(`📈 ${report.improved.length} improved`);
332
- }
333
- if (report.regressed.length > 0) {
334
- parts.push(`📉 ${report.regressed.length} regressed`);
335
- }
336
- if (report.unchanged.length > 0) {
337
- parts.push(`➡️ ${report.unchanged.length} unchanged`);
338
- }
339
- if (report.notEvaluated?.length > 0) {
340
- parts.push(`⏭️ ${report.notEvaluated.length} not evaluated`);
341
- }
342
- if (parts.length > 0) {
343
- const isEmpirical = "noiseThresholdEmpirical" in report &&
344
- report.noiseThresholdEmpirical === true;
345
- const thresholdNote = isEmpirical
346
- ? ` (empirical threshold: ±${report.noiseThreshold.toFixed(1)})`
347
- : ` (threshold: ±${report.noiseThreshold})`;
348
- lines.push(parts.join(" · ") + thresholdNote);
349
- lines.push("");
16
+ import { reportToMarkdown } from "../_vendor/ailf-core/index.js";
17
+ export function generatePrComment(options) {
18
+ const { outputPath, promptfooUrl, rootDir } = options;
19
+ const summaryPath = resolve(rootDir, "results/latest/score-summary.json");
20
+ const comparisonPath = resolve(rootDir, "results/latest/comparison-report.json");
21
+ const raw = readFileSync(summaryPath, "utf-8");
22
+ const parsed = JSON.parse(raw);
23
+ const summary = {
24
+ ...parsed,
25
+ scores: parsed.scores.map((s) => normalizeScore(s)),
26
+ };
27
+ let comparison;
28
+ if (existsSync(comparisonPath)) {
29
+ try {
30
+ comparison = JSON.parse(readFileSync(comparisonPath, "utf-8"));
350
31
  }
351
- // Dimension averages in collapsible
352
- lines.push("<details>");
353
- lines.push("<summary>Dimension averages</summary>");
354
- lines.push("");
355
- const dim = report.deltas.perDimension;
356
- const dd = (n) => n > 0 ? `+${Math.round(n)}` : String(Math.round(n));
357
- lines.push("| Dimension | Delta |");
358
- lines.push("|-----------|-------|");
359
- lines.push(`| Task Completion | ${dd(dim.taskCompletion)} |`);
360
- lines.push(`| Code Correctness | ${dd(dim.codeCorrectness)} |`);
361
- lines.push(`| Doc Coverage | ${dd(dim.docCoverage)} |`);
362
- lines.push(`| Doc Lift | ${dd(report.deltas.docLift)} |`);
363
- lines.push("");
364
- lines.push("</details>");
365
- lines.push("");
366
- }
367
- // Recommendations
368
- if (belowCritical.length > 0 || sorted.some((s) => s.totalScore < 70)) {
369
- lines.push("### 💡 Recommendations");
370
- lines.push("");
371
- for (const s of sorted) {
372
- if (s.totalScore < 50) {
373
- lines.push(`- 🔴 **${s.feature}** (score: ${Math.round(s.totalScore)}) — needs significant doc improvements. `);
374
- if (s.codeCorrectness < 10) {
375
- lines.push(` Code correctness is very low (${Math.round(s.codeCorrectness)}) — add more complete code examples.`);
376
- }
377
- if (s.docCoverage < 10) {
378
- lines.push(` Doc coverage is very low (${Math.round(s.docCoverage)}) — key APIs/patterns may be missing from docs.`);
379
- }
380
- }
381
- else if (s.totalScore < 70) {
382
- lines.push(`- 🟠 **${s.feature}** (score: ${Math.round(s.totalScore)}) — has room for improvement.`);
383
- if (s.codeCorrectness < 15) {
384
- lines.push(` Code correctness (${Math.round(s.codeCorrectness)}) could improve with better code examples.`);
385
- }
386
- }
32
+ catch {
33
+ // Non-fatal — comparison report is optional.
387
34
  }
388
- lines.push("");
389
35
  }
390
- // Footer
391
- const date = new Date(timestamp).toLocaleString("en-US", {
392
- day: "numeric",
393
- hour: "numeric",
394
- minute: "2-digit",
395
- month: "short",
396
- timeZone: "UTC",
397
- timeZoneName: "short",
398
- year: "numeric",
36
+ const report = scoreSummaryToRenderableReport(summary, comparison, {
37
+ promptfooUrl,
399
38
  });
400
- lines.push("---");
401
- const runUrl = process.env.GITHUB_RUN_URL ?? "";
402
- const runLink = runUrl ? ` · <a href="${runUrl}">view run</a>` : "";
403
- const promptfooLink = options.promptfooUrl
404
- ? ` · <a href="${options.promptfooUrl}">view detailed results</a>`
405
- : "";
406
- lines.push(`<sub>🤖 Generated by AI Literacy Framework · ${date}${runLink}${promptfooLink} · <a href="https://github.com/sanity-labs/ai-literacy-framework">docs</a></sub>`);
407
- return lines.join("\n");
408
- }
409
- function gradeEmoji(score) {
410
- if (score >= 80) {
411
- return "✅";
412
- }
413
- if (score >= 70) {
414
- return "🟡";
415
- }
416
- if (score >= 50) {
417
- return "🟠";
418
- }
419
- return "🔴";
420
- }
421
- function gradeLetter(score) {
422
- if (score >= 80) {
423
- return "A";
424
- }
425
- if (score >= 70) {
426
- return "B";
427
- }
428
- if (score >= 50) {
429
- return "C";
430
- }
431
- return "D";
432
- }
433
- // ── Main ───────────────────────────────────────────────────────────────
434
- function liftArrow(lift) {
435
- const rounded = Math.round(lift);
436
- if (rounded > 0) {
437
- return `📈 +${rounded}`;
39
+ const markdown = reportToMarkdown(report);
40
+ if (outputPath) {
41
+ writeFileSync(outputPath, markdown);
438
42
  }
439
- if (rounded < 0) {
440
- return `📉 ${rounded}`;
43
+ else {
44
+ process.stdout.write(markdown);
441
45
  }
442
- return "➡️ 0";
443
46
  }
444
- function overallEmoji(avg) {
445
- if (avg >= 75) {
446
- return "🟢";
447
- }
448
- if (avg >= 60) {
449
- return "🟡";
450
- }
451
- if (avg >= 45) {
452
- return "🟠";
47
+ /**
48
+ * Adapter: build a {@link RenderableReport} from the in-memory pipeline
49
+ * artifacts. Exposed for the cross-renderer byte-equality contract test.
50
+ */
51
+ export function scoreSummaryToRenderableReport(summary, comparison, options = {}) {
52
+ const provenance = {};
53
+ if (options.promptfooUrl) {
54
+ provenance.promptfooUrls = [{ mode: "unknown", url: options.promptfooUrl }];
453
55
  }
454
- return "🔴";
56
+ return {
57
+ completedAt: summary.timestamp,
58
+ summary,
59
+ comparison,
60
+ provenance,
61
+ };
455
62
  }
456
- /** Normalize legacy field names in a score object */
63
+ // ---------------------------------------------------------------------------
64
+ // Legacy field normalization — pre-W0051 score summaries used different
65
+ // field names. Keep these here so old cached score-summary.json files
66
+ // still render correctly.
67
+ // ---------------------------------------------------------------------------
457
68
  function normalizeScore(s) {
458
69
  const ceiling = s.ceilingScore ??
459
70
  s.withDocsScore ??
@@ -474,34 +85,3 @@ function normalizeScore(s) {
474
85
  negativeDocLift: s.negativeDocLift ?? lift < 0,
475
86
  };
476
87
  }
477
- // ── Main ──────────────────────────────────────────────────────────────
478
- export function generatePrComment(options) {
479
- const { outputPath, promptfooUrl, rootDir } = options;
480
- const summaryPath = resolve(rootDir, "results/latest/score-summary.json");
481
- const comparisonPath = resolve(rootDir, "results/latest/comparison-report.json");
482
- const raw = readFileSync(summaryPath, "utf-8");
483
- const parsed = JSON.parse(raw);
484
- // Normalize legacy field names in scores
485
- const summary = {
486
- ...parsed,
487
- scores: parsed.scores.map((s) => normalizeScore(s)),
488
- };
489
- // Load comparison report if it exists (produced by --compare flag)
490
- let comparisonReport;
491
- if (existsSync(comparisonPath)) {
492
- try {
493
- const compRaw = readFileSync(comparisonPath, "utf-8");
494
- comparisonReport = JSON.parse(compRaw);
495
- }
496
- catch {
497
- // Non-fatal — comparison report is optional
498
- }
499
- }
500
- const comment = generateComment(summary, { comparisonReport, promptfooUrl });
501
- if (outputPath) {
502
- writeFileSync(outputPath, comment);
503
- }
504
- else {
505
- process.stdout.write(comment);
506
- }
507
- }
@@ -8,10 +8,15 @@
8
8
  * The output shape matches what downstream consumers expect so
9
9
  * fetch-docs, validate, and calculate-scores work without changes.
10
10
  */
11
- export interface CanonicalDoc {
12
- reason: string;
11
+ import type { CanonicalDoc as CoreCanonicalDoc } from "../_vendor/ailf-core/index.d.ts";
12
+ /**
13
+ * Slug-keyed variant of the canonical doc reference. Resolve-mappings only
14
+ * deals with `{ slug, reason }` pairs (path/id/perspective variants are
15
+ * filtered upstream); deriving via `Extract` keeps drift impossible.
16
+ */
17
+ export type CanonicalDoc = Extract<CoreCanonicalDoc, {
13
18
  slug: string;
14
- }
19
+ }>;
15
20
  export interface CanonicalTask {
16
21
  canonical_docs: CanonicalDoc[];
17
22
  description: string;
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Absolute filesystem path to the AILF mock Promptfoo provider
3
+ * (`mock-provider.cjs`, this directory's sibling).
4
+ *
5
+ * Promptfoo's `file://` provider loader requires an absolute path. Both
6
+ * the top-level promptfoo compiler (`promptfoo-compiler.ts:buildProviders`)
7
+ * and the literacy provider assembler (`provider-assembler.ts`) swap real
8
+ * provider IDs to `file://${MOCK_PROVIDER_ABSPATH}` when
9
+ * `AILF_REPLAY_LLMS=1` is set (W0110). This module is the single source
10
+ * of truth for that path so the two call sites can't drift apart.
11
+ */
12
+ export declare const MOCK_PROVIDER_ABSPATH: string;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Absolute filesystem path to the AILF mock Promptfoo provider
3
+ * (`mock-provider.cjs`, this directory's sibling).
4
+ *
5
+ * Promptfoo's `file://` provider loader requires an absolute path. Both
6
+ * the top-level promptfoo compiler (`promptfoo-compiler.ts:buildProviders`)
7
+ * and the literacy provider assembler (`provider-assembler.ts`) swap real
8
+ * provider IDs to `file://${MOCK_PROVIDER_ABSPATH}` when
9
+ * `AILF_REPLAY_LLMS=1` is set (W0110). This module is the single source
10
+ * of truth for that path so the two call sites can't drift apart.
11
+ */
12
+ import { dirname, resolve } from "node:path";
13
+ import { fileURLToPath } from "node:url";
14
+ const __dirname = dirname(fileURLToPath(import.meta.url));
15
+ export const MOCK_PROVIDER_ABSPATH = resolve(__dirname, "mock-provider.cjs");