pi-cloudflare-agent-tracing 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +250 -2
- package/extensions/cloudflare-agent-tracing.ts +107 -0
- package/package.json +48 -4
- package/runtime/README.md +29 -0
- package/runtime/cloudflare-telemetry-context.test.mjs +89 -0
- package/runtime/cloudflare-telemetry-context.ts +225 -0
- package/skills/cloudflare-agent-tracing/SKILL.md +143 -0
- package/skills/cloudflare-agent-tracing/references/evaluation-input.example.json +24 -0
- package/skills/cloudflare-agent-tracing/references/report.example.json +103 -0
- package/skills/cloudflare-agent-tracing/scripts/evaluate.mjs +79 -0
- package/skills/cloudflare-agent-tracing/scripts/evaluate.test.mjs +38 -0
- package/skills/cloudflare-agent-tracing/scripts/project-profile.mjs +237 -0
- package/skills/cloudflare-agent-tracing/scripts/project-profile.test.mjs +88 -0
- package/skills/cloudflare-agent-tracing/scripts/render-report.mjs +260 -0
- package/skills/cloudflare-agent-tracing/scripts/render-report.test.mjs +66 -0
- package/skills/cloudflare-agent-tracing/scripts/summarize-session-context.mjs +92 -0
- package/skills/cloudflare-agent-tracing/scripts/summarize-session-context.test.mjs +46 -0
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readdir, readFile, stat } from "node:fs/promises";
|
|
3
|
+
import { dirname, extname, join, relative, resolve } from "node:path";
|
|
4
|
+
import { pathToFileURL } from "node:url";
|
|
5
|
+
|
|
6
|
+
const DEFAULT_CONFIG_NAMES = ["wrangler.jsonc", "wrangler.json", "wrangler.toml"];
|
|
7
|
+
const EXCLUDED_DIRECTORIES = new Set([
|
|
8
|
+
".git",
|
|
9
|
+
".wrangler",
|
|
10
|
+
"dist",
|
|
11
|
+
"build",
|
|
12
|
+
"coverage",
|
|
13
|
+
"node_modules",
|
|
14
|
+
".next",
|
|
15
|
+
".output",
|
|
16
|
+
"vendor",
|
|
17
|
+
"test",
|
|
18
|
+
"tests",
|
|
19
|
+
"__tests__",
|
|
20
|
+
]);
|
|
21
|
+
const SOURCE_EXTENSIONS = new Set([".ts", ".tsx", ".js", ".jsx", ".mts", ".mjs"]);
|
|
22
|
+
const MAX_CONFIG_DEPTH = 4;
|
|
23
|
+
const MAX_SOURCE_FILES = 1_000;
|
|
24
|
+
const MAX_SOURCE_BYTES = 2_000_000;
|
|
25
|
+
|
|
26
|
+
export async function profileProject(options = {}) {
|
|
27
|
+
const cwd = resolve(options.cwd ?? process.cwd());
|
|
28
|
+
const explicitConfig = options.config ? resolve(cwd, options.config) : undefined;
|
|
29
|
+
const candidates = explicitConfig
|
|
30
|
+
? [explicitConfig]
|
|
31
|
+
: await findNamedFiles(cwd, new Set(DEFAULT_CONFIG_NAMES), MAX_CONFIG_DEPTH);
|
|
32
|
+
const configPath = chooseConfig(candidates, cwd);
|
|
33
|
+
const configText = configPath ? await readFile(configPath, "utf8") : "";
|
|
34
|
+
const configFormat = configPath ? extname(configPath).slice(1) : undefined;
|
|
35
|
+
const packagePath = configPath
|
|
36
|
+
? await findUp(dirname(configPath), "package.json", cwd)
|
|
37
|
+
: await findUp(cwd, "package.json", cwd);
|
|
38
|
+
const packageJson = packagePath
|
|
39
|
+
? JSON.parse(await readFile(packagePath, "utf8"))
|
|
40
|
+
: undefined;
|
|
41
|
+
const sourceRoot = configPath ? dirname(configPath) : cwd;
|
|
42
|
+
const sourceEvidence = await inspectSource(sourceRoot);
|
|
43
|
+
|
|
44
|
+
return {
|
|
45
|
+
projectRoot: relative(cwd, sourceRoot) || ".",
|
|
46
|
+
project: packageJson?.name ?? null,
|
|
47
|
+
wranglerConfig: configPath ? relative(cwd, configPath) || configPath : null,
|
|
48
|
+
wranglerCandidates: candidates.map((path) => relative(cwd, path) || path),
|
|
49
|
+
ambiguousConfiguration: !explicitConfig && candidates.length > 1,
|
|
50
|
+
worker: matchConfigString(configText, "name", configFormat),
|
|
51
|
+
main: matchConfigString(configText, "main", configFormat),
|
|
52
|
+
compatibilityDate: matchConfigString(configText, "compatibility_date", configFormat),
|
|
53
|
+
pi: {
|
|
54
|
+
durable: dependencyVersion(packageJson, "@earendil-works/pi-durable"),
|
|
55
|
+
ai: dependencyVersion(packageJson, "@earendil-works/pi-ai"),
|
|
56
|
+
agents: dependencyVersion(packageJson, "agents"),
|
|
57
|
+
},
|
|
58
|
+
observability: {
|
|
59
|
+
enabled: configBoolean(configText, "observability", "enabled"),
|
|
60
|
+
tracesEnabled: configBoolean(configText, "traces", "enabled"),
|
|
61
|
+
},
|
|
62
|
+
bindings: extractBindings(configText),
|
|
63
|
+
harness: sourceEvidence,
|
|
64
|
+
notes: [
|
|
65
|
+
"Configuration and telemetry detection are source heuristics; confirm relevant source before concluding.",
|
|
66
|
+
"Wrangler tracing does not by itself emit Pi Durable or Pi AI custom spans.",
|
|
67
|
+
...(candidates.length === 0
|
|
68
|
+
? ["No Wrangler configuration was found within the bounded project search."]
|
|
69
|
+
: []),
|
|
70
|
+
...(!explicitConfig && candidates.length > 1
|
|
71
|
+
? ["Multiple Wrangler configurations were found; select one with --config."]
|
|
72
|
+
: []),
|
|
73
|
+
],
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function chooseConfig(candidates, cwd) {
|
|
78
|
+
if (candidates.length === 0) return undefined;
|
|
79
|
+
const root = candidates.find((path) => dirname(path) === cwd);
|
|
80
|
+
return root ?? (candidates.length === 1 ? candidates[0] : undefined);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async function inspectSource(root) {
|
|
84
|
+
const files = await findSourceFiles(root);
|
|
85
|
+
const harnessCalls = [];
|
|
86
|
+
let telemetryWired = false;
|
|
87
|
+
for (const path of files) {
|
|
88
|
+
const text = await readFile(path, "utf8").catch(() => "");
|
|
89
|
+
if (!text.includes("Harness.open")) continue;
|
|
90
|
+
const positions = [...text.matchAll(/Harness\.open\s*\(/gu)].map((match) => match.index ?? 0);
|
|
91
|
+
for (const position of positions) {
|
|
92
|
+
const window = text.slice(position, position + 4_000);
|
|
93
|
+
const hasTelemetry = /\btelemetry\s*:/u.test(window);
|
|
94
|
+
telemetryWired ||= hasTelemetry;
|
|
95
|
+
harnessCalls.push({ path: relative(root, path), telemetryOptionDetected: hasTelemetry });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return {
|
|
99
|
+
filesScanned: files.length,
|
|
100
|
+
calls: harnessCalls.slice(0, 20),
|
|
101
|
+
telemetryWired,
|
|
102
|
+
truncated: files.length >= MAX_SOURCE_FILES,
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async function findSourceFiles(root) {
|
|
107
|
+
const results = [];
|
|
108
|
+
const queue = [root];
|
|
109
|
+
while (queue.length > 0 && results.length < MAX_SOURCE_FILES) {
|
|
110
|
+
const directory = queue.shift();
|
|
111
|
+
const entries = await readdir(directory, { withFileTypes: true }).catch(() => []);
|
|
112
|
+
for (const entry of entries) {
|
|
113
|
+
if (results.length >= MAX_SOURCE_FILES) break;
|
|
114
|
+
const path = join(directory, entry.name);
|
|
115
|
+
if (entry.isDirectory()) {
|
|
116
|
+
if (!EXCLUDED_DIRECTORIES.has(entry.name) && !entry.name.startsWith(".")) queue.push(path);
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
if (!entry.isFile() || !SOURCE_EXTENSIONS.has(extname(entry.name))) continue;
|
|
120
|
+
const info = await stat(path).catch(() => undefined);
|
|
121
|
+
if (info && info.size <= MAX_SOURCE_BYTES) results.push(path);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return results;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function findNamedFiles(root, names, maxDepth) {
|
|
128
|
+
const results = [];
|
|
129
|
+
const queue = [{ directory: root, depth: 0 }];
|
|
130
|
+
while (queue.length > 0) {
|
|
131
|
+
const { directory, depth } = queue.shift();
|
|
132
|
+
const entries = await readdir(directory, { withFileTypes: true }).catch(() => []);
|
|
133
|
+
for (const entry of entries) {
|
|
134
|
+
const path = join(directory, entry.name);
|
|
135
|
+
if (entry.isFile() && names.has(entry.name)) results.push(path);
|
|
136
|
+
if (
|
|
137
|
+
entry.isDirectory() &&
|
|
138
|
+
depth < maxDepth &&
|
|
139
|
+
!EXCLUDED_DIRECTORIES.has(entry.name) &&
|
|
140
|
+
!entry.name.startsWith(".")
|
|
141
|
+
) {
|
|
142
|
+
queue.push({ directory: path, depth: depth + 1 });
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return results.sort();
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
async function findUp(start, name, boundary) {
|
|
150
|
+
let directory = resolve(start);
|
|
151
|
+
const stop = resolve(boundary);
|
|
152
|
+
while (directory.startsWith(stop)) {
|
|
153
|
+
const candidate = join(directory, name);
|
|
154
|
+
if (await stat(candidate).then((value) => value.isFile()).catch(() => false)) return candidate;
|
|
155
|
+
if (directory === stop) break;
|
|
156
|
+
directory = dirname(directory);
|
|
157
|
+
}
|
|
158
|
+
return undefined;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function dependencyVersion(packageJson, name) {
|
|
162
|
+
return (
|
|
163
|
+
packageJson?.dependencies?.[name] ??
|
|
164
|
+
packageJson?.devDependencies?.[name] ??
|
|
165
|
+
packageJson?.peerDependencies?.[name] ??
|
|
166
|
+
null
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function matchConfigString(text, key, format) {
|
|
171
|
+
const pattern =
|
|
172
|
+
format === "toml"
|
|
173
|
+
? new RegExp(`^\\s*${escapeRegExp(key)}\\s*=\\s*["']([^"']+)["']`, "mu")
|
|
174
|
+
: new RegExp(`["']${escapeRegExp(key)}["']\\s*:\\s*["']([^"']+)["']`, "u");
|
|
175
|
+
return text.match(pattern)?.[1] ?? null;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function configBoolean(text, section, key) {
|
|
179
|
+
const jsonSection = text.match(
|
|
180
|
+
new RegExp(`["']${escapeRegExp(section)}["']\\s*:\\s*\\{([\\s\\S]*?)\\n\\s*\\}`, "u"),
|
|
181
|
+
)?.[1];
|
|
182
|
+
if (jsonSection && new RegExp(`["']${escapeRegExp(key)}["']\\s*:\\s*true`, "u").test(jsonSection)) {
|
|
183
|
+
return true;
|
|
184
|
+
}
|
|
185
|
+
for (const block of tomlSections(text)) {
|
|
186
|
+
if (block.name !== section && !block.name.endsWith(`.${section}`)) continue;
|
|
187
|
+
if (new RegExp(`^\\s*${escapeRegExp(key)}\\s*=\\s*true`, "mu").test(block.body)) return true;
|
|
188
|
+
}
|
|
189
|
+
return false;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function extractBindings(text) {
|
|
193
|
+
const names = new Set();
|
|
194
|
+
for (const match of text.matchAll(/"binding"\s*:\s*"([^"\n]+)"/gu)) {
|
|
195
|
+
if (match[1]) names.add(match[1]);
|
|
196
|
+
}
|
|
197
|
+
for (const match of text.matchAll(/\{[^{}]*"name"\s*:\s*"([^"\n]+)"[^{}]*"class_name"\s*:/gu)) {
|
|
198
|
+
if (match[1]) names.add(match[1]);
|
|
199
|
+
}
|
|
200
|
+
for (const block of tomlSections(text)) {
|
|
201
|
+
if (!block.name.endsWith("bindings")) continue;
|
|
202
|
+
const name = block.body.match(/^\s*(?:name|binding)\s*=\s*"([^"\n]+)"/mu)?.[1];
|
|
203
|
+
if (name) names.add(name);
|
|
204
|
+
}
|
|
205
|
+
return [...names].sort();
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function tomlSections(text) {
|
|
209
|
+
const headers = [...text.matchAll(/^\s*\[\[?([^\]]+)\]\]?\s*$/gmu)];
|
|
210
|
+
return headers.map((header, index) => ({
|
|
211
|
+
name: header[1]?.trim() ?? "",
|
|
212
|
+
body: text.slice(
|
|
213
|
+
(header.index ?? 0) + header[0].length,
|
|
214
|
+
headers[index + 1]?.index ?? text.length,
|
|
215
|
+
),
|
|
216
|
+
}));
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function escapeRegExp(value) {
|
|
220
|
+
return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function parseArguments(argv) {
|
|
224
|
+
const options = {};
|
|
225
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
226
|
+
const value = argv[index];
|
|
227
|
+
if (value === "--cwd") options.cwd = argv[++index];
|
|
228
|
+
else if (value === "--config") options.config = argv[++index];
|
|
229
|
+
else throw new Error(`Unknown argument: ${value}`);
|
|
230
|
+
}
|
|
231
|
+
return options;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
|
|
235
|
+
const options = parseArguments(process.argv.slice(2));
|
|
236
|
+
console.log(JSON.stringify(await profileProject(options), null, 2));
|
|
237
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import test from "node:test";
|
|
6
|
+
import { profileProject } from "./project-profile.mjs";
|
|
7
|
+
|
|
8
|
+
async function fixture(run) {
|
|
9
|
+
const root = await mkdtemp(join(tmpdir(), "pi-agent-tracing-"));
|
|
10
|
+
try {
|
|
11
|
+
await run(root);
|
|
12
|
+
} finally {
|
|
13
|
+
await rm(root, { recursive: true, force: true });
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
test("profiles a JSONC Pi Durable Worker without project-specific paths", async () => {
|
|
18
|
+
await fixture(async (root) => {
|
|
19
|
+
await mkdir(join(root, "app", "runtime"), { recursive: true });
|
|
20
|
+
await writeFile(
|
|
21
|
+
join(root, "app", "package.json"),
|
|
22
|
+
JSON.stringify({
|
|
23
|
+
name: "portable-agent",
|
|
24
|
+
dependencies: {
|
|
25
|
+
"@earendil-works/pi-durable": "1.5.2",
|
|
26
|
+
"@earendil-works/pi-ai": "1.5.2",
|
|
27
|
+
},
|
|
28
|
+
}),
|
|
29
|
+
);
|
|
30
|
+
await writeFile(
|
|
31
|
+
join(root, "app", "wrangler.jsonc"),
|
|
32
|
+
`{
|
|
33
|
+
"name": "portable-worker",
|
|
34
|
+
"main": "runtime/session.ts",
|
|
35
|
+
"compatibility_date": "2026-01-01",
|
|
36
|
+
"observability": { "enabled": true, "traces": { "enabled": true } },
|
|
37
|
+
"durable_objects": { "bindings": [{ "name": "SESSIONS", "class_name": "Session" }] }
|
|
38
|
+
}`,
|
|
39
|
+
);
|
|
40
|
+
await writeFile(
|
|
41
|
+
join(root, "app", "runtime", "session.ts"),
|
|
42
|
+
`await Harness.open(storage, { ...options, telemetry: tracing }, context);`,
|
|
43
|
+
);
|
|
44
|
+
|
|
45
|
+
const profile = await profileProject({ cwd: join(root, "app") });
|
|
46
|
+
assert.equal(profile.worker, "portable-worker");
|
|
47
|
+
assert.equal(profile.pi.durable, "1.5.2");
|
|
48
|
+
assert.equal(profile.harness.telemetryWired, true);
|
|
49
|
+
assert.deepEqual(profile.bindings, ["SESSIONS"]);
|
|
50
|
+
assert.equal(profile.ambiguousConfiguration, false);
|
|
51
|
+
});
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
test("supports an explicit TOML configuration in a monorepo", async () => {
|
|
55
|
+
await fixture(async (root) => {
|
|
56
|
+
await mkdir(join(root, "apps", "first"), { recursive: true });
|
|
57
|
+
await mkdir(join(root, "apps", "second"), { recursive: true });
|
|
58
|
+
await writeFile(join(root, "package.json"), JSON.stringify({ name: "monorepo" }));
|
|
59
|
+
await writeFile(join(root, "apps", "first", "wrangler.jsonc"), '{ "name": "first" }');
|
|
60
|
+
await writeFile(
|
|
61
|
+
join(root, "apps", "second", "wrangler.toml"),
|
|
62
|
+
`name = "second"
|
|
63
|
+
main = "src/index.ts"
|
|
64
|
+
compatibility_date = "2026-02-02"
|
|
65
|
+
[observability]
|
|
66
|
+
enabled = true
|
|
67
|
+
[observability.traces]
|
|
68
|
+
enabled = true
|
|
69
|
+
[[durable_objects.bindings]]
|
|
70
|
+
name = "AGENT"
|
|
71
|
+
class_name = "Agent"
|
|
72
|
+
`,
|
|
73
|
+
);
|
|
74
|
+
|
|
75
|
+
const ambiguous = await profileProject({ cwd: root });
|
|
76
|
+
assert.equal(ambiguous.ambiguousConfiguration, true);
|
|
77
|
+
assert.equal(ambiguous.worker, null);
|
|
78
|
+
|
|
79
|
+
const selected = await profileProject({
|
|
80
|
+
cwd: root,
|
|
81
|
+
config: "apps/second/wrangler.toml",
|
|
82
|
+
});
|
|
83
|
+
assert.equal(selected.worker, "second");
|
|
84
|
+
assert.equal(selected.main, "src/index.ts");
|
|
85
|
+
assert.equal(selected.observability.enabled, true);
|
|
86
|
+
assert.deepEqual(selected.bindings, ["AGENT"]);
|
|
87
|
+
});
|
|
88
|
+
});
|
|
@@ -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) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[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, /<script>alert\(1\)<\/script>/);
|
|
44
|
+
assert.match(html, /<b>unsafe<\/b>/);
|
|
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
|
+
});
|