pi-cloudflare-agent-tracing 0.1.0 → 0.2.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.
package/README.md CHANGED
@@ -62,7 +62,7 @@ pi install /absolute/path/to/pi-cloudflare-agent-tracing
62
62
  The same package can be installed from Git:
63
63
 
64
64
  ```bash
65
- pi install git:github.com/oskarcode/pi-cloudflare-agent-tracing@v0.1.0
65
+ pi install git:github.com/oskarcode/pi-cloudflare-agent-tracing@v0.2.0
66
66
  ```
67
67
 
68
68
  Use a pinned release tag or commit for reproducible investigations.
@@ -92,6 +92,18 @@ Then run, for example:
92
92
  /agent-incident my-worker last 15m
93
93
  ```
94
94
 
95
+ Add `--html` to save a detailed human-review bundle:
96
+
97
+ ```text
98
+ /agent-health my-worker last 6h --html
99
+ /agent-trace ray-id --html
100
+ /agent-cost my-worker last 24h --html
101
+ /agent-eval submission 42 --html
102
+ /agent-incident my-worker last 30m --html
103
+ ```
104
+
105
+ Each saved report produces matching `.md`, content-free `.json`, and standalone `.html` files under the target project's `.pi/agent-tracing-reports/`. The HTML is printable, responsive, self-contained, uses no remote assets, and renders the same bounded evidence as the Markdown and JSON versions.
106
+
95
107
  ## How it works
96
108
 
97
109
  ```text
@@ -146,6 +158,30 @@ node skills/cloudflare-agent-tracing/scripts/evaluate.mjs /tmp/evidence.json
146
158
 
147
159
  Deterministic evidence checks submission settlement, final answer presence, required tools, required durable effects, constraints, and terminal failures. Semantic evidence is optional; without authorized semantic evidence, a deterministic pass can remain `indeterminate`.
148
160
 
161
+ ## Human-review HTML reports
162
+
163
+ All five investigation modes use one normalized report schema. See:
164
+
165
+ ```text
166
+ skills/cloudflare-agent-tracing/references/report.example.json
167
+ ```
168
+
169
+ Render a normalized report directly:
170
+
171
+ ```bash
172
+ node skills/cloudflare-agent-tracing/scripts/render-report.mjs \
173
+ path/to/report.json \
174
+ --out path/to/report.html
175
+ ```
176
+
177
+ If `--out` is omitted, the renderer writes beside the JSON input with an `.html` extension. The renderer validates the schema version and mode, caps CLI input at 2 MB, escapes every displayed value, and emits a restrictive content security policy. Unknown JSON fields are not rendered, reducing the risk of accidentally exposing unrelated diagnostic data.
178
+
179
+ Saved reports should remain content-free and should normally be ignored by Git:
180
+
181
+ ```gitignore
182
+ .pi/agent-tracing-reports/
183
+ ```
184
+
149
185
  ## Optional application diagnostics
150
186
 
151
187
  The package intentionally has no project-specific transcript reader. A target application may expose an existing narrow, authorized diagnostic export. Keep raw output in `/tmp`, summarize it locally, and remove it.
@@ -198,7 +234,9 @@ The suite uses Node's built-in test runner and covers extension registration, re
198
234
  extensions/cloudflare-agent-tracing.ts
199
235
  skills/cloudflare-agent-tracing/SKILL.md
200
236
  skills/cloudflare-agent-tracing/scripts/
237
+ render-report.mjs
201
238
  skills/cloudflare-agent-tracing/references/
239
+ report.example.json
202
240
  runtime/cloudflare-telemetry-context.ts
203
241
  test/extension.test.mjs
204
242
  ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-cloudflare-agent-tracing",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Read-only Cloudflare observability, health, cost, incident, and fulfillment workflows for Pi Durable projects.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -34,7 +34,8 @@
34
34
  },
35
35
  "scripts": {
36
36
  "test": "node --test test/*.test.mjs runtime/*.test.mjs skills/cloudflare-agent-tracing/scripts/*.test.mjs",
37
- "profile": "node skills/cloudflare-agent-tracing/scripts/project-profile.mjs"
37
+ "profile": "node skills/cloudflare-agent-tracing/scripts/project-profile.mjs",
38
+ "render-report": "node skills/cloudflare-agent-tracing/scripts/render-report.mjs"
38
39
  },
39
40
  "files": [
40
41
  "extensions",
@@ -4,7 +4,7 @@ description: Investigate Pi Durable and other agent applications on Cloudflare u
4
4
  compatibility: Requires Node.js 22+, a Cloudflare account available through the official Cloudflare MCP, and a local Cloudflare Worker project or an explicit Worker target.
5
5
  metadata:
6
6
  author: oskarcode
7
- version: "0.1.0"
7
+ version: "0.2.0"
8
8
  ---
9
9
 
10
10
  # Cloudflare agent tracing
@@ -15,7 +15,7 @@ Resolve relative paths in this skill against the directory containing this `SKIL
15
15
 
16
16
  ## Inputs
17
17
 
18
- Interpret the first argument as one of `trace`, `health`, `cost`, `evaluate`, or `incident`. The rest identifies a Worker, request/Ray/trace/conversation/submission ID, deployment, or bounded time range. If the target is ambiguous, profile the local project before asking one focused question.
18
+ Interpret the first argument as one of `trace`, `health`, `cost`, `evaluate`, or `incident`. The rest identifies a Worker, request/Ray/trace/conversation/submission ID, deployment, or bounded time range. `--html` requests a saved human-review bundle and is not part of the target. If the target is ambiguous, profile the local project before asking one focused question.
19
19
 
20
20
  ## Start locally
21
21
 
@@ -124,4 +124,20 @@ Return a concise report with:
124
124
 
125
125
  Distinguish observations from hypotheses. Every conclusion must name its evidence. Local source inspection alone is not production verification.
126
126
 
127
- When asked to save a report, write Markdown and content-free JSON under the target project's `.pi/agent-tracing-reports/`. Never save transcript text there.
127
+ Always return the concise report in the conversation. When the command includes `--html`, or the user asks to save the report:
128
+
129
+ 1. Create `.pi/agent-tracing-reports/` under the target project.
130
+ 2. Use one collision-resistant basename: `<UTC timestamp>-<mode>-<safe target slug>`.
131
+ 3. Write the concise Markdown report to `<basename>.md`.
132
+ 4. Write normalized, content-free JSON to `<basename>.json` using `references/report.example.json` as the schema example. Use `schemaVersion: 1` and the current mode. Omit unavailable sections rather than inventing values.
133
+ 5. Render the standalone HTML report:
134
+
135
+ ```bash
136
+ node <skill-directory>/scripts/render-report.mjs \
137
+ <project>/.pi/agent-tracing-reports/<basename>.json \
138
+ --out <project>/.pi/agent-tracing-reports/<basename>.html
139
+ ```
140
+
141
+ 6. Return all three paths and state that the HTML contains the same bounded evidence, not additional private data.
142
+
143
+ The HTML renderer supports every report mode, is printable, embeds no remote assets, applies a restrictive content security policy, and escapes all report values. Never put prompts, answers, thinking, tool arguments/results, credentials, headers, attachment contents, or raw transcript text in any report format. Recommend ignoring `.pi/agent-tracing-reports/` in Git.
@@ -0,0 +1,103 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "mode": "incident",
4
+ "title": "Checkout agent incident",
5
+ "generatedAt": "2026-12-02T17:30:00Z",
6
+ "verdict": {
7
+ "label": "partial",
8
+ "confidence": "high",
9
+ "summary": "Requests recovered after a bounded model-provider failure, but two submissions were cancelled."
10
+ },
11
+ "scope": {
12
+ "worker": "checkout-agent",
13
+ "environment": "production",
14
+ "deployment": "version-id",
15
+ "target": "incident-window",
16
+ "startUtc": "2026-12-02T17:00:00Z",
17
+ "endUtc": "2026-12-02T17:30:00Z"
18
+ },
19
+ "metrics": [
20
+ { "label": "Successful requests", "value": 147, "status": "healthy" },
21
+ { "label": "Cancelled requests", "value": 2, "status": "warning" },
22
+ { "label": "p95 wall time", "value": 935, "unit": "ms" }
23
+ ],
24
+ "requestPath": [
25
+ {
26
+ "stage": "Worker request",
27
+ "status": "succeeded",
28
+ "timestampUtc": "2026-12-02T17:12:03Z",
29
+ "durationMs": 42,
30
+ "detail": "The edge request reached the active Worker version.",
31
+ "evidenceIds": ["E1"]
32
+ }
33
+ ],
34
+ "failures": [
35
+ {
36
+ "severity": "medium",
37
+ "status": "recovered",
38
+ "title": "Provider timeout",
39
+ "detail": "One bounded provider call timed out.",
40
+ "recovery": "Pi Durable resumed the committed submission.",
41
+ "evidenceIds": ["E2"]
42
+ }
43
+ ],
44
+ "latency": {
45
+ "summary": "Successful requests remained within the expected range.",
46
+ "metrics": [
47
+ { "label": "p95 wall time", "value": 935, "unit": "ms", "source": "Workers observability" }
48
+ ]
49
+ },
50
+ "cost": {
51
+ "summary": "No authoritative provider cost was available.",
52
+ "completeness": "incomplete",
53
+ "source": "sampled traces"
54
+ },
55
+ "fulfillment": {
56
+ "verdict": "indeterminate",
57
+ "score": 100,
58
+ "semanticEvidence": "unavailable",
59
+ "summary": "Deterministic checks passed; semantic request content was not inspected.",
60
+ "checks": [
61
+ { "name": "submission settled", "passed": true, "evidence": "E3" }
62
+ ]
63
+ },
64
+ "durableState": [
65
+ {
66
+ "owner": "Session Durable Object",
67
+ "record": "submission",
68
+ "status": "done",
69
+ "summary": "Committed completion was observed through an authorized diagnostic.",
70
+ "evidenceId": "E3"
71
+ }
72
+ ],
73
+ "recommendations": [
74
+ {
75
+ "priority": "P1",
76
+ "title": "Correlate provider timeouts",
77
+ "detail": "Add content-free provider request identifiers to custom telemetry.",
78
+ "evidenceId": "E2"
79
+ }
80
+ ],
81
+ "evidence": [
82
+ {
83
+ "id": "E1",
84
+ "type": "Workers trace",
85
+ "source": "Cloudflare observability",
86
+ "observedAt": "2026-12-02T17:32:00Z",
87
+ "summary": "Successful Worker request",
88
+ "correlation": "exact trace ID"
89
+ },
90
+ {
91
+ "id": "E2",
92
+ "type": "Pi telemetry",
93
+ "source": "custom span",
94
+ "observedAt": "2026-12-02T17:32:00Z",
95
+ "summary": "Provider timeout followed by recovery",
96
+ "limitation": "The sampled trace does not establish complete incident totals."
97
+ }
98
+ ],
99
+ "limitations": [
100
+ "Trace sampling may omit requests.",
101
+ "No private request or answer content was inspected."
102
+ ]
103
+ }
@@ -0,0 +1,260 @@
1
+ #!/usr/bin/env node
2
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
3
+ import { dirname, extname, resolve } from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+
6
+ const MODES = new Set(["trace", "health", "cost", "evaluate", "incident"]);
7
+ const MAX_INPUT_BYTES = 2_000_000;
8
+
9
+ if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
10
+ try {
11
+ const { input, output } = parseArguments(process.argv.slice(2));
12
+ const source = await readFile(input, "utf8");
13
+ if (Buffer.byteLength(source) > MAX_INPUT_BYTES) {
14
+ throw new Error(`Report JSON exceeds ${MAX_INPUT_BYTES} bytes`);
15
+ }
16
+ const report = JSON.parse(source);
17
+ const destination = resolve(output ?? replaceExtension(input, ".html"));
18
+ await mkdir(dirname(destination), { recursive: true });
19
+ await writeFile(destination, renderReportHtml(report), "utf8");
20
+ console.log(destination);
21
+ } catch (error) {
22
+ console.error(error instanceof Error ? error.message : String(error));
23
+ process.exitCode = 2;
24
+ }
25
+ }
26
+
27
+ export function renderReportHtml(report) {
28
+ validateReport(report);
29
+ const mode = report.mode;
30
+ const verdict = asObject(report.verdict);
31
+ const verdictLabel = text(verdict.label, "Indeterminate");
32
+ const confidence = text(verdict.confidence, "not stated");
33
+ const generatedAt = text(report.generatedAt, new Date().toISOString());
34
+ const title = text(report.title, `${capitalize(mode)} report`);
35
+ const sections = [
36
+ renderScope(report.scope),
37
+ renderMetrics(report.metrics),
38
+ renderRequestPath(report.requestPath),
39
+ renderFailures(report.failures),
40
+ renderLatency(report.latency),
41
+ renderCost(report.cost),
42
+ renderFulfillment(report.fulfillment),
43
+ renderDurableState(report.durableState),
44
+ renderRecommendations(report.recommendations),
45
+ renderEvidence(report.evidence),
46
+ renderLimitations(report.limitations),
47
+ ].filter(Boolean);
48
+
49
+ return `<!doctype html>
50
+ <html lang="en">
51
+ <head>
52
+ <meta charset="utf-8">
53
+ <meta name="viewport" content="width=device-width,initial-scale=1">
54
+ <meta name="color-scheme" content="light dark">
55
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; img-src data:; base-uri 'none'; form-action 'none'">
56
+ <title>${escapeHtml(title)}</title>
57
+ <style>
58
+ :root{color-scheme:light dark;--bg:#f5f7fb;--panel:#fff;--ink:#172033;--muted:#5e687c;--line:#dce2ec;--accent:#3157d5;--good:#08795b;--warn:#a15c00;--bad:#b42318;--shadow:0 12px 32px rgba(23,32,51,.08)}
59
+ @media(prefers-color-scheme:dark){:root{--bg:#10141d;--panel:#181e29;--ink:#edf1f8;--muted:#aab3c3;--line:#303949;--accent:#8ba6ff;--good:#62d4ad;--warn:#ffc166;--bad:#ff8a82;--shadow:none}}
60
+ *{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:15px/1.55 ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}main{width:min(1120px,calc(100% - 32px));margin:32px auto 64px}.hero,.section{background:var(--panel);border:1px solid var(--line);border-radius:16px;box-shadow:var(--shadow)}.hero{padding:28px}.eyebrow{margin:0 0 6px;color:var(--accent);font-size:12px;font-weight:750;letter-spacing:.09em;text-transform:uppercase}h1{margin:0;font-size:clamp(28px,5vw,46px);line-height:1.1}h2{margin:0;font-size:20px}h3{margin:0 0 5px;font-size:15px}.subtitle{max-width:780px;margin:14px 0 0;color:var(--muted);font-size:16px}.hero-grid,.metric-grid,.scope-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:12px;margin-top:22px}.stat,.scope-item{padding:14px;border:1px solid var(--line);border-radius:12px;background:color-mix(in srgb,var(--panel) 92%,var(--accent) 8%)}.label{display:block;color:var(--muted);font-size:11px;font-weight:700;letter-spacing:.06em;text-transform:uppercase}.value{display:block;margin-top:4px;font-weight:700;overflow-wrap:anywhere}.section{margin-top:18px;padding:22px}.section-head{display:flex;align-items:baseline;justify-content:space-between;gap:14px;margin-bottom:15px}.count{color:var(--muted);font-size:13px}.cards{display:grid;gap:12px}.card{padding:15px;border:1px solid var(--line);border-radius:12px}.card p{margin:6px 0 0;color:var(--muted)}.meta{display:flex;flex-wrap:wrap;gap:7px;margin-top:10px}.chip{display:inline-flex;padding:3px 8px;border:1px solid var(--line);border-radius:999px;color:var(--muted);font-size:12px}.status-good{color:var(--good)}.status-warn{color:var(--warn)}.status-bad{color:var(--bad)}.timeline{position:relative;display:grid;gap:0;margin-left:8px}.timeline:before{content:"";position:absolute;left:7px;top:12px;bottom:12px;width:2px;background:var(--line)}.timeline-item{position:relative;padding:0 0 20px 30px}.timeline-item:last-child{padding-bottom:0}.dot{position:absolute;left:0;top:6px;width:16px;height:16px;border:4px solid var(--panel);border-radius:50%;background:var(--accent);box-shadow:0 0 0 1px var(--line)}table{width:100%;border-collapse:collapse}th,td{padding:10px;border-bottom:1px solid var(--line);text-align:left;vertical-align:top;overflow-wrap:anywhere}th{color:var(--muted);font-size:11px;letter-spacing:.05em;text-transform:uppercase}.table-wrap{overflow-x:auto}details{border:1px solid var(--line);border-radius:10px;padding:10px 12px}details+details{margin-top:8px}summary{cursor:pointer;font-weight:700}.empty{color:var(--muted);font-style:italic}.footer{margin-top:18px;color:var(--muted);font-size:12px;text-align:center}.mono{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:13px}.check{font-weight:800}.check.pass{color:var(--good)}.check.fail{color:var(--bad)}
61
+ @media print{body{background:#fff;color:#111}main{width:100%;margin:0}.hero,.section{break-inside:avoid;box-shadow:none}.section{margin-top:12px}details{break-inside:avoid}}
62
+ </style>
63
+ </head>
64
+ <body>
65
+ <main>
66
+ <header class="hero">
67
+ <p class="eyebrow">${escapeHtml(mode)} · Cloudflare agent tracing</p>
68
+ <h1>${escapeHtml(title)}</h1>
69
+ <p class="subtitle">${escapeHtml(text(verdict.summary, "Evidence-backed report for human review."))}</p>
70
+ <div class="hero-grid">
71
+ ${stat("Verdict", verdictLabel, statusClass(verdictLabel))}
72
+ ${stat("Confidence", confidence)}
73
+ ${stat("Generated", formatTimestamp(generatedAt))}
74
+ ${stat("Schema", text(report.schemaVersion, "1"))}
75
+ </div>
76
+ </header>
77
+ ${sections.join("\n")}
78
+ <p class="footer">Generated from bounded, content-safe evidence. Re-check source systems before acting on time-sensitive findings.</p>
79
+ </main>
80
+ </body>
81
+ </html>`;
82
+ }
83
+
84
+ 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");
88
+ }
89
+
90
+ function renderScope(scopeValue) {
91
+ const scope = asObject(scopeValue);
92
+ const entries = [
93
+ ["Worker", scope.worker], ["Environment", scope.environment], ["Deployment", scope.deployment],
94
+ ["Target", scope.target], ["Start UTC", scope.startUtc], ["End UTC", scope.endUtc],
95
+ ].filter(([, value]) => present(value));
96
+ 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>`);
98
+ }
99
+
100
+ function renderMetrics(metrics) {
101
+ 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("");
107
+ return section("Key metrics", `<div class="metric-grid">${cards}</div>`, metrics.length);
108
+ }
109
+
110
+ function renderRequestPath(items) {
111
+ 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("");
116
+ return section("Request path", `<div class="timeline">${timeline}</div>`, items.length);
117
+ }
118
+
119
+ function renderFailures(items) {
120
+ 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);
125
+ }
126
+
127
+ function renderLatency(value) {
128
+ const latency = asObject(value);
129
+ const metrics = array(latency.metrics);
130
+ if (!present(latency.summary) && metrics.length === 0) return "";
131
+ return section("Latency", `${paragraph(latency.summary)}${renderSimpleTable(metrics, ["label", "value", "unit", "source"])}`);
132
+ }
133
+
134
+ function renderCost(value) {
135
+ const cost = asObject(value);
136
+ const items = array(cost.items);
137
+ if (!present(cost.total) && !present(cost.summary) && items.length === 0) return "";
138
+ const overview = `<div class="scope-grid">${[
139
+ ["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"])}`);
143
+ }
144
+
145
+ function renderFulfillment(value) {
146
+ const fulfillment = asObject(value);
147
+ const checks = array(fulfillment.checks);
148
+ if (!present(fulfillment.verdict) && checks.length === 0) return "";
149
+ 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>` : "";
153
+ return section("Fulfillment", `${paragraph(fulfillment.summary)}${header}${rows}`);
154
+ }
155
+
156
+ function renderDurableState(items) {
157
+ if (!Array.isArray(items) || items.length === 0) return "";
158
+ return section("Durable state evidence", renderSimpleTable(items, ["owner", "record", "status", "summary", "evidenceId"]), items.length);
159
+ }
160
+
161
+ function renderRecommendations(items) {
162
+ 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);
164
+ }
165
+
166
+ function renderEvidence(items) {
167
+ 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("");
172
+ return section("Evidence", details, items.length);
173
+ }
174
+
175
+ function renderLimitations(items) {
176
+ 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);
178
+ }
179
+
180
+ function renderSimpleTable(items, keys) {
181
+ 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>`;
183
+ }
184
+
185
+ function section(title, body, count) {
186
+ return `<section class="section"><div class="section-head"><h2>${escapeHtml(title)}</h2>${Number.isFinite(count) ? `<span class="count">${count} item${count === 1 ? "" : "s"}</span>` : ""}</div>${body}</section>`;
187
+ }
188
+
189
+ function stat(label, value, className = "") {
190
+ return `<div class="stat"><span class="label">${escapeHtml(label)}</span><span class="value ${className}">${escapeHtml(text(value))}</span></div>`;
191
+ }
192
+
193
+ function paragraph(value) {
194
+ return present(value) ? `<p>${escapeHtml(text(value))}</p>` : "";
195
+ }
196
+
197
+ function chips(values) {
198
+ return values.filter(present).map((value) => `<span class="chip">${escapeHtml(text(value))}</span>`).join("");
199
+ }
200
+
201
+ function duration(value) {
202
+ return Number.isFinite(value) ? `${value} ms` : "";
203
+ }
204
+
205
+ function statusClass(value) {
206
+ const normalized = text(value).toLowerCase();
207
+ if (/fulfilled|healthy|success|succeeded|done|recovered|verified|low|complete/.test(normalized)) return "status-good";
208
+ 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";
210
+ return "";
211
+ }
212
+
213
+ function formatTimestamp(value) {
214
+ const date = new Date(value);
215
+ return Number.isNaN(date.valueOf()) ? value : date.toISOString().replace("T", " ").replace(".000Z", " UTC");
216
+ }
217
+
218
+ function parseArguments(args) {
219
+ const input = args[0];
220
+ if (!input || input === "--help") throw new Error("Usage: node render-report.mjs <report.json> [--out <report.html>]");
221
+ const outIndex = args.indexOf("--out");
222
+ if (outIndex >= 0 && !args[outIndex + 1]) throw new Error("--out requires a path");
223
+ return { input: resolve(input), output: outIndex >= 0 ? args[outIndex + 1] : undefined };
224
+ }
225
+
226
+ function replaceExtension(path, extension) {
227
+ const current = extname(path);
228
+ return current ? path.slice(0, -current.length) + extension : path + extension;
229
+ }
230
+
231
+ function asObject(value) {
232
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
233
+ }
234
+
235
+ function array(value) {
236
+ return Array.isArray(value) ? value : [];
237
+ }
238
+
239
+ function present(value) {
240
+ return value !== undefined && value !== null && text(value).trim() !== "";
241
+ }
242
+
243
+ function text(value, fallback = "") {
244
+ if (value === undefined || value === null) return fallback;
245
+ if (typeof value === "string") return value;
246
+ if (["number", "boolean", "bigint"].includes(typeof value)) return String(value);
247
+ return fallback;
248
+ }
249
+
250
+ 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;
256
+ }
257
+
258
+ function titleCase(value) {
259
+ return value.replace(/([A-Z])/g, " $1").replace(/^./, (character) => character.toUpperCase());
260
+ }
@@ -0,0 +1,66 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { spawnSync } from "node:child_process";
6
+ import { fileURLToPath } from "node:url";
7
+ import test from "node:test";
8
+ import { renderReportHtml, validateReport } from "./render-report.mjs";
9
+
10
+ const modes = ["trace", "health", "cost", "evaluate", "incident"];
11
+
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
+ });
24
+
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
+ }
32
+
33
+ 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
+ });
40
+
41
+ assert.doesNotMatch(html, /<script>alert/);
42
+ assert.doesNotMatch(html, /<img src=x/);
43
+ assert.match(html, /&lt;script&gt;alert\(1\)&lt;\/script&gt;/);
44
+ assert.match(html, /&lt;b&gt;unsafe&lt;\/b&gt;/);
45
+ });
46
+
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/);
50
+ });
51
+
52
+ test("CLI writes the report beside JSON by default", async () => {
53
+ const directory = await mkdtemp(join(tmpdir(), "agent-report-"));
54
+ try {
55
+ const input = join(directory, "health.json");
56
+ await writeFile(input, JSON.stringify({ mode: "health", title: "Health review", verdict: { label: "healthy" } }));
57
+ const script = fileURLToPath(new URL("./render-report.mjs", import.meta.url));
58
+ const result = spawnSync(process.execPath, [script, input], { encoding: "utf8" });
59
+ assert.equal(result.status, 0, result.stderr);
60
+ const output = join(directory, "health.html");
61
+ assert.equal(result.stdout.trim(), output);
62
+ assert.match(await readFile(output, "utf8"), /Health review/);
63
+ } finally {
64
+ await rm(directory, { recursive: true, force: true });
65
+ }
66
+ });