pi-cloudflare-agent-tracing 0.2.0 → 0.4.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.
@@ -3,7 +3,8 @@ import { mkdir, readFile, writeFile } from "node:fs/promises";
3
3
  import { dirname, extname, resolve } from "node:path";
4
4
  import { pathToFileURL } from "node:url";
5
5
 
6
- const MODES = new Set(["trace", "health", "cost", "evaluate", "incident"]);
6
+ const REPORT_KIND = "pi-agent-trace";
7
+ const SCOPE_LEVELS = new Set(["turn", "thread", "service"]);
7
8
  const MAX_INPUT_BYTES = 2_000_000;
8
9
 
9
10
  if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
@@ -26,12 +27,13 @@ if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
26
27
 
27
28
  export function renderReportHtml(report) {
28
29
  validateReport(report);
29
- const mode = report.mode;
30
+ const scope = asObject(report.scope);
31
+ const level = text(scope.level, "service");
30
32
  const verdict = asObject(report.verdict);
31
33
  const verdictLabel = text(verdict.label, "Indeterminate");
32
34
  const confidence = text(verdict.confidence, "not stated");
33
35
  const generatedAt = text(report.generatedAt, new Date().toISOString());
34
- const title = text(report.title, `${capitalize(mode)} report`);
36
+ const title = text(report.title, "Pi agent trace");
35
37
  const sections = [
36
38
  renderScope(report.scope),
37
39
  renderMetrics(report.metrics),
@@ -64,7 +66,7 @@ export function renderReportHtml(report) {
64
66
  <body>
65
67
  <main>
66
68
  <header class="hero">
67
- <p class="eyebrow">${escapeHtml(mode)} · Cloudflare agent tracing</p>
69
+ <p class="eyebrow">${escapeHtml(level)} · Pi agent trace</p>
68
70
  <h1>${escapeHtml(title)}</h1>
69
71
  <p class="subtitle">${escapeHtml(text(verdict.summary, "Evidence-backed report for human review."))}</p>
70
72
  <div class="hero-grid">
@@ -82,53 +84,81 @@ ${sections.join("\n")}
82
84
  }
83
85
 
84
86
  export function validateReport(report) {
85
- if (!report || typeof report !== "object" || Array.isArray(report)) throw new Error("Report must be a JSON object");
86
- if (!MODES.has(report.mode)) throw new Error(`Report mode must be one of: ${[...MODES].join(", ")}`);
87
- if (report.schemaVersion !== undefined && report.schemaVersion !== 1) throw new Error("Unsupported report schemaVersion");
87
+ if (!report || typeof report !== "object" || Array.isArray(report))
88
+ throw new Error("Report must be a JSON object");
89
+ if (report.kind !== REPORT_KIND) throw new Error(`Report kind must be ${REPORT_KIND}`);
90
+ if (report.schemaVersion !== 2) throw new Error("Unsupported report schemaVersion");
91
+ const level = asObject(report.scope).level;
92
+ if (!SCOPE_LEVELS.has(level))
93
+ throw new Error(`Report scope.level must be one of: ${[...SCOPE_LEVELS].join(", ")}`);
88
94
  }
89
95
 
90
96
  function renderScope(scopeValue) {
91
97
  const scope = asObject(scopeValue);
92
98
  const entries = [
93
- ["Worker", scope.worker], ["Environment", scope.environment], ["Deployment", scope.deployment],
94
- ["Target", scope.target], ["Start UTC", scope.startUtc], ["End UTC", scope.endUtc],
99
+ ["Level", scope.level],
100
+ ["Worker", scope.worker],
101
+ ["Environment", scope.environment],
102
+ ["Deployment", scope.deployment],
103
+ ["Target", scope.target],
104
+ ["Start UTC", scope.startUtc],
105
+ ["End UTC", scope.endUtc],
95
106
  ].filter(([, value]) => present(value));
96
107
  if (!entries.length) return "";
97
- return section("Scope", `<div class="scope-grid">${entries.map(([label, value]) => `<div class="scope-item"><span class="label">${escapeHtml(label)}</span><span class="value mono">${escapeHtml(text(value))}</span></div>`).join("")}</div>`);
108
+ return section(
109
+ "Scope",
110
+ `<div class="scope-grid">${entries.map(([label, value]) => `<div class="scope-item"><span class="label">${escapeHtml(label)}</span><span class="value mono">${escapeHtml(text(value))}</span></div>`).join("")}</div>`,
111
+ );
98
112
  }
99
113
 
100
114
  function renderMetrics(metrics) {
101
115
  if (!Array.isArray(metrics) || metrics.length === 0) return "";
102
- const cards = metrics.slice(0, 50).map((metric) => {
103
- const item = asObject(metric);
104
- const value = [text(item.value, "—"), text(item.unit)].filter(Boolean).join(" ");
105
- return `<div class="stat"><span class="label">${escapeHtml(text(item.label, "Metric"))}</span><span class="value ${statusClass(item.status)}">${escapeHtml(value)}</span>${present(item.detail) ? `<span class="count">${escapeHtml(text(item.detail))}</span>` : ""}</div>`;
106
- }).join("");
116
+ const cards = metrics
117
+ .slice(0, 50)
118
+ .map((metric) => {
119
+ const item = asObject(metric);
120
+ const value = [text(item.value, "—"), text(item.unit)].filter(Boolean).join(" ");
121
+ return `<div class="stat"><span class="label">${escapeHtml(text(item.label, "Metric"))}</span><span class="value ${statusClass(item.status)}">${escapeHtml(value)}</span>${present(item.detail) ? `<span class="count">${escapeHtml(text(item.detail))}</span>` : ""}</div>`;
122
+ })
123
+ .join("");
107
124
  return section("Key metrics", `<div class="metric-grid">${cards}</div>`, metrics.length);
108
125
  }
109
126
 
110
127
  function renderRequestPath(items) {
111
128
  if (!Array.isArray(items) || items.length === 0) return "";
112
- const timeline = items.slice(0, 100).map((entry) => {
113
- const item = asObject(entry);
114
- return `<div class="timeline-item"><span class="dot"></span><h3>${escapeHtml(text(item.stage, "Stage"))} <span class="${statusClass(item.status)}">${escapeHtml(text(item.status))}</span></h3>${present(item.detail) ? `<p>${escapeHtml(text(item.detail))}</p>` : ""}<div class="meta">${chips([item.timestampUtc, duration(item.durationMs), ...array(item.evidenceIds)])}</div></div>`;
115
- }).join("");
129
+ const timeline = items
130
+ .slice(0, 100)
131
+ .map((entry) => {
132
+ const item = asObject(entry);
133
+ return `<div class="timeline-item"><span class="dot"></span><h3>${escapeHtml(text(item.stage, "Stage"))} <span class="${statusClass(item.status)}">${escapeHtml(text(item.status))}</span></h3>${present(item.detail) ? `<p>${escapeHtml(text(item.detail))}</p>` : ""}<div class="meta">${chips([item.timestampUtc, duration(item.durationMs), ...array(item.evidenceIds)])}</div></div>`;
134
+ })
135
+ .join("");
116
136
  return section("Request path", `<div class="timeline">${timeline}</div>`, items.length);
117
137
  }
118
138
 
119
139
  function renderFailures(items) {
120
140
  if (!Array.isArray(items) || items.length === 0) return "";
121
- return section("Failures and recovery", `<div class="cards">${items.slice(0, 100).map((entry) => {
122
- const item = asObject(entry);
123
- return `<article class="card"><h3 class="${statusClass(item.severity)}">${escapeHtml(text(item.title, "Failure"))}</h3>${paragraph(item.detail)}${present(item.recovery) ? `<p><strong>Recovery:</strong> ${escapeHtml(text(item.recovery))}</p>` : ""}<div class="meta">${chips([item.severity, item.status, ...array(item.evidenceIds)])}</div></article>`;
124
- }).join("")}</div>`, items.length);
141
+ return section(
142
+ "Failures and recovery",
143
+ `<div class="cards">${items
144
+ .slice(0, 100)
145
+ .map((entry) => {
146
+ const item = asObject(entry);
147
+ return `<article class="card"><h3 class="${statusClass(item.severity)}">${escapeHtml(text(item.title, "Failure"))}</h3>${paragraph(item.detail)}${present(item.recovery) ? `<p><strong>Recovery:</strong> ${escapeHtml(text(item.recovery))}</p>` : ""}<div class="meta">${chips([item.severity, item.status, ...array(item.evidenceIds)])}</div></article>`;
148
+ })
149
+ .join("")}</div>`,
150
+ items.length,
151
+ );
125
152
  }
126
153
 
127
154
  function renderLatency(value) {
128
155
  const latency = asObject(value);
129
156
  const metrics = array(latency.metrics);
130
157
  if (!present(latency.summary) && metrics.length === 0) return "";
131
- return section("Latency", `${paragraph(latency.summary)}${renderSimpleTable(metrics, ["label", "value", "unit", "source"])}`);
158
+ return section(
159
+ "Latency",
160
+ `${paragraph(latency.summary)}${renderSimpleTable(metrics, ["label", "value", "unit", "source"])}`,
161
+ );
132
162
  }
133
163
 
134
164
  function renderCost(value) {
@@ -137,9 +167,19 @@ function renderCost(value) {
137
167
  if (!present(cost.total) && !present(cost.summary) && items.length === 0) return "";
138
168
  const overview = `<div class="scope-grid">${[
139
169
  ["Total", [text(cost.currency), text(cost.total)].filter(Boolean).join(" ")],
140
- ["Source", cost.source], ["Completeness", cost.completeness],
141
- ].filter(([, item]) => present(item)).map(([label, item]) => `<div class="scope-item"><span class="label">${escapeHtml(label)}</span><span class="value">${escapeHtml(text(item))}</span></div>`).join("")}</div>`;
142
- return section("Cost", `${paragraph(cost.summary)}${overview}${renderSimpleTable(items, ["label", "model", "tokens", "cost", "source"])}`);
170
+ ["Source", cost.source],
171
+ ["Completeness", cost.completeness],
172
+ ]
173
+ .filter(([, item]) => present(item))
174
+ .map(
175
+ ([label, item]) =>
176
+ `<div class="scope-item"><span class="label">${escapeHtml(label)}</span><span class="value">${escapeHtml(text(item))}</span></div>`,
177
+ )
178
+ .join("")}</div>`;
179
+ return section(
180
+ "Cost",
181
+ `${paragraph(cost.summary)}${overview}${renderSimpleTable(items, ["label", "model", "tokens", "cost", "source"])}`,
182
+ );
143
183
  }
144
184
 
145
185
  function renderFulfillment(value) {
@@ -147,39 +187,86 @@ function renderFulfillment(value) {
147
187
  const checks = array(fulfillment.checks);
148
188
  if (!present(fulfillment.verdict) && checks.length === 0) return "";
149
189
  const header = `<div class="scope-grid">${[
150
- ["Verdict", fulfillment.verdict], ["Score", fulfillment.score], ["Semantic evidence", fulfillment.semanticEvidence],
151
- ].filter(([, item]) => present(item)).map(([label, item]) => `<div class="scope-item"><span class="label">${escapeHtml(label)}</span><span class="value ${statusClass(item)}">${escapeHtml(text(item))}</span></div>`).join("")}</div>`;
152
- const rows = checks.length ? `<div class="table-wrap"><table><thead><tr><th>Check</th><th>Result</th><th>Evidence</th></tr></thead><tbody>${checks.slice(0, 100).map((entry) => { const item = asObject(entry); const passed = item.passed === true; return `<tr><td>${escapeHtml(text(item.name, "Check"))}</td><td><span class="check ${passed ? "pass" : "fail"}">${passed ? "Passed" : "Failed"}</span></td><td>${escapeHtml(text(item.evidence, "—"))}</td></tr>`; }).join("")}</tbody></table></div>` : "";
190
+ ["Verdict", fulfillment.verdict],
191
+ ["Score", fulfillment.score],
192
+ ["Semantic evidence", fulfillment.semanticEvidence],
193
+ ]
194
+ .filter(([, item]) => present(item))
195
+ .map(
196
+ ([label, item]) =>
197
+ `<div class="scope-item"><span class="label">${escapeHtml(label)}</span><span class="value ${statusClass(item)}">${escapeHtml(text(item))}</span></div>`,
198
+ )
199
+ .join("")}</div>`;
200
+ const rows = checks.length
201
+ ? `<div class="table-wrap"><table><thead><tr><th>Check</th><th>Result</th><th>Evidence</th></tr></thead><tbody>${checks
202
+ .slice(0, 100)
203
+ .map((entry) => {
204
+ const item = asObject(entry);
205
+ const passed = item.passed === true;
206
+ return `<tr><td>${escapeHtml(text(item.name, "Check"))}</td><td><span class="check ${passed ? "pass" : "fail"}">${passed ? "Passed" : "Failed"}</span></td><td>${escapeHtml(text(item.evidence, "—"))}</td></tr>`;
207
+ })
208
+ .join("")}</tbody></table></div>`
209
+ : "";
153
210
  return section("Fulfillment", `${paragraph(fulfillment.summary)}${header}${rows}`);
154
211
  }
155
212
 
156
213
  function renderDurableState(items) {
157
214
  if (!Array.isArray(items) || items.length === 0) return "";
158
- return section("Durable state evidence", renderSimpleTable(items, ["owner", "record", "status", "summary", "evidenceId"]), items.length);
215
+ return section(
216
+ "Durable state evidence",
217
+ renderSimpleTable(items, ["owner", "record", "status", "summary", "evidenceId"]),
218
+ items.length,
219
+ );
159
220
  }
160
221
 
161
222
  function renderRecommendations(items) {
162
223
  if (!Array.isArray(items) || items.length === 0) return "";
163
- return section("Recommendations", `<div class="cards">${items.slice(0, 100).map((entry, index) => { const item = asObject(entry); return `<article class="card"><h3>${index + 1}. ${escapeHtml(text(item.title, "Recommendation"))}</h3>${paragraph(item.detail)}<div class="meta">${chips([item.priority, item.owner, item.evidenceId])}</div></article>`; }).join("")}</div>`, items.length);
224
+ return section(
225
+ "Recommendations",
226
+ `<div class="cards">${items
227
+ .slice(0, 100)
228
+ .map((entry, index) => {
229
+ const item = asObject(entry);
230
+ return `<article class="card"><h3>${index + 1}. ${escapeHtml(text(item.title, "Recommendation"))}</h3>${paragraph(item.detail)}<div class="meta">${chips([item.priority, item.owner, item.evidenceId])}</div></article>`;
231
+ })
232
+ .join("")}</div>`,
233
+ items.length,
234
+ );
164
235
  }
165
236
 
166
237
  function renderEvidence(items) {
167
238
  if (!Array.isArray(items) || items.length === 0) return "";
168
- const details = items.slice(0, 200).map((entry) => {
169
- const item = asObject(entry);
170
- return `<details><summary><span class="mono">${escapeHtml(text(item.id, "evidence"))}</span> · ${escapeHtml(text(item.summary, item.type ?? "Evidence"))}</summary>${paragraph(item.detail)}<div class="meta">${chips([item.type, item.source, item.observedAt, item.correlation])}</div>${present(item.limitation) ? `<p><strong>Limitation:</strong> ${escapeHtml(text(item.limitation))}</p>` : ""}</details>`;
171
- }).join("");
239
+ const details = items
240
+ .slice(0, 200)
241
+ .map((entry) => {
242
+ const item = asObject(entry);
243
+ return `<details><summary><span class="mono">${escapeHtml(text(item.id, "evidence"))}</span> · ${escapeHtml(text(item.summary, item.type ?? "Evidence"))}</summary>${paragraph(item.detail)}<div class="meta">${chips([item.type, item.source, item.observedAt, item.correlation])}</div>${present(item.limitation) ? `<p><strong>Limitation:</strong> ${escapeHtml(text(item.limitation))}</p>` : ""}</details>`;
244
+ })
245
+ .join("");
172
246
  return section("Evidence", details, items.length);
173
247
  }
174
248
 
175
249
  function renderLimitations(items) {
176
250
  if (!Array.isArray(items) || items.length === 0) return "";
177
- return section("Limitations", `<div class="cards">${items.slice(0, 100).map((item) => `<div class="card">${escapeHtml(text(item))}</div>`).join("")}</div>`, items.length);
251
+ return section(
252
+ "Limitations",
253
+ `<div class="cards">${items
254
+ .slice(0, 100)
255
+ .map((item) => `<div class="card">${escapeHtml(text(item))}</div>`)
256
+ .join("")}</div>`,
257
+ items.length,
258
+ );
178
259
  }
179
260
 
180
261
  function renderSimpleTable(items, keys) {
181
262
  if (!items.length) return "";
182
- return `<div class="table-wrap"><table><thead><tr>${keys.map((key) => `<th>${escapeHtml(titleCase(key))}</th>`).join("")}</tr></thead><tbody>${items.slice(0, 100).map((entry) => { const item = asObject(entry); return `<tr>${keys.map((key) => `<td>${escapeHtml(text(item[key], "—"))}</td>`).join("")}</tr>`; }).join("")}</tbody></table></div>`;
263
+ return `<div class="table-wrap"><table><thead><tr>${keys.map((key) => `<th>${escapeHtml(titleCase(key))}</th>`).join("")}</tr></thead><tbody>${items
264
+ .slice(0, 100)
265
+ .map((entry) => {
266
+ const item = asObject(entry);
267
+ return `<tr>${keys.map((key) => `<td>${escapeHtml(text(item[key], "—"))}</td>`).join("")}</tr>`;
268
+ })
269
+ .join("")}</tbody></table></div>`;
183
270
  }
184
271
 
185
272
  function section(title, body, count) {
@@ -195,7 +282,10 @@ function paragraph(value) {
195
282
  }
196
283
 
197
284
  function chips(values) {
198
- return values.filter(present).map((value) => `<span class="chip">${escapeHtml(text(value))}</span>`).join("");
285
+ return values
286
+ .filter(present)
287
+ .map((value) => `<span class="chip">${escapeHtml(text(value))}</span>`)
288
+ .join("");
199
289
  }
200
290
 
201
291
  function duration(value) {
@@ -204,20 +294,25 @@ function duration(value) {
204
294
 
205
295
  function statusClass(value) {
206
296
  const normalized = text(value).toLowerCase();
207
- if (/fulfilled|healthy|success|succeeded|done|recovered|verified|low|complete/.test(normalized)) return "status-good";
297
+ if (/fulfilled|healthy|success|succeeded|done|recovered|verified|low|complete/.test(normalized))
298
+ return "status-good";
208
299
  if (/fail|error|critical|high|not_fulfilled|unhealthy/.test(normalized)) return "status-bad";
209
- if (/partial|warning|warn|indeterminate|medium|incomplete|cancel/.test(normalized)) return "status-warn";
300
+ if (/partial|warning|warn|indeterminate|medium|incomplete|cancel/.test(normalized))
301
+ return "status-warn";
210
302
  return "";
211
303
  }
212
304
 
213
305
  function formatTimestamp(value) {
214
306
  const date = new Date(value);
215
- return Number.isNaN(date.valueOf()) ? value : date.toISOString().replace("T", " ").replace(".000Z", " UTC");
307
+ return Number.isNaN(date.valueOf())
308
+ ? value
309
+ : date.toISOString().replace("T", " ").replace(".000Z", " UTC");
216
310
  }
217
311
 
218
312
  function parseArguments(args) {
219
313
  const input = args[0];
220
- if (!input || input === "--help") throw new Error("Usage: node render-report.mjs <report.json> [--out <report.html>]");
314
+ if (!input || input === "--help")
315
+ throw new Error("Usage: node render-report.mjs <report.json> [--out <report.html>]");
221
316
  const outIndex = args.indexOf("--out");
222
317
  if (outIndex >= 0 && !args[outIndex + 1]) throw new Error("--out requires a path");
223
318
  return { input: resolve(input), output: outIndex >= 0 ? args[outIndex + 1] : undefined };
@@ -248,11 +343,11 @@ function text(value, fallback = "") {
248
343
  }
249
344
 
250
345
  function escapeHtml(value) {
251
- return text(value).replace(/[&<>"']/g, (character) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[character]);
252
- }
253
-
254
- function capitalize(value) {
255
- return value ? value[0].toUpperCase() + value.slice(1) : value;
346
+ return text(value).replace(
347
+ /[&<>"']/g,
348
+ (character) =>
349
+ ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[character],
350
+ );
256
351
  }
257
352
 
258
353
  function titleCase(value) {
@@ -1,42 +1,52 @@
1
1
  import assert from "node:assert/strict";
2
+ import { spawnSync } from "node:child_process";
2
3
  import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
3
4
  import { tmpdir } from "node:os";
4
5
  import { join } from "node:path";
5
- import { spawnSync } from "node:child_process";
6
- import { fileURLToPath } from "node:url";
7
6
  import test from "node:test";
7
+ import { fileURLToPath } from "node:url";
8
8
  import { renderReportHtml, validateReport } from "./render-report.mjs";
9
9
 
10
- const modes = ["trace", "health", "cost", "evaluate", "incident"];
10
+ function report(overrides = {}) {
11
+ return {
12
+ schemaVersion: 2,
13
+ kind: "pi-agent-trace",
14
+ title: "Pi agent trace",
15
+ generatedAt: "2026-12-02T17:30:00Z",
16
+ verdict: { label: "indeterminate", confidence: "medium", summary: "Bounded evidence." },
17
+ scope: { level: "turn", worker: "portable-worker", startUtc: "2026-12-02T17:00:00Z" },
18
+ evidence: [{ id: "E1", type: "trace", summary: "Request observed" }],
19
+ limitations: ["Sampling enabled"],
20
+ ...overrides,
21
+ };
22
+ }
23
+
24
+ test("renders one unified Pi agent trace report", () => {
25
+ const html = renderReportHtml(report());
11
26
 
12
- for (const mode of modes) {
13
- test(`renders a standalone ${mode} report`, () => {
14
- const html = renderReportHtml({
15
- schemaVersion: 1,
16
- mode,
17
- title: `${mode} report`,
18
- generatedAt: "2026-12-02T17:30:00Z",
19
- verdict: { label: "indeterminate", confidence: "medium", summary: "Bounded evidence." },
20
- scope: { worker: "portable-worker", startUtc: "2026-12-02T17:00:00Z" },
21
- evidence: [{ id: "E1", type: "trace", summary: "Request observed" }],
22
- limitations: ["Sampling enabled"],
23
- });
27
+ assert.match(html, /<!doctype html>/);
28
+ assert.match(html, /Content-Security-Policy/);
29
+ assert.match(html, /Pi agent trace/);
30
+ assert.match(html, /portable-worker/);
31
+ assert.match(html, /Request observed/);
32
+ assert.match(html, /turn · Pi agent trace/);
33
+ });
24
34
 
25
- assert.match(html, /<!doctype html>/);
26
- assert.match(html, /Content-Security-Policy/);
27
- assert.match(html, new RegExp(`${mode} report`));
28
- assert.match(html, /portable-worker/);
29
- assert.match(html, /Request observed/);
30
- });
31
- }
35
+ test("supports turn, thread, and service scopes", () => {
36
+ for (const level of ["turn", "thread", "service"]) {
37
+ const html = renderReportHtml(report({ scope: { level } }));
38
+ assert.match(html, new RegExp(`${level} · Pi agent trace`));
39
+ }
40
+ });
32
41
 
33
42
  test("escapes report values instead of emitting executable markup", () => {
34
- const html = renderReportHtml({
35
- mode: "trace",
36
- title: "<script>alert(1)</script>",
37
- verdict: { label: "partial", summary: "<img src=x onerror=alert(1)>" },
38
- evidence: [{ id: "E1", summary: "<b>unsafe</b>" }],
39
- });
43
+ const html = renderReportHtml(
44
+ report({
45
+ title: "<script>alert(1)</script>",
46
+ verdict: { label: "partial", summary: "<img src=x onerror=alert(1)>" },
47
+ evidence: [{ id: "E1", summary: "<b>unsafe</b>" }],
48
+ }),
49
+ );
40
50
 
41
51
  assert.doesNotMatch(html, /<script>alert/);
42
52
  assert.doesNotMatch(html, /<img src=x/);
@@ -44,22 +54,26 @@ test("escapes report values instead of emitting executable markup", () => {
44
54
  assert.match(html, /&lt;b&gt;unsafe&lt;\/b&gt;/);
45
55
  });
46
56
 
47
- test("rejects unknown report modes and schema versions", () => {
48
- assert.throws(() => validateReport({ mode: "repair" }), /Report mode/);
49
- assert.throws(() => validateReport({ mode: "health", schemaVersion: 2 }), /schemaVersion/);
57
+ test("rejects legacy modes, unknown scopes, and schema versions", () => {
58
+ assert.throws(
59
+ () => validateReport({ ...report(), kind: undefined, mode: "health" }),
60
+ /Report kind/,
61
+ );
62
+ assert.throws(() => validateReport(report({ scope: { level: "repair" } })), /scope.level/);
63
+ assert.throws(() => validateReport(report({ schemaVersion: 1 })), /schemaVersion/);
50
64
  });
51
65
 
52
66
  test("CLI writes the report beside JSON by default", async () => {
53
67
  const directory = await mkdtemp(join(tmpdir(), "agent-report-"));
54
68
  try {
55
- const input = join(directory, "health.json");
56
- await writeFile(input, JSON.stringify({ mode: "health", title: "Health review", verdict: { label: "healthy" } }));
69
+ const input = join(directory, "trace.json");
70
+ await writeFile(input, JSON.stringify(report({ title: "Human trace review" })));
57
71
  const script = fileURLToPath(new URL("./render-report.mjs", import.meta.url));
58
72
  const result = spawnSync(process.execPath, [script, input], { encoding: "utf8" });
59
73
  assert.equal(result.status, 0, result.stderr);
60
- const output = join(directory, "health.html");
74
+ const output = join(directory, "trace.html");
61
75
  assert.equal(result.stdout.trim(), output);
62
- assert.match(await readFile(output, "utf8"), /Health review/);
76
+ assert.match(await readFile(output, "utf8"), /Human trace review/);
63
77
  } finally {
64
78
  await rm(directory, { recursive: true, force: true });
65
79
  }
@@ -1,225 +0,0 @@
1
- export type AttributeValue =
2
- | string
3
- | number
4
- | boolean
5
- | readonly string[]
6
- | readonly number[]
7
- | readonly boolean[];
8
-
9
- export interface SpanAttributes {
10
- [name: string]: AttributeValue | undefined;
11
- }
12
-
13
- export type TelemetryStatus =
14
- | { status: "ok" }
15
- | { status: "error"; error?: { name: string; message: string } };
16
-
17
- export interface TelemetryLink {
18
- context: TelemetryContext;
19
- attributes?: SpanAttributes;
20
- }
21
-
22
- export interface TelemetryContext {
23
- startSpan<T>(
24
- options: { name: string; attributes?: SpanAttributes; links?: readonly TelemetryLink[] },
25
- callback: (span: TelemetrySpan) => T | Promise<T>,
26
- ): Promise<T>;
27
- }
28
-
29
- export interface TelemetrySpan extends TelemetryContext {
30
- addLink(link: TelemetryLink): void;
31
- addEvent(name: string, attributes?: SpanAttributes): void;
32
- setAttributes(attributes: SpanAttributes): void;
33
- setStatus(status: TelemetryStatus): void;
34
- }
35
-
36
- export interface CloudflareSpan {
37
- setAttribute(key: string, value: string | number | boolean): this;
38
- setAttributes(
39
- attributes: Record<string, string | number | boolean | undefined>,
40
- ): this;
41
- setStatus(status: { code: "unset" | "ok" | "error"; message?: string }): this;
42
- spanContext(): { traceId: string; spanId: string; traceFlags: number };
43
- }
44
-
45
- export interface CloudflareTracing {
46
- enterSpan<T>(name: string, callback: (span: CloudflareSpan) => T): T;
47
- }
48
-
49
- export interface CloudflareTelemetryOptions {
50
- /** Error messages can contain user/provider content and are redacted by default. */
51
- includeErrorMessages?: boolean;
52
- /** Events are encoded as bounded attributes because Workers custom spans have no event API. */
53
- maxEventsPerSpan?: number;
54
- maxLinksPerSpan?: number;
55
- }
56
-
57
- const DEFAULT_MAX_EVENTS = 32;
58
- const DEFAULT_MAX_LINKS = 16;
59
- const MAX_ERROR_MESSAGE = 500;
60
-
61
- export function createCloudflareTelemetryContext(
62
- tracing: CloudflareTracing,
63
- options: CloudflareTelemetryOptions = {},
64
- ): TelemetryContext {
65
- return new CloudflareTelemetryContext(tracing, {
66
- includeErrorMessages: options.includeErrorMessages ?? false,
67
- maxEventsPerSpan: options.maxEventsPerSpan ?? DEFAULT_MAX_EVENTS,
68
- maxLinksPerSpan: options.maxLinksPerSpan ?? DEFAULT_MAX_LINKS,
69
- });
70
- }
71
-
72
- interface ResolvedOptions {
73
- includeErrorMessages: boolean;
74
- maxEventsPerSpan: number;
75
- maxLinksPerSpan: number;
76
- }
77
-
78
- class CloudflareTelemetryContext implements TelemetryContext {
79
- private readonly tracing: CloudflareTracing;
80
- private readonly options: ResolvedOptions;
81
-
82
- constructor(tracing: CloudflareTracing, options: ResolvedOptions) {
83
- this.tracing = tracing;
84
- this.options = options;
85
- }
86
-
87
- async startSpan<T>(
88
- options: { name: string; attributes?: SpanAttributes; links?: readonly TelemetryLink[] },
89
- callback: (span: TelemetrySpan) => T | Promise<T>,
90
- ): Promise<T> {
91
- return await this.tracing.enterSpan(options.name, (nativeSpan) => {
92
- const span = new CloudflareTelemetrySpan(this.tracing, nativeSpan, this.options);
93
- if (options.attributes) span.setAttributes(options.attributes);
94
- for (const link of options.links ?? []) span.addLink(link);
95
-
96
- let result: T | Promise<T>;
97
- try {
98
- result = callback(span);
99
- } catch (error) {
100
- span.finishError(error);
101
- return Promise.reject(error);
102
- }
103
-
104
- return Promise.resolve(result).then(
105
- (value) => {
106
- span.finishSuccess();
107
- return value;
108
- },
109
- (error: unknown) => {
110
- span.finishError(error);
111
- throw error;
112
- },
113
- );
114
- });
115
- }
116
- }
117
-
118
- class CloudflareTelemetrySpan implements TelemetrySpan {
119
- private settled = false;
120
- private explicitStatus = false;
121
- private eventCount = 0;
122
- private linkCount = 0;
123
- private readonly tracing: CloudflareTracing;
124
- private readonly nativeSpan: CloudflareSpan;
125
- private readonly options: ResolvedOptions;
126
-
127
- constructor(
128
- tracing: CloudflareTracing,
129
- nativeSpan: CloudflareSpan,
130
- options: ResolvedOptions,
131
- ) {
132
- this.tracing = tracing;
133
- this.nativeSpan = nativeSpan;
134
- this.options = options;
135
- }
136
-
137
- startSpan<T>(
138
- options: { name: string; attributes?: SpanAttributes; links?: readonly TelemetryLink[] },
139
- callback: (span: TelemetrySpan) => T | Promise<T>,
140
- ): Promise<T> {
141
- return new CloudflareTelemetryContext(this.tracing, this.options).startSpan(options, callback);
142
- }
143
-
144
- addLink(link: TelemetryLink): void {
145
- if (this.settled || this.linkCount >= this.options.maxLinksPerSpan) return;
146
- if (!(link.context instanceof CloudflareTelemetrySpan)) return;
147
-
148
- const index = this.linkCount++;
149
- const context = link.context.nativeSpan.spanContext();
150
- this.nativeSpan.setAttributes({
151
- [`link.${index}.trace_id`]: context.traceId,
152
- [`link.${index}.span_id`]: context.spanId,
153
- ...prefixAttributes(`link.${index}.attribute.`, link.attributes),
154
- });
155
- }
156
-
157
- addEvent(name: string, attributes?: SpanAttributes): void {
158
- if (this.settled || this.eventCount >= this.options.maxEventsPerSpan) return;
159
- const index = this.eventCount++;
160
- this.nativeSpan.setAttributes({
161
- [`event.${index}.name`]: name,
162
- ...prefixAttributes(`event.${index}.attribute.`, attributes),
163
- });
164
- }
165
-
166
- setAttributes(attributes: SpanAttributes): void {
167
- if (this.settled) return;
168
- this.nativeSpan.setAttributes(normalizeAttributes(attributes));
169
- }
170
-
171
- setStatus(status: TelemetryStatus): void {
172
- if (this.settled) return;
173
- this.explicitStatus = true;
174
- if (status.status === "ok") {
175
- this.nativeSpan.setStatus({ code: "ok" });
176
- return;
177
- }
178
-
179
- const message = this.options.includeErrorMessages
180
- ? status.error?.message.slice(0, MAX_ERROR_MESSAGE)
181
- : undefined;
182
- this.nativeSpan.setAttributes({ "error.name": status.error?.name });
183
- this.nativeSpan.setStatus({ code: "error", ...(message ? { message } : {}) });
184
- }
185
-
186
- finishSuccess(): void {
187
- if (this.settled) return;
188
- if (!this.explicitStatus) this.nativeSpan.setStatus({ code: "ok" });
189
- this.settled = true;
190
- }
191
-
192
- finishError(error: unknown): void {
193
- if (this.settled) return;
194
- const name = error instanceof Error ? error.name : "UnknownError";
195
- const message =
196
- this.options.includeErrorMessages && error instanceof Error
197
- ? error.message.slice(0, MAX_ERROR_MESSAGE)
198
- : undefined;
199
- this.nativeSpan.setAttributes({ "error.name": name });
200
- this.nativeSpan.setStatus({ code: "error", ...(message ? { message } : {}) });
201
- this.settled = true;
202
- }
203
- }
204
-
205
- function normalizeAttributes(
206
- attributes: SpanAttributes | undefined,
207
- ): Record<string, string | number | boolean | undefined> {
208
- const normalized: Record<string, string | number | boolean | undefined> = {};
209
- for (const [name, value] of Object.entries(attributes ?? {})) {
210
- normalized[name] =
211
- value !== undefined && typeof value === "object" ? JSON.stringify(value) : value;
212
- }
213
- return normalized;
214
- }
215
-
216
- function prefixAttributes(
217
- prefix: string,
218
- attributes: SpanAttributes | undefined,
219
- ): Record<string, string | number | boolean | undefined> {
220
- const prefixed: Record<string, string | number | boolean | undefined> = {};
221
- for (const [name, value] of Object.entries(normalizeAttributes(attributes))) {
222
- prefixed[`${prefix}${name}`] = value;
223
- }
224
- return prefixed;
225
- }