mirror of
https://github.com/morluto/rea.git
synced 2026-11-10 17:30:32 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
93a0643077 | ||
|
|
3df8f26073 |
No files matched your search
@@ -1,4 +1,8 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { z } from "zod";
|
||||
|
||||
import { ANALYSIS_VIEW_TOOL_CONTRACTS } from "../../contracts/analysisViewToolContracts.js";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
@@ -79,6 +83,57 @@ const view = async (
|
||||
return projected.value.normalized_result as Record<string, unknown>;
|
||||
};
|
||||
|
||||
it("summarizes every three-digit status bucket within the advertised output contract", async () => {
|
||||
const contract = ANALYSIS_VIEW_TOOL_CONTRACTS.find(
|
||||
({ name }) => name === "inspect_analysis_view",
|
||||
);
|
||||
if (contract === undefined)
|
||||
throw new Error("Missing inspect_analysis_view contract");
|
||||
const validateOutput = new Ajv2020({
|
||||
strict: false,
|
||||
validateFormats: false,
|
||||
inlineRefs: false,
|
||||
code: { optimize: false },
|
||||
}).compile(z.toJSONSchema(contract.outputSchema));
|
||||
for (const [status, statusClass] of [
|
||||
[100, "1xx"],
|
||||
[200, "2xx"],
|
||||
[300, "3xx"],
|
||||
[400, "4xx"],
|
||||
[599, "5xx"],
|
||||
[600, "6xx"],
|
||||
[700, "7xx"],
|
||||
[800, "8xx"],
|
||||
[999, "9xx"],
|
||||
] as const) {
|
||||
const capture = scenarioCaptureFixture([
|
||||
{ method: "GET", url: "/status", status },
|
||||
]);
|
||||
const original = JSON.stringify(capture);
|
||||
const result = await inspectAnalysisView({
|
||||
source: { kind: "inline", evidence: scenarioCaptureEvidence(capture) },
|
||||
view: { kind: "summary" },
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.normalized_result).toMatchObject({
|
||||
summary: {
|
||||
network: {
|
||||
by_status_class: [{ status_class: statusClass, transactions: 1 }],
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(contract.outputSchema.safeParse(result.value).success).toBe(true);
|
||||
expect(
|
||||
validateOutput(result.value),
|
||||
JSON.stringify(validateOutput.errors),
|
||||
).toBe(true);
|
||||
expect(JSON.stringify(capture)).toBe(original);
|
||||
expect(capture.events.items).toContainEqual(
|
||||
expect.objectContaining({ kind: "response", status }),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
describe("browser scenario analysis views", () => {
|
||||
it("counts inherited Evidence limitations alongside capture-local caveats", async () => {
|
||||
const capture = scenarioCaptureFixture();
|
||||
|
||||
@@ -5,8 +5,6 @@ import { expect, it, vi } from "vitest";
|
||||
import { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js";
|
||||
import { apiContractSchema } from "../../domain/apiContract/apiContract.js";
|
||||
import { AnalysisResourceConstraintError } from "../../domain/analysisErrorCore.js";
|
||||
import { parseEvidence } from "../../domain/evidence.js";
|
||||
import { projectAnalysisView } from "../../domain/analysisView/analysisView.js";
|
||||
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
|
||||
import { inspectApiContractEvidence } from "./ApiContractService.js";
|
||||
import * as readOwner from "./ApiContractRead.js";
|
||||
@@ -319,89 +317,3 @@ it("cancels a cooperative document traversal after the actual verified file read
|
||||
await resources.close();
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["between-paths", "after-projection"] as const)(
|
||||
"preserves authenticated OpenAPI facts on cancellation %s",
|
||||
async (stage) => {
|
||||
const bytes = JSON.stringify({
|
||||
openapi: "3.1.2",
|
||||
info: { title: "Cancellation", version: "1" },
|
||||
paths: { "/first": { get: {} }, "/second": { post: {} } },
|
||||
});
|
||||
const { path } = await inputFile(bytes);
|
||||
const resources = new ArtifactResourceScope();
|
||||
const controller = new AbortController();
|
||||
const realParse = parser.parseApiContractSteps;
|
||||
try {
|
||||
const baseline = await inspectApiContractEvidence({ path }, resources);
|
||||
if (!baseline.ok) throw baseline.error;
|
||||
const complete = apiContractSchema.parse(
|
||||
baseline.value.normalized_result,
|
||||
);
|
||||
const scheduled = vi
|
||||
.spyOn(parser, "parseApiContractSteps")
|
||||
.mockImplementationOnce(function* (...args) {
|
||||
const steps = realParse(...args);
|
||||
if (stage === "between-paths") {
|
||||
expect(steps.next().done).toBe(false);
|
||||
expect(steps.next().done).toBe(false);
|
||||
setImmediate(() => controller.abort(stage));
|
||||
return yield* steps;
|
||||
}
|
||||
const result = yield* steps;
|
||||
setImmediate(() => controller.abort(stage));
|
||||
return result;
|
||||
});
|
||||
try {
|
||||
const result = await inspectApiContractEvidence({ path }, resources, {
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (result.ok) throw new Error("Expected cancellation");
|
||||
expect(result.error._tag).toBe("AnalysisCancelledError");
|
||||
expect(result.error.cause).toBe(stage);
|
||||
const evidence = parseEvidence(result.error.partialObservation);
|
||||
const retained = apiContractSchema.parse(evidence.normalized_result);
|
||||
expect(evidence.subject).toEqual(baseline.value.subject);
|
||||
expect(evidence.parameters).toEqual(baseline.value.parameters);
|
||||
expect(retained.artifact).toEqual(complete.artifact);
|
||||
expect(retained.contract_id).toBe(complete.contract_id);
|
||||
if (stage === "between-paths") {
|
||||
expect(retained.operations).toEqual(complete.operations.slice(0, 1));
|
||||
expect(retained.source_coverage.status).toBe("partial");
|
||||
expect(evidence.evidence_id).not.toBe(baseline.value.evidence_id);
|
||||
const page = projectAnalysisView(
|
||||
{
|
||||
evidenceId: evidence.evidence_id,
|
||||
operation: evidence.operation,
|
||||
predicateType: evidence.predicate_type,
|
||||
normalizedResult: evidence.normalized_result,
|
||||
limitations: evidence.limitations,
|
||||
},
|
||||
{
|
||||
kind: "api-contract",
|
||||
collection: "operations",
|
||||
offset: 0,
|
||||
limit: 1,
|
||||
},
|
||||
);
|
||||
expect(page).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
parent_evidence_id: evidence.evidence_id,
|
||||
items: [{ path: "/first", state: "declared" }],
|
||||
coverage: { exhausted: true },
|
||||
source_coverage: { status: "partial" },
|
||||
},
|
||||
});
|
||||
} else {
|
||||
expect(retained).toEqual(complete);
|
||||
expect(evidence.evidence_id).toBe(baseline.value.evidence_id);
|
||||
}
|
||||
} finally {
|
||||
scheduled.mockRestore();
|
||||
}
|
||||
} finally {
|
||||
await resources.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -11,8 +11,6 @@ import { err, ok, type Result } from "../../domain/result.js";
|
||||
import {
|
||||
API_CONTRACT_OPERATION as operation,
|
||||
API_CONTRACT_PROVIDER,
|
||||
apiContractSchema,
|
||||
type ApiContract,
|
||||
type ApiContractArtifact,
|
||||
} from "../../domain/apiContract/apiContract.js";
|
||||
import {
|
||||
@@ -72,32 +70,8 @@ function* documentSteps(document: unknown, artifact: ApiContractArtifact) {
|
||||
return yield* parseApiContractSteps(document, artifact);
|
||||
}
|
||||
|
||||
type OpenApiInput = Extract<
|
||||
InspectApiContractInput,
|
||||
{ format: "openapi-json" }
|
||||
>;
|
||||
|
||||
const documentEvidence = (input: OpenApiInput, result: ApiContract): Evidence =>
|
||||
createEvidence(
|
||||
{ path: input.path, format: "file", sha256: result.artifact.sha256 },
|
||||
API_CONTRACT_PROVIDER,
|
||||
{
|
||||
operation,
|
||||
predicateType: "rea.api-contract-inventory",
|
||||
parameters: {
|
||||
path: input.path,
|
||||
format: input.format,
|
||||
max_file_bytes: input.max_file_bytes,
|
||||
},
|
||||
result,
|
||||
confidence: "observed",
|
||||
limitations: result.limitations,
|
||||
locations: [{ kind: "artifact-path", path: input.path }],
|
||||
},
|
||||
);
|
||||
|
||||
const importDocument = async (
|
||||
input: OpenApiInput,
|
||||
input: Extract<InspectApiContractInput, { format: "openapi-json" }>,
|
||||
bytes: Buffer,
|
||||
sha256: string,
|
||||
signal?: AbortSignal,
|
||||
@@ -112,16 +86,26 @@ const importDocument = async (
|
||||
}),
|
||||
signal,
|
||||
);
|
||||
if (!parsed.ok) {
|
||||
const partial = apiContractSchema.safeParse(
|
||||
parsed.error.partialObservation,
|
||||
);
|
||||
if (partial.success)
|
||||
parsed.error.partialObservation = documentEvidence(input, partial.data);
|
||||
return parsed;
|
||||
}
|
||||
if (!parsed.ok) return parsed;
|
||||
const result = parsed.value;
|
||||
return completeProviderEvidence(
|
||||
documentEvidence(input, parsed.value),
|
||||
createEvidence(
|
||||
{ path: input.path, format: "file", sha256 },
|
||||
API_CONTRACT_PROVIDER,
|
||||
{
|
||||
operation,
|
||||
predicateType: "rea.api-contract-inventory",
|
||||
parameters: {
|
||||
path: input.path,
|
||||
format: input.format,
|
||||
max_file_bytes: input.max_file_bytes,
|
||||
},
|
||||
result,
|
||||
confidence: "observed",
|
||||
limitations: result.limitations,
|
||||
locations: [{ kind: "artifact-path", path: input.path }],
|
||||
},
|
||||
),
|
||||
signal,
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import type { PartialTaskMeasurement } from "./desktop/taskDifficulty.js";
|
||||
import type { AppleIpsPartialObservation } from "./native/appleIps.js";
|
||||
import type { PlaywrightTrace } from "./playwrightTrace/playwrightTrace.js";
|
||||
import type { ApiContract } from "./apiContract/apiContract.js";
|
||||
import type { GraphqlContract } from "./apiContract/graphqlContract.js";
|
||||
import type { SavedAnalysisSnapshotPartialObservation } from "./savedAnalysisSnapshot.js";
|
||||
import type { AnalysisSettingLimit } from "./analysisSettings.js";
|
||||
@@ -499,7 +498,6 @@ export type AnalysisPartialObservation =
|
||||
}
|
||||
| { readonly kind: "unretained-evidence"; readonly evidence: Evidence }
|
||||
| { readonly kind: "retained-evidence"; readonly evidence_id: string }
|
||||
| ApiContract
|
||||
| GraphqlContract
|
||||
| PlaywrightTrace
|
||||
| SavedAnalysisSnapshotPartialObservation
|
||||
|
||||
@@ -185,7 +185,7 @@ export const projectApiContractView = (
|
||||
unknowns:
|
||||
context.source_coverage.status === "partial"
|
||||
? [
|
||||
"This inventory is partial. Inspect limitations for coverage and query path-item-references and diagnostics for any retained source pointers.",
|
||||
"Unresolved or malformed declarations limit this inventory; query path-item-references and diagnostics for exact source pointers.",
|
||||
]
|
||||
: [],
|
||||
};
|
||||
|
||||
@@ -4,15 +4,23 @@ import { isImmutableJsonSnapshot } from "../immutableJson.js";
|
||||
import { compareAsciiStrings } from "../canonicalOrdering.js";
|
||||
|
||||
const count = z.int().nonnegative();
|
||||
const statusClass = z.enum([
|
||||
"1xx",
|
||||
"2xx",
|
||||
"3xx",
|
||||
"4xx",
|
||||
"5xx",
|
||||
"failed",
|
||||
"unknown",
|
||||
]);
|
||||
const statusClass = z
|
||||
.enum([
|
||||
"1xx",
|
||||
"2xx",
|
||||
"3xx",
|
||||
"4xx",
|
||||
"5xx",
|
||||
"6xx",
|
||||
"7xx",
|
||||
"8xx",
|
||||
"9xx",
|
||||
"failed",
|
||||
"unknown",
|
||||
])
|
||||
.describe(
|
||||
"Numeric hundreds bucket of the recorded three-digit status. The 6xx through 9xx buckets retain nonstandard source values without assigning standard HTTP semantics.",
|
||||
);
|
||||
|
||||
/** Counts concern retained transaction identities, including those without a request event. */
|
||||
export const browserScenarioNetworkSummarySchema = z.strictObject({
|
||||
@@ -107,9 +115,7 @@ export const browserScenarioTransactionGroups = (
|
||||
: null,
|
||||
status_class:
|
||||
group.statuses.size === 1 && status !== undefined
|
||||
? (`${String(Math.floor(status / 100))}xx` as z.infer<
|
||||
typeof statusClass
|
||||
>)
|
||||
? statusClass.parse(`${String(Math.floor(status / 100))}xx`)
|
||||
: group.statuses.size === 0 && group.failed
|
||||
? "failed"
|
||||
: "unknown",
|
||||
|
||||
@@ -3,7 +3,6 @@ import { readFileSync } from "node:fs";
|
||||
import { expect, it } from "vitest";
|
||||
import { apiContractSchema, type ApiContractArtifact } from "./apiContract.js";
|
||||
import { parseApiContractSteps } from "./parseApiContract.js";
|
||||
import { AnalysisCancelledError } from "../analysisErrorCore.js";
|
||||
|
||||
const artifact: ApiContractArtifact = {
|
||||
path: "/contract.json",
|
||||
@@ -306,39 +305,9 @@ it("handles 3.2 QUERY and case-sensitive additional methods, diagnosing invalid
|
||||
|
||||
it("bounds expanded identities and source pointers before building a giant row", () => {
|
||||
const result = parse(
|
||||
document({
|
||||
"/retained": { get: {} },
|
||||
[`/${"a".repeat(1_100_000)}`]: { get: {} },
|
||||
}),
|
||||
document({ [`/${"a".repeat(1_100_000)}`]: { get: {} } }),
|
||||
);
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("Expected a retained-facts refusal");
|
||||
expect(result.error._tag).toBe("AnalysisResourceConstraintError");
|
||||
const partial = apiContractSchema.parse(result.error.partialObservation);
|
||||
expect(partial.operations.map((row) => row.path)).toEqual(["/retained"]);
|
||||
expect(partial.source_coverage.status).toBe("partial");
|
||||
});
|
||||
|
||||
it("retains an interpreted path when cancellation interrupts traversal", () => {
|
||||
const input = document({
|
||||
"/first": { get: { operationId: "first" } },
|
||||
"/second": { get: { operationId: "second" } },
|
||||
});
|
||||
const steps = parseApiContractSteps(input, artifact);
|
||||
for (let checkpoint = 0; checkpoint < 3; checkpoint++)
|
||||
expect(steps.next().done).toBe(false);
|
||||
const cancellation = new AnalysisCancelledError("inspect_api_contract");
|
||||
const stopped = steps.throw(cancellation);
|
||||
if (!stopped.done || stopped.value.ok)
|
||||
throw new Error("Expected cancellation");
|
||||
expect(stopped.value.error).toBe(cancellation);
|
||||
const partial = apiContractSchema.parse(cancellation.partialObservation);
|
||||
const complete = report(input);
|
||||
expect(partial.operations).toEqual(complete.operations.slice(0, 1));
|
||||
expect(partial.summary.operation_slots).toBe(1);
|
||||
expect(partial.source_coverage).toMatchObject({
|
||||
status: "partial",
|
||||
path_entries_examined: 1,
|
||||
});
|
||||
expect(complete.source_coverage.status).toBe("complete-within-scope");
|
||||
if (!result.ok)
|
||||
expect(result.error._tag).toBe("AnalysisResourceConstraintError");
|
||||
});
|
||||
@@ -1,5 +1,4 @@
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisInputError,
|
||||
AnalysisResourceConstraintError,
|
||||
AnalysisUnsupportedTargetError,
|
||||
@@ -317,17 +316,14 @@ function* pathItem(
|
||||
return ok(undefined);
|
||||
}
|
||||
|
||||
interface ContractReportContext {
|
||||
readonly openapi: string;
|
||||
readonly info: ApiContract["info"];
|
||||
readonly pathsState: ApiContract["source_coverage"]["paths_state"];
|
||||
examined: number;
|
||||
}
|
||||
|
||||
const contractReport = (
|
||||
const completedInventory = (
|
||||
inventory: ContractInventory,
|
||||
context: ContractReportContext,
|
||||
incomplete = false,
|
||||
context: {
|
||||
openapi: string;
|
||||
info: ApiContract["info"];
|
||||
pathsState: ApiContract["source_coverage"]["paths_state"];
|
||||
examined: number;
|
||||
},
|
||||
): ApiContract => {
|
||||
const artifact = inventory.artifact;
|
||||
let declared = 0;
|
||||
@@ -352,9 +348,7 @@ const contractReport = (
|
||||
source_coverage: {
|
||||
scope: "inline-path-operations",
|
||||
status:
|
||||
incomplete ||
|
||||
inventory.references.length > 0 ||
|
||||
inventory.diagnostics.length > 0
|
||||
inventory.references.length > 0 || inventory.diagnostics.length > 0
|
||||
? "partial"
|
||||
: "complete-within-scope",
|
||||
paths_state: context.pathsState,
|
||||
@@ -364,11 +358,6 @@ const contractReport = (
|
||||
duplicate_json_members: "last-value-wins",
|
||||
},
|
||||
limitations: [
|
||||
...(incomplete
|
||||
? [
|
||||
"Traversal stopped before the inventory was complete. Counts describe the retained rows.",
|
||||
]
|
||||
: []),
|
||||
"Operations are document declarations, not evidence of runtime implementation, reachability or authorization.",
|
||||
"Only inline operations under paths are inventoried; callbacks, webhooks, components, servers, parameters, schemas, request/response contracts and security are not analyzed.",
|
||||
"No reference is resolved, including local fragments. A Path Item reference makes its effective operations unknown; adjacent inline slots are preserved without merging referenced definitions.",
|
||||
@@ -379,32 +368,6 @@ const contractReport = (
|
||||
};
|
||||
};
|
||||
|
||||
function* collectPaths(
|
||||
sourcePaths: Record<string, unknown>,
|
||||
inventory: ContractInventory,
|
||||
context: ContractReportContext,
|
||||
modern: boolean,
|
||||
): Generator<void, Result<void, AnalysisError>> {
|
||||
for (const path in sourcePaths) {
|
||||
if (!Object.hasOwn(sourcePaths, path) || path.startsWith("x-")) continue;
|
||||
yield;
|
||||
context.examined++;
|
||||
// Reserve expanded pointer/path strings before escaping or building a row.
|
||||
const admitted = inventory.reserve(512 + path.length * 16);
|
||||
if (!admitted.ok) return admitted;
|
||||
const pointer = `/paths/${pointerPart(path)}`;
|
||||
const read = path.startsWith("/")
|
||||
? yield* pathItem(sourcePaths[path], { inventory, path, pointer, modern })
|
||||
: inventory.diagnostic(
|
||||
"invalid-path-key",
|
||||
pointer,
|
||||
"A Paths entry must start with /; it was not interpreted as an endpoint.",
|
||||
);
|
||||
if (!read.ok) return read;
|
||||
}
|
||||
return ok(undefined);
|
||||
}
|
||||
|
||||
/** Enumerate declarations only; never resolve references, servers, callbacks or runtime expressions. */
|
||||
export function* parseApiContractSteps(
|
||||
value: unknown,
|
||||
@@ -454,32 +417,36 @@ export function* parseApiContractSteps(
|
||||
);
|
||||
if (!diagnosed.ok) return diagnosed;
|
||||
}
|
||||
const context: ContractReportContext = {
|
||||
openapi: root.openapi,
|
||||
info: info.value,
|
||||
pathsState,
|
||||
examined: 0,
|
||||
};
|
||||
const interrupted = (error: AnalysisError) => {
|
||||
const retainedRows =
|
||||
inventory.operations.length +
|
||||
inventory.references.length +
|
||||
inventory.diagnostics.length;
|
||||
if (retainedRows > 0)
|
||||
error.retainPartialObservation(contractReport(inventory, context, true));
|
||||
return err(error);
|
||||
};
|
||||
try {
|
||||
const read = yield* collectPaths(
|
||||
paths ?? {},
|
||||
inventory,
|
||||
context,
|
||||
version[1] === "2",
|
||||
);
|
||||
if (!read.ok) return interrupted(read.error);
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof AnalysisCancelledError) return interrupted(cause);
|
||||
throw cause;
|
||||
let examined = 0;
|
||||
const sourcePaths = paths ?? {};
|
||||
for (const path in sourcePaths) {
|
||||
if (!Object.hasOwn(sourcePaths, path) || path.startsWith("x-")) continue;
|
||||
yield;
|
||||
examined++;
|
||||
// Reserve expanded pointer/path strings before escaping or building a row.
|
||||
const admitted = inventory.reserve(512 + path.length * 16);
|
||||
if (!admitted.ok) return admitted;
|
||||
const pointer = `/paths/${pointerPart(path)}`;
|
||||
const read = path.startsWith("/")
|
||||
? yield* pathItem(sourcePaths[path], {
|
||||
inventory,
|
||||
path,
|
||||
pointer,
|
||||
modern: version[1] === "2",
|
||||
})
|
||||
: inventory.diagnostic(
|
||||
"invalid-path-key",
|
||||
pointer,
|
||||
"A Paths entry must start with /; it was not interpreted as an endpoint.",
|
||||
);
|
||||
if (!read.ok) return read;
|
||||
}
|
||||
return ok(contractReport(inventory, context));
|
||||
return ok(
|
||||
completedInventory(inventory, {
|
||||
openapi: root.openapi,
|
||||
info: info.value,
|
||||
pathsState,
|
||||
examined,
|
||||
}),
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user