1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
|
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { execFile } from 'node:child_process';
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { promisify } from 'node:util';
import { fileURLToPath } from 'node:url';
import { buildFinalReportMessage, renderReport } from '../../../skills/vercel-optimize/lib/render-report.mjs';
const exec = promisify(execFile);
const HERE = dirname(fileURLToPath(import.meta.url));
const RENDER_SCRIPT = join(HERE, '..', '..', '..', 'skills', 'vercel-optimize', 'scripts', 'render-report.mjs');
const baseSignals = {
stack: { framework: 'next', frameworkVersion: '15.4.10', hasAppRouter: true, orm: 'none' },
plan: { plan: 'pro', reason: 'commitment category=Spend' },
observabilityPlus: true,
usage: {
period: { from: '2026-04-13', to: '2026-05-13' },
services: [
{ name: 'Function Duration', usage: '1.20M GB-hr', billedCost: 142.50 },
{ name: 'Edge Requests', usage: 5_400_000, unit: 'requests', billedCost: 28.40 },
],
totals: { billedCost: 170.90 },
},
metrics: {
fdtByCache: { rows: [
{ cache_result: 'HIT', value: 2_000_000_000 },
{ cache_result: 'MISS', value: 400_000_000 },
]},
fnStartTypeByRoute: { rows: [
{ route: '/x', total: 5000, coldCount: 50, warmCount: 4900, prewarmedCount: 50 },
]},
},
};
async function renderCli(recsRaw, extraArgs = [], gateRaw = { toLaunch: [], platform: [], gated: [] }, signalsRaw = baseSignals) {
const root = await mkdtemp(join(tmpdir(), 'vo-render-report-'));
try {
const recsPath = join(root, 'recs.json');
const gatePath = join(root, 'gate.json');
const signalsPath = join(root, 'signals.json');
await Promise.all([
writeFile(recsPath, JSON.stringify(recsRaw), 'utf-8'),
writeFile(gatePath, JSON.stringify(gateRaw), 'utf-8'),
writeFile(signalsPath, JSON.stringify(signalsRaw), 'utf-8'),
]);
return await exec('node', [RENDER_SCRIPT, recsPath, gatePath, signalsPath, '--project', 'x', '--no-timestamp', ...extraArgs]);
} finally {
await rm(root, { recursive: true, force: true });
}
}
const sampleRec = {
what: 'Parallelize three sequential fetch waves in /dashboard/[sessionId]',
why: 'src/app/(app)/dashboard/[sessionId]/page.tsx:28 awaits getDashboardSummary() in isolation; cpu.p95=117ms but latency.p95=1066ms.',
fix: '1. Start parallel fetches.\n2. Chain the plateau fan-out.\n3. Await all promises together.',
bucket: 'performance',
effort: 'low',
impactTier: 'high',
affectedFiles: ['src/app/(app)/dashboard/[sessionId]/page.tsx'],
currentBehavior: '```ts\nconst data = await getDashboardSummary();\n```',
desiredBehavior: '```ts\nconst dataPromise = getDashboardSummary();\n```',
verify: 'Watch p95 drop on /dashboard/[sessionId].',
candidateRef: 'slow_route:/dashboard/[sessionId]',
o11ySignal: 'inv=4923,p95=1067ms',
citations: [
'https://react.dev/reference/react/cache',
'vercel-react-best-practices:async-parallel',
],
impactLabel: { performance: 'Reduce /dashboard/[sessionId] p95 from 1066ms toward ~400-600ms' },
priority: 5253,
quality: { overall: 0.85, grade: 'Excellent' },
};
function assertNoPublicInternals(md) {
assert.doesNotMatch(md, /passRate|avgQuality|\bquality\b|sanitizer|\babstain(?:ed)?\b|\babstentions?\b|sub[- ]agent|debug/i);
}
test('renderReport: deterministic for same inputs (no timestamp)', () => {
const args = {
recommendations: [sampleRec],
gated: [],
signals: baseSignals,
opts: { projectName: 'fixture-app', generatedAt: null },
};
assert.equal(renderReport(args), renderReport(args));
});
test('renderReport: contains every required section per scoring.md template', () => {
const md = renderReport({
recommendations: [sampleRec],
gated: [],
signals: baseSignals,
opts: { projectName: 'fixture-app' },
});
for (const section of [
'# Vercel Optimization Report — fixture-app',
'## Cost breakdown',
'## Highest-impact recommendations',
'## Recommendations',
'### High impact',
'### Medium impact',
'## Detailed recommendations',
'## Platform recommendations',
'## Not investigated in this run',
'## Strengths',
'## Data gaps',
]) {
assert.ok(md.includes(section), `missing section: ${section}`);
}
});
test('renderReport: renders usage.services + totals when usage is present', () => {
const md = renderReport({
recommendations: [],
gated: [],
signals: baseSignals,
});
assert.match(md, /Function Duration.*\$142\.50/);
assert.match(md, /\*\*Total billed: \$170\.90\*\*/);
});
test('renderReport: falls back to o11y-derived ranking when usage missing', () => {
const signals = {
...baseSignals,
usage: null,
metrics: {
...baseSignals.metrics,
fnGbHrByRoute: { rows: [
{ route: '/x', value: 0.5 },
{ route: '/y', value: 0.2 },
]},
},
};
const md = renderReport({ recommendations: [], gated: [], signals });
assert.match(md, /Ranking by `function_duration_gbhr`/);
assert.match(md, /\| \/x \| 0\.5000 \|/);
});
test('renderReport: Observability Plus blocker does not invent billing or Speed Insights gaps', () => {
const signals = {
...baseSignals,
observabilityPlus: true,
observabilityPlusUsable: false,
observabilityPlusBlocker: 'payment_required',
observabilityPlusBlockerDetail: 'Route-level metrics were recognized for this team, but these queries are not usable.',
usage: null,
usageError: 'NOT_COLLECTED_OBSERVABILITY_BLOCKED',
metrics: {
observabilityPlusCanary: {
ok: false,
code: 'OPLUS_REQUIRED',
},
},
};
const md = renderReport({ recommendations: [], gated: [], signals });
assert.match(md, /Per-route metrics unavailable/);
assert.match(md, /Observability Plus metrics were not usable for this scope/);
assert.match(md, /`vercel usage` was not collected because the audit paused before billing collection/);
assert.doesNotMatch(md, /Observability Plus enabled — per-route metrics included/);
assert.doesNotMatch(md, /analysis based on billing/);
assert.doesNotMatch(md, /free-tier|Costs feature disabled/);
assert.doesNotMatch(md, /Observability Plus blocker:/);
assert.doesNotMatch(md, /cost breakdown derived from observability/);
assert.doesNotMatch(md, /No Speed Insights measurements|Core Web Vitals analysis dormant/);
assert.doesNotMatch(md, /No ISR activity observed/);
assert.doesNotMatch(md, /No image transformations observed/);
assert.doesNotMatch(md, /No middleware invocations/);
});
test('renderReport: unsupported-framework preflight does not claim Observability Plus was checked', () => {
const signals = {
...baseSignals,
observabilityPlus: null,
observabilityPlusUsable: null,
frameworkSupportBlocker: 'unsupported_framework',
usage: null,
usageError: 'NOT_COLLECTED_UNSUPPORTED_FRAMEWORK',
metrics: {},
};
const md = renderReport({ recommendations: [], gated: [], signals });
assert.match(md, /Not checked — audit paused at unsupported-framework preflight/);
assert.match(md, /`vercel usage` was not collected because the audit paused at the unsupported-framework preflight/);
assert.doesNotMatch(md, /Observability Plus enabled — per-route metrics included/);
assert.doesNotMatch(md, /Observability Plus not enabled/);
});
test('renderReport: limited audit after Observability blocker is not described as paused', () => {
const signals = {
...baseSignals,
observabilityPlus: false,
observabilityPlusUsable: false,
observabilityPlusBlocker: 'no_oplus_probe',
usage: null,
usageError: 'USAGE_UNAVAILABLE',
metrics: {},
};
const md = renderReport({ recommendations: [], gated: [], signals });
assert.match(md, /Per-route metrics unavailable — limited analysis based on scanner findings/);
assert.match(md, /Observability Plus was not detected for this scope/);
assert.match(md, /`vercel usage` returned `USAGE_UNAVAILABLE`; no billing breakdown was available/);
assert.doesNotMatch(md, /audit paused before metric-backed route ranking/);
assert.doesNotMatch(md, /Observability Plus blocker:/);
});
test('renderReport: usage unavailable copy is reserved for an actual usage error', () => {
const signals = {
...baseSignals,
usage: null,
usageError: 'USAGE_UNAVAILABLE',
metrics: {
...baseSignals.metrics,
fnGbHrByRoute: { rows: [] },
},
};
const md = renderReport({ recommendations: [], gated: [], signals });
assert.match(md, /`vercel usage` returned `USAGE_UNAVAILABLE`; no billing breakdown was available/);
assert.doesNotMatch(md, /free-tier|Costs feature disabled/);
});
test('renderReport: Speed Insights gap only renders after the metric is collected', () => {
const md = renderReport({
recommendations: [],
gated: [],
signals: {
...baseSignals,
metrics: {
...baseSignals.metrics,
cwvCount: { rows: [] },
},
},
});
assert.match(md, /No Speed Insights measurements/);
});
test('renderReport: failed Speed Insights query is not rendered as no measurements', () => {
const md = renderReport({
recommendations: [],
gated: [],
signals: {
...baseSignals,
metrics: {
...baseSignals.metrics,
cwvCount: { ok: false, code: 'FORBIDDEN', rows: [] },
},
},
});
assert.match(md, /Speed Insights metrics were not usable \(`FORBIDDEN`\)/);
assert.doesNotMatch(md, /No Speed Insights measurements/);
});
test('renderReport: canonicalizes o11y-derived cost routes', () => {
const signals = {
...baseSignals,
usage: null,
metrics: {
...baseSignals.metrics,
fnGbHrByRoute: { rows: [
{ route: '/docs/[[...slug]]/london.segments/_tree.segment', value: 0.25 },
{ route: '/docs/[[...slug]]', value: 0.25 },
]},
},
};
const md = renderReport({ recommendations: [], gated: [], signals });
assert.match(md, /\| \/docs\/\[\[\.\.\.slug\]\] \| 0\.5000 \|/);
});
test('renderReport: gated table groups the "Not investigated" rows', () => {
const md = renderReport({
recommendations: [],
gated: [
{ kind: 'uncached_route', route: '/api/orders', gatedReason: 'hitRate 0.65 above threshold' },
{ kind: 'slow_route', route: '/api/healthcheck', gatedReason: 'only 50 invocations' },
],
signals: baseSignals,
});
assert.match(md, /\| Low cache-hit route \| hitRate 0\.65 above threshold \| \/api\/orders \| 1 \|/);
assert.match(md, /\| Slow route \| only 50 invocations \| \/api\/healthcheck \| 1 \|/);
});
test('renderReport: recommendations use displayRoute from candidate metadata', () => {
const md = renderReport({
recommendations: [{
...sampleRec,
candidateRef: 'isr_overrevalidation:/event/[*]/london',
what: 'Add cacheLife to the event homepage.',
o11ySignal: null,
}],
candidates: [{
kind: 'isr_overrevalidation',
route: '/event/[*]/london',
displayRoute: '/event/[code]/[location]',
o11ySignal: 'writes=100,reads=20,w/r=5',
}],
gated: [],
signals: baseSignals,
});
assert.match(md, /ISR over-revalidation on \/event\/\[code\]\/\[location\]/);
assert.doesNotMatch(md, /ISR over-revalidation on \/event\/\[\*\]\/london/);
});
test('renderReport: gated table caps noisy target lists while preserving counts', () => {
const md = renderReport({
recommendations: [],
gated: Array.from({ length: 8 }, (_, i) => ({
kind: 'route_errors',
route: `/docs/page-${i}`,
gatedReason: 'coveredBy (route_errors::/docs) — duplicate of higher-priority sibling',
})),
signals: baseSignals,
});
assert.match(md, /\| Route errors \| covered by a higher-priority candidate .* \| \/docs\/page-0<br>\/docs\/page-1<br>\/docs\/page-2<br>\/docs\/page-3<br>\/docs\/page-4<br>\+3 more \| 8 \|/);
assert.doesNotMatch(md, /\/docs\/page-7<br>/);
});
test('renderReport: public gated reasons avoid raw budget internals', () => {
const md = renderReport({
recommendations: [],
gated: [
{
kind: 'slow_route',
route: '/docs',
gatedReason: 'skippedByBudget (max-candidates=6; raise with --max-candidates N or =all)',
},
],
signals: baseSignals,
});
assert.match(md, /left for a larger run \(max candidates: 6\)/);
assert.doesNotMatch(md, /skippedByBudget/);
assert.doesNotMatch(md, /=all/);
});
test('renderReport: public gated reasons avoid hard-gate internals', () => {
const md = renderReport({
recommendations: [],
gated: [
{
kind: 'slow_route',
route: '/.well-known/workflow/v1/step',
gatedReason: 'hardGated: Vercel Workflow runtime endpoint; long-running step/flow requests are expected orchestration, not an app-route optimization target',
},
],
signals: baseSignals,
});
assert.match(md, /Vercel Workflow runtime endpoint; long-running step\/flow requests are expected orchestration/);
assert.doesNotMatch(md, /hardGated/);
});
test('renderReport: partitions recs by impactTier into High / Medium / Low', () => {
const md = renderReport({
recommendations: [
{ ...sampleRec, what: 'high one', impactTier: 'high', candidateRef: 'a:1' },
{ ...sampleRec, what: 'medium one', impactTier: 'medium', candidateRef: 'b:1' },
{ ...sampleRec, what: 'low one', impactTier: 'low', candidateRef: 'c:1' },
],
gated: [],
signals: baseSignals,
});
const high = md.split('### Medium impact')[0];
const med = md.split('### Medium impact')[1].split('### Low impact')[0];
assert.ok(high.includes('high one'));
assert.ok(med.includes('medium one'));
});
test('renderReport: omits quick wins table to avoid duplicate recommendation surfaces', () => {
const md = renderReport({
recommendations: [
{ ...sampleRec, what: 'high repeated elsewhere', impactTier: 'high', effort: 'low', priority: 100 },
{ ...sampleRec, what: 'medium quick win', impactTier: 'medium', effort: 'low', priority: 90, candidateRef: 'slow_route:/medium' },
],
gated: [],
signals: baseSignals,
});
assert.doesNotMatch(md, /### Quick wins/);
});
test('renderReport: caps platform-scope recs at 3', () => {
const recs = Array.from({ length: 5 }, (_, i) => ({
...sampleRec,
what: `platform rec ${i}`,
candidateRef: `platform_fluid_compute:account-${i}`,
scope: 'account',
}));
const md = renderReport({ recommendations: recs, gated: [], signals: baseSignals });
const platSection = md.split('## Platform recommendations')[1].split('## Not investigated in this run')[0];
const count = (platSection.match(/platform rec \d/g) ?? []).length;
assert.equal(count, 3, `expected platform cap of 3, saw ${count}`);
});
test('renderReport: includes the abstention-friendly "no recs" fallback', () => {
const md = renderReport({ recommendations: [], gated: [], signals: baseSignals });
assert.match(md, /No recommendations are ready to apply from this run/);
});
test('renderReport: handles missing observabilityPlus gracefully', () => {
const md = renderReport({
recommendations: [],
gated: [],
signals: { ...baseSignals, observabilityPlus: false },
});
assert.match(md, /Not enabled — analysis based on billing \+ scanner findings/);
assert.match(md, /Observability Plus not enabled/);
});
test('renderReport: hides sanitizerTrail by default and does not emit generic review notes', () => {
const rec = {
...sampleRec,
needsReview: true,
sanitizerTrail: ['$-strip:2', 'unknown-citation:https://made-up.example.com'],
};
const md = renderReport({
recommendations: [rec],
gated: [],
signals: baseSignals,
});
assert.doesNotMatch(md, /Review before applying: automated checks flagged this recommendation/);
assertNoPublicInternals(md);
assert.doesNotMatch(md, /\$-strip:2/);
});
test('renderReport: public markdown hides internal reporting fields and labels', () => {
const rec = {
...sampleRec,
passRate: 0.67,
avgQuality: 0.72,
needsReview: true,
sanitizerTrail: ['$-strip:2'],
};
const md = renderReport({
recommendations: [rec],
gated: [],
abstentions: [{
candidateRef: 'slow_route:/internal',
reason: 'sub-agent was abstaining after quality + verification; sanitizer changed the draft',
}],
signals: baseSignals,
});
assertNoPublicInternals(md);
assert.match(md, /Why no recommendation shipped/);
assert.match(md, /investigation was not recommending a change after verification; checks changed the draft/);
});
test('renderReport: rewrites bare abstain in no-change reasons', () => {
const md = renderReport({
recommendations: [],
gated: [],
abstentions: [{
candidateRef: 'slow_route:/docs',
reason: 'Evidence and source diverge — abstain.',
}],
signals: baseSignals,
});
assertNoPublicInternals(md);
assert.match(md, /Evidence and source diverge — found no supported change\./);
});
test('renderReport: highest-impact recommendations use readable metric labels', () => {
const md = renderReport({
recommendations: [sampleRec],
gated: [],
signals: baseSignals,
});
const top = md.split('## Highest-impact recommendations')[1].split('## Recommendations')[0];
assert.match(top, /Slow route on \/dashboard\/\[sessionId\]/);
assert.match(top, /function invocations: 4,923/);
assert.match(top, /95th percentile duration: 1067ms/);
assert.doesNotMatch(top, /(?:^|[,\s])inv=/);
assert.doesNotMatch(top, /(?:^|[,\s])p95=/);
});
test('renderReport: softens overconfident recommendation wording in public surfaces', () => {
const rec = {
...sampleRec,
what: 'Stop blocking metadata so the response head ships immediately.',
};
const md = renderReport({
recommendations: [rec],
gated: [],
signals: baseSignals,
});
assert.ok(!md.includes('ships immediately'));
assert.match(md, /response head can ship sooner/);
});
test('renderReport: never writes internal review details into public markdown', () => {
const rec = {
...sampleRec,
passRate: 0.8,
avgQuality: 0.73,
needsReview: true,
sanitizerTrail: ['$-strip:2', 'unknown-citation:https://made-up.example.com'],
};
const md = renderReport({
recommendations: [rec],
gated: [],
signals: baseSignals,
opts: { debug: true },
});
assertNoPublicInternals(md);
assert.doesNotMatch(md, /Internal debug details/);
assert.doesNotMatch(md, /passRate: 0\.8/);
});
test('render-report CLI: --debug-out writes internal details outside customer markdown', async () => {
const root = await mkdtemp(join(tmpdir(), 'vo-render-report-debug-'));
try {
const debugPath = join(root, 'debug.json');
const { stdout } = await renderCli({
schemaVersion: '1.0',
summary: { totalRecs: 1, observations: 0 },
recsGraded: [{
...sampleRec,
passRate: 0.8,
avgQuality: 0.73,
sanitizerTrail: ['$-strip:2'],
}],
abstentions: [],
observations: [],
}, ['--debug-out', debugPath]);
assertNoPublicInternals(stdout);
const debug = JSON.parse(await readFile(debugPath, 'utf-8'));
assert.equal(debug.summary.rawRecommendationCount, 1);
assert.equal(debug.summary.renderedRecommendationCount, 1);
assert.equal(debug.recommendations[0].candidateRef, sampleRec.candidateRef);
assert.equal(debug.recommendations[0].quality.overall, 0.85);
assert.equal(debug.recommendations[0].passRate, 0.8);
assert.deepEqual(debug.recommendations[0].sanitizerTrail, ['$-strip:2']);
} finally {
await rm(root, { recursive: true, force: true });
}
});
test('buildFinalReportMessage: extracts concise public message from rendered markdown', () => {
const md = renderReport({
recommendations: [sampleRec],
gated: [],
candidates: [{ kind: 'slow_route', route: '/dashboard/[sessionId]' }],
signals: baseSignals,
opts: { projectName: 'x', generatedAt: null },
});
const message = buildFinalReportMessage({
reportPath: '/tmp/report.md',
markdown: md,
recommendations: [sampleRec],
signals: baseSignals,
});
assert.match(message.body, /^Report saved: \/tmp\/report\.md/);
assert.match(message.body, /\*\*Coverage\*\*: Found \*\*1\*\* potential issue to check/);
assert.match(message.body, /Ready recommendations:/);
assert.match(message.body, /1\. Parallelize three sequential fetch waves in \/dashboard\/\[sessionId\]/);
assert.match(message.body, /Impact: Reduce \/dashboard\/\[sessionId\] 95th percentile from 1066ms toward ~400-600ms/);
assert.doesNotMatch(message.body, /details|passRate|\bquality\b|sanitizer|sub[- ]agent|abstention|debug/i);
assert.equal(message.lineCount, message.body.split('\n').length);
assert.equal(message.reportPath, '/tmp/report.md');
assert.equal(message.recommendationsShown, 1);
});
test('buildFinalReportMessage: does not invent counts without a Coverage line', () => {
const message = buildFinalReportMessage({ reportPath: '/tmp/report.md', markdown: '# Report\n\nNo coverage.' });
assert.equal(message.body, 'Report saved: /tmp/report.md\n\nOpen the report for details. No coverage summary was available.');
assert.equal(message.coverageLine, null);
});
test('render-report CLI: --message-out writes concise final message separate from debug', async () => {
const root = await mkdtemp(join(tmpdir(), 'vo-render-report-message-'));
try {
const recsPath = join(root, 'recs.json');
const gatePath = join(root, 'gate.json');
const signalsPath = join(root, 'signals.json');
const reportPath = join(root, 'report.md');
const messagePath = join(root, 'message.json');
const debugPath = join(root, 'debug.json');
await Promise.all([
writeFile(recsPath, JSON.stringify({
schemaVersion: '1.0',
summary: { totalRecs: 1, observations: 0 },
recsGraded: [{ ...sampleRec, passRate: 0.8, sanitizerTrail: ['$-strip:2'] }],
abstentions: [],
observations: [],
}), 'utf-8'),
writeFile(gatePath, JSON.stringify({ toLaunch: [{ kind: 'slow_route', route: '/dashboard/[sessionId]' }], platform: [], gated: [] }), 'utf-8'),
writeFile(signalsPath, JSON.stringify(baseSignals), 'utf-8'),
]);
await exec('node', [
RENDER_SCRIPT,
recsPath,
gatePath,
signalsPath,
'--project',
'x',
'--no-timestamp',
'--out',
reportPath,
'--message-out',
messagePath,
'--debug-out',
debugPath,
]);
const [report, message, debug] = await Promise.all([
readFile(reportPath, 'utf-8'),
readFile(messagePath, 'utf-8').then(JSON.parse),
readFile(debugPath, 'utf-8').then(JSON.parse),
]);
assertNoPublicInternals(report);
assertNoPublicInternals(message.body);
assert.match(message.body, /^Report saved:/);
assert.match(message.body, /\*\*Coverage\*\*:/);
assert.match(message.body, /Ready recommendations:/);
assert.match(message.body, /Parallelize three sequential fetch waves/);
assert.doesNotMatch(message.body, /Developer diagnostics|debug\.json|passRate|\bquality\b|sanitizer/i);
assert.equal(message.recommendationsShown, 1);
assert.equal(debug.recommendations[0].passRate, 0.8);
assert.deepEqual(debug.recommendations[0].sanitizerTrail, ['$-strip:2']);
} finally {
await rm(root, { recursive: true, force: true });
}
});
test('render-report CLI: legacy --debug does not leak into markdown', async () => {
const { stdout } = await renderCli({
schemaVersion: '1.0',
summary: { totalRecs: 1, observations: 0 },
recsGraded: [{
...sampleRec,
passRate: 0.8,
avgQuality: 0.73,
sanitizerTrail: ['$-strip:2'],
}],
abstentions: [],
observations: [],
}, ['--debug']);
assertNoPublicInternals(stdout);
});
test('renderReport: does NOT include $N literals when impactLabel is magnitude', () => {
const rec = {
...sampleRec,
impactLabel: { costPhrase: 'hundreds of dollars per month at current traffic' },
};
const md = renderReport({ recommendations: [rec], gated: [], signals: baseSignals });
assert.match(md, /hundreds of dollars per month/);
});
test('renderReport: renders "Investigated, no change recommended" section when no-change findings are present', () => {
const md = renderReport({
recommendations: [],
gated: [],
abstentions: [
{ candidateRef: 'uncached_route:/dashboard/[sessionId]', reason: 'POST-heavy route, no cache opportunity' },
{ candidateRef: 'slow_route:/api/x', reason: 'wall-clock dominated by an external API not in scope' },
],
signals: baseSignals,
});
assert.match(md, /## Investigated, no change recommended/);
assert.match(md, /Why no recommendation shipped/);
assert.match(md, /Low cache-hit route on \/dashboard\/\[sessionId\]/);
assert.match(md, /POST-heavy route, no cache opportunity/);
assert.match(md, /Slow route on \/api\/x/);
});
test('renderReport: separates held-back findings from no-change findings', () => {
const md = renderReport({
recommendations: [],
gated: [],
abstentions: [
{ candidateRef: 'slow_route:/docs', reason: 'Needs stronger framework evidence before applying.', needsEvidence: true },
{ candidateRef: 'uncached_route:/api/search', reason: 'POST-heavy route, no cache opportunity' },
],
signals: baseSignals,
});
assert.match(md, /## Needs more evidence/);
assert.match(md, /Why it was held back/);
assert.match(md, /Slow route on \/docs/);
assert.match(md, /## Investigated, no change recommended/);
assert.match(md, /Low cache-hit route on \/api\/search/);
assert.ok(md.indexOf('Slow route on /docs') < md.indexOf('## Investigated, no change recommended'));
});
test('renderReport: NO "Investigated, no change recommended" section when no no-change findings exist', () => {
const md = renderReport({
recommendations: [],
gated: [],
abstentions: [],
signals: baseSignals,
});
assert.ok(!md.includes('## Investigated, no change recommended'));
});
test('renderReport: pipe-escapes user content inside table cells', () => {
const rec = { ...sampleRec, what: 'before | after' };
const md = renderReport({ recommendations: [rec], gated: [], signals: baseSignals });
const tableRow = md.split('\n').find((l) => l.startsWith('|') && l.includes('before'));
assert.ok(tableRow, 'rec row should appear in a table');
// Literal `|` must be escaped to `\|` so it doesn't break the column separator.
assert.ok(
tableRow.includes('before \\| after'),
`expected escaped pipe in row, got: ${tableRow}`,
);
});
test('renderReport: drops Usage column when every row has no real unit (CLI USD-collapse)', () => {
// fixture-site: `vercel usage` returned pricingUnit=USD with
// pricingQuantity==billedCost on every row. Detect + drop Usage column.
const collapsed = {
...baseSignals,
usage: {
...baseSignals.usage,
services: [
{ name: 'Sandbox Provisioned Memory', billedCost: 518185.55 },
{ name: 'AI Gateway', billedCost: 207934.42 },
],
totals: { billedCost: 726119.97 },
},
};
const md = renderReport({ recommendations: [], gated: [], signals: collapsed, opts: { projectName: 'x' } });
assert.ok(md.includes('| Service | Billed cost |'), 'collapsed table should be Service+Cost only');
assert.ok(!md.includes('(unspecified)'), 'no "(unspecified)" rows should leak through');
});
test('renderReport: keeps Usage column when at least one row has a real unit', () => {
const md = renderReport({ recommendations: [], gated: [], signals: baseSignals, opts: { projectName: 'x' } });
assert.ok(md.includes('| Service | Usage | Billed cost |'));
});
test('renderReport: omits zero-cost usage service rows', () => {
const md = renderReport({
recommendations: [],
gated: [],
signals: {
...baseSignals,
usage: {
...baseSignals.usage,
services: [
{ name: 'Function Duration', usage: '1.20M GB-hr', billedCost: 142.50 },
{ name: 'Edge Requests', billedCost: 0 },
{ name: 'Image Optimization Cache Reads', billedCost: 0 },
],
totals: { billedCost: 142.50 },
},
},
opts: { projectName: 'x' },
});
assert.ok(md.includes('| Function Duration | 1.20M GB-hr | $142.50 |'));
assert.ok(md.includes('_2 zero-cost service rows were omitted._'));
assert.ok(!md.includes('Edge Requests'));
assert.ok(!md.includes('Image Optimization Cache Reads'));
});
test('renderReport: replaces all-zero usage payload with concise note', () => {
const md = renderReport({
recommendations: [],
gated: [],
signals: {
...baseSignals,
usageScope: 'team',
usage: {
...baseSignals.usage,
services: [
{ name: 'Fast Origin Transfer', billedCost: 0 },
{ name: 'Function Invocations', billedCost: 0 },
{ name: 'Image Optimization Transformation', billedCost: 0 },
],
totals: { billedCost: 0 },
},
},
opts: { projectName: 'x' },
});
assert.ok(md.includes('every reported service cost was $0.00 for this window'));
assert.ok(md.includes('team-wide billing payload'));
assert.ok(!md.includes('| Service | Billed cost |'));
assert.ok(!md.includes('Fast Origin Transfer'));
});
test('renderReport: shows effective cost when included credits zero out billed cost', () => {
const md = renderReport({
recommendations: [],
gated: [],
signals: {
...baseSignals,
usageScope: 'project',
usage: {
...baseSignals.usage,
services: [
{ name: 'Fast Origin Transfer', pricingUnit: 'USD', effectiveCost: 0.00056132736, billedCost: 2.0000000000194732e-10 },
{ name: 'Function Duration', pricingUnit: 'USD', effectiveCost: 0.08251739315, billedCost: 1.4999999853326784e-10 },
{ name: 'Edge Requests', pricingUnit: 'USD', effectiveCost: 0, billedCost: 0 },
],
totals: { billedCost: 4.4999999854348125e-10, effectiveCost: 0.08307872051 },
},
},
opts: { projectName: 'x' },
});
assert.ok(md.includes('Net billed cost is $0.00 after included credits or allotments'));
assert.ok(md.includes('| Service | Effective cost |'));
assert.ok(md.includes('| Function Duration | $0.08 |'));
assert.ok(md.includes('**Total effective cost: $0.08**'));
assert.ok(!md.includes('| Service | Billed cost |'));
});
test('renderReport: cost-header labels team-wide vs project scope', () => {
const team = renderReport({ recommendations: [], gated: [], signals: { ...baseSignals, usageScope: 'team' }, opts: { projectName: 'x' } });
assert.ok(team.includes('## Cost breakdown (team-wide — `vercel usage` has no per-project filter)'));
const proj = renderReport({ recommendations: [], gated: [], signals: { ...baseSignals, usageScope: 'project' }, opts: { projectName: 'x' } });
assert.ok(proj.includes('## Cost breakdown (this project)'));
});
test('renderReport: stack line omits plan-inference reason when plan is known', () => {
// Pre-fix shipped "**Plan**: pro (commitments=[] but usage=...)" — debug leak.
const md = renderReport({
recommendations: [],
gated: [],
signals: {
...baseSignals,
plan: { plan: 'pro', reason: "commitments=[] but usage=$2311899.01/window — Pro pay-as-you-go (Hobby teams don't bill)" },
},
opts: { projectName: 'x' },
});
assert.ok(md.includes('**Plan**: pro ·'));
assert.ok(!md.includes("Hobby teams don't bill"));
});
test('renderReport: synthesizes impact framing from o11ySignal when impactLabel absent', () => {
const rec = {
what: 'Speed up /api/x by parallelizing fetches.',
impactTier: 'high',
o11ySignal: 'inv=84004,p95=4609ms',
candidateRef: 'slow_route:/api/x',
bucket: 'performance',
effort: 'medium',
affectedFiles: [],
citations: [],
// impactLabel intentionally omitted.
};
const md = renderReport({ recommendations: [rec], gated: [], signals: baseSignals, opts: { projectName: 'x' } });
assert.ok(!md.includes('_(no impact framing recorded)_'), 'placeholder should be replaced by synthesized magnitude');
assert.match(md, /current 95th percentile duration is 4,609ms across 84,004 function invocations in this window \(9\.2x the 500ms slow-route threshold\)/);
});
test('renderReport: synthesizes CWV impact against Google thresholds', () => {
const rec = {
what: 'Reduce landing page layout and interaction work.',
impactTier: 'medium',
o11ySignal: 'LCP=3200ms,INP=250ms,CLS=0.18',
candidateRef: 'cwv_poor:/landing',
bucket: 'performance',
effort: 'medium',
affectedFiles: ['src/app/page.tsx'],
citations: [],
};
const md = renderReport({ recommendations: [rec], gated: [], signals: baseSignals, opts: { projectName: 'x' } });
assert.match(md, /bring LCP below 2,500ms \(current 3,200ms\), INP below 200ms \(current 250ms\), and CLS below 0\.1 \(current 0\.18\)/);
});
test('renderReport: synthesizes route-error impact toward sub-0.1% reliability', () => {
const rec = {
what: 'Fix failing send route.',
impactTier: 'high',
o11ySignal: 'errs=300,rate=1.2%',
candidateRef: 'route_errors:/api/send',
bucket: 'reliability',
effort: 'medium',
affectedFiles: ['src/app/api/send/route.ts'],
citations: [],
};
const md = renderReport({ recommendations: [rec], gated: [], signals: baseSignals, opts: { projectName: 'x' } });
assert.match(md, /cut 5xx rate by ~92% to get below 0\.1% \(current 1\.2%, 300 errors in this window\)/);
});
test('renderReport: synthesizes route-error impact when rate is unavailable', () => {
const rec = {
what: 'Fix failing checkout route.',
impactTier: 'medium',
o11ySignal: 'errs=1250',
candidateRef: 'route_errors:/api/checkout',
bucket: 'reliability',
effort: 'medium',
affectedFiles: ['src/app/api/checkout/route.ts'],
citations: [],
};
const md = renderReport({ recommendations: [rec], gated: [], signals: baseSignals, opts: { projectName: 'x' } });
assert.match(md, /resolve 1,250 billed 5xx errors in this window/);
});
test('renderReport: Coverage line shows "investigated all N" when no skipping', () => {
const candidates = [
{ kind: 'slow_route', route: '/a', priority: 100 },
{ kind: 'slow_route', route: '/b', priority: 50 },
];
const md = renderReport({
recommendations: [{ ...sampleRec, what: 'rec a', candidateRef: 'slow_route:/a' }],
gated: [],
candidates,
signals: baseSignals,
opts: { projectName: 'x' },
});
assert.match(md, /\*\*Coverage\*\*: Found \*\*2\*\* potential issues to check/);
assert.match(md, /2 investigated/);
assert.match(md, /1 recommendation ready/);
});
test('renderReport: Coverage line shows N of M when budget bound', () => {
const candidates = [
{ kind: 'slow_route', route: '/a' },
{ kind: 'slow_route', route: '/b' },
{ kind: 'slow_route', route: '/c', gatedReason: 'skippedByBudget (max-candidates=2)' },
{ kind: 'slow_route', route: '/d', gatedReason: 'skippedByBudget (max-candidates=2)' },
];
const md = renderReport({
recommendations: [],
gated: [],
candidates,
signals: baseSignals,
opts: { projectName: 'x' },
});
assert.match(md, /\*\*Coverage\*\*: Found \*\*4\*\* potential issues to check/);
assert.match(md, /2 investigated/);
assert.match(md, /2 left for a larger run/);
assert.match(md, /--max-candidates all/);
});
test('renderReport: Coverage line mentions grouped similar route variants', () => {
const candidates = [
{ kind: 'slow_route', route: '/a' },
{ kind: 'slow_route', route: '/a.dup1', gatedReason: 'coveredBy (slow_route::/a)' },
{ kind: 'slow_route', route: '/a.dup2', gatedReason: 'coveredBy (slow_route::/a)' },
];
const md = renderReport({
recommendations: [],
gated: [],
candidates,
signals: baseSignals,
opts: { projectName: 'x' },
});
assert.match(md, /2 similar route variants grouped/);
});
test('renderReport: Coverage line includes no-change and held-back verification counts', () => {
const md = renderReport({
recommendations: [{ ...sampleRec, candidateRef: 'slow_route:/a' }],
abstentions: [
{ candidateRef: 'slow_route:/b', reason: 'Deep-dive p95 is below threshold.' },
{ candidateRef: 'route_errors:/c', reason: 'Needs stronger evidence.' },
],
gated: [],
candidates: [
{ kind: 'slow_route', route: '/a' },
{ kind: 'slow_route', route: '/b' },
{ kind: 'route_errors', route: '/c' },
],
signals: baseSignals,
opts: { projectName: 'x', heldBackCount: 1 },
});
assert.match(md, /Found \*\*3\*\* potential issues to check/);
assert.match(md, /1 recommendation ready/);
assert.match(md, /1 need more evidence/);
assert.match(md, /1 investigated, no change recommended/);
});
test('renderReport: Cost coverage gaps appears when uncovered services dominate', () => {
const sig = {
...baseSignals,
usage: {
...baseSignals.usage,
services: [
{ name: 'Sandbox Provisioned Memory', billedCost: 500000 },
{ name: 'Function Duration', billedCost: 100000 },
],
totals: { billedCost: 600000 },
},
};
const md = renderReport({ recommendations: [], gated: [], signals: sig, opts: { projectName: 'x' } });
assert.match(md, /### Coverage gaps/);
assert.match(md, /Sandbox Provisioned Memory/);
});
test('render-report CLI: renders flat wrapper observations', async () => {
const { stdout } = await renderCli({
schemaVersion: '1.0',
summary: { totalRecs: 0, observations: 1 },
recsGraded: [],
abstentions: [],
observations: [{
candidateRef: 'slow_route:/event',
summary: 'deployment p95 rose from 256ms to 3135ms',
evidence: 'latest deployment p95=3135ms',
suggestedAction: 'Check the deployment diff for new awaits.',
kind: 'regression',
}],
});
assert.match(stdout, /## Observations from investigation/);
assert.match(stdout, /deployment 95th percentile rose from 256ms to 3135ms/);
assert.match(stdout, /latest deployment 95th percentile duration: 3135ms/);
});
test('render-report CLI: flattens nested wrapper observations', async () => {
const { stdout } = await renderCli({
schemaVersion: '1.0',
summary: { totalRecs: 0, observations: 1 },
recsGraded: [],
abstentions: [],
observations: [{
candidateRef: 'route_errors:/api/send',
observation: {
summary: '5xx rate is concentrated on /api/send',
evidence: 'status=500 count=1200',
suggestedAction: 'Inspect the mail provider branch before tuning performance.',
kind: 'error_storm',
},
}],
});
assert.match(stdout, /5xx rate is concentrated on \/api\/send/);
assert.match(stdout, /status: 500 count: 1200/);
assert.match(stdout, /Error Storm/);
});
test('renderReport: observation evidence expands raw metric shorthand', () => {
const md = renderReport({
recommendations: [],
gated: [],
observations: [{
candidateRef: 'slow_route:/docs',
summary: 'Broad signal inv=10000,p95=900ms did not hold',
evidence: 'deepDive.latency.p95=220ms',
suggestedAction: 'Skip this candidate.',
kind: 'metric_mismatch',
}],
signals: baseSignals,
});
assert.match(md, /function invocations: 10,000/);
assert.match(md, /95th percentile duration: 900ms/);
assert.match(md, /follow-up metric 95th percentile latency: 220ms/);
assert.doesNotMatch(md, /(?:^|[,\s])inv=/);
assert.doesNotMatch(md, /(?:^|[,\s])p95=/);
});
test('renderReport: observation evidence expands dotted metric shorthand', () => {
const md = renderReport({
recommendations: [],
gated: [],
observations: [{
candidateRef: 'slow_route:/docs',
summary: 'cpu.p95=120ms vs latency.p95=900ms and ttfb.p95=880ms',
evidence: 'deepDive.cpu.p95=120ms; deepDive.latency.p95=900ms',
suggestedAction: 'Inspect runtime traces before recommending a code change.',
kind: 'other',
}],
signals: baseSignals,
});
assert.match(md, /95th percentile CPU time: 120ms/);
assert.match(md, /95th percentile latency: 900ms/);
assert.match(md, /95th percentile TTFB: 880ms/);
assert.doesNotMatch(md, /\b(?:cpu|latency|ttfb)\.p95=/);
});
test('renderReport: direct renderer holds back unsafe observations', () => {
const md = renderReport({
recommendations: [],
gated: [],
observations: [{
candidateRef: 'platform_bot_protection:<account>',
summary: 'Bot traffic dominates bandwidth.',
evidence: 'browser_impersonation traffic is high.',
suggestedAction: 'Enable WAF managed bot rules.',
kind: 'config_gap',
}],
signals: baseSignals,
});
assert.ok(!md.includes('Enable WAF managed bot rules'));
assert.match(md, /## Needs more evidence/);
assert.match(md, /staged safe-rollout plan/);
});
test('renderReport: throws when observation summary is missing', () => {
assert.throws(
() => renderReport({
recommendations: [],
gated: [],
observations: [{ candidateRef: 'slow_route:/x', evidence: 'p95=3000ms' }],
signals: baseSignals,
}),
/observations\[0\]\.summary is required/,
);
});
test('render-report CLI: drops wrapper recs with missing quality', async () => {
const { quality, ...ungradedRec } = sampleRec;
const { stdout } = await renderCli({
schemaVersion: '1.0',
summary: { totalRecs: 1, observations: 0 },
recsGraded: [ungradedRec],
abstentions: [],
observations: [],
});
assert.ok(!stdout.includes(ungradedRec.what), 'ungraded wrapper rec should not ship');
assert.match(stdout, /No recommendations are ready to apply from this run/);
});
test('render-report CLI: hard-drops cache-vary safety failures from customer recommendations', async () => {
const unsafe = {
...sampleRec,
what: 'Add s-maxage Cache-Control to /api/banner.',
candidateRef: 'uncached_route:/api/banner',
};
const { stdout } = await renderCli({
schemaVersion: '1.0',
summary: { totalRecs: 1, observations: 0 },
recsGraded: [unsafe],
abstentions: [],
observations: [],
regenPlan: [{
index: 5,
candidateRef: 'uncached_route:/api/banner',
regenTrigger: 'cache_vary_safety',
}],
});
assert.ok(!stdout.includes(unsafe.what), 'unsafe cache rec should not ship');
assert.match(stdout, /varies by request geography without the required Vary header/);
});
test('render-report CLI: hard-drops semantic safety failures from customer recommendations', async () => {
const unsafe = {
...sampleRec,
what: "Move notFound() out of 'use cache' to stop 500s.",
candidateRef: 'route_errors:/docs/messages/dynamic-server-error',
};
const { stdout } = await renderCli({
schemaVersion: '1.0',
summary: { totalRecs: 1, observations: 0 },
recsGraded: [unsafe],
abstentions: [],
observations: [],
regenPlan: [{
index: 0,
candidateRef: unsafe.candidateRef,
regenTrigger: 'semantic_safety',
}],
});
assert.ok(!stdout.includes(unsafe.what), 'unsupported semantic rec should not ship');
assert.match(stdout, /stronger framework evidence before it is safe to apply/);
});
test('render-report CLI: does not render needs-review recommendations as ready', async () => {
const reviewOnly = {
...sampleRec,
what: 'Enable a risky platform setting.',
candidateRef: 'platform_bot_protection:<account>',
needsReview: true,
};
const { stdout } = await renderCli({
schemaVersion: '1.0',
summary: { totalRecs: 1, observations: 0, withheldRecommendations: 1 },
renderableRecommendations: [reviewOnly],
recsGraded: [reviewOnly],
withheldRecommendations: [{
candidateRef: reviewOnly.candidateRef,
what: reviewOnly.what,
reason: 'needs_review',
}],
abstentions: [],
observations: [],
});
assert.ok(!stdout.includes(reviewOnly.what), 'needs-review rec should not ship as ready');
assert.match(stdout, /kept the recommendation out of the ready-to-apply list/);
});
test('render-report CLI: hard-drops stale wrapper recs that are absent from current gate output', async () => {
const active = {
...sampleRec,
what: 'Fix the active slow route.',
candidateRef: 'slow_route:/active',
};
const stale = {
...sampleRec,
what: 'Fix the stale slow route.',
candidateRef: 'slow_route:/stale',
};
const { stdout } = await renderCli({
schemaVersion: '1.0',
summary: { totalRecs: 2, observations: 0 },
recsGraded: [active, stale],
abstentions: [],
observations: [],
}, [], {
toLaunch: [{ kind: 'slow_route', route: '/active' }],
platform: [],
gated: [],
});
assert.match(stdout, /Fix the active slow route/);
assert.ok(!stdout.includes('Fix the stale slow route'), 'stale rec should not ship');
assert.match(stdout, /not in the current run output/);
});
test('render-report CLI: holds back unsupported framework-causal observations', async () => {
const { stdout } = await renderCli({
schemaVersion: '1.0',
summary: { totalRecs: 0, observations: 1 },
recsGraded: [],
abstentions: [],
observations: [{
candidateRef: 'route_errors:/docs/pages',
summary: "notFound() inside a 'use cache' page is a known Next.js Cache Components edge case that can surface as 5xx.",
evidence: "apps/docs/page.tsx:1 declares 'use cache' and calls notFound().",
suggestedAction: 'Move notFound() outside the cached scope.',
kind: 'config_gap',
}],
});
assert.ok(!stdout.includes('known Next.js Cache Components edge case'), 'unsupported observation should not ship');
assert.ok(!stdout.includes('Move notFound() outside the cached scope'), 'unsupported action should not ship');
assert.match(stdout, /framework-specific cause claim that verification could not support/);
});
test('render-report CLI: holds back implementation-grade observation actions', async () => {
const { stdout } = await renderCli({
schemaVersion: '1.0',
summary: { totalRecs: 0, observations: 1 },
recsGraded: [],
abstentions: [],
observations: [{
candidateRef: 'platform_bot_protection:<account>',
summary: 'Bot traffic accounts for 92% of edge bandwidth.',
evidence: 'browser_impersonation dominates Fast Data Transfer.',
suggestedAction: 'Enable WAF managed bot rules to challenge or deny browser_impersonation traffic.',
kind: 'config_gap',
}],
});
assert.ok(!stdout.includes('Enable WAF managed bot rules'), 'implementation-grade observation action should not ship');
assert.match(stdout, /verified platform recommendation/);
});
test('render-report CLI: counts held-back observations in coverage', async () => {
const { stdout } = await renderCli({
schemaVersion: '1.0',
summary: { totalRecs: 0, observations: 1, abstentions: 0 },
recsGraded: [],
abstentions: [],
observations: [{
candidateRef: 'slow_route:/api/ribbon',
summary: 'The route waits on shared origin data.',
evidence: 'latency.p95=900ms',
suggestedAction: 'wrap the shared fetch helper before returning the route response.',
kind: 'upstream_dependency',
}],
}, [], {
toLaunch: [{ kind: 'slow_route', route: '/api/ribbon' }],
platform: [],
gated: [],
});
assert.match(stdout, /0 recommendations ready\s+·\s+1 need more evidence/);
assert.match(stdout, /## Needs more evidence/);
assert.ok(!stdout.includes('wrap the shared fetch helper'), 'lower-case implementation action should not ship as an observation');
});
test('render-report CLI: holds back alternate implementation verbs in observations', async () => {
const { stdout } = await renderCli({
schemaVersion: '1.0',
summary: { totalRecs: 0, observations: 1 },
recsGraded: [],
abstentions: [],
observations: [{
candidateRef: 'slow_route:/api/search',
summary: 'The route has independent upstream calls.',
evidence: 'cpu.p95=100ms vs latency.p95=1200ms',
suggestedAction: 'use Promise.all and raise the TTL for the shared search lookup.',
kind: 'upstream_dependency',
}],
});
assert.ok(!stdout.includes('use Promise.all'), 'alternate implementation action should not ship as an observation');
assert.match(stdout, /ready-to-apply recommendation evidence bar/);
});
test('render-report CLI: holds back root-cause claims even when action asks to inspect logs', async () => {
const { stdout } = await renderCli({
schemaVersion: '1.0',
summary: { totalRecs: 0, observations: 1 },
recsGraded: [],
abstentions: [],
observations: [{
candidateRef: 'route_errors:/api/checkout',
summary: '500 error rate is caused by an upstream checkout gateway response.',
evidence: 'http_status=500 count=92; route.ts:57 parses the upstream response.',
suggestedAction: 'Inspect logs before recommending a code change.',
kind: 'error_storm',
}],
});
assert.ok(!stdout.includes('caused by an upstream checkout gateway response'));
assert.match(stdout, /runtime root-cause claim/);
});
test('render-report CLI: holds back stale Next cache APIs in observations', async () => {
const { stdout } = await renderCli({
schemaVersion: '1.0',
summary: { totalRecs: 0, observations: 1 },
recsGraded: [],
abstentions: [],
observations: [{
candidateRef: 'slow_route:/api/ribbon',
summary: 'The route fetches shared Sanity data on every request.',
evidence: 'next@16 app route with repeated shared fetches.',
suggestedAction: 'Wrap the fetch in unstable_cache with a 60s TTL.',
kind: 'upstream_dependency',
}],
}, [], { toLaunch: [], platform: [], gated: [] }, {
...baseSignals,
stack: { ...baseSignals.stack, frameworkVersion: '16.2.6', cacheComponents: true },
});
assert.ok(!stdout.includes('unstable_cache'), 'Next 16 stale cache API should not ship in observations');
assert.match(stdout, /framework-version evidence/);
});
test('render-report CLI: does not hold back unstable_cache observations for Next 15', async () => {
const { stdout } = await renderCli({
schemaVersion: '1.0',
summary: { totalRecs: 0, observations: 1 },
recsGraded: [],
abstentions: [],
observations: [{
candidateRef: 'slow_route:/api/ribbon',
summary: 'The route uses unstable_cache on a shared lookup.',
evidence: 'Next 15 route with runtime-cache evidence.',
suggestedAction: 'Inspect cache key cardinality and freshness before recommending a code change.',
kind: 'upstream_dependency',
}],
}, [], { toLaunch: [], platform: [], gated: [] }, {
...baseSignals,
stack: { ...baseSignals.stack, frameworkVersion: '15.4.10' },
});
assert.match(stdout, /The route uses unstable_cache/);
assert.doesNotMatch(stdout, /cache API that does not match/);
});
test('render-report CLI: holds back WAF bot-category custom-rule claims', async () => {
const { stdout } = await renderCli({
schemaVersion: '1.0',
summary: { totalRecs: 0, observations: 1 },
recsGraded: [],
abstentions: [],
observations: [{
candidateRef: 'platform_bot_protection:<account>',
summary: 'browser_impersonation traffic dominates bandwidth.',
evidence: 'bot_category=browser_impersonation accounts for most Fast Data Transfer.',
suggestedAction: 'Add a WAF custom rule targeting bot_category=browser_impersonation with a Challenge action.',
kind: 'config_gap',
}],
});
assert.ok(!stdout.includes('bot_category=browser_impersonation'), 'unsupported WAF condition should not ship');
assert.match(stdout, /WAF-rule condition/);
});
test('render-report CLI: suppresses same-route same-family observations covered by a ready rec', async () => {
const readyCacheRec = {
...sampleRec,
what: 'Add Cache-Control to /docs/llm-digest success responses',
candidateRef: 'uncached_route:/docs/llm-digest/[...slug]',
o11ySignal: 'inv=1000,cache=44%',
};
const { stdout } = await renderCli({
schemaVersion: '1.0',
summary: { totalRecs: 2, observations: 2 },
renderableRecommendations: [readyCacheRec],
recsGraded: [readyCacheRec],
abstentions: [],
observations: [
{
candidateRef: 'cache_header_gap:/docs/llm-digest/[...slug]',
summary: 'Cache fix is blocked on error-rate triage.',
evidence: 'Same route and same cache family as the ready recommendation.',
suggestedAction: 'Do not cache this route yet.',
kind: 'error_storm',
},
{
candidateRef: 'route_errors:/docs/llm-digest/[...slug]',
summary: 'The route still has a confirmed 5xx storm.',
evidence: 'Status distribution confirms many 500s.',
suggestedAction: 'Pull runtime logs for the failing helper.',
kind: 'error_storm',
},
],
});
assert.match(stdout, /Add Cache-Control to \/docs\/llm-digest success responses/);
assert.match(stdout, /requests: 1,000; cache hit rate: 44%/);
assert.ok(!stdout.includes('function invocations: 1,000; cache hit rate: 44%'));
assert.ok(!stdout.includes('Cache fix is blocked on error-rate triage'), 'same-family cache observation should not also ship');
assert.match(stdout, /The route still has a confirmed 5xx storm/);
});
test('render-report CLI: holds back source-absence observations that need verification', async () => {
const { stdout } = await renderCli({
schemaVersion: '1.0',
summary: { totalRecs: 0, observations: 1 },
recsGraded: [],
abstentions: [],
observations: [{
candidateRef: 'route_errors:/blog/llm-digest/next-16',
summary: 'The route has no matching MDX file for next-16.',
evidence: 'No corresponding post file exists in content/posts.',
suggestedAction: 'Stop reading the file at request time.',
kind: 'error_storm',
}],
});
assert.ok(!stdout.includes('no matching MDX file'), 'unsupported source-absence observation should not ship');
assert.match(stdout, /source-file absence claim that verification could not support/);
});
test('render-report CLI: holds back cacheLife-to-CDN observations and rewrites duplicate no-change rows', async () => {
const { stdout } = await renderCli({
schemaVersion: '1.0',
summary: { totalRecs: 0, observations: 1 },
recsGraded: [],
abstentions: [{
candidateRef: 'uncached_route:/docs/other',
reason: "The fix belongs in toLaunch-10; a single `cacheLife('weeks')` call covers every /docs/* slug.",
}],
observations: [{
candidateRef: 'uncached_route:/docs/page',
summary: 'This route rolls into the catch-all docs route fix tracked by toLaunch-10.',
evidence: "page.tsx declares 'use cache' with no cacheLife(); cache breakdown is 0% HIT.",
suggestedAction: "Treat toLaunch-10's `cacheLife('weeks')` rec as canonical for this slug.",
kind: 'other',
}],
});
assert.ok(!stdout.includes("cacheLife('weeks')"), 'unsupported cacheLife fix text should not ship');
assert.ok(!stdout.includes('toLaunch-10'), 'internal candidate ids should not ship');
assert.match(stdout, /unsupported cacheLife-to-CDN claim/);
assert.match(stdout, /cache-lifetime draft that did not meet the framework evidence bar/);
});
test('render-report CLI: dedupes verified wrapper recs before rendering', async () => {
const duplicate = {
...sampleRec,
candidateRef: 'slow_route:/dashboard/[sessionId]/details',
o11ySignal: 'inv=4000,p95=990ms',
priority: sampleRec.priority - 10,
};
const { stdout } = await renderCli({
schemaVersion: '1.0',
summary: { totalRecs: 2, observations: 0 },
recsGraded: [sampleRec, duplicate],
abstentions: [],
observations: [],
});
assert.match(stdout, /corroborated: 2/);
assert.match(stdout, /Also applies to: Slow route on \/dashboard\/\[sessionId\]\/details/);
});
|