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.
@@ -0,0 +1,225 @@
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
+ }
@@ -0,0 +1,143 @@
1
+ ---
2
+ name: cloudflare-agent-tracing
3
+ description: Investigate Pi Durable and other agent applications on Cloudflare using read-only Workers observability, deployments, Durable Object evidence, model telemetry, and bounded fulfillment evaluation. Use for traces, health, incidents, latency, model cost, errors, recovery, or whether an agent fulfilled a request.
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
+ metadata:
6
+ author: oskarcode
7
+ version: "0.2.0"
8
+ ---
9
+
10
+ # Cloudflare agent tracing
11
+
12
+ Investigate from evidence. Never mutate Cloudflare resources, deploy code, alter Durable Object state, or expose private conversation content.
13
+
14
+ Resolve relative paths in this skill against the directory containing this `SKILL.md`, not the current project.
15
+
16
+ ## Inputs
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. `--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
+
20
+ ## Start locally
21
+
22
+ 1. Run `node <skill-directory>/scripts/project-profile.mjs --cwd <project-directory>`.
23
+ 2. If the profiler reports multiple Wrangler configurations, select the relevant one from the user's target or ask one focused question. Re-run with `--config <path>` when needed.
24
+ 3. Read only the selected Wrangler configuration, relevant composition root, and installed Pi versions as needed.
25
+ 4. Check whether custom Pi telemetry is actually passed to `Harness.open()`. Wrangler tracing alone does not prove Pi spans are emitted.
26
+ 5. Use the Cloudflare MCP namespace. Read its namespace instructions before querying unfamiliar tools.
27
+ 6. Search the Cloudflare OpenAPI schema before an unfamiliar API call.
28
+ 7. Use only Cloudflare GET requests. The extension blocks `cloudflare_execute` unless all statically visible requests are explicit GETs.
29
+
30
+ ## Evidence order
31
+
32
+ Use the cheapest authoritative source first:
33
+
34
+ 1. Local source and selected Wrangler configuration.
35
+ 2. Worker identity, current deployment/version, bindings, routes, and observability settings.
36
+ 3. Workers logs and traces for the requested bounded time range.
37
+ 4. AI Gateway, provider, or Pi usage telemetry when available.
38
+ 5. Bounded authorized application diagnostics only when infrastructure evidence cannot answer the question.
39
+ 6. Documentation search for API semantics or known limitations.
40
+
41
+ Do not infer that a missing span means success or failure. Sampling, retention, deployment changes, missing instrumentation, authorization, and late ingestion can all create gaps.
42
+
43
+ ## Correlation
44
+
45
+ Prefer exact joins in this order: trace ID, Ray ID, deployment/version ID, request ID, Pi submission ID, task ID, conversation ID, then a narrow timestamp window. Label every temporal join as an inference.
46
+
47
+ For Dynamic Workers, inspect dispatcher and dispatched Worker separately and verify propagation. For Durable Objects, inspect RPC/invocation evidence and bounded application diagnostics. Never invent or expose arbitrary remote SQL or transcript endpoints.
48
+
49
+ ## Modes
50
+
51
+ ### Trace
52
+
53
+ Reconstruct only evidence-backed stages: edge request, Worker, Durable Object/RPC, Pi submission or task, model call, tools/subrequests, storage/commit, and streaming. Mark absent stages as unavailable.
54
+
55
+ ### Health
56
+
57
+ Measure outcomes, exceptions, cancellations, latency, CPU/wall time, deployment boundaries, authorization failures, task faults, retries, recovery, and alarm gaps. Distinguish successful Pi Durable recovery from terminal failure.
58
+
59
+ ### Cost
60
+
61
+ Use provider- or Pi-reported token and `cost.total` data when present. Label catalog estimates separately. Never present a precise total from sampled or incomplete telemetry.
62
+
63
+ ### Evaluate
64
+
65
+ Tracing cannot establish semantic fulfillment by itself. Normalize deterministic evidence and run:
66
+
67
+ ```bash
68
+ node <skill-directory>/scripts/evaluate.mjs /tmp/agent-evaluation.json
69
+ ```
70
+
71
+ Use `references/evaluation-input.example.json` as the content-free contract. Check:
72
+
73
+ - submission settled `done`, not `unanswered`;
74
+ - final committed answer exists;
75
+ - required tools succeeded;
76
+ - required durable side effects exist;
77
+ - explicit constraints were met;
78
+ - no terminal failure invalidated the outcome.
79
+
80
+ Only use semantic evidence when the user authorized content inspection and an existing authorized application path provides it. If semantic evidence is unavailable, return `indeterminate` when appropriate.
81
+
82
+ ### Incident
83
+
84
+ Combine bounded trace and health evidence into a timeline, impact statement, recovery assessment, and prioritized recommendations. Do not perform repairs.
85
+
86
+ ## Optional application evidence
87
+
88
+ This package deliberately has no project-specific transcript reader. If the target project already provides a narrow, authorized diagnostic export, keep its raw output in `/tmp`, summarize it immediately, and delete it after use.
89
+
90
+ For Pi Durable-shaped context exports, use:
91
+
92
+ ```bash
93
+ node <skill-directory>/scripts/summarize-session-context.mjs /tmp/session-context.json
94
+ ```
95
+
96
+ The summarizer removes transcript text, thinking, tool arguments, and tool results. Do not save raw private content in reports.
97
+
98
+ If no authorized diagnostic path exists, do not create one during an investigation. Report fulfillment as `indeterminate` when infrastructure evidence is insufficient.
99
+
100
+ ## Cloudflare query rules
101
+
102
+ - Bound every time range and page count.
103
+ - Query observability keys before selecting unfamiliar fields.
104
+ - Select only fields needed for the report.
105
+ - Avoid broad event output that may include request headers or private payloads.
106
+ - Stop on authorization errors and state the missing permission.
107
+ - Do not use POST, PUT, PATCH, or DELETE.
108
+ - Do not expose tokens, headers, emails, prompts, completions, tool arguments/results, or attachment contents.
109
+
110
+ ## Output contract
111
+
112
+ Return a concise report with:
113
+
114
+ 1. **Verdict and confidence**
115
+ 2. **Scope** — Worker, environment, deployment, exact UTC time range
116
+ 3. **Request path** — evidence-backed stages only
117
+ 4. **Failures and recovery**
118
+ 5. **Latency**
119
+ 6. **Cost**
120
+ 7. **Fulfillment** — `fulfilled`, `partial`, `not_fulfilled`, or `indeterminate`
121
+ 8. **Durable state evidence** — bounded and authorized
122
+ 9. **Recommendations** — prioritized; no automatic mutations
123
+ 10. **Evidence and limitations** — IDs, queries, sampling gaps, unavailable sources
124
+
125
+ Distinguish observations from hypotheses. Every conclusion must name its evidence. Local source inspection alone is not production verification.
126
+
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,24 @@
1
+ {
2
+ "target": {
3
+ "worker": "pi-durable-family-agent",
4
+ "submissionId": 123,
5
+ "conversationId": 456
6
+ },
7
+ "submissionStatus": "done",
8
+ "finalAnswerPresent": true,
9
+ "requiredTools": [
10
+ { "name": "example_read_tool", "required": true, "status": "succeeded" }
11
+ ],
12
+ "requiredEffects": [
13
+ { "name": "record committed", "required": true, "status": "verified" }
14
+ ],
15
+ "constraints": [
16
+ { "name": "read-only", "status": "met" }
17
+ ],
18
+ "terminalFailures": [],
19
+ "semanticJudge": {
20
+ "verdict": "indeterminate",
21
+ "score": null,
22
+ "rubricVersion": "v1"
23
+ }
24
+ }
@@ -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,79 @@
1
+ #!/usr/bin/env node
2
+ import { readFile } from "node:fs/promises";
3
+ import { pathToFileURL } from "node:url";
4
+
5
+ if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
6
+ const path = process.argv[2];
7
+ if (!path) {
8
+ console.error("Usage: node .pi/agent-tracing/scripts/evaluate.mjs <evidence.json>");
9
+ process.exitCode = 2;
10
+ } else {
11
+ const evidence = JSON.parse(await readFile(path, "utf8"));
12
+ console.log(JSON.stringify(evaluate(evidence), null, 2));
13
+ }
14
+ }
15
+
16
+ export function evaluate(evidence) {
17
+ const checks = [];
18
+ checks.push(check("submission settled", evidence.submissionStatus === "done", 30));
19
+ checks.push(check("final answer committed", evidence.finalAnswerPresent === true, 20));
20
+
21
+ for (const tool of evidence.requiredTools ?? []) {
22
+ if (tool.required !== true) continue;
23
+ checks.push(check(`tool:${safeName(tool.name)}`, tool.status === "succeeded", 10));
24
+ }
25
+ for (const effect of evidence.requiredEffects ?? []) {
26
+ if (effect.required !== true) continue;
27
+ checks.push(check(`effect:${safeName(effect.name)}`, effect.status === "verified", 15));
28
+ }
29
+ for (const constraint of evidence.constraints ?? []) {
30
+ checks.push(check(`constraint:${safeName(constraint.name)}`, constraint.status === "met", 10));
31
+ }
32
+
33
+ const failures = Array.isArray(evidence.terminalFailures) ? evidence.terminalFailures : [];
34
+ checks.push(check("no terminal failure", failures.length === 0, 25));
35
+
36
+ const possible = checks.reduce((sum, item) => sum + item.weight, 0);
37
+ const earned = checks.reduce((sum, item) => sum + (item.passed ? item.weight : 0), 0);
38
+ const deterministicScore = possible === 0 ? 0 : Math.round((earned / possible) * 100);
39
+ const semantic = evidence.semanticJudge;
40
+ const semanticAvailable =
41
+ semantic &&
42
+ ["fulfilled", "partial", "not_fulfilled"].includes(semantic.verdict) &&
43
+ typeof semantic.score === "number";
44
+ const score = semanticAvailable
45
+ ? Math.round(deterministicScore * 0.7 + clamp(semantic.score, 0, 100) * 0.3)
46
+ : deterministicScore;
47
+
48
+ let verdict;
49
+ if (!semanticAvailable && checks.every((item) => item.passed)) verdict = "indeterminate";
50
+ else if (score >= 85 && failures.length === 0) verdict = "fulfilled";
51
+ else if (score >= 45) verdict = "partial";
52
+ else verdict = "not_fulfilled";
53
+
54
+ return {
55
+ verdict,
56
+ score,
57
+ deterministicScore,
58
+ semanticEvidence: semanticAvailable ? "available" : "unavailable",
59
+ checks: checks.map(({ weight, ...item }) => item),
60
+ limitations: semanticAvailable
61
+ ? []
62
+ : [
63
+ "Semantic fulfillment was not established from authorized request and answer content.",
64
+ "A deterministic pass without semantic evidence remains indeterminate.",
65
+ ],
66
+ };
67
+ }
68
+
69
+ function check(name, passed, weight) {
70
+ return { name, passed, weight };
71
+ }
72
+
73
+ function safeName(value) {
74
+ return typeof value === "string" && value.trim() ? value.trim().slice(0, 100) : "unnamed";
75
+ }
76
+
77
+ function clamp(value, min, max) {
78
+ return Math.min(max, Math.max(min, value));
79
+ }
@@ -0,0 +1,38 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { evaluate } from "./evaluate.mjs";
4
+
5
+ test("keeps deterministic success indeterminate without semantic evidence", () => {
6
+ const result = evaluate({
7
+ submissionStatus: "done",
8
+ finalAnswerPresent: true,
9
+ requiredTools: [{ name: "search", required: true, status: "succeeded" }],
10
+ requiredEffects: [{ name: "saved", required: true, status: "verified" }],
11
+ constraints: [{ name: "read-only", status: "met" }],
12
+ terminalFailures: [],
13
+ });
14
+ assert.equal(result.deterministicScore, 100);
15
+ assert.equal(result.verdict, "indeterminate");
16
+ });
17
+
18
+ test("reports a failed required effect as partial", () => {
19
+ const result = evaluate({
20
+ submissionStatus: "done",
21
+ finalAnswerPresent: true,
22
+ requiredEffects: [{ name: "saved", required: true, status: "missing" }],
23
+ terminalFailures: [],
24
+ semanticJudge: { verdict: "partial", score: 50, rubricVersion: "v1" },
25
+ });
26
+ assert.equal(result.verdict, "partial");
27
+ assert.ok(result.score >= 45 && result.score < 85);
28
+ });
29
+
30
+ test("terminal failure prevents a fulfilled verdict", () => {
31
+ const result = evaluate({
32
+ submissionStatus: "unanswered",
33
+ finalAnswerPresent: false,
34
+ terminalFailures: ["restart_limit"],
35
+ semanticJudge: { verdict: "not_fulfilled", score: 0, rubricVersion: "v1" },
36
+ });
37
+ assert.equal(result.verdict, "not_fulfilled");
38
+ });